]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
Merge remote-tracking branch 'qatar/master'
[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  * by Ronald Bultje <rbultje@ronald.bitfreak.net>
26  * with a little help from Moritz Bunkus <moritz@bunkus.org>
27  * totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28  * 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 "rm.h"
39 #include "matroska.h"
40 #include "libavcodec/mpeg4audio.h"
41 #include "libavutil/intfloat_readwrite.h"
42 #include "libavutil/intreadwrite.h"
43 #include "libavutil/avstring.h"
44 #include "libavutil/lzo.h"
45 #include "libavutil/dict.h"
46 #if CONFIG_ZLIB
47 #include <zlib.h>
48 #endif
49 #if CONFIG_BZLIB
50 #include <bzlib.h>
51 #endif
52
53 typedef enum {
54     EBML_NONE,
55     EBML_UINT,
56     EBML_FLOAT,
57     EBML_STR,
58     EBML_UTF8,
59     EBML_BIN,
60     EBML_NEST,
61     EBML_PASS,
62     EBML_STOP,
63     EBML_TYPE_COUNT
64 } EbmlType;
65
66 typedef const struct EbmlSyntax {
67     uint32_t id;
68     EbmlType type;
69     int list_elem_size;
70     int data_offset;
71     union {
72         uint64_t    u;
73         double      f;
74         const char *s;
75         const struct EbmlSyntax *n;
76     } def;
77 } EbmlSyntax;
78
79 typedef struct {
80     int nb_elem;
81     void *elem;
82 } EbmlList;
83
84 typedef struct {
85     int      size;
86     uint8_t *data;
87     int64_t  pos;
88 } EbmlBin;
89
90 typedef struct {
91     uint64_t version;
92     uint64_t max_size;
93     uint64_t id_length;
94     char    *doctype;
95     uint64_t doctype_version;
96 } Ebml;
97
98 typedef struct {
99     uint64_t algo;
100     EbmlBin  settings;
101 } MatroskaTrackCompression;
102
103 typedef struct {
104     uint64_t scope;
105     uint64_t type;
106     MatroskaTrackCompression compression;
107 } MatroskaTrackEncoding;
108
109 typedef struct {
110     double   frame_rate;
111     uint64_t display_width;
112     uint64_t display_height;
113     uint64_t pixel_width;
114     uint64_t pixel_height;
115     EbmlBin color_space;
116     uint64_t stereo_mode;
117 } MatroskaTrackVideo;
118
119 typedef struct {
120     double   samplerate;
121     double   out_samplerate;
122     uint64_t bitdepth;
123     uint64_t channels;
124
125     /* real audio header (extracted from extradata) */
126     int      coded_framesize;
127     int      sub_packet_h;
128     int      frame_size;
129     int      sub_packet_size;
130     int      sub_packet_cnt;
131     int      pkt_cnt;
132     uint64_t buf_timecode;
133     uint8_t *buf;
134 } MatroskaTrackAudio;
135
136 typedef struct {
137     uint64_t uid;
138     uint64_t type;
139 } MatroskaTrackPlane;
140
141 typedef struct {
142     EbmlList combine_planes;
143 } MatroskaTrackOperation;
144
145 typedef struct {
146     uint64_t num;
147     uint64_t uid;
148     uint64_t type;
149     char    *name;
150     char    *codec_id;
151     EbmlBin  codec_priv;
152     char    *language;
153     double time_scale;
154     uint64_t default_duration;
155     uint64_t flag_default;
156     uint64_t flag_forced;
157     MatroskaTrackVideo video;
158     MatroskaTrackAudio audio;
159     MatroskaTrackOperation operation;
160     EbmlList encodings;
161
162     AVStream *stream;
163     int64_t end_timecode;
164     int ms_compat;
165 } MatroskaTrack;
166
167 typedef struct {
168     uint64_t uid;
169     char *filename;
170     char *mime;
171     EbmlBin bin;
172
173     AVStream *stream;
174 } MatroskaAttachement;
175
176 typedef struct {
177     uint64_t start;
178     uint64_t end;
179     uint64_t uid;
180     char    *title;
181
182     AVChapter *chapter;
183 } MatroskaChapter;
184
185 typedef struct {
186     uint64_t track;
187     uint64_t pos;
188 } MatroskaIndexPos;
189
190 typedef struct {
191     uint64_t time;
192     EbmlList pos;
193 } MatroskaIndex;
194
195 typedef struct {
196     char *name;
197     char *string;
198     char *lang;
199     uint64_t def;
200     EbmlList sub;
201 } MatroskaTag;
202
203 typedef struct {
204     char    *type;
205     uint64_t typevalue;
206     uint64_t trackuid;
207     uint64_t chapteruid;
208     uint64_t attachuid;
209 } MatroskaTagTarget;
210
211 typedef struct {
212     MatroskaTagTarget target;
213     EbmlList tag;
214 } MatroskaTags;
215
216 typedef struct {
217     uint64_t id;
218     uint64_t pos;
219 } MatroskaSeekhead;
220
221 typedef struct {
222     uint64_t start;
223     uint64_t length;
224 } MatroskaLevel;
225
226 typedef struct {
227     AVFormatContext *ctx;
228
229     /* EBML stuff */
230     int num_levels;
231     MatroskaLevel levels[EBML_MAX_DEPTH];
232     int level_up;
233     uint32_t current_id;
234
235     uint64_t time_scale;
236     double   duration;
237     char    *title;
238     EbmlList tracks;
239     EbmlList attachments;
240     EbmlList chapters;
241     EbmlList index;
242     EbmlList tags;
243     EbmlList seekhead;
244
245     /* byte position of the segment inside the stream */
246     int64_t segment_start;
247
248     /* the packet queue */
249     AVPacket **packets;
250     int num_packets;
251     AVPacket *prev_pkt;
252
253     int done;
254
255     /* What to skip before effectively reading a packet. */
256     int skip_to_keyframe;
257     uint64_t skip_to_timecode;
258
259     /* File has a CUES element, but we defer parsing until it is needed. */
260     int cues_parsing_deferred;
261 } MatroskaDemuxContext;
262
263 typedef struct {
264     uint64_t duration;
265     int64_t  reference;
266     uint64_t non_simple;
267     EbmlBin  bin;
268 } MatroskaBlock;
269
270 typedef struct {
271     uint64_t timecode;
272     EbmlList blocks;
273 } MatroskaCluster;
274
275 static EbmlSyntax ebml_header[] = {
276     { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
277     { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
278     { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
279     { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
280     { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
281     { EBML_ID_EBMLVERSION,            EBML_NONE },
282     { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
283     { 0 }
284 };
285
286 static EbmlSyntax ebml_syntax[] = {
287     { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
288     { 0 }
289 };
290
291 static EbmlSyntax matroska_info[] = {
292     { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
293     { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
294     { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
295     { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
296     { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
297     { MATROSKA_ID_DATEUTC,            EBML_NONE },
298     { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
299     { 0 }
300 };
301
302 static EbmlSyntax matroska_track_video[] = {
303     { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
304     { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
305     { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
306     { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
307     { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
308     { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_BIN,  0, offsetof(MatroskaTrackVideo,color_space) },
309     { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,stereo_mode) },
310     { MATROSKA_ID_VIDEOPIXELCROPB,    EBML_NONE },
311     { MATROSKA_ID_VIDEOPIXELCROPT,    EBML_NONE },
312     { MATROSKA_ID_VIDEOPIXELCROPL,    EBML_NONE },
313     { MATROSKA_ID_VIDEOPIXELCROPR,    EBML_NONE },
314     { MATROSKA_ID_VIDEODISPLAYUNIT,   EBML_NONE },
315     { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
316     { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
317     { 0 }
318 };
319
320 static EbmlSyntax matroska_track_audio[] = {
321     { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
322     { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
323     { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
324     { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
325     { 0 }
326 };
327
328 static EbmlSyntax matroska_track_encoding_compression[] = {
329     { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
330     { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
331     { 0 }
332 };
333
334 static EbmlSyntax matroska_track_encoding[] = {
335     { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
336     { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
337     { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
338     { MATROSKA_ID_ENCODINGORDER,      EBML_NONE },
339     { 0 }
340 };
341
342 static EbmlSyntax matroska_track_encodings[] = {
343     { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
344     { 0 }
345 };
346
347 static EbmlSyntax matroska_track_plane[] = {
348     { MATROSKA_ID_TRACKPLANEUID,  EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
349     { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
350     { 0 }
351 };
352
353 static EbmlSyntax matroska_track_combine_planes[] = {
354     { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n=matroska_track_plane} },
355     { 0 }
356 };
357
358 static EbmlSyntax matroska_track_operation[] = {
359     { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n=matroska_track_combine_planes} },
360     { 0 }
361 };
362
363 static EbmlSyntax matroska_track[] = {
364     { MATROSKA_ID_TRACKNUMBER,          EBML_UINT, 0, offsetof(MatroskaTrack,num) },
365     { MATROSKA_ID_TRACKNAME,            EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
366     { MATROSKA_ID_TRACKUID,             EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
367     { MATROSKA_ID_TRACKTYPE,            EBML_UINT, 0, offsetof(MatroskaTrack,type) },
368     { MATROSKA_ID_CODECID,              EBML_STR,  0, offsetof(MatroskaTrack,codec_id) },
369     { MATROSKA_ID_CODECPRIVATE,         EBML_BIN,  0, offsetof(MatroskaTrack,codec_priv) },
370     { MATROSKA_ID_TRACKLANGUAGE,        EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
371     { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
372     { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
373     { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
374     { MATROSKA_ID_TRACKFLAGFORCED,      EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
375     { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
376     { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
377     { MATROSKA_ID_TRACKOPERATION,       EBML_NEST, 0, offsetof(MatroskaTrack,operation), {.n=matroska_track_operation} },
378     { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
379     { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
380     { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
381     { MATROSKA_ID_CODECNAME,            EBML_NONE },
382     { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
383     { MATROSKA_ID_CODECINFOURL,         EBML_NONE },
384     { MATROSKA_ID_CODECDOWNLOADURL,     EBML_NONE },
385     { MATROSKA_ID_TRACKMINCACHE,        EBML_NONE },
386     { MATROSKA_ID_TRACKMAXCACHE,        EBML_NONE },
387     { MATROSKA_ID_TRACKMAXBLKADDID,     EBML_NONE },
388     { 0 }
389 };
390
391 static EbmlSyntax matroska_tracks[] = {
392     { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
393     { 0 }
394 };
395
396 static EbmlSyntax matroska_attachment[] = {
397     { MATROSKA_ID_FILEUID,            EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
398     { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
399     { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
400     { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
401     { MATROSKA_ID_FILEDESC,           EBML_NONE },
402     { 0 }
403 };
404
405 static EbmlSyntax matroska_attachments[] = {
406     { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
407     { 0 }
408 };
409
410 static EbmlSyntax matroska_chapter_display[] = {
411     { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
412     { MATROSKA_ID_CHAPLANG,           EBML_NONE },
413     { 0 }
414 };
415
416 static EbmlSyntax matroska_chapter_entry[] = {
417     { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
418     { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
419     { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
420     { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
421     { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
422     { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
423     { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
424     { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
425     { 0 }
426 };
427
428 static EbmlSyntax matroska_chapter[] = {
429     { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
430     { MATROSKA_ID_EDITIONUID,         EBML_NONE },
431     { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
432     { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
433     { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
434     { 0 }
435 };
436
437 static EbmlSyntax matroska_chapters[] = {
438     { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
439     { 0 }
440 };
441
442 static EbmlSyntax matroska_index_pos[] = {
443     { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
444     { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
445     { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
446     { 0 }
447 };
448
449 static EbmlSyntax matroska_index_entry[] = {
450     { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
451     { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
452     { 0 }
453 };
454
455 static EbmlSyntax matroska_index[] = {
456     { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
457     { 0 }
458 };
459
460 static EbmlSyntax matroska_simpletag[] = {
461     { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
462     { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
463     { MATROSKA_ID_TAGLANG,            EBML_STR,  0, offsetof(MatroskaTag,lang), {.s="und"} },
464     { MATROSKA_ID_TAGDEFAULT,         EBML_UINT, 0, offsetof(MatroskaTag,def) },
465     { MATROSKA_ID_TAGDEFAULT_BUG,     EBML_UINT, 0, offsetof(MatroskaTag,def) },
466     { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
467     { 0 }
468 };
469
470 static EbmlSyntax matroska_tagtargets[] = {
471     { MATROSKA_ID_TAGTARGETS_TYPE,      EBML_STR,  0, offsetof(MatroskaTagTarget,type) },
472     { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
473     { MATROSKA_ID_TAGTARGETS_TRACKUID,  EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
474     { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
475     { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
476     { 0 }
477 };
478
479 static EbmlSyntax matroska_tag[] = {
480     { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
481     { MATROSKA_ID_TAGTARGETS,         EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
482     { 0 }
483 };
484
485 static EbmlSyntax matroska_tags[] = {
486     { MATROSKA_ID_TAG,                EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
487     { 0 }
488 };
489
490 static EbmlSyntax matroska_seekhead_entry[] = {
491     { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
492     { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
493     { 0 }
494 };
495
496 static EbmlSyntax matroska_seekhead[] = {
497     { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
498     { 0 }
499 };
500
501 static EbmlSyntax matroska_segment[] = {
502     { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
503     { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
504     { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
505     { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
506     { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
507     { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
508     { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
509     { MATROSKA_ID_CLUSTER,        EBML_STOP },
510     { 0 }
511 };
512
513 static EbmlSyntax matroska_segments[] = {
514     { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
515     { 0 }
516 };
517
518 static EbmlSyntax matroska_blockgroup[] = {
519     { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
520     { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
521     { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration) },
522     { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
523     { 1,                          EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
524     { 0 }
525 };
526
527 static EbmlSyntax matroska_cluster[] = {
528     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
529     { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
530     { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
531     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
532     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
533     { 0 }
534 };
535
536 static EbmlSyntax matroska_clusters[] = {
537     { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
538     { MATROSKA_ID_INFO,           EBML_NONE },
539     { MATROSKA_ID_CUES,           EBML_NONE },
540     { MATROSKA_ID_TAGS,           EBML_NONE },
541     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
542     { 0 }
543 };
544
545 static const char *matroska_doctypes[] = { "matroska", "webm" };
546
547 /*
548  * Return: Whether we reached the end of a level in the hierarchy or not.
549  */
550 static int ebml_level_end(MatroskaDemuxContext *matroska)
551 {
552     AVIOContext *pb = matroska->ctx->pb;
553     int64_t pos = avio_tell(pb);
554
555     if (matroska->num_levels > 0) {
556         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
557         if (pos - level->start >= level->length || matroska->current_id) {
558             matroska->num_levels--;
559             return 1;
560         }
561     }
562     return 0;
563 }
564
565 /*
566  * Read: an "EBML number", which is defined as a variable-length
567  * array of bytes. The first byte indicates the length by giving a
568  * number of 0-bits followed by a one. The position of the first
569  * "one" bit inside the first byte indicates the length of this
570  * number.
571  * Returns: number of bytes read, < 0 on error
572  */
573 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
574                          int max_size, uint64_t *number)
575 {
576     int read = 1, n = 1;
577     uint64_t total = 0;
578
579     /* The first byte tells us the length in bytes - avio_r8() can normally
580      * return 0, but since that's not a valid first ebmlID byte, we can
581      * use it safely here to catch EOS. */
582     if (!(total = avio_r8(pb))) {
583         /* we might encounter EOS here */
584         if (!url_feof(pb)) {
585             int64_t pos = avio_tell(pb);
586             av_log(matroska->ctx, AV_LOG_ERROR,
587                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
588                    pos, pos);
589         }
590         return AVERROR(EIO); /* EOS or actual I/O error */
591     }
592
593     /* get the length of the EBML number */
594     read = 8 - ff_log2_tab[total];
595     if (read > max_size) {
596         int64_t pos = avio_tell(pb) - 1;
597         av_log(matroska->ctx, AV_LOG_ERROR,
598                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
599                (uint8_t) total, pos, pos);
600         return AVERROR_INVALIDDATA;
601     }
602
603     /* read out length */
604     total ^= 1 << ff_log2_tab[total];
605     while (n++ < read)
606         total = (total << 8) | avio_r8(pb);
607
608     *number = total;
609
610     return read;
611 }
612
613 /**
614  * Read a EBML length value.
615  * This needs special handling for the "unknown length" case which has multiple
616  * encodings.
617  */
618 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
619                             uint64_t *number)
620 {
621     int res = ebml_read_num(matroska, pb, 8, number);
622     if (res > 0 && *number + 1 == 1ULL << (7 * res))
623         *number = 0xffffffffffffffULL;
624     return res;
625 }
626
627 /*
628  * Read the next element as an unsigned int.
629  * 0 is success, < 0 is failure.
630  */
631 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
632 {
633     int n = 0;
634
635     if (size > 8)
636         return AVERROR_INVALIDDATA;
637
638     /* big-endian ordering; build up number */
639     *num = 0;
640     while (n++ < size)
641         *num = (*num << 8) | avio_r8(pb);
642
643     return 0;
644 }
645
646 /*
647  * Read the next element as a float.
648  * 0 is success, < 0 is failure.
649  */
650 static int ebml_read_float(AVIOContext *pb, int size, double *num)
651 {
652     if (size == 0) {
653         *num = 0;
654     } else if (size == 4) {
655         *num= av_int2flt(avio_rb32(pb));
656     } else if(size==8){
657         *num= av_int2dbl(avio_rb64(pb));
658     } else
659         return AVERROR_INVALIDDATA;
660
661     return 0;
662 }
663
664 /*
665  * Read the next element as an ASCII string.
666  * 0 is success, < 0 is failure.
667  */
668 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
669 {
670     av_free(*str);
671     /* EBML strings are usually not 0-terminated, so we allocate one
672      * byte more, read the string and NULL-terminate it ourselves. */
673     if (!(*str = av_malloc(size + 1)))
674         return AVERROR(ENOMEM);
675     if (avio_read(pb, (uint8_t *) *str, size) != size) {
676         av_freep(str);
677         return AVERROR(EIO);
678     }
679     (*str)[size] = '\0';
680
681     return 0;
682 }
683
684 /*
685  * Read the next element as binary data.
686  * 0 is success, < 0 is failure.
687  */
688 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
689 {
690     av_free(bin->data);
691     if (!(bin->data = av_malloc(length)))
692         return AVERROR(ENOMEM);
693
694     bin->size = length;
695     bin->pos  = avio_tell(pb);
696     if (avio_read(pb, bin->data, length) != length) {
697         av_freep(&bin->data);
698         return AVERROR(EIO);
699     }
700
701     return 0;
702 }
703
704 /*
705  * Read the next element, but only the header. The contents
706  * are supposed to be sub-elements which can be read separately.
707  * 0 is success, < 0 is failure.
708  */
709 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
710 {
711     AVIOContext *pb = matroska->ctx->pb;
712     MatroskaLevel *level;
713
714     if (matroska->num_levels >= EBML_MAX_DEPTH) {
715         av_log(matroska->ctx, AV_LOG_ERROR,
716                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
717         return AVERROR(ENOSYS);
718     }
719
720     level = &matroska->levels[matroska->num_levels++];
721     level->start = avio_tell(pb);
722     level->length = length;
723
724     return 0;
725 }
726
727 /*
728  * Read signed/unsigned "EBML" numbers.
729  * Return: number of bytes processed, < 0 on error
730  */
731 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
732                                  uint8_t *data, uint32_t size, uint64_t *num)
733 {
734     AVIOContext pb;
735     ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
736     return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
737 }
738
739 /*
740  * Same as above, but signed.
741  */
742 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
743                                  uint8_t *data, uint32_t size, int64_t *num)
744 {
745     uint64_t unum;
746     int res;
747
748     /* read as unsigned number first */
749     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
750         return res;
751
752     /* make signed (weird way) */
753     *num = unum - ((1LL << (7*res - 1)) - 1);
754
755     return res;
756 }
757
758 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
759                            EbmlSyntax *syntax, void *data);
760
761 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
762                          uint32_t id, void *data)
763 {
764     int i;
765     for (i=0; syntax[i].id; i++)
766         if (id == syntax[i].id)
767             break;
768     if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
769         matroska->num_levels > 0 &&
770         matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
771         return 0;  // we reached the end of an unknown size cluster
772     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
773         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
774     return ebml_parse_elem(matroska, &syntax[i], data);
775 }
776
777 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
778                       void *data)
779 {
780     if (!matroska->current_id) {
781         uint64_t id;
782         int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
783         if (res < 0)
784             return res;
785         matroska->current_id = id | 1 << 7*res;
786     }
787     return ebml_parse_id(matroska, syntax, matroska->current_id, data);
788 }
789
790 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
791                            void *data)
792 {
793     int i, res = 0;
794
795     for (i=0; syntax[i].id; i++)
796         switch (syntax[i].type) {
797         case EBML_UINT:
798             *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
799             break;
800         case EBML_FLOAT:
801             *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
802             break;
803         case EBML_STR:
804         case EBML_UTF8:
805             *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
806             break;
807         }
808
809     while (!res && !ebml_level_end(matroska))
810         res = ebml_parse(matroska, syntax, data);
811
812     return res;
813 }
814
815 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
816                            EbmlSyntax *syntax, void *data)
817 {
818     static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
819         [EBML_UINT]  = 8,
820         [EBML_FLOAT] = 8,
821         // max. 16 MB for strings
822         [EBML_STR]   = 0x1000000,
823         [EBML_UTF8]  = 0x1000000,
824         // max. 256 MB for binary data
825         [EBML_BIN]   = 0x10000000,
826         // no limits for anything else
827     };
828     AVIOContext *pb = matroska->ctx->pb;
829     uint32_t id = syntax->id;
830     uint64_t length;
831     int res;
832
833     data = (char *)data + syntax->data_offset;
834     if (syntax->list_elem_size) {
835         EbmlList *list = data;
836         list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
837         data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
838         memset(data, 0, syntax->list_elem_size);
839         list->nb_elem++;
840     }
841
842     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
843         matroska->current_id = 0;
844         if ((res = ebml_read_length(matroska, pb, &length)) < 0)
845             return res;
846         if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
847             av_log(matroska->ctx, AV_LOG_ERROR,
848                    "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
849                    length, max_lengths[syntax->type], syntax->type);
850             return AVERROR_INVALIDDATA;
851         }
852     }
853
854     switch (syntax->type) {
855     case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
856     case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
857     case EBML_STR:
858     case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
859     case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
860     case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
861                          return res;
862                      if (id == MATROSKA_ID_SEGMENT)
863                          matroska->segment_start = avio_tell(matroska->ctx->pb);
864                      return ebml_parse_nest(matroska, syntax->def.n, data);
865     case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
866     case EBML_STOP:  return 1;
867     default:         return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
868     }
869     if (res == AVERROR_INVALIDDATA)
870         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
871     else if (res == AVERROR(EIO))
872         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
873     return res;
874 }
875
876 static void ebml_free(EbmlSyntax *syntax, void *data)
877 {
878     int i, j;
879     for (i=0; syntax[i].id; i++) {
880         void *data_off = (char *)data + syntax[i].data_offset;
881         switch (syntax[i].type) {
882         case EBML_STR:
883         case EBML_UTF8:  av_freep(data_off);                      break;
884         case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
885         case EBML_NEST:
886             if (syntax[i].list_elem_size) {
887                 EbmlList *list = data_off;
888                 char *ptr = list->elem;
889                 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
890                     ebml_free(syntax[i].def.n, ptr);
891                 av_free(list->elem);
892             } else
893                 ebml_free(syntax[i].def.n, data_off);
894         default:  break;
895         }
896     }
897 }
898
899
900 /*
901  * Autodetecting...
902  */
903 static int matroska_probe(AVProbeData *p)
904 {
905     uint64_t total = 0;
906     int len_mask = 0x80, size = 1, n = 1, i;
907
908     /* EBML header? */
909     if (AV_RB32(p->buf) != EBML_ID_HEADER)
910         return 0;
911
912     /* length of header */
913     total = p->buf[4];
914     while (size <= 8 && !(total & len_mask)) {
915         size++;
916         len_mask >>= 1;
917     }
918     if (size > 8)
919       return 0;
920     total &= (len_mask - 1);
921     while (n < size)
922         total = (total << 8) | p->buf[4 + n++];
923
924     /* Does the probe data contain the whole header? */
925     if (p->buf_size < 4 + size + total)
926       return 0;
927
928     /* The header should contain a known document type. For now,
929      * we don't parse the whole header but simply check for the
930      * availability of that array of characters inside the header.
931      * Not fully fool-proof, but good enough. */
932     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
933         int probelen = strlen(matroska_doctypes[i]);
934         for (n = 4+size; n <= 4+size+total-probelen; n++)
935             if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
936                 return AVPROBE_SCORE_MAX;
937     }
938
939     // probably valid EBML header but no recognized doctype
940     return AVPROBE_SCORE_MAX/2;
941 }
942
943 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
944                                                  int num)
945 {
946     MatroskaTrack *tracks = matroska->tracks.elem;
947     int i;
948
949     for (i=0; i < matroska->tracks.nb_elem; i++)
950         if (tracks[i].num == num)
951             return &tracks[i];
952
953     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
954     return NULL;
955 }
956
957 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
958                                   MatroskaTrack *track)
959 {
960     MatroskaTrackEncoding *encodings = track->encodings.elem;
961     uint8_t* data = *buf;
962     int isize = *buf_size;
963     uint8_t* pkt_data = NULL;
964     int pkt_size = isize;
965     int result = 0;
966     int olen;
967
968     if (pkt_size >= 10000000)
969         return -1;
970
971     switch (encodings[0].compression.algo) {
972     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
973         return encodings[0].compression.settings.size;
974     case MATROSKA_TRACK_ENCODING_COMP_LZO:
975         do {
976             olen = pkt_size *= 3;
977             pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
978             result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
979         } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
980         if (result)
981             goto failed;
982         pkt_size -= olen;
983         break;
984 #if CONFIG_ZLIB
985     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
986         z_stream zstream = {0};
987         if (inflateInit(&zstream) != Z_OK)
988             return -1;
989         zstream.next_in = data;
990         zstream.avail_in = isize;
991         do {
992             pkt_size *= 3;
993             pkt_data = av_realloc(pkt_data, pkt_size);
994             zstream.avail_out = pkt_size - zstream.total_out;
995             zstream.next_out = pkt_data + zstream.total_out;
996             result = inflate(&zstream, Z_NO_FLUSH);
997         } while (result==Z_OK && pkt_size<10000000);
998         pkt_size = zstream.total_out;
999         inflateEnd(&zstream);
1000         if (result != Z_STREAM_END)
1001             goto failed;
1002         break;
1003     }
1004 #endif
1005 #if CONFIG_BZLIB
1006     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1007         bz_stream bzstream = {0};
1008         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1009             return -1;
1010         bzstream.next_in = data;
1011         bzstream.avail_in = isize;
1012         do {
1013             pkt_size *= 3;
1014             pkt_data = av_realloc(pkt_data, pkt_size);
1015             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1016             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1017             result = BZ2_bzDecompress(&bzstream);
1018         } while (result==BZ_OK && pkt_size<10000000);
1019         pkt_size = bzstream.total_out_lo32;
1020         BZ2_bzDecompressEnd(&bzstream);
1021         if (result != BZ_STREAM_END)
1022             goto failed;
1023         break;
1024     }
1025 #endif
1026     default:
1027         return -1;
1028     }
1029
1030     *buf = pkt_data;
1031     *buf_size = pkt_size;
1032     return 0;
1033  failed:
1034     av_free(pkt_data);
1035     return -1;
1036 }
1037
1038 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1039                                     AVPacket *pkt, uint64_t display_duration)
1040 {
1041     char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1042     for (; *ptr!=',' && ptr<end-1; ptr++);
1043     if (*ptr == ',')
1044         ptr++;
1045     layer = ptr;
1046     for (; *ptr!=',' && ptr<end-1; ptr++);
1047     if (*ptr == ',') {
1048         int64_t end_pts = pkt->pts + display_duration;
1049         int sc = matroska->time_scale * pkt->pts / 10000000;
1050         int ec = matroska->time_scale * end_pts  / 10000000;
1051         int sh, sm, ss, eh, em, es, len;
1052         sh = sc/360000;  sc -= 360000*sh;
1053         sm = sc/  6000;  sc -=   6000*sm;
1054         ss = sc/   100;  sc -=    100*ss;
1055         eh = ec/360000;  ec -= 360000*eh;
1056         em = ec/  6000;  ec -=   6000*em;
1057         es = ec/   100;  ec -=    100*es;
1058         *ptr++ = '\0';
1059         len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1060         if (!(line = av_malloc(len)))
1061             return;
1062         snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1063                  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1064         av_free(pkt->data);
1065         pkt->data = line;
1066         pkt->size = strlen(line);
1067     }
1068 }
1069
1070 static void matroska_merge_packets(AVPacket *out, AVPacket *in)
1071 {
1072     out->data = av_realloc(out->data, out->size+in->size);
1073     memcpy(out->data+out->size, in->data, in->size);
1074     out->size += in->size;
1075     av_destruct_packet(in);
1076     av_free(in);
1077 }
1078
1079 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1080                                  AVDictionary **metadata, char *prefix)
1081 {
1082     MatroskaTag *tags = list->elem;
1083     char key[1024];
1084     int i;
1085
1086     for (i=0; i < list->nb_elem; i++) {
1087         const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1088
1089         if (!tags[i].name) {
1090             av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1091             continue;
1092         }
1093         if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1094         else         av_strlcpy(key, tags[i].name, sizeof(key));
1095         if (tags[i].def || !lang) {
1096         av_dict_set(metadata, key, tags[i].string, 0);
1097         if (tags[i].sub.nb_elem)
1098             matroska_convert_tag(s, &tags[i].sub, metadata, key);
1099         }
1100         if (lang) {
1101             av_strlcat(key, "-", sizeof(key));
1102             av_strlcat(key, lang, sizeof(key));
1103             av_dict_set(metadata, key, tags[i].string, 0);
1104             if (tags[i].sub.nb_elem)
1105                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1106         }
1107     }
1108     ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1109 }
1110
1111 static void matroska_convert_tags(AVFormatContext *s)
1112 {
1113     MatroskaDemuxContext *matroska = s->priv_data;
1114     MatroskaTags *tags = matroska->tags.elem;
1115     int i, j;
1116
1117     for (i=0; i < matroska->tags.nb_elem; i++) {
1118         if (tags[i].target.attachuid) {
1119             MatroskaAttachement *attachment = matroska->attachments.elem;
1120             for (j=0; j<matroska->attachments.nb_elem; j++)
1121                 if (attachment[j].uid == tags[i].target.attachuid
1122                     && attachment[j].stream)
1123                     matroska_convert_tag(s, &tags[i].tag,
1124                                          &attachment[j].stream->metadata, NULL);
1125         } else if (tags[i].target.chapteruid) {
1126             MatroskaChapter *chapter = matroska->chapters.elem;
1127             for (j=0; j<matroska->chapters.nb_elem; j++)
1128                 if (chapter[j].uid == tags[i].target.chapteruid
1129                     && chapter[j].chapter)
1130                     matroska_convert_tag(s, &tags[i].tag,
1131                                          &chapter[j].chapter->metadata, NULL);
1132         } else if (tags[i].target.trackuid) {
1133             MatroskaTrack *track = matroska->tracks.elem;
1134             for (j=0; j<matroska->tracks.nb_elem; j++)
1135                 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1136                     matroska_convert_tag(s, &tags[i].tag,
1137                                          &track[j].stream->metadata, NULL);
1138         } else {
1139             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1140                                  tags[i].target.type);
1141         }
1142     }
1143 }
1144
1145 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
1146 {
1147     EbmlList *seekhead_list = &matroska->seekhead;
1148     MatroskaSeekhead *seekhead = seekhead_list->elem;
1149     uint32_t level_up = matroska->level_up;
1150     int64_t before_pos = avio_tell(matroska->ctx->pb);
1151     uint32_t saved_id = matroska->current_id;
1152     MatroskaLevel level;
1153     int64_t offset;
1154     int ret = 0;
1155
1156     if (idx >= seekhead_list->nb_elem
1157             || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1158             || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1159         return 0;
1160
1161     /* seek */
1162     offset = seekhead[idx].pos + matroska->segment_start;
1163     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1164         /* We don't want to lose our seekhead level, so we add
1165          * a dummy. This is a crude hack. */
1166         if (matroska->num_levels == EBML_MAX_DEPTH) {
1167             av_log(matroska->ctx, AV_LOG_INFO,
1168                    "Max EBML element depth (%d) reached, "
1169                    "cannot parse further.\n", EBML_MAX_DEPTH);
1170             ret = AVERROR_INVALIDDATA;
1171         } else {
1172             level.start = 0;
1173             level.length = (uint64_t)-1;
1174             matroska->levels[matroska->num_levels] = level;
1175             matroska->num_levels++;
1176             matroska->current_id = 0;
1177
1178             ebml_parse(matroska, matroska_segment, matroska);
1179
1180             /* remove dummy level */
1181             while (matroska->num_levels) {
1182                 uint64_t length = matroska->levels[--matroska->num_levels].length;
1183                 if (length == (uint64_t)-1)
1184                     break;
1185             }
1186         }
1187     }
1188     /* seek back */
1189     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1190     matroska->level_up = level_up;
1191     matroska->current_id = saved_id;
1192
1193     return ret;
1194 }
1195
1196 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1197 {
1198     EbmlList *seekhead_list = &matroska->seekhead;
1199     MatroskaSeekhead *seekhead = seekhead_list->elem;
1200     int64_t before_pos = avio_tell(matroska->ctx->pb);
1201     int i;
1202
1203     // we should not do any seeking in the streaming case
1204     if (!matroska->ctx->pb->seekable ||
1205         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1206         return;
1207
1208     for (i = 0; i < seekhead_list->nb_elem; i++) {
1209         if (seekhead[i].pos <= before_pos)
1210             continue;
1211
1212         // defer cues parsing until we actually need cue data.
1213         if (seekhead[i].id == MATROSKA_ID_CUES) {
1214             matroska->cues_parsing_deferred = 1;
1215             continue;
1216         }
1217
1218         if (matroska_parse_seekhead_entry(matroska, i) < 0)
1219             break;
1220     }
1221 }
1222
1223 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1224     EbmlList *seekhead_list = &matroska->seekhead;
1225     MatroskaSeekhead *seekhead = seekhead_list->elem;
1226     EbmlList *index_list;
1227     MatroskaIndex *index;
1228     int index_scale = 1;
1229     int i, j;
1230
1231     for (i = 0; i < seekhead_list->nb_elem; i++)
1232         if (seekhead[i].id == MATROSKA_ID_CUES)
1233             break;
1234     assert(i <= seekhead_list->nb_elem);
1235
1236     matroska_parse_seekhead_entry(matroska, i);
1237
1238     index_list = &matroska->index;
1239     index = index_list->elem;
1240     if (index_list->nb_elem
1241         && index[0].time > 1E14/matroska->time_scale) {
1242         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1243         index_scale = matroska->time_scale;
1244     }
1245     for (i = 0; i < index_list->nb_elem; i++) {
1246         EbmlList *pos_list = &index[i].pos;
1247         MatroskaIndexPos *pos = pos_list->elem;
1248         for (j = 0; j < pos_list->nb_elem; j++) {
1249             MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1250             if (track && track->stream)
1251                 av_add_index_entry(track->stream,
1252                                    pos[j].pos + matroska->segment_start,
1253                                    index[i].time/index_scale, 0, 0,
1254                                    AVINDEX_KEYFRAME);
1255         }
1256     }
1257 }
1258
1259 static int matroska_aac_profile(char *codec_id)
1260 {
1261     static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1262     int profile;
1263
1264     for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1265         if (strstr(codec_id, aac_profiles[profile]))
1266             break;
1267     return profile + 1;
1268 }
1269
1270 static int matroska_aac_sri(int samplerate)
1271 {
1272     int sri;
1273
1274     for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
1275         if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1276             break;
1277     return sri;
1278 }
1279
1280 static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1281 {
1282     MatroskaDemuxContext *matroska = s->priv_data;
1283     EbmlList *attachements_list = &matroska->attachments;
1284     MatroskaAttachement *attachements;
1285     EbmlList *chapters_list = &matroska->chapters;
1286     MatroskaChapter *chapters;
1287     MatroskaTrack *tracks;
1288     uint64_t max_start = 0;
1289     Ebml ebml = { 0 };
1290     AVStream *st;
1291     int i, j, k, res;
1292
1293     matroska->ctx = s;
1294
1295     /* First read the EBML header. */
1296     if (ebml_parse(matroska, ebml_syntax, &ebml)
1297         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1298         || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3) {
1299         av_log(matroska->ctx, AV_LOG_ERROR,
1300                "EBML header using unsupported features\n"
1301                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1302                ebml.version, ebml.doctype, ebml.doctype_version);
1303         ebml_free(ebml_syntax, &ebml);
1304         return AVERROR_PATCHWELCOME;
1305     } else if (ebml.doctype_version == 3) {
1306         av_log(matroska->ctx, AV_LOG_WARNING,
1307                "EBML header using unsupported features\n"
1308                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1309                ebml.version, ebml.doctype, ebml.doctype_version);
1310     }
1311     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1312         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1313             break;
1314     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1315         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1316     }
1317     ebml_free(ebml_syntax, &ebml);
1318
1319     /* The next thing is a segment. */
1320     if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1321         return res;
1322     matroska_execute_seekhead(matroska);
1323
1324     if (!matroska->time_scale)
1325         matroska->time_scale = 1000000;
1326     if (matroska->duration)
1327         matroska->ctx->duration = matroska->duration * matroska->time_scale
1328                                   * 1000 / AV_TIME_BASE;
1329     av_dict_set(&s->metadata, "title", matroska->title, 0);
1330
1331     tracks = matroska->tracks.elem;
1332     for (i=0; i < matroska->tracks.nb_elem; i++) {
1333         MatroskaTrack *track = &tracks[i];
1334         enum CodecID codec_id = CODEC_ID_NONE;
1335         EbmlList *encodings_list = &tracks->encodings;
1336         MatroskaTrackEncoding *encodings = encodings_list->elem;
1337         uint8_t *extradata = NULL;
1338         int extradata_size = 0;
1339         int extradata_offset = 0;
1340         uint32_t fourcc = 0;
1341         AVIOContext b;
1342
1343         /* Apply some sanity checks. */
1344         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1345             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1346             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1347             av_log(matroska->ctx, AV_LOG_INFO,
1348                    "Unknown or unsupported track type %"PRIu64"\n",
1349                    track->type);
1350             continue;
1351         }
1352         if (track->codec_id == NULL)
1353             continue;
1354
1355         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1356             if (!track->default_duration)
1357                 track->default_duration = 1000000000/track->video.frame_rate;
1358             if (!track->video.display_width)
1359                 track->video.display_width = track->video.pixel_width;
1360             if (!track->video.display_height)
1361                 track->video.display_height = track->video.pixel_height;
1362             if (track->video.color_space.size == 4)
1363                 fourcc = AV_RL32(track->video.color_space.data);
1364         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1365             if (!track->audio.out_samplerate)
1366                 track->audio.out_samplerate = track->audio.samplerate;
1367         }
1368         if (encodings_list->nb_elem > 1) {
1369             av_log(matroska->ctx, AV_LOG_ERROR,
1370                    "Multiple combined encodings no supported");
1371         } else if (encodings_list->nb_elem == 1) {
1372             if (encodings[0].type ||
1373                 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1374 #if CONFIG_ZLIB
1375                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1376 #endif
1377 #if CONFIG_BZLIB
1378                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1379 #endif
1380                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1381                 encodings[0].scope = 0;
1382                 av_log(matroska->ctx, AV_LOG_ERROR,
1383                        "Unsupported encoding type");
1384             } else if (track->codec_priv.size && encodings[0].scope&2) {
1385                 uint8_t *codec_priv = track->codec_priv.data;
1386                 int offset = matroska_decode_buffer(&track->codec_priv.data,
1387                                                     &track->codec_priv.size,
1388                                                     track);
1389                 if (offset < 0) {
1390                     track->codec_priv.data = NULL;
1391                     track->codec_priv.size = 0;
1392                     av_log(matroska->ctx, AV_LOG_ERROR,
1393                            "Failed to decode codec private data\n");
1394                 } else if (offset > 0) {
1395                     track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1396                     memcpy(track->codec_priv.data,
1397                            encodings[0].compression.settings.data, offset);
1398                     memcpy(track->codec_priv.data+offset, codec_priv,
1399                            track->codec_priv.size);
1400                     track->codec_priv.size += offset;
1401                 }
1402                 if (codec_priv != track->codec_priv.data)
1403                     av_free(codec_priv);
1404             }
1405         }
1406
1407         for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1408             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1409                         strlen(ff_mkv_codec_tags[j].str))){
1410                 codec_id= ff_mkv_codec_tags[j].id;
1411                 break;
1412             }
1413         }
1414
1415         st = track->stream = av_new_stream(s, 0);
1416         if (st == NULL)
1417             return AVERROR(ENOMEM);
1418
1419         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1420             && track->codec_priv.size >= 40
1421             && track->codec_priv.data != NULL) {
1422             track->ms_compat = 1;
1423             fourcc = AV_RL32(track->codec_priv.data + 16);
1424             codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
1425             extradata_offset = 40;
1426         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1427                    && track->codec_priv.size >= 14
1428                    && track->codec_priv.data != NULL) {
1429             int ret;
1430             ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1431                           AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
1432             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1433             if (ret < 0)
1434                 return ret;
1435             codec_id = st->codec->codec_id;
1436             extradata_offset = FFMIN(track->codec_priv.size, 18);
1437         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1438                    && (track->codec_priv.size >= 86)
1439                    && (track->codec_priv.data != NULL)) {
1440             fourcc = AV_RL32(track->codec_priv.data);
1441             codec_id = ff_codec_get_id(codec_movvideo_tags, fourcc);
1442         } else if (codec_id == CODEC_ID_PCM_S16BE) {
1443             switch (track->audio.bitdepth) {
1444             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1445             case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
1446             case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
1447             }
1448         } else if (codec_id == CODEC_ID_PCM_S16LE) {
1449             switch (track->audio.bitdepth) {
1450             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1451             case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
1452             case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
1453             }
1454         } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1455             codec_id = CODEC_ID_PCM_F64LE;
1456         } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1457             int profile = matroska_aac_profile(track->codec_id);
1458             int sri = matroska_aac_sri(track->audio.samplerate);
1459             extradata = av_malloc(5);
1460             if (extradata == NULL)
1461                 return AVERROR(ENOMEM);
1462             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1463             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1464             if (strstr(track->codec_id, "SBR")) {
1465                 sri = matroska_aac_sri(track->audio.out_samplerate);
1466                 extradata[2] = 0x56;
1467                 extradata[3] = 0xE5;
1468                 extradata[4] = 0x80 | (sri<<3);
1469                 extradata_size = 5;
1470             } else
1471                 extradata_size = 2;
1472         } else if (codec_id == CODEC_ID_TTA) {
1473             extradata_size = 30;
1474             extradata = av_mallocz(extradata_size);
1475             if (extradata == NULL)
1476                 return AVERROR(ENOMEM);
1477             ffio_init_context(&b, extradata, extradata_size, 1,
1478                           NULL, NULL, NULL, NULL);
1479             avio_write(&b, "TTA1", 4);
1480             avio_wl16(&b, 1);
1481             avio_wl16(&b, track->audio.channels);
1482             avio_wl16(&b, track->audio.bitdepth);
1483             avio_wl32(&b, track->audio.out_samplerate);
1484             avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1485         } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1486                    codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1487             extradata_offset = 26;
1488         } else if (codec_id == CODEC_ID_RA_144) {
1489             track->audio.out_samplerate = 8000;
1490             track->audio.channels = 1;
1491         } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1492                    codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1493             int flavor;
1494             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1495                           0, NULL, NULL, NULL, NULL);
1496             avio_skip(&b, 22);
1497             flavor                       = avio_rb16(&b);
1498             track->audio.coded_framesize = avio_rb32(&b);
1499             avio_skip(&b, 12);
1500             track->audio.sub_packet_h    = avio_rb16(&b);
1501             track->audio.frame_size      = avio_rb16(&b);
1502             track->audio.sub_packet_size = avio_rb16(&b);
1503             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1504             if (codec_id == CODEC_ID_RA_288) {
1505                 st->codec->block_align = track->audio.coded_framesize;
1506                 track->codec_priv.size = 0;
1507             } else {
1508                 if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1509                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1510                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1511                     st->codec->bit_rate = sipr_bit_rate[flavor];
1512                 }
1513                 st->codec->block_align = track->audio.sub_packet_size;
1514                 extradata_offset = 78;
1515             }
1516         }
1517         track->codec_priv.size -= extradata_offset;
1518
1519         if (codec_id == CODEC_ID_NONE)
1520             av_log(matroska->ctx, AV_LOG_INFO,
1521                    "Unknown/unsupported CodecID %s.\n", track->codec_id);
1522
1523         if (track->time_scale < 0.01)
1524             track->time_scale = 1.0;
1525         av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1526
1527         st->codec->codec_id = codec_id;
1528         st->start_time = 0;
1529         if (strcmp(track->language, "und"))
1530             av_dict_set(&st->metadata, "language", track->language, 0);
1531         av_dict_set(&st->metadata, "title", track->name, 0);
1532
1533         if (track->flag_default)
1534             st->disposition |= AV_DISPOSITION_DEFAULT;
1535         if (track->flag_forced)
1536             st->disposition |= AV_DISPOSITION_FORCED;
1537
1538         if (track->default_duration)
1539             av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1540                       track->default_duration, 1000000000, 30000);
1541
1542         if (!st->codec->extradata) {
1543             if(extradata){
1544                 st->codec->extradata = extradata;
1545                 st->codec->extradata_size = extradata_size;
1546             } else if(track->codec_priv.data && track->codec_priv.size > 0){
1547                 st->codec->extradata = av_mallocz(track->codec_priv.size +
1548                                                   FF_INPUT_BUFFER_PADDING_SIZE);
1549                 if(st->codec->extradata == NULL)
1550                     return AVERROR(ENOMEM);
1551                 st->codec->extradata_size = track->codec_priv.size;
1552                 memcpy(st->codec->extradata,
1553                        track->codec_priv.data + extradata_offset,
1554                        track->codec_priv.size);
1555             }
1556         }
1557
1558         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1559             MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
1560
1561             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1562             st->codec->codec_tag  = fourcc;
1563             st->codec->width  = track->video.pixel_width;
1564             st->codec->height = track->video.pixel_height;
1565             av_reduce(&st->sample_aspect_ratio.num,
1566                       &st->sample_aspect_ratio.den,
1567                       st->codec->height * track->video.display_width,
1568                       st->codec-> width * track->video.display_height,
1569                       255);
1570             if (st->codec->codec_id != CODEC_ID_H264)
1571             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1572             if (track->default_duration)
1573                 st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
1574
1575             /* export stereo mode flag as metadata tag */
1576             if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
1577                 av_dict_set(&st->metadata, "stereo_mode", matroska_video_stereo_mode[track->video.stereo_mode], 0);
1578
1579             /* if we have virtual track, mark the real tracks */
1580             for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
1581                 char buf[32];
1582                 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
1583                     continue;
1584                 snprintf(buf, sizeof(buf), "%s_%d",
1585                          matroska_video_stereo_plane[planes[j].type], i);
1586                 for (k=0; k < matroska->tracks.nb_elem; k++)
1587                     if (planes[j].uid == tracks[k].uid) {
1588                         av_dict_set(&s->streams[k]->metadata,
1589                                     "stereo_mode", buf, 0);
1590                         break;
1591                     }
1592             }
1593         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1594             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1595             st->codec->sample_rate = track->audio.out_samplerate;
1596             st->codec->channels = track->audio.channels;
1597             if (st->codec->codec_id != CODEC_ID_AAC)
1598             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1599         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1600             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1601         }
1602     }
1603
1604     attachements = attachements_list->elem;
1605     for (j=0; j<attachements_list->nb_elem; j++) {
1606         if (!(attachements[j].filename && attachements[j].mime &&
1607               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1608             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1609         } else {
1610             AVStream *st = av_new_stream(s, 0);
1611             if (st == NULL)
1612                 break;
1613             av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1614             st->codec->codec_id = CODEC_ID_NONE;
1615             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1616             st->codec->extradata  = av_malloc(attachements[j].bin.size);
1617             if(st->codec->extradata == NULL)
1618                 break;
1619             st->codec->extradata_size = attachements[j].bin.size;
1620             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1621
1622             for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1623                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1624                              strlen(ff_mkv_mime_tags[i].str))) {
1625                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1626                     break;
1627                 }
1628             }
1629             attachements[j].stream = st;
1630         }
1631     }
1632
1633     chapters = chapters_list->elem;
1634     for (i=0; i<chapters_list->nb_elem; i++)
1635         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1636             && (max_start==0 || chapters[i].start > max_start)) {
1637             chapters[i].chapter =
1638             ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1639                            chapters[i].start, chapters[i].end,
1640                            chapters[i].title);
1641             av_dict_set(&chapters[i].chapter->metadata,
1642                              "title", chapters[i].title, 0);
1643             max_start = chapters[i].start;
1644         }
1645
1646     matroska_convert_tags(s);
1647
1648     return 0;
1649 }
1650
1651 /*
1652  * Put one packet in an application-supplied AVPacket struct.
1653  * Returns 0 on success or -1 on failure.
1654  */
1655 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1656                                    AVPacket *pkt)
1657 {
1658     if (matroska->num_packets > 0) {
1659         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1660         av_free(matroska->packets[0]);
1661         if (matroska->num_packets > 1) {
1662             memmove(&matroska->packets[0], &matroska->packets[1],
1663                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1664             matroska->packets =
1665                 av_realloc(matroska->packets, (matroska->num_packets - 1) *
1666                            sizeof(AVPacket *));
1667         } else {
1668             av_freep(&matroska->packets);
1669         }
1670         matroska->num_packets--;
1671         return 0;
1672     }
1673
1674     return -1;
1675 }
1676
1677 /*
1678  * Free all packets in our internal queue.
1679  */
1680 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1681 {
1682     if (matroska->packets) {
1683         int n;
1684         for (n = 0; n < matroska->num_packets; n++) {
1685             av_free_packet(matroska->packets[n]);
1686             av_free(matroska->packets[n]);
1687         }
1688         av_freep(&matroska->packets);
1689         matroska->num_packets = 0;
1690     }
1691 }
1692
1693 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1694                                 int size, int64_t pos, uint64_t cluster_time,
1695                                 uint64_t duration, int is_keyframe,
1696                                 int64_t cluster_pos)
1697 {
1698     uint64_t timecode = AV_NOPTS_VALUE;
1699     MatroskaTrack *track;
1700     int res = 0;
1701     AVStream *st;
1702     AVPacket *pkt;
1703     int16_t block_time;
1704     uint32_t *lace_size = NULL;
1705     int n, flags, laces = 0;
1706     uint64_t num;
1707
1708     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1709         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1710         return res;
1711     }
1712     data += n;
1713     size -= n;
1714
1715     track = matroska_find_track_by_num(matroska, num);
1716     if (size <= 3 || !track || !track->stream) {
1717         av_log(matroska->ctx, AV_LOG_INFO,
1718                "Invalid stream %"PRIu64" or size %u\n", num, size);
1719         return AVERROR_INVALIDDATA;
1720     }
1721     st = track->stream;
1722     if (st->discard >= AVDISCARD_ALL)
1723         return res;
1724     if (!duration)
1725         duration = track->default_duration / matroska->time_scale;
1726
1727     block_time = AV_RB16(data);
1728     data += 2;
1729     flags = *data++;
1730     size -= 3;
1731     if (is_keyframe == -1)
1732         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1733
1734     if (cluster_time != (uint64_t)-1
1735         && (block_time >= 0 || cluster_time >= -block_time)) {
1736         timecode = cluster_time + block_time;
1737         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1738             && timecode < track->end_timecode)
1739             is_keyframe = 0;  /* overlapping subtitles are not key frame */
1740         if (is_keyframe)
1741             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1742         track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1743     }
1744
1745     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1746         if (!is_keyframe || timecode < matroska->skip_to_timecode)
1747             return res;
1748         matroska->skip_to_keyframe = 0;
1749     }
1750
1751     switch ((flags & 0x06) >> 1) {
1752         case 0x0: /* no lacing */
1753             laces = 1;
1754             lace_size = av_mallocz(sizeof(int));
1755             lace_size[0] = size;
1756             break;
1757
1758         case 0x1: /* Xiph lacing */
1759         case 0x2: /* fixed-size lacing */
1760         case 0x3: /* EBML lacing */
1761             assert(size>0); // size <=3 is checked before size-=3 above
1762             laces = (*data) + 1;
1763             data += 1;
1764             size -= 1;
1765             lace_size = av_mallocz(laces * sizeof(int));
1766
1767             switch ((flags & 0x06) >> 1) {
1768                 case 0x1: /* Xiph lacing */ {
1769                     uint8_t temp;
1770                     uint32_t total = 0;
1771                     for (n = 0; res == 0 && n < laces - 1; n++) {
1772                         while (1) {
1773                             if (size == 0) {
1774                                 res = -1;
1775                                 break;
1776                             }
1777                             temp = *data;
1778                             lace_size[n] += temp;
1779                             data += 1;
1780                             size -= 1;
1781                             if (temp != 0xff)
1782                                 break;
1783                         }
1784                         total += lace_size[n];
1785                     }
1786                     lace_size[n] = size - total;
1787                     break;
1788                 }
1789
1790                 case 0x2: /* fixed-size lacing */
1791                     for (n = 0; n < laces; n++)
1792                         lace_size[n] = size / laces;
1793                     break;
1794
1795                 case 0x3: /* EBML lacing */ {
1796                     uint32_t total;
1797                     n = matroska_ebmlnum_uint(matroska, data, size, &num);
1798                     if (n < 0) {
1799                         av_log(matroska->ctx, AV_LOG_INFO,
1800                                "EBML block data error\n");
1801                         break;
1802                     }
1803                     data += n;
1804                     size -= n;
1805                     total = lace_size[0] = num;
1806                     for (n = 1; res == 0 && n < laces - 1; n++) {
1807                         int64_t snum;
1808                         int r;
1809                         r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1810                         if (r < 0) {
1811                             av_log(matroska->ctx, AV_LOG_INFO,
1812                                    "EBML block data error\n");
1813                             break;
1814                         }
1815                         data += r;
1816                         size -= r;
1817                         lace_size[n] = lace_size[n - 1] + snum;
1818                         total += lace_size[n];
1819                     }
1820                     lace_size[n] = size - total;
1821                     break;
1822                 }
1823             }
1824             break;
1825     }
1826
1827     if (res == 0) {
1828         for (n = 0; n < laces; n++) {
1829             if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1830                  st->codec->codec_id == CODEC_ID_COOK ||
1831                  st->codec->codec_id == CODEC_ID_SIPR ||
1832                  st->codec->codec_id == CODEC_ID_ATRAC3) &&
1833                  st->codec->block_align && track->audio.sub_packet_size) {
1834                 int a = st->codec->block_align;
1835                 int sps = track->audio.sub_packet_size;
1836                 int cfs = track->audio.coded_framesize;
1837                 int h = track->audio.sub_packet_h;
1838                 int y = track->audio.sub_packet_cnt;
1839                 int w = track->audio.frame_size;
1840                 int x;
1841
1842                 if (!track->audio.pkt_cnt) {
1843                     if (track->audio.sub_packet_cnt == 0)
1844                         track->audio.buf_timecode = timecode;
1845                     if (st->codec->codec_id == CODEC_ID_RA_288)
1846                         for (x=0; x<h/2; x++)
1847                             memcpy(track->audio.buf+x*2*w+y*cfs,
1848                                    data+x*cfs, cfs);
1849                     else if (st->codec->codec_id == CODEC_ID_SIPR)
1850                         memcpy(track->audio.buf + y*w, data, w);
1851                     else
1852                         for (x=0; x<w/sps; x++)
1853                             memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1854
1855                     if (++track->audio.sub_packet_cnt >= h) {
1856                         if (st->codec->codec_id == CODEC_ID_SIPR)
1857                             ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1858                         track->audio.sub_packet_cnt = 0;
1859                         track->audio.pkt_cnt = h*w / a;
1860                     }
1861                 }
1862                 while (track->audio.pkt_cnt) {
1863                     pkt = av_mallocz(sizeof(AVPacket));
1864                     av_new_packet(pkt, a);
1865                     memcpy(pkt->data, track->audio.buf
1866                            + a * (h*w / a - track->audio.pkt_cnt--), a);
1867                     pkt->pts = track->audio.buf_timecode;
1868                     track->audio.buf_timecode = AV_NOPTS_VALUE;
1869                     pkt->pos = pos;
1870                     pkt->stream_index = st->index;
1871                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1872                 }
1873             } else {
1874                 MatroskaTrackEncoding *encodings = track->encodings.elem;
1875                 int offset = 0, pkt_size = lace_size[n];
1876                 uint8_t *pkt_data = data;
1877
1878                 if (pkt_size > size) {
1879                     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1880                     break;
1881                 }
1882
1883                 if (encodings && encodings->scope & 1) {
1884                     offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1885                     if (offset < 0)
1886                         continue;
1887                 }
1888
1889                 pkt = av_mallocz(sizeof(AVPacket));
1890                 /* XXX: prevent data copy... */
1891                 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1892                     av_free(pkt);
1893                     res = AVERROR(ENOMEM);
1894                     break;
1895                 }
1896                 if (offset)
1897                     memcpy (pkt->data, encodings->compression.settings.data, offset);
1898                 memcpy (pkt->data+offset, pkt_data, pkt_size);
1899
1900                 if (pkt_data != data)
1901                     av_free(pkt_data);
1902
1903                 if (n == 0)
1904                     pkt->flags = is_keyframe;
1905                 pkt->stream_index = st->index;
1906
1907                 if (track->ms_compat)
1908                     pkt->dts = timecode;
1909                 else
1910                     pkt->pts = timecode;
1911                 pkt->pos = pos;
1912                 if (st->codec->codec_id == CODEC_ID_TEXT)
1913                     pkt->convergence_duration = duration;
1914                 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1915                     pkt->duration = duration;
1916
1917                 if (st->codec->codec_id == CODEC_ID_SSA)
1918                     matroska_fix_ass_packet(matroska, pkt, duration);
1919
1920                 if (matroska->prev_pkt &&
1921                     timecode != AV_NOPTS_VALUE &&
1922                     matroska->prev_pkt->pts == timecode &&
1923                     matroska->prev_pkt->stream_index == st->index &&
1924                     st->codec->codec_id == CODEC_ID_SSA)
1925                     matroska_merge_packets(matroska->prev_pkt, pkt);
1926                 else {
1927                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1928                     matroska->prev_pkt = pkt;
1929                 }
1930             }
1931
1932             if (timecode != AV_NOPTS_VALUE)
1933                 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1934             data += lace_size[n];
1935             size -= lace_size[n];
1936         }
1937     }
1938
1939     av_free(lace_size);
1940     return res;
1941 }
1942
1943 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1944 {
1945     MatroskaCluster cluster = { 0 };
1946     EbmlList *blocks_list;
1947     MatroskaBlock *blocks;
1948     int i, res;
1949     int64_t pos = avio_tell(matroska->ctx->pb);
1950     matroska->prev_pkt = NULL;
1951     if (matroska->current_id)
1952         pos -= 4;  /* sizeof the ID which was already read */
1953     res = ebml_parse(matroska, matroska_clusters, &cluster);
1954     blocks_list = &cluster.blocks;
1955     blocks = blocks_list->elem;
1956     for (i=0; i<blocks_list->nb_elem && !res; i++)
1957         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
1958             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
1959             res=matroska_parse_block(matroska,
1960                                      blocks[i].bin.data, blocks[i].bin.size,
1961                                      blocks[i].bin.pos,  cluster.timecode,
1962                                      blocks[i].duration, is_keyframe,
1963                                      pos);
1964         }
1965     ebml_free(matroska_cluster, &cluster);
1966     if (res < 0)  matroska->done = 1;
1967     return res;
1968 }
1969
1970 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1971 {
1972     MatroskaDemuxContext *matroska = s->priv_data;
1973     int ret = 0;
1974
1975     while (!ret && matroska_deliver_packet(matroska, pkt)) {
1976         if (matroska->done)
1977             return AVERROR_EOF;
1978         ret = matroska_parse_cluster(matroska);
1979     }
1980
1981     return ret;
1982 }
1983
1984 static int matroska_read_seek(AVFormatContext *s, int stream_index,
1985                               int64_t timestamp, int flags)
1986 {
1987     MatroskaDemuxContext *matroska = s->priv_data;
1988     MatroskaTrack *tracks = matroska->tracks.elem;
1989     AVStream *st = s->streams[stream_index];
1990     int i, index, index_sub, index_min;
1991
1992     /* Parse the CUES now since we need the index data to seek. */
1993     if (matroska->cues_parsing_deferred) {
1994         matroska_parse_cues(matroska);
1995         matroska->cues_parsing_deferred = 0;
1996     }
1997
1998     if (!st->nb_index_entries)
1999         return 0;
2000     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2001
2002     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2003         avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2004         matroska->current_id = 0;
2005         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2006             matroska_clear_queue(matroska);
2007             if (matroska_parse_cluster(matroska) < 0)
2008                 break;
2009         }
2010     }
2011
2012     matroska_clear_queue(matroska);
2013     if (index < 0)
2014         return 0;
2015
2016     index_min = index;
2017     for (i=0; i < matroska->tracks.nb_elem; i++) {
2018         tracks[i].audio.pkt_cnt = 0;
2019         tracks[i].audio.sub_packet_cnt = 0;
2020         tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2021         tracks[i].end_timecode = 0;
2022         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2023             && !tracks[i].stream->discard != AVDISCARD_ALL) {
2024             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2025             if (index_sub >= 0
2026                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2027                 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2028                 index_min = index_sub;
2029         }
2030     }
2031
2032     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2033     matroska->current_id = 0;
2034     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2035     matroska->skip_to_timecode = st->index_entries[index].timestamp;
2036     matroska->done = 0;
2037     av_update_cur_dts(s, st, st->index_entries[index].timestamp);
2038     return 0;
2039 }
2040
2041 static int matroska_read_close(AVFormatContext *s)
2042 {
2043     MatroskaDemuxContext *matroska = s->priv_data;
2044     MatroskaTrack *tracks = matroska->tracks.elem;
2045     int n;
2046
2047     matroska_clear_queue(matroska);
2048
2049     for (n=0; n < matroska->tracks.nb_elem; n++)
2050         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2051             av_free(tracks[n].audio.buf);
2052     ebml_free(matroska_segment, matroska);
2053
2054     return 0;
2055 }
2056
2057 AVInputFormat ff_matroska_demuxer = {
2058     .name           = "matroska,webm",
2059     .long_name      = NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
2060     .priv_data_size = sizeof(MatroskaDemuxContext),
2061     .read_probe     = matroska_probe,
2062     .read_header    = matroska_read_header,
2063     .read_packet    = matroska_read_packet,
2064     .read_close     = matroska_read_close,
2065     .read_seek      = matroska_read_seek,
2066 };