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