• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

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

Generated on Wed Apr 11 2012 07:31:36 for FFmpeg by  doxygen 1.7.1