Libav

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