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