matroskadec: expand useless ebml_read_element_id() wrapper
[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 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 "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, ByteIOContext *pb,
482                          int max_size, uint64_t *number)
483 {
484     int len_mask = 0x80, read = 1, n = 1;
485     int64_t total = 0;
486
487     /* the first byte tells us the length in bytes - get_byte() can normally
488      * return 0, but since that's not a valid first ebmlID byte, we can
489      * use it safely here to catch EOS. */
490     if (!(total = get_byte(pb))) {
491         /* we might encounter EOS here */
492         if (!url_feof(pb)) {
493             offset_t pos = url_ftell(pb);
494             av_log(matroska->ctx, AV_LOG_ERROR,
495                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
496                    pos, pos);
497         }
498         return AVERROR(EIO); /* EOS or actual I/O error */
499     }
500
501     /* get the length of the EBML number */
502     while (read <= max_size && !(total & len_mask)) {
503         read++;
504         len_mask >>= 1;
505     }
506     if (read > max_size) {
507         offset_t pos = url_ftell(pb) - 1;
508         av_log(matroska->ctx, AV_LOG_ERROR,
509                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
510                (uint8_t) total, pos, pos);
511         return AVERROR_INVALIDDATA;
512     }
513
514     /* read out length */
515     total &= ~len_mask;
516     while (n++ < read)
517         total = (total << 8) | get_byte(pb);
518
519     *number = total;
520
521     return read;
522 }
523
524 /*
525  * Read the next element as an unsigned int.
526  * 0 is success, < 0 is failure.
527  */
528 static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
529 {
530     int n = 0;
531
532     if (size < 1 || size > 8)
533         return AVERROR_INVALIDDATA;
534
535     /* big-endian ordening; build up number */
536     *num = 0;
537     while (n++ < size)
538         *num = (*num << 8) | get_byte(pb);
539
540     return 0;
541 }
542
543 /*
544  * Read the next element as a float.
545  * 0 is success, < 0 is failure.
546  */
547 static int ebml_read_float(ByteIOContext *pb, int size, double *num)
548 {
549     if (size == 4) {
550         *num= av_int2flt(get_be32(pb));
551     } else if(size==8){
552         *num= av_int2dbl(get_be64(pb));
553     } else
554         return AVERROR_INVALIDDATA;
555
556     return 0;
557 }
558
559 /*
560  * Read the next element as an ASCII string.
561  * 0 is success, < 0 is failure.
562  */
563 static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
564 {
565     av_free(*str);
566     /* ebml strings are usually not 0-terminated, so we allocate one
567      * byte more, read the string and NULL-terminate it ourselves. */
568     if (!(*str = av_malloc(size + 1)))
569         return AVERROR(ENOMEM);
570     if (get_buffer(pb, (uint8_t *) *str, size) != size) {
571         av_free(*str);
572         return AVERROR(EIO);
573     }
574     (*str)[size] = '\0';
575
576     return 0;
577 }
578
579 /*
580  * Read the next element as binary data.
581  * 0 is success, < 0 is failure.
582  */
583 static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
584 {
585     av_free(bin->data);
586     if (!(bin->data = av_malloc(length)))
587         return AVERROR(ENOMEM);
588
589     bin->size = length;
590     bin->pos  = url_ftell(pb);
591     if (get_buffer(pb, bin->data, length) != length)
592         return AVERROR(EIO);
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 signed/unsigned "EBML" numbers.
622  * Return: number of bytes processed, < 0 on error.
623  */
624 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
625                                  uint8_t *data, uint32_t size, uint64_t *num)
626 {
627     ByteIOContext pb;
628     init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
629     return ebml_read_num(matroska, &pb, 8, num);
630 }
631
632 /*
633  * Same as above, but signed.
634  */
635 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
636                                  uint8_t *data, uint32_t size, int64_t *num)
637 {
638     uint64_t unum;
639     int res;
640
641     /* read as unsigned number first */
642     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
643         return res;
644
645     /* make signed (weird way) */
646     *num = unum - ((1LL << (7*res - 1)) - 1);
647
648     return res;
649 }
650
651 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
652                            EbmlSyntax *syntax, void *data);
653
654 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
655                          uint32_t id, void *data)
656 {
657     int i;
658     for (i=0; syntax[i].id; i++)
659         if (id == syntax[i].id)
660             break;
661     if (!syntax[i].id)
662         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
663     return ebml_parse_elem(matroska, &syntax[i], data);
664 }
665
666 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
667                       void *data)
668 {
669     uint64_t id;
670     int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
671     id |= 1 << 7*res;
672     return res < 0 ? res : ebml_parse_id(matroska, syntax, id, data);
673 }
674
675 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
676                            void *data)
677 {
678     int i, res = 0;
679
680     for (i=0; syntax[i].id; i++)
681         switch (syntax[i].type) {
682         case EBML_UINT:
683             *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
684             break;
685         case EBML_FLOAT:
686             *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
687             break;
688         case EBML_STR:
689         case EBML_UTF8:
690             *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
691             break;
692         }
693
694     while (!res && !ebml_level_end(matroska))
695         res = ebml_parse(matroska, syntax, data);
696
697     return res;
698 }
699
700 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
701                            EbmlSyntax *syntax, void *data)
702 {
703     ByteIOContext *pb = matroska->ctx->pb;
704     uint32_t id = syntax->id;
705     uint64_t length;
706     int res;
707
708     data = (char *)data + syntax->data_offset;
709     if (syntax->list_elem_size) {
710         EbmlList *list = data;
711         list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
712         data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
713         memset(data, 0, syntax->list_elem_size);
714         list->nb_elem++;
715     }
716
717     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
718         if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
719             return res;
720
721     switch (syntax->type) {
722     case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
723     case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
724     case EBML_STR:
725     case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
726     case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
727     case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
728                          return res;
729                      if (id == MATROSKA_ID_SEGMENT)
730                          matroska->segment_start = url_ftell(matroska->ctx->pb);
731                      return ebml_parse_nest(matroska, syntax->def.n, data);
732     case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
733     case EBML_STOP:  *(int *)data = 1;      return 1;
734     default:         url_fskip(pb, length); return 0;
735     }
736     if (res == AVERROR_INVALIDDATA)
737         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
738     else if (res == AVERROR(EIO))
739         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
740     return res;
741 }
742
743 static void ebml_free(EbmlSyntax *syntax, void *data)
744 {
745     int i, j;
746     for (i=0; syntax[i].id; i++) {
747         void *data_off = (char *)data + syntax[i].data_offset;
748         switch (syntax[i].type) {
749         case EBML_STR:
750         case EBML_UTF8:  av_freep(data_off);                      break;
751         case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
752         case EBML_NEST:
753             if (syntax[i].list_elem_size) {
754                 EbmlList *list = data_off;
755                 char *ptr = list->elem;
756                 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
757                     ebml_free(syntax[i].def.n, ptr);
758                 av_free(list->elem);
759             } else
760                 ebml_free(syntax[i].def.n, data_off);
761         default:  break;
762         }
763     }
764 }
765
766
767 /*
768  * Autodetecting...
769  */
770 static int matroska_probe(AVProbeData *p)
771 {
772     uint64_t total = 0;
773     int len_mask = 0x80, size = 1, n = 1;
774     char probe_data[] = "matroska";
775
776     /* ebml header? */
777     if (AV_RB32(p->buf) != EBML_ID_HEADER)
778         return 0;
779
780     /* length of header */
781     total = p->buf[4];
782     while (size <= 8 && !(total & len_mask)) {
783         size++;
784         len_mask >>= 1;
785     }
786     if (size > 8)
787       return 0;
788     total &= (len_mask - 1);
789     while (n < size)
790         total = (total << 8) | p->buf[4 + n++];
791
792     /* does the probe data contain the whole header? */
793     if (p->buf_size < 4 + size + total)
794       return 0;
795
796     /* the header must contain the document type 'matroska'. For now,
797      * we don't parse the whole header but simply check for the
798      * availability of that array of characters inside the header.
799      * Not fully fool-proof, but good enough. */
800     for (n = 4+size; n <= 4+size+total-(sizeof(probe_data)-1); n++)
801         if (!memcmp(p->buf+n, probe_data, sizeof(probe_data)-1))
802             return AVPROBE_SCORE_MAX;
803
804     return 0;
805 }
806
807 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
808                                                  int num)
809 {
810     MatroskaTrack *tracks = matroska->tracks.elem;
811     int i;
812
813     for (i=0; i < matroska->tracks.nb_elem; i++)
814         if (tracks[i].num == num)
815             return &tracks[i];
816
817     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
818     return NULL;
819 }
820
821 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
822                                   MatroskaTrack *track)
823 {
824     MatroskaTrackEncoding *encodings = track->encodings.elem;
825     uint8_t* data = *buf;
826     int isize = *buf_size;
827     uint8_t* pkt_data = NULL;
828     int pkt_size = isize;
829     int result = 0;
830     int olen;
831
832     switch (encodings[0].compression.algo) {
833     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
834         return encodings[0].compression.settings.size;
835     case MATROSKA_TRACK_ENCODING_COMP_LZO:
836         do {
837             olen = pkt_size *= 3;
838             pkt_data = av_realloc(pkt_data,
839                                   pkt_size+LZO_OUTPUT_PADDING);
840             result = lzo1x_decode(pkt_data, &olen, data, &isize);
841         } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
842         if (result)
843             goto failed;
844         pkt_size -= olen;
845         break;
846 #ifdef CONFIG_ZLIB
847     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
848         z_stream zstream = {0};
849         if (inflateInit(&zstream) != Z_OK)
850             return -1;
851         zstream.next_in = data;
852         zstream.avail_in = isize;
853         do {
854             pkt_size *= 3;
855             pkt_data = av_realloc(pkt_data, pkt_size);
856             zstream.avail_out = pkt_size - zstream.total_out;
857             zstream.next_out = pkt_data + zstream.total_out;
858             result = inflate(&zstream, Z_NO_FLUSH);
859         } while (result==Z_OK && pkt_size<10000000);
860         pkt_size = zstream.total_out;
861         inflateEnd(&zstream);
862         if (result != Z_STREAM_END)
863             goto failed;
864         break;
865     }
866 #endif
867 #ifdef CONFIG_BZLIB
868     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
869         bz_stream bzstream = {0};
870         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
871             return -1;
872         bzstream.next_in = data;
873         bzstream.avail_in = isize;
874         do {
875             pkt_size *= 3;
876             pkt_data = av_realloc(pkt_data, pkt_size);
877             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
878             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
879             result = BZ2_bzDecompress(&bzstream);
880         } while (result==BZ_OK && pkt_size<10000000);
881         pkt_size = bzstream.total_out_lo32;
882         BZ2_bzDecompressEnd(&bzstream);
883         if (result != BZ_STREAM_END)
884             goto failed;
885         break;
886     }
887 #endif
888     }
889
890     *buf = pkt_data;
891     *buf_size = pkt_size;
892     return 0;
893  failed:
894     av_free(pkt_data);
895     return -1;
896 }
897
898 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
899 {
900     EbmlList *seekhead_list = &matroska->seekhead;
901     MatroskaSeekhead *seekhead = seekhead_list->elem;
902     uint32_t level_up = matroska->level_up;
903     offset_t before_pos = url_ftell(matroska->ctx->pb);
904     MatroskaLevel level;
905     int i;
906
907     for (i=0; i<seekhead_list->nb_elem; i++) {
908         offset_t offset = seekhead[i].pos + matroska->segment_start;
909
910         if (seekhead[i].pos <= before_pos
911             || seekhead[i].id == MATROSKA_ID_SEEKHEAD
912             || seekhead[i].id == MATROSKA_ID_CLUSTER)
913             continue;
914
915         /* seek */
916         if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
917             continue;
918
919         /* we don't want to lose our seekhead level, so we add
920          * a dummy. This is a crude hack. */
921         if (matroska->num_levels == EBML_MAX_DEPTH) {
922             av_log(matroska->ctx, AV_LOG_INFO,
923                    "Max EBML element depth (%d) reached, "
924                    "cannot parse further.\n", EBML_MAX_DEPTH);
925             break;
926         }
927
928         level.start = 0;
929         level.length = (uint64_t)-1;
930         matroska->levels[matroska->num_levels] = level;
931         matroska->num_levels++;
932
933         ebml_parse(matroska, matroska_segment, matroska);
934
935         /* remove dummy level */
936         while (matroska->num_levels) {
937             uint64_t length = matroska->levels[--matroska->num_levels].length;
938             if (length == (uint64_t)-1)
939                 break;
940         }
941     }
942
943     /* seek back */
944     url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
945     matroska->level_up = level_up;
946 }
947
948 static int matroska_aac_profile(char *codec_id)
949 {
950     static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
951     int profile;
952
953     for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
954         if (strstr(codec_id, aac_profiles[profile]))
955             break;
956     return profile + 1;
957 }
958
959 static int matroska_aac_sri(int samplerate)
960 {
961     int sri;
962
963     for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
964         if (ff_mpeg4audio_sample_rates[sri] == samplerate)
965             break;
966     return sri;
967 }
968
969 static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
970 {
971     MatroskaDemuxContext *matroska = s->priv_data;
972     EbmlList *attachements_list = &matroska->attachments;
973     MatroskaAttachement *attachements;
974     EbmlList *chapters_list = &matroska->chapters;
975     MatroskaChapter *chapters;
976     MatroskaTrack *tracks;
977     EbmlList *index_list;
978     MatroskaIndex *index;
979     Ebml ebml = { 0 };
980     AVStream *st;
981     int i, j;
982
983     matroska->ctx = s;
984
985     /* First read the EBML header. */
986     if (ebml_parse(matroska, ebml_syntax, &ebml)
987         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
988         || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
989         || ebml.doctype_version > 2) {
990         av_log(matroska->ctx, AV_LOG_ERROR,
991                "EBML header using unsupported features\n"
992                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
993                ebml.version, ebml.doctype, ebml.doctype_version);
994         return AVERROR_NOFMT;
995     }
996     ebml_free(ebml_syntax, &ebml);
997
998     /* The next thing is a segment. */
999     if (ebml_parse(matroska, matroska_segments, matroska) < 0)
1000         return -1;
1001     matroska_execute_seekhead(matroska);
1002
1003     if (matroska->duration)
1004         matroska->ctx->duration = matroska->duration * matroska->time_scale
1005                                   * 1000 / AV_TIME_BASE;
1006     if (matroska->title)
1007         strncpy(matroska->ctx->title, matroska->title,
1008                 sizeof(matroska->ctx->title)-1);
1009
1010     tracks = matroska->tracks.elem;
1011     for (i=0; i < matroska->tracks.nb_elem; i++) {
1012         MatroskaTrack *track = &tracks[i];
1013         enum CodecID codec_id = CODEC_ID_NONE;
1014         EbmlList *encodings_list = &tracks->encodings;
1015         MatroskaTrackEncoding *encodings = encodings_list->elem;
1016         uint8_t *extradata = NULL;
1017         int extradata_size = 0;
1018         int extradata_offset = 0;
1019
1020         /* Apply some sanity checks. */
1021         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1022             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1023             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1024             av_log(matroska->ctx, AV_LOG_INFO,
1025                    "Unknown or unsupported track type %"PRIu64"\n",
1026                    track->type);
1027             continue;
1028         }
1029         if (track->codec_id == NULL)
1030             continue;
1031
1032         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1033             if (!track->default_duration)
1034                 track->default_duration = 1000000000/track->video.frame_rate;
1035             if (!track->video.display_width)
1036                 track->video.display_width = track->video.pixel_width;
1037             if (!track->video.display_height)
1038                 track->video.display_height = track->video.pixel_height;
1039         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1040             if (!track->audio.out_samplerate)
1041                 track->audio.out_samplerate = track->audio.samplerate;
1042         }
1043         if (encodings_list->nb_elem > 1) {
1044             av_log(matroska->ctx, AV_LOG_ERROR,
1045                    "Multiple combined encodings no supported");
1046         } else if (encodings_list->nb_elem == 1) {
1047             if (encodings[0].type ||
1048                 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1049 #ifdef CONFIG_ZLIB
1050                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1051 #endif
1052 #ifdef CONFIG_BZLIB
1053                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1054 #endif
1055                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1056                 encodings[0].scope = 0;
1057                 av_log(matroska->ctx, AV_LOG_ERROR,
1058                        "Unsupported encoding type");
1059             } else if (track->codec_priv.size && encodings[0].scope&2) {
1060                 uint8_t *codec_priv = track->codec_priv.data;
1061                 int offset = matroska_decode_buffer(&track->codec_priv.data,
1062                                                     &track->codec_priv.size,
1063                                                     track);
1064                 if (offset < 0) {
1065                     track->codec_priv.data = NULL;
1066                     track->codec_priv.size = 0;
1067                     av_log(matroska->ctx, AV_LOG_ERROR,
1068                            "Failed to decode codec private data\n");
1069                 } else if (offset > 0) {
1070                     track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1071                     memcpy(track->codec_priv.data,
1072                            encodings[0].compression.settings.data, offset);
1073                     memcpy(track->codec_priv.data+offset, codec_priv,
1074                            track->codec_priv.size);
1075                     track->codec_priv.size += offset;
1076                 }
1077                 if (codec_priv != track->codec_priv.data)
1078                     av_free(codec_priv);
1079             }
1080         }
1081
1082         for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1083             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1084                         strlen(ff_mkv_codec_tags[j].str))){
1085                 codec_id= ff_mkv_codec_tags[j].id;
1086                 break;
1087             }
1088         }
1089
1090         st = track->stream = av_new_stream(s, matroska->num_streams++);
1091         if (st == NULL)
1092             return AVERROR(ENOMEM);
1093
1094         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1095             && track->codec_priv.size >= 40
1096             && track->codec_priv.data != NULL) {
1097             track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1098             codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1099         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1100                    && track->codec_priv.size >= 18
1101                    && track->codec_priv.data != NULL) {
1102             uint16_t tag = AV_RL16(track->codec_priv.data);
1103             codec_id = codec_get_id(codec_wav_tags, tag);
1104         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1105                    && (track->codec_priv.size >= 86)
1106                    && (track->codec_priv.data != NULL)) {
1107             track->video.fourcc = AV_RL32(track->codec_priv.data);
1108             codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1109         } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1110             int profile = matroska_aac_profile(track->codec_id);
1111             int sri = matroska_aac_sri(track->audio.samplerate);
1112             extradata = av_malloc(5);
1113             if (extradata == NULL)
1114                 return AVERROR(ENOMEM);
1115             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1116             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1117             if (strstr(track->codec_id, "SBR")) {
1118                 sri = matroska_aac_sri(track->audio.out_samplerate);
1119                 extradata[2] = 0x56;
1120                 extradata[3] = 0xE5;
1121                 extradata[4] = 0x80 | (sri<<3);
1122                 extradata_size = 5;
1123             } else
1124                 extradata_size = 2;
1125         } else if (codec_id == CODEC_ID_TTA) {
1126             ByteIOContext b;
1127             extradata_size = 30;
1128             extradata = av_mallocz(extradata_size);
1129             if (extradata == NULL)
1130                 return AVERROR(ENOMEM);
1131             init_put_byte(&b, extradata, extradata_size, 1,
1132                           NULL, NULL, NULL, NULL);
1133             put_buffer(&b, "TTA1", 4);
1134             put_le16(&b, 1);
1135             put_le16(&b, track->audio.channels);
1136             put_le16(&b, track->audio.bitdepth);
1137             put_le32(&b, track->audio.out_samplerate);
1138             put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1139         } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1140                    codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1141             extradata_offset = 26;
1142             track->codec_priv.size -= extradata_offset;
1143         } else if (codec_id == CODEC_ID_RA_144) {
1144             track->audio.out_samplerate = 8000;
1145             track->audio.channels = 1;
1146         } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1147                    codec_id == CODEC_ID_ATRAC3) {
1148             ByteIOContext b;
1149
1150             init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1151                           0, NULL, NULL, NULL, NULL);
1152             url_fskip(&b, 24);
1153             track->audio.coded_framesize = get_be32(&b);
1154             url_fskip(&b, 12);
1155             track->audio.sub_packet_h    = get_be16(&b);
1156             track->audio.frame_size      = get_be16(&b);
1157             track->audio.sub_packet_size = get_be16(&b);
1158             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1159             if (codec_id == CODEC_ID_RA_288) {
1160                 st->codec->block_align = track->audio.coded_framesize;
1161                 track->codec_priv.size = 0;
1162             } else {
1163                 st->codec->block_align = track->audio.sub_packet_size;
1164                 extradata_offset = 78;
1165                 track->codec_priv.size -= extradata_offset;
1166             }
1167         }
1168
1169         if (codec_id == CODEC_ID_NONE)
1170             av_log(matroska->ctx, AV_LOG_INFO,
1171                    "Unknown/unsupported CodecID %s.\n", track->codec_id);
1172
1173         av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1174
1175         st->codec->codec_id = codec_id;
1176         st->start_time = 0;
1177         if (strcmp(track->language, "und"))
1178             av_strlcpy(st->language, track->language, 4);
1179
1180         if (track->flag_default)
1181             st->disposition |= AV_DISPOSITION_DEFAULT;
1182
1183         if (track->default_duration)
1184             av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1185                       track->default_duration, 1000000000, 30000);
1186
1187         if(extradata){
1188             st->codec->extradata = extradata;
1189             st->codec->extradata_size = extradata_size;
1190         } else if(track->codec_priv.data && track->codec_priv.size > 0){
1191             st->codec->extradata = av_malloc(track->codec_priv.size);
1192             if(st->codec->extradata == NULL)
1193                 return AVERROR(ENOMEM);
1194             st->codec->extradata_size = track->codec_priv.size;
1195             memcpy(st->codec->extradata,
1196                    track->codec_priv.data + extradata_offset,
1197                    track->codec_priv.size);
1198         }
1199
1200         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1201             st->codec->codec_type = CODEC_TYPE_VIDEO;
1202             st->codec->codec_tag  = track->video.fourcc;
1203             st->codec->width  = track->video.pixel_width;
1204             st->codec->height = track->video.pixel_height;
1205             av_reduce(&st->codec->sample_aspect_ratio.num,
1206                       &st->codec->sample_aspect_ratio.den,
1207                       st->codec->height * track->video.display_width,
1208                       st->codec-> width * track->video.display_height,
1209                       255);
1210             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1211         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1212             st->codec->codec_type = CODEC_TYPE_AUDIO;
1213             st->codec->sample_rate = track->audio.out_samplerate;
1214             st->codec->channels = track->audio.channels;
1215         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1216             st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1217         }
1218     }
1219
1220     attachements = attachements_list->elem;
1221     for (j=0; j<attachements_list->nb_elem; j++) {
1222         if (!(attachements[j].filename && attachements[j].mime &&
1223               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1224             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1225         } else {
1226             AVStream *st = av_new_stream(s, matroska->num_streams++);
1227             if (st == NULL)
1228                 break;
1229             st->filename          = av_strdup(attachements[j].filename);
1230             st->codec->codec_id = CODEC_ID_NONE;
1231             st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1232             st->codec->extradata  = av_malloc(attachements[j].bin.size);
1233             if(st->codec->extradata == NULL)
1234                 break;
1235             st->codec->extradata_size = attachements[j].bin.size;
1236             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1237
1238             for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1239                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1240                              strlen(ff_mkv_mime_tags[i].str))) {
1241                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1242                     break;
1243                 }
1244             }
1245         }
1246     }
1247
1248     chapters = chapters_list->elem;
1249     for (i=0; i<chapters_list->nb_elem; i++)
1250         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1251             ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1252                            chapters[i].start, chapters[i].end,
1253                            chapters[i].title);
1254
1255     index_list = &matroska->index;
1256     index = index_list->elem;
1257     for (i=0; i<index_list->nb_elem; i++) {
1258         EbmlList *pos_list = &index[i].pos;
1259         MatroskaIndexPos *pos = pos_list->elem;
1260         for (j=0; j<pos_list->nb_elem; j++) {
1261             MatroskaTrack *track = matroska_find_track_by_num(matroska,
1262                                                               pos[j].track);
1263             if (track && track->stream)
1264                 av_add_index_entry(track->stream,
1265                                    pos[j].pos + matroska->segment_start,
1266                                    index[i].time*matroska->time_scale/AV_TIME_BASE,
1267                                    0, 0, AVINDEX_KEYFRAME);
1268         }
1269     }
1270
1271     return 0;
1272 }
1273
1274 /*
1275  * Put a packet into our internal queue. Will be delivered to the
1276  * user/application during the next get_packet() call.
1277  */
1278 static void matroska_queue_packet(MatroskaDemuxContext *matroska, AVPacket *pkt)
1279 {
1280     matroska->packets =
1281         av_realloc(matroska->packets, (matroska->num_packets + 1) *
1282                    sizeof(AVPacket *));
1283     matroska->packets[matroska->num_packets] = pkt;
1284     matroska->num_packets++;
1285 }
1286
1287 /*
1288  * Put one packet in an application-supplied AVPacket struct.
1289  * Returns 0 on success or -1 on failure.
1290  */
1291 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1292                                    AVPacket *pkt)
1293 {
1294     if (matroska->num_packets > 0) {
1295         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1296         av_free(matroska->packets[0]);
1297         if (matroska->num_packets > 1) {
1298             memmove(&matroska->packets[0], &matroska->packets[1],
1299                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1300             matroska->packets =
1301                 av_realloc(matroska->packets, (matroska->num_packets - 1) *
1302                            sizeof(AVPacket *));
1303         } else {
1304             av_freep(&matroska->packets);
1305         }
1306         matroska->num_packets--;
1307         return 0;
1308     }
1309
1310     return -1;
1311 }
1312
1313 /*
1314  * Free all packets in our internal queue.
1315  */
1316 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1317 {
1318     if (matroska->packets) {
1319         int n;
1320         for (n = 0; n < matroska->num_packets; n++) {
1321             av_free_packet(matroska->packets[n]);
1322             av_free(matroska->packets[n]);
1323         }
1324         av_free(matroska->packets);
1325         matroska->packets = NULL;
1326         matroska->num_packets = 0;
1327     }
1328 }
1329
1330 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1331                                 int size, int64_t pos, uint64_t cluster_time,
1332                                 uint64_t duration, int is_keyframe)
1333 {
1334     MatroskaTrack *track;
1335     int res = 0;
1336     AVStream *st;
1337     AVPacket *pkt;
1338     int16_t block_time;
1339     uint32_t *lace_size = NULL;
1340     int n, flags, laces = 0;
1341     uint64_t num;
1342
1343     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1344         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1345         return res;
1346     }
1347     data += n;
1348     size -= n;
1349
1350     track = matroska_find_track_by_num(matroska, num);
1351     if (size <= 3 || !track || !track->stream) {
1352         av_log(matroska->ctx, AV_LOG_INFO,
1353                "Invalid stream %"PRIu64" or size %u\n", num, size);
1354         return res;
1355     }
1356     st = track->stream;
1357     if (st->discard >= AVDISCARD_ALL)
1358         return res;
1359     if (duration == AV_NOPTS_VALUE)
1360         duration = track->default_duration / matroska->time_scale;
1361
1362     block_time = AV_RB16(data);
1363     data += 2;
1364     flags = *data++;
1365     size -= 3;
1366     if (is_keyframe == -1)
1367         is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1368
1369     if (matroska->skip_to_keyframe) {
1370         if (!is_keyframe || st != matroska->skip_to_stream)
1371             return res;
1372         matroska->skip_to_keyframe = 0;
1373     }
1374
1375     switch ((flags & 0x06) >> 1) {
1376         case 0x0: /* no lacing */
1377             laces = 1;
1378             lace_size = av_mallocz(sizeof(int));
1379             lace_size[0] = size;
1380             break;
1381
1382         case 0x1: /* xiph lacing */
1383         case 0x2: /* fixed-size lacing */
1384         case 0x3: /* EBML lacing */
1385             assert(size>0); // size <=3 is checked before size-=3 above
1386             laces = (*data) + 1;
1387             data += 1;
1388             size -= 1;
1389             lace_size = av_mallocz(laces * sizeof(int));
1390
1391             switch ((flags & 0x06) >> 1) {
1392                 case 0x1: /* xiph lacing */ {
1393                     uint8_t temp;
1394                     uint32_t total = 0;
1395                     for (n = 0; res == 0 && n < laces - 1; n++) {
1396                         while (1) {
1397                             if (size == 0) {
1398                                 res = -1;
1399                                 break;
1400                             }
1401                             temp = *data;
1402                             lace_size[n] += temp;
1403                             data += 1;
1404                             size -= 1;
1405                             if (temp != 0xff)
1406                                 break;
1407                         }
1408                         total += lace_size[n];
1409                     }
1410                     lace_size[n] = size - total;
1411                     break;
1412                 }
1413
1414                 case 0x2: /* fixed-size lacing */
1415                     for (n = 0; n < laces; n++)
1416                         lace_size[n] = size / laces;
1417                     break;
1418
1419                 case 0x3: /* EBML lacing */ {
1420                     uint32_t total;
1421                     n = matroska_ebmlnum_uint(matroska, data, size, &num);
1422                     if (n < 0) {
1423                         av_log(matroska->ctx, AV_LOG_INFO,
1424                                "EBML block data error\n");
1425                         break;
1426                     }
1427                     data += n;
1428                     size -= n;
1429                     total = lace_size[0] = num;
1430                     for (n = 1; res == 0 && n < laces - 1; n++) {
1431                         int64_t snum;
1432                         int r;
1433                         r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1434                         if (r < 0) {
1435                             av_log(matroska->ctx, AV_LOG_INFO,
1436                                    "EBML block data error\n");
1437                             break;
1438                         }
1439                         data += r;
1440                         size -= r;
1441                         lace_size[n] = lace_size[n - 1] + snum;
1442                         total += lace_size[n];
1443                     }
1444                     lace_size[n] = size - total;
1445                     break;
1446                 }
1447             }
1448             break;
1449     }
1450
1451     if (res == 0) {
1452         uint64_t timecode = AV_NOPTS_VALUE;
1453
1454         if (cluster_time != (uint64_t)-1
1455             && (block_time >= 0 || cluster_time >= -block_time))
1456             timecode = cluster_time + block_time;
1457
1458         for (n = 0; n < laces; n++) {
1459             if (st->codec->codec_id == CODEC_ID_RA_288 ||
1460                 st->codec->codec_id == CODEC_ID_COOK ||
1461                 st->codec->codec_id == CODEC_ID_ATRAC3) {
1462                 int a = st->codec->block_align;
1463                 int sps = track->audio.sub_packet_size;
1464                 int cfs = track->audio.coded_framesize;
1465                 int h = track->audio.sub_packet_h;
1466                 int y = track->audio.sub_packet_cnt;
1467                 int w = track->audio.frame_size;
1468                 int x;
1469
1470                 if (!track->audio.pkt_cnt) {
1471                     if (st->codec->codec_id == CODEC_ID_RA_288)
1472                         for (x=0; x<h/2; x++)
1473                             memcpy(track->audio.buf+x*2*w+y*cfs,
1474                                    data+x*cfs, cfs);
1475                     else
1476                         for (x=0; x<w/sps; x++)
1477                             memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1478
1479                     if (++track->audio.sub_packet_cnt >= h) {
1480                         track->audio.sub_packet_cnt = 0;
1481                         track->audio.pkt_cnt = h*w / a;
1482                     }
1483                 }
1484                 while (track->audio.pkt_cnt) {
1485                     pkt = av_mallocz(sizeof(AVPacket));
1486                     av_new_packet(pkt, a);
1487                     memcpy(pkt->data, track->audio.buf
1488                            + a * (h*w / a - track->audio.pkt_cnt--), a);
1489                     pkt->pos = pos;
1490                     pkt->stream_index = st->index;
1491                     matroska_queue_packet(matroska, pkt);
1492                 }
1493             } else {
1494                 MatroskaTrackEncoding *encodings = track->encodings.elem;
1495                 int offset = 0, pkt_size = lace_size[n];
1496                 uint8_t *pkt_data = data;
1497
1498                 if (encodings && encodings->scope & 1) {
1499                     offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1500                     if (offset < 0)
1501                         continue;
1502                 }
1503
1504                 pkt = av_mallocz(sizeof(AVPacket));
1505                 /* XXX: prevent data copy... */
1506                 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1507                     av_free(pkt);
1508                     res = AVERROR(ENOMEM);
1509                     n = laces-1;
1510                     break;
1511                 }
1512                 if (offset)
1513                     memcpy (pkt->data, encodings->compression.settings.data, offset);
1514                 memcpy (pkt->data+offset, pkt_data, pkt_size);
1515
1516                 if (pkt_data != data)
1517                     av_free(pkt_data);
1518
1519                 if (n == 0)
1520                     pkt->flags = is_keyframe;
1521                 pkt->stream_index = st->index;
1522
1523                 pkt->pts = timecode;
1524                 pkt->pos = pos;
1525                 pkt->duration = duration;
1526
1527                 matroska_queue_packet(matroska, pkt);
1528             }
1529
1530             if (timecode != AV_NOPTS_VALUE)
1531                 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1532             data += lace_size[n];
1533         }
1534     }
1535
1536     av_free(lace_size);
1537     return res;
1538 }
1539
1540 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1541 {
1542     MatroskaCluster cluster = { 0 };
1543     EbmlList *blocks_list;
1544     MatroskaBlock *blocks;
1545     int i, res;
1546     if (matroska->has_cluster_id){
1547         /* For the first cluster we parse, it's ID was already read as
1548            part of matroska_read_header(), so don't read it again */
1549         res = ebml_parse_id(matroska, matroska_clusters,
1550                             MATROSKA_ID_CLUSTER, &cluster);
1551         matroska->has_cluster_id = 0;
1552     } else
1553         res = ebml_parse(matroska, matroska_clusters, &cluster);
1554     blocks_list = &cluster.blocks;
1555     blocks = blocks_list->elem;
1556     for (i=0; !res && i<blocks_list->nb_elem; i++)
1557         if (blocks[i].bin.size > 0)
1558             res=matroska_parse_block(matroska,
1559                                      blocks[i].bin.data, blocks[i].bin.size,
1560                                      blocks[i].bin.pos,  cluster.timecode,
1561                                      blocks[i].duration, !blocks[i].reference);
1562     ebml_free(matroska_cluster, &cluster);
1563     return res;
1564 }
1565
1566 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1567 {
1568     MatroskaDemuxContext *matroska = s->priv_data;
1569
1570     while (matroska_deliver_packet(matroska, pkt)) {
1571         if (matroska->done)
1572             return AVERROR(EIO);
1573         if (matroska_parse_cluster(matroska) < 0)
1574             matroska->done = 1;
1575     }
1576
1577     return 0;
1578 }
1579
1580 static int matroska_read_seek(AVFormatContext *s, int stream_index,
1581                               int64_t timestamp, int flags)
1582 {
1583     MatroskaDemuxContext *matroska = s->priv_data;
1584     AVStream *st = s->streams[stream_index];
1585     int index;
1586
1587     index = av_index_search_timestamp(st, timestamp, flags);
1588     if (index < 0)
1589         return 0;
1590
1591     matroska_clear_queue(matroska);
1592
1593     url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1594     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1595     matroska->skip_to_stream = st;
1596     av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1597     return 0;
1598 }
1599
1600 static int matroska_read_close(AVFormatContext *s)
1601 {
1602     MatroskaDemuxContext *matroska = s->priv_data;
1603     MatroskaTrack *tracks = matroska->tracks.elem;
1604     int n;
1605
1606     matroska_clear_queue(matroska);
1607
1608     for (n=0; n < matroska->tracks.nb_elem; n++)
1609         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1610             av_free(tracks[n].audio.buf);
1611     ebml_free(matroska_segment, matroska);
1612
1613     return 0;
1614 }
1615
1616 AVInputFormat matroska_demuxer = {
1617     "matroska",
1618     NULL_IF_CONFIG_SMALL("Matroska file format"),
1619     sizeof(MatroskaDemuxContext),
1620     matroska_probe,
1621     matroska_read_header,
1622     matroska_read_packet,
1623     matroska_read_close,
1624     matroska_read_seek,
1625 };