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