matroskadec.c 84.7 KB
Newer Older
1
/*
2
 * Matroska file demuxer
3
 * Copyright (c) 2003-2008 The Libav Project
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
8 9 10 11
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
12
 * Libav is distributed in the hope that it will be useful,
13 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with Libav; if not, write to the Free Software
19 20 21 22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
23
 * @file
24
 * Matroska file demuxer
25 26 27 28
 * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
 * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
 * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
 * @see specs available on the Matroska project page: http://www.matroska.org/
29 30
 */

31
#include <stdio.h>
32
#include "avformat.h"
33
#include "internal.h"
34
#include "avio_internal.h"
35
/* For ff_codec_get_id(). */
36
#include "riff.h"
37
#include "isom.h"
38
#include "rmsipr.h"
39
#include "matroska.h"
40
#include "libavcodec/bytestream.h"
41
#include "libavcodec/mpeg4audio.h"
42
#include "libavutil/intfloat.h"
43
#include "libavutil/intreadwrite.h"
44
#include "libavutil/avstring.h"
45
#include "libavutil/lzo.h"
46
#include "libavutil/dict.h"
47
#if CONFIG_ZLIB
48 49
#include <zlib.h>
#endif
50
#if CONFIG_BZLIB
51 52
#include <bzlib.h>
#endif
53

54 55 56 57 58 59 60 61 62 63
typedef enum {
    EBML_NONE,
    EBML_UINT,
    EBML_FLOAT,
    EBML_STR,
    EBML_UTF8,
    EBML_BIN,
    EBML_NEST,
    EBML_PASS,
    EBML_STOP,
64
    EBML_TYPE_COUNT
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
} EbmlType;

typedef const struct EbmlSyntax {
    uint32_t id;
    EbmlType type;
    int list_elem_size;
    int data_offset;
    union {
        uint64_t    u;
        double      f;
        const char *s;
        const struct EbmlSyntax *n;
    } def;
} EbmlSyntax;

typedef struct {
    int nb_elem;
    void *elem;
} EbmlList;

typedef struct {
    int      size;
    uint8_t *data;
    int64_t  pos;
} EbmlBin;

91 92 93 94 95 96 97 98
typedef struct {
    uint64_t version;
    uint64_t max_size;
    uint64_t id_length;
    char    *doctype;
    uint64_t doctype_version;
} Ebml;

99 100 101 102
typedef struct {
    uint64_t algo;
    EbmlBin  settings;
} MatroskaTrackCompression;
103

104 105 106 107 108
typedef struct {
    uint64_t scope;
    uint64_t type;
    MatroskaTrackCompression compression;
} MatroskaTrackEncoding;
109

110 111 112 113 114 115 116 117
typedef struct {
    double   frame_rate;
    uint64_t display_width;
    uint64_t display_height;
    uint64_t pixel_width;
    uint64_t pixel_height;
    uint64_t fourcc;
} MatroskaTrackVideo;
118

119 120 121 122 123 124 125 126 127 128 129 130 131
typedef struct {
    double   samplerate;
    double   out_samplerate;
    uint64_t bitdepth;
    uint64_t channels;

    /* real audio header (extracted from extradata) */
    int      coded_framesize;
    int      sub_packet_h;
    int      frame_size;
    int      sub_packet_size;
    int      sub_packet_cnt;
    int      pkt_cnt;
132
    uint64_t buf_timecode;
133 134
    uint8_t *buf;
} MatroskaTrackAudio;
135

136 137
typedef struct {
    uint64_t num;
138
    uint64_t uid;
139
    uint64_t type;
140
    char    *name;
141 142 143
    char    *codec_id;
    EbmlBin  codec_priv;
    char    *language;
144
    double time_scale;
145
    uint64_t default_duration;
146
    uint64_t flag_default;
147
    uint64_t flag_forced;
148 149 150
    MatroskaTrackVideo video;
    MatroskaTrackAudio audio;
    EbmlList encodings;
151 152

    AVStream *stream;
153
    int64_t end_timecode;
154
    int ms_compat;
155 156
} MatroskaTrack;

