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