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