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