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