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