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