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