matroskadec: introduce resync function.
[ffmpeg.git] / libavformat / matroskadec.c
1 /*
2  * Matroska file demuxer
3  * Copyright (c) 2003-2008 The FFmpeg Project
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Matroska file demuxer
25  * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
26  * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
27  * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28  * @see specs available on the Matroska project page: http://www.matroska.org/
29  */
30
31 #include <stdio.h>
32 #include "avformat.h"
33 #include "internal.h"
34 #include "avio_internal.h"
35 /* For ff_codec_get_id(). */
36 #include "riff.h"
37 #include "isom.h"
38 #include "rm.h"
39 #include "matroska.h"
40 #include "libavcodec/mpeg4audio.h"
41 #include "libavutil/intfloat.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 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
548 {
549     AVIOContext *pb = matroska->ctx->pb;
550     uint32_t id;
551     matroska->current_id = 0;
552     matroska->num_levels = 0;
553
554     // seek to next position to resync from
555     if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0 || avio_tell(pb) <= last_pos)
556         goto eof;
557
558     id = avio_rb32(pb);
559
560     // try to find a toplevel element
561     while (!url_feof(pb)) {
562         if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
563             id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
564             id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
565             id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS)
566         {
567             matroska->current_id = id;
568             return 0;
569         }
570         id = (id << 8) | avio_r8(pb);
571     }
572 eof:
573     matroska->done = 1;
574     return AVERROR_EOF;
575 }
576
577 /*
578  * Return: Whether we reached the end of a level in the hierarchy or not.
579  */
580 static int ebml_level_end(MatroskaDemuxContext *matroska)
581 {
582     AVIOContext *pb = matroska->ctx->pb;
583     int64_t pos = avio_tell(pb);
584
585     if (matroska->num_levels > 0) {
586         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
587         if (pos - level->start >= level->length || matroska->current_id) {
588             matroska->num_levels--;
589             return 1;
590         }
591     }
592     return 0;
593 }
594
595 /*
596  * Read: an "EBML number", which is defined as a variable-length
597  * array of bytes. The first byte indicates the length by giving a
598  * number of 0-bits followed by a one. The position of the first
599  * "one" bit inside the first byte indicates the length of this
600  * number.
601  * Returns: number of bytes read, < 0 on error
602  */
603 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
604                          int max_size, uint64_t *number)
605 {
606     int read = 1, n = 1;
607     uint64_t total = 0;
608
609     /* The first byte tells us the length in bytes - avio_r8() can normally
610      * return 0, but since that's not a valid first ebmlID byte, we can
611      * use it safely here to catch EOS. */
612     if (!(total = avio_r8(pb))) {
613         /* we might encounter EOS here */
614         if (!url_feof(pb)) {
615             int64_t pos = avio_tell(pb);
616             av_log(matroska->ctx, AV_LOG_ERROR,
617                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
618                    pos, pos);
619         }
620         return AVERROR(EIO); /* EOS or actual I/O error */
621     }
622
623     /* get the length of the EBML number */
624     read = 8 - ff_log2_tab[total];
625     if (read > max_size) {
626         int64_t pos = avio_tell(pb) - 1;
627         av_log(matroska->ctx, AV_LOG_ERROR,
628                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
629                (uint8_t) total, pos, pos);
630         return AVERROR_INVALIDDATA;
631     }
632
633     /* read out length */
634     total ^= 1 << ff_log2_tab[total];
635     while (n++ < read)
636         total = (total << 8) | avio_r8(pb);
637
638     *number = total;
639
640     return read;
641 }
642
643 /**
644  * Read a EBML length value.
645  * This needs special handling for the "unknown length" case which has multiple
646  * encodings.
647  */
648 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
649                             uint64_t *number)
650 {
651     int res = ebml_read_num(matroska, pb, 8, number);
652     if (res > 0 && *number + 1 == 1ULL << (7 * res))
653         *number = 0xffffffffffffffULL;
654     return res;
655 }
656
657 /*
658  * Read the next element as an unsigned int.
659  * 0 is success, < 0 is failure.
660  */
661 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
662 {
663     int n = 0;
664
665     if (size > 8)
666         return AVERROR_INVALIDDATA;
667
668     /* big-endian ordering; build up number */
669     *num = 0;
670     while (n++ < size)
671         *num = (*num << 8) | avio_r8(pb);
672
673     return 0;
674 }
675
676 /*
677  * Read the next element as a float.
678  * 0 is success, < 0 is failure.
679  */
680 static int ebml_read_float(AVIOContext *pb, int size, double *num)
681 {
682     if (size == 0) {
683         *num = 0;
684     } else if (size == 4) {
685         *num = av_int2float(avio_rb32(pb));
686     } else if (size == 8){
687         *num = av_int2double(avio_rb64(pb));
688     } else
689         return AVERROR_INVALIDDATA;
690
691     return 0;
692 }
693
694 /*
695  * Read the next element as an ASCII string.
696  * 0 is success, < 0 is failure.
697  */
698 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
699 {
700     av_free(*str);
701     /* EBML strings are usually not 0-terminated, so we allocate one
702      * byte more, read the string and NULL-terminate it ourselves. */
703     if (!(*str = av_malloc(size + 1)))
704         return AVERROR(ENOMEM);
705     if (avio_read(pb, (uint8_t *) *str, size) != size) {
706         av_freep(str);
707         return AVERROR(EIO);
708     }
709     (*str)[size] = '\0';
710
711     return 0;
712 }
713
714 /*
715  * Read the next element as binary data.
716  * 0 is success, < 0 is failure.
717  */
718 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
719 {
720     av_free(bin->data);
721     if (!(bin->data = av_malloc(length)))
722         return AVERROR(ENOMEM);
723
724     bin->size = length;
725     bin->pos  = avio_tell(pb);
726     if (avio_read(pb, bin->data, length) != length) {
727         av_freep(&bin->data);
728         return AVERROR(EIO);
729     }
730
731     return 0;
732 }
733
734 /*
735  * Read the next element, but only the header. The contents
736  * are supposed to be sub-elements which can be read separately.
737  * 0 is success, < 0 is failure.
738  */
739 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
740 {
741     AVIOContext *pb = matroska->ctx->pb;
742     MatroskaLevel *level;
743
744     if (matroska->num_levels >= EBML_MAX_DEPTH) {
745         av_log(matroska->ctx, AV_LOG_ERROR,
746                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
747         return AVERROR(ENOSYS);
748     }
749
750     level = &matroska->levels[matroska->num_levels++];
751     level->start = avio_tell(pb);
752     level->length = length;
753
754     return 0;
755 }
756
757 /*
758  * Read signed/unsigned "EBML" numbers.
759  * Return: number of bytes processed, < 0 on error
760  */
761 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
762                                  uint8_t *data, uint32_t size, uint64_t *num)
763 {
764     AVIOContext pb;
765     ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
766     return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
767 }
768
769 /*
770  * Same as above, but signed.
771  */
772 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
773                                  uint8_t *data, uint32_t size, int64_t *num)
774 {
775     uint64_t unum;
776     int res;
777
778     /* read as unsigned number first */
779     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
780         return res;
781
782     /* make signed (weird way) */
783     *num = unum - ((1LL << (7*res - 1)) - 1);
784
785     return res;
786 }
787
788 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
789                            EbmlSyntax *syntax, void *data);
790
791 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
792                          uint32_t id, void *data)
793 {
794     int i;
795     for (i=0; syntax[i].id; i++)
796         if (id == syntax[i].id)
797             break;
798     if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
799         matroska->num_levels > 0 &&
800         matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
801         return 0;  // we reached the end of an unknown size cluster
802     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
803         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
804     return ebml_parse_elem(matroska, &syntax[i], data);
805 }
806
807 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
808                       void *data)
809 {
810     if (!matroska->current_id) {
811         uint64_t id;
812         int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
813         if (res < 0)
814             return res;
815         matroska->current_id = id | 1 << 7*res;
816     }
817     return ebml_parse_id(matroska, syntax, matroska->current_id, data);
818 }
819
820 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
821                            void *data)
822 {
823     int i, res = 0;
824
825     for (i=0; syntax[i].id; i++)
826         switch (syntax[i].type) {
827         case EBML_UINT:
828             *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
829             break;
830         case EBML_FLOAT:
831             *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
832             break;
833         case EBML_STR:
834         case EBML_UTF8:
835             *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
836             break;
837         }
838
839     while (!res && !ebml_level_end(matroska))
840         res = ebml_parse(matroska, syntax, data);
841
842     return res;
843 }
844
845 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
846                            EbmlSyntax *syntax, void *data)
847 {
848     static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
849         [EBML_UINT]  = 8,
850         [EBML_FLOAT] = 8,
851         // max. 16 MB for strings
852         [EBML_STR]   = 0x1000000,
853         [EBML_UTF8]  = 0x1000000,
854         // max. 256 MB for binary data
855         [EBML_BIN]   = 0x10000000,
856         // no limits for anything else
857     };
858     AVIOContext *pb = matroska->ctx->pb;
859     uint32_t id = syntax->id;
860     uint64_t length;
861     int res;
862     void *newelem;
863
864     data = (char *)data + syntax->data_offset;
865     if (syntax->list_elem_size) {
866         EbmlList *list = data;
867         newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
868         if (!newelem)
869             return AVERROR(ENOMEM);
870         list->elem = newelem;
871         data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
872         memset(data, 0, syntax->list_elem_size);
873         list->nb_elem++;
874     }
875
876     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
877         matroska->current_id = 0;
878         if ((res = ebml_read_length(matroska, pb, &length)) < 0)
879             return res;
880         if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
881             av_log(matroska->ctx, AV_LOG_ERROR,
882                    "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
883                    length, max_lengths[syntax->type], syntax->type);
884             return AVERROR_INVALIDDATA;
885         }
886     }
887
888     switch (syntax->type) {
889     case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
890     case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
891     case EBML_STR:
892     case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
893     case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
894     case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
895                          return res;
896                      if (id == MATROSKA_ID_SEGMENT)
897                          matroska->segment_start = avio_tell(matroska->ctx->pb);
898                      return ebml_parse_nest(matroska, syntax->def.n, data);
899     case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
900     case EBML_STOP:  return 1;
901     default:         return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
902     }
903     if (res == AVERROR_INVALIDDATA)
904         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
905     else if (res == AVERROR(EIO))
906         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
907     return res;
908 }
909
910 static void ebml_free(EbmlSyntax *syntax, void *data)
911 {
912     int i, j;
913     for (i=0; syntax[i].id; i++) {
914         void *data_off = (char *)data + syntax[i].data_offset;
915         switch (syntax[i].type) {
916         case EBML_STR:
917         case EBML_UTF8:  av_freep(data_off);                      break;
918         case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
919         case EBML_NEST:
920             if (syntax[i].list_elem_size) {
921                 EbmlList *list = data_off;
922                 char *ptr = list->elem;
923                 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
924                     ebml_free(syntax[i].def.n, ptr);
925                 av_free(list->elem);
926             } else
927                 ebml_free(syntax[i].def.n, data_off);
928         default:  break;
929         }
930     }
931 }
932
933
934 /*
935  * Autodetecting...
936  */
937 static int matroska_probe(AVProbeData *p)
938 {
939     uint64_t total = 0;
940     int len_mask = 0x80, size = 1, n = 1, i;
941
942     /* EBML header? */
943     if (AV_RB32(p->buf) != EBML_ID_HEADER)
944         return 0;
945
946     /* length of header */
947     total = p->buf[4];
948     while (size <= 8 && !(total & len_mask)) {
949         size++;
950         len_mask >>= 1;
951     }
952     if (size > 8)
953       return 0;
954     total &= (len_mask - 1);
955     while (n < size)
956         total = (total << 8) | p->buf[4 + n++];
957
958     /* Does the probe data contain the whole header? */
959     if (p->buf_size < 4 + size + total)
960       return 0;
961
962     /* The header should contain a known document type. For now,
963      * we don't parse the whole header but simply check for the
964      * availability of that array of characters inside the header.
965      * Not fully fool-proof, but good enough. */
966     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
967         int probelen = strlen(matroska_doctypes[i]);
968         if (total < probelen)
969             continue;
970         for (n = 4+size; n <= 4+size+total-probelen; n++)
971             if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
972                 return AVPROBE_SCORE_MAX;
973     }
974
975     // probably valid EBML header but no recognized doctype
976     return AVPROBE_SCORE_MAX/2;
977 }
978
979 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
980                                                  int num)
981 {
982     MatroskaTrack *tracks = matroska->tracks.elem;
983     int i;
984
985     for (i=0; i < matroska->tracks.nb_elem; i++)
986         if (tracks[i].num == num)
987             return &tracks[i];
988
989     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
990     return NULL;
991 }
992
993 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
994                                   MatroskaTrack *track)
995 {
996     MatroskaTrackEncoding *encodings = track->encodings.elem;
997     uint8_t* data = *buf;
998     int isize = *buf_size;
999     uint8_t* pkt_data = NULL;
1000     uint8_t av_unused *newpktdata;
1001     int pkt_size = isize;
1002     int result = 0;
1003     int olen;
1004
1005     if (pkt_size >= 10000000)
1006         return -1;
1007
1008     switch (encodings[0].compression.algo) {
1009     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1010         return encodings[0].compression.settings.size;
1011     case MATROSKA_TRACK_ENCODING_COMP_LZO:
1012         do {
1013             olen = pkt_size *= 3;
1014             pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
1015             result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1016         } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1017         if (result)
1018             goto failed;
1019         pkt_size -= olen;
1020         break;
1021 #if CONFIG_ZLIB
1022     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1023         z_stream zstream = {0};
1024         if (inflateInit(&zstream) != Z_OK)
1025             return -1;
1026         zstream.next_in = data;
1027         zstream.avail_in = isize;
1028         do {
1029             pkt_size *= 3;
1030             newpktdata = av_realloc(pkt_data, pkt_size);
1031             if (!newpktdata) {
1032                 inflateEnd(&zstream);
1033                 goto failed;
1034             }
1035             pkt_data = newpktdata;
1036             zstream.avail_out = pkt_size - zstream.total_out;
1037             zstream.next_out = pkt_data + zstream.total_out;
1038             if (pkt_data) {
1039                 result = inflate(&zstream, Z_NO_FLUSH);
1040             } else
1041                 result = Z_MEM_ERROR;
1042         } while (result==Z_OK && pkt_size<10000000);
1043         pkt_size = zstream.total_out;
1044         inflateEnd(&zstream);
1045         if (result != Z_STREAM_END)
1046             goto failed;
1047         break;
1048     }
1049 #endif
1050 #if CONFIG_BZLIB
1051     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1052         bz_stream bzstream = {0};
1053         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1054             return -1;
1055         bzstream.next_in = data;
1056         bzstream.avail_in = isize;
1057         do {
1058             pkt_size *= 3;
1059             newpktdata = av_realloc(pkt_data, pkt_size);
1060             if (!newpktdata) {
1061                 BZ2_bzDecompressEnd(&bzstream);
1062                 goto failed;
1063             }
1064             pkt_data = newpktdata;
1065             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1066             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1067             if (pkt_data) {
1068                 result = BZ2_bzDecompress(&bzstream);
1069             } else
1070                 result = BZ_MEM_ERROR;
1071         } while (result==BZ_OK && pkt_size<10000000);
1072         pkt_size = bzstream.total_out_lo32;
1073         BZ2_bzDecompressEnd(&bzstream);
1074         if (result != BZ_STREAM_END)
1075             goto failed;
1076         break;
1077     }
1078 #endif
1079     default:
1080         return -1;
1081     }
1082
1083     *buf = pkt_data;
1084     *buf_size = pkt_size;
1085     return 0;
1086  failed:
1087     av_free(pkt_data);
1088     return -1;
1089 }
1090
1091 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1092                                     AVPacket *pkt, uint64_t display_duration)
1093 {
1094     char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1095     for (; *ptr!=',' && ptr<end-1; ptr++);
1096     if (*ptr == ',')
1097         ptr++;
1098     layer = ptr;
1099     for (; *ptr!=',' && ptr<end-1; ptr++);
1100     if (*ptr == ',') {
1101         int64_t end_pts = pkt->pts + display_duration;
1102         int sc = matroska->time_scale * pkt->pts / 10000000;
1103         int ec = matroska->time_scale * end_pts  / 10000000;
1104         int sh, sm, ss, eh, em, es, len;
1105         sh = sc/360000;  sc -= 360000*sh;
1106         sm = sc/  6000;  sc -=   6000*sm;
1107         ss = sc/   100;  sc -=    100*ss;
1108         eh = ec/360000;  ec -= 360000*eh;
1109         em = ec/  6000;  ec -=   6000*em;
1110         es = ec/   100;  ec -=    100*es;
1111         *ptr++ = '\0';
1112         len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1113         if (!(line = av_malloc(len)))
1114             return;
1115         snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1116                  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1117         av_free(pkt->data);
1118         pkt->data = line;
1119         pkt->size = strlen(line);
1120     }
1121 }
1122
1123 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1124 {
1125     void *newdata = av_realloc(out->data, out->size+in->size);
1126     if (!newdata)
1127         return AVERROR(ENOMEM);
1128     out->data = newdata;
1129     memcpy(out->data+out->size, in->data, in->size);
1130     out->size += in->size;
1131     av_destruct_packet(in);
1132     av_free(in);
1133     return 0;
1134 }
1135
1136 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1137                                  AVDictionary **metadata, char *prefix)
1138 {
1139     MatroskaTag *tags = list->elem;
1140     char key[1024];
1141     int i;
1142
1143     for (i=0; i < list->nb_elem; i++) {
1144         const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1145
1146         if (!tags[i].name) {
1147             av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1148             continue;
1149         }
1150         if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1151         else         av_strlcpy(key, tags[i].name, sizeof(key));
1152         if (tags[i].def || !lang) {
1153         av_dict_set(metadata, key, tags[i].string, 0);
1154         if (tags[i].sub.nb_elem)
1155             matroska_convert_tag(s, &tags[i].sub, metadata, key);
1156         }
1157         if (lang) {
1158             av_strlcat(key, "-", sizeof(key));
1159             av_strlcat(key, lang, sizeof(key));
1160             av_dict_set(metadata, key, tags[i].string, 0);
1161             if (tags[i].sub.nb_elem)
1162                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1163         }
1164     }
1165     ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1166 }
1167
1168 static void matroska_convert_tags(AVFormatContext *s)
1169 {
1170     MatroskaDemuxContext *matroska = s->priv_data;
1171     MatroskaTags *tags = matroska->tags.elem;
1172     int i, j;
1173
1174     for (i=0; i < matroska->tags.nb_elem; i++) {
1175         if (tags[i].target.attachuid) {
1176             MatroskaAttachement *attachment = matroska->attachments.elem;
1177             for (j=0; j<matroska->attachments.nb_elem; j++)
1178                 if (attachment[j].uid == tags[i].target.attachuid
1179                     && attachment[j].stream)
1180                     matroska_convert_tag(s, &tags[i].tag,
1181                                          &attachment[j].stream->metadata, NULL);
1182         } else if (tags[i].target.chapteruid) {
1183             MatroskaChapter *chapter = matroska->chapters.elem;
1184             for (j=0; j<matroska->chapters.nb_elem; j++)
1185                 if (chapter[j].uid == tags[i].target.chapteruid
1186                     && chapter[j].chapter)
1187                     matroska_convert_tag(s, &tags[i].tag,
1188                                          &chapter[j].chapter->metadata, NULL);
1189         } else if (tags[i].target.trackuid) {
1190             MatroskaTrack *track = matroska->tracks.elem;
1191             for (j=0; j<matroska->tracks.nb_elem; j++)
1192                 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1193                     matroska_convert_tag(s, &tags[i].tag,
1194                                          &track[j].stream->metadata, NULL);
1195         } else {
1196             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1197                                  tags[i].target.type);
1198         }
1199     }
1200 }
1201
1202 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
1203 {
1204     EbmlList *seekhead_list = &matroska->seekhead;
1205     MatroskaSeekhead *seekhead = seekhead_list->elem;
1206     uint32_t level_up = matroska->level_up;
1207     int64_t before_pos = avio_tell(matroska->ctx->pb);
1208     uint32_t saved_id = matroska->current_id;
1209     MatroskaLevel level;
1210     int64_t offset;
1211     int ret = 0;
1212
1213     if (idx >= seekhead_list->nb_elem
1214             || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1215             || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1216         return 0;
1217
1218     /* seek */
1219     offset = seekhead[idx].pos + matroska->segment_start;
1220     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1221         /* We don't want to lose our seekhead level, so we add
1222          * a dummy. This is a crude hack. */
1223         if (matroska->num_levels == EBML_MAX_DEPTH) {
1224             av_log(matroska->ctx, AV_LOG_INFO,
1225                    "Max EBML element depth (%d) reached, "
1226                    "cannot parse further.\n", EBML_MAX_DEPTH);
1227             ret = AVERROR_INVALIDDATA;
1228         } else {
1229             level.start = 0;
1230             level.length = (uint64_t)-1;
1231             matroska->levels[matroska->num_levels] = level;
1232             matroska->num_levels++;
1233             matroska->current_id = 0;
1234
1235             ret = ebml_parse(matroska, matroska_segment, matroska);
1236
1237             /* remove dummy level */
1238             while (matroska->num_levels) {
1239                 uint64_t length = matroska->levels[--matroska->num_levels].length;
1240                 if (length == (uint64_t)-1)
1241                     break;
1242             }
1243         }
1244     }
1245     /* seek back */
1246     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1247     matroska->level_up = level_up;
1248     matroska->current_id = saved_id;
1249
1250     return ret;
1251 }
1252
1253 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1254 {
1255     EbmlList *seekhead_list = &matroska->seekhead;
1256     int64_t before_pos = avio_tell(matroska->ctx->pb);
1257     int i;
1258
1259     // we should not do any seeking in the streaming case
1260     if (!matroska->ctx->pb->seekable ||
1261         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1262         return;
1263
1264     for (i = 0; i < seekhead_list->nb_elem; i++) {
1265         MatroskaSeekhead *seekhead = seekhead_list->elem;
1266         if (seekhead[i].pos <= before_pos)
1267             continue;
1268
1269         // defer cues parsing until we actually need cue data.
1270         if (seekhead[i].id == MATROSKA_ID_CUES) {
1271             matroska->cues_parsing_deferred = 1;
1272             continue;
1273         }
1274
1275         if (matroska_parse_seekhead_entry(matroska, i) < 0) {
1276             // mark index as broken
1277             matroska->cues_parsing_deferred = -1;
1278             break;
1279         }
1280     }
1281 }
1282
1283 static void matroska_add_index_entries(MatroskaDemuxContext *matroska) {
1284     EbmlList *index_list;
1285     MatroskaIndex *index;
1286     int index_scale = 1;
1287     int i, j;
1288
1289     index_list = &matroska->index;
1290     index = index_list->elem;
1291     if (index_list->nb_elem
1292         && index[0].time > 1E14/matroska->time_scale) {
1293         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1294         index_scale = matroska->time_scale;
1295     }
1296     for (i = 0; i < index_list->nb_elem; i++) {
1297         EbmlList *pos_list = &index[i].pos;
1298         MatroskaIndexPos *pos = pos_list->elem;
1299         for (j = 0; j < pos_list->nb_elem; j++) {
1300             MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1301             if (track && track->stream)
1302                 av_add_index_entry(track->stream,
1303                                    pos[j].pos + matroska->segment_start,
1304                                    index[i].time/index_scale, 0, 0,
1305                                    AVINDEX_KEYFRAME);
1306         }
1307     }
1308 }
1309
1310 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1311     EbmlList *seekhead_list = &matroska->seekhead;
1312     MatroskaSeekhead *seekhead = seekhead_list->elem;
1313     int i;
1314
1315     for (i = 0; i < seekhead_list->nb_elem; i++)
1316         if (seekhead[i].id == MATROSKA_ID_CUES)
1317             break;
1318     assert(i <= seekhead_list->nb_elem);
1319
1320     if (matroska_parse_seekhead_entry(matroska, i) < 0)
1321        matroska->cues_parsing_deferred = -1;
1322     matroska_add_index_entries(matroska);
1323 }
1324
1325 static int matroska_aac_profile(char *codec_id)
1326 {
1327     static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1328     int profile;
1329
1330     for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1331         if (strstr(codec_id, aac_profiles[profile]))
1332             break;
1333     return profile + 1;
1334 }
1335
1336 static int matroska_aac_sri(int samplerate)
1337 {
1338     int sri;
1339
1340     for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1341         if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1342             break;
1343     return sri;
1344 }
1345
1346 static int matroska_read_header(AVFormatContext *s)
1347 {
1348     MatroskaDemuxContext *matroska = s->priv_data;
1349     EbmlList *attachements_list = &matroska->attachments;
1350     MatroskaAttachement *attachements;
1351     EbmlList *chapters_list = &matroska->chapters;
1352     MatroskaChapter *chapters;
1353     MatroskaTrack *tracks;
1354     uint64_t max_start = 0;
1355     int64_t pos;
1356     Ebml ebml = { 0 };
1357     AVStream *st;
1358     int i, j, k, res;
1359
1360     matroska->ctx = s;
1361
1362     /* First read the EBML header. */
1363     if (ebml_parse(matroska, ebml_syntax, &ebml)
1364         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1365         || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3) {
1366         av_log(matroska->ctx, AV_LOG_ERROR,
1367                "EBML header using unsupported features\n"
1368                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1369                ebml.version, ebml.doctype, ebml.doctype_version);
1370         ebml_free(ebml_syntax, &ebml);
1371         return AVERROR_PATCHWELCOME;
1372     } else if (ebml.doctype_version == 3) {
1373         av_log(matroska->ctx, AV_LOG_WARNING,
1374                "EBML header using unsupported features\n"
1375                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1376                ebml.version, ebml.doctype, ebml.doctype_version);
1377     }
1378     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1379         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1380             break;
1381     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1382         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1383     }
1384     ebml_free(ebml_syntax, &ebml);
1385
1386     /* The next thing is a segment. */
1387     pos = avio_tell(matroska->ctx->pb);
1388     res = ebml_parse(matroska, matroska_segments, matroska);
1389     // try resyncing until we find a EBML_STOP type element.
1390     while (res != 1) {
1391         res = matroska_resync(matroska, pos);
1392         if (res < 0)
1393             return res;
1394         pos = avio_tell(matroska->ctx->pb);
1395         res = ebml_parse(matroska, matroska_segment, matroska);
1396     }
1397     matroska_execute_seekhead(matroska);
1398
1399     if (!matroska->time_scale)
1400         matroska->time_scale = 1000000;
1401     if (matroska->duration)
1402         matroska->ctx->duration = matroska->duration * matroska->time_scale
1403                                   * 1000 / AV_TIME_BASE;
1404     av_dict_set(&s->metadata, "title", matroska->title, 0);
1405
1406     tracks = matroska->tracks.elem;
1407     for (i=0; i < matroska->tracks.nb_elem; i++) {
1408         MatroskaTrack *track = &tracks[i];
1409         enum CodecID codec_id = CODEC_ID_NONE;
1410         EbmlList *encodings_list = &track->encodings;
1411         MatroskaTrackEncoding *encodings = encodings_list->elem;
1412         uint8_t *extradata = NULL;
1413         int extradata_size = 0;
1414         int extradata_offset = 0;
1415         uint32_t fourcc = 0;
1416         AVIOContext b;
1417
1418         /* Apply some sanity checks. */
1419         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1420             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1421             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1422             av_log(matroska->ctx, AV_LOG_INFO,
1423                    "Unknown or unsupported track type %"PRIu64"\n",
1424                    track->type);
1425             continue;
1426         }
1427         if (track->codec_id == NULL)
1428             continue;
1429
1430         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1431             if (!track->default_duration)
1432                 track->default_duration = 1000000000/track->video.frame_rate;
1433             if (!track->video.display_width)
1434                 track->video.display_width = track->video.pixel_width;
1435             if (!track->video.display_height)
1436                 track->video.display_height = track->video.pixel_height;
1437             if (track->video.color_space.size == 4)
1438                 fourcc = AV_RL32(track->video.color_space.data);
1439         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1440             if (!track->audio.out_samplerate)
1441                 track->audio.out_samplerate = track->audio.samplerate;
1442         }
1443         if (encodings_list->nb_elem > 1) {
1444             av_log(matroska->ctx, AV_LOG_ERROR,
1445                    "Multiple combined encodings not supported");
1446         } else if (encodings_list->nb_elem == 1) {
1447             if (encodings[0].type ||
1448                 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1449 #if CONFIG_ZLIB
1450                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1451 #endif
1452 #if CONFIG_BZLIB
1453                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1454 #endif
1455                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1456                 encodings[0].scope = 0;
1457                 av_log(matroska->ctx, AV_LOG_ERROR,
1458                        "Unsupported encoding type");
1459             } else if (track->codec_priv.size && encodings[0].scope&2) {
1460                 uint8_t *codec_priv = track->codec_priv.data;
1461                 int offset = matroska_decode_buffer(&track->codec_priv.data,
1462                                                     &track->codec_priv.size,
1463                                                     track);
1464                 if (offset < 0) {
1465                     track->codec_priv.data = NULL;
1466                     track->codec_priv.size = 0;
1467                     av_log(matroska->ctx, AV_LOG_ERROR,
1468                            "Failed to decode codec private data\n");
1469                 } else if (offset > 0) {
1470                     track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1471                     memcpy(track->codec_priv.data,
1472                            encodings[0].compression.settings.data, offset);
1473                     memcpy(track->codec_priv.data+offset, codec_priv,
1474                            track->codec_priv.size);
1475                     track->codec_priv.size += offset;
1476                 }
1477                 if (codec_priv != track->codec_priv.data)
1478                     av_free(codec_priv);
1479             }
1480         }
1481
1482         for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1483             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1484                         strlen(ff_mkv_codec_tags[j].str))){
1485                 codec_id= ff_mkv_codec_tags[j].id;
1486                 break;
1487             }
1488         }
1489
1490         st = track->stream = avformat_new_stream(s, NULL);
1491         if (st == NULL)
1492             return AVERROR(ENOMEM);
1493
1494         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1495             && track->codec_priv.size >= 40
1496             && track->codec_priv.data != NULL) {
1497             track->ms_compat = 1;
1498             fourcc = AV_RL32(track->codec_priv.data + 16);
1499             codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
1500             extradata_offset = 40;
1501         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1502                    && track->codec_priv.size >= 14
1503                    && track->codec_priv.data != NULL) {
1504             int ret;
1505             ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1506                           AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
1507             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1508             if (ret < 0)
1509                 return ret;
1510             codec_id = st->codec->codec_id;
1511             extradata_offset = FFMIN(track->codec_priv.size, 18);
1512         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1513                    && (track->codec_priv.size >= 86)
1514                    && (track->codec_priv.data != NULL)) {
1515             fourcc = AV_RL32(track->codec_priv.data);
1516             codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
1517         } else if (codec_id == CODEC_ID_PCM_S16BE) {
1518             switch (track->audio.bitdepth) {
1519             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1520             case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
1521             case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
1522             }
1523         } else if (codec_id == CODEC_ID_PCM_S16LE) {
1524             switch (track->audio.bitdepth) {
1525             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1526             case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
1527             case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
1528             }
1529         } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1530             codec_id = CODEC_ID_PCM_F64LE;
1531         } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1532             int profile = matroska_aac_profile(track->codec_id);
1533             int sri = matroska_aac_sri(track->audio.samplerate);
1534             extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1535             if (extradata == NULL)
1536                 return AVERROR(ENOMEM);
1537             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1538             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1539             if (strstr(track->codec_id, "SBR")) {
1540                 sri = matroska_aac_sri(track->audio.out_samplerate);
1541                 extradata[2] = 0x56;
1542                 extradata[3] = 0xE5;
1543                 extradata[4] = 0x80 | (sri<<3);
1544                 extradata_size = 5;
1545             } else
1546                 extradata_size = 2;
1547         } else if (codec_id == CODEC_ID_TTA) {
1548             extradata_size = 30;
1549             extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1550             if (extradata == NULL)
1551                 return AVERROR(ENOMEM);
1552             ffio_init_context(&b, extradata, extradata_size, 1,
1553                           NULL, NULL, NULL, NULL);
1554             avio_write(&b, "TTA1", 4);
1555             avio_wl16(&b, 1);
1556             avio_wl16(&b, track->audio.channels);
1557             avio_wl16(&b, track->audio.bitdepth);
1558             avio_wl32(&b, track->audio.out_samplerate);
1559             avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1560         } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1561                    codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1562             extradata_offset = 26;
1563         } else if (codec_id == CODEC_ID_RA_144) {
1564             track->audio.out_samplerate = 8000;
1565             track->audio.channels = 1;
1566         } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1567                    codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1568             int flavor;
1569             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1570                           0, NULL, NULL, NULL, NULL);
1571             avio_skip(&b, 22);
1572             flavor                       = avio_rb16(&b);
1573             track->audio.coded_framesize = avio_rb32(&b);
1574             avio_skip(&b, 12);
1575             track->audio.sub_packet_h    = avio_rb16(&b);
1576             track->audio.frame_size      = avio_rb16(&b);
1577             track->audio.sub_packet_size = avio_rb16(&b);
1578             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1579             if (codec_id == CODEC_ID_RA_288) {
1580                 st->codec->block_align = track->audio.coded_framesize;
1581                 track->codec_priv.size = 0;
1582             } else {
1583                 if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1584                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1585                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1586                     st->codec->bit_rate = sipr_bit_rate[flavor];
1587                 }
1588                 st->codec->block_align = track->audio.sub_packet_size;
1589                 extradata_offset = 78;
1590             }
1591         }
1592         track->codec_priv.size -= extradata_offset;
1593
1594         if (codec_id == CODEC_ID_NONE)
1595             av_log(matroska->ctx, AV_LOG_INFO,
1596                    "Unknown/unsupported CodecID %s.\n", track->codec_id);
1597
1598         if (track->time_scale < 0.01)
1599             track->time_scale = 1.0;
1600         avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1601
1602         st->codec->codec_id = codec_id;
1603         st->start_time = 0;
1604         if (strcmp(track->language, "und"))
1605             av_dict_set(&st->metadata, "language", track->language, 0);
1606         av_dict_set(&st->metadata, "title", track->name, 0);
1607
1608         if (track->flag_default)
1609             st->disposition |= AV_DISPOSITION_DEFAULT;
1610         if (track->flag_forced)
1611             st->disposition |= AV_DISPOSITION_FORCED;
1612
1613         if (!st->codec->extradata) {
1614             if(extradata){
1615                 st->codec->extradata = extradata;
1616                 st->codec->extradata_size = extradata_size;
1617             } else if(track->codec_priv.data && track->codec_priv.size > 0){
1618                 st->codec->extradata = av_mallocz(track->codec_priv.size +
1619                                                   FF_INPUT_BUFFER_PADDING_SIZE);
1620                 if(st->codec->extradata == NULL)
1621                     return AVERROR(ENOMEM);
1622                 st->codec->extradata_size = track->codec_priv.size;
1623                 memcpy(st->codec->extradata,
1624                        track->codec_priv.data + extradata_offset,
1625                        track->codec_priv.size);
1626             }
1627         }
1628
1629         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1630             MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
1631
1632             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1633             st->codec->codec_tag  = fourcc;
1634             st->codec->width  = track->video.pixel_width;
1635             st->codec->height = track->video.pixel_height;
1636             av_reduce(&st->sample_aspect_ratio.num,
1637                       &st->sample_aspect_ratio.den,
1638                       st->codec->height * track->video.display_width,
1639                       st->codec-> width * track->video.display_height,
1640                       255);
1641             if (st->codec->codec_id != CODEC_ID_H264)
1642             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1643             if (track->default_duration)
1644                 st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
1645
1646             /* export stereo mode flag as metadata tag */
1647             if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
1648                 av_dict_set(&st->metadata, "stereo_mode", matroska_video_stereo_mode[track->video.stereo_mode], 0);
1649
1650             /* if we have virtual track, mark the real tracks */
1651             for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
1652                 char buf[32];
1653                 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
1654                     continue;
1655                 snprintf(buf, sizeof(buf), "%s_%d",
1656                          matroska_video_stereo_plane[planes[j].type], i);
1657                 for (k=0; k < matroska->tracks.nb_elem; k++)
1658                     if (planes[j].uid == tracks[k].uid) {
1659                         av_dict_set(&s->streams[k]->metadata,
1660                                     "stereo_mode", buf, 0);
1661                         break;
1662                     }
1663             }
1664         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1665             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1666             st->codec->sample_rate = track->audio.out_samplerate;
1667             st->codec->channels = track->audio.channels;
1668             if (st->codec->codec_id != CODEC_ID_AAC)
1669             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1670         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1671             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1672         }
1673     }
1674
1675     attachements = attachements_list->elem;
1676     for (j=0; j<attachements_list->nb_elem; j++) {
1677         if (!(attachements[j].filename && attachements[j].mime &&
1678               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1679             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1680         } else {
1681             AVStream *st = avformat_new_stream(s, NULL);
1682             if (st == NULL)
1683                 break;
1684             av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1685             av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1686             st->codec->codec_id = CODEC_ID_NONE;
1687             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1688             st->codec->extradata  = av_malloc(attachements[j].bin.size + FF_INPUT_BUFFER_PADDING_SIZE);
1689             if(st->codec->extradata == NULL)
1690                 break;
1691             st->codec->extradata_size = attachements[j].bin.size;
1692             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1693
1694             for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1695                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1696                              strlen(ff_mkv_mime_tags[i].str))) {
1697                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1698                     break;
1699                 }
1700             }
1701             attachements[j].stream = st;
1702         }
1703     }
1704
1705     chapters = chapters_list->elem;
1706     for (i=0; i<chapters_list->nb_elem; i++)
1707         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1708             && (max_start==0 || chapters[i].start > max_start)) {
1709             chapters[i].chapter =
1710             avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1711                            chapters[i].start, chapters[i].end,
1712                            chapters[i].title);
1713             av_dict_set(&chapters[i].chapter->metadata,
1714                              "title", chapters[i].title, 0);
1715             max_start = chapters[i].start;
1716         }
1717
1718     matroska_add_index_entries(matroska);
1719
1720     matroska_convert_tags(s);
1721
1722     return 0;
1723 }
1724
1725 /*
1726  * Put one packet in an application-supplied AVPacket struct.
1727  * Returns 0 on success or -1 on failure.
1728  */
1729 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1730                                    AVPacket *pkt)
1731 {
1732     if (matroska->num_packets > 0) {
1733         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1734         av_free(matroska->packets[0]);
1735         if (matroska->num_packets > 1) {
1736             void *newpackets;
1737             memmove(&matroska->packets[0], &matroska->packets[1],
1738                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1739             newpackets = av_realloc(matroska->packets,
1740                             (matroska->num_packets - 1) * sizeof(AVPacket *));
1741             if (newpackets)
1742                 matroska->packets = newpackets;
1743         } else {
1744             av_freep(&matroska->packets);
1745         }
1746         matroska->num_packets--;
1747         return 0;
1748     }
1749
1750     return -1;
1751 }
1752
1753 /*
1754  * Free all packets in our internal queue.
1755  */
1756 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1757 {
1758     if (matroska->packets) {
1759         int n;
1760         for (n = 0; n < matroska->num_packets; n++) {
1761             av_free_packet(matroska->packets[n]);
1762             av_free(matroska->packets[n]);
1763         }
1764         av_freep(&matroska->packets);
1765         matroska->num_packets = 0;
1766     }
1767 }
1768
1769 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1770                                 int size, int64_t pos, uint64_t cluster_time,
1771                                 uint64_t duration, int is_keyframe,
1772                                 int64_t cluster_pos)
1773 {
1774     uint64_t timecode = AV_NOPTS_VALUE;
1775     MatroskaTrack *track;
1776     int res = 0;
1777     AVStream *st;
1778     AVPacket *pkt;
1779     int16_t block_time;
1780     uint32_t *lace_size = NULL;
1781     int n, flags, laces = 0;
1782     uint64_t num;
1783
1784     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1785         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1786         return AVERROR_INVALIDDATA;
1787     }
1788     data += n;
1789     size -= n;
1790
1791     track = matroska_find_track_by_num(matroska, num);
1792     if (!track || !track->stream) {
1793         av_log(matroska->ctx, AV_LOG_INFO,
1794                "Invalid stream %"PRIu64" or size %u\n", num, size);
1795         return AVERROR_INVALIDDATA;
1796     } else if (size <= 3)
1797         return 0;
1798     st = track->stream;
1799     if (st->discard >= AVDISCARD_ALL)
1800         return res;
1801     if (!duration)
1802         duration = track->default_duration / matroska->time_scale;
1803
1804     block_time = AV_RB16(data);
1805     data += 2;
1806     flags = *data++;
1807     size -= 3;
1808     if (is_keyframe == -1)
1809         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1810
1811     if (cluster_time != (uint64_t)-1
1812         && (block_time >= 0 || cluster_time >= -block_time)) {
1813         timecode = cluster_time + block_time;
1814         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1815             && timecode < track->end_timecode)
1816             is_keyframe = 0;  /* overlapping subtitles are not key frame */
1817         if (is_keyframe)
1818             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1819         track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1820     }
1821
1822     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1823         if (!is_keyframe || timecode < matroska->skip_to_timecode)
1824             return res;
1825         matroska->skip_to_keyframe = 0;
1826     }
1827
1828     switch ((flags & 0x06) >> 1) {
1829         case 0x0: /* no lacing */
1830             laces = 1;
1831             lace_size = av_mallocz(sizeof(int));
1832             lace_size[0] = size;
1833             break;
1834
1835         case 0x1: /* Xiph lacing */
1836         case 0x2: /* fixed-size lacing */
1837         case 0x3: /* EBML lacing */
1838             assert(size>0); // size <=3 is checked before size-=3 above
1839             laces = (*data) + 1;
1840             data += 1;
1841             size -= 1;
1842             lace_size = av_mallocz(laces * sizeof(int));
1843
1844             switch ((flags & 0x06) >> 1) {
1845                 case 0x1: /* Xiph lacing */ {
1846                     uint8_t temp;
1847                     uint32_t total = 0;
1848                     for (n = 0; res == 0 && n < laces - 1; n++) {
1849                         while (1) {
1850                             if (size == 0) {
1851                                 res = -1;
1852                                 break;
1853                             }
1854                             temp = *data;
1855                             lace_size[n] += temp;
1856                             data += 1;
1857                             size -= 1;
1858                             if (temp != 0xff)
1859                                 break;
1860                         }
1861                         total += lace_size[n];
1862                     }
1863                     lace_size[n] = size - total;
1864                     break;
1865                 }
1866
1867                 case 0x2: /* fixed-size lacing */
1868                     for (n = 0; n < laces; n++)
1869                         lace_size[n] = size / laces;
1870                     break;
1871
1872                 case 0x3: /* EBML lacing */ {
1873                     uint32_t total;
1874                     n = matroska_ebmlnum_uint(matroska, data, size, &num);
1875                     if (n < 0) {
1876                         av_log(matroska->ctx, AV_LOG_INFO,
1877                                "EBML block data error\n");
1878                         break;
1879                     }
1880                     data += n;
1881                     size -= n;
1882                     total = lace_size[0] = num;
1883                     for (n = 1; res == 0 && n < laces - 1; n++) {
1884                         int64_t snum;
1885                         int r;
1886                         r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1887                         if (r < 0) {
1888                             av_log(matroska->ctx, AV_LOG_INFO,
1889                                    "EBML block data error\n");
1890                             break;
1891                         }
1892                         data += r;
1893                         size -= r;
1894                         lace_size[n] = lace_size[n - 1] + snum;
1895                         total += lace_size[n];
1896                     }
1897                     lace_size[laces - 1] = size - total;
1898                     break;
1899                 }
1900             }
1901             break;
1902     }
1903
1904     if (res == 0) {
1905         for (n = 0; n < laces; n++) {
1906             if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1907                  st->codec->codec_id == CODEC_ID_COOK ||
1908                  st->codec->codec_id == CODEC_ID_SIPR ||
1909                  st->codec->codec_id == CODEC_ID_ATRAC3) &&
1910                  st->codec->block_align && track->audio.sub_packet_size) {
1911                 int a = st->codec->block_align;
1912                 int sps = track->audio.sub_packet_size;
1913                 int cfs = track->audio.coded_framesize;
1914                 int h = track->audio.sub_packet_h;
1915                 int y = track->audio.sub_packet_cnt;
1916                 int w = track->audio.frame_size;
1917                 int x;
1918
1919                 if (!track->audio.pkt_cnt) {
1920                     if (track->audio.sub_packet_cnt == 0)
1921                         track->audio.buf_timecode = timecode;
1922                     if (st->codec->codec_id == CODEC_ID_RA_288)
1923                         for (x=0; x<h/2; x++)
1924                             memcpy(track->audio.buf+x*2*w+y*cfs,
1925                                    data+x*cfs, cfs);
1926                     else if (st->codec->codec_id == CODEC_ID_SIPR)
1927                         memcpy(track->audio.buf + y*w, data, w);
1928                     else
1929                         for (x=0; x<w/sps; x++)
1930                             memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1931
1932                     if (++track->audio.sub_packet_cnt >= h) {
1933                         if (st->codec->codec_id == CODEC_ID_SIPR)
1934                             ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1935                         track->audio.sub_packet_cnt = 0;
1936                         track->audio.pkt_cnt = h*w / a;
1937                     }
1938                 }
1939                 while (track->audio.pkt_cnt) {
1940                     pkt = av_mallocz(sizeof(AVPacket));
1941                     av_new_packet(pkt, a);
1942                     memcpy(pkt->data, track->audio.buf
1943                            + a * (h*w / a - track->audio.pkt_cnt--), a);
1944                     pkt->pts = track->audio.buf_timecode;
1945                     track->audio.buf_timecode = AV_NOPTS_VALUE;
1946                     pkt->pos = pos;
1947                     pkt->stream_index = st->index;
1948                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1949                 }
1950             } else {
1951                 MatroskaTrackEncoding *encodings = track->encodings.elem;
1952                 int offset = 0, pkt_size = lace_size[n];
1953                 uint8_t *pkt_data = data;
1954
1955                 if (pkt_size > size) {
1956                     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1957                     break;
1958                 }
1959
1960                 if (encodings && encodings->scope & 1) {
1961                     offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1962                     if (offset < 0)
1963                         continue;
1964                 }
1965
1966                 pkt = av_mallocz(sizeof(AVPacket));
1967                 /* XXX: prevent data copy... */
1968                 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1969                     av_free(pkt);
1970                     res = AVERROR(ENOMEM);
1971                     break;
1972                 }
1973                 if (offset)
1974                     memcpy (pkt->data, encodings->compression.settings.data, offset);
1975                 memcpy (pkt->data+offset, pkt_data, pkt_size);
1976
1977                 if (pkt_data != data)
1978                     av_free(pkt_data);
1979
1980                 if (n == 0)
1981                     pkt->flags = is_keyframe;
1982                 pkt->stream_index = st->index;
1983
1984                 if (track->ms_compat)
1985                     pkt->dts = timecode;
1986                 else
1987                     pkt->pts = timecode;
1988                 pkt->pos = pos;
1989                 if (st->codec->codec_id == CODEC_ID_TEXT)
1990                     pkt->convergence_duration = duration;
1991                 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1992                     pkt->duration = duration;
1993
1994                 if (st->codec->codec_id == CODEC_ID_SSA)
1995                     matroska_fix_ass_packet(matroska, pkt, duration);
1996
1997                 if (matroska->prev_pkt &&
1998                     timecode != AV_NOPTS_VALUE &&
1999                     matroska->prev_pkt->pts == timecode &&
2000                     matroska->prev_pkt->stream_index == st->index &&
2001                     st->codec->codec_id == CODEC_ID_SSA)
2002                     matroska_merge_packets(matroska->prev_pkt, pkt);
2003                 else {
2004                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2005                     matroska->prev_pkt = pkt;
2006                 }
2007             }
2008
2009             if (timecode != AV_NOPTS_VALUE)
2010                 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2011             data += lace_size[n];
2012             size -= lace_size[n];
2013         }
2014     }
2015
2016     av_free(lace_size);
2017     return res;
2018 }
2019
2020 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2021 {
2022     MatroskaCluster cluster = { 0 };
2023     EbmlList *blocks_list;
2024     MatroskaBlock *blocks;
2025     int i, res;
2026     int64_t pos = avio_tell(matroska->ctx->pb);
2027     matroska->prev_pkt = NULL;
2028     if (matroska->current_id)
2029         pos -= 4;  /* sizeof the ID which was already read */
2030     res = ebml_parse(matroska, matroska_clusters, &cluster);
2031     blocks_list = &cluster.blocks;
2032     blocks = blocks_list->elem;
2033     for (i=0; i<blocks_list->nb_elem; i++)
2034         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2035             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2036             res=matroska_parse_block(matroska,
2037                                      blocks[i].bin.data, blocks[i].bin.size,
2038                                      blocks[i].bin.pos,  cluster.timecode,
2039                                      blocks[i].duration, is_keyframe,
2040                                      pos);
2041         }
2042     ebml_free(matroska_cluster, &cluster);
2043     return res;
2044 }
2045
2046 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2047 {
2048     MatroskaDemuxContext *matroska = s->priv_data;
2049
2050     while (matroska_deliver_packet(matroska, pkt)) {
2051         int64_t pos = avio_tell(matroska->ctx->pb);
2052         if (matroska->done)
2053             return AVERROR_EOF;
2054         if (matroska_parse_cluster(matroska) < 0)
2055             matroska_resync(matroska, pos);
2056     }
2057
2058     return 0;
2059 }
2060
2061 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2062                               int64_t timestamp, int flags)
2063 {
2064     MatroskaDemuxContext *matroska = s->priv_data;
2065     MatroskaTrack *tracks = matroska->tracks.elem;
2066     AVStream *st = s->streams[stream_index];
2067     int i, index, index_sub, index_min;
2068
2069     /* Parse the CUES now since we need the index data to seek. */
2070     if (matroska->cues_parsing_deferred > 0) {
2071         matroska->cues_parsing_deferred = 0;
2072         matroska_parse_cues(matroska);
2073     }
2074
2075     if (!st->nb_index_entries)
2076         goto err;
2077     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2078
2079     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2080         avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2081         matroska->current_id = 0;
2082         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2083             matroska_clear_queue(matroska);
2084             if (matroska_parse_cluster(matroska) < 0)
2085                 break;
2086         }
2087     }
2088
2089     matroska_clear_queue(matroska);
2090     if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
2091         goto err;
2092
2093     index_min = index;
2094     for (i=0; i < matroska->tracks.nb_elem; i++) {
2095         tracks[i].audio.pkt_cnt = 0;
2096         tracks[i].audio.sub_packet_cnt = 0;
2097         tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2098         tracks[i].end_timecode = 0;
2099         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2100             && !tracks[i].stream->discard != AVDISCARD_ALL) {
2101             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2102             if (index_sub >= 0
2103                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2104                 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2105                 index_min = index_sub;
2106         }
2107     }
2108
2109     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2110     matroska->current_id = 0;
2111     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2112     matroska->skip_to_timecode = st->index_entries[index].timestamp;
2113     matroska->done = 0;
2114     matroska->num_levels = 0;
2115     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2116     return 0;
2117 err:
2118     // slightly hackish but allows proper fallback to
2119     // the generic seeking code.
2120     matroska_clear_queue(matroska);
2121     matroska->current_id = 0;
2122     matroska->skip_to_keyframe = 0;
2123     matroska->done = 0;
2124     matroska->num_levels = 0;
2125     return -1;
2126 }
2127
2128 static int matroska_read_close(AVFormatContext *s)
2129 {
2130     MatroskaDemuxContext *matroska = s->priv_data;
2131     MatroskaTrack *tracks = matroska->tracks.elem;
2132     int n;
2133
2134     matroska_clear_queue(matroska);
2135
2136     for (n=0; n < matroska->tracks.nb_elem; n++)
2137         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2138             av_free(tracks[n].audio.buf);
2139     ebml_free(matroska_segment, matroska);
2140
2141     return 0;
2142 }
2143
2144 AVInputFormat ff_matroska_demuxer = {
2145     .name           = "matroska,webm",
2146     .long_name      = NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
2147     .priv_data_size = sizeof(MatroskaDemuxContext),
2148     .read_probe     = matroska_probe,
2149     .read_header    = matroska_read_header,
2150     .read_packet    = matroska_read_packet,
2151     .read_close     = matroska_read_close,
2152     .read_seek      = matroska_read_seek,
2153 };