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