OSDN Git Service

Merge remote-tracking branch 'qatar/master'
[coroid/ffmpeg_saccubus.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     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     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_BIN,  0, offsetof(MatroskaTrackVideo,color_space) },
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         uint32_t fourcc = 0;
1285         AVIOContext b;
1286
1287         /* Apply some sanity checks. */
1288         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1289             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1290             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1291             av_log(matroska->ctx, AV_LOG_INFO,
1292                    "Unknown or unsupported track type %"PRIu64"\n",
1293                    track->type);
1294             continue;
1295         }
1296         if (track->codec_id == NULL)
1297             continue;
1298
1299         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1300             if (!track->default_duration)
1301                 track->default_duration = 1000000000/track->video.frame_rate;
1302             if (!track->video.display_width)
1303                 track->video.display_width = track->video.pixel_width;
1304             if (!track->video.display_height)
1305                 track->video.display_height = track->video.pixel_height;
1306             if (track->video.color_space.size == 4)
1307                 fourcc = AV_RL32(track->video.color_space.data);
1308         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1309             if (!track->audio.out_samplerate)
1310                 track->audio.out_samplerate = track->audio.samplerate;
1311         }
1312         if (encodings_list->nb_elem > 1) {
1313             av_log(matroska->ctx, AV_LOG_ERROR,
1314                    "Multiple combined encodings no supported");
1315         } else if (encodings_list->nb_elem == 1) {
1316             if (encodings[0].type ||
1317                 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1318 #if CONFIG_ZLIB
1319                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1320 #endif
1321 #if CONFIG_BZLIB
1322                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1323 #endif
1324                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1325                 encodings[0].scope = 0;
1326                 av_log(matroska->ctx, AV_LOG_ERROR,
1327                        "Unsupported encoding type");
1328             } else if (track->codec_priv.size && encodings[0].scope&2) {
1329                 uint8_t *codec_priv = track->codec_priv.data;
1330                 int offset = matroska_decode_buffer(&track->codec_priv.data,
1331                                                     &track->codec_priv.size,
1332                                                     track);
1333                 if (offset < 0) {
1334                     track->codec_priv.data = NULL;
1335                     track->codec_priv.size = 0;
1336                     av_log(matroska->ctx, AV_LOG_ERROR,
1337                            "Failed to decode codec private data\n");
1338                 } else if (offset > 0) {
1339                     track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1340                     memcpy(track->codec_priv.data,
1341                            encodings[0].compression.settings.data, offset);
1342                     memcpy(track->codec_priv.data+offset, codec_priv,
1343                            track->codec_priv.size);
1344                     track->codec_priv.size += offset;
1345                 }
1346                 if (codec_priv != track->codec_priv.data)
1347                     av_free(codec_priv);
1348             }
1349         }
1350
1351         for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1352             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1353                         strlen(ff_mkv_codec_tags[j].str))){
1354                 codec_id= ff_mkv_codec_tags[j].id;
1355                 break;
1356             }
1357         }
1358
1359         st = track->stream = av_new_stream(s, 0);
1360         if (st == NULL)
1361             return AVERROR(ENOMEM);
1362
1363         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1364             && track->codec_priv.size >= 40
1365             && track->codec_priv.data != NULL) {
1366             track->ms_compat = 1;
1367             fourcc = AV_RL32(track->codec_priv.data + 16);
1368             codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
1369             extradata_offset = 40;
1370         } else if (!strcmp(track->codec_id, "A_MS/ACM")
1371                    && track->codec_priv.size >= 14
1372                    && track->codec_priv.data != NULL) {
1373             int ret;
1374             ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1375                           AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
1376             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1377             if (ret < 0)
1378                 return ret;
1379             codec_id = st->codec->codec_id;
1380             extradata_offset = FFMIN(track->codec_priv.size, 18);
1381         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1382                    && (track->codec_priv.size >= 86)
1383                    && (track->codec_priv.data != NULL)) {
1384             fourcc = AV_RL32(track->codec_priv.data);
1385             codec_id = ff_codec_get_id(codec_movvideo_tags, fourcc);
1386         } else if (codec_id == CODEC_ID_PCM_S16BE) {
1387             switch (track->audio.bitdepth) {
1388             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1389             case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
1390             case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
1391             }
1392         } else if (codec_id == CODEC_ID_PCM_S16LE) {
1393             switch (track->audio.bitdepth) {
1394             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1395             case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
1396             case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
1397             }
1398         } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1399             codec_id = CODEC_ID_PCM_F64LE;
1400         } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1401             int profile = matroska_aac_profile(track->codec_id);
1402             int sri = matroska_aac_sri(track->audio.samplerate);
1403             extradata = av_malloc(5);
1404             if (extradata == NULL)
1405                 return AVERROR(ENOMEM);
1406             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1407             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1408             if (strstr(track->codec_id, "SBR")) {
1409                 sri = matroska_aac_sri(track->audio.out_samplerate);
1410                 extradata[2] = 0x56;
1411                 extradata[3] = 0xE5;
1412                 extradata[4] = 0x80 | (sri<<3);
1413                 extradata_size = 5;
1414             } else
1415                 extradata_size = 2;
1416         } else if (codec_id == CODEC_ID_TTA) {
1417             extradata_size = 30;
1418             extradata = av_mallocz(extradata_size);
1419             if (extradata == NULL)
1420                 return AVERROR(ENOMEM);
1421             ffio_init_context(&b, extradata, extradata_size, 1,
1422                           NULL, NULL, NULL, NULL);
1423             avio_write(&b, "TTA1", 4);
1424             avio_wl16(&b, 1);
1425             avio_wl16(&b, track->audio.channels);
1426             avio_wl16(&b, track->audio.bitdepth);
1427             avio_wl32(&b, track->audio.out_samplerate);
1428             avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1429         } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1430                    codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1431             extradata_offset = 26;
1432         } else if (codec_id == CODEC_ID_RA_144) {
1433             track->audio.out_samplerate = 8000;
1434             track->audio.channels = 1;
1435         } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1436                    codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1437             int flavor;
1438             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1439                           0, NULL, NULL, NULL, NULL);
1440             avio_skip(&b, 22);
1441             flavor                       = avio_rb16(&b);
1442             track->audio.coded_framesize = avio_rb32(&b);
1443             avio_skip(&b, 12);
1444             track->audio.sub_packet_h    = avio_rb16(&b);
1445             track->audio.frame_size      = avio_rb16(&b);
1446             track->audio.sub_packet_size = avio_rb16(&b);
1447             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1448             if (codec_id == CODEC_ID_RA_288) {
1449                 st->codec->block_align = track->audio.coded_framesize;
1450                 track->codec_priv.size = 0;
1451             } else {
1452                 if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1453                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1454                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1455                     st->codec->bit_rate = sipr_bit_rate[flavor];
1456                 }
1457                 st->codec->block_align = track->audio.sub_packet_size;
1458                 extradata_offset = 78;
1459             }
1460         }
1461         track->codec_priv.size -= extradata_offset;
1462
1463         if (codec_id == CODEC_ID_NONE)
1464             av_log(matroska->ctx, AV_LOG_INFO,
1465                    "Unknown/unsupported CodecID %s.\n", track->codec_id);
1466
1467         if (track->time_scale < 0.01)
1468             track->time_scale = 1.0;
1469         av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1470
1471         st->codec->codec_id = codec_id;
1472         st->start_time = 0;
1473         if (strcmp(track->language, "und"))
1474             av_dict_set(&st->metadata, "language", track->language, 0);
1475         av_dict_set(&st->metadata, "title", track->name, 0);
1476
1477         if (track->flag_default)
1478             st->disposition |= AV_DISPOSITION_DEFAULT;
1479         if (track->flag_forced)
1480             st->disposition |= AV_DISPOSITION_FORCED;
1481
1482         if (track->default_duration)
1483             av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1484                       track->default_duration, 1000000000, 30000);
1485
1486         if (!st->codec->extradata) {
1487             if(extradata){
1488                 st->codec->extradata = extradata;
1489                 st->codec->extradata_size = extradata_size;
1490             } else if(track->codec_priv.data && track->codec_priv.size > 0){
1491                 st->codec->extradata = av_mallocz(track->codec_priv.size +
1492                                                   FF_INPUT_BUFFER_PADDING_SIZE);
1493                 if(st->codec->extradata == NULL)
1494                     return AVERROR(ENOMEM);
1495                 st->codec->extradata_size = track->codec_priv.size;
1496                 memcpy(st->codec->extradata,
1497                        track->codec_priv.data + extradata_offset,
1498                        track->codec_priv.size);
1499             }
1500         }
1501
1502         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1503             MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
1504
1505             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1506             st->codec->codec_tag  = fourcc;
1507             st->codec->width  = track->video.pixel_width;
1508             st->codec->height = track->video.pixel_height;
1509             av_reduce(&st->sample_aspect_ratio.num,
1510                       &st->sample_aspect_ratio.den,
1511                       st->codec->height * track->video.display_width,
1512                       st->codec-> width * track->video.display_height,
1513                       255);
1514             if (st->codec->codec_id != CODEC_ID_H264)
1515             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1516             if (track->default_duration)
1517                 st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
1518
1519             /* export stereo mode flag as metadata tag */
1520             if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
1521                 av_dict_set(&st->metadata, "stereo_mode", matroska_video_stereo_mode[track->video.stereo_mode], 0);
1522
1523             /* if we have virtual track, mark the real tracks */
1524             for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
1525                 char buf[32];
1526                 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
1527                     continue;
1528                 snprintf(buf, sizeof(buf), "%s_%d",
1529                          matroska_video_stereo_plane[planes[j].type], i);
1530                 for (k=0; k < matroska->tracks.nb_elem; k++)
1531                     if (planes[j].uid == tracks[k].uid) {
1532                         av_dict_set(&s->streams[k]->metadata,
1533                                     "stereo_mode", buf, 0);
1534                         break;
1535                     }
1536             }
1537         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1538             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1539             st->codec->sample_rate = track->audio.out_samplerate;
1540             st->codec->channels = track->audio.channels;
1541             if (st->codec->codec_id != CODEC_ID_AAC)
1542             st->need_parsing = AVSTREAM_PARSE_HEADERS;
1543         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1544             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1545         }
1546     }
1547
1548     attachements = attachements_list->elem;
1549     for (j=0; j<attachements_list->nb_elem; j++) {
1550         if (!(attachements[j].filename && attachements[j].mime &&
1551               attachements[j].bin.data && attachements[j].bin.size > 0)) {
1552             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1553         } else {
1554             AVStream *st = av_new_stream(s, 0);
1555             if (st == NULL)
1556                 break;
1557             av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1558             st->codec->codec_id = CODEC_ID_NONE;
1559             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1560             st->codec->extradata  = av_malloc(attachements[j].bin.size);
1561             if(st->codec->extradata == NULL)
1562                 break;
1563             st->codec->extradata_size = attachements[j].bin.size;
1564             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1565
1566             for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1567                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1568                              strlen(ff_mkv_mime_tags[i].str))) {
1569                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
1570                     break;
1571                 }
1572             }
1573             attachements[j].stream = st;
1574         }
1575     }
1576
1577     chapters = chapters_list->elem;
1578     for (i=0; i<chapters_list->nb_elem; i++)
1579         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1580             && (max_start==0 || chapters[i].start > max_start)) {
1581             chapters[i].chapter =
1582             ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1583                            chapters[i].start, chapters[i].end,
1584                            chapters[i].title);
1585             av_dict_set(&chapters[i].chapter->metadata,
1586                              "title", chapters[i].title, 0);
1587             max_start = chapters[i].start;
1588         }
1589
1590     index_list = &matroska->index;
1591     index = index_list->elem;
1592     if (index_list->nb_elem
1593         && index[0].time > 100000000000000/matroska->time_scale) {
1594         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1595         index_scale = matroska->time_scale;
1596     }
1597     for (i=0; i<index_list->nb_elem; i++) {
1598         EbmlList *pos_list = &index[i].pos;
1599         MatroskaIndexPos *pos = pos_list->elem;
1600         for (j=0; j<pos_list->nb_elem; j++) {
1601             MatroskaTrack *track = matroska_find_track_by_num(matroska,
1602                                                               pos[j].track);
1603             if (track && track->stream)
1604                 av_add_index_entry(track->stream,
1605                                    pos[j].pos + matroska->segment_start,
1606                                    index[i].time/index_scale, 0, 0,
1607                                    AVINDEX_KEYFRAME);
1608         }
1609     }
1610
1611     matroska_convert_tags(s);
1612
1613     return 0;
1614 }
1615
1616 /*
1617  * Put one packet in an application-supplied AVPacket struct.
1618  * Returns 0 on success or -1 on failure.
1619  */
1620 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1621                                    AVPacket *pkt)
1622 {
1623     if (matroska->num_packets > 0) {
1624         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1625         av_free(matroska->packets[0]);
1626         if (matroska->num_packets > 1) {
1627             memmove(&matroska->packets[0], &matroska->packets[1],
1628                     (matroska->num_packets - 1) * sizeof(AVPacket *));
1629             matroska->packets =
1630                 av_realloc(matroska->packets, (matroska->num_packets - 1) *
1631                            sizeof(AVPacket *));
1632         } else {
1633             av_freep(&matroska->packets);
1634         }
1635         matroska->num_packets--;
1636         return 0;
1637     }
1638
1639     return -1;
1640 }
1641
1642 /*
1643  * Free all packets in our internal queue.
1644  */
1645 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1646 {
1647     if (matroska->packets) {
1648         int n;
1649         for (n = 0; n < matroska->num_packets; n++) {
1650             av_free_packet(matroska->packets[n]);
1651             av_free(matroska->packets[n]);
1652         }
1653         av_freep(&matroska->packets);
1654         matroska->num_packets = 0;
1655     }
1656 }
1657
1658 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1659                                 int size, int64_t pos, uint64_t cluster_time,
1660                                 uint64_t duration, int is_keyframe,
1661                                 int64_t cluster_pos)
1662 {
1663     uint64_t timecode = AV_NOPTS_VALUE;
1664     MatroskaTrack *track;
1665     int res = 0;
1666     AVStream *st;
1667     AVPacket *pkt;
1668     int16_t block_time;
1669     uint32_t *lace_size = NULL;
1670     int n, flags, laces = 0;
1671     uint64_t num;
1672
1673     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1674         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1675         return res;
1676     }
1677     data += n;
1678     size -= n;
1679
1680     track = matroska_find_track_by_num(matroska, num);
1681     if (size <= 3 || !track || !track->stream) {
1682         av_log(matroska->ctx, AV_LOG_INFO,
1683                "Invalid stream %"PRIu64" or size %u\n", num, size);
1684         return res;
1685     }
1686     st = track->stream;
1687     if (st->discard >= AVDISCARD_ALL)
1688         return res;
1689     if (!duration)
1690         duration = track->default_duration / matroska->time_scale;
1691
1692     block_time = AV_RB16(data);
1693     data += 2;
1694     flags = *data++;
1695     size -= 3;
1696     if (is_keyframe == -1)
1697         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1698
1699     if (cluster_time != (uint64_t)-1
1700         && (block_time >= 0 || cluster_time >= -block_time)) {
1701         timecode = cluster_time + block_time;
1702         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1703             && timecode < track->end_timecode)
1704             is_keyframe = 0;  /* overlapping subtitles are not key frame */
1705         if (is_keyframe)
1706             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1707         track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1708     }
1709
1710     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1711         if (!is_keyframe || timecode < matroska->skip_to_timecode)
1712             return res;
1713         matroska->skip_to_keyframe = 0;
1714     }
1715
1716     switch ((flags & 0x06) >> 1) {
1717         case 0x0: /* no lacing */
1718             laces = 1;
1719             lace_size = av_mallocz(sizeof(int));
1720             lace_size[0] = size;
1721             break;
1722
1723         case 0x1: /* Xiph lacing */
1724         case 0x2: /* fixed-size lacing */
1725         case 0x3: /* EBML lacing */
1726             assert(size>0); // size <=3 is checked before size-=3 above
1727             laces = (*data) + 1;
1728             data += 1;
1729             size -= 1;
1730             lace_size = av_mallocz(laces * sizeof(int));
1731
1732             switch ((flags & 0x06) >> 1) {
1733                 case 0x1: /* Xiph lacing */ {
1734                     uint8_t temp;
1735                     uint32_t total = 0;
1736                     for (n = 0; res == 0 && n < laces - 1; n++) {
1737                         while (1) {
1738                             if (size == 0) {
1739                                 res = -1;
1740                                 break;
1741                             }
1742                             temp = *data;
1743                             lace_size[n] += temp;
1744                             data += 1;
1745                             size -= 1;
1746                             if (temp != 0xff)
1747                                 break;
1748                         }
1749                         total += lace_size[n];
1750                     }
1751                     lace_size[n] = size - total;
1752                     break;
1753                 }
1754
1755                 case 0x2: /* fixed-size lacing */
1756                     for (n = 0; n < laces; n++)
1757                         lace_size[n] = size / laces;
1758                     break;
1759
1760                 case 0x3: /* EBML lacing */ {
1761                     uint32_t total;
1762                     n = matroska_ebmlnum_uint(matroska, data, size, &num);
1763                     if (n < 0) {
1764                         av_log(matroska->ctx, AV_LOG_INFO,
1765                                "EBML block data error\n");
1766                         break;
1767                     }
1768                     data += n;
1769                     size -= n;
1770                     total = lace_size[0] = num;
1771                     for (n = 1; res == 0 && n < laces - 1; n++) {
1772                         int64_t snum;
1773                         int r;
1774                         r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1775                         if (r < 0) {
1776                             av_log(matroska->ctx, AV_LOG_INFO,
1777                                    "EBML block data error\n");
1778                             break;
1779                         }
1780                         data += r;
1781                         size -= r;
1782                         lace_size[n] = lace_size[n - 1] + snum;
1783                         total += lace_size[n];
1784                     }
1785                     lace_size[n] = size - total;
1786                     break;
1787                 }
1788             }
1789             break;
1790     }
1791
1792     if (res == 0) {
1793         for (n = 0; n < laces; n++) {
1794             if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1795                  st->codec->codec_id == CODEC_ID_COOK ||
1796                  st->codec->codec_id == CODEC_ID_SIPR ||
1797                  st->codec->codec_id == CODEC_ID_ATRAC3) &&
1798                  st->codec->block_align && track->audio.sub_packet_size) {
1799                 int a = st->codec->block_align;
1800                 int sps = track->audio.sub_packet_size;
1801                 int cfs = track->audio.coded_framesize;
1802                 int h = track->audio.sub_packet_h;
1803                 int y = track->audio.sub_packet_cnt;
1804                 int w = track->audio.frame_size;
1805                 int x;
1806
1807                 if (!track->audio.pkt_cnt) {
1808                     if (track->audio.sub_packet_cnt == 0)
1809                         track->audio.buf_timecode = timecode;
1810                     if (st->codec->codec_id == CODEC_ID_RA_288)
1811                         for (x=0; x<h/2; x++)
1812                             memcpy(track->audio.buf+x*2*w+y*cfs,
1813                                    data+x*cfs, cfs);
1814                     else if (st->codec->codec_id == CODEC_ID_SIPR)
1815                         memcpy(track->audio.buf + y*w, data, w);
1816                     else
1817                         for (x=0; x<w/sps; x++)
1818                             memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1819
1820                     if (++track->audio.sub_packet_cnt >= h) {
1821                         if (st->codec->codec_id == CODEC_ID_SIPR)
1822                             ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1823                         track->audio.sub_packet_cnt = 0;
1824                         track->audio.pkt_cnt = h*w / a;
1825                     }
1826                 }
1827                 while (track->audio.pkt_cnt) {
1828                     pkt = av_mallocz(sizeof(AVPacket));
1829                     av_new_packet(pkt, a);
1830                     memcpy(pkt->data, track->audio.buf
1831                            + a * (h*w / a - track->audio.pkt_cnt--), a);
1832                     pkt->pts = track->audio.buf_timecode;
1833                     track->audio.buf_timecode = AV_NOPTS_VALUE;
1834                     pkt->pos = pos;
1835                     pkt->stream_index = st->index;
1836                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1837                 }
1838             } else {
1839                 MatroskaTrackEncoding *encodings = track->encodings.elem;
1840                 int offset = 0, pkt_size = lace_size[n];
1841                 uint8_t *pkt_data = data;
1842
1843                 if (pkt_size > size) {
1844                     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1845                     break;
1846                 }
1847
1848                 if (encodings && encodings->scope & 1) {
1849                     offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1850                     if (offset < 0)
1851                         continue;
1852                 }
1853
1854                 pkt = av_mallocz(sizeof(AVPacket));
1855                 /* XXX: prevent data copy... */
1856                 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1857                     av_free(pkt);
1858                     res = AVERROR(ENOMEM);
1859                     break;
1860                 }
1861                 if (offset)
1862                     memcpy (pkt->data, encodings->compression.settings.data, offset);
1863                 memcpy (pkt->data+offset, pkt_data, pkt_size);
1864
1865                 if (pkt_data != data)
1866                     av_free(pkt_data);
1867
1868                 if (n == 0)
1869                     pkt->flags = is_keyframe;
1870                 pkt->stream_index = st->index;
1871
1872                 if (track->ms_compat)
1873                     pkt->dts = timecode;
1874                 else
1875                     pkt->pts = timecode;
1876                 pkt->pos = pos;
1877                 if (st->codec->codec_id == CODEC_ID_TEXT)
1878                     pkt->convergence_duration = duration;
1879                 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1880                     pkt->duration = duration;
1881
1882                 if (st->codec->codec_id == CODEC_ID_SSA)
1883                     matroska_fix_ass_packet(matroska, pkt, duration);
1884
1885                 if (matroska->prev_pkt &&
1886                     timecode != AV_NOPTS_VALUE &&
1887                     matroska->prev_pkt->pts == timecode &&
1888                     matroska->prev_pkt->stream_index == st->index &&
1889                     st->codec->codec_id == CODEC_ID_SSA)
1890                     matroska_merge_packets(matroska->prev_pkt, pkt);
1891                 else {
1892                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1893                     matroska->prev_pkt = pkt;
1894                 }
1895             }
1896
1897             if (timecode != AV_NOPTS_VALUE)
1898                 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1899             data += lace_size[n];
1900             size -= lace_size[n];
1901         }
1902     }
1903
1904     av_free(lace_size);
1905     return res;
1906 }
1907
1908 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1909 {
1910     MatroskaCluster cluster = { 0 };
1911     EbmlList *blocks_list;
1912     MatroskaBlock *blocks;
1913     int i, res;
1914     int64_t pos = avio_tell(matroska->ctx->pb);
1915     matroska->prev_pkt = NULL;
1916     if (matroska->current_id)
1917         pos -= 4;  /* sizeof the ID which was already read */
1918     res = ebml_parse(matroska, matroska_clusters, &cluster);
1919     blocks_list = &cluster.blocks;
1920     blocks = blocks_list->elem;
1921     for (i=0; i<blocks_list->nb_elem; i++)
1922         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
1923             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
1924             res=matroska_parse_block(matroska,
1925                                      blocks[i].bin.data, blocks[i].bin.size,
1926                                      blocks[i].bin.pos,  cluster.timecode,
1927                                      blocks[i].duration, is_keyframe,
1928                                      pos);
1929         }
1930     ebml_free(matroska_cluster, &cluster);
1931     if (res < 0)  matroska->done = 1;
1932     return res;
1933 }
1934
1935 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1936 {
1937     MatroskaDemuxContext *matroska = s->priv_data;
1938
1939     while (matroska_deliver_packet(matroska, pkt)) {
1940         if (matroska->done)
1941             return AVERROR_EOF;
1942         matroska_parse_cluster(matroska);
1943     }
1944
1945     return 0;
1946 }
1947
1948 static int matroska_read_seek(AVFormatContext *s, int stream_index,
1949                               int64_t timestamp, int flags)
1950 {
1951     MatroskaDemuxContext *matroska = s->priv_data;
1952     MatroskaTrack *tracks = matroska->tracks.elem;
1953     AVStream *st = s->streams[stream_index];
1954     int i, index, index_sub, index_min;
1955
1956     if (!st->nb_index_entries)
1957         return 0;
1958     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1959
1960     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1961         avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1962         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1963             matroska_clear_queue(matroska);
1964             if (matroska_parse_cluster(matroska) < 0)
1965                 break;
1966         }
1967     }
1968
1969     matroska_clear_queue(matroska);
1970     if (index < 0)
1971         return 0;
1972
1973     index_min = index;
1974     for (i=0; i < matroska->tracks.nb_elem; i++) {
1975         tracks[i].audio.pkt_cnt = 0;
1976         tracks[i].audio.sub_packet_cnt = 0;
1977         tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
1978         tracks[i].end_timecode = 0;
1979         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1980             && !tracks[i].stream->discard != AVDISCARD_ALL) {
1981             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1982             if (index_sub >= 0
1983                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1984                 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1985                 index_min = index_sub;
1986         }
1987     }
1988
1989     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
1990     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1991     matroska->skip_to_timecode = st->index_entries[index].timestamp;
1992     matroska->done = 0;
1993     av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1994     return 0;
1995 }
1996
1997 static int matroska_read_close(AVFormatContext *s)
1998 {
1999     MatroskaDemuxContext *matroska = s->priv_data;
2000     MatroskaTrack *tracks = matroska->tracks.elem;
2001     int n;
2002
2003     matroska_clear_queue(matroska);
2004
2005     for (n=0; n < matroska->tracks.nb_elem; n++)
2006         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2007             av_free(tracks[n].audio.buf);
2008     ebml_free(matroska_segment, matroska);
2009
2010     return 0;
2011 }
2012
2013 AVInputFormat ff_matroska_demuxer = {
2014     "matroska,webm",
2015     NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
2016     sizeof(MatroskaDemuxContext),
2017     matroska_probe,
2018     matroska_read_header,
2019     matroska_read_packet,
2020     matroska_read_close,
2021     matroska_read_seek,
2022 };