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