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