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