libavformat/matroskadec.c
Go to the documentation of this file.
00001 /*
00002  * Matroska file demuxer
00003  * Copyright (c) 2003-2008 The Libav Project
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * Libav is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00031 #include <stdio.h>
00032 #include "avformat.h"
00033 #include "internal.h"
00034 #include "avio_internal.h"
00035 /* For ff_codec_get_id(). */
00036 #include "riff.h"
00037 #include "isom.h"
00038 #include "rm.h"
00039 #include "matroska.h"
00040 #include "libavcodec/mpeg4audio.h"
00041 #include "libavutil/intfloat.h"
00042 #include "libavutil/intreadwrite.h"
00043 #include "libavutil/avstring.h"
00044 #include "libavutil/lzo.h"
00045 #include "libavutil/dict.h"
00046 #if CONFIG_ZLIB
00047 #include <zlib.h>
00048 #endif
00049 #if CONFIG_BZLIB
00050 #include <bzlib.h>
00051 #endif
00052 
00053 typedef enum {
00054     EBML_NONE,
00055     EBML_UINT,
00056     EBML_FLOAT,
00057     EBML_STR,
00058     EBML_UTF8,
00059     EBML_BIN,
00060     EBML_NEST,
00061     EBML_PASS,
00062     EBML_STOP,
00063     EBML_TYPE_COUNT
00064 } EbmlType;
00065 
00066 typedef const struct EbmlSyntax {
00067     uint32_t id;
00068     EbmlType type;
00069     int list_elem_size;
00070     int data_offset;
00071     union {
00072         uint64_t    u;
00073         double      f;
00074         const char *s;
00075         const struct EbmlSyntax *n;
00076     } def;
00077 } EbmlSyntax;
00078 
00079 typedef struct {
00080     int nb_elem;
00081     void *elem;
00082 } EbmlList;
00083 
00084 typedef struct {
00085     int      size;
00086     uint8_t *data;
00087     int64_t  pos;
00088 } EbmlBin;
00089 
00090 typedef struct {
00091     uint64_t version;
00092     uint64_t max_size;
00093     uint64_t id_length;
00094     char    *doctype;
00095     uint64_t doctype_version;
00096 } Ebml;
00097 
00098 typedef struct {
00099     uint64_t algo;
00100     EbmlBin  settings;
00101 } MatroskaTrackCompression;
00102 
00103 typedef struct {
00104     uint64_t scope;
00105     uint64_t type;
00106     MatroskaTrackCompression compression;
00107 } MatroskaTrackEncoding;
00108 
00109 typedef struct {
00110     double   frame_rate;
00111     uint64_t display_width;
00112     uint64_t display_height;
00113     uint64_t pixel_width;
00114     uint64_t pixel_height;
00115     uint64_t fourcc;
00116 } MatroskaTrackVideo;
00117 
00118 typedef struct {
00119     double   samplerate;
00120     double   out_samplerate;
00121     uint64_t bitdepth;
00122     uint64_t channels;
00123 
00124     /* real audio header (extracted from extradata) */
00125     int      coded_framesize;
00126     int      sub_packet_h;
00127     int      frame_size;
00128     int      sub_packet_size;
00129     int      sub_packet_cnt;
00130     int      pkt_cnt;
00131     uint64_t buf_timecode;
00132     uint8_t *buf;
00133 } MatroskaTrackAudio;
00134 
00135 typedef struct {
00136     uint64_t num;
00137     uint64_t uid;
00138     uint64_t type;
00139     char    *name;
00140     char    *codec_id;
00141     EbmlBin  codec_priv;
00142     char    *language;
00143     double time_scale;
00144     uint64_t default_duration;
00145     uint64_t flag_default;
00146     uint64_t flag_forced;
00147     MatroskaTrackVideo video;
00148     MatroskaTrackAudio audio;
00149     EbmlList encodings;
00150 
00151     AVStream *stream;
00152     int64_t end_timecode;
00153     int ms_compat;
00154 } MatroskaTrack;
00155 
00156 typedef struct {
00157     uint64_t uid;
00158     char *filename;
00159     char *mime;
00160     EbmlBin bin;
00161 
00162     AVStream *stream;
00163 } MatroskaAttachement;
00164 
00165 typedef struct {
00166     uint64_t start;
00167     uint64_t end;
00168     uint64_t uid;
00169     char    *title;
00170 
00171     AVChapter *chapter;
00172 } MatroskaChapter;
00173 
00174 typedef struct {
00175     uint64_t track;
00176     uint64_t pos;
00177 } MatroskaIndexPos;
00178 
00179 typedef struct {
00180     uint64_t time;
00181     EbmlList pos;
00182 } MatroskaIndex;
00183 
00184 typedef struct {
00185     char *name;
00186     char *string;
00187     char *lang;
00188     uint64_t def;
00189     EbmlList sub;
00190 } MatroskaTag;
00191 
00192 typedef struct {
00193     char    *type;
00194     uint64_t typevalue;
00195     uint64_t trackuid;
00196     uint64_t chapteruid;
00197     uint64_t attachuid;
00198 } MatroskaTagTarget;
00199 
00200 typedef struct {
00201     MatroskaTagTarget target;
00202     EbmlList tag;
00203 } MatroskaTags;
00204 
00205 typedef struct {
00206     uint64_t id;
00207     uint64_t pos;
00208 } MatroskaSeekhead;
00209 
00210 typedef struct {
00211     uint64_t start;
00212     uint64_t length;
00213 } MatroskaLevel;
00214 
00215 typedef struct {
00216     AVFormatContext *ctx;
00217 
00218     /* EBML stuff */
00219     int num_levels;
00220     MatroskaLevel levels[EBML_MAX_DEPTH];
00221     int level_up;
00222     uint32_t current_id;
00223 
00224     uint64_t time_scale;
00225     double   duration;
00226     char    *title;
00227     EbmlList tracks;
00228     EbmlList attachments;
00229     EbmlList chapters;
00230     EbmlList index;
00231     EbmlList tags;
00232     EbmlList seekhead;
00233 
00234     /* byte position of the segment inside the stream */
00235     int64_t segment_start;
00236 
00237     /* the packet queue */
00238     AVPacket **packets;
00239     int num_packets;
00240     AVPacket *prev_pkt;
00241 
00242     int done;
00243 
00244     /* What to skip before effectively reading a packet. */
00245     int skip_to_keyframe;
00246     uint64_t skip_to_timecode;
00247 
00248     /* File has a CUES element, but we defer parsing until it is needed. */
00249     int cues_parsing_deferred;
00250 } MatroskaDemuxContext;
00251 
00252 typedef struct {
00253     uint64_t duration;
00254     int64_t  reference;
00255     uint64_t non_simple;
00256     EbmlBin  bin;
00257 } MatroskaBlock;
00258 
00259 typedef struct {
00260     uint64_t timecode;
00261     EbmlList blocks;
00262 } MatroskaCluster;
00263 
00264 static EbmlSyntax ebml_header[] = {
00265     { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
00266     { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
00267     { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
00268     { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
00269     { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
00270     { EBML_ID_EBMLVERSION,            EBML_NONE },
00271     { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
00272     { 0 }
00273 };
00274 
00275 static EbmlSyntax ebml_syntax[] = {
00276     { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
00277     { 0 }
00278 };
00279 
00280 static EbmlSyntax matroska_info[] = {
00281     { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
00282     { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
00283     { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
00284     { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
00285     { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
00286     { MATROSKA_ID_DATEUTC,            EBML_NONE },
00287     { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
00288     { 0 }
00289 };
00290 
00291 static EbmlSyntax matroska_track_video[] = {
00292     { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
00293     { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
00294     { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
00295     { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
00296     { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
00297     { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
00298     { MATROSKA_ID_VIDEOPIXELCROPB,    EBML_NONE },
00299     { MATROSKA_ID_VIDEOPIXELCROPT,    EBML_NONE },
00300     { MATROSKA_ID_VIDEOPIXELCROPL,    EBML_NONE },
00301     { MATROSKA_ID_VIDEOPIXELCROPR,    EBML_NONE },
00302     { MATROSKA_ID_VIDEODISPLAYUNIT,   EBML_NONE },
00303     { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
00304     { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
00305     { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
00306     { 0 }
00307 };
00308 
00309 static EbmlSyntax matroska_track_audio[] = {
00310     { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
00311     { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
00312     { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
00313     { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
00314     { 0 }
00315 };
00316 
00317 static EbmlSyntax matroska_track_encoding_compression[] = {
00318     { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
00319     { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
00320     { 0 }
00321 };
00322 
00323 static EbmlSyntax matroska_track_encoding[] = {
00324     { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
00325     { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
00326     { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
00327     { MATROSKA_ID_ENCODINGORDER,      EBML_NONE },
00328     { 0 }
00329 };
00330 
00331 static EbmlSyntax matroska_track_encodings[] = {
00332     { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
00333     { 0 }
00334 };
00335 
00336 static EbmlSyntax matroska_track[] = {
00337     { MATROSKA_ID_TRACKNUMBER,          EBML_UINT, 0, offsetof(MatroskaTrack,num) },
00338     { MATROSKA_ID_TRACKNAME,            EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
00339     { MATROSKA_ID_TRACKUID,             EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
00340     { MATROSKA_ID_TRACKTYPE,            EBML_UINT, 0, offsetof(MatroskaTrack,type) },
00341     { MATROSKA_ID_CODECID,              EBML_STR,  0, offsetof(MatroskaTrack,codec_id) },
00342     { MATROSKA_ID_CODECPRIVATE,         EBML_BIN,  0, offsetof(MatroskaTrack,codec_priv) },
00343     { MATROSKA_ID_TRACKLANGUAGE,        EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
00344     { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
00345     { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
00346     { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
00347     { MATROSKA_ID_TRACKFLAGFORCED,      EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
00348     { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
00349     { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
00350     { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
00351     { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
00352     { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
00353     { MATROSKA_ID_CODECNAME,            EBML_NONE },
00354     { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
00355     { MATROSKA_ID_CODECINFOURL,         EBML_NONE },
00356     { MATROSKA_ID_CODECDOWNLOADURL,     EBML_NONE },
00357     { MATROSKA_ID_TRACKMINCACHE,        EBML_NONE },
00358     { MATROSKA_ID_TRACKMAXCACHE,        EBML_NONE },
00359     { MATROSKA_ID_TRACKMAXBLKADDID,     EBML_NONE },
00360     { 0 }
00361 };
00362 
00363 static EbmlSyntax matroska_tracks[] = {
00364     { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
00365     { 0 }
00366 };
00367 
00368 static EbmlSyntax matroska_attachment[] = {
00369     { MATROSKA_ID_FILEUID,            EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
00370     { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
00371     { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
00372     { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
00373     { MATROSKA_ID_FILEDESC,           EBML_NONE },
00374     { 0 }
00375 };
00376 
00377 static EbmlSyntax matroska_attachments[] = {
00378     { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
00379     { 0 }
00380 };
00381 
00382 static EbmlSyntax matroska_chapter_display[] = {
00383     { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
00384     { MATROSKA_ID_CHAPLANG,           EBML_NONE },
00385     { 0 }
00386 };
00387 
00388 static EbmlSyntax matroska_chapter_entry[] = {
00389     { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
00390     { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
00391     { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
00392     { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
00393     { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
00394     { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
00395     { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
00396     { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
00397     { 0 }
00398 };
00399 
00400 static EbmlSyntax matroska_chapter[] = {
00401     { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
00402     { MATROSKA_ID_EDITIONUID,         EBML_NONE },
00403     { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
00404     { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
00405     { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
00406     { 0 }
00407 };
00408 
00409 static EbmlSyntax matroska_chapters[] = {
00410     { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
00411     { 0 }
00412 };
00413 
00414 static EbmlSyntax matroska_index_pos[] = {
00415     { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
00416     { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
00417     { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
00418     { 0 }
00419 };
00420 
00421 static EbmlSyntax matroska_index_entry[] = {
00422     { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
00423     { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
00424     { 0 }
00425 };
00426 
00427 static EbmlSyntax matroska_index[] = {
00428     { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
00429     { 0 }
00430 };
00431 
00432 static EbmlSyntax matroska_simpletag[] = {
00433     { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
00434     { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
00435     { MATROSKA_ID_TAGLANG,            EBML_STR,  0, offsetof(MatroskaTag,lang), {.s="und"} },
00436     { MATROSKA_ID_TAGDEFAULT,         EBML_UINT, 0, offsetof(MatroskaTag,def) },
00437     { MATROSKA_ID_TAGDEFAULT_BUG,     EBML_UINT, 0, offsetof(MatroskaTag,def) },
00438     { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
00439     { 0 }
00440 };
00441 
00442 static EbmlSyntax matroska_tagtargets[] = {
00443     { MATROSKA_ID_TAGTARGETS_TYPE,      EBML_STR,  0, offsetof(MatroskaTagTarget,type) },
00444     { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
00445     { MATROSKA_ID_TAGTARGETS_TRACKUID,  EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
00446     { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
00447     { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
00448     { 0 }
00449 };
00450 
00451 static EbmlSyntax matroska_tag[] = {
00452     { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
00453     { MATROSKA_ID_TAGTARGETS,         EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
00454     { 0 }
00455 };
00456 
00457 static EbmlSyntax matroska_tags[] = {
00458     { MATROSKA_ID_TAG,                EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
00459     { 0 }
00460 };
00461 
00462 static EbmlSyntax matroska_seekhead_entry[] = {
00463     { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
00464     { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
00465     { 0 }
00466 };
00467 
00468 static EbmlSyntax matroska_seekhead[] = {
00469     { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
00470     { 0 }
00471 };
00472 
00473 static EbmlSyntax matroska_segment[] = {
00474     { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
00475     { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
00476     { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
00477     { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
00478     { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
00479     { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
00480     { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
00481     { MATROSKA_ID_CLUSTER,        EBML_STOP },
00482     { 0 }
00483 };
00484 
00485 static EbmlSyntax matroska_segments[] = {
00486     { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
00487     { 0 }
00488 };
00489 
00490 static EbmlSyntax matroska_blockgroup[] = {
00491     { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
00492     { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
00493     { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
00494     { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
00495     { 1,                          EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
00496     { 0 }
00497 };
00498 
00499 static EbmlSyntax matroska_cluster[] = {
00500     { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
00501     { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
00502     { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
00503     { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
00504     { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
00505     { 0 }
00506 };
00507 
00508 static EbmlSyntax matroska_clusters[] = {
00509     { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
00510     { MATROSKA_ID_INFO,           EBML_NONE },
00511     { MATROSKA_ID_CUES,           EBML_NONE },
00512     { MATROSKA_ID_TAGS,           EBML_NONE },
00513     { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
00514     { 0 }
00515 };
00516 
00517 static const char *matroska_doctypes[] = { "matroska", "webm" };
00518 
00519 /*
00520  * Return: Whether we reached the end of a level in the hierarchy or not.
00521  */
00522 static int ebml_level_end(MatroskaDemuxContext *matroska)
00523 {
00524     AVIOContext *pb = matroska->ctx->pb;
00525     int64_t pos = avio_tell(pb);
00526 
00527     if (matroska->num_levels > 0) {
00528         MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
00529         if (pos - level->start >= level->length || matroska->current_id) {
00530             matroska->num_levels--;
00531             return 1;
00532         }
00533     }
00534     return 0;
00535 }
00536 
00537 /*
00538  * Read: an "EBML number", which is defined as a variable-length
00539  * array of bytes. The first byte indicates the length by giving a
00540  * number of 0-bits followed by a one. The position of the first
00541  * "one" bit inside the first byte indicates the length of this
00542  * number.
00543  * Returns: number of bytes read, < 0 on error
00544  */
00545 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
00546                          int max_size, uint64_t *number)
00547 {
00548     int read = 1, n = 1;
00549     uint64_t total = 0;
00550 
00551     /* The first byte tells us the length in bytes - avio_r8() can normally
00552      * return 0, but since that's not a valid first ebmlID byte, we can
00553      * use it safely here to catch EOS. */
00554     if (!(total = avio_r8(pb))) {
00555         /* we might encounter EOS here */
00556         if (!pb->eof_reached) {
00557             int64_t pos = avio_tell(pb);
00558             av_log(matroska->ctx, AV_LOG_ERROR,
00559                    "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
00560                    pos, pos);
00561         }
00562         return AVERROR(EIO); /* EOS or actual I/O error */
00563     }
00564 
00565     /* get the length of the EBML number */
00566     read = 8 - ff_log2_tab[total];
00567     if (read > max_size) {
00568         int64_t pos = avio_tell(pb) - 1;
00569         av_log(matroska->ctx, AV_LOG_ERROR,
00570                "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
00571                (uint8_t) total, pos, pos);
00572         return AVERROR_INVALIDDATA;
00573     }
00574 
00575     /* read out length */
00576     total ^= 1 << ff_log2_tab[total];
00577     while (n++ < read)
00578         total = (total << 8) | avio_r8(pb);
00579 
00580     *number = total;
00581 
00582     return read;
00583 }
00584 
00590 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
00591                             uint64_t *number)
00592 {
00593     int res = ebml_read_num(matroska, pb, 8, number);
00594     if (res > 0 && *number + 1 == 1ULL << (7 * res))
00595         *number = 0xffffffffffffffULL;
00596     return res;
00597 }
00598 
00599 /*
00600  * Read the next element as an unsigned int.
00601  * 0 is success, < 0 is failure.
00602  */
00603 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
00604 {
00605     int n = 0;
00606 
00607     if (size > 8)
00608         return AVERROR_INVALIDDATA;
00609 
00610     /* big-endian ordering; build up number */
00611     *num = 0;
00612     while (n++ < size)
00613         *num = (*num << 8) | avio_r8(pb);
00614 
00615     return 0;
00616 }
00617 
00618 /*
00619  * Read the next element as a float.
00620  * 0 is success, < 0 is failure.
00621  */
00622 static int ebml_read_float(AVIOContext *pb, int size, double *num)
00623 {
00624     if (size == 0) {
00625         *num = 0;
00626     } else if (size == 4) {
00627         *num = av_int2float(avio_rb32(pb));
00628     } else if (size == 8){
00629         *num = av_int2double(avio_rb64(pb));
00630     } else
00631         return AVERROR_INVALIDDATA;
00632 
00633     return 0;
00634 }
00635 
00636 /*
00637  * Read the next element as an ASCII string.
00638  * 0 is success, < 0 is failure.
00639  */
00640 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
00641 {
00642     char *res;
00643 
00644     /* EBML strings are usually not 0-terminated, so we allocate one
00645      * byte more, read the string and NULL-terminate it ourselves. */
00646     if (!(res = av_malloc(size + 1)))
00647         return AVERROR(ENOMEM);
00648     if (avio_read(pb, (uint8_t *) res, size) != size) {
00649         av_free(res);
00650         return AVERROR(EIO);
00651     }
00652     (res)[size] = '\0';
00653     av_free(*str);
00654     *str = res;
00655 
00656     return 0;
00657 }
00658 
00659 /*
00660  * Read the next element as binary data.
00661  * 0 is success, < 0 is failure.
00662  */
00663 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
00664 {
00665     av_free(bin->data);
00666     if (!(bin->data = av_malloc(length)))
00667         return AVERROR(ENOMEM);
00668 
00669     bin->size = length;
00670     bin->pos  = avio_tell(pb);
00671     if (avio_read(pb, bin->data, length) != length) {
00672         av_freep(&bin->data);
00673         return AVERROR(EIO);
00674     }
00675 
00676     return 0;
00677 }
00678 
00679 /*
00680  * Read the next element, but only the header. The contents
00681  * are supposed to be sub-elements which can be read separately.
00682  * 0 is success, < 0 is failure.
00683  */
00684 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
00685 {
00686     AVIOContext *pb = matroska->ctx->pb;
00687     MatroskaLevel *level;
00688 
00689     if (matroska->num_levels >= EBML_MAX_DEPTH) {
00690         av_log(matroska->ctx, AV_LOG_ERROR,
00691                "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
00692         return AVERROR(ENOSYS);
00693     }
00694 
00695     level = &matroska->levels[matroska->num_levels++];
00696     level->start = avio_tell(pb);
00697     level->length = length;
00698 
00699     return 0;
00700 }
00701 
00702 /*
00703  * Read signed/unsigned "EBML" numbers.
00704  * Return: number of bytes processed, < 0 on error
00705  */
00706 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
00707                                  uint8_t *data, uint32_t size, uint64_t *num)
00708 {
00709     AVIOContext pb;
00710     ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
00711     return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
00712 }
00713 
00714 /*
00715  * Same as above, but signed.
00716  */
00717 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
00718                                  uint8_t *data, uint32_t size, int64_t *num)
00719 {
00720     uint64_t unum;
00721     int res;
00722 
00723     /* read as unsigned number first */
00724     if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
00725         return res;
00726 
00727     /* make signed (weird way) */
00728     *num = unum - ((1LL << (7*res - 1)) - 1);
00729 
00730     return res;
00731 }
00732 
00733 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
00734                            EbmlSyntax *syntax, void *data);
00735 
00736 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
00737                          uint32_t id, void *data)
00738 {
00739     int i;
00740     for (i=0; syntax[i].id; i++)
00741         if (id == syntax[i].id)
00742             break;
00743     if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
00744         matroska->num_levels > 0 &&
00745         matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
00746         return 0;  // we reached the end of an unknown size cluster
00747     if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
00748         av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
00749     return ebml_parse_elem(matroska, &syntax[i], data);
00750 }
00751 
00752 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
00753                       void *data)
00754 {
00755     if (!matroska->current_id) {
00756         uint64_t id;
00757         int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
00758         if (res < 0)
00759             return res;
00760         matroska->current_id = id | 1 << 7*res;
00761     }
00762     return ebml_parse_id(matroska, syntax, matroska->current_id, data);
00763 }
00764 
00765 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
00766                            void *data)
00767 {
00768     int i, res = 0;
00769 
00770     for (i=0; syntax[i].id; i++)
00771         switch (syntax[i].type) {
00772         case EBML_UINT:
00773             *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
00774             break;
00775         case EBML_FLOAT:
00776             *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
00777             break;
00778         case EBML_STR:
00779         case EBML_UTF8:
00780             *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
00781             break;
00782         }
00783 
00784     while (!res && !ebml_level_end(matroska))
00785         res = ebml_parse(matroska, syntax, data);
00786 
00787     return res;
00788 }
00789 
00790 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
00791                            EbmlSyntax *syntax, void *data)
00792 {
00793     static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
00794         [EBML_UINT]  = 8,
00795         [EBML_FLOAT] = 8,
00796         // max. 16 MB for strings
00797         [EBML_STR]   = 0x1000000,
00798         [EBML_UTF8]  = 0x1000000,
00799         // max. 256 MB for binary data
00800         [EBML_BIN]   = 0x10000000,
00801         // no limits for anything else
00802     };
00803     AVIOContext *pb = matroska->ctx->pb;
00804     uint32_t id = syntax->id;
00805     uint64_t length;
00806     int res;
00807     void *newelem;
00808 
00809     data = (char *)data + syntax->data_offset;
00810     if (syntax->list_elem_size) {
00811         EbmlList *list = data;
00812         newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
00813         if (!newelem)
00814             return AVERROR(ENOMEM);
00815         list->elem = newelem;
00816         data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
00817         memset(data, 0, syntax->list_elem_size);
00818         list->nb_elem++;
00819     }
00820 
00821     if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
00822         matroska->current_id = 0;
00823         if ((res = ebml_read_length(matroska, pb, &length)) < 0)
00824             return res;
00825         if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
00826             av_log(matroska->ctx, AV_LOG_ERROR,
00827                    "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
00828                    length, max_lengths[syntax->type], syntax->type);
00829             return AVERROR_INVALIDDATA;
00830         }
00831     }
00832 
00833     switch (syntax->type) {
00834     case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
00835     case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
00836     case EBML_STR:
00837     case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
00838     case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
00839     case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
00840                          return res;
00841                      if (id == MATROSKA_ID_SEGMENT)
00842                          matroska->segment_start = avio_tell(matroska->ctx->pb);
00843                      return ebml_parse_nest(matroska, syntax->def.n, data);
00844     case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
00845     case EBML_STOP:  return 1;
00846     default:         return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
00847     }
00848     if (res == AVERROR_INVALIDDATA)
00849         av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
00850     else if (res == AVERROR(EIO))
00851         av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
00852     return res;
00853 }
00854 
00855 static void ebml_free(EbmlSyntax *syntax, void *data)
00856 {
00857     int i, j;
00858     for (i=0; syntax[i].id; i++) {
00859         void *data_off = (char *)data + syntax[i].data_offset;
00860         switch (syntax[i].type) {
00861         case EBML_STR:
00862         case EBML_UTF8:  av_freep(data_off);                      break;
00863         case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
00864         case EBML_NEST:
00865             if (syntax[i].list_elem_size) {
00866                 EbmlList *list = data_off;
00867                 char *ptr = list->elem;
00868                 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
00869                     ebml_free(syntax[i].def.n, ptr);
00870                 av_free(list->elem);
00871             } else
00872                 ebml_free(syntax[i].def.n, data_off);
00873         default:  break;
00874         }
00875     }
00876 }
00877 
00878 
00879 /*
00880  * Autodetecting...
00881  */
00882 static int matroska_probe(AVProbeData *p)
00883 {
00884     uint64_t total = 0;
00885     int len_mask = 0x80, size = 1, n = 1, i;
00886 
00887     /* EBML header? */
00888     if (AV_RB32(p->buf) != EBML_ID_HEADER)
00889         return 0;
00890 
00891     /* length of header */
00892     total = p->buf[4];
00893     while (size <= 8 && !(total & len_mask)) {
00894         size++;
00895         len_mask >>= 1;
00896     }
00897     if (size > 8)
00898       return 0;
00899     total &= (len_mask - 1);
00900     while (n < size)
00901         total = (total << 8) | p->buf[4 + n++];
00902 
00903     /* Does the probe data contain the whole header? */
00904     if (p->buf_size < 4 + size + total)
00905       return 0;
00906 
00907     /* The header should contain a known document type. For now,
00908      * we don't parse the whole header but simply check for the
00909      * availability of that array of characters inside the header.
00910      * Not fully fool-proof, but good enough. */
00911     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
00912         int probelen = strlen(matroska_doctypes[i]);
00913         if (total < probelen)
00914             continue;
00915         for (n = 4+size; n <= 4+size+total-probelen; n++)
00916             if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
00917                 return AVPROBE_SCORE_MAX;
00918     }
00919 
00920     // probably valid EBML header but no recognized doctype
00921     return AVPROBE_SCORE_MAX/2;
00922 }
00923 
00924 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
00925                                                  int num)
00926 {
00927     MatroskaTrack *tracks = matroska->tracks.elem;
00928     int i;
00929 
00930     for (i=0; i < matroska->tracks.nb_elem; i++)
00931         if (tracks[i].num == num)
00932             return &tracks[i];
00933 
00934     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
00935     return NULL;
00936 }
00937 
00938 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
00939                                   MatroskaTrack *track)
00940 {
00941     MatroskaTrackEncoding *encodings = track->encodings.elem;
00942     uint8_t* data = *buf;
00943     int isize = *buf_size;
00944     uint8_t* pkt_data = NULL;
00945     uint8_t* newpktdata;
00946     int pkt_size = isize;
00947     int result = 0;
00948     int olen;
00949 
00950     if (pkt_size >= 10000000)
00951         return -1;
00952 
00953     switch (encodings[0].compression.algo) {
00954     case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
00955         return encodings[0].compression.settings.size;
00956     case MATROSKA_TRACK_ENCODING_COMP_LZO:
00957         do {
00958             olen = pkt_size *= 3;
00959             pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
00960             result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
00961         } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
00962         if (result)
00963             goto failed;
00964         pkt_size -= olen;
00965         break;
00966 #if CONFIG_ZLIB
00967     case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
00968         z_stream zstream = {0};
00969         if (inflateInit(&zstream) != Z_OK)
00970             return -1;
00971         zstream.next_in = data;
00972         zstream.avail_in = isize;
00973         do {
00974             pkt_size *= 3;
00975             newpktdata = av_realloc(pkt_data, pkt_size);
00976             if (!newpktdata) {
00977                 inflateEnd(&zstream);
00978                 goto failed;
00979             }
00980             pkt_data = newpktdata;
00981             zstream.avail_out = pkt_size - zstream.total_out;
00982             zstream.next_out = pkt_data + zstream.total_out;
00983             result = inflate(&zstream, Z_NO_FLUSH);
00984         } while (result==Z_OK && pkt_size<10000000);
00985         pkt_size = zstream.total_out;
00986         inflateEnd(&zstream);
00987         if (result != Z_STREAM_END)
00988             goto failed;
00989         break;
00990     }
00991 #endif
00992 #if CONFIG_BZLIB
00993     case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
00994         bz_stream bzstream = {0};
00995         if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
00996             return -1;
00997         bzstream.next_in = data;
00998         bzstream.avail_in = isize;
00999         do {
01000             pkt_size *= 3;
01001             newpktdata = av_realloc(pkt_data, pkt_size);
01002             if (!newpktdata) {
01003                 BZ2_bzDecompressEnd(&bzstream);
01004                 goto failed;
01005             }
01006             pkt_data = newpktdata;
01007             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
01008             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
01009             result = BZ2_bzDecompress(&bzstream);
01010         } while (result==BZ_OK && pkt_size<10000000);
01011         pkt_size = bzstream.total_out_lo32;
01012         BZ2_bzDecompressEnd(&bzstream);
01013         if (result != BZ_STREAM_END)
01014             goto failed;
01015         break;
01016     }
01017 #endif
01018     default:
01019         return -1;
01020     }
01021 
01022     *buf = pkt_data;
01023     *buf_size = pkt_size;
01024     return 0;
01025  failed:
01026     av_free(pkt_data);
01027     return -1;
01028 }
01029 
01030 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
01031                                     AVPacket *pkt, uint64_t display_duration)
01032 {
01033     char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
01034     for (; *ptr!=',' && ptr<end-1; ptr++);
01035     if (*ptr == ',')
01036         layer = ++ptr;
01037     for (; *ptr!=',' && ptr<end-1; ptr++);
01038     if (*ptr == ',') {
01039         int64_t end_pts = pkt->pts + display_duration;
01040         int sc = matroska->time_scale * pkt->pts / 10000000;
01041         int ec = matroska->time_scale * end_pts  / 10000000;
01042         int sh, sm, ss, eh, em, es, len;
01043         sh = sc/360000;  sc -= 360000*sh;
01044         sm = sc/  6000;  sc -=   6000*sm;
01045         ss = sc/   100;  sc -=    100*ss;
01046         eh = ec/360000;  ec -= 360000*eh;
01047         em = ec/  6000;  ec -=   6000*em;
01048         es = ec/   100;  ec -=    100*es;
01049         *ptr++ = '\0';
01050         len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
01051         if (!(line = av_malloc(len)))
01052             return;
01053         snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
01054                  layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
01055         av_free(pkt->data);
01056         pkt->data = line;
01057         pkt->size = strlen(line);
01058     }
01059 }
01060 
01061 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
01062 {
01063     void *newdata = av_realloc(out->data, out->size+in->size);
01064     if (!newdata)
01065         return AVERROR(ENOMEM);
01066     out->data = newdata;
01067     memcpy(out->data+out->size, in->data, in->size);
01068     out->size += in->size;
01069     av_destruct_packet(in);
01070     av_free(in);
01071     return 0;
01072 }
01073 
01074 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
01075                                  AVDictionary **metadata, char *prefix)
01076 {
01077     MatroskaTag *tags = list->elem;
01078     char key[1024];
01079     int i;
01080 
01081     for (i=0; i < list->nb_elem; i++) {
01082         const char *lang = tags[i].lang && strcmp(tags[i].lang, "und") ?
01083                            tags[i].lang : NULL;
01084 
01085         if (!tags[i].name) {
01086             av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
01087             continue;
01088         }
01089         if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
01090         else         av_strlcpy(key, tags[i].name, sizeof(key));
01091         if (tags[i].def || !lang) {
01092         av_dict_set(metadata, key, tags[i].string, 0);
01093         if (tags[i].sub.nb_elem)
01094             matroska_convert_tag(s, &tags[i].sub, metadata, key);
01095         }
01096         if (lang) {
01097             av_strlcat(key, "-", sizeof(key));
01098             av_strlcat(key, lang, sizeof(key));
01099             av_dict_set(metadata, key, tags[i].string, 0);
01100             if (tags[i].sub.nb_elem)
01101                 matroska_convert_tag(s, &tags[i].sub, metadata, key);
01102         }
01103     }
01104     ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
01105 }
01106 
01107 static void matroska_convert_tags(AVFormatContext *s)
01108 {
01109     MatroskaDemuxContext *matroska = s->priv_data;
01110     MatroskaTags *tags = matroska->tags.elem;
01111     int i, j;
01112 
01113     for (i=0; i < matroska->tags.nb_elem; i++) {
01114         if (tags[i].target.attachuid) {
01115             MatroskaAttachement *attachment = matroska->attachments.elem;
01116             for (j=0; j<matroska->attachments.nb_elem; j++)
01117                 if (attachment[j].uid == tags[i].target.attachuid
01118                     && attachment[j].stream)
01119                     matroska_convert_tag(s, &tags[i].tag,
01120                                          &attachment[j].stream->metadata, NULL);
01121         } else if (tags[i].target.chapteruid) {
01122             MatroskaChapter *chapter = matroska->chapters.elem;
01123             for (j=0; j<matroska->chapters.nb_elem; j++)
01124                 if (chapter[j].uid == tags[i].target.chapteruid
01125                     && chapter[j].chapter)
01126                     matroska_convert_tag(s, &tags[i].tag,
01127                                          &chapter[j].chapter->metadata, NULL);
01128         } else if (tags[i].target.trackuid) {
01129             MatroskaTrack *track = matroska->tracks.elem;
01130             for (j=0; j<matroska->tracks.nb_elem; j++)
01131                 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
01132                     matroska_convert_tag(s, &tags[i].tag,
01133                                          &track[j].stream->metadata, NULL);
01134         } else {
01135             matroska_convert_tag(s, &tags[i].tag, &s->metadata,
01136                                  tags[i].target.type);
01137         }
01138     }
01139 }
01140 
01141 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
01142 {
01143     EbmlList *seekhead_list = &matroska->seekhead;
01144     MatroskaSeekhead *seekhead = seekhead_list->elem;
01145     uint32_t level_up = matroska->level_up;
01146     int64_t before_pos = avio_tell(matroska->ctx->pb);
01147     uint32_t saved_id = matroska->current_id;
01148     MatroskaLevel level;
01149     int64_t offset;
01150     int ret = 0;
01151 
01152     if (idx >= seekhead_list->nb_elem
01153             || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
01154             || seekhead[idx].id == MATROSKA_ID_CLUSTER)
01155         return 0;
01156 
01157     /* seek */
01158     offset = seekhead[idx].pos + matroska->segment_start;
01159     if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
01160         /* We don't want to lose our seekhead level, so we add
01161          * a dummy. This is a crude hack. */
01162         if (matroska->num_levels == EBML_MAX_DEPTH) {
01163             av_log(matroska->ctx, AV_LOG_INFO,
01164                    "Max EBML element depth (%d) reached, "
01165                    "cannot parse further.\n", EBML_MAX_DEPTH);
01166             ret = AVERROR_INVALIDDATA;
01167         } else {
01168             level.start = 0;
01169             level.length = (uint64_t)-1;
01170             matroska->levels[matroska->num_levels] = level;
01171             matroska->num_levels++;
01172             matroska->current_id = 0;
01173 
01174             ret = ebml_parse(matroska, matroska_segment, matroska);
01175 
01176             /* remove dummy level */
01177             while (matroska->num_levels) {
01178                 uint64_t length = matroska->levels[--matroska->num_levels].length;
01179                 if (length == (uint64_t)-1)
01180                     break;
01181             }
01182         }
01183     }
01184     /* seek back */
01185     avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
01186     matroska->level_up = level_up;
01187     matroska->current_id = saved_id;
01188 
01189     return ret;
01190 }
01191 
01192 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
01193 {
01194     EbmlList *seekhead_list = &matroska->seekhead;
01195     int64_t before_pos = avio_tell(matroska->ctx->pb);
01196     int i;
01197 
01198     // we should not do any seeking in the streaming case
01199     if (!matroska->ctx->pb->seekable ||
01200         (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
01201         return;
01202 
01203     for (i = 0; i < seekhead_list->nb_elem; i++) {
01204         MatroskaSeekhead *seekhead = seekhead_list->elem;
01205         if (seekhead[i].pos <= before_pos)
01206             continue;
01207 
01208         // defer cues parsing until we actually need cue data.
01209         if (seekhead[i].id == MATROSKA_ID_CUES) {
01210             matroska->cues_parsing_deferred = 1;
01211             continue;
01212         }
01213 
01214         if (matroska_parse_seekhead_entry(matroska, i) < 0)
01215             break;
01216     }
01217 }
01218 
01219 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
01220     EbmlList *seekhead_list = &matroska->seekhead;
01221     MatroskaSeekhead *seekhead = seekhead_list->elem;
01222     EbmlList *index_list;
01223     MatroskaIndex *index;
01224     int index_scale = 1;
01225     int i, j;
01226 
01227     for (i = 0; i < seekhead_list->nb_elem; i++)
01228         if (seekhead[i].id == MATROSKA_ID_CUES)
01229             break;
01230     assert(i <= seekhead_list->nb_elem);
01231 
01232     matroska_parse_seekhead_entry(matroska, i);
01233 
01234     index_list = &matroska->index;
01235     index = index_list->elem;
01236     if (index_list->nb_elem
01237         && index[0].time > 1E14/matroska->time_scale) {
01238         av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
01239         index_scale = matroska->time_scale;
01240     }
01241     for (i = 0; i < index_list->nb_elem; i++) {
01242         EbmlList *pos_list = &index[i].pos;
01243         MatroskaIndexPos *pos = pos_list->elem;
01244         for (j = 0; j < pos_list->nb_elem; j++) {
01245             MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
01246             if (track && track->stream)
01247                 av_add_index_entry(track->stream,
01248                                    pos[j].pos + matroska->segment_start,
01249                                    index[i].time/index_scale, 0, 0,
01250                                    AVINDEX_KEYFRAME);
01251         }
01252     }
01253 }
01254 
01255 static int matroska_aac_profile(char *codec_id)
01256 {
01257     static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
01258     int profile;
01259 
01260     for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
01261         if (strstr(codec_id, aac_profiles[profile]))
01262             break;
01263     return profile + 1;
01264 }
01265 
01266 static int matroska_aac_sri(int samplerate)
01267 {
01268     int sri;
01269 
01270     for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
01271         if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
01272             break;
01273     return sri;
01274 }
01275 
01276 static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
01277 {
01278     MatroskaDemuxContext *matroska = s->priv_data;
01279     EbmlList *attachements_list = &matroska->attachments;
01280     MatroskaAttachement *attachements;
01281     EbmlList *chapters_list = &matroska->chapters;
01282     MatroskaChapter *chapters;
01283     MatroskaTrack *tracks;
01284     uint64_t max_start = 0;
01285     Ebml ebml = { 0 };
01286     AVStream *st;
01287     int i, j, res;
01288 
01289     matroska->ctx = s;
01290 
01291     /* First read the EBML header. */
01292     if (ebml_parse(matroska, ebml_syntax, &ebml)
01293         || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
01294         || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
01295         av_log(matroska->ctx, AV_LOG_ERROR,
01296                "EBML header using unsupported features\n"
01297                "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
01298                ebml.version, ebml.doctype, ebml.doctype_version);
01299         ebml_free(ebml_syntax, &ebml);
01300         return AVERROR_PATCHWELCOME;
01301     }
01302     for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
01303         if (!strcmp(ebml.doctype, matroska_doctypes[i]))
01304             break;
01305     if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
01306         av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
01307     }
01308     ebml_free(ebml_syntax, &ebml);
01309 
01310     /* The next thing is a segment. */
01311     if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
01312         return res;
01313     matroska_execute_seekhead(matroska);
01314 
01315     if (!matroska->time_scale)
01316         matroska->time_scale = 1000000;
01317     if (matroska->duration)
01318         matroska->ctx->duration = matroska->duration * matroska->time_scale
01319                                   * 1000 / AV_TIME_BASE;
01320     av_dict_set(&s->metadata, "title", matroska->title, 0);
01321 
01322     tracks = matroska->tracks.elem;
01323     for (i=0; i < matroska->tracks.nb_elem; i++) {
01324         MatroskaTrack *track = &tracks[i];
01325         enum CodecID codec_id = CODEC_ID_NONE;
01326         EbmlList *encodings_list = &tracks->encodings;
01327         MatroskaTrackEncoding *encodings = encodings_list->elem;
01328         uint8_t *extradata = NULL;
01329         int extradata_size = 0;
01330         int extradata_offset = 0;
01331         AVIOContext b;
01332 
01333         /* Apply some sanity checks. */
01334         if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
01335             track->type != MATROSKA_TRACK_TYPE_AUDIO &&
01336             track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
01337             av_log(matroska->ctx, AV_LOG_INFO,
01338                    "Unknown or unsupported track type %"PRIu64"\n",
01339                    track->type);
01340             continue;
01341         }
01342         if (track->codec_id == NULL)
01343             continue;
01344 
01345         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
01346             if (!track->default_duration)
01347                 track->default_duration = 1000000000/track->video.frame_rate;
01348             if (!track->video.display_width)
01349                 track->video.display_width = track->video.pixel_width;
01350             if (!track->video.display_height)
01351                 track->video.display_height = track->video.pixel_height;
01352         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
01353             if (!track->audio.out_samplerate)
01354                 track->audio.out_samplerate = track->audio.samplerate;
01355         }
01356         if (encodings_list->nb_elem > 1) {
01357             av_log(matroska->ctx, AV_LOG_ERROR,
01358                    "Multiple combined encodings not supported");
01359         } else if (encodings_list->nb_elem == 1) {
01360             if (encodings[0].type ||
01361                 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
01362 #if CONFIG_ZLIB
01363                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
01364 #endif
01365 #if CONFIG_BZLIB
01366                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
01367 #endif
01368                  encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
01369                 encodings[0].scope = 0;
01370                 av_log(matroska->ctx, AV_LOG_ERROR,
01371                        "Unsupported encoding type");
01372             } else if (track->codec_priv.size && encodings[0].scope&2) {
01373                 uint8_t *codec_priv = track->codec_priv.data;
01374                 int offset = matroska_decode_buffer(&track->codec_priv.data,
01375                                                     &track->codec_priv.size,
01376                                                     track);
01377                 if (offset < 0) {
01378                     track->codec_priv.data = NULL;
01379                     track->codec_priv.size = 0;
01380                     av_log(matroska->ctx, AV_LOG_ERROR,
01381                            "Failed to decode codec private data\n");
01382                 } else if (offset > 0) {
01383                     track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
01384                     memcpy(track->codec_priv.data,
01385                            encodings[0].compression.settings.data, offset);
01386                     memcpy(track->codec_priv.data+offset, codec_priv,
01387                            track->codec_priv.size);
01388                     track->codec_priv.size += offset;
01389                 }
01390                 if (codec_priv != track->codec_priv.data)
01391                     av_free(codec_priv);
01392             }
01393         }
01394 
01395         for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
01396             if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
01397                         strlen(ff_mkv_codec_tags[j].str))){
01398                 codec_id= ff_mkv_codec_tags[j].id;
01399                 break;
01400             }
01401         }
01402 
01403         st = track->stream = avformat_new_stream(s, NULL);
01404         if (st == NULL)
01405             return AVERROR(ENOMEM);
01406 
01407         if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
01408             && track->codec_priv.size >= 40
01409             && track->codec_priv.data != NULL) {
01410             track->ms_compat = 1;
01411             track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
01412             codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
01413             extradata_offset = 40;
01414         } else if (!strcmp(track->codec_id, "A_MS/ACM")
01415                    && track->codec_priv.size >= 14
01416                    && track->codec_priv.data != NULL) {
01417             int ret;
01418             ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
01419                               0, NULL, NULL, NULL, NULL);
01420             ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
01421             if (ret < 0)
01422                 return ret;
01423             codec_id = st->codec->codec_id;
01424             extradata_offset = FFMIN(track->codec_priv.size, 18);
01425         } else if (!strcmp(track->codec_id, "V_QUICKTIME")
01426                    && (track->codec_priv.size >= 86)
01427                    && (track->codec_priv.data != NULL)) {
01428             track->video.fourcc = AV_RL32(track->codec_priv.data);
01429             codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
01430         } else if (codec_id == CODEC_ID_PCM_S16BE) {
01431             switch (track->audio.bitdepth) {
01432             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
01433             case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
01434             case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
01435             }
01436         } else if (codec_id == CODEC_ID_PCM_S16LE) {
01437             switch (track->audio.bitdepth) {
01438             case  8:  codec_id = CODEC_ID_PCM_U8;     break;
01439             case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
01440             case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
01441             }
01442         } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
01443             codec_id = CODEC_ID_PCM_F64LE;
01444         } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
01445             int profile = matroska_aac_profile(track->codec_id);
01446             int sri = matroska_aac_sri(track->audio.samplerate);
01447             extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
01448             if (extradata == NULL)
01449                 return AVERROR(ENOMEM);
01450             extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
01451             extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
01452             if (strstr(track->codec_id, "SBR")) {
01453                 sri = matroska_aac_sri(track->audio.out_samplerate);
01454                 extradata[2] = 0x56;
01455                 extradata[3] = 0xE5;
01456                 extradata[4] = 0x80 | (sri<<3);
01457                 extradata_size = 5;
01458             } else
01459                 extradata_size = 2;
01460         } else if (codec_id == CODEC_ID_TTA) {
01461             extradata_size = 30;
01462             extradata = av_mallocz(extradata_size);
01463             if (extradata == NULL)
01464                 return AVERROR(ENOMEM);
01465             ffio_init_context(&b, extradata, extradata_size, 1,
01466                           NULL, NULL, NULL, NULL);
01467             avio_write(&b, "TTA1", 4);
01468             avio_wl16(&b, 1);
01469             avio_wl16(&b, track->audio.channels);
01470             avio_wl16(&b, track->audio.bitdepth);
01471             avio_wl32(&b, track->audio.out_samplerate);
01472             avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
01473         } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
01474                    codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
01475             extradata_offset = 26;
01476         } else if (codec_id == CODEC_ID_RA_144) {
01477             track->audio.out_samplerate = 8000;
01478             track->audio.channels = 1;
01479         } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
01480                    codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
01481             int flavor;
01482             ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
01483                           0, NULL, NULL, NULL, NULL);
01484             avio_skip(&b, 22);
01485             flavor                       = avio_rb16(&b);
01486             track->audio.coded_framesize = avio_rb32(&b);
01487             avio_skip(&b, 12);
01488             track->audio.sub_packet_h    = avio_rb16(&b);
01489             track->audio.frame_size      = avio_rb16(&b);
01490             track->audio.sub_packet_size = avio_rb16(&b);
01491             if (flavor <= 0 || track->audio.coded_framesize <= 0 ||
01492                 track->audio.sub_packet_h <= 0 || track->audio.frame_size <= 0 ||
01493                 track->audio.sub_packet_size <= 0)
01494                 return AVERROR_INVALIDDATA;
01495             track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
01496             if (codec_id == CODEC_ID_RA_288) {
01497                 st->codec->block_align = track->audio.coded_framesize;
01498                 track->codec_priv.size = 0;
01499             } else {
01500                 if (codec_id == CODEC_ID_SIPR && flavor < 4) {
01501                     const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
01502                     track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
01503                     st->codec->bit_rate = sipr_bit_rate[flavor];
01504                 }
01505                 st->codec->block_align = track->audio.sub_packet_size;
01506                 extradata_offset = 78;
01507             }
01508         }
01509         track->codec_priv.size -= extradata_offset;
01510 
01511         if (codec_id == CODEC_ID_NONE)
01512             av_log(matroska->ctx, AV_LOG_INFO,
01513                    "Unknown/unsupported CodecID %s.\n", track->codec_id);
01514 
01515         if (track->time_scale < 0.01)
01516             track->time_scale = 1.0;
01517         avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
01518 
01519         st->codec->codec_id = codec_id;
01520         st->start_time = 0;
01521         if (strcmp(track->language, "und"))
01522             av_dict_set(&st->metadata, "language", track->language, 0);
01523         av_dict_set(&st->metadata, "title", track->name, 0);
01524 
01525         if (track->flag_default)
01526             st->disposition |= AV_DISPOSITION_DEFAULT;
01527         if (track->flag_forced)
01528             st->disposition |= AV_DISPOSITION_FORCED;
01529 
01530         if (!st->codec->extradata) {
01531             if(extradata){
01532                 st->codec->extradata = extradata;
01533                 st->codec->extradata_size = extradata_size;
01534             } else if(track->codec_priv.data && track->codec_priv.size > 0){
01535                 st->codec->extradata = av_mallocz(track->codec_priv.size +
01536                                                   FF_INPUT_BUFFER_PADDING_SIZE);
01537                 if(st->codec->extradata == NULL)
01538                     return AVERROR(ENOMEM);
01539                 st->codec->extradata_size = track->codec_priv.size;
01540                 memcpy(st->codec->extradata,
01541                        track->codec_priv.data + extradata_offset,
01542                        track->codec_priv.size);
01543             }
01544         }
01545 
01546         if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
01547             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
01548             st->codec->codec_tag  = track->video.fourcc;
01549             st->codec->width  = track->video.pixel_width;
01550             st->codec->height = track->video.pixel_height;
01551             av_reduce(&st->sample_aspect_ratio.num,
01552                       &st->sample_aspect_ratio.den,
01553                       st->codec->height * track->video.display_width,
01554                       st->codec-> width * track->video.display_height,
01555                       255);
01556             if (st->codec->codec_id != CODEC_ID_H264)
01557             st->need_parsing = AVSTREAM_PARSE_HEADERS;
01558             if (track->default_duration)
01559                 st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
01560         } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
01561             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
01562             st->codec->sample_rate = track->audio.out_samplerate;
01563             st->codec->channels = track->audio.channels;
01564             if (st->codec->codec_id != CODEC_ID_AAC)
01565             st->need_parsing = AVSTREAM_PARSE_HEADERS;
01566         } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
01567             st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
01568         }
01569     }
01570 
01571     attachements = attachements_list->elem;
01572     for (j=0; j<attachements_list->nb_elem; j++) {
01573         if (!(attachements[j].filename && attachements[j].mime &&
01574               attachements[j].bin.data && attachements[j].bin.size > 0)) {
01575             av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
01576         } else {
01577             AVStream *st = avformat_new_stream(s, NULL);
01578             if (st == NULL)
01579                 break;
01580             av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
01581             av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
01582             st->codec->codec_id = CODEC_ID_NONE;
01583             st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
01584             st->codec->extradata  = av_malloc(attachements[j].bin.size);
01585             if(st->codec->extradata == NULL)
01586                 break;
01587             st->codec->extradata_size = attachements[j].bin.size;
01588             memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
01589 
01590             for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
01591                 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
01592                              strlen(ff_mkv_mime_tags[i].str))) {
01593                     st->codec->codec_id = ff_mkv_mime_tags[i].id;
01594                     break;
01595                 }
01596             }
01597             attachements[j].stream = st;
01598         }
01599     }
01600 
01601     chapters = chapters_list->elem;
01602     for (i=0; i<chapters_list->nb_elem; i++)
01603         if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
01604             && (max_start==0 || chapters[i].start > max_start)) {
01605             chapters[i].chapter =
01606             avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
01607                            chapters[i].start, chapters[i].end,
01608                            chapters[i].title);
01609             av_dict_set(&chapters[i].chapter->metadata,
01610                              "title", chapters[i].title, 0);
01611             max_start = chapters[i].start;
01612         }
01613 
01614     matroska_convert_tags(s);
01615 
01616     return 0;
01617 }
01618 
01619 /*
01620  * Put one packet in an application-supplied AVPacket struct.
01621  * Returns 0 on success or -1 on failure.
01622  */
01623 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
01624                                    AVPacket *pkt)
01625 {
01626     if (matroska->num_packets > 0) {
01627         memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
01628         av_free(matroska->packets[0]);
01629         if (matroska->num_packets > 1) {
01630             void *newpackets;
01631             memmove(&matroska->packets[0], &matroska->packets[1],
01632                     (matroska->num_packets - 1) * sizeof(AVPacket *));
01633             newpackets = av_realloc(matroska->packets,
01634                             (matroska->num_packets - 1) * sizeof(AVPacket *));
01635             if (newpackets)
01636                 matroska->packets = newpackets;
01637         } else {
01638             av_freep(&matroska->packets);
01639         }
01640         matroska->num_packets--;
01641         return 0;
01642     }
01643 
01644     return -1;
01645 }
01646 
01647 /*
01648  * Free all packets in our internal queue.
01649  */
01650 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
01651 {
01652     if (matroska->packets) {
01653         int n;
01654         for (n = 0; n < matroska->num_packets; n++) {
01655             av_free_packet(matroska->packets[n]);
01656             av_free(matroska->packets[n]);
01657         }
01658         av_freep(&matroska->packets);
01659         matroska->num_packets = 0;
01660     }
01661 }
01662 
01663 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
01664                                 int size, int64_t pos, uint64_t cluster_time,
01665                                 uint64_t duration, int is_keyframe,
01666                                 int64_t cluster_pos)
01667 {
01668     uint64_t timecode = AV_NOPTS_VALUE;
01669     MatroskaTrack *track;
01670     int res = 0;
01671     AVStream *st;
01672     AVPacket *pkt;
01673     int16_t block_time;
01674     uint32_t *lace_size = NULL;
01675     int n, flags, laces = 0;
01676     uint64_t num;
01677 
01678     if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
01679         av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
01680         return res;
01681     }
01682     data += n;
01683     size -= n;
01684 
01685     track = matroska_find_track_by_num(matroska, num);
01686     if (!track || !track->stream) {
01687         av_log(matroska->ctx, AV_LOG_INFO,
01688                "Invalid stream %"PRIu64" or size %u\n", num, size);
01689         return AVERROR_INVALIDDATA;
01690     } else if (size <= 3)
01691         return 0;
01692     st = track->stream;
01693     if (st->discard >= AVDISCARD_ALL)
01694         return res;
01695     if (duration == AV_NOPTS_VALUE)
01696         duration = track->default_duration / matroska->time_scale;
01697 
01698     block_time = AV_RB16(data);
01699     data += 2;
01700     flags = *data++;
01701     size -= 3;
01702     if (is_keyframe == -1)
01703         is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
01704 
01705     if (cluster_time != (uint64_t)-1
01706         && (block_time >= 0 || cluster_time >= -block_time)) {
01707         timecode = cluster_time + block_time;
01708         if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
01709             && timecode < track->end_timecode)
01710             is_keyframe = 0;  /* overlapping subtitles are not key frame */
01711         if (is_keyframe)
01712             av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
01713         track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
01714     }
01715 
01716     if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
01717         if (!is_keyframe || timecode < matroska->skip_to_timecode)
01718             return res;
01719         matroska->skip_to_keyframe = 0;
01720     }
01721 
01722     switch ((flags & 0x06) >> 1) {
01723         case 0x0: /* no lacing */
01724             laces = 1;
01725             lace_size = av_mallocz(sizeof(int));
01726             lace_size[0] = size;
01727             break;
01728 
01729         case 0x1: /* Xiph lacing */
01730         case 0x2: /* fixed-size lacing */
01731         case 0x3: /* EBML lacing */
01732             assert(size>0); // size <=3 is checked before size-=3 above
01733             laces = (*data) + 1;
01734             data += 1;
01735             size -= 1;
01736             lace_size = av_mallocz(laces * sizeof(int));
01737 
01738             switch ((flags & 0x06) >> 1) {
01739                 case 0x1: /* Xiph lacing */ {
01740                     uint8_t temp;
01741                     uint32_t total = 0;
01742                     for (n = 0; res == 0 && n < laces - 1; n++) {
01743                         while (1) {
01744                             if (size == 0) {
01745                                 res = -1;
01746                                 break;
01747                             }
01748                             temp = *data;
01749                             lace_size[n] += temp;
01750                             data += 1;
01751                             size -= 1;
01752                             if (temp != 0xff)
01753                                 break;
01754                         }
01755                         total += lace_size[n];
01756                     }
01757                     lace_size[n] = size - total;
01758                     break;
01759                 }
01760 
01761                 case 0x2: /* fixed-size lacing */
01762                     for (n = 0; n < laces; n++)
01763                         lace_size[n] = size / laces;
01764                     break;
01765 
01766                 case 0x3: /* EBML lacing */ {
01767                     uint32_t total;
01768                     n = matroska_ebmlnum_uint(matroska, data, size, &num);
01769                     if (n < 0) {
01770                         av_log(matroska->ctx, AV_LOG_INFO,
01771                                "EBML block data error\n");
01772                         break;
01773                     }
01774                     data += n;
01775                     size -= n;
01776                     total = lace_size[0] = num;
01777                     for (n = 1; res == 0 && n < laces - 1; n++) {
01778                         int64_t snum;
01779                         int r;
01780                         r = matroska_ebmlnum_sint(matroska, data, size, &snum);
01781                         if (r < 0) {
01782                             av_log(matroska->ctx, AV_LOG_INFO,
01783                                    "EBML block data error\n");
01784                             break;
01785                         }
01786                         data += r;
01787                         size -= r;
01788                         lace_size[n] = lace_size[n - 1] + snum;
01789                         total += lace_size[n];
01790                     }
01791                     lace_size[laces - 1] = size - total;
01792                     break;
01793                 }
01794             }
01795             break;
01796     }
01797 
01798     if (res == 0) {
01799         for (n = 0; n < laces; n++) {
01800             if ((st->codec->codec_id == CODEC_ID_RA_288 ||
01801                  st->codec->codec_id == CODEC_ID_COOK ||
01802                  st->codec->codec_id == CODEC_ID_SIPR ||
01803                  st->codec->codec_id == CODEC_ID_ATRAC3) &&
01804                  st->codec->block_align && track->audio.sub_packet_size) {
01805                 int a = st->codec->block_align;
01806                 int sps = track->audio.sub_packet_size;
01807                 int cfs = track->audio.coded_framesize;
01808                 int h = track->audio.sub_packet_h;
01809                 int y = track->audio.sub_packet_cnt;
01810                 int w = track->audio.frame_size;
01811                 int x;
01812 
01813                 if (!track->audio.pkt_cnt) {
01814                     if (track->audio.sub_packet_cnt == 0)
01815                         track->audio.buf_timecode = timecode;
01816                     if (st->codec->codec_id == CODEC_ID_RA_288) {
01817                         if (size < cfs * h / 2) {
01818                             av_log(matroska->ctx, AV_LOG_ERROR,
01819                                    "Corrupt int4 RM-style audio packet size\n");
01820                             return AVERROR_INVALIDDATA;
01821                         }
01822                         for (x=0; x<h/2; x++)
01823                             memcpy(track->audio.buf+x*2*w+y*cfs,
01824                                    data+x*cfs, cfs);
01825                     } else if (st->codec->codec_id == CODEC_ID_SIPR) {
01826                         if (size < w) {
01827                             av_log(matroska->ctx, AV_LOG_ERROR,
01828                                    "Corrupt sipr RM-style audio packet size\n");
01829                             return AVERROR_INVALIDDATA;
01830                         }
01831                         memcpy(track->audio.buf + y*w, data, w);
01832                     } else {
01833                         if (size < sps * w / sps) {
01834                             av_log(matroska->ctx, AV_LOG_ERROR,
01835                                    "Corrupt generic RM-style audio packet size\n");
01836                             return AVERROR_INVALIDDATA;
01837                         }
01838                         for (x=0; x<w/sps; x++)
01839                             memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
01840                     }
01841 
01842                     if (++track->audio.sub_packet_cnt >= h) {
01843                         if (st->codec->codec_id == CODEC_ID_SIPR)
01844                             ff_rm_reorder_sipr_data(track->audio.buf, h, w);
01845                         track->audio.sub_packet_cnt = 0;
01846                         track->audio.pkt_cnt = h*w / a;
01847                     }
01848                 }
01849                 while (track->audio.pkt_cnt) {
01850                     pkt = av_mallocz(sizeof(AVPacket));
01851                     av_new_packet(pkt, a);
01852                     memcpy(pkt->data, track->audio.buf
01853                            + a * (h*w / a - track->audio.pkt_cnt--), a);
01854                     pkt->pts = track->audio.buf_timecode;
01855                     track->audio.buf_timecode = AV_NOPTS_VALUE;
01856                     pkt->pos = pos;
01857                     pkt->stream_index = st->index;
01858                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
01859                 }
01860             } else {
01861                 MatroskaTrackEncoding *encodings = track->encodings.elem;
01862                 int offset = 0, pkt_size = lace_size[n];
01863                 uint8_t *pkt_data = data;
01864 
01865                 if (pkt_size > size) {
01866                     av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
01867                     break;
01868                 }
01869 
01870                 if (encodings && encodings->scope & 1) {
01871                     offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
01872                     if (offset < 0)
01873                         continue;
01874                 }
01875 
01876                 pkt = av_mallocz(sizeof(AVPacket));
01877                 /* XXX: prevent data copy... */
01878                 if (av_new_packet(pkt, pkt_size+offset) < 0) {
01879                     av_free(pkt);
01880                     res = AVERROR(ENOMEM);
01881                     break;
01882                 }
01883                 if (offset)
01884                     memcpy (pkt->data, encodings->compression.settings.data, offset);
01885                 memcpy (pkt->data+offset, pkt_data, pkt_size);
01886 
01887                 if (pkt_data != data)
01888                     av_free(pkt_data);
01889 
01890                 if (n == 0)
01891                     pkt->flags = is_keyframe;
01892                 pkt->stream_index = st->index;
01893 
01894                 if (track->ms_compat)
01895                     pkt->dts = timecode;
01896                 else
01897                     pkt->pts = timecode;
01898                 pkt->pos = pos;
01899                 if (st->codec->codec_id == CODEC_ID_TEXT)
01900                     pkt->convergence_duration = duration;
01901                 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
01902                     pkt->duration = duration;
01903 
01904                 if (st->codec->codec_id == CODEC_ID_SSA)
01905                     matroska_fix_ass_packet(matroska, pkt, duration);
01906 
01907                 if (matroska->prev_pkt &&
01908                     timecode != AV_NOPTS_VALUE &&
01909                     matroska->prev_pkt->pts == timecode &&
01910                     matroska->prev_pkt->stream_index == st->index &&
01911                     st->codec->codec_id == CODEC_ID_SSA)
01912                     matroska_merge_packets(matroska->prev_pkt, pkt);
01913                 else {
01914                     dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
01915                     matroska->prev_pkt = pkt;
01916                 }
01917             }
01918 
01919             if (timecode != AV_NOPTS_VALUE)
01920                 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
01921             data += lace_size[n];
01922             size -= lace_size[n];
01923         }
01924     }
01925 
01926     av_free(lace_size);
01927     return res;
01928 }
01929 
01930 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
01931 {
01932     MatroskaCluster cluster = { 0 };
01933     EbmlList *blocks_list;
01934     MatroskaBlock *blocks;
01935     int i, res;
01936     int64_t pos = avio_tell(matroska->ctx->pb);
01937     matroska->prev_pkt = NULL;
01938     if (matroska->current_id)
01939         pos -= 4;  /* sizeof the ID which was already read */
01940     res = ebml_parse(matroska, matroska_clusters, &cluster);
01941     blocks_list = &cluster.blocks;
01942     blocks = blocks_list->elem;
01943     for (i=0; i<blocks_list->nb_elem && !res; i++)
01944         if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
01945             int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
01946             if (!blocks[i].non_simple)
01947                 blocks[i].duration = AV_NOPTS_VALUE;
01948             res=matroska_parse_block(matroska,
01949                                      blocks[i].bin.data, blocks[i].bin.size,
01950                                      blocks[i].bin.pos,  cluster.timecode,
01951                                      blocks[i].duration, is_keyframe,
01952                                      pos);
01953         }
01954     ebml_free(matroska_cluster, &cluster);
01955     if (res < 0)  matroska->done = 1;
01956     return res;
01957 }
01958 
01959 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
01960 {
01961     MatroskaDemuxContext *matroska = s->priv_data;
01962     int ret = 0;
01963 
01964     while (!ret && matroska_deliver_packet(matroska, pkt)) {
01965         if (matroska->done)
01966             return AVERROR_EOF;
01967         ret = matroska_parse_cluster(matroska);
01968     }
01969 
01970     return ret;
01971 }
01972 
01973 static int matroska_read_seek(AVFormatContext *s, int stream_index,
01974                               int64_t timestamp, int flags)
01975 {
01976     MatroskaDemuxContext *matroska = s->priv_data;
01977     MatroskaTrack *tracks = NULL;
01978     AVStream *st = s->streams[stream_index];
01979     int i, index, index_sub, index_min;
01980 
01981     /* Parse the CUES now since we need the index data to seek. */
01982     if (matroska->cues_parsing_deferred) {
01983         matroska_parse_cues(matroska);
01984         matroska->cues_parsing_deferred = 0;
01985     }
01986 
01987     if (!st->nb_index_entries)
01988         return 0;
01989     timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
01990 
01991     if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
01992         avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
01993         matroska->current_id = 0;
01994         while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
01995             matroska_clear_queue(matroska);
01996             if (matroska_parse_cluster(matroska) < 0)
01997                 break;
01998         }
01999     }
02000 
02001     matroska_clear_queue(matroska);
02002     if (index < 0)
02003         return 0;
02004 
02005     index_min = index;
02006     tracks = matroska->tracks.elem;
02007     for (i=0; i < matroska->tracks.nb_elem; i++) {
02008         tracks[i].audio.pkt_cnt = 0;
02009         tracks[i].audio.sub_packet_cnt = 0;
02010         tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
02011         tracks[i].end_timecode = 0;
02012         if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
02013             && !tracks[i].stream->discard != AVDISCARD_ALL) {
02014             index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
02015             if (index_sub >= 0
02016                 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
02017                 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
02018                 index_min = index_sub;
02019         }
02020     }
02021 
02022     avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
02023     matroska->current_id = 0;
02024     matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
02025     matroska->skip_to_timecode = st->index_entries[index].timestamp;
02026     matroska->done = 0;
02027     ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
02028     return 0;
02029 }
02030 
02031 static int matroska_read_close(AVFormatContext *s)
02032 {
02033     MatroskaDemuxContext *matroska = s->priv_data;
02034     MatroskaTrack *tracks = matroska->tracks.elem;
02035     int n;
02036 
02037     matroska_clear_queue(matroska);
02038 
02039     for (n=0; n < matroska->tracks.nb_elem; n++)
02040         if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
02041             av_free(tracks[n].audio.buf);
02042     ebml_free(matroska_segment, matroska);
02043 
02044     return 0;
02045 }
02046 
02047 AVInputFormat ff_matroska_demuxer = {
02048     .name           = "matroska,webm",
02049     .long_name      = NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
02050     .priv_data_size = sizeof(MatroskaDemuxContext),
02051     .read_probe     = matroska_probe,
02052     .read_header    = matroska_read_header,
02053     .read_packet    = matroska_read_packet,
02054     .read_close     = matroska_read_close,
02055     .read_seek      = matroska_read_seek,
02056 };