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