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