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