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

libavformat/matroskadec.c

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

Generated on Sat Feb 16 2013 09:23:14 for ffmpeg by  doxygen 1.7.1