157
typedef struct {
158
    uint64_t uid;
159 160 161
    char *filename;
    char *mime;
    EbmlBin bin;
162 163

    AVStream *stream;
164 165
} MatroskaAttachement;

166 167 168 169 170
typedef struct {
    uint64_t start;
    uint64_t end;
    uint64_t uid;
    char    *title;
171 172

    AVChapter *chapter;
173 174
} MatroskaChapter;

175 176 177 178 179 180 181 182 183 184
typedef struct {
    uint64_t track;
    uint64_t pos;
} MatroskaIndexPos;

typedef struct {
    uint64_t time;
    EbmlList pos;
} MatroskaIndex;

185 186 187
typedef struct {
    char *name;
    char *string;
188 189
    char *lang;
    uint64_t def;
190 191 192
    EbmlList sub;
} MatroskaTag;

193 194 195 196 197 198 199 200 201 202 203 204 205
typedef struct {
    char    *type;
    uint64_t typevalue;
    uint64_t trackuid;
    uint64_t chapteruid;
    uint64_t attachuid;
} MatroskaTagTarget;

typedef struct {
    MatroskaTagTarget target;
    EbmlList tag;
} MatroskaTags;

206 207 208 209 210
typedef struct {
    uint64_t id;
    uint64_t pos;
} MatroskaSeekhead;

211
typedef struct {
212 213
    uint64_t start;
    uint64_t length;
214 215
} MatroskaLevel;

216 217 218 219 220
typedef struct {
    uint64_t timecode;
    EbmlList blocks;
} MatroskaCluster;

221
typedef struct {
222 223
    AVFormatContext *ctx;

Diego Biurrun's avatar
Diego Biurrun committed
224
    /* EBML stuff */
225 226 227
    int num_levels;
    MatroskaLevel levels[EBML_MAX_DEPTH];
    int level_up;
228
    uint32_t current_id;
229

230 231 232
    uint64_t time_scale;
    double   duration;
    char    *title;
233
    EbmlList tracks;
234
    EbmlList attachments;
235
    EbmlList chapters;
236
    EbmlList index;
237
    EbmlList tags;
238
    EbmlList seekhead;
239 240

    /* byte position of the segment inside the stream */
241
    int64_t segment_start;
242

Diego Biurrun's avatar
Diego Biurrun committed
243
    /* the packet queue */
244 245
    AVPacket **packets;
    int num_packets;
246
    AVPacket *prev_pkt;
247

248
    int done;
249 250 251

    /* What to skip before effectively reading a packet. */
    int skip_to_keyframe;
252
    uint64_t skip_to_timecode;
253 254 255

    /* File has a CUES element, but we defer parsing until it is needed. */
    int cues_parsing_deferred;
256 257 258 259 260 261 262

    int current_cluster_num_blocks;
    int64_t current_cluster_pos;
    MatroskaCluster current_cluster;

    /* File has SSA subtitles which prevent incremental cluster parsing. */
    int contains_ssa;
263 264
} MatroskaDemuxContext;

265 266 267
typedef struct {
    uint64_t duration;
    int64_t  reference;
268
    uint64_t non_simple;
269 270 271
    EbmlBin  bin;
} MatroskaBlock;

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
static EbmlSyntax ebml_header[] = {
    { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
    { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
    { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
    { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
    { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
    { EBML_ID_EBMLVERSION,            EBML_NONE },
    { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
    { 0 }
};

static EbmlSyntax ebml_syntax[] = {
    { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
    { 0 }
};

288 289 290 291 292 293 294 295 296 297 298
static EbmlSyntax matroska_info[] = {
    { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
    { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
    { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
    { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
    { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
    { MATROSKA_ID_DATEUTC,            EBML_NONE },
    { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
    { 0 }
};

299 300 301 302 303 304 305
static EbmlSyntax matroska_track_video[] = {
    { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
    { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
    { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
    { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
    { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
    { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
306 307 308 309 310
    { MATROSKA_ID_VIDEOPIXELCROPB,    EBML_NONE },
    { MATROSKA_ID_VIDEOPIXELCROPT,    EBML_NONE },
    { MATROSKA_ID_VIDEOPIXELCROPL,    EBML_NONE },
    { MATROSKA_ID_VIDEOPIXELCROPR,    EBML_NONE },
    { MATROSKA_ID_VIDEODISPLAYUNIT,   EBML_NONE },
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
    { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
    { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
    { 0 }
};

static EbmlSyntax matroska_track_audio[] = {
    { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
    { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
    { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
    { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
    { 0 }
};

static EbmlSyntax matroska_track_encoding_compression[] = {
    { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
    { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
    { 0 }
};

static EbmlSyntax matroska_track_encoding[] = {
    { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
    { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
    { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
335
    { MATROSKA_ID_ENCODINGORDER,      EBML_NONE },
336 337 338 339 340 341 342 343 344 345
    { 0 }
};

static EbmlSyntax matroska_track_encodings[] = {
    { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
    { 0 }
};

static EbmlSyntax matroska_track[] = {
    { MATROSKA_ID_TRACKNUMBER,          EBML_UINT, 0, offsetof(MatroskaTrack,num) },
346
    { MATROSKA_ID_TRACKNAME,            EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
347
    { MATROSKA_ID_TRACKUID,             EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
348 349 350 351 352 353 354
    { MATROSKA_ID_TRACKTYPE,            EBML_UINT, 0, offsetof(MatroskaTrack,type) },
    { MATROSKA_ID_CODECID,              EBML_STR,  0, offsetof(MatroskaTrack,codec_id) },
    { MATROSKA_ID_CODECPRIVATE,         EBML_BIN,  0, offsetof(MatroskaTrack,codec_priv) },
    { MATROSKA_ID_TRACKLANGUAGE,        EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
    { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
    { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
    { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
355
    { MATROSKA_ID_TRACKFLAGFORCED,      EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
356 357 358 359 360 361 362 363 364 365 366
    { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
    { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
    { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
    { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
    { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
    { MATROSKA_ID_CODECNAME,            EBML_NONE },
    { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
    { MATROSKA_ID_CODECINFOURL,         EBML_NONE },
    { MATROSKA_ID_CODECDOWNLOADURL,     EBML_NONE },
    { MATROSKA_ID_TRACKMINCACHE,        EBML_NONE },
    { MATROSKA_ID_TRACKMAXCACHE,        EBML_NONE },
367
    { MATROSKA_ID_TRACKMAXBLKADDID,     EBML_NONE },
368 369 370 371 372 373 374 375
    { 0 }
};

static EbmlSyntax matroska_tracks[] = {
    { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
    { 0 }
};

376
static EbmlSyntax matroska_attachment[] = {
377
    { MATROSKA_ID_FILEUID,            EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
378 379 380
    { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
    { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
    { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
381
    { MATROSKA_ID_FILEDESC,           EBML_NONE },
382 383 384 385 386 387 388 389
    { 0 }
};

static EbmlSyntax matroska_attachments[] = {
    { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
    { 0 }
};

390 391
static EbmlSyntax matroska_chapter_display[] = {
    { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
392
    { MATROSKA_ID_CHAPLANG,           EBML_NONE },
393 394 395 396 397 398 399 400 401
    { 0 }
};

static EbmlSyntax matroska_chapter_entry[] = {
    { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
    { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
    { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
    { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
    { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
402 403 404
    { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
    { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
    { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
405 406 407 408 409 410 411 412
    { 0 }
};

static EbmlSyntax matroska_chapter[] = {
    { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
    { MATROSKA_ID_EDITIONUID,         EBML_NONE },
    { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
    { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
413
    { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
414 415 416 417 418 419 420 421
    { 0 }
};

static EbmlSyntax matroska_chapters[] = {
    { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
    { 0 }
};

422 423 424
static EbmlSyntax matroska_index_pos[] = {
    { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
    { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
425
    { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
426 427 428 429 430 431 432 433 434 435 436 437 438 439
    { 0 }
};

static EbmlSyntax matroska_index_entry[] = {
    { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
    { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
    { 0 }
};

static EbmlSyntax matroska_index[] = {
    { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
    { 0 }
};

440 441 442
static EbmlSyntax matroska_simpletag[] = {
    { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
    { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
443 444
    { MATROSKA_ID_TAGLANG,            EBML_STR,  0, offsetof(MatroskaTag,lang), {.s="und"} },
    { MATROSKA_ID_TAGDEFAULT,         EBML_UINT, 0, offsetof(MatroskaTag,def) },
445
    { MATROSKA_ID_TAGDEFAULT_BUG,     EBML_UINT, 0, offsetof(MatroskaTag,def) },
446 447 448 449
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
    { 0 }
};

450 451 452 453 454 455 456 457 458
static EbmlSyntax matroska_tagtargets[] = {
    { MATROSKA_ID_TAGTARGETS_TYPE,      EBML_STR,  0, offsetof(MatroskaTagTarget,type) },
    { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
    { MATROSKA_ID_TAGTARGETS_TRACKUID,  EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
    { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
    { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
    { 0 }
};

459
static EbmlSyntax matroska_tag[] = {
460 461
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
    { MATROSKA_ID_TAGTARGETS,         EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
462 463 464
    { 0 }
};

465
static EbmlSyntax matroska_tags[] = {
466
    { MATROSKA_ID_TAG,                EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
467 468 469
    { 0 }
};

470 471 472 473 474 475 476 477 478 479 480
static EbmlSyntax matroska_seekhead_entry[] = {
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
    { 0 }
};

static EbmlSyntax matroska_seekhead[] = {
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
    { 0 }
};

481 482 483 484 485 486 487 488
static EbmlSyntax matroska_segment[] = {
    { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
    { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
    { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
    { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
    { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
    { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
    { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
489
    { MATROSKA_ID_CLUSTER,        EBML_STOP },
490 491 492 493 494 495 496 497
    { 0 }
};

static EbmlSyntax matroska_segments[] = {
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
    { 0 }
};

498 499 500 501 502
static EbmlSyntax matroska_blockgroup[] = {
    { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
    { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
    { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
503
    { MATROSKA_ID_CODECSTATE,     EBML_NONE },
504
    { 1,                          EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
505 506 507 508 509 510 511
    { 0 }
};

static EbmlSyntax matroska_cluster[] = {
    { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
    { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
512 513
    { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
    { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
514 515 516 517 518
    { 0 }
};

static EbmlSyntax matroska_clusters[] = {
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
519 520 521 522
    { MATROSKA_ID_INFO,           EBML_NONE },
    { MATROSKA_ID_CUES,           EBML_NONE },
    { MATROSKA_ID_TAGS,           EBML_NONE },
    { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
523 524 525
    { 0 }
};

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
static EbmlSyntax matroska_cluster_incremental_parsing[] = {
    { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
    { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
    { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
    { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
    { MATROSKA_ID_INFO,           EBML_NONE },
    { MATROSKA_ID_CUES,           EBML_NONE },
    { MATROSKA_ID_TAGS,           EBML_NONE },
    { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
    { MATROSKA_ID_CLUSTER,        EBML_STOP },
    { 0 }
};

static EbmlSyntax matroska_cluster_incremental[] = {
    { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
    { MATROSKA_ID_BLOCKGROUP,     EBML_STOP },
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_STOP },
    { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
    { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
    { 0 }
};

static EbmlSyntax matroska_clusters_incremental[] = {
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
    { MATROSKA_ID_INFO,           EBML_NONE },
    { MATROSKA_ID_CUES,           EBML_NONE },
    { MATROSKA_ID_TAGS,           EBML_NONE },
    { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
    { 0 }
};

558
static const char *const matroska_doctypes[] = { "matroska", "webm" };
James Zern's avatar
James Zern committed
559

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
{
    AVIOContext *pb = matroska->ctx->pb;
    uint32_t id;
    matroska->current_id = 0;
    matroska->num_levels = 0;

    /* seek to next position to resync from */
    if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0)
        goto eof;

    id = avio_rb32(pb);

    // try to find a toplevel element
    while (!pb->eof_reached) {
        if (id == MATROSKA_ID_INFO     || id == MATROSKA_ID_TRACKS      ||
            id == MATROSKA_ID_CUES     || id == MATROSKA_ID_TAGS        ||
            id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
            id == MATROSKA_ID_CLUSTER  || id == MATROSKA_ID_CHAPTERS) {
                matroska->current_id = id;
                return 0;
        }
        id = (id << 8) | avio_r8(pb);
    }
eof:
    matroska->done = 1;
    return AVERROR_EOF;
}

589
/*
Diego Biurrun's avatar
Diego Biurrun committed
590
 * Return: Whether we reached the end of a level in the hierarchy or not.
591
 */
592
static int ebml_level_end(MatroskaDemuxContext *matroska)
593
{
594
    AVIOContext *pb = matroska->ctx->pb;
595
    int64_t pos = avio_tell(pb);
596

597
    if (matroska->num_levels > 0) {
598
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
599
        if (pos - level->start >= level->length || matroska->current_id) {
600
            matroska->num_levels--;
601
            return 1;
602 603
        }
    }
604
    return 0;
605 606 607 608 609 610 611 612
}

/*
 * Read: an "EBML number", which is defined as a variable-length
 * array of bytes. The first byte indicates the length by giving a
 * number of 0-bits followed by a one. The position of the first
 * "one" bit inside the first byte indicates the length of this
 * number.
Diego Biurrun's avatar
Diego Biurrun committed
613
 * Returns: number of bytes read, < 0 on error
614
 */
615
static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
616
                         int max_size, uint64_t *number)
617
{
618 619
    int read = 1, n = 1;
    uint64_t total = 0;
620

621
    /* The first byte tells us the length in bytes - avio_r8() can normally
622 623
     * return 0, but since that's not a valid first ebmlID byte, we can
     * use it safely here to catch EOS. */
624
    if (!(total = avio_r8(pb))) {
625
        /* we might encounter EOS here */
Anton Khirnov's avatar
Anton Khirnov committed
626
        if (!pb->eof_reached) {
627
            int64_t pos = avio_tell(pb);
628 629 630
            av_log(matroska->ctx, AV_LOG_ERROR,
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
                   pos, pos);
631
            return pb->error ? pb->error : AVERROR(EIO);
632
        }
633
        return AVERROR_EOF;
634 635 636
    }

    /* get the length of the EBML number */
637
    read = 8 - ff_log2_tab[total];
638
    if (read > max_size) {
639
        int64_t pos = avio_tell(pb) - 1;
640 641 642 643 644 645 646
        av_log(matroska->ctx, AV_LOG_ERROR,
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
               (uint8_t) total, pos, pos);
        return AVERROR_INVALIDDATA;
    }

    /* read out length */
647
    total ^= 1 << ff_log2_tab[total];
648
    while (n++ < read)
649
        total = (total << 8) | avio_r8(pb);
650 651 652 653 654 655

    *number = total;

    return read;
}

656 657 658 659 660
/**
 * Read a EBML length value.
 * This needs special handling for the "unknown length" case which has multiple
 * encodings.
 */
661
static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
662 663 664 665 666 667 668 669
                            uint64_t *number)
{
    int res = ebml_read_num(matroska, pb, 8, number);
    if (res > 0 && *number + 1 == 1ULL << (7 * res))
        *number = 0xffffffffffffffULL;
    return res;
}

670 671 672 673
/*
 * Read the next element as an unsigned int.
 * 0 is success, < 0 is failure.
 */
674
static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
675
{
676
    int n = 0;
677

678
    if (size > 8)
679 680
        return AVERROR_INVALIDDATA;

Diego Biurrun's avatar
Diego Biurrun committed
681
    /* big-endian ordering; build up number */
682 683
    *num = 0;
    while (n++ < size)
684
        *num = (*num << 8) | avio_r8(pb);
685 686 687 688 689 690 691 692

    return 0;
}

/*
 * Read the next element as a float.
 * 0 is success, < 0 is failure.
 */
693
static int ebml_read_float(AVIOContext *pb, int size, double *num)
694
{
695 696 697
    if (size == 0) {
        *num = 0;
    } else if (size == 4) {
698 699 700
        *num = av_int2float(avio_rb32(pb));
    } else if (size == 8){
        *num = av_int2double(avio_rb64(pb));
701
    } else
702 703 704 705 706 707 708 709 710
        return AVERROR_INVALIDDATA;

    return 0;
}

/*
 * Read the next element as an ASCII string.
 * 0 is success, < 0 is failure.
 */
711
static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
712
{
713 714
    char *res;

Diego Biurrun's avatar
Diego Biurrun committed
715
    /* EBML strings are usually not 0-terminated, so we allocate one
716
     * byte more, read the string and NULL-terminate it ourselves. */
717
    if (!(res = av_malloc(size + 1)))
718
        return AVERROR(ENOMEM);
719 720
    if (avio_read(pb, (uint8_t *) res, size) != size) {
        av_free(res);
721
        return AVERROR(EIO);
722
    }
723 724 725
    (res)[size] = '\0';
    av_free(*str);
    *str = res;
726 727 728 729

    return 0;
}

730 731 732 733
/*
 * Read the next element as binary data.
 * 0 is success, < 0 is failure.
 */
734
static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
735 736
{
    av_free(bin->data);
737
    if (!(bin->data = av_malloc(length + FF_INPUT_BUFFER_PADDING_SIZE)))
738 739
        return AVERROR(ENOMEM);

740 741
    memset(bin->data + length, 0, FF_INPUT_BUFFER_PADDING_SIZE);

742
    bin->size = length;
743
    bin->pos  = avio_tell(pb);
744
    if (avio_read(pb, bin->data, length) != length) {
745
        av_freep(&bin->data);
746
        return AVERROR(EIO);
747
    }
748 749 750 751

    return 0;
}

752 753 754 755 756
/*
 * Read the next element, but only the header. The contents
 * are supposed to be sub-elements which can be read separately.
 * 0 is success, < 0 is failure.
 */
757
static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
758
{
759
    AVIOContext *pb = matroska->ctx->pb;
760 761 762 763 764
    MatroskaLevel *level;

    if (matroska->num_levels >= EBML_MAX_DEPTH) {
        av_log(matroska->ctx, AV_LOG_ERROR,
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
765
        return AVERROR(ENOSYS);
766 767 768
    }

    level = &matroska->levels[matroska->num_levels++];
769
    level->start = avio_tell(pb);
770 771 772 773 774 775 776
    level->length = length;

    return 0;
}

/*
 * Read signed/unsigned "EBML" numbers.
Diego Biurrun's avatar
Diego Biurrun committed
777
 * Return: number of bytes processed, < 0 on error
778
 */
779 780
static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
                                 uint8_t *data, uint32_t size, uint64_t *num)
781
{
782
    AVIOContext pb;
783
    ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
784
    return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
785 786 787 788 789
}

/*
 * Same as above, but signed.
 */
790 791
static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
                                 uint8_t *data, uint32_t size, int64_t *num)
792 793 794 795 796
{
    uint64_t unum;
    int res;

    /* read as unsigned number first */
797
    if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
798 799 800
        return res;

    /* make signed (weird way) */
801
    *num = unum - ((1LL << (7*res - 1)) - 1);
802 803 804 805

    return res;
}

806 807
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
                           EbmlSyntax *syntax, void *data);
808

809 810
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
                         uint32_t id, void *data)
811 812
{
    int i;
813 814 815
    for (i=0; syntax[i].id; i++)
        if (id == syntax[i].id)
            break;
816 817
    if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
        matroska->num_levels > 0 &&
818
        matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
819
        return 0;  // we reached the end of an unknown size cluster
820
    if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32) {
821
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
822 823 824
        if (matroska->ctx->error_recognition & AV_EF_EXPLODE)
            return AVERROR_INVALIDDATA;
    }
825
    return ebml_parse_elem(matroska, &syntax[i], data);
826 827
}

828 829
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
                      void *data)
830
{
831
    if (!matroska->current_id) {
832 833 834 835 836
        uint64_t id;
        int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
        if (res < 0)
            return res;
        matroska->current_id = id | 1 << 7*res;
837 838
    }
    return ebml_parse_id(matroska, syntax, matroska->current_id, data);
839 840
}

841 842
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
                           void *data)
843
{
844
    int i, res = 0;
845

846 847 848 849 850 851 852 853 854 855
    for (i=0; syntax[i].id; i++)
        switch (syntax[i].type) {
        case EBML_UINT:
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
            break;
        case EBML_FLOAT:
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
            break;
        case EBML_STR:
        case EBML_UTF8:
856 857 858 859 860 861 862
            // the default may be NULL
            if (syntax[i].def.s) {
                uint8_t **dst = (uint8_t**)((uint8_t*)data + syntax[i].data_offset);
                *dst = av_strdup(syntax[i].def.s);
                if (!*dst)
                    return AVERROR(ENOMEM);
            }
863
            break;
864
        }
865

866 867
    while (!res && !ebml_level_end(matroska))
        res = ebml_parse(matroska, syntax, data);
868

869
    return res;
870 871
}

872 873 874
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
                           EbmlSyntax *syntax, void *data)
{
875 876 877 878 879 880 881 882 883 884
    static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
        [EBML_UINT]  = 8,
        [EBML_FLOAT] = 8,
        // max. 16 MB for strings
        [EBML_STR]   = 0x1000000,
        [EBML_UTF8]  = 0x1000000,
        // max. 256 MB for binary data
        [EBML_BIN]   = 0x10000000,
        // no limits for anything else
    };
885
    AVIOContext *pb = matroska->ctx->pb;
886
    uint32_t id = syntax->id;
887
    uint64_t length;
888 889 890 891 892
    int res;

    data = (char *)data + syntax->data_offset;
    if (syntax->list_elem_size) {
        EbmlList *list = data;
893 894 895 896 897 898
        if ((res = av_reallocp_array(&list->elem,
                                     list->nb_elem + 1,
                                     syntax->list_elem_size)) < 0) {
            list->nb_elem = 0;
            return res;
        }
899 900 901 902 903
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
        memset(data, 0, syntax->list_elem_size);
        list->nb_elem++;
    }

904 905
    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
        matroska->current_id = 0;
906
        if ((res = ebml_read_length(matroska, pb, &length)) < 0)
907
            return res;
908 909 910 911 912 913
        if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
            av_log(matroska->ctx, AV_LOG_ERROR,
                   "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
                   length, max_lengths[syntax->type], syntax->type);
            return AVERROR_INVALIDDATA;
        }
914
    }
915

916
    switch (syntax->type) {
917 918
    case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
    case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
919
    case EBML_STR:
920
    case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
921
    case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
922
    case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
923 924
                         return res;
                     if (id == MATROSKA_ID_SEGMENT)
925
                         matroska->segment_start = avio_tell(matroska->ctx->pb);
926
                     return ebml_parse_nest(matroska, syntax->def.n, data);
927
    case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
928
    case EBML_STOP:  return 1;
929
    default:         return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
930
    }
931 932 933 934 935
    if (res == AVERROR_INVALIDDATA)
        av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
    else if (res == AVERROR(EIO))
        av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
    return res;
936 937 938 939 940 941 942 943 944