OSDN Git Service

avformat/matroskadec: Fix number suffixes
[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_freep(&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     int nb_elem;
1429
1430     // we should not do any seeking in the streaming case
1431     if (!matroska->ctx->pb->seekable ||
1432         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1433         return;
1434
1435     // do not read entries that are added while parsing seekhead entries
1436     nb_elem = seekhead_list->nb_elem;
1437
1438     for (i = 0; i < nb_elem; i++) {
1439         MatroskaSeekhead *seekhead = seekhead_list->elem;
1440         if (seekhead[i].pos <= before_pos)
1441             continue;
1442
1443         // defer cues parsing until we actually need cue data.
1444         if (seekhead[i].id == MATROSKA_ID_CUES) {
1445             matroska->cues_parsing_deferred = 1;
1446             continue;
1447         }
1448
1449         if (matroska_parse_seekhead_entry(matroska, i) < 0) {
1450             // mark index as broken
1451             matroska->cues_parsing_deferred = -1;
1452             break;
1453         }
1454     }
1455 }
1456
1457 static void matroska_add_index_entries(MatroskaDemuxContext *matroska) {
1458     EbmlList *index_list;
1459     MatroskaIndex *index;
1460     int index_scale = 1;
1461     int i, j;
1462
1463     index_list = &matroska->index;
1464     index = index_list->elem;
1465     if (index_list->nb_elem
1466         && index[0].time > 1E14/matroska->time_scale) {
1467         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1468         index_scale = matroska->time_scale;
1469     }
1470     for (i = 0; i < index_list->nb_elem; i++) {
1471         EbmlList *pos_list = &index[i].pos;
1472         MatroskaIndexPos *pos = pos_list->elem;
1473         for (j = 0; j < pos_list->nb_elem; j++) {
1474             MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1475             if (track && track->stream)
1476                 av_add_index_entry(track->stream,
1477                                    pos[j].pos + matroska->segment_start,
1478                                    index[i].time/index_scale, 0, 0,
1479                                    AVINDEX_KEYFRAME);
1480         }
1481     }
1482 }
1483
1484 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1485     EbmlList *seekhead_list = &matroska->seekhead;
1486     MatroskaSeekhead *seekhead = seekhead_list->elem;
1487     int i;
1488
1489     for (i = 0; i < seekhead_list->nb_elem; i++)
1490         if (seekhead[i].id == MATROSKA_ID_CUES)
1491             break;
1492     av_assert1(i <= seekhead_list->nb_elem);
1493
1494     if (matroska_parse_seekhead_entry(matroska, i) < 0)
1495        matroska->cues_parsing_deferred = -1;
1496     matroska_add_index_entries(matroska);
1497 }
1498
1499 static int matroska_aac_profile(char *codec_id)
1500 {
1501     static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1502     int profile;
1503
1504     for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1505         if (strstr(codec_id, aac_profiles[profile]))
1506             break;
1507     return profile + 1;
1508 }
1509
1510 static int matroska_aac_sri(int samplerate)
1511 {
1512     int sri;
1513
1514     for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1515         if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1516             break;
1517     return sri;
1518 }
1519
1520 static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
1521 {
1522     char buffer[32];
1523     /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
1524     time_t creation_time = date_utc / 1000000000 + 978307200;
1525     struct tm *ptm = gmtime(&creation_time);
1526     if (!ptm) return;
1527     strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
1528     av_dict_set(metadata, "creation_time", buffer, 0);
1529 }
1530
1531 static int matroska_read_header(AVFormatContext *s)
1532 {
1533     MatroskaDemuxContext *matroska = s->priv_data;
1534     EbmlList *attachements_list = &matroska->attachments;
1535     MatroskaAttachement *attachements;
1536     EbmlList *chapters_list = &matroska->chapters;
1537     MatroskaChapter *chapters;
1538     MatroskaTrack *tracks;
1539     uint64_t max_start = 0;
1540     int64_t pos;
1541     Ebml ebml = { 0 };
1542     AVStream *st;
1543     int i, j, k, res;
1544
1545     matroska->ctx = s;
1546
1547     /* First read the EBML header. */
1548     if (ebml_parse(matroska, ebml_syntax, &ebml)
1549         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1550         || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3 || !ebml.doctype) {
1551         av_log(matroska->ctx, AV_LOG_ERROR,
1552                "EBML header using unsupported features\n"
1553                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1554                ebml.version, ebml.doctype, ebml.doctype_version);
1555         ebml_free(ebml_syntax, &ebml);
1556         return AVERROR_PATCHWELCOME;
1557     } else if (ebml.doctype_version == 3) {
1558         av_log(matroska->ctx, AV_LOG_WARNING,
1559                "EBML header using unsupported features\n"
1560                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1561                ebml.version, ebml.doctype, ebml.doctype_version);
1562     }
1563     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1564         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1565             break;
1566     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1567         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1568         if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1569             ebml_free(ebml_syntax, &ebml);
1570             return AVERROR_INVALIDDATA;
1571         }
1572     }
1573     ebml_free(ebml_syntax, &ebml);
1574
1575     /* The next thing is a segment. */
1576     pos = avio_tell(matroska->ctx->pb);
1577     res = ebml_parse(matroska, matroska_segments, matroska);
1578     // try resyncing until we find a EBML_STOP type element.
1579     while (res != 1) {
1580         res = matroska_resync(matroska, pos);
1581         if (res < 0)
1582             return res;
1583         pos = avio_tell(matroska->ctx->pb);
1584         res = ebml_parse(matroska, matroska_segment, matroska);
1585     }
1586     matroska_execute_seekhead(matroska);
1587
1588     if (!matroska->time_scale)
1589         matroska->time_scale = 1000000;
1590     if (matroska->duration)
1591         matroska->ctx->duration = matroska->duration * matroska->time_scale
1592                                   * 1000 / AV_TIME_BASE;
1593     av_dict_set(&s->metadata, "title", matroska->title, 0);
1594
1595     if (matroska->date_utc.size == 8)
1596         matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
1597
1598     tracks = matroska->tracks.elem;
1599     for (i=0; i < matroska->tracks.nb_elem; i++) {
1600         MatroskaTrack *track = &tracks[i];
1601         enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1602         EbmlList *encodings_list = &track->encodings;
1603         MatroskaTrackEncoding *encodings = encodings_list->elem;
1604         uint8_t *extradata = NULL;
1605         int extradata_size = 0;
1606         int extradata_offset = 0;
1607         uint32_t fourcc = 0;
1608         AVIOContext b;
1609         char* key_id_base64 = NULL;
1610
1611         /* Apply some sanity checks. */
1612         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1613             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1614             track->type != MATROSKA_TRACK_TYPE_SUBTITLE &&
1615             track->type != MATROSKA_TRACK_TYPE_METADATA) {
1616             av_log(matroska->ctx, AV_LOG_INFO,
1617                    "Unknown or unsupported track type %"PRIu64"\n",
1618                    track->type);
1619             continue;
1620         }
1621         if (track->codec_id == NULL)
1622             continue;
1623
1624         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1625             if (!track->default_duration && track->video.frame_rate > 0)
1626                 track->default_duration = 1000000000/track->video.frame_rate;
1627             if (track->video.display_width == -1)
1628                 track->video.display_width = track->video.pixel_width;
1629             if (track->video.display_height == -1)
1630                 track->video.display_height = track->video.pixel_height;
1631             if (track->video.color_space.size == 4)
1632                 fourcc = AV_RL32(track->video.color_space.data);
1633         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1634             if (!track->audio.out_samplerate)
1635                 track->audio.out_samplerate = track->audio.samplerate;
1636         }
1637         if (encodings_list->nb_elem > 1) {
1638             av_log(matroska->ctx, AV_LOG_ERROR,
1639                    "Multiple combined encodings not supported");
1640         } else if (encodings_list->nb_elem == 1) {
1641             if (encodings[0].type) {
1642                 if (encodings[0].encryption.key_id.size > 0) {
1643                     /* Save the encryption key id to be stored later as a
1644                        metadata tag. */
1645                     const int b64_size = AV_BASE64_SIZE(encodings[0].encryption.key_id.size);
1646                     key_id_base64 = av_malloc(b64_size);
1647                     if (key_id_base64 == NULL)
1648                         return AVERROR(ENOMEM);
1649
1650                     av_base64_encode(key_id_base64, b64_size,
1651                                      encodings[0].encryption.key_id.data,
1652                                      encodings[0].encryption.key_id.size);
1653                 } else {
1654                     encodings[0].scope = 0;
1655                     av_log(matroska->ctx, AV_LOG_ERROR,
1656                            "Unsupported encoding type");
1657                 }
1658             } else if (
1659 #if CONFIG_ZLIB
1660                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1661 #endif
1662 #if CONFIG_BZLIB
1663                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1664 #endif
1665 #if CONFIG_LZO
1666                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
1667 #endif
1668                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP) {
1669                 encodings[0].scope = 0;
1670                 av_log(matroska->ctx, AV_LOG_ERROR,
1671                        "Unsupported encoding type");
1672             } else if (track->codec_priv.size && encodings[0].scope&2) {
1673                 uint8_t *codec_priv = track->codec_priv.data;
1674                 int ret = matroska_decode_buffer(&track->codec_priv.data,
1675                                                  &track->codec_priv.size,
1676                                                  track);
1677                 if (ret < 0) {
1678                     track->codec_priv.data = NULL;
1679                     track->codec_priv.size = 0;
1680                     av_log(matroska->ctx, AV_LOG_ERROR,
1681                            "Failed to decode codec private data\n");
1682                 }
1683
1684                 if (codec_priv != track->codec_priv.data)
1685                     av_free(codec_priv);
1686             }
1687         }
1688
1689         for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1690             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1691                         strlen(ff_mkv_codec_tags[j].str))){
1692                 codec_id= ff_mkv_codec_tags[j].id;
1693                 break;
1694             }
1695         }
1696
1697         st = track->stream = avformat_new_stream(s, NULL);
1698         if (st == NULL) {
1699             av_free(key_id_base64);
1700             return AVERROR(ENOMEM);
1701         }
1702
1703         if (key_id_base64) {
1704             /* export encryption key id as base64 metadata tag */
1705             av_dict_set(&st->metadata, "enc_key_id", key_id_base64, 0);
1706             av_freep(&key_id_base64);
1707         }
1708
1709         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1710             && track->codec_priv.size >= 40
1711             && track->codec_priv.data != NULL) {
1712             track->ms_compat = 1;
1713             fourcc = AV_RL32(track->codec_priv.data + 16);
1714             codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
1715             extradata_offset = 40;
1716         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1717                    && track->codec_priv.size >= 14
1718                    && track->codec_priv.data != NULL) {
1719             int ret;
1720             ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1721                               0, NULL, NULL, NULL, NULL);
1722             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1723             if (ret < 0)
1724                 return ret;
1725             codec_id = st->codec->codec_id;
1726             extradata_offset = FFMIN(track->codec_priv.size, 18);
1727         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1728                    && (track->codec_priv.size >= 86)
1729                    && (track->codec_priv.data != NULL)) {
1730             fourcc = AV_RL32(track->codec_priv.data + 4);
1731             codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
1732             if (ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(track->codec_priv.data))) {
1733                 fourcc = AV_RL32(track->codec_priv.data);
1734                 codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
1735             }
1736         } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1737             switch (track->audio.bitdepth) {
1738             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1739             case 24:  codec_id = AV_CODEC_ID_PCM_S24BE;  break;
1740             case 32:  codec_id = AV_CODEC_ID_PCM_S32BE;  break;
1741             }
1742         } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1743             switch (track->audio.bitdepth) {
1744             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1745             case 24:  codec_id = AV_CODEC_ID_PCM_S24LE;  break;
1746             case 32:  codec_id = AV_CODEC_ID_PCM_S32LE;  break;
1747             }
1748         } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1749             codec_id = AV_CODEC_ID_PCM_F64LE;
1750         } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1751             int profile = matroska_aac_profile(track->codec_id);
1752             int sri = matroska_aac_sri(track->audio.samplerate);
1753             extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1754             if (extradata == NULL)
1755                 return AVERROR(ENOMEM);
1756             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1757             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1758             if (strstr(track->codec_id, "SBR")) {
1759                 sri = matroska_aac_sri(track->audio.out_samplerate);
1760                 extradata[2] = 0x56;
1761                 extradata[3] = 0xE5;
1762                 extradata[4] = 0x80 | (sri<<3);
1763                 extradata_size = 5;
1764             } else
1765                 extradata_size = 2;
1766         } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX - 12 - FF_INPUT_BUFFER_PADDING_SIZE) {
1767             /* Only ALAC's magic cookie is stored in Matroska's track headers.
1768                Create the "atom size", "tag", and "tag version" fields the
1769                decoder expects manually. */
1770             extradata_size = 12 + track->codec_priv.size;
1771             extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1772             if (extradata == NULL)
1773                 return AVERROR(ENOMEM);
1774             AV_WB32(extradata, extradata_size);
1775             memcpy(&extradata[4], "alac", 4);
1776             AV_WB32(&extradata[8], 0);
1777             memcpy(&extradata[12], track->codec_priv.data,
1778                                    track->codec_priv.size);
1779         } else if (codec_id == AV_CODEC_ID_TTA) {
1780             extradata_size = 30;
1781             extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1782             if (extradata == NULL)
1783                 return AVERROR(ENOMEM);
1784             ffio_init_context(&b, extradata, extradata_size, 1,
1785                           NULL, NULL, NULL, NULL);
1786             avio_write(&b, "TTA1", 4);
1787             avio_wl16(&b, 1);
1788             avio_wl16(&b, track->audio.channels);
1789             avio_wl16(&b, track->audio.bitdepth);
1790             if (track->audio.out_samplerate < 0 || track->audio.out_samplerate > INT_MAX)
1791                 return AVERROR_INVALIDDATA;
1792             avio_wl32(&b, track->audio.out_samplerate);
1793             avio_wl32(&b, av_rescale((matroska->duration * matroska->time_scale), track->audio.out_samplerate, AV_TIME_BASE * 1000));
1794         } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1795                    codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1796             extradata_offset = 26;
1797         } else if (codec_id == AV_CODEC_ID_RA_144) {
1798             track->audio.out_samplerate = 8000;
1799             track->audio.channels = 1;
1800         } else if ((codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1801                     codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR)
1802                     && track->codec_priv.data) {
1803             int flavor;
1804
1805             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1806                           0, NULL, NULL, NULL, NULL);
1807             avio_skip(&b, 22);
1808             flavor                       = avio_rb16(&b);
1809             track->audio.coded_framesize = avio_rb32(&b);
1810             avio_skip(&b, 12);
1811             track->audio.sub_packet_h    = avio_rb16(&b);
1812             track->audio.frame_size      = avio_rb16(&b);
1813             track->audio.sub_packet_size = avio_rb16(&b);
1814             if (flavor < 0 || track->audio.coded_framesize <= 0 ||
1815                 track->audio.sub_packet_h <= 0 || track->audio.frame_size <= 0 ||
1816                 track->audio.sub_packet_size <= 0)
1817                 return AVERROR_INVALIDDATA;
1818             track->audio.buf = av_malloc_array(track->audio.sub_packet_h, track->audio.frame_size);
1819             if (!track->audio.buf)
1820                 return AVERROR(ENOMEM);
1821             if (codec_id == AV_CODEC_ID_RA_288) {
1822                 st->codec->block_align = track->audio.coded_framesize;
1823                 track->codec_priv.size = 0;
1824             } else {
1825                 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1826                     static const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1827                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1828                     st->codec->bit_rate = sipr_bit_rate[flavor];
1829                 }
1830                 st->codec->block_align = track->audio.sub_packet_size;
1831                 extradata_offset = 78;
1832             }
1833         }
1834         track->codec_priv.size -= extradata_offset;
1835
1836         if (codec_id == AV_CODEC_ID_NONE)
1837             av_log(matroska->ctx, AV_LOG_INFO,
1838                    "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1839
1840         if (track->time_scale < 0.01)
1841             track->time_scale = 1.0;
1842         avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1843
1844         st->codec->codec_id = codec_id;
1845
1846         if (strcmp(track->language, "und"))
1847             av_dict_set(&st->metadata, "language", track->language, 0);
1848         av_dict_set(&st->metadata, "title", track->name, 0);
1849
1850         if (track->flag_default)
1851             st->disposition |= AV_DISPOSITION_DEFAULT;
1852         if (track->flag_forced)
1853             st->disposition |= AV_DISPOSITION_FORCED;
1854
1855         if (!st->codec->extradata) {
1856             if(extradata){
1857                 st->codec->extradata = extradata;
1858                 st->codec->extradata_size = extradata_size;
1859             } else if(track->codec_priv.data && track->codec_priv.size > 0){
1860                 if (ff_alloc_extradata(st->codec, track->codec_priv.size))
1861                     return AVERROR(ENOMEM);
1862                 memcpy(st->codec->extradata,
1863                        track->codec_priv.data + extradata_offset,
1864                        track->codec_priv.size);
1865             }
1866         }
1867
1868         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1869             MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
1870
1871             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1872             st->codec->codec_tag  = fourcc;
1873             st->codec->width  = track->video.pixel_width;
1874             st->codec->height = track->video.pixel_height;
1875             av_reduce(&st->sample_aspect_ratio.num,
1876                       &st->sample_aspect_ratio.den,
1877                       st->codec->height * track->video.display_width,
1878                       st->codec-> width * track->video.display_height,
1879                       255);
1880             if (st->codec->codec_id != AV_CODEC_ID_HEVC)
1881                 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1882             if (track->default_duration) {
1883                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1884                           1000000000, track->default_duration, 30000);
1885 #if FF_API_R_FRAME_RATE
1886                 if (st->avg_frame_rate.num < st->avg_frame_rate.den * 1000LL)
1887                     st->r_frame_rate = st->avg_frame_rate;
1888 #endif
1889             }
1890
1891             /* export stereo mode flag as metadata tag */
1892             if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
1893                 av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
1894
1895             /* export alpha mode flag as metadata tag  */
1896             if (track->video.alpha_mode)
1897                 av_dict_set(&st->metadata, "alpha_mode", "1", 0);
1898
1899             /* if we have virtual track, mark the real tracks */
1900             for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
1901                 char buf[32];
1902                 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
1903                     continue;
1904                 snprintf(buf, sizeof(buf), "%s_%d",
1905                          ff_matroska_video_stereo_plane[planes[j].type], i);
1906                 for (k=0; k < matroska->tracks.nb_elem; k++)
1907                     if (planes[j].uid == tracks[k].uid) {
1908                         av_dict_set(&s->streams[k]->metadata,
1909                                     "stereo_mode", buf, 0);
1910                         break;
1911                     }
1912             }
1913         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1914             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1915             st->codec->sample_rate = track->audio.out_samplerate;
1916             st->codec->channels = track->audio.channels;
1917             if (!st->codec->bits_per_coded_sample)
1918             st->codec->bits_per_coded_sample = track->audio.bitdepth;
1919             if (st->codec->codec_id != AV_CODEC_ID_AAC)
1920             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1921             if (track->codec_delay > 0) {
1922                 st->codec->delay = av_rescale_q(track->codec_delay,
1923                                                 (AVRational){1, 1000000000},
1924                                                 (AVRational){1, st->codec->sample_rate});
1925             }
1926             if (track->seek_preroll > 0) {
1927                 av_codec_set_seek_preroll(st->codec,
1928                                           av_rescale_q(track->seek_preroll,
1929                                                        (AVRational){1, 1000000000},
1930                                                        (AVRational){1, st->codec->sample_rate}));
1931             }
1932         } else if (codec_id == AV_CODEC_ID_WEBVTT) {
1933             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1934
1935             if (!strcmp(track->codec_id, "D_WEBVTT/CAPTIONS")) {
1936                 st->disposition |= AV_DISPOSITION_CAPTIONS;
1937             } else if (!strcmp(track->codec_id, "D_WEBVTT/DESCRIPTIONS")) {
1938                 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
1939             } else if (!strcmp(track->codec_id, "D_WEBVTT/METADATA")) {
1940                 st->disposition |= AV_DISPOSITION_METADATA;
1941             }
1942         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1943             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1944 #if FF_API_ASS_SSA
1945             if (st->codec->codec_id == AV_CODEC_ID_SSA ||
1946                 st->codec->codec_id == AV_CODEC_ID_ASS)
1947 #else
1948             if (st->codec->codec_id == AV_CODEC_ID_ASS)
1949 #endif
1950                 matroska->contains_ssa = 1;
1951         }
1952     }
1953
1954     attachements = attachements_list->elem;
1955     for (j=0; j<attachements_list->nb_elem; j++) {
1956         if (!(attachements[j].filename && attachements[j].mime &&
1957               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1958             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1959         } else {
1960             AVStream *st = avformat_new_stream(s, NULL);
1961             if (st == NULL)
1962                 break;
1963             av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1964             av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1965             st->codec->codec_id = AV_CODEC_ID_NONE;
1966             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1967             if (ff_alloc_extradata(st->codec, attachements[j].bin.size))
1968                 break;
1969             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1970
1971             for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1972                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1973                              strlen(ff_mkv_mime_tags[i].str))) {
1974                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1975                     break;
1976                 }
1977             }
1978             attachements[j].stream = st;
1979         }
1980     }
1981
1982     chapters = chapters_list->elem;
1983     for (i=0; i<chapters_list->nb_elem; i++)
1984         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1985             && (max_start==0 || chapters[i].start > max_start)) {
1986             chapters[i].chapter =
1987             avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1988                            chapters[i].start, chapters[i].end,
1989                            chapters[i].title);
1990             av_dict_set(&chapters[i].chapter->metadata,
1991                              "title", chapters[i].title, 0);
1992             max_start = chapters[i].start;
1993         }
1994
1995     matroska_add_index_entries(matroska);
1996
1997     matroska_convert_tags(s);
1998
1999     return 0;
2000 }
2001
2002 /*
2003  * Put one packet in an application-supplied AVPacket struct.
2004  * Returns 0 on success or -1 on failure.
2005  */
2006 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
2007                                    AVPacket *pkt)
2008 {
2009     if (matroska->num_packets > 0) {
2010         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
2011         av_freep(&matroska->packets[0]);
2012         if (matroska->num_packets > 1) {
2013             void *newpackets;
2014             memmove(&matroska->packets[0], &matroska->packets[1],
2015                     (matroska->num_packets - 1) * sizeof(AVPacket *));
2016             newpackets = av_realloc(matroska->packets,
2017                             (matroska->num_packets - 1) * sizeof(AVPacket *));
2018             if (newpackets)
2019                 matroska->packets = newpackets;
2020         } else {
2021             av_freep(&matroska->packets);
2022             matroska->prev_pkt = NULL;
2023         }
2024         matroska->num_packets--;
2025         return 0;
2026     }
2027
2028     return -1;
2029 }
2030
2031 /*
2032  * Free all packets in our internal queue.
2033  */
2034 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
2035 {
2036     matroska->prev_pkt = NULL;
2037     if (matroska->packets) {
2038         int n;
2039         for (n = 0; n < matroska->num_packets; n++) {
2040             av_free_packet(matroska->packets[n]);
2041             av_freep(&matroska->packets[n]);
2042         }
2043         av_freep(&matroska->packets);
2044         matroska->num_packets = 0;
2045     }
2046 }
2047
2048 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
2049                                 int* buf_size, int type,
2050                                 uint32_t **lace_buf, int *laces)
2051 {
2052     int res = 0, n, size = *buf_size;
2053     uint8_t *data = *buf;
2054     uint32_t *lace_size;
2055
2056     if (!type) {
2057         *laces = 1;
2058         *lace_buf = av_mallocz(sizeof(int));
2059         if (!*lace_buf)
2060             return AVERROR(ENOMEM);
2061
2062         *lace_buf[0] = size;
2063         return 0;
2064     }
2065
2066     av_assert0(size > 0);
2067     *laces = *data + 1;
2068     data += 1;
2069     size -= 1;
2070     lace_size = av_mallocz(*laces * sizeof(int));
2071     if (!lace_size)
2072         return AVERROR(ENOMEM);
2073
2074     switch (type) {
2075     case 0x1: /* Xiph lacing */ {
2076         uint8_t temp;
2077         uint32_t total = 0;
2078         for (n = 0; res == 0 && n < *laces - 1; n++) {
2079             while (1) {
2080                 if (size <= total) {
2081                     res = AVERROR_INVALIDDATA;
2082                     break;
2083                 }
2084                 temp = *data;
2085                 total += temp;
2086                 lace_size[n] += temp;
2087                 data += 1;
2088                 size -= 1;
2089                 if (temp != 0xff)
2090                     break;
2091             }
2092         }
2093         if (size <= total) {
2094             res = AVERROR_INVALIDDATA;
2095             break;
2096         }
2097
2098         lace_size[n] = size - total;
2099         break;
2100     }
2101
2102     case 0x2: /* fixed-size lacing */
2103         if (size % (*laces)) {
2104             res = AVERROR_INVALIDDATA;
2105             break;
2106         }
2107         for (n = 0; n < *laces; n++)
2108             lace_size[n] = size / *laces;
2109         break;
2110
2111     case 0x3: /* EBML lacing */ {
2112         uint64_t num;
2113         uint64_t total;
2114         n = matroska_ebmlnum_uint(matroska, data, size, &num);
2115         if (n < 0 || num > INT_MAX) {
2116             av_log(matroska->ctx, AV_LOG_INFO,
2117                    "EBML block data error\n");
2118             res = n<0 ? n : AVERROR_INVALIDDATA;
2119             break;
2120         }
2121         data += n;
2122         size -= n;
2123         total = lace_size[0] = num;
2124         for (n = 1; res == 0 && n < *laces - 1; n++) {
2125             int64_t snum;
2126             int r;
2127             r = matroska_ebmlnum_sint(matroska, data, size, &snum);
2128             if (r < 0 || lace_size[n - 1] + snum > (uint64_t)INT_MAX) {
2129                 av_log(matroska->ctx, AV_LOG_INFO,
2130                        "EBML block data error\n");
2131                 res = r<0 ? r : AVERROR_INVALIDDATA;
2132                 break;
2133             }
2134             data += r;
2135             size -= r;
2136             lace_size[n] = lace_size[n - 1] + snum;
2137             total += lace_size[n];
2138         }
2139         if (size <= total) {
2140             res = AVERROR_INVALIDDATA;
2141             break;
2142         }
2143         lace_size[*laces - 1] = size - total;
2144         break;
2145     }
2146     }
2147
2148     *buf      = data;
2149     *lace_buf = lace_size;
2150     *buf_size = size;
2151
2152     return res;
2153 }
2154
2155 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
2156                                    MatroskaTrack *track,
2157                                    AVStream *st,
2158                                    uint8_t *data, int size,
2159                                    uint64_t timecode,
2160                                    int64_t pos)
2161 {
2162     int a = st->codec->block_align;
2163     int sps = track->audio.sub_packet_size;
2164     int cfs = track->audio.coded_framesize;
2165     int h = track->audio.sub_packet_h;
2166     int y = track->audio.sub_packet_cnt;
2167     int w = track->audio.frame_size;
2168     int x;
2169
2170     if (!track->audio.pkt_cnt) {
2171         if (track->audio.sub_packet_cnt == 0)
2172             track->audio.buf_timecode = timecode;
2173         if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
2174             if (size < cfs * h / 2) {
2175                 av_log(matroska->ctx, AV_LOG_ERROR,
2176                        "Corrupt int4 RM-style audio packet size\n");
2177                 return AVERROR_INVALIDDATA;
2178             }
2179             for (x=0; x<h/2; x++)
2180                 memcpy(track->audio.buf+x*2*w+y*cfs,
2181                        data+x*cfs, cfs);
2182         } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
2183             if (size < w) {
2184                 av_log(matroska->ctx, AV_LOG_ERROR,
2185                        "Corrupt sipr RM-style audio packet size\n");
2186                 return AVERROR_INVALIDDATA;
2187             }
2188             memcpy(track->audio.buf + y*w, data, w);
2189         } else {
2190             if (size < sps * w / sps || h<=0 || w%sps) {
2191                 av_log(matroska->ctx, AV_LOG_ERROR,
2192                        "Corrupt generic RM-style audio packet size\n");
2193                 return AVERROR_INVALIDDATA;
2194             }
2195             for (x=0; x<w/sps; x++)
2196                 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2197         }
2198
2199         if (++track->audio.sub_packet_cnt >= h) {
2200             if (st->codec->codec_id == AV_CODEC_ID_SIPR)
2201                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2202             track->audio.sub_packet_cnt = 0;
2203             track->audio.pkt_cnt = h*w / a;
2204         }
2205     }
2206
2207     while (track->audio.pkt_cnt) {
2208         AVPacket *pkt = NULL;
2209         if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0){
2210             av_free(pkt);
2211             return AVERROR(ENOMEM);
2212         }
2213         memcpy(pkt->data, track->audio.buf
2214                + a * (h*w / a - track->audio.pkt_cnt--), a);
2215         pkt->pts = track->audio.buf_timecode;
2216         track->audio.buf_timecode = AV_NOPTS_VALUE;
2217         pkt->pos = pos;
2218         pkt->stream_index = st->index;
2219         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2220     }
2221
2222     return 0;
2223 }
2224
2225 /* reconstruct full wavpack blocks from mangled matroska ones */
2226 static int matroska_parse_wavpack(MatroskaTrack *track, uint8_t *src,
2227                                   uint8_t **pdst, int *size)
2228 {
2229     uint8_t *dst = NULL;
2230     int dstlen   = 0;
2231     int srclen   = *size;
2232     uint32_t samples;
2233     uint16_t ver;
2234     int ret, offset = 0;
2235
2236     if (srclen < 12 || track->stream->codec->extradata_size < 2)
2237         return AVERROR_INVALIDDATA;
2238
2239     ver = AV_RL16(track->stream->codec->extradata);
2240
2241     samples = AV_RL32(src);
2242     src    += 4;
2243     srclen -= 4;
2244
2245     while (srclen >= 8) {
2246         int multiblock;
2247         uint32_t blocksize;
2248         uint8_t *tmp;
2249
2250         uint32_t flags = AV_RL32(src);
2251         uint32_t crc   = AV_RL32(src + 4);
2252         src    += 8;
2253         srclen -= 8;
2254
2255         multiblock = (flags & 0x1800) != 0x1800;
2256         if (multiblock) {
2257             if (srclen < 4) {
2258                 ret = AVERROR_INVALIDDATA;
2259                 goto fail;
2260             }
2261             blocksize = AV_RL32(src);
2262             src    += 4;
2263             srclen -= 4;
2264         } else
2265             blocksize = srclen;
2266
2267         if (blocksize > srclen) {
2268             ret = AVERROR_INVALIDDATA;
2269             goto fail;
2270         }
2271
2272         tmp = av_realloc(dst, dstlen + blocksize + 32);
2273         if (!tmp) {
2274             ret = AVERROR(ENOMEM);
2275             goto fail;
2276         }
2277         dst     = tmp;
2278         dstlen += blocksize + 32;
2279
2280         AV_WL32(dst + offset,      MKTAG('w', 'v', 'p', 'k')); // tag
2281         AV_WL32(dst + offset + 4,  blocksize + 24);            // blocksize - 8
2282         AV_WL16(dst + offset + 8,  ver);                       // version
2283         AV_WL16(dst + offset + 10, 0);                         // track/index_no
2284         AV_WL32(dst + offset + 12, 0);                         // total samples
2285         AV_WL32(dst + offset + 16, 0);                         // block index
2286         AV_WL32(dst + offset + 20, samples);                   // number of samples
2287         AV_WL32(dst + offset + 24, flags);                     // flags
2288         AV_WL32(dst + offset + 28, crc);                       // crc
2289         memcpy (dst + offset + 32, src, blocksize);            // block data
2290
2291         src    += blocksize;
2292         srclen -= blocksize;
2293         offset += blocksize + 32;
2294     }
2295
2296     *pdst = dst;
2297     *size = dstlen;
2298
2299     return 0;
2300
2301 fail:
2302     av_freep(&dst);
2303     return ret;
2304 }
2305
2306 static int matroska_parse_webvtt(MatroskaDemuxContext *matroska,
2307                                  MatroskaTrack *track,
2308                                  AVStream *st,
2309                                  uint8_t *data, int data_len,
2310                                  uint64_t timecode,
2311                                  uint64_t duration,
2312                                  int64_t pos)
2313 {
2314     AVPacket *pkt;
2315     uint8_t *id, *settings, *text, *buf;
2316     int id_len, settings_len, text_len;
2317     uint8_t *p, *q;
2318     int err;
2319
2320     if (data_len <= 0)
2321         return AVERROR_INVALIDDATA;
2322
2323     p = data;
2324     q = data + data_len;
2325
2326     id = p;
2327     id_len = -1;
2328     while (p < q) {
2329         if (*p == '\r' || *p == '\n') {
2330             id_len = p - id;
2331             if (*p == '\r')
2332                 p++;
2333             break;
2334         }
2335         p++;
2336     }
2337
2338     if (p >= q || *p != '\n')
2339         return AVERROR_INVALIDDATA;
2340     p++;
2341
2342     settings = p;
2343     settings_len = -1;
2344     while (p < q) {
2345         if (*p == '\r' || *p == '\n') {
2346             settings_len = p - settings;
2347             if (*p == '\r')
2348                 p++;
2349             break;
2350         }
2351         p++;
2352     }
2353
2354     if (p >= q || *p != '\n')
2355         return AVERROR_INVALIDDATA;
2356     p++;
2357
2358     text = p;
2359     text_len = q - p;
2360     while (text_len > 0) {
2361         const int len = text_len - 1;
2362         const uint8_t c = p[len];
2363         if (c != '\r' && c != '\n')
2364             break;
2365         text_len = len;
2366     }
2367
2368     if (text_len <= 0)
2369         return AVERROR_INVALIDDATA;
2370
2371     pkt = av_mallocz(sizeof(*pkt));
2372     err = av_new_packet(pkt, text_len);
2373     if (err < 0) {
2374         av_free(pkt);
2375         return AVERROR(err);
2376     }
2377
2378     memcpy(pkt->data, text, text_len);
2379
2380     if (id_len > 0) {
2381         buf = av_packet_new_side_data(pkt,
2382                                       AV_PKT_DATA_WEBVTT_IDENTIFIER,
2383                                       id_len);
2384         if (buf == NULL) {
2385             av_free(pkt);
2386             return AVERROR(ENOMEM);
2387         }
2388         memcpy(buf, id, id_len);
2389     }
2390
2391     if (settings_len > 0) {
2392         buf = av_packet_new_side_data(pkt,
2393                                       AV_PKT_DATA_WEBVTT_SETTINGS,
2394                                       settings_len);
2395         if (buf == NULL) {
2396             av_free(pkt);
2397             return AVERROR(ENOMEM);
2398         }
2399         memcpy(buf, settings, settings_len);
2400     }
2401
2402     // Do we need this for subtitles?
2403     // pkt->flags = AV_PKT_FLAG_KEY;
2404
2405     pkt->stream_index = st->index;
2406     pkt->pts = timecode;
2407
2408     // Do we need this for subtitles?
2409     // pkt->dts = timecode;
2410
2411     pkt->duration = duration;
2412     pkt->pos = pos;
2413
2414     dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2415     matroska->prev_pkt = pkt;
2416
2417     return 0;
2418 }
2419
2420 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
2421                                 MatroskaTrack *track,
2422                                 AVStream *st,
2423                                 uint8_t *data, int pkt_size,
2424                                 uint64_t timecode, uint64_t lace_duration,
2425                                 int64_t pos, int is_keyframe,
2426                                 uint8_t *additional, uint64_t additional_id, int additional_size,
2427                                 int64_t discard_padding)
2428 {
2429     MatroskaTrackEncoding *encodings = track->encodings.elem;
2430     uint8_t *pkt_data = data;
2431     int offset = 0, res;
2432     AVPacket *pkt;
2433
2434     if (encodings && !encodings->type && encodings->scope & 1) {
2435         res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2436         if (res < 0)
2437             return res;
2438     }
2439
2440     if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {
2441         uint8_t *wv_data;
2442         res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);
2443         if (res < 0) {
2444             av_log(matroska->ctx, AV_LOG_ERROR, "Error parsing a wavpack block.\n");
2445             goto fail;
2446         }
2447         if (pkt_data != data)
2448             av_freep(&pkt_data);
2449         pkt_data = wv_data;
2450     }
2451
2452     if (st->codec->codec_id == AV_CODEC_ID_PRORES)
2453         offset = 8;
2454
2455     pkt = av_mallocz(sizeof(AVPacket));
2456     /* XXX: prevent data copy... */
2457     if (av_new_packet(pkt, pkt_size + offset) < 0) {
2458         av_free(pkt);
2459         res = AVERROR(ENOMEM);
2460         goto fail;
2461     }
2462
2463     if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
2464         uint8_t *buf = pkt->data;
2465         bytestream_put_be32(&buf, pkt_size);
2466         bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
2467     }
2468
2469     memcpy(pkt->data + offset, pkt_data, pkt_size);
2470
2471     if (pkt_data != data)
2472         av_freep(&pkt_data);
2473
2474     pkt->flags = is_keyframe;
2475     pkt->stream_index = st->index;
2476
2477     if (additional_size > 0) {
2478         uint8_t *side_data = av_packet_new_side_data(pkt,
2479                                                      AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
2480                                                      additional_size + 8);
2481         if(side_data == NULL) {
2482             av_free_packet(pkt);
2483             av_free(pkt);
2484             return AVERROR(ENOMEM);
2485         }
2486         AV_WB64(side_data, additional_id);
2487         memcpy(side_data + 8, additional, additional_size);
2488     }
2489
2490     if (discard_padding) {
2491         uint8_t *side_data = av_packet_new_side_data(pkt,
2492                                                      AV_PKT_DATA_SKIP_SAMPLES,
2493                                                      10);
2494         if(side_data == NULL) {
2495             av_free_packet(pkt);
2496             av_free(pkt);
2497             return AVERROR(ENOMEM);
2498         }
2499         AV_WL32(side_data, 0);
2500         AV_WL32(side_data + 4, av_rescale_q(discard_padding,
2501                                             (AVRational){1, 1000000000},
2502                                             (AVRational){1, st->codec->sample_rate}));
2503     }
2504
2505     if (track->ms_compat)
2506         pkt->dts = timecode;
2507     else
2508         pkt->pts = timecode;
2509     pkt->pos = pos;
2510     if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
2511         /*
2512          * For backward compatibility.
2513          * Historically, we have put subtitle duration
2514          * in convergence_duration, on the off chance
2515          * that the time_scale is less than 1us, which
2516          * could result in a 32bit overflow on the
2517          * normal duration field.
2518          */
2519         pkt->convergence_duration = lace_duration;
2520     }
2521
2522     if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
2523         lace_duration <= INT_MAX) {
2524         /*
2525          * For non subtitle tracks, just store the duration
2526          * as normal.
2527          *
2528          * If it's a subtitle track and duration value does
2529          * not overflow a uint32, then also store it normally.
2530          */
2531         pkt->duration = lace_duration;
2532     }
2533
2534 #if FF_API_ASS_SSA
2535     if (st->codec->codec_id == AV_CODEC_ID_SSA)
2536         matroska_fix_ass_packet(matroska, pkt, lace_duration);
2537
2538     if (matroska->prev_pkt &&
2539         timecode != AV_NOPTS_VALUE &&
2540         matroska->prev_pkt->pts == timecode &&
2541         matroska->prev_pkt->stream_index == st->index &&
2542         st->codec->codec_id == AV_CODEC_ID_SSA)
2543         matroska_merge_packets(matroska->prev_pkt, pkt);
2544     else {
2545         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2546         matroska->prev_pkt = pkt;
2547     }
2548 #else
2549     dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
2550     matroska->prev_pkt = pkt;
2551 #endif
2552
2553     return 0;
2554 fail:
2555     if (pkt_data != data)
2556         av_freep(&pkt_data);
2557     return res;
2558 }
2559
2560 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
2561                                 int size, int64_t pos, uint64_t cluster_time,
2562                                 uint64_t block_duration, int is_keyframe,
2563                                 uint8_t *additional, uint64_t additional_id, int additional_size,
2564                                 int64_t cluster_pos, int64_t discard_padding)
2565 {
2566     uint64_t timecode = AV_NOPTS_VALUE;
2567     MatroskaTrack *track;
2568     int res = 0;
2569     AVStream *st;
2570     int16_t block_time;
2571     uint32_t *lace_size = NULL;
2572     int n, flags, laces = 0;
2573     uint64_t num;
2574     int trust_default_duration = 1;
2575
2576     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2577         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2578         return n;
2579     }
2580     data += n;
2581     size -= n;
2582
2583     track = matroska_find_track_by_num(matroska, num);
2584     if (!track || !track->stream) {
2585         av_log(matroska->ctx, AV_LOG_INFO,
2586                "Invalid stream %"PRIu64" or size %u\n", num, size);
2587         return AVERROR_INVALIDDATA;
2588     } else if (size <= 3)
2589         return 0;
2590     st = track->stream;
2591     if (st->discard >= AVDISCARD_ALL)
2592         return res;
2593     av_assert1(block_duration != AV_NOPTS_VALUE);
2594
2595     block_time = sign_extend(AV_RB16(data), 16);
2596     data += 2;
2597     flags = *data++;
2598     size -= 3;
2599     if (is_keyframe == -1)
2600         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2601
2602     if (cluster_time != (uint64_t)-1
2603         && (block_time >= 0 || cluster_time >= -block_time)) {
2604         timecode = cluster_time + block_time;
2605         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2606             && timecode < track->end_timecode)
2607             is_keyframe = 0;  /* overlapping subtitles are not key frame */
2608         if (is_keyframe)
2609             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2610     }
2611
2612     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2613         if (timecode < matroska->skip_to_timecode)
2614             return res;
2615         if (is_keyframe)
2616             matroska->skip_to_keyframe = 0;
2617         else if (!st->skip_to_keyframe) {
2618             av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
2619             matroska->skip_to_keyframe = 0;
2620         }
2621     }
2622
2623     res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,
2624                                &lace_size, &laces);
2625
2626     if (res)
2627         goto end;
2628
2629     if (track->audio.samplerate == 8000) {
2630         // If this is needed for more codecs, then add them here
2631         if (st->codec->codec_id == AV_CODEC_ID_AC3) {
2632             if(track->audio.samplerate != st->codec->sample_rate || !st->codec->frame_size)
2633                 trust_default_duration = 0;
2634         }
2635     }
2636
2637     if (!block_duration && trust_default_duration)
2638         block_duration = track->default_duration * laces / matroska->time_scale;
2639
2640     if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
2641         track->end_timecode =
2642             FFMAX(track->end_timecode, timecode + block_duration);
2643
2644     for (n = 0; n < laces; n++) {
2645         int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
2646
2647         if (lace_size[n] > size) {
2648             av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
2649             break;
2650         }
2651
2652         if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2653              st->codec->codec_id == AV_CODEC_ID_COOK ||
2654              st->codec->codec_id == AV_CODEC_ID_SIPR ||
2655              st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2656              st->codec->block_align && track->audio.sub_packet_size) {
2657
2658             res = matroska_parse_rm_audio(matroska, track, st, data,
2659                                           lace_size[n],
2660                                           timecode, pos);
2661             if (res)
2662                 goto end;
2663
2664         } else if (st->codec->codec_id == AV_CODEC_ID_WEBVTT) {
2665             res = matroska_parse_webvtt(matroska, track, st,
2666                                         data, lace_size[n],
2667                                         timecode, lace_duration,
2668                                         pos);
2669             if (res)
2670                 goto end;
2671
2672         } else {
2673             res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2674                                       timecode, lace_duration,
2675                                       pos, !n? is_keyframe : 0,
2676                                       additional, additional_id, additional_size,
2677                                       discard_padding);
2678             if (res)
2679                 goto end;
2680         }
2681
2682         if (timecode != AV_NOPTS_VALUE)
2683             timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
2684         data += lace_size[n];
2685         size -= lace_size[n];
2686     }
2687
2688 end:
2689     av_free(lace_size);
2690     return res;
2691 }
2692
2693 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
2694 {
2695     EbmlList *blocks_list;
2696     MatroskaBlock *blocks;
2697     int i, res;
2698     res = ebml_parse(matroska,
2699                      matroska_cluster_incremental_parsing,
2700                      &matroska->current_cluster);
2701     if (res == 1) {
2702         /* New Cluster */
2703         if (matroska->current_cluster_pos)
2704             ebml_level_end(matroska);
2705         ebml_free(matroska_cluster, &matroska->current_cluster);
2706         memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2707         matroska->current_cluster_num_blocks = 0;
2708         matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2709         matroska->prev_pkt = NULL;
2710         /* sizeof the ID which was already read */
2711         if (matroska->current_id)
2712             matroska->current_cluster_pos -= 4;
2713         res = ebml_parse(matroska,
2714                          matroska_clusters_incremental,
2715                          &matroska->current_cluster);
2716         /* Try parsing the block again. */
2717         if (res == 1)
2718             res = ebml_parse(matroska,
2719                              matroska_cluster_incremental_parsing,
2720                              &matroska->current_cluster);
2721     }
2722
2723     if (!res &&
2724         matroska->current_cluster_num_blocks <
2725             matroska->current_cluster.blocks.nb_elem) {
2726         blocks_list = &matroska->current_cluster.blocks;
2727         blocks = blocks_list->elem;
2728
2729         matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2730         i = blocks_list->nb_elem - 1;
2731         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2732             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2733             uint8_t* additional = blocks[i].additional.size > 0 ?
2734                                     blocks[i].additional.data : NULL;
2735             if (!blocks[i].non_simple)
2736                 blocks[i].duration = 0;
2737             res = matroska_parse_block(matroska,
2738                                        blocks[i].bin.data, blocks[i].bin.size,
2739                                        blocks[i].bin.pos,
2740                                        matroska->current_cluster.timecode,
2741                                        blocks[i].duration, is_keyframe,
2742                                        additional, blocks[i].additional_id,
2743                                        blocks[i].additional.size,
2744                                        matroska->current_cluster_pos,
2745                                        blocks[i].discard_padding);
2746         }
2747     }
2748
2749     return res;
2750 }
2751
2752 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2753 {
2754     MatroskaCluster cluster = { 0 };
2755     EbmlList *blocks_list;
2756     MatroskaBlock *blocks;
2757     int i, res;
2758     int64_t pos;
2759     if (!matroska->contains_ssa)
2760         return matroska_parse_cluster_incremental(matroska);
2761     pos = avio_tell(matroska->ctx->pb);
2762     matroska->prev_pkt = NULL;
2763     if (matroska->current_id)
2764         pos -= 4;  /* sizeof the ID which was already read */
2765     res = ebml_parse(matroska, matroska_clusters, &cluster);
2766     blocks_list = &cluster.blocks;
2767     blocks = blocks_list->elem;
2768     for (i=0; i<blocks_list->nb_elem; i++)
2769         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2770             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2771             res=matroska_parse_block(matroska,
2772                                      blocks[i].bin.data, blocks[i].bin.size,
2773                                      blocks[i].bin.pos,  cluster.timecode,
2774                                      blocks[i].duration, is_keyframe, NULL, 0, 0,
2775                                      pos, blocks[i].discard_padding);
2776         }
2777     ebml_free(matroska_cluster, &cluster);
2778     return res;
2779 }
2780
2781 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2782 {
2783     MatroskaDemuxContext *matroska = s->priv_data;
2784
2785     while (matroska_deliver_packet(matroska, pkt)) {
2786         int64_t pos = avio_tell(matroska->ctx->pb);
2787         if (matroska->done)
2788             return AVERROR_EOF;
2789         if (matroska_parse_cluster(matroska) < 0)
2790             matroska_resync(matroska, pos);
2791     }
2792
2793     return 0;
2794 }
2795
2796 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2797                               int64_t timestamp, int flags)
2798 {
2799     MatroskaDemuxContext *matroska = s->priv_data;
2800     MatroskaTrack *tracks = matroska->tracks.elem;
2801     AVStream *st = s->streams[stream_index];
2802     int i, index, index_sub, index_min;
2803
2804     /* Parse the CUES now since we need the index data to seek. */
2805     if (matroska->cues_parsing_deferred > 0) {
2806         matroska->cues_parsing_deferred = 0;
2807         matroska_parse_cues(matroska);
2808     }
2809
2810     if (!st->nb_index_entries)
2811         goto err;
2812     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2813
2814     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2815         avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2816         matroska->current_id = 0;
2817         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2818             matroska_clear_queue(matroska);
2819             if (matroska_parse_cluster(matroska) < 0)
2820                 break;
2821         }
2822     }
2823
2824     matroska_clear_queue(matroska);
2825     if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
2826         goto err;
2827
2828     index_min = index;
2829     for (i=0; i < matroska->tracks.nb_elem; i++) {
2830         tracks[i].audio.pkt_cnt = 0;
2831         tracks[i].audio.sub_packet_cnt = 0;
2832         tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2833         tracks[i].end_timecode = 0;
2834         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2835             && tracks[i].stream->discard != AVDISCARD_ALL) {
2836             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2837             while(index_sub >= 0
2838                   && index_min >= 0
2839                   && tracks[i].stream->index_entries[index_sub].pos < st->index_entries[index_min].pos
2840                   && st->index_entries[index].timestamp - tracks[i].stream->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2841                 index_min--;
2842         }
2843     }
2844
2845     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2846     matroska->current_id = 0;
2847     if (flags & AVSEEK_FLAG_ANY) {
2848         st->skip_to_keyframe = 0;
2849         matroska->skip_to_timecode = timestamp;
2850     } else {
2851         st->skip_to_keyframe = 1;
2852         matroska->skip_to_timecode = st->index_entries[index].timestamp;
2853     }
2854     matroska->skip_to_keyframe = 1;
2855     matroska->done = 0;
2856     matroska->num_levels = 0;
2857     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2858     return 0;
2859 err:
2860     // slightly hackish but allows proper fallback to
2861     // the generic seeking code.
2862     matroska_clear_queue(matroska);
2863     matroska->current_id = 0;
2864     st->skip_to_keyframe =
2865     matroska->skip_to_keyframe = 0;
2866     matroska->done = 0;
2867     matroska->num_levels = 0;
2868     return -1;
2869 }
2870
2871 static int matroska_read_close(AVFormatContext *s)
2872 {
2873     MatroskaDemuxContext *matroska = s->priv_data;
2874     MatroskaTrack *tracks = matroska->tracks.elem;
2875     int n;
2876
2877     matroska_clear_queue(matroska);
2878
2879     for (n=0; n < matroska->tracks.nb_elem; n++)
2880         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2881             av_freep(&tracks[n].audio.buf);
2882     ebml_free(matroska_cluster, &matroska->current_cluster);
2883     ebml_free(matroska_segment, matroska);
2884
2885     return 0;
2886 }
2887
2888 AVInputFormat ff_matroska_demuxer = {
2889     .name           = "matroska,webm",
2890     .long_name      = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2891     .priv_data_size = sizeof(MatroskaDemuxContext),
2892     .read_probe     = matroska_probe,
2893     .read_header    = matroska_read_header,
2894     .read_packet    = matroska_read_packet,
2895     .read_close     = matroska_read_close,
2896     .read_seek      = matroska_read_seek,
2897 };