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