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