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