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