]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskadec.c
Merge commit '68f930d2188aba5b32624887dcbf688c23482834'
[ffmpeg] / 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  * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
26  * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
27  * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28  * @see 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 #include "avio_internal.h"
35 /* For ff_codec_get_id(). */
36 #include "riff.h"
37 #include "isom.h"
38 #include "rmsipr.h"
39 #include "matroska.h"
40 #include "libavcodec/bytestream.h"
41 #include "libavcodec/mpeg4audio.h"
42 #include "libavutil/intfloat.h"
43 #include "libavutil/intreadwrite.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/lzo.h"
46 #include "libavutil/dict.h"
47 #if CONFIG_ZLIB
48 #include <zlib.h>
49 #endif
50 #if CONFIG_BZLIB
51 #include <bzlib.h>
52 #endif
53
54 typedef enum {
55     EBML_NONE,
56     EBML_UINT,
57     EBML_FLOAT,
58     EBML_STR,
59     EBML_UTF8,
60     EBML_BIN,
61     EBML_NEST,
62     EBML_PASS,
63     EBML_STOP,
64     EBML_TYPE_COUNT
65 } EbmlType;
66
67 typedef const struct EbmlSyntax {
68     uint32_t id;
69     EbmlType type;
70     int list_elem_size;
71     int data_offset;
72     union {
73         uint64_t    u;
74         double      f;
75         const char *s;
76         const struct EbmlSyntax *n;
77     } def;
78 } EbmlSyntax;
79
80 typedef struct {
81     int nb_elem;
82     void *elem;
83 } EbmlList;
84
85 typedef struct {
86     int      size;
87     uint8_t *data;
88     int64_t  pos;
89 } EbmlBin;
90
91 typedef struct {
92     uint64_t version;
93     uint64_t max_size;
94     uint64_t id_length;
95     char    *doctype;
96     uint64_t doctype_version;
97 } Ebml;
98
99 typedef struct {
100     uint64_t algo;
101     EbmlBin  settings;
102 } MatroskaTrackCompression;
103
104 typedef struct {
105     uint64_t scope;
106     uint64_t type;
107     MatroskaTrackCompression compression;
108 } MatroskaTrackEncoding;
109
110 typedef struct {
111     double   frame_rate;
112     uint64_t display_width;
113     uint64_t display_height;
114     uint64_t pixel_width;
115     uint64_t pixel_height;
116     EbmlBin color_space;
117     uint64_t stereo_mode;
118     uint64_t alpha_mode;
119 } MatroskaTrackVideo;
120
121 typedef struct {
122     double   samplerate;
123     double   out_samplerate;
124     uint64_t bitdepth;
125     uint64_t channels;
126
127     /* real audio header (extracted from extradata) */
128     int      coded_framesize;
129     int      sub_packet_h;
130     int      frame_size;
131     int      sub_packet_size;
132     int      sub_packet_cnt;
133     int      pkt_cnt;
134     uint64_t buf_timecode;
135     uint8_t *buf;
136 } MatroskaTrackAudio;
137
138 typedef struct {
139     uint64_t uid;
140     uint64_t type;
141 } MatroskaTrackPlane;
142
143 typedef struct {
144     EbmlList combine_planes;
145 } MatroskaTrackOperation;
146
147 typedef struct {
148     uint64_t num;
149     uint64_t uid;
150     uint64_t type;
151     char    *name;
152     char    *codec_id;
153     EbmlBin  codec_priv;
154     char    *language;
155     double time_scale;
156     uint64_t default_duration;
157     uint64_t flag_default;
158     uint64_t flag_forced;
159     MatroskaTrackVideo video;
160     MatroskaTrackAudio audio;
161     MatroskaTrackOperation operation;
162     EbmlList encodings;
163
164     AVStream *stream;
165     int64_t end_timecode;
166     int ms_compat;
167     uint64_t max_block_additional_id;
168 } MatroskaTrack;
169
170 typedef struct {
171     uint64_t uid;
172     char *filename;
173     char *mime;
174     EbmlBin bin;
175
176     AVStream *stream;
177 } MatroskaAttachement;
178
179 typedef struct {
180     uint64_t start;
181     uint64_t end;
182     uint64_t uid;
183     char    *title;
184
185     AVChapter *chapter;
186 } MatroskaChapter;
187
188 typedef struct {
189     uint64_t track;
190     uint64_t pos;
191 } MatroskaIndexPos;
192
193 typedef struct {
194     uint64_t time;
195     EbmlList pos;
196 } MatroskaIndex;
197
198 typedef struct {
199     char *name;
200     char *string;
201     char *lang;
202     uint64_t def;
203     EbmlList sub;
204 } MatroskaTag;
205
206 typedef struct {
207     char    *type;
208     uint64_t typevalue;
209     uint64_t trackuid;
210     uint64_t chapteruid;
211     uint64_t attachuid;
212 } MatroskaTagTarget;
213
214 typedef struct {
215     MatroskaTagTarget target;
216     EbmlList tag;
217 } MatroskaTags;
218
219 typedef struct {
220     uint64_t id;
221     uint64_t pos;
222 } MatroskaSeekhead;
223
224 typedef struct {
225     uint64_t start;
226     uint64_t length;
227 } MatroskaLevel;
228
229 typedef struct {
230     uint64_t timecode;
231     EbmlList blocks;
232 } MatroskaCluster;
233
234 typedef struct {
235     AVFormatContext *ctx;
236
237     /* EBML stuff */
238     int num_levels;
239     MatroskaLevel levels[EBML_MAX_DEPTH];
240     int level_up;
241     uint32_t current_id;
242
243     uint64_t time_scale;
244     double   duration;
245     char    *title;
246     EbmlBin date_utc;
247     EbmlList tracks;
248     EbmlList attachments;
249     EbmlList chapters;
250     EbmlList index;
251     EbmlList tags;
252     EbmlList seekhead;
253
254     /* byte position of the segment inside the stream */
255     int64_t segment_start;
256
257     /* the packet queue */
258     AVPacket **packets;
259     int num_packets;
260     AVPacket *prev_pkt;
261
262     int done;
263
264     /* What to skip before effectively reading a packet. */
265     int skip_to_keyframe;
266     uint64_t skip_to_timecode;
267
268     /* File has a CUES element, but we defer parsing until it is needed. */
269     int cues_parsing_deferred;
270
271     int current_cluster_num_blocks;
272     int64_t current_cluster_pos;
273     MatroskaCluster current_cluster;
274
275     /* File has SSA subtitles which prevent incremental cluster parsing. */
276     int contains_ssa;
277 } MatroskaDemuxContext;
278
279 typedef struct {
280     uint64_t duration;
281     int64_t  reference;
282     uint64_t non_simple;
283     EbmlBin  bin;
284     uint64_t additional_id;
285     EbmlBin  additional;
286 } MatroskaBlock;
287
288 static EbmlSyntax ebml_header[] = {
289     { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
290     { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
291     { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
292     { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
293     { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
294     { EBML_ID_EBMLVERSION,            EBML_NONE },
295     { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
296     { 0 }
297 };
298
299 static EbmlSyntax ebml_syntax[] = {
300     { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
301     { 0 }
302 };
303
304 static EbmlSyntax matroska_info[] = {
305     { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
306     { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
307     { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
308     { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
309     { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
310     { MATROSKA_ID_DATEUTC,            EBML_BIN,  0, offsetof(MatroskaDemuxContext,date_utc) },
311     { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
312     { 0 }
313 };
314
315 static EbmlSyntax matroska_track_video[] = {
316     { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
317     { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
318     { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
319     { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
320     { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
321     { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_BIN,  0, offsetof(MatroskaTrackVideo,color_space) },
322     { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,stereo_mode) },
323     { MATROSKA_ID_VIDEOALPHAMODE,     EBML_UINT, 0, offsetof(MatroskaTrackVideo,alpha_mode) },
324     { MATROSKA_ID_VIDEOPIXELCROPB,    EBML_NONE },
325     { MATROSKA_ID_VIDEOPIXELCROPT,    EBML_NONE },
326     { MATROSKA_ID_VIDEOPIXELCROPL,    EBML_NONE },
327     { MATROSKA_ID_VIDEOPIXELCROPR,    EBML_NONE },
328     { MATROSKA_ID_VIDEODISPLAYUNIT,   EBML_NONE },
329     { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
330     { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
331     { 0 }
332 };
333
334 static EbmlSyntax matroska_track_audio[] = {
335     { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
336     { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
337     { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
338     { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
339     { 0 }
340 };
341
342 static EbmlSyntax matroska_track_encoding_compression[] = {
343     { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
344     { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
345     { 0 }
346 };
347
348 static EbmlSyntax matroska_track_encoding[] = {
349     { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
350     { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
351     { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
352     { MATROSKA_ID_ENCODINGORDER,      EBML_NONE },
353     { 0 }
354 };
355
356 static EbmlSyntax matroska_track_encodings[] = {
357     { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
358     { 0 }
359 };
360
361 static EbmlSyntax matroska_track_plane[] = {
362     { MATROSKA_ID_TRACKPLANEUID,  EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
363     { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
364     { 0 }
365 };
366
367 static EbmlSyntax matroska_track_combine_planes[] = {
368     { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n=matroska_track_plane} },
369     { 0 }
370 };
371
372 static EbmlSyntax matroska_track_operation[] = {
373     { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n=matroska_track_combine_planes} },
374     { 0 }
375 };
376
377 static EbmlSyntax matroska_track[] = {
378     { MATROSKA_ID_TRACKNUMBER,          EBML_UINT, 0, offsetof(MatroskaTrack,num) },
379     { MATROSKA_ID_TRACKNAME,            EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
380     { MATROSKA_ID_TRACKUID,             EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
381     { MATROSKA_ID_TRACKTYPE,            EBML_UINT, 0, offsetof(MatroskaTrack,type) },
382     { MATROSKA_ID_CODECID,              EBML_STR,  0, offsetof(MatroskaTrack,codec_id) },
383     { MATROSKA_ID_CODECPRIVATE,         EBML_BIN,  0, offsetof(MatroskaTrack,codec_priv) },
384     { MATROSKA_ID_TRACKLANGUAGE,        EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
385     { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
386     { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
387     { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
388     { MATROSKA_ID_TRACKFLAGFORCED,      EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
389     { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
390     { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
391     { MATROSKA_ID_TRACKOPERATION,       EBML_NEST, 0, offsetof(MatroskaTrack,operation), {.n=matroska_track_operation} },
392     { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
393     { MATROSKA_ID_TRACKMAXBLKADDID,     EBML_UINT, 0, offsetof(MatroskaTrack,max_block_additional_id) },
394     { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
395     { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
396     { MATROSKA_ID_CODECNAME,            EBML_NONE },
397     { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
398     { MATROSKA_ID_CODECINFOURL,         EBML_NONE },
399     { MATROSKA_ID_CODECDOWNLOADURL,     EBML_NONE },
400     { MATROSKA_ID_TRACKMINCACHE,        EBML_NONE },
401     { MATROSKA_ID_TRACKMAXCACHE,        EBML_NONE },
402     { 0 }
403 };
404
405 static EbmlSyntax matroska_tracks[] = {
406     { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
407     { 0 }
408 };
409
410 static EbmlSyntax matroska_attachment[] = {
411     { MATROSKA_ID_FILEUID,            EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
412     { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
413     { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
414     { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
415     { MATROSKA_ID_FILEDESC,           EBML_NONE },
416     { 0 }
417 };
418
419 static EbmlSyntax matroska_attachments[] = {
420     { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
421     { 0 }
422 };
423
424 static EbmlSyntax matroska_chapter_display[] = {
425     { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
426     { MATROSKA_ID_CHAPLANG,           EBML_NONE },
427     { 0 }
428 };
429
430 static EbmlSyntax matroska_chapter_entry[] = {
431     { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
432     { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
433     { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
434     { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
435     { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
436     { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
437     { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
438     { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
439     { 0 }
440 };
441
442 static EbmlSyntax matroska_chapter[] = {
443     { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
444     { MATROSKA_ID_EDITIONUID,         EBML_NONE },
445     { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
446     { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
447     { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
448     { 0 }
449 };
450
451 static EbmlSyntax matroska_chapters[] = {
452     { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
453     { 0 }
454 };
455
456 static EbmlSyntax matroska_index_pos[] = {
457     { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
458     { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
459     { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
460     { 0 }
461 };
462
463 static EbmlSyntax matroska_index_entry[] = {
464     { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
465     { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
466     { 0 }
467 };
468
469 static EbmlSyntax matroska_index[] = {
470     { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
471     { 0 }
472 };
473
474 static EbmlSyntax matroska_simpletag[] = {
475     { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
476     { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
477     { MATROSKA_ID_TAGLANG,            EBML_STR,  0, offsetof(MatroskaTag,lang), {.s="und"} },
478     { MATROSKA_ID_TAGDEFAULT,         EBML_UINT, 0, offsetof(MatroskaTag,def) },
479     { MATROSKA_ID_TAGDEFAULT_BUG,     EBML_UINT, 0, offsetof(MatroskaTag,def) },
480     { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
481     { 0 }
482 };
483
484 static EbmlSyntax matroska_tagtargets[] = {
485     { MATROSKA_ID_TAGTARGETS_TYPE,      EBML_STR,  0, offsetof(MatroskaTagTarget,type) },
486     { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
487     { MATROSKA_ID_TAGTARGETS_TRACKUID,  EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
488     { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
489     { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
490     { 0 }
491 };
492
493 static EbmlSyntax matroska_tag[] = {
494     { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
495     { MATROSKA_ID_TAGTARGETS,         EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
496     { 0 }
497 };
498
499 static EbmlSyntax matroska_tags[] = {
500     { MATROSKA_ID_TAG,                EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
501     { 0 }
502 };
503
504 static EbmlSyntax matroska_seekhead_entry[] = {
505     { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
506     { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
507     { 0 }
508 };
509
510 static EbmlSyntax matroska_seekhead[] = {
511     { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
512     { 0 }
513 };
514
515 static EbmlSyntax matroska_segment[] = {
516     { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
517     { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
518     { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
519     { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
520     { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
521     { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
522     { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
523     { MATROSKA_ID_CLUSTER,        EBML_STOP },
524     { 0 }
525 };
526
527 static EbmlSyntax matroska_segments[] = {
528     { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
529     { 0 }
530 };
531
532 static EbmlSyntax matroska_blockmore[] = {
533     { MATROSKA_ID_BLOCKADDID,      EBML_UINT, 0, offsetof(MatroskaBlock,additional_id) },
534     { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN,  0, offsetof(MatroskaBlock,additional) },
535     { 0 }
536 };
537
538 static EbmlSyntax matroska_blockadditions[] = {
539     { MATROSKA_ID_BLOCKMORE, EBML_NEST, 0, 0, {.n=matroska_blockmore} },
540     { 0 }
541 };
542
543 static EbmlSyntax matroska_blockgroup[] = {
544     { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
545     { MATROSKA_ID_BLOCKADDITIONS, EBML_NEST, 0, 0, {.n=matroska_blockadditions} },
546     { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
547     { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration) },
548     { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
549     { 1,                          EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
550     { 0 }
551 };
552
553 static EbmlSyntax matroska_cluster[] = {
554     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
555     { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
556     { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
557     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
558     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
559     { 0 }
560 };
561
562 static EbmlSyntax matroska_clusters[] = {
563     { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
564     { MATROSKA_ID_INFO,           EBML_NONE },
565     { MATROSKA_ID_CUES,           EBML_NONE },
566     { MATROSKA_ID_TAGS,           EBML_NONE },
567     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
568     { 0 }
569 };
570
571 static EbmlSyntax matroska_cluster_incremental_parsing[] = {
572     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
573     { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
574     { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
575     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
576     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
577     { MATROSKA_ID_INFO,           EBML_NONE },
578     { MATROSKA_ID_CUES,           EBML_NONE },
579     { MATROSKA_ID_TAGS,           EBML_NONE },
580     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
581     { MATROSKA_ID_CLUSTER,        EBML_STOP },
582     { 0 }
583 };
584
585 static EbmlSyntax matroska_cluster_incremental[] = {
586     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
587     { MATROSKA_ID_BLOCKGROUP,     EBML_STOP },
588     { MATROSKA_ID_SIMPLEBLOCK,    EBML_STOP },
589     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
590     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
591     { 0 }
592 };
593
594 static EbmlSyntax matroska_clusters_incremental[] = {
595     { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
596     { MATROSKA_ID_INFO,           EBML_NONE },
597     { MATROSKA_ID_CUES,           EBML_NONE },
598     { MATROSKA_ID_TAGS,           EBML_NONE },
599     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
600     { 0 }
601 };
602
603 static const char *const matroska_doctypes[] = { "matroska", "webm" };
604
605 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
606 {
607     AVIOContext *pb = matroska->ctx->pb;
608     uint32_t id;
609     matroska->current_id = 0;
610     matroska->num_levels = 0;
611
612     // seek to next position to resync from
613     if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0 || avio_tell(pb) <= last_pos)
614         goto eof;
615
616     id = avio_rb32(pb);
617
618     // try to find a toplevel element
619     while (!url_feof(pb)) {
620         if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
621             id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
622             id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
623             id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS)
624         {
625             matroska->current_id = id;
626             return 0;
627         }
628         id = (id << 8) | avio_r8(pb);
629     }
630 eof:
631     matroska->done = 1;
632     return AVERROR_EOF;
633 }
634
635 /*
636  * Return: Whether we reached the end of a level in the hierarchy or not.
637  */
638 static int ebml_level_end(MatroskaDemuxContext *matroska)
639 {
640     AVIOContext *pb = matroska->ctx->pb;
641     int64_t pos = avio_tell(pb);
642
643     if (matroska->num_levels > 0) {
644         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
645         if (pos - level->start >= level->length || matroska->current_id) {
646             matroska->num_levels--;
647             return 1;
648         }
649     }
650     return 0;
651 }
652
653 /*
654  * Read: an "EBML number", which is defined as a variable-length
655  * array of bytes. The first byte indicates the length by giving a
656  * number of 0-bits followed by a one. The position of the first
657  * "one" bit inside the first byte indicates the length of this
658  * number.
659  * Returns: number of bytes read, < 0 on error
660  */
661 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
662                          int max_size, uint64_t *number)
663 {
664     int read = 1, n = 1;
665     uint64_t total = 0;
666
667     /* The first byte tells us the length in bytes - avio_r8() can normally
668      * return 0, but since that's not a valid first ebmlID byte, we can
669      * use it safely here to catch EOS. */
670     if (!(total = avio_r8(pb))) {
671         /* we might encounter EOS here */
672         if (!url_feof(pb)) {
673             int64_t pos = avio_tell(pb);
674             av_log(matroska->ctx, AV_LOG_ERROR,
675                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
676                    pos, pos);
677             return pb->error ? pb->error : AVERROR(EIO);
678         }
679         return AVERROR_EOF;
680     }
681
682     /* get the length of the EBML number */
683     read = 8 - ff_log2_tab[total];
684     if (read > max_size) {
685         int64_t pos = avio_tell(pb) - 1;
686         av_log(matroska->ctx, AV_LOG_ERROR,
687                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
688                (uint8_t) total, pos, pos);
689         return AVERROR_INVALIDDATA;
690     }
691
692     /* read out length */
693     total ^= 1 << ff_log2_tab[total];
694     while (n++ < read)
695         total = (total << 8) | avio_r8(pb);
696
697     *number = total;
698
699     return read;
700 }
701
702 /**
703  * Read a EBML length value.
704  * This needs special handling for the "unknown length" case which has multiple
705  * encodings.
706  */
707 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
708                             uint64_t *number)
709 {
710     int res = ebml_read_num(matroska, pb, 8, number);
711     if (res > 0 && *number + 1 == 1ULL << (7 * res))
712         *number = 0xffffffffffffffULL;
713     return res;
714 }
715
716 /*
717  * Read the next element as an unsigned int.
718  * 0 is success, < 0 is failure.
719  */
720 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
721 {
722     int n = 0;
723
724     if (size > 8)
725         return AVERROR_INVALIDDATA;
726
727     /* big-endian ordering; build up number */
728     *num = 0;
729     while (n++ < size)
730         *num = (*num << 8) | avio_r8(pb);
731
732     return 0;
733 }
734
735 /*
736  * Read the next element as a float.
737  * 0 is success, < 0 is failure.
738  */
739 static int ebml_read_float(AVIOContext *pb, int size, double *num)
740 {
741     if (size == 0) {
742         *num = 0;
743     } else if (size == 4) {
744         *num = av_int2float(avio_rb32(pb));
745     } else if (size == 8){
746         *num = av_int2double(avio_rb64(pb));
747     } else
748         return AVERROR_INVALIDDATA;
749
750     return 0;
751 }
752
753 /*
754  * Read the next element as an ASCII string.
755  * 0 is success, < 0 is failure.
756  */
757 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
758 {
759     char *res;
760
761     /* EBML strings are usually not 0-terminated, so we allocate one
762      * byte more, read the string and NULL-terminate it ourselves. */
763     if (!(res = av_malloc(size + 1)))
764         return AVERROR(ENOMEM);
765     if (avio_read(pb, (uint8_t *) res, size) != size) {
766         av_free(res);
767         return AVERROR(EIO);
768     }
769     (res)[size] = '\0';
770     av_free(*str);
771     *str = res;
772
773     return 0;
774 }
775
776 /*
777  * Read the next element as binary data.
778  * 0 is success, < 0 is failure.
779  */
780 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
781 {
782     av_fast_padded_malloc(&bin->data, &bin->size, length);
783     if (!bin->data)
784         return AVERROR(ENOMEM);
785
786     bin->size = length;
787     bin->pos  = avio_tell(pb);
788     if (avio_read(pb, bin->data, length) != length) {
789         av_freep(&bin->data);
790         bin->size = 0;
791         return AVERROR(EIO);
792     }
793
794     return 0;
795 }
796
797 /*
798  * Read the next element, but only the header. The contents
799  * are supposed to be sub-elements which can be read separately.
800  * 0 is success, < 0 is failure.
801  */
802 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
803 {
804     AVIOContext *pb = matroska->ctx->pb;
805     MatroskaLevel *level;
806
807     if (matroska->num_levels >= EBML_MAX_DEPTH) {
808         av_log(matroska->ctx, AV_LOG_ERROR,
809                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
810         return AVERROR(ENOSYS);
811     }
812
813     level = &matroska->levels[matroska->num_levels++];
814     level->start = avio_tell(pb);
815     level->length = length;
816
817     return 0;
818 }
819
820 /*
821  * Read signed/unsigned "EBML" numbers.
822  * Return: number of bytes processed, < 0 on error
823  */
824 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
825                                  uint8_t *data, uint32_t size, uint64_t *num)
826 {
827     AVIOContext pb;
828     ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
829     return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
830 }
831
832 /*
833  * Same as above, but signed.
834  */
835 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
836                                  uint8_t *data, uint32_t size, int64_t *num)
837 {
838     uint64_t unum;
839     int res;
840
841     /* read as unsigned number first */
842     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
843         return res;
844
845     /* make signed (weird way) */
846     *num = unum - ((1LL << (7*res - 1)) - 1);
847
848     return res;
849 }
850
851 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
852                            EbmlSyntax *syntax, void *data);
853
854 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
855                          uint32_t id, void *data)
856 {
857     int i;
858     for (i=0; syntax[i].id; i++)
859         if (id == syntax[i].id)
860             break;
861     if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
862         matroska->num_levels > 0 &&
863         matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
864         return 0;  // we reached the end of an unknown size cluster
865     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
866         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
867         if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
868             return AVERROR_INVALIDDATA;
869     }
870     return ebml_parse_elem(matroska, &syntax[i], data);
871 }
872
873 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
874                       void *data)
875 {
876     if (!matroska->current_id) {
877         uint64_t id;
878         int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
879         if (res < 0)
880             return res;
881         matroska->current_id = id | 1 << 7*res;
882     }
883     return ebml_parse_id(matroska, syntax, matroska->current_id, data);
884 }
885
886 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
887                            void *data)
888 {
889     int i, res = 0;
890
891     for (i=0; syntax[i].id; i++)
892         switch (syntax[i].type) {
893         case EBML_UINT:
894             *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
895             break;
896         case EBML_FLOAT:
897             *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
898             break;
899         case EBML_STR:
900         case EBML_UTF8:
901             *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
902             break;
903         }
904
905     while (!res && !ebml_level_end(matroska))
906         res = ebml_parse(matroska, syntax, data);
907
908     return res;
909 }
910
911 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
912                            EbmlSyntax *syntax, void *data)
913 {
914     static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
915         [EBML_UINT]  = 8,
916         [EBML_FLOAT] = 8,
917         // max. 16 MB for strings
918         [EBML_STR]   = 0x1000000,
919         [EBML_UTF8]  = 0x1000000,
920         // max. 256 MB for binary data
921         [EBML_BIN]   = 0x10000000,
922         // no limits for anything else
923     };
924     AVIOContext *pb = matroska->ctx->pb;
925     uint32_t id = syntax->id;
926     uint64_t length;
927     int res;
928     void *newelem;
929
930     data = (char *)data + syntax->data_offset;
931     if (syntax->list_elem_size) {
932         EbmlList *list = data;
933         newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
934         if (!newelem)
935             return AVERROR(ENOMEM);
936         list->elem = newelem;
937         data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
938         memset(data, 0, syntax->list_elem_size);
939         list->nb_elem++;
940     }
941
942     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
943         matroska->current_id = 0;
944         if ((res = ebml_read_length(matroska, pb, &length)) < 0)
945             return res;
946         if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
947             av_log(matroska->ctx, AV_LOG_ERROR,
948                    "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
949                    length, max_lengths[syntax->type], syntax->type);
950             return AVERROR_INVALIDDATA;
951         }
952     }
953
954     switch (syntax->type) {
955     case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
956     case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
957     case EBML_STR:
958     case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
959     case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
960     case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
961                          return res;
962                      if (id == MATROSKA_ID_SEGMENT)
963                          matroska->segment_start = avio_tell(matroska->ctx->pb);
964                      return ebml_parse_nest(matroska, syntax->def.n, data);
965     case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
966     case EBML_STOP:  return 1;
967     default:
968         if(ffio_limit(pb, length) != length)
969             return AVERROR(EIO);
970         return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
971     }
972     if (res == AVERROR_INVALIDDATA)
973         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
974     else if (res == AVERROR(EIO))
975         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
976     return res;
977 }
978
979 static void ebml_free(EbmlSyntax *syntax, void *data)
980 {
981     int i, j;
982     for (i=0; syntax[i].id; i++) {
983         void *data_off = (char *)data + syntax[i].data_offset;
984         switch (syntax[i].type) {
985         case EBML_STR:
986         case EBML_UTF8:  av_freep(data_off);                      break;
987         case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
988         case EBML_NEST:
989             if (syntax[i].list_elem_size) {
990                 EbmlList *list = data_off;
991                 char *ptr = list->elem;
992                 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
993                     ebml_free(syntax[i].def.n, ptr);
994                 av_free(list->elem);
995             } else
996                 ebml_free(syntax[i].def.n, data_off);
997         default:  break;
998         }
999     }
1000 }
1001
1002
1003 /*
1004  * Autodetecting...
1005  */
1006 static int matroska_probe(AVProbeData *p)
1007 {
1008     uint64_t total = 0;
1009     int len_mask = 0x80, size = 1, n = 1, i;
1010
1011     /* EBML header? */
1012     if (AV_RB32(p->buf) != EBML_ID_HEADER)
1013         return 0;
1014
1015     /* length of header */
1016     total = p->buf[4];
1017     while (size <= 8 && !(total & len_mask)) {
1018         size++;
1019         len_mask >>= 1;
1020     }
1021     if (size > 8)
1022       return 0;
1023     total &= (len_mask - 1);
1024     while (n < size)
1025         total = (total << 8) | p->buf[4 + n++];
1026
1027     /* Does the probe data contain the whole header? */
1028     if (p->buf_size < 4 + size + total)
1029       return 0;
1030
1031     /* The header should contain a known document type. For now,
1032      * we don't parse the whole header but simply check for the
1033      * availability of that array of characters inside the header.
1034      * Not fully fool-proof, but good enough. */
1035     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
1036         int probelen = strlen(matroska_doctypes[i]);
1037         if (total < probelen)
1038             continue;
1039         for (n = 4+size; n <= 4+size+total-probelen; n++)
1040             if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
1041                 return AVPROBE_SCORE_MAX;
1042     }
1043
1044     // probably valid EBML header but no recognized doctype
1045     return AVPROBE_SCORE_MAX/2;
1046 }
1047
1048 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
1049                                                  int num)
1050 {
1051     MatroskaTrack *tracks = matroska->tracks.elem;
1052     int i;
1053
1054     for (i=0; i < matroska->tracks.nb_elem; i++)
1055         if (tracks[i].num == num)
1056             return &tracks[i];
1057
1058     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
1059     return NULL;
1060 }
1061
1062 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
1063                                   MatroskaTrack *track)
1064 {
1065     MatroskaTrackEncoding *encodings = track->encodings.elem;
1066     uint8_t* data = *buf;
1067     int isize = *buf_size;
1068     uint8_t* pkt_data = NULL;
1069     uint8_t av_unused *newpktdata;
1070     int pkt_size = isize;
1071     int result = 0;
1072     int olen;
1073
1074     if (pkt_size >= 10000000U)
1075         return AVERROR_INVALIDDATA;
1076
1077     switch (encodings[0].compression.algo) {
1078     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP: {
1079         int header_size = encodings[0].compression.settings.size;
1080         uint8_t *header = encodings[0].compression.settings.data;
1081
1082         if (header_size && !header) {
1083             av_log(NULL, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
1084             return -1;
1085         }
1086
1087         if (!header_size)
1088             return 0;
1089
1090         pkt_size = isize + header_size;
1091         pkt_data = av_malloc(pkt_size);
1092         if (!pkt_data)
1093             return AVERROR(ENOMEM);
1094
1095         memcpy(pkt_data, header, header_size);
1096         memcpy(pkt_data + header_size, data, isize);
1097         break;
1098     }
1099 #if CONFIG_LZO
1100     case MATROSKA_TRACK_ENCODING_COMP_LZO:
1101         do {
1102             olen = pkt_size *= 3;
1103             newpktdata = av_realloc(pkt_data, pkt_size + AV_LZO_OUTPUT_PADDING);
1104             if (!newpktdata) {
1105                 result = AVERROR(ENOMEM);
1106                 goto failed;
1107             }
1108             pkt_data = newpktdata;
1109             result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1110         } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1111         if (result) {
1112             result = AVERROR_INVALIDDATA;
1113             goto failed;
1114         }
1115         pkt_size -= olen;
1116         break;
1117 #endif
1118 #if CONFIG_ZLIB
1119     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1120         z_stream zstream = {0};
1121         if (inflateInit(&zstream) != Z_OK)
1122             return -1;
1123         zstream.next_in = data;
1124         zstream.avail_in = isize;
1125         do {
1126             pkt_size *= 3;
1127             newpktdata = av_realloc(pkt_data, pkt_size);
1128             if (!newpktdata) {
1129                 inflateEnd(&zstream);
1130                 goto failed;
1131             }
1132             pkt_data = newpktdata;
1133             zstream.avail_out = pkt_size - zstream.total_out;
1134             zstream.next_out = pkt_data + zstream.total_out;
1135             if (pkt_data) {
1136                 result = inflate(&zstream, Z_NO_FLUSH);
1137             } else
1138                 result = Z_MEM_ERROR;
1139         } while (result==Z_OK && pkt_size<10000000);
1140         pkt_size = zstream.total_out;
1141         inflateEnd(&zstream);
1142         if (result != Z_STREAM_END) {
1143             if (result == Z_MEM_ERROR)
1144                 result = AVERROR(ENOMEM);
1145             else
1146                 result = AVERROR_INVALIDDATA;
1147             goto failed;
1148         }
1149         break;
1150     }
1151 #endif
1152 #if CONFIG_BZLIB
1153     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1154         bz_stream bzstream = {0};
1155         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1156             return -1;
1157         bzstream.next_in = data;
1158         bzstream.avail_in = isize;
1159         do {
1160             pkt_size *= 3;
1161             newpktdata = av_realloc(pkt_data, pkt_size);
1162             if (!newpktdata) {
1163                 BZ2_bzDecompressEnd(&bzstream);
1164                 goto failed;
1165             }
1166             pkt_data = newpktdata;
1167             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1168             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1169             if (pkt_data) {
1170                 result = BZ2_bzDecompress(&bzstream);
1171             } else
1172                 result = BZ_MEM_ERROR;
1173         } while (result==BZ_OK && pkt_size<10000000);
1174         pkt_size = bzstream.total_out_lo32;
1175         BZ2_bzDecompressEnd(&bzstream);
1176         if (result != BZ_STREAM_END) {
1177             if (result == BZ_MEM_ERROR)
1178                 result = AVERROR(ENOMEM);
1179             else
1180                 result = AVERROR_INVALIDDATA;
1181             goto failed;
1182         }
1183         break;
1184     }
1185 #endif
1186     default:
1187         return AVERROR_INVALIDDATA;
1188     }
1189
1190     *buf = pkt_data;
1191     *buf_size = pkt_size;
1192     return 0;
1193  failed:
1194     av_free(pkt_data);
1195     return result;
1196 }
1197
1198 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1199                                     AVPacket *pkt, uint64_t display_duration)
1200 {
1201     char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1202     for (; *ptr!=',' && ptr<end-1; ptr++);
1203     if (*ptr == ',')
1204         ptr++;
1205     layer = ptr;
1206     for (; *ptr!=',' && ptr<end-1; ptr++);
1207     if (*ptr == ',') {
1208         int64_t end_pts = pkt->pts + display_duration;
1209         int sc = matroska->time_scale * pkt->pts / 10000000;
1210         int ec = matroska->time_scale * end_pts  / 10000000;
1211         int sh, sm, ss, eh, em, es, len;
1212         sh = sc/360000;  sc -= 360000*sh;
1213         sm = sc/  6000;  sc -=   6000*sm;
1214         ss = sc/   100;  sc -=    100*ss;
1215         eh = ec/360000;  ec -= 360000*eh;
1216         em = ec/  6000;  ec -=   6000*em;
1217         es = ec/   100;  ec -=    100*es;
1218         *ptr++ = '\0';
1219         len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1220         if (!(line = av_malloc(len)))
1221             return;
1222         snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1223                  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1224         av_free(pkt->data);
1225         pkt->data = line;
1226         pkt->size = strlen(line);
1227     }
1228 }
1229
1230 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1231 {
1232     int ret = av_grow_packet(out, in->size);
1233     if (ret < 0)
1234         return ret;
1235
1236     memcpy(out->data + out->size - in->size, in->data, in->size);
1237
1238     av_free_packet(in);
1239     av_free(in);
1240     return 0;
1241 }
1242
1243 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1244                                  AVDictionary **metadata, char *prefix)
1245 {
1246     MatroskaTag *tags = list->elem;
1247     char key[1024];
1248     int i;
1249
1250     for (i=0; i < list->nb_elem; i++) {
1251         const char *lang= (tags[i].lang && strcmp(tags[i].lang, "und")) ? tags[i].lang : NULL;
1252
1253         if (!tags[i].name) {
1254             av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1255             continue;
1256         }
1257         if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1258         else         av_strlcpy(key, tags[i].name, sizeof(key));
1259         if (tags[i].def || !lang) {
1260         av_dict_set(metadata, key, tags[i].string, 0);
1261         if (tags[i].sub.nb_elem)
1262             matroska_convert_tag(s, &tags[i].sub, metadata, key);
1263         }
1264         if (lang) {
1265             av_strlcat(key, "-", sizeof(key));
1266             av_strlcat(key, lang, sizeof(key));
1267             av_dict_set(metadata, key, tags[i].string, 0);
1268             if (tags[i].sub.nb_elem)
1269                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1270         }
1271     }
1272     ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1273 }
1274
1275 static void matroska_convert_tags(AVFormatContext *s)
1276 {
1277     MatroskaDemuxContext *matroska = s->priv_data;
1278     MatroskaTags *tags = matroska->tags.elem;
1279     int i, j;
1280
1281     for (i=0; i < matroska->tags.nb_elem; i++) {
1282         if (tags[i].target.attachuid) {
1283             MatroskaAttachement *attachment = matroska->attachments.elem;
1284             for (j=0; j<matroska->attachments.nb_elem; j++)
1285                 if (attachment[j].uid == tags[i].target.attachuid
1286                     && attachment[j].stream)
1287                     matroska_convert_tag(s, &tags[i].tag,
1288                                          &attachment[j].stream->metadata, NULL);
1289         } else if (tags[i].target.chapteruid) {
1290             MatroskaChapter *chapter = matroska->chapters.elem;
1291             for (j=0; j<matroska->chapters.nb_elem; j++)
1292                 if (chapter[j].uid == tags[i].target.chapteruid
1293                     && chapter[j].chapter)
1294                     matroska_convert_tag(s, &tags[i].tag,
1295                                          &chapter[j].chapter->metadata, NULL);
1296         } else if (tags[i].target.trackuid) {
1297             MatroskaTrack *track = matroska->tracks.elem;
1298             for (j=0; j<matroska->tracks.nb_elem; j++)
1299                 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1300                     matroska_convert_tag(s, &tags[i].tag,
1301                                          &track[j].stream->metadata, NULL);
1302         } else {
1303             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1304                                  tags[i].target.type);
1305         }
1306     }
1307 }
1308
1309 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
1310 {
1311     EbmlList *seekhead_list = &matroska->seekhead;
1312     MatroskaSeekhead *seekhead = seekhead_list->elem;
1313     uint32_t level_up = matroska->level_up;
1314     int64_t before_pos = avio_tell(matroska->ctx->pb);
1315     uint32_t saved_id = matroska->current_id;
1316     MatroskaLevel level;
1317     int64_t offset;
1318     int ret = 0;
1319
1320     if (idx >= seekhead_list->nb_elem
1321             || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1322             || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1323         return 0;
1324
1325     /* seek */
1326     offset = seekhead[idx].pos + matroska->segment_start;
1327     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1328         /* We don't want to lose our seekhead level, so we add
1329          * a dummy. This is a crude hack. */
1330         if (matroska->num_levels == EBML_MAX_DEPTH) {
1331             av_log(matroska->ctx, AV_LOG_INFO,
1332                    "Max EBML element depth (%d) reached, "
1333                    "cannot parse further.\n", EBML_MAX_DEPTH);
1334             ret = AVERROR_INVALIDDATA;
1335         } else {
1336             level.start = 0;
1337             level.length = (uint64_t)-1;
1338             matroska->levels[matroska->num_levels] = level;
1339             matroska->num_levels++;
1340             matroska->current_id = 0;
1341
1342             ret = ebml_parse(matroska, matroska_segment, matroska);
1343
1344             /* remove dummy level */
1345             while (matroska->num_levels) {
1346                 uint64_t length = matroska->levels[--matroska->num_levels].length;
1347                 if (length == (uint64_t)-1)
1348                     break;
1349             }
1350         }
1351     }
1352     /* seek back */
1353     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1354     matroska->level_up = level_up;
1355     matroska->current_id = saved_id;
1356
1357     return ret;
1358 }
1359
1360 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1361 {
1362     EbmlList *seekhead_list = &matroska->seekhead;
1363     int64_t before_pos = avio_tell(matroska->ctx->pb);
1364     int i;
1365
1366     // we should not do any seeking in the streaming case
1367     if (!matroska->ctx->pb->seekable ||
1368         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1369         return;
1370
1371     for (i = 0; i < seekhead_list->nb_elem; i++) {
1372         MatroskaSeekhead *seekhead = seekhead_list->elem;
1373         if (seekhead[i].pos <= before_pos)
1374             continue;
1375
1376         // defer cues parsing until we actually need cue data.
1377         if (seekhead[i].id == MATROSKA_ID_CUES) {
1378             matroska->cues_parsing_deferred = 1;
1379             continue;
1380         }
1381
1382         if (matroska_parse_seekhead_entry(matroska, i) < 0) {
1383             // mark index as broken
1384             matroska->cues_parsing_deferred = -1;
1385             break;
1386         }
1387     }
1388 }
1389
1390 static void matroska_add_index_entries(MatroskaDemuxContext *matroska) {
1391     EbmlList *index_list;
1392     MatroskaIndex *index;
1393     int index_scale = 1;
1394     int i, j;
1395
1396     index_list = &matroska->index;
1397     index = index_list->elem;
1398     if (index_list->nb_elem
1399         && index[0].time > 1E14/matroska->time_scale) {
1400         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1401         index_scale = matroska->time_scale;
1402     }
1403     for (i = 0; i < index_list->nb_elem; i++) {
1404         EbmlList *pos_list = &index[i].pos;
1405         MatroskaIndexPos *pos = pos_list->elem;
1406         for (j = 0; j < pos_list->nb_elem; j++) {
1407             MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1408             if (track && track->stream)
1409                 av_add_index_entry(track->stream,
1410                                    pos[j].pos + matroska->segment_start,
1411                                    index[i].time/index_scale, 0, 0,
1412                                    AVINDEX_KEYFRAME);
1413         }
1414     }
1415 }
1416
1417 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1418     EbmlList *seekhead_list = &matroska->seekhead;
1419     MatroskaSeekhead *seekhead = seekhead_list->elem;
1420     int i;
1421
1422     for (i = 0; i < seekhead_list->nb_elem; i++)
1423         if (seekhead[i].id == MATROSKA_ID_CUES)
1424             break;
1425     assert(i <= seekhead_list->nb_elem);
1426
1427     if (matroska_parse_seekhead_entry(matroska, i) < 0)
1428        matroska->cues_parsing_deferred = -1;
1429     matroska_add_index_entries(matroska);
1430 }
1431
1432 static int matroska_aac_profile(char *codec_id)
1433 {
1434     static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1435     int profile;
1436
1437     for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1438         if (strstr(codec_id, aac_profiles[profile]))
1439             break;
1440     return profile + 1;
1441 }
1442
1443 static int matroska_aac_sri(int samplerate)
1444 {
1445     int sri;
1446
1447     for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1448         if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1449             break;
1450     return sri;
1451 }
1452
1453 static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
1454 {
1455     char buffer[32];
1456     /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
1457     time_t creation_time = date_utc / 1000000000 + 978307200;
1458     struct tm *ptm = gmtime(&creation_time);
1459     if (!ptm) return;
1460     strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
1461     av_dict_set(metadata, "creation_time", buffer, 0);
1462 }
1463
1464 static int matroska_read_header(AVFormatContext *s)
1465 {
1466     MatroskaDemuxContext *matroska = s->priv_data;
1467     EbmlList *attachements_list = &matroska->attachments;
1468     MatroskaAttachement *attachements;
1469     EbmlList *chapters_list = &matroska->chapters;
1470     MatroskaChapter *chapters;
1471     MatroskaTrack *tracks;
1472     uint64_t max_start = 0;
1473     int64_t pos;
1474     Ebml ebml = { 0 };
1475     AVStream *st;
1476     int i, j, k, res;
1477
1478     matroska->ctx = s;
1479
1480     /* First read the EBML header. */
1481     if (ebml_parse(matroska, ebml_syntax, &ebml)
1482         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1483         || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3 || !ebml.doctype) {
1484         av_log(matroska->ctx, AV_LOG_ERROR,
1485                "EBML header using unsupported features\n"
1486                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1487                ebml.version, ebml.doctype, ebml.doctype_version);
1488         ebml_free(ebml_syntax, &ebml);
1489         return AVERROR_PATCHWELCOME;
1490     } else if (ebml.doctype_version == 3) {
1491         av_log(matroska->ctx, AV_LOG_WARNING,
1492                "EBML header using unsupported features\n"
1493                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1494                ebml.version, ebml.doctype, ebml.doctype_version);
1495     }
1496     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1497         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1498             break;
1499     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1500         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1501         if (matroska->ctx->error_recognition & AV_EF_EXPLODE) {
1502             ebml_free(ebml_syntax, &ebml);
1503             return AVERROR_INVALIDDATA;
1504         }
1505     }
1506     ebml_free(ebml_syntax, &ebml);
1507
1508     /* The next thing is a segment. */
1509     pos = avio_tell(matroska->ctx->pb);
1510     res = ebml_parse(matroska, matroska_segments, matroska);
1511     // try resyncing until we find a EBML_STOP type element.
1512     while (res != 1) {
1513         res = matroska_resync(matroska, pos);
1514         if (res < 0)
1515             return res;
1516         pos = avio_tell(matroska->ctx->pb);
1517         res = ebml_parse(matroska, matroska_segment, matroska);
1518     }
1519     matroska_execute_seekhead(matroska);
1520
1521     if (!matroska->time_scale)
1522         matroska->time_scale = 1000000;
1523     if (matroska->duration)
1524         matroska->ctx->duration = matroska->duration * matroska->time_scale
1525                                   * 1000 / AV_TIME_BASE;
1526     av_dict_set(&s->metadata, "title", matroska->title, 0);
1527
1528     if (matroska->date_utc.size == 8)
1529         matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
1530
1531     tracks = matroska->tracks.elem;
1532     for (i=0; i < matroska->tracks.nb_elem; i++) {
1533         MatroskaTrack *track = &tracks[i];
1534         enum AVCodecID codec_id = AV_CODEC_ID_NONE;
1535         EbmlList *encodings_list = &track->encodings;
1536         MatroskaTrackEncoding *encodings = encodings_list->elem;
1537         uint8_t *extradata = NULL;
1538         int extradata_size = 0;
1539         int extradata_offset = 0;
1540         uint32_t fourcc = 0;
1541         AVIOContext b;
1542
1543         /* Apply some sanity checks. */
1544         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1545             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1546             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1547             av_log(matroska->ctx, AV_LOG_INFO,
1548                    "Unknown or unsupported track type %"PRIu64"\n",
1549                    track->type);
1550             continue;
1551         }
1552         if (track->codec_id == NULL)
1553             continue;
1554
1555         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1556             if (!track->default_duration && track->video.frame_rate > 0)
1557                 track->default_duration = 1000000000/track->video.frame_rate;
1558             if (!track->video.display_width)
1559                 track->video.display_width = track->video.pixel_width;
1560             if (!track->video.display_height)
1561                 track->video.display_height = track->video.pixel_height;
1562             if (track->video.color_space.size == 4)
1563                 fourcc = AV_RL32(track->video.color_space.data);
1564         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1565             if (!track->audio.out_samplerate)
1566                 track->audio.out_samplerate = track->audio.samplerate;
1567         }
1568         if (encodings_list->nb_elem > 1) {
1569             av_log(matroska->ctx, AV_LOG_ERROR,
1570                    "Multiple combined encodings not supported");
1571         } else if (encodings_list->nb_elem == 1) {
1572             if (encodings[0].type ||
1573                 (
1574 #if CONFIG_ZLIB
1575                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1576 #endif
1577 #if CONFIG_BZLIB
1578                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1579 #endif
1580 #if CONFIG_LZO
1581                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO &&
1582 #endif
1583                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP)) {
1584                 encodings[0].scope = 0;
1585                 av_log(matroska->ctx, AV_LOG_ERROR,
1586                        "Unsupported encoding type");
1587             } else if (track->codec_priv.size && encodings[0].scope&2) {
1588                 uint8_t *codec_priv = track->codec_priv.data;
1589                 int ret = matroska_decode_buffer(&track->codec_priv.data,
1590                                                  &track->codec_priv.size,
1591                                                  track);
1592                 if (ret < 0) {
1593                     track->codec_priv.data = NULL;
1594                     track->codec_priv.size = 0;
1595                     av_log(matroska->ctx, AV_LOG_ERROR,
1596                            "Failed to decode codec private data\n");
1597                 }
1598
1599                 if (codec_priv != track->codec_priv.data)
1600                     av_free(codec_priv);
1601             }
1602         }
1603
1604         for(j=0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++){
1605             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1606                         strlen(ff_mkv_codec_tags[j].str))){
1607                 codec_id= ff_mkv_codec_tags[j].id;
1608                 break;
1609             }
1610         }
1611
1612         st = track->stream = avformat_new_stream(s, NULL);
1613         if (st == NULL)
1614             return AVERROR(ENOMEM);
1615
1616         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1617             && track->codec_priv.size >= 40
1618             && track->codec_priv.data != NULL) {
1619             track->ms_compat = 1;
1620             fourcc = AV_RL32(track->codec_priv.data + 16);
1621             codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
1622             extradata_offset = 40;
1623         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1624                    && track->codec_priv.size >= 14
1625                    && track->codec_priv.data != NULL) {
1626             int ret;
1627             ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1628                               0, NULL, NULL, NULL, NULL);
1629             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1630             if (ret < 0)
1631                 return ret;
1632             codec_id = st->codec->codec_id;
1633             extradata_offset = FFMIN(track->codec_priv.size, 18);
1634         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1635                    && (track->codec_priv.size >= 86)
1636                    && (track->codec_priv.data != NULL)) {
1637             fourcc = AV_RL32(track->codec_priv.data);
1638             codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
1639         } else if (codec_id == AV_CODEC_ID_ALAC && track->codec_priv.size && track->codec_priv.size < INT_MAX-12) {
1640             /* Only ALAC's magic cookie is stored in Matroska's track headers.
1641                Create the "atom size", "tag", and "tag version" fields the
1642                decoder expects manually. */
1643             extradata_size = 12 + track->codec_priv.size;
1644             extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1645             if (extradata == NULL)
1646                 return AVERROR(ENOMEM);
1647             AV_WB32(extradata, extradata_size);
1648             memcpy(&extradata[4], "alac", 4);
1649             AV_WB32(&extradata[8], 0);
1650             memcpy(&extradata[12], track->codec_priv.data, track->codec_priv.size);
1651         } else if (codec_id == AV_CODEC_ID_PCM_S16BE) {
1652             switch (track->audio.bitdepth) {
1653             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1654             case 24:  codec_id = AV_CODEC_ID_PCM_S24BE;  break;
1655             case 32:  codec_id = AV_CODEC_ID_PCM_S32BE;  break;
1656             }
1657         } else if (codec_id == AV_CODEC_ID_PCM_S16LE) {
1658             switch (track->audio.bitdepth) {
1659             case  8:  codec_id = AV_CODEC_ID_PCM_U8;     break;
1660             case 24:  codec_id = AV_CODEC_ID_PCM_S24LE;  break;
1661             case 32:  codec_id = AV_CODEC_ID_PCM_S32LE;  break;
1662             }
1663         } else if (codec_id==AV_CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1664             codec_id = AV_CODEC_ID_PCM_F64LE;
1665         } else if (codec_id == AV_CODEC_ID_AAC && !track->codec_priv.size) {
1666             int profile = matroska_aac_profile(track->codec_id);
1667             int sri = matroska_aac_sri(track->audio.samplerate);
1668             extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1669             if (extradata == NULL)
1670                 return AVERROR(ENOMEM);
1671             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1672             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1673             if (strstr(track->codec_id, "SBR")) {
1674                 sri = matroska_aac_sri(track->audio.out_samplerate);
1675                 extradata[2] = 0x56;
1676                 extradata[3] = 0xE5;
1677                 extradata[4] = 0x80 | (sri<<3);
1678                 extradata_size = 5;
1679             } else
1680                 extradata_size = 2;
1681         } else if (codec_id == AV_CODEC_ID_TTA) {
1682             extradata_size = 30;
1683             extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1684             if (extradata == NULL)
1685                 return AVERROR(ENOMEM);
1686             ffio_init_context(&b, extradata, extradata_size, 1,
1687                           NULL, NULL, NULL, NULL);
1688             avio_write(&b, "TTA1", 4);
1689             avio_wl16(&b, 1);
1690             avio_wl16(&b, track->audio.channels);
1691             avio_wl16(&b, track->audio.bitdepth);
1692             avio_wl32(&b, track->audio.out_samplerate);
1693             avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1694         } else if (codec_id == AV_CODEC_ID_RV10 || codec_id == AV_CODEC_ID_RV20 ||
1695                    codec_id == AV_CODEC_ID_RV30 || codec_id == AV_CODEC_ID_RV40) {
1696             extradata_offset = 26;
1697         } else if (codec_id == AV_CODEC_ID_RA_144) {
1698             track->audio.out_samplerate = 8000;
1699             track->audio.channels = 1;
1700         } else if ((codec_id == AV_CODEC_ID_RA_288 || codec_id == AV_CODEC_ID_COOK ||
1701                     codec_id == AV_CODEC_ID_ATRAC3 || codec_id == AV_CODEC_ID_SIPR)
1702                     && track->codec_priv.data) {
1703             int flavor;
1704
1705             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1706                           0, NULL, NULL, NULL, NULL);
1707             avio_skip(&b, 22);
1708             flavor                       = avio_rb16(&b);
1709             track->audio.coded_framesize = avio_rb32(&b);
1710             avio_skip(&b, 12);
1711             track->audio.sub_packet_h    = avio_rb16(&b);
1712             track->audio.frame_size      = avio_rb16(&b);
1713             track->audio.sub_packet_size = avio_rb16(&b);
1714             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1715             if (codec_id == AV_CODEC_ID_RA_288) {
1716                 st->codec->block_align = track->audio.coded_framesize;
1717                 track->codec_priv.size = 0;
1718             } else {
1719                 if (codec_id == AV_CODEC_ID_SIPR && flavor < 4) {
1720                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1721                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1722                     st->codec->bit_rate = sipr_bit_rate[flavor];
1723                 }
1724                 st->codec->block_align = track->audio.sub_packet_size;
1725                 extradata_offset = 78;
1726             }
1727         }
1728         track->codec_priv.size -= extradata_offset;
1729
1730         if (codec_id == AV_CODEC_ID_NONE)
1731             av_log(matroska->ctx, AV_LOG_INFO,
1732                    "Unknown/unsupported AVCodecID %s.\n", track->codec_id);
1733
1734         if (track->time_scale < 0.01)
1735             track->time_scale = 1.0;
1736         avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1737
1738         st->codec->codec_id = codec_id;
1739         st->start_time = 0;
1740         if (strcmp(track->language, "und"))
1741             av_dict_set(&st->metadata, "language", track->language, 0);
1742         av_dict_set(&st->metadata, "title", track->name, 0);
1743
1744         if (track->flag_default)
1745             st->disposition |= AV_DISPOSITION_DEFAULT;
1746         if (track->flag_forced)
1747             st->disposition |= AV_DISPOSITION_FORCED;
1748
1749         if (!st->codec->extradata) {
1750             if(extradata){
1751                 st->codec->extradata = extradata;
1752                 st->codec->extradata_size = extradata_size;
1753             } else if(track->codec_priv.data && track->codec_priv.size > 0){
1754                 st->codec->extradata = av_mallocz(track->codec_priv.size +
1755                                                   FF_INPUT_BUFFER_PADDING_SIZE);
1756                 if(st->codec->extradata == NULL)
1757                     return AVERROR(ENOMEM);
1758                 st->codec->extradata_size = track->codec_priv.size;
1759                 memcpy(st->codec->extradata,
1760                        track->codec_priv.data + extradata_offset,
1761                        track->codec_priv.size);
1762             }
1763         }
1764
1765         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1766             MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
1767
1768             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1769             st->codec->codec_tag  = fourcc;
1770             st->codec->width  = track->video.pixel_width;
1771             st->codec->height = track->video.pixel_height;
1772             av_reduce(&st->sample_aspect_ratio.num,
1773                       &st->sample_aspect_ratio.den,
1774                       st->codec->height * track->video.display_width,
1775                       st->codec-> width * track->video.display_height,
1776                       255);
1777             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1778             if (track->default_duration) {
1779                 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1780                           1000000000, track->default_duration, 30000);
1781 #if FF_API_R_FRAME_RATE
1782                 st->r_frame_rate = st->avg_frame_rate;
1783 #endif
1784             }
1785
1786             /* export stereo mode flag as metadata tag */
1787             if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
1788                 av_dict_set(&st->metadata, "stereo_mode", ff_matroska_video_stereo_mode[track->video.stereo_mode], 0);
1789
1790             /* export alpha mode flag as metadata tag  */
1791             if (track->video.alpha_mode)
1792                 av_dict_set(&st->metadata, "alpha_mode", "1", 0);
1793
1794             /* if we have virtual track, mark the real tracks */
1795             for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
1796                 char buf[32];
1797                 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
1798                     continue;
1799                 snprintf(buf, sizeof(buf), "%s_%d",
1800                          ff_matroska_video_stereo_plane[planes[j].type], i);
1801                 for (k=0; k < matroska->tracks.nb_elem; k++)
1802                     if (planes[j].uid == tracks[k].uid) {
1803                         av_dict_set(&s->streams[k]->metadata,
1804                                     "stereo_mode", buf, 0);
1805                         break;
1806                     }
1807             }
1808         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1809             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1810             st->codec->sample_rate = track->audio.out_samplerate;
1811             st->codec->channels = track->audio.channels;
1812             st->codec->bits_per_coded_sample = track->audio.bitdepth;
1813             if (st->codec->codec_id != AV_CODEC_ID_AAC)
1814             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1815         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1816             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1817             if (st->codec->codec_id == AV_CODEC_ID_SSA)
1818                 matroska->contains_ssa = 1;
1819         }
1820     }
1821
1822     attachements = attachements_list->elem;
1823     for (j=0; j<attachements_list->nb_elem; j++) {
1824         if (!(attachements[j].filename && attachements[j].mime &&
1825               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1826             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1827         } else {
1828             AVStream *st = avformat_new_stream(s, NULL);
1829             if (st == NULL)
1830                 break;
1831             av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1832             av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1833             st->codec->codec_id = AV_CODEC_ID_NONE;
1834             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1835             st->codec->extradata  = av_malloc(attachements[j].bin.size + FF_INPUT_BUFFER_PADDING_SIZE);
1836             if(st->codec->extradata == NULL)
1837                 break;
1838             st->codec->extradata_size = attachements[j].bin.size;
1839             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1840
1841             for (i=0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++) {
1842                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1843                              strlen(ff_mkv_mime_tags[i].str))) {
1844                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1845                     break;
1846                 }
1847             }
1848             attachements[j].stream = st;
1849         }
1850     }
1851
1852     chapters = chapters_list->elem;
1853     for (i=0; i<chapters_list->nb_elem; i++)
1854         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1855             && (max_start==0 || chapters[i].start > max_start)) {
1856             chapters[i].chapter =
1857             avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1858                            chapters[i].start, chapters[i].end,
1859                            chapters[i].title);
1860             av_dict_set(&chapters[i].chapter->metadata,
1861                              "title", chapters[i].title, 0);
1862             max_start = chapters[i].start;
1863         }
1864
1865     matroska_add_index_entries(matroska);
1866
1867     matroska_convert_tags(s);
1868
1869     return 0;
1870 }
1871
1872 /*
1873  * Put one packet in an application-supplied AVPacket struct.
1874  * Returns 0 on success or -1 on failure.
1875  */
1876 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1877                                    AVPacket *pkt)
1878 {
1879     if (matroska->num_packets > 0) {
1880         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1881         av_free(matroska->packets[0]);
1882         if (matroska->num_packets > 1) {
1883             void *newpackets;
1884             memmove(&matroska->packets[0], &matroska->packets[1],
1885                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1886             newpackets = av_realloc(matroska->packets,
1887                             (matroska->num_packets - 1) * sizeof(AVPacket *));
1888             if (newpackets)
1889                 matroska->packets = newpackets;
1890         } else {
1891             av_freep(&matroska->packets);
1892             matroska->prev_pkt = NULL;
1893         }
1894         matroska->num_packets--;
1895         return 0;
1896     }
1897
1898     return -1;
1899 }
1900
1901 /*
1902  * Free all packets in our internal queue.
1903  */
1904 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1905 {
1906     matroska->prev_pkt = NULL;
1907     if (matroska->packets) {
1908         int n;
1909         for (n = 0; n < matroska->num_packets; n++) {
1910             av_free_packet(matroska->packets[n]);
1911             av_free(matroska->packets[n]);
1912         }
1913         av_freep(&matroska->packets);
1914         matroska->num_packets = 0;
1915     }
1916 }
1917
1918 static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,
1919                                 int size, int type,
1920                                 uint32_t **lace_buf, int *laces)
1921 {
1922     int res = 0, n;
1923     uint8_t *data = *buf;
1924     uint32_t *lace_size;
1925
1926     if (!type) {
1927         *laces = 1;
1928         *lace_buf = av_mallocz(sizeof(int));
1929         if (!*lace_buf)
1930             return AVERROR(ENOMEM);
1931
1932         *lace_buf[0] = size;
1933         return 0;
1934     }
1935
1936     av_assert0(size > 0);
1937     *laces = *data + 1;
1938     data += 1;
1939     size -= 1;
1940     lace_size = av_mallocz(*laces * sizeof(int));
1941     if (!lace_size)
1942         return AVERROR(ENOMEM);
1943
1944     switch (type) {
1945     case 0x1: /* Xiph lacing */ {
1946         uint8_t temp;
1947         uint32_t total = 0;
1948         for (n = 0; res == 0 && n < *laces - 1; n++) {
1949             while (1) {
1950                 if (size == 0) {
1951                     res = AVERROR_EOF;
1952                     break;
1953                 }
1954                 temp = *data;
1955                 lace_size[n] += temp;
1956                 data += 1;
1957                 size -= 1;
1958                 if (temp != 0xff)
1959                     break;
1960             }
1961             total += lace_size[n];
1962         }
1963         if (size <= total) {
1964             res = AVERROR_INVALIDDATA;
1965             break;
1966         }
1967
1968         lace_size[n] = size - total;
1969         break;
1970     }
1971
1972     case 0x2: /* fixed-size lacing */
1973         if (size % (*laces)) {
1974             res = AVERROR_INVALIDDATA;
1975             break;
1976         }
1977         for (n = 0; n < *laces; n++)
1978             lace_size[n] = size / *laces;
1979         break;
1980
1981     case 0x3: /* EBML lacing */ {
1982         uint64_t num;
1983         uint32_t total;
1984         n = matroska_ebmlnum_uint(matroska, data, size, &num);
1985         if (n < 0) {
1986             av_log(matroska->ctx, AV_LOG_INFO,
1987                    "EBML block data error\n");
1988             res = n;
1989             break;
1990         }
1991         data += n;
1992         size -= n;
1993         total = lace_size[0] = num;
1994         for (n = 1; res == 0 && n < *laces - 1; n++) {
1995             int64_t snum;
1996             int r;
1997             r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1998             if (r < 0) {
1999                 av_log(matroska->ctx, AV_LOG_INFO,
2000                        "EBML block data error\n");
2001                 res = r;
2002                 break;
2003             }
2004             data += r;
2005             size -= r;
2006             lace_size[n] = lace_size[n - 1] + snum;
2007             total += lace_size[n];
2008         }
2009         if (size <= total) {
2010             res = AVERROR_INVALIDDATA;
2011             break;
2012         }
2013         lace_size[*laces - 1] = size - total;
2014         break;
2015     }
2016     }
2017
2018     *buf      = data;
2019     *lace_buf = lace_size;
2020
2021     return res;
2022 }
2023
2024 static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,
2025                                    MatroskaTrack *track,
2026                                    AVStream *st,
2027                                    uint8_t *data, int size,
2028                                    uint64_t timecode,
2029                                    int64_t pos)
2030 {
2031     int a = st->codec->block_align;
2032     int sps = track->audio.sub_packet_size;
2033     int cfs = track->audio.coded_framesize;
2034     int h = track->audio.sub_packet_h;
2035     int y = track->audio.sub_packet_cnt;
2036     int w = track->audio.frame_size;
2037     int x;
2038
2039     if (!track->audio.pkt_cnt) {
2040         if (track->audio.sub_packet_cnt == 0)
2041             track->audio.buf_timecode = timecode;
2042         if (st->codec->codec_id == AV_CODEC_ID_RA_288) {
2043             if (size < cfs * h / 2) {
2044                 av_log(matroska->ctx, AV_LOG_ERROR,
2045                        "Corrupt int4 RM-style audio packet size\n");
2046                 return AVERROR_INVALIDDATA;
2047             }
2048             for (x=0; x<h/2; x++)
2049                 memcpy(track->audio.buf+x*2*w+y*cfs,
2050                        data+x*cfs, cfs);
2051         } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {
2052             if (size < w) {
2053                 av_log(matroska->ctx, AV_LOG_ERROR,
2054                        "Corrupt sipr RM-style audio packet size\n");
2055                 return AVERROR_INVALIDDATA;
2056             }
2057             memcpy(track->audio.buf + y*w, data, w);
2058         } else {
2059             if (size < sps * w / sps || h<=0) {
2060                 av_log(matroska->ctx, AV_LOG_ERROR,
2061                        "Corrupt generic RM-style audio packet size\n");
2062                 return AVERROR_INVALIDDATA;
2063             }
2064             for (x=0; x<w/sps; x++)
2065                 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2066         }
2067
2068         if (++track->audio.sub_packet_cnt >= h) {
2069             if (st->codec->codec_id == AV_CODEC_ID_SIPR)
2070                 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2071             track->audio.sub_packet_cnt = 0;
2072             track->audio.pkt_cnt = h*w / a;
2073         }
2074     }
2075
2076     while (track->audio.pkt_cnt) {
2077         AVPacket *pkt = NULL;
2078         if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0){
2079             av_free(pkt);
2080             return AVERROR(ENOMEM);
2081         }
2082         memcpy(pkt->data, track->audio.buf
2083                + a * (h*w / a - track->audio.pkt_cnt--), a);
2084         pkt->pts = track->audio.buf_timecode;
2085         track->audio.buf_timecode = AV_NOPTS_VALUE;
2086         pkt->pos = pos;
2087         pkt->stream_index = st->index;
2088         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2089     }
2090
2091     return 0;
2092 }
2093 static int matroska_parse_frame(MatroskaDemuxContext *matroska,
2094                                 MatroskaTrack *track,
2095                                 AVStream *st,
2096                                 uint8_t *data, int pkt_size,
2097                                 uint64_t timecode, uint64_t lace_duration,
2098                                 int64_t pos, int is_keyframe,
2099                                 uint8_t *additional, uint64_t additional_id, int additional_size)
2100 {
2101     MatroskaTrackEncoding *encodings = track->encodings.elem;
2102     uint8_t *pkt_data = data;
2103     int offset = 0, res;
2104     AVPacket *pkt;
2105
2106     if (encodings && encodings->scope & 1) {
2107         res = matroska_decode_buffer(&pkt_data, &pkt_size, track);
2108         if (res < 0)
2109             return res;
2110     }
2111
2112     if (st->codec->codec_id == AV_CODEC_ID_PRORES)
2113         offset = 8;
2114
2115     pkt = av_mallocz(sizeof(AVPacket));
2116     /* XXX: prevent data copy... */
2117     if (av_new_packet(pkt, pkt_size + offset) < 0) {
2118         av_free(pkt);
2119         return AVERROR(ENOMEM);
2120     }
2121
2122     if (st->codec->codec_id == AV_CODEC_ID_PRORES) {
2123         uint8_t *buf = pkt->data;
2124         bytestream_put_be32(&buf, pkt_size);
2125         bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));
2126     }
2127
2128     memcpy(pkt->data + offset, pkt_data, pkt_size);
2129
2130     if (pkt_data != data)
2131         av_free(pkt_data);
2132
2133     pkt->flags = is_keyframe;
2134     pkt->stream_index = st->index;
2135
2136     if (additional_size > 0) {
2137         uint8_t *side_data = av_packet_new_side_data(pkt,
2138                                                      AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
2139                                                      additional_size + 8);
2140         if(side_data == NULL) {
2141             return AVERROR(ENOMEM);
2142         }
2143         AV_WB64(side_data, additional_id);
2144         memcpy(side_data + 8, additional, additional_size);
2145     }
2146
2147     if (track->ms_compat)
2148         pkt->dts = timecode;
2149     else
2150         pkt->pts = timecode;
2151     pkt->pos = pos;
2152     if (st->codec->codec_id == AV_CODEC_ID_SUBRIP) {
2153         /*
2154          * For backward compatibility.
2155          * Historically, we have put subtitle duration
2156          * in convergence_duration, on the off chance
2157          * that the time_scale is less than 1us, which
2158          * could result in a 32bit overflow on the
2159          * normal duration field.
2160          */
2161         pkt->convergence_duration = lace_duration;
2162     }
2163
2164     if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE ||
2165         lace_duration <= INT_MAX) {
2166         /*
2167          * For non subtitle tracks, just store the duration
2168          * as normal.
2169          *
2170          * If it's a subtitle track and duration value does
2171          * not overflow a uint32, then also store it normally.
2172          */
2173         pkt->duration = lace_duration;
2174     }
2175
2176     if (st->codec->codec_id == AV_CODEC_ID_SSA)
2177         matroska_fix_ass_packet(matroska, pkt, lace_duration);
2178
2179     if (matroska->prev_pkt &&
2180         timecode != AV_NOPTS_VALUE &&
2181         matroska->prev_pkt->pts == timecode &&
2182         matroska->prev_pkt->stream_index == st->index &&
2183         st->codec->codec_id == AV_CODEC_ID_SSA)
2184         matroska_merge_packets(matroska->prev_pkt, pkt);
2185     else {
2186         dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2187         matroska->prev_pkt = pkt;
2188     }
2189
2190     return 0;
2191 }
2192
2193 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
2194                                 int size, int64_t pos, uint64_t cluster_time,
2195                                 uint64_t block_duration, int is_keyframe,
2196                                 uint8_t *additional, uint64_t additional_id, int additional_size,
2197                                 int64_t cluster_pos)
2198 {
2199     uint64_t timecode = AV_NOPTS_VALUE;
2200     MatroskaTrack *track;
2201     int res = 0;
2202     AVStream *st;
2203     int16_t block_time;
2204     uint32_t *lace_size = NULL;
2205     int n, flags, laces = 0;
2206     uint64_t num;
2207
2208     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2209         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2210         return n;
2211     }
2212     data += n;
2213     size -= n;
2214
2215     track = matroska_find_track_by_num(matroska, num);
2216     if (!track || !track->stream) {
2217         av_log(matroska->ctx, AV_LOG_INFO,
2218                "Invalid stream %"PRIu64" or size %u\n", num, size);
2219         return AVERROR_INVALIDDATA;
2220     } else if (size <= 3)
2221         return 0;
2222     st = track->stream;
2223     if (st->discard >= AVDISCARD_ALL)
2224         return res;
2225     av_assert1(block_duration != AV_NOPTS_VALUE);
2226
2227     block_time = AV_RB16(data);
2228     data += 2;
2229     flags = *data++;
2230     size -= 3;
2231     if (is_keyframe == -1)
2232         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
2233
2234     if (cluster_time != (uint64_t)-1
2235         && (block_time >= 0 || cluster_time >= -block_time)) {
2236         timecode = cluster_time + block_time;
2237         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
2238             && timecode < track->end_timecode)
2239             is_keyframe = 0;  /* overlapping subtitles are not key frame */
2240         if (is_keyframe)
2241             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
2242     }
2243
2244     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
2245         if (timecode < matroska->skip_to_timecode)
2246             return res;
2247         if (!st->skip_to_keyframe) {
2248             av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
2249             matroska->skip_to_keyframe = 0;
2250         }
2251         if (is_keyframe)
2252             matroska->skip_to_keyframe = 0;
2253     }
2254
2255     res = matroska_parse_laces(matroska, &data, size, (flags & 0x06) >> 1,
2256                                &lace_size, &laces);
2257
2258     if (res)
2259         goto end;
2260
2261     if (!block_duration)
2262         block_duration = track->default_duration * laces / matroska->time_scale;
2263
2264     if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))
2265         track->end_timecode =
2266             FFMAX(track->end_timecode, timecode + block_duration);
2267
2268     for (n = 0; n < laces; n++) {
2269         int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;
2270
2271         if (lace_size[n] > size) {
2272             av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
2273             break;
2274         }
2275
2276         if ((st->codec->codec_id == AV_CODEC_ID_RA_288 ||
2277              st->codec->codec_id == AV_CODEC_ID_COOK ||
2278              st->codec->codec_id == AV_CODEC_ID_SIPR ||
2279              st->codec->codec_id == AV_CODEC_ID_ATRAC3) &&
2280              st->codec->block_align && track->audio.sub_packet_size) {
2281
2282             res = matroska_parse_rm_audio(matroska, track, st, data, size,
2283                                           timecode, pos);
2284             if (res)
2285                 goto end;
2286
2287         } else {
2288             res = matroska_parse_frame(matroska, track, st, data, lace_size[n],
2289                                       timecode, lace_duration,
2290                                       pos, !n? is_keyframe : 0,
2291                                       additional, additional_id, additional_size);
2292             if (res)
2293                 goto end;
2294         }
2295
2296         if (timecode != AV_NOPTS_VALUE)
2297             timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;
2298         data += lace_size[n];
2299         size -= lace_size[n];
2300     }
2301
2302 end:
2303     av_free(lace_size);
2304     return res;
2305 }
2306
2307 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
2308 {
2309     EbmlList *blocks_list;
2310     MatroskaBlock *blocks;
2311     int i, res;
2312     res = ebml_parse(matroska,
2313                      matroska_cluster_incremental_parsing,
2314                      &matroska->current_cluster);
2315     if (res == 1) {
2316         /* New Cluster */
2317         if (matroska->current_cluster_pos)
2318             ebml_level_end(matroska);
2319         ebml_free(matroska_cluster, &matroska->current_cluster);
2320         memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2321         matroska->current_cluster_num_blocks = 0;
2322         matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2323         matroska->prev_pkt = NULL;
2324         /* sizeof the ID which was already read */
2325         if (matroska->current_id)
2326             matroska->current_cluster_pos -= 4;
2327         res = ebml_parse(matroska,
2328                          matroska_clusters_incremental,
2329                          &matroska->current_cluster);
2330         /* Try parsing the block again. */
2331         if (res == 1)
2332             res = ebml_parse(matroska,
2333                              matroska_cluster_incremental_parsing,
2334                              &matroska->current_cluster);
2335     }
2336
2337     if (!res &&
2338         matroska->current_cluster_num_blocks <
2339             matroska->current_cluster.blocks.nb_elem) {
2340         blocks_list = &matroska->current_cluster.blocks;
2341         blocks = blocks_list->elem;
2342
2343         matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2344         i = blocks_list->nb_elem - 1;
2345         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2346             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2347             uint8_t* additional = blocks[i].additional.size > 0 ?
2348                                     blocks[i].additional.data : NULL;
2349             if (!blocks[i].non_simple)
2350                 blocks[i].duration = 0;
2351             res = matroska_parse_block(matroska,
2352                                        blocks[i].bin.data, blocks[i].bin.size,
2353                                        blocks[i].bin.pos,
2354                                        matroska->current_cluster.timecode,
2355                                        blocks[i].duration, is_keyframe,
2356                                        additional, blocks[i].additional_id,
2357                                        blocks[i].additional.size,
2358                                        matroska->current_cluster_pos);
2359         }
2360     }
2361
2362     if (res < 0)  matroska->done = 1;
2363     return res;
2364 }
2365
2366 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2367 {
2368     MatroskaCluster cluster = { 0 };
2369     EbmlList *blocks_list;
2370     MatroskaBlock *blocks;
2371     int i, res;
2372     int64_t pos;
2373     if (!matroska->contains_ssa)
2374         return matroska_parse_cluster_incremental(matroska);
2375     pos = avio_tell(matroska->ctx->pb);
2376     matroska->prev_pkt = NULL;
2377     if (matroska->current_id)
2378         pos -= 4;  /* sizeof the ID which was already read */
2379     res = ebml_parse(matroska, matroska_clusters, &cluster);
2380     blocks_list = &cluster.blocks;
2381     blocks = blocks_list->elem;
2382     for (i=0; i<blocks_list->nb_elem; i++)
2383         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2384             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2385             res=matroska_parse_block(matroska,
2386                                      blocks[i].bin.data, blocks[i].bin.size,
2387                                      blocks[i].bin.pos,  cluster.timecode,
2388                                      blocks[i].duration, is_keyframe, NULL, 0, 0,
2389                                      pos);
2390         }
2391     ebml_free(matroska_cluster, &cluster);
2392     return res;
2393 }
2394
2395 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2396 {
2397     MatroskaDemuxContext *matroska = s->priv_data;
2398
2399     while (matroska_deliver_packet(matroska, pkt)) {
2400         int64_t pos = avio_tell(matroska->ctx->pb);
2401         if (matroska->done)
2402             return AVERROR_EOF;
2403         if (matroska_parse_cluster(matroska) < 0)
2404             matroska_resync(matroska, pos);
2405     }
2406
2407     return 0;
2408 }
2409
2410 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2411                               int64_t timestamp, int flags)
2412 {
2413     MatroskaDemuxContext *matroska = s->priv_data;
2414     MatroskaTrack *tracks = matroska->tracks.elem;
2415     AVStream *st = s->streams[stream_index];
2416     int i, index, index_sub, index_min;
2417
2418     /* Parse the CUES now since we need the index data to seek. */
2419     if (matroska->cues_parsing_deferred > 0) {
2420         matroska->cues_parsing_deferred = 0;
2421         matroska_parse_cues(matroska);
2422     }
2423
2424     if (!st->nb_index_entries)
2425         goto err;
2426     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2427
2428     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2429         avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2430         matroska->current_id = 0;
2431         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2432             matroska_clear_queue(matroska);
2433             if (matroska_parse_cluster(matroska) < 0)
2434                 break;
2435         }
2436     }
2437
2438     matroska_clear_queue(matroska);
2439     if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
2440         goto err;
2441
2442     index_min = index;
2443     for (i=0; i < matroska->tracks.nb_elem; i++) {
2444         tracks[i].audio.pkt_cnt = 0;
2445         tracks[i].audio.sub_packet_cnt = 0;
2446         tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2447         tracks[i].end_timecode = 0;
2448         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2449             && tracks[i].stream->discard != AVDISCARD_ALL) {
2450             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2451             if (index_sub >= 0
2452                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2453                 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2454                 index_min = index_sub;
2455         }
2456     }
2457
2458     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2459     matroska->current_id = 0;
2460     if (flags & AVSEEK_FLAG_ANY) {
2461         st->skip_to_keyframe = 0;
2462         matroska->skip_to_timecode = timestamp;
2463     } else {
2464         st->skip_to_keyframe = 1;
2465         matroska->skip_to_timecode = st->index_entries[index].timestamp;
2466     }
2467     matroska->skip_to_keyframe = 1;
2468     matroska->done = 0;
2469     matroska->num_levels = 0;
2470     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2471     return 0;
2472 err:
2473     // slightly hackish but allows proper fallback to
2474     // the generic seeking code.
2475     matroska_clear_queue(matroska);
2476     matroska->current_id = 0;
2477     st->skip_to_keyframe =
2478     matroska->skip_to_keyframe = 0;
2479     matroska->done = 0;
2480     matroska->num_levels = 0;
2481     return -1;
2482 }
2483
2484 static int matroska_read_close(AVFormatContext *s)
2485 {
2486     MatroskaDemuxContext *matroska = s->priv_data;
2487     MatroskaTrack *tracks = matroska->tracks.elem;
2488     int n;
2489
2490     matroska_clear_queue(matroska);
2491
2492     for (n=0; n < matroska->tracks.nb_elem; n++)
2493         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2494             av_free(tracks[n].audio.buf);
2495     ebml_free(matroska_cluster, &matroska->current_cluster);
2496     ebml_free(matroska_segment, matroska);
2497
2498     return 0;
2499 }
2500
2501 AVInputFormat ff_matroska_demuxer = {
2502     .name           = "matroska,webm",
2503     .long_name      = NULL_IF_CONFIG_SMALL("Matroska / WebM"),
2504     .priv_data_size = sizeof(MatroskaDemuxContext),
2505     .read_probe     = matroska_probe,
2506     .read_header    = matroska_read_header,
2507     .read_packet    = matroska_read_packet,
2508     .read_close     = matroska_read_close,
2509     .read_seek      = matroska_read_seek,
2510 };