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