matroskadec.c 95.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * Matroska file demuxer (no muxer yet)
 * Copyright (c) 2003-2004 The ffmpeg Project
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * 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.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * 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
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
23
 * @file matroskadec.c
24 25 26 27 28 29 30 31 32 33
 * Matroska file demuxer
 * by Ronald Bultje <rbultje@ronald.bitfreak.net>
 * with a little help from Moritz Bunkus <moritz@bunkus.org>
 * Specs available on the matroska project page:
 * http://www.matroska.org/.
 */

#include "avformat.h"
/* For codec_get_id(). */
#include "riff.h"
34
#include "isom.h"
35
#include "matroska.h"
36
#include "libavcodec/mpeg4audio.h"
37
#include "libavutil/intfloat_readwrite.h"
38
#include "libavutil/avstring.h"
39
#include "libavutil/lzo.h"
40 41 42
#ifdef CONFIG_ZLIB
#include <zlib.h>
#endif
43 44 45
#ifdef CONFIG_BZLIB
#include <bzlib.h>
#endif
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
typedef enum {
    EBML_NONE,
    EBML_UINT,
    EBML_FLOAT,
    EBML_STR,
    EBML_UTF8,
    EBML_BIN,
    EBML_NEST,
    EBML_PASS,
    EBML_STOP,
} 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;

83 84 85 86 87 88 89 90
typedef struct {
    uint64_t version;
    uint64_t max_size;
    uint64_t id_length;
    char    *doctype;
    uint64_t doctype_version;
} Ebml;

91 92 93 94 95
typedef struct Track {
    MatroskaTrackType type;

    /* Unique track number and track ID. stream_index is the index that
     * the calling app uses for this track. */
96 97
    uint32_t num;
    uint32_t uid;
98

99
    char *name;
100
    char language[4];
101

102
    char *codec_id;
103 104 105 106

    unsigned char *codec_priv;
    int codec_priv_size;

107
    double time_scale;
108
    uint64_t default_duration;
109
    uint64_t flag_default;
110 111

    int encoding_scope;
A
Aurelien Jacobs 已提交
112
    MatroskaTrackEncodingCompAlgo encoding_algo;
113 114
    uint8_t *encoding_settings;
    int encoding_settings_len;
115 116

    AVStream *stream;
117 118 119 120 121
} MatroskaTrack;

typedef struct MatroskaVideoTrack {
    MatroskaTrack track;

122 123 124 125
    int pixel_width;
    int pixel_height;
    int display_width;
    int display_height;
126 127 128 129 130 131 132 133 134

    uint32_t fourcc;

    //..
} MatroskaVideoTrack;

typedef struct MatroskaAudioTrack {
    MatroskaTrack track;

135 136 137 138
    int channels;
    int bitdepth;
    int internal_samplerate;
    int samplerate;
139 140 141 142 143 144 145 146 147 148
    int block_align;

    /* real audio header */
    int coded_framesize;
    int sub_packet_h;
    int frame_size;
    int sub_packet_size;
    int sub_packet_cnt;
    int pkt_cnt;
    uint8_t *buf;
149 150 151 152 153 154 155 156
    //..
} MatroskaAudioTrack;

typedef struct MatroskaSubtitleTrack {
    MatroskaTrack track;
    //..
} MatroskaSubtitleTrack;

157 158
#define MAX_TRACK_SIZE (FFMAX3(sizeof(MatroskaVideoTrack), \
                                    sizeof(MatroskaAudioTrack), \
159 160
                                    sizeof(MatroskaSubtitleTrack)))

161 162 163 164 165 166
typedef struct {
    char *filename;
    char *mime;
    EbmlBin bin;
} MatroskaAttachement;

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

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

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

184
typedef struct MatroskaLevel {
185 186
    uint64_t start;
    uint64_t length;
187 188 189 190 191 192 193 194 195 196 197 198
} MatroskaLevel;

typedef struct MatroskaDemuxContext {
    AVFormatContext *ctx;

    /* ebml stuff */
    int num_levels;
    MatroskaLevel levels[EBML_MAX_DEPTH];
    int level_up;

    /* timescale in the file */
    int64_t time_scale;
199
    EbmlList attachments;
200
    EbmlList chapters;
201
    EbmlList index;
202 203 204

    /* num_streams is the number of streams that av_new_stream() was called
     * for ( = that are available to the calling program). */
205 206
    int num_tracks;
    int num_streams;
207 208 209 210 211 212 213 214 215 216 217 218 219
    MatroskaTrack *tracks[MAX_STREAMS];

    /* cache for ID peeking */
    uint32_t peek_id;

    /* byte position of the segment inside the stream */
    offset_t segment_start;

    /* The packet queue. */
    AVPacket **packets;
    int num_packets;

    /* have we already parse metadata/cues/clusters? */
220 221 222
    int metadata_parsed;
    int index_parsed;
    int done;
223 224 225 226 227 228

    /* What to skip before effectively reading a packet. */
    int skip_to_keyframe;
    AVStream *skip_to_stream;
} MatroskaDemuxContext;

229 230
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
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 },
    { EBML_ID_VOID,                   EBML_NONE },
    { 0 }
};

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

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
static EbmlSyntax matroska_attachment[] = {
    { 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) },
    { MATROSKA_ID_FILEUID,            EBML_NONE },
    { EBML_ID_VOID,                   EBML_NONE },
    { 0 }
};

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

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
static EbmlSyntax matroska_chapter_display[] = {
    { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
    { EBML_ID_VOID,                   EBML_NONE },
    { 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 },
    { EBML_ID_VOID,                   EBML_NONE },
    { 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 },
    { EBML_ID_VOID,                   EBML_NONE },
    { 0 }
};

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

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
static EbmlSyntax matroska_index_pos[] = {
    { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
    { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
    { EBML_ID_VOID,                   EBML_NONE },
    { 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} },
    { EBML_ID_VOID,                   EBML_NONE },
    { 0 }
};

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

314 315 316 317 318
static EbmlSyntax matroska_tags[] = {
    { EBML_ID_VOID,                   EBML_NONE },
    { 0 }
};

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
/*
 * The first few functions handle EBML file parsing. The rest
 * is the document interpretation. Matroska really just is a
 * EBML file.
 */

/*
 * Return: the amount of levels in the hierarchy that the
 * current element lies higher than the previous one.
 * The opposite isn't done - that's auto-done using master
 * element reading.
 */

static int
ebml_read_element_level_up (MatroskaDemuxContext *matroska)
{
335
    ByteIOContext *pb = matroska->ctx->pb;
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    offset_t pos = url_ftell(pb);
    int num = 0;

    while (matroska->num_levels > 0) {
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];

        if (pos >= level->start + level->length) {
            matroska->num_levels--;
            num++;
        } else {
            break;
        }
    }

    return num;
}

/*
 * 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.
 * Returns: num. of bytes read. < 0 on error.
 */

static int
ebml_read_num (MatroskaDemuxContext *matroska,
               int                   max_size,
               uint64_t             *number)
{
367
    ByteIOContext *pb = matroska->ctx->pb;
368 369 370 371 372 373 374 375 376 377 378 379 380 381
    int len_mask = 0x80, read = 1, n = 1;
    int64_t total = 0;

    /* the first byte tells us the length in bytes - get_byte() can normally
     * return 0, but since that's not a valid first ebmlID byte, we can
     * use it safely here to catch EOS. */
    if (!(total = get_byte(pb))) {
        /* we might encounter EOS here */
        if (!url_feof(pb)) {
            offset_t pos = url_ftell(pb);
            av_log(matroska->ctx, AV_LOG_ERROR,
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
                   pos, pos);
        }
382
        return AVERROR(EIO); /* EOS or actual I/O error */
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    }

    /* get the length of the EBML number */
    while (read <= max_size && !(total & len_mask)) {
        read++;
        len_mask >>= 1;
    }
    if (read > max_size) {
        offset_t pos = url_ftell(pb) - 1;
        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 */
    total &= ~len_mask;
    while (n++ < read)
        total = (total << 8) | get_byte(pb);

    *number = total;

    return read;
}

/*
 * Read: the element content data ID.
 * Return: the number of bytes read or < 0 on error.
 */

static int
ebml_read_element_id (MatroskaDemuxContext *matroska,
                      uint32_t             *id,
                      int                  *level_up)
{
    int read;
    uint64_t total;

    /* if we re-call this, use our cached ID */
    if (matroska->peek_id != 0) {
        if (level_up)
            *level_up = 0;
        *id = matroska->peek_id;
        return 0;
    }

    /* read out the "EBML number", include tag in ID */
    if ((read = ebml_read_num(matroska, 4, &total)) < 0)
        return read;
    *id = matroska->peek_id  = total | (1 << (read * 7));

    /* level tracking */
    if (level_up)
        *level_up = ebml_read_element_level_up(matroska);

    return read;
}

/*
 * Read: element content length.
 * Return: the number of bytes read or < 0 on error.
 */

static int
ebml_read_element_length (MatroskaDemuxContext *matroska,
                          uint64_t             *length)
{
    /* clear cache since we're now beyond that data point */
    matroska->peek_id = 0;

    /* read out the "EBML number", include tag in ID */
    return ebml_read_num(matroska, 8, length);
}

/*
 * Return: the ID of the next element, or 0 on error.
 * Level_up contains the amount of levels that this
 * next element lies higher than the previous one.
 */

static uint32_t
ebml_peek_id (MatroskaDemuxContext *matroska,
              int                  *level_up)
{
    uint32_t id;

    if (ebml_read_element_id(matroska, &id, level_up) < 0)
        return 0;

    return id;
}

/*
 * Seek to a given offset.
 * 0 is success, -1 is failure.
 */

static int
ebml_read_seek (MatroskaDemuxContext *matroska,
                offset_t              offset)
{
484
    ByteIOContext *pb = matroska->ctx->pb;
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499

    /* clear ID cache, if any */
    matroska->peek_id = 0;

    return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
}

/*
 * Skip the next element.
 * 0 is success, -1 is failure.
 */

static int
ebml_read_skip (MatroskaDemuxContext *matroska)
{
500
    ByteIOContext *pb = matroska->ctx->pb;
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
    uint32_t id;
    uint64_t length;
    int res;

    if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
        (res = ebml_read_element_length(matroska, &length)) < 0)
        return res;

    url_fskip(pb, length);

    return 0;
}

/*
 * Read the next element as an unsigned int.
 * 0 is success, < 0 is failure.
 */

static int
ebml_read_uint (MatroskaDemuxContext *matroska,
                uint32_t             *id,
                uint64_t             *num)
{
524
    ByteIOContext *pb = matroska->ctx->pb;
525 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
    int n = 0, size, res;
    uint64_t rlength;

    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
        return res;
    size = rlength;
    if (size < 1 || size > 8) {
        offset_t pos = url_ftell(pb);
        av_log(matroska->ctx, AV_LOG_ERROR,
               "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
                size, pos, pos);
        return AVERROR_INVALIDDATA;
    }

    /* big-endian ordening; build up number */
    *num = 0;
    while (n++ < size)
        *num = (*num << 8) | get_byte(pb);

    return 0;
}

/*
 * Read the next element as a signed int.
 * 0 is success, < 0 is failure.
 */

static int
ebml_read_sint (MatroskaDemuxContext *matroska,
                uint32_t             *id,
                int64_t              *num)
{
558
    ByteIOContext *pb = matroska->ctx->pb;
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 589 590 591 592 593 594 595 596
    int size, n = 1, negative = 0, res;
    uint64_t rlength;

    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
        return res;
    size = rlength;
    if (size < 1 || size > 8) {
        offset_t pos = url_ftell(pb);
        av_log(matroska->ctx, AV_LOG_ERROR,
               "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
                size, pos, pos);
        return AVERROR_INVALIDDATA;
    }
    if ((*num = get_byte(pb)) & 0x80) {
        negative = 1;
        *num &= ~0x80;
    }
    while (n++ < size)
        *num = (*num << 8) | get_byte(pb);

    /* make signed */
    if (negative)
        *num = *num - (1LL << ((8 * size) - 1));

    return 0;
}

/*
 * Read the next element as a float.
 * 0 is success, < 0 is failure.
 */

static int
ebml_read_float (MatroskaDemuxContext *matroska,
                 uint32_t             *id,
                 double               *num)
{
597
    ByteIOContext *pb = matroska->ctx->pb;
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    int size, res;
    uint64_t rlength;

    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
        return res;
    size = rlength;

    if (size == 4) {
        *num= av_int2flt(get_be32(pb));
    } else if(size==8){
        *num= av_int2dbl(get_be64(pb));
    } else{
        offset_t pos = url_ftell(pb);
        av_log(matroska->ctx, AV_LOG_ERROR,
               "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
               size, pos, pos);
        return AVERROR_INVALIDDATA;
    }

    return 0;
}

/*
 * Read the next element as an ASCII string.
 * 0 is success, < 0 is failure.
 */

static int
ebml_read_ascii (MatroskaDemuxContext *matroska,
                 uint32_t             *id,
                 char                **str)
{
631
    ByteIOContext *pb = matroska->ctx->pb;
632 633 634 635 636 637 638 639 640 641 642 643
    int size, res;
    uint64_t rlength;

    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
        return res;
    size = rlength;

    /* ebml strings are usually not 0-terminated, so we allocate one
     * byte more, read the string and NULL-terminate it ourselves. */
    if (size < 0 || !(*str = av_malloc(size + 1))) {
        av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
644
        return AVERROR(ENOMEM);
645 646 647 648 649
    }
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
        offset_t pos = url_ftell(pb);
        av_log(matroska->ctx, AV_LOG_ERROR,
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
650
        av_free(*str);
651
        return AVERROR(EIO);
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
    }
    (*str)[size] = '\0';

    return 0;
}

/*
 * Read the next element as a UTF-8 string.
 * 0 is success, < 0 is failure.
 */

static int
ebml_read_utf8 (MatroskaDemuxContext *matroska,
                uint32_t             *id,
                char                **str)
{
  return ebml_read_ascii(matroska, id, str);
}

/*
 * 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.
 */

static int
ebml_read_master (MatroskaDemuxContext *matroska,
                  uint32_t             *id)
{
681
    ByteIOContext *pb = matroska->ctx->pb;
682 683 684 685 686 687 688 689 690 691 692 693
    uint64_t length;
    MatroskaLevel *level;
    int res;

    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
        (res = ebml_read_element_length(matroska, &length)) < 0)
        return res;

    /* protect... (Heaven forbids that the '>' is true) */
    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);
694
        return AVERROR(ENOSYS);
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
    }

    /* remember level */
    level = &matroska->levels[matroska->num_levels++];
    level->start = url_ftell(pb);
    level->length = length;

    return 0;
}

/*
 * Read the next element as binary data.
 * 0 is success, < 0 is failure.
 */

static int
ebml_read_binary (MatroskaDemuxContext *matroska,
                  uint32_t             *id,
                  uint8_t             **binary,
                  int                  *size)
{
716
    ByteIOContext *pb = matroska->ctx->pb;
717 718 719 720 721 722 723 724 725 726 727
    uint64_t rlength;
    int res;

    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
        return res;
    *size = rlength;

    if (!(*binary = av_malloc(*size))) {
        av_log(matroska->ctx, AV_LOG_ERROR,
               "Memory allocation error\n");
728
        return AVERROR(ENOMEM);
729 730 731 732 733 734
    }

    if (get_buffer(pb, *binary, *size) != *size) {
        offset_t pos = url_ftell(pb);
        av_log(matroska->ctx, AV_LOG_ERROR,
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
735
        return AVERROR(EIO);
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
    }

    return 0;
}

/*
 * Read signed/unsigned "EBML" numbers.
 * Return: number of bytes processed, < 0 on error.
 * XXX: use ebml_read_num().
 */

static int
matroska_ebmlnum_uint (uint8_t  *data,
                       uint32_t  size,
                       uint64_t *num)
{
    int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
    uint64_t total;

    if (size <= 0)
        return AVERROR_INVALIDDATA;

    total = data[0];
    while (read <= 8 && !(total & len_mask)) {
        read++;
        len_mask >>= 1;
    }
    if (read > 8)
        return AVERROR_INVALIDDATA;

    if ((total &= (len_mask - 1)) == len_mask - 1)
        num_ffs++;
    if (size < read)
        return AVERROR_INVALIDDATA;
    while (n < read) {
        if (data[n] == 0xff)
            num_ffs++;
        total = (total << 8) | data[n];
        n++;
    }

    if (read == num_ffs)
        *num = (uint64_t)-1;
    else
        *num = total;

    return read;
}

/*
 * Same as above, but signed.
 */

static int
matroska_ebmlnum_sint (uint8_t  *data,
                       uint32_t  size,
                       int64_t  *num)
{
    uint64_t unum;
    int res;

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

    /* make signed (weird way) */
    if (unum == (uint64_t)-1)
        *num = INT64_MAX;
    else
        *num = unum - ((1LL << ((7 * res) - 1)) - 1);

    return res;
}


811
static MatroskaTrack *
812 813 814 815 816 817 818
matroska_find_track_by_num (MatroskaDemuxContext *matroska,
                            int                   num)
{
    int i;

    for (i = 0; i < matroska->num_tracks; i++)
        if (matroska->tracks[i]->num == num)
819
            return matroska->tracks[i];
820

821 822
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
    return NULL;
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
}


/*
 * Put one packet in an application-supplied AVPacket struct.
 * Returns 0 on success or -1 on failure.
 */

static int
matroska_deliver_packet (MatroskaDemuxContext *matroska,
                         AVPacket             *pkt)
{
    if (matroska->num_packets > 0) {
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
        av_free(matroska->packets[0]);
        if (matroska->num_packets > 1) {
            memmove(&matroska->packets[0], &matroska->packets[1],
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
            matroska->packets =
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
                           sizeof(AVPacket *));
        } else {
            av_freep(&matroska->packets);
        }
        matroska->num_packets--;
        return 0;
    }

    return -1;
}

/*
 * Put a packet into our internal queue. Will be delivered to the
 * user/application during the next get_packet() call.
 */

static void
matroska_queue_packet (MatroskaDemuxContext *matroska,
                       AVPacket             *pkt)
{
    matroska->packets =
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
                   sizeof(AVPacket *));
    matroska->packets[matroska->num_packets] = pkt;
    matroska->num_packets++;
}

870 871 872 873 874 875 876 877 878 879 880 881 882 883
/*
 * Free all packets in our internal queue.
 */
static void
matroska_clear_queue (MatroskaDemuxContext *matroska)
{
    if (matroska->packets) {
        int n;
        for (n = 0; n < matroska->num_packets; n++) {
            av_free_packet(matroska->packets[n]);
            av_free(matroska->packets[n]);
        }
        av_free(matroska->packets);
        matroska->packets = NULL;
884
        matroska->num_packets = 0;
885 886 887
    }
}

888 889 890 891 892 893 894 895 896 897 898 899 900

/*
 * Autodetecting...
 */

static int
matroska_probe (AVProbeData *p)
{
    uint64_t total = 0;
    int len_mask = 0x80, size = 1, n = 1;
    uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };

    /* ebml header? */
901
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
        return 0;

    /* length of header */
    total = p->buf[4];
    while (size <= 8 && !(total & len_mask)) {
        size++;
        len_mask >>= 1;
    }
    if (size > 8)
      return 0;
    total &= (len_mask - 1);
    while (n < size)
        total = (total << 8) | p->buf[4 + n++];

    /* does the probe data contain the whole header? */
    if (p->buf_size < 4 + size + total)
      return 0;

    /* the header must contain the document type 'matroska'. For now,
     * we don't parse the whole header but simply check for the
     * availability of that array of characters inside the header.
     * Not fully fool-proof, but good enough. */
    for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
        if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
            return AVPROBE_SCORE_MAX;

    return 0;
}

/*
 * From here on, it's all XML-style DTD stuff... Needs no comments.
 */

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
                      void *data, uint32_t expected_id, int once);

static int ebml_parse_elem(MatroskaDemuxContext *matroska,
                           EbmlSyntax *syntax, void *data)
{
    uint32_t id = syntax->id;
    EbmlBin *bin;
    int res;

    data = (char *)data + syntax->data_offset;
    if (syntax->list_elem_size) {
        EbmlList *list = data;
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
        memset(data, 0, syntax->list_elem_size);
        list->nb_elem++;
    }
    bin = data;

    switch (syntax->type) {
    case EBML_UINT:  return ebml_read_uint (matroska, &id, data);
    case EBML_FLOAT: return ebml_read_float(matroska, &id, data);
    case EBML_STR:
    case EBML_UTF8:  av_free(*(char **)data);
                     return ebml_read_ascii(matroska, &id, data);
    case EBML_BIN:   av_free(bin->data);
                     bin->pos = url_ftell(matroska->ctx->pb);
                     return ebml_read_binary(matroska, &id, &bin->data,
                                                            &bin->size);
    case EBML_NEST:  if ((res=ebml_read_master(matroska, &id)) < 0)
                         return res;
                     if (id == MATROSKA_ID_SEGMENT)
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
                     return ebml_parse(matroska, syntax->def.n, data, 0, 0);
    case EBML_PASS:  return ebml_parse(matroska, syntax->def.n, data, 0, 1);
    case EBML_STOP:  *(int *)data = 1;      return 1;
    default:         return ebml_read_skip(matroska);
    }
}

static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
                         uint32_t id, void *data)
{
    int i;
    for (i=0; syntax[i].id; i++)
        if (id == syntax[i].id)
            break;
    if (!syntax[i].id)
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
    return ebml_parse_elem(matroska, &syntax[i], data);
}

static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
                      void *data, uint32_t expected_id, int once)
{
    int i, res = 0;
    uint32_t id = 0;

    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:
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
            break;
        }

    if (expected_id) {
        res = ebml_read_master(matroska, &id);
        if (id != expected_id)
            return AVERROR_INVALIDDATA;
        if (id == MATROSKA_ID_SEGMENT)
            matroska->segment_start = url_ftell(matroska->ctx->pb);
    }

    while (!res) {
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
            res = AVERROR(EIO);
            break;
        } else if (matroska->level_up) {
            matroska->level_up--;
            break;
        }

        res = ebml_parse_id(matroska, syntax, id, data);
        if (once)
            break;


        if (matroska->level_up) {
            matroska->level_up--;
            break;
        }
    }

    return res;
}

static void ebml_free(EbmlSyntax *syntax, void *data)
{
    int i, j;
    for (i=0; syntax[i].id; i++) {
        void *data_off = (char *)data + syntax[i].data_offset;
        switch (syntax[i].type) {
        case EBML_STR:
        case EBML_UTF8:  av_freep(data_off);                      break;
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
        case EBML_NEST:
            if (syntax[i].list_elem_size) {
                EbmlList *list = data_off;
                char *ptr = list->elem;
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
                    ebml_free(syntax[i].def.n, ptr);
                av_free(list->elem);
            } else
                ebml_free(syntax[i].def.n, data_off);
        default:  break;
        }
    }
}

1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
static int
matroska_parse_info (MatroskaDemuxContext *matroska)
{
    int res = 0;
    uint32_t id;

    av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");

    while (res == 0) {
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1072
            res = AVERROR(EIO);
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
            break;
        } else if (matroska->level_up) {
            matroska->level_up--;
            break;
        }

        switch (id) {
            /* cluster timecode */
            case MATROSKA_ID_TIMECODESCALE: {
                uint64_t num;
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                    break;
                matroska->time_scale = num;
                break;
            }

            case MATROSKA_ID_DURATION: {
                double num;
                if ((res = ebml_read_float(matroska, &id, &num)) < 0)
                    break;
                matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
                break;
            }

            case MATROSKA_ID_TITLE: {
                char *text;
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
                    break;
                strncpy(matroska->ctx->title, text,
                        sizeof(matroska->ctx->title)-1);
                av_free(text);
                break;
            }

            default:
                av_log(matroska->ctx, AV_LOG_INFO,
                       "Unknown entry 0x%x in info header\n", id);
                /* fall-through */

1112 1113 1114
            case MATROSKA_ID_WRITINGAPP:
            case MATROSKA_ID_MUXINGAPP:
            case MATROSKA_ID_DATEUTC:
1115
            case MATROSKA_ID_SEGMENTUID:
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
            case EBML_ID_VOID:
                res = ebml_read_skip(matroska);
                break;
        }

        if (matroska->level_up) {
            matroska->level_up--;
            break;
        }
    }

    return res;
}

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
static int
matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
{
    uint8_t* data = *buf;
    int isize = *buf_size;
    uint8_t* pkt_data = NULL;
    int pkt_size = isize;
    int result = 0;
    int olen;

    switch (track->encoding_algo) {
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
        return track->encoding_settings_len;
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
        do {
            olen = pkt_size *= 3;
            pkt_data = av_realloc(pkt_data,
                                  pkt_size+LZO_OUTPUT_PADDING);
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
        if (result)
            goto failed;
        pkt_size -= olen;
        break;
#ifdef CONFIG_ZLIB
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
        z_stream zstream = {0};
        if (inflateInit(&zstream) != Z_OK)
            return -1;
        zstream.next_in = data;
        zstream.avail_in = isize;
        do {
            pkt_size *= 3;
            pkt_data = av_realloc(pkt_data, pkt_size);
            zstream.avail_out = pkt_size - zstream.total_out;
            zstream.next_out = pkt_data + zstream.total_out;
            result = inflate(&zstream, Z_NO_FLUSH);
        } while (result==Z_OK && pkt_size<10000000);
        pkt_size = zstream.total_out;
        inflateEnd(&zstream);
        if (result != Z_STREAM_END)
            goto failed;
        break;
    }
#endif
#ifdef CONFIG_BZLIB
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
        bz_stream bzstream = {0};
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
            return -1;
        bzstream.next_in = data;
        bzstream.avail_in = isize;
        do {
            pkt_size *= 3;
            pkt_data = av_realloc(pkt_data, pkt_size);
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
            result = BZ2_bzDecompress(&bzstream);
        } while (result==BZ_OK && pkt_size<10000000);
        pkt_size = bzstream.total_out_lo32;
        BZ2_bzDecompressEnd(&bzstream);
        if (result != BZ_STREAM_END)
            goto failed;
        break;
    }
#endif
    }

    *buf = pkt_data;
    *buf_size = pkt_size;
    return 0;
 failed:
    av_free(pkt_data);
    return -1;
}

1206 1207 1208 1209 1210 1211 1212
static int
matroska_add_stream (MatroskaDemuxContext *matroska)
{
    int res = 0;
    uint32_t id;
    MatroskaTrack *track;

1213 1214 1215 1216
    /* start with the master */
    if ((res = ebml_read_master(matroska, &id)) < 0)
        return res;

1217 1218
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");

A
Aurelien Jacobs 已提交
1219
    /* Allocate a generic track. */
1220
    track = av_mallocz(MAX_TRACK_SIZE);
1221
    track->time_scale = 1.0;
1222
    strcpy(track->language, "eng");
1223 1224 1225 1226

    /* try reading the trackentry headers */
    while (res == 0) {
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1227
            res = AVERROR(EIO);
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
            break;
        } else if (matroska->level_up > 0) {
            matroska->level_up--;
            break;
        }

        switch (id) {
            /* track number (unique stream ID) */
            case MATROSKA_ID_TRACKNUMBER: {
                uint64_t num;
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                    break;
                track->num = num;
                break;
            }

            /* track UID (unique identifier) */
            case MATROSKA_ID_TRACKUID: {
                uint64_t num;
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                    break;
                track->uid = num;
                break;
            }

            /* track type (video, audio, combined, subtitle, etc.) */
            case MATROSKA_ID_TRACKTYPE: {
                uint64_t num;
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                    break;
                if (track->type && track->type != num) {
                    av_log(matroska->ctx, AV_LOG_INFO,
                           "More than one tracktype in an entry - skip\n");
                    break;
                }
                track->type = num;

                switch (track->type) {
                    case MATROSKA_TRACK_TYPE_VIDEO:
                    case MATROSKA_TRACK_TYPE_AUDIO:
                    case MATROSKA_TRACK_TYPE_SUBTITLE:
                        break;
                    case MATROSKA_TRACK_TYPE_COMPLEX:
                    case MATROSKA_TRACK_TYPE_LOGO:
                    case MATROSKA_TRACK_TYPE_CONTROL:
                    default:
                        av_log(matroska->ctx, AV_LOG_INFO,
                               "Unknown or unsupported track type 0x%x\n",
                               track->type);
C
Carl Eugen Hoyos 已提交
1277
                        track->type = MATROSKA_TRACK_TYPE_NONE;
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
                        break;
                }
                break;
            }

            /* tracktype specific stuff for video */
            case MATROSKA_ID_TRACKVIDEO: {
                MatroskaVideoTrack *videotrack;
                if (!track->type)
                    track->type = MATROSKA_TRACK_TYPE_VIDEO;
                if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
                    av_log(matroska->ctx, AV_LOG_INFO,
                           "video data in non-video track - ignoring\n");
                    res = AVERROR_INVALIDDATA;
                    break;
                } else if ((res = ebml_read_master(matroska, &id)) < 0)
                    break;
                videotrack = (MatroskaVideoTrack *)track;

                while (res == 0) {
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1299
                        res = AVERROR(EIO);
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
                        break;
                    } else if (matroska->level_up > 0) {
                        matroska->level_up--;
                        break;
                    }

                    switch (id) {
                        /* fixme, this should be one-up, but I get it here */
                        case MATROSKA_ID_TRACKDEFAULTDURATION: {
                            uint64_t num;
                            if ((res = ebml_read_uint (matroska, &id,
                                                       &num)) < 0)
                                break;
1313
                            track->default_duration = num;
1314 1315 1316 1317 1318 1319 1320 1321 1322
                            break;
                        }

                        /* video framerate */
                        case MATROSKA_ID_VIDEOFRAMERATE: {
                            double num;
                            if ((res = ebml_read_float(matroska, &id,
                                                       &num)) < 0)
                                break;
1323
                            if (!track->default_duration)
A
Aurelien Jacobs 已提交
1324
                                track->default_duration = 1000000000/num;
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
                            break;
                        }

                        /* width of the size to display the video at */
                        case MATROSKA_ID_VIDEODISPLAYWIDTH: {
                            uint64_t num;
                            if ((res = ebml_read_uint(matroska, &id,
                                                      &num)) < 0)
                                break;
                            videotrack->display_width = num;
                            break;
                        }

                        /* height of the size to display the video at */
                        case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
                            uint64_t num;
                            if ((res = ebml_read_uint(matroska, &id,
                                                      &num)) < 0)
                                break;
                            videotrack->display_height = num;
                            break;
                        }

                        /* width of the video in the file */
                        case MATROSKA_ID_VIDEOPIXELWIDTH: {
                            uint64_t num;
                            if ((res = ebml_read_uint(matroska, &id,
                                                      &num)) < 0)
                                break;
                            videotrack->pixel_width = num;
                            break;
                        }

                        /* height of the video in the file */
                        case MATROSKA_ID_VIDEOPIXELHEIGHT: {
                            uint64_t num;
                            if ((res = ebml_read_uint(matroska, &id,
                                                      &num)) < 0)
                                break;
                            videotrack->pixel_height = num;
                            break;
                        }

                        /* whether the video is interlaced */
                        case MATROSKA_ID_VIDEOFLAGINTERLACED: {
                            uint64_t num;
                            if ((res = ebml_read_uint(matroska, &id,
                                                      &num)) < 0)
                                break;
                            break;
                        }

D
Diego Biurrun 已提交
1377
                        /* colorspace (only matters for raw video)
1378
                         * fourcc */
D
Diego Biurrun 已提交
1379
                        case MATROSKA_ID_VIDEOCOLORSPACE: {
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
                            uint64_t num;
                            if ((res = ebml_read_uint(matroska, &id,
                                                      &num)) < 0)
                                break;
                            videotrack->fourcc = num;
                            break;
                        }

                        default:
                            av_log(matroska->ctx, AV_LOG_INFO,
                                   "Unknown video track header entry "
                                   "0x%x - ignoring\n", id);
                            /* pass-through */

1394 1395
                        case MATROSKA_ID_VIDEOSTEREOMODE:
                        case MATROSKA_ID_VIDEOASPECTRATIO:
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
                        case EBML_ID_VOID:
                            res = ebml_read_skip(matroska);
                            break;
                    }

                    if (matroska->level_up) {
                        matroska->level_up--;
                        break;
                    }
                }
                break;
            }

            /* tracktype specific stuff for audio */
            case MATROSKA_ID_TRACKAUDIO: {
                MatroskaAudioTrack *audiotrack;
                if (!track->type)
                    track->type = MATROSKA_TRACK_TYPE_AUDIO;
                if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
                    av_log(matroska->ctx, AV_LOG_INFO,
                           "audio data in non-audio track - ignoring\n");
                    res = AVERROR_INVALIDDATA;
                    break;
                } else if ((res = ebml_read_master(matroska, &id)) < 0)
                    break;
                audiotrack = (MatroskaAudioTrack *)track;
                audiotrack->channels = 1;
                audiotrack->samplerate = 8000;

                while (res == 0) {
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1427
                        res = AVERROR(EIO);
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
                        break;
                    } else if (matroska->level_up > 0) {
                        matroska->level_up--;
                        break;
                    }

                    switch (id) {
                        /* samplerate */
                        case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
                            double num;
                            if ((res = ebml_read_float(matroska, &id,
                                                       &num)) < 0)
                                break;
                            audiotrack->internal_samplerate =
                            audiotrack->samplerate = num;
                            break;
                        }

                        case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
                            double num;
                            if ((res = ebml_read_float(matroska, &id,
                                                       &num)) < 0)
                                break;
                            audiotrack->samplerate = num;
                            break;
                        }

                            /* bitdepth */
                        case MATROSKA_ID_AUDIOBITDEPTH: {
                            uint64_t num;
                            if ((res = ebml_read_uint(matroska, &id,
                                                      &num)) < 0)
                                break;
                            audiotrack->bitdepth = num;
                            break;
                        }

                            /* channels */
                        case MATROSKA_ID_AUDIOCHANNELS: {
                            uint64_t num;
                            if ((res = ebml_read_uint(matroska, &id,
                                                      &num)) < 0)
                                break;
                            audiotrack->channels = num;
                            break;
                        }

                        default:
                            av_log(matroska->ctx, AV_LOG_INFO,
                                   "Unknown audio track header entry "
                                   "0x%x - ignoring\n", id);
                            /* pass-through */

                        case EBML_ID_VOID:
                            res = ebml_read_skip(matroska);
                            break;
                    }

                    if (matroska->level_up) {
                        matroska->level_up--;
                        break;
                    }
                }
                break;
            }

                /* codec identifier */
            case MATROSKA_ID_CODECID: {
                char *text;
                if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
                    break;
                track->codec_id = text;
                break;
            }

                /* codec private data */
            case MATROSKA_ID_CODECPRIVATE: {
                uint8_t *data;
                int size;
                if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
                    break;
                track->codec_priv = data;
                track->codec_priv_size = size;
                break;
            }

                /* name of this track */
            case MATROSKA_ID_TRACKNAME: {
                char *text;
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
                    break;
                track->name = text;
                break;
            }

                /* language (matters for audio/subtitles, mostly) */
            case MATROSKA_ID_TRACKLANGUAGE: {
1525
                char *text, *end;
1526 1527
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
                    break;
1528 1529 1530 1531 1532
                if ((end = strchr(text, '-')))
                    *end = '\0';
                if (strlen(text) == 3)
                    strcpy(track->language, text);
                av_free(text);
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
                break;
            }

                /* whether this is actually used */
            case MATROSKA_ID_TRACKFLAGENABLED: {
                uint64_t num;
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                    break;
                break;
            }

                /* whether it's the default for this track type */
            case MATROSKA_ID_TRACKFLAGDEFAULT: {
                uint64_t num;
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                    break;
1549
                track->flag_default = num;
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
                break;
            }

                /* lacing (like MPEG, where blocks don't end/start on frame
                 * boundaries) */
            case MATROSKA_ID_TRACKFLAGLACING: {
                uint64_t num;
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                    break;
                break;
            }

                /* default length (in time) of one data block in this track */
            case MATROSKA_ID_TRACKDEFAULTDURATION: {
                uint64_t num;
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                    break;
1567
                track->default_duration = num;
1568 1569 1570
                break;
            }

1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
            case MATROSKA_ID_TRACKCONTENTENCODINGS: {
                if ((res = ebml_read_master(matroska, &id)) < 0)
                    break;

                while (res == 0) {
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
                        res = AVERROR(EIO);
                        break;
                    } else if (matroska->level_up > 0) {
                        matroska->level_up--;
                        break;
                    }

                    switch (id) {
                        case MATROSKA_ID_TRACKCONTENTENCODING: {
                            int encoding_scope = 1;
                            if ((res = ebml_read_master(matroska, &id)) < 0)
                                break;

                            while (res == 0) {
                                if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
                                    res = AVERROR(EIO);
                                    break;
                                } else if (matroska->level_up > 0) {
                                    matroska->level_up--;
                                    break;
                                }

                                switch (id) {
                                    case MATROSKA_ID_ENCODINGSCOPE: {
                                        uint64_t num;
                                        if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                                            break;
                                        encoding_scope = num;
                                        break;
                                    }

                                    case MATROSKA_ID_ENCODINGTYPE: {
                                        uint64_t num;
                                        if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                                            break;
                                        if (num)
                                            av_log(matroska->ctx, AV_LOG_ERROR,
                                                   "Unsupported encoding type");
                                        break;
                                    }

                                    case MATROSKA_ID_ENCODINGCOMPRESSION: {
                                        if ((res = ebml_read_master(matroska, &id)) < 0)
                                            break;

                                        while (res == 0) {
                                            if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
                                                res = AVERROR(EIO);
                                                break;
                                            } else if (matroska->level_up > 0) {
                                                matroska->level_up--;
                                                break;
                                            }

                                            switch (id) {
                                                case MATROSKA_ID_ENCODINGCOMPALGO: {
                                                    uint64_t num;
                                                    if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                                                        break;
1636
                                                    if (num != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1637 1638
#ifdef CONFIG_ZLIB
                                                        num != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1639 1640 1641
#endif
#ifdef CONFIG_BZLIB
                                                        num != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1642
#endif
1643
                                                        num != MATROSKA_TRACK_ENCODING_COMP_LZO)
1644
                                                        av_log(matroska->ctx, AV_LOG_ERROR,
1645
                                                               "Unsupported compression algo\n");
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
                                                    track->encoding_algo = num;
                                                    break;
                                                }

                                                case MATROSKA_ID_ENCODINGCOMPSETTINGS: {
                                                    uint8_t *data;
                                                    int size;
                                                    if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
                                                        break;
                                                    track->encoding_settings = data;
                                                    track->encoding_settings_len = size;
                                                    break;
                                                }

                                                default:
                                                    av_log(matroska->ctx, AV_LOG_INFO,
                                                           "Unknown compression header entry "
                                                           "0x%x - ignoring\n", id);
                                                    /* pass-through */

                                                case EBML_ID_VOID:
                                                    res = ebml_read_skip(matroska);
                                                    break;
                                            }

                                            if (matroska->level_up) {
                                                matroska->level_up--;
                                                break;
                                            }
                                        }
                                        break;
                                    }

                                    default:
                                        av_log(matroska->ctx, AV_LOG_INFO,
                                               "Unknown content encoding header entry "
                                               "0x%x - ignoring\n", id);
                                        /* pass-through */

                                    case EBML_ID_VOID:
                                        res = ebml_read_skip(matroska);
                                        break;
                                }

                                if (matroska->level_up) {
                                    matroska->level_up--;
                                    break;
                                }
                            }

                            track->encoding_scope = encoding_scope;
                            break;
                        }

                        default:
                            av_log(matroska->ctx, AV_LOG_INFO,
                                   "Unknown content encodings header entry "
                                   "0x%x - ignoring\n", id);
                            /* pass-through */

                        case EBML_ID_VOID:
                            res = ebml_read_skip(matroska);
                            break;
                    }

                    if (matroska->level_up) {
                        matroska->level_up--;
                        break;
                    }
                }
                break;
            }

1719 1720 1721 1722 1723 1724 1725 1726
            case MATROSKA_ID_TRACKTIMECODESCALE: {
                double num;
                if ((res = ebml_read_float(matroska, &id, &num)) < 0)
                    break;
                track->time_scale = num;
                break;
            }

1727 1728 1729 1730 1731 1732 1733
            default:
                av_log(matroska->ctx, AV_LOG_INFO,
                       "Unknown track header entry 0x%x - ignoring\n", id);
                /* pass-through */

            case EBML_ID_VOID:
            /* we ignore these because they're nothing useful. */
1734
            case MATROSKA_ID_TRACKFLAGFORCED:
1735
            case MATROSKA_ID_CODECNAME:
1736
            case MATROSKA_ID_CODECDECODEALL:
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
            case MATROSKA_ID_CODECINFOURL:
            case MATROSKA_ID_CODECDOWNLOADURL:
            case MATROSKA_ID_TRACKMINCACHE:
            case MATROSKA_ID_TRACKMAXCACHE:
                res = ebml_read_skip(matroska);
                break;
        }

        if (matroska->level_up) {
            matroska->level_up--;
            break;
        }
    }

1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
    if (track->codec_priv_size && track->encoding_scope & 2) {
        uint8_t *orig_priv = track->codec_priv;
        int offset = matroska_decode_buffer(&track->codec_priv,
                                            &track->codec_priv_size, track);
        if (offset > 0) {
            track->codec_priv = av_malloc(track->codec_priv_size + offset);
            memcpy(track->codec_priv, track->encoding_settings, offset);
            memcpy(track->codec_priv+offset, orig_priv, track->codec_priv_size);
            track->codec_priv_size += offset;
            av_free(orig_priv);
        } else if (!offset) {
            av_free(orig_priv);
        } else
            av_log(matroska->ctx, AV_LOG_ERROR,
                   "Failed to decode codec private data\n");
    }

1768 1769 1770 1771 1772
    if (track->type && matroska->num_tracks < ARRAY_SIZE(matroska->tracks)) {
        matroska->tracks[matroska->num_tracks++] = track;
    } else {
        av_free(track);
    }
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
    return res;
}

static int
matroska_parse_tracks (MatroskaDemuxContext *matroska)
{
    int res = 0;
    uint32_t id;

    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");

    while (res == 0) {
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1786
            res = AVERROR(EIO);
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
            break;
        } else if (matroska->level_up) {
            matroska->level_up--;
            break;
        }

        switch (id) {
            /* one track within the "all-tracks" header */
            case MATROSKA_ID_TRACKENTRY:
                res = matroska_add_stream(matroska);
                break;

            default:
                av_log(matroska->ctx, AV_LOG_INFO,
                       "Unknown entry 0x%x in track header\n", id);
                /* fall-through */

            case EBML_ID_VOID:
                res = ebml_read_skip(matroska);
                break;
        }

        if (matroska->level_up) {
            matroska->level_up--;
            break;
        }
    }

    return res;
}

static int
matroska_parse_index (MatroskaDemuxContext *matroska)
{
1821
    return ebml_parse(matroska, matroska_index, matroska, MATROSKA_ID_CUES, 0);
1822 1823 1824 1825 1826
}

static int
matroska_parse_metadata (MatroskaDemuxContext *matroska)
{
1827
    return ebml_parse(matroska, matroska_tags, matroska, MATROSKA_ID_TAGS, 0);
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
}

static int
matroska_parse_seekhead (MatroskaDemuxContext *matroska)
{
    int res = 0;
    uint32_t id;

    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");

    while (res == 0) {
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1840
            res = AVERROR(EIO);
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
            break;
        } else if (matroska->level_up) {
            matroska->level_up--;
            break;
        }

        switch (id) {
            case MATROSKA_ID_SEEKENTRY: {
                uint32_t seek_id = 0, peek_id_cache = 0;
                uint64_t seek_pos = (uint64_t) -1, t;
1851
                int dummy_level = 0;
1852 1853 1854 1855 1856 1857

                if ((res = ebml_read_master(matroska, &id)) < 0)
                    break;

                while (res == 0) {
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1858
                        res = AVERROR(EIO);
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
                        break;
                    } else if (matroska->level_up) {
                        matroska->level_up--;
                        break;
                    }

                    switch (id) {
                        case MATROSKA_ID_SEEKID:
                            res = ebml_read_uint(matroska, &id, &t);
                            seek_id = t;
                            break;

                        case MATROSKA_ID_SEEKPOSITION:
                            res = ebml_read_uint(matroska, &id, &seek_pos);
                            break;

                        default:
                            av_log(matroska->ctx, AV_LOG_INFO,
                                   "Unknown seekhead ID 0x%x\n", id);
                            /* fall-through */

                        case EBML_ID_VOID:
                            res = ebml_read_skip(matroska);
                            break;
                    }

                    if (matroska->level_up) {
                        matroska->level_up--;
                        break;
                    }
                }

                if (!seek_id || seek_pos == (uint64_t) -1) {
                    av_log(matroska->ctx, AV_LOG_INFO,
                           "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
                           seek_id, seek_pos);
                    break;
                }

                switch (seek_id) {
                    case MATROSKA_ID_CUES:
                    case MATROSKA_ID_TAGS: {
                        uint32_t level_up = matroska->level_up;
                        offset_t before_pos;
                        uint64_t length;
                        MatroskaLevel level;

                        /* remember the peeked ID and the current position */
                        peek_id_cache = matroska->peek_id;
1908
                        before_pos = url_ftell(matroska->ctx->pb);
1909 1910 1911 1912

                        /* seek */
                        if ((res = ebml_read_seek(matroska, seek_pos +
                                               matroska->segment_start)) < 0)
1913
                            goto finish;
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927

                        /* we don't want to lose our seekhead level, so we add
                         * a dummy. This is a crude hack. */
                        if (matroska->num_levels == EBML_MAX_DEPTH) {
                            av_log(matroska->ctx, AV_LOG_INFO,
                                   "Max EBML element depth (%d) reached, "
                                   "cannot parse further.\n", EBML_MAX_DEPTH);
                            return AVERROR_UNKNOWN;
                        }

                        level.start = 0;
                        level.length = (uint64_t)-1;
                        matroska->levels[matroska->num_levels] = level;
                        matroska->num_levels++;
1928
                        dummy_level = 1;
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946

                        /* check ID */
                        if (!(id = ebml_peek_id (matroska,
                                                 &matroska->level_up)))
                            goto finish;
                        if (id != seek_id) {
                            av_log(matroska->ctx, AV_LOG_INFO,
                                   "We looked for ID=0x%x but got "
                                   "ID=0x%x (pos=%"PRIu64")",
                                   seek_id, id, seek_pos +
                                   matroska->segment_start);
                            goto finish;
                        }

                        /* read master + parse */
                        switch (id) {
                            case MATROSKA_ID_CUES:
                                if (!(res = matroska_parse_index(matroska)) ||
1947
                                    url_feof(matroska->ctx->pb)) {
1948 1949 1950 1951 1952 1953
                                    matroska->index_parsed = 1;
                                    res = 0;
                                }
                                break;
                            case MATROSKA_ID_TAGS:
                                if (!(res = matroska_parse_metadata(matroska)) ||
1954
                                   url_feof(matroska->ctx->pb)) {
1955 1956 1957 1958 1959 1960 1961 1962
                                    matroska->metadata_parsed = 1;
                                    res = 0;
                                }
                                break;
                        }

                    finish:
                        /* remove dummy level */
1963
                        if (dummy_level)
A
Aurelien Jacobs 已提交
1964 1965 1966 1967 1968 1969 1970
                            while (matroska->num_levels) {
                                matroska->num_levels--;
                                length =
                                  matroska->levels[matroska->num_levels].length;
                                if (length == (uint64_t)-1)
                                    break;
                            }
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008

                        /* seek back */
                        if ((res = ebml_read_seek(matroska, before_pos)) < 0)
                            return res;
                        matroska->peek_id = peek_id_cache;
                        matroska->level_up = level_up;
                        break;
                    }

                    default:
                        av_log(matroska->ctx, AV_LOG_INFO,
                               "Ignoring seekhead entry for ID=0x%x\n",
                               seek_id);
                        break;
                }

                break;
            }

            default:
                av_log(matroska->ctx, AV_LOG_INFO,
                       "Unknown seekhead ID 0x%x\n", id);
                /* fall-through */

            case EBML_ID_VOID:
                res = ebml_read_skip(matroska);
                break;
        }

        if (matroska->level_up) {
            matroska->level_up--;
            break;
        }
    }

    return res;
}

2009 2010 2011 2012
static int
matroska_parse_attachments(AVFormatContext *s)
{
    MatroskaDemuxContext *matroska = s->priv_data;
2013 2014 2015
    EbmlList *attachements_list = &matroska->attachments;
    MatroskaAttachement *attachements;
    int i, j, res;
2016

2017
    res = ebml_parse(matroska, matroska_attachments, matroska, MATROSKA_ID_ATTACHMENTS, 0);
2018

2019 2020 2021 2022 2023 2024 2025
    attachements = attachements_list->elem;
    for (j=0; j<attachements_list->nb_elem; j++) {
        if (!(attachements[j].filename && attachements[j].mime &&
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
        } else {
            AVStream *st = av_new_stream(s, matroska->num_streams++);
2026
            if (st == NULL)
2027 2028
                break;
            st->filename          = av_strdup(attachements[j].filename);
2029 2030
            st->codec->codec_id = CODEC_ID_NONE;
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
2031
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
2032
            if(st->codec->extradata == NULL)
2033 2034 2035
                break;
            st->codec->extradata_size = attachements[j].bin.size;
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
2036 2037

            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
2038
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
                             strlen(ff_mkv_mime_tags[i].str))) {
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
                    break;
                }
            }
        }
    }

    return res;
}

A
Anton Khirnov 已提交
2050 2051 2052 2053
static int
matroska_parse_chapters(AVFormatContext *s)
{
    MatroskaDemuxContext *matroska = s->priv_data;
2054 2055 2056
    EbmlList *chapters_list = &matroska->chapters;
    MatroskaChapter *chapters;
    int i, res;
A
Anton Khirnov 已提交
2057

2058
    res = ebml_parse(matroska, matroska_chapters, matroska, MATROSKA_ID_CHAPTERS, 0);
A
Anton Khirnov 已提交
2059

2060 2061 2062 2063 2064 2065
    chapters = chapters_list->elem;
    for (i=0; i<chapters_list->nb_elem; i++)
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
                           chapters[i].start, chapters[i].end,
                           chapters[i].title);
A
Anton Khirnov 已提交
2066 2067 2068 2069

    return res;
}

2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
static int
matroska_aac_profile (char *codec_id)
{
    static const char *aac_profiles[] = {
        "MAIN", "LC", "SSR"
    };
    int profile;

    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
        if (strstr(codec_id, aac_profiles[profile]))
            break;
    return profile + 1;
}

static int
matroska_aac_sri (int samplerate)
{
    int sri;

2089 2090
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
2091 2092 2093 2094 2095 2096 2097 2098 2099
            break;
    return sri;
}

static int
matroska_read_header (AVFormatContext    *s,
                      AVFormatParameters *ap)
{
    MatroskaDemuxContext *matroska = s->priv_data;
2100 2101 2102
    EbmlList *index_list;
    MatroskaIndex *index;
    int i, j, last_level, res = 0;
2103
    Ebml ebml = { 0 };
2104 2105 2106 2107 2108
    uint32_t id;

    matroska->ctx = s;

    /* First read the EBML header. */
2109 2110 2111 2112
    if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
        || ebml.doctype_version > 2) {
2113
        av_log(matroska->ctx, AV_LOG_ERROR,
2114 2115 2116
               "EBML header using unsupported features\n"
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
               ebml.version, ebml.doctype, ebml.doctype_version);
2117 2118
        return AVERROR_NOFMT;
    }
2119
    ebml_free(ebml_syntax, &ebml);
2120 2121 2122 2123

    /* The next thing is a segment. */
    while (1) {
        if (!(id = ebml_peek_id(matroska, &last_level)))
2124
            return AVERROR(EIO);
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
        if (id == MATROSKA_ID_SEGMENT)
            break;

        /* oi! */
        av_log(matroska->ctx, AV_LOG_INFO,
               "Expected a Segment ID (0x%x), but received 0x%x!\n",
               MATROSKA_ID_SEGMENT, id);
        if ((res = ebml_read_skip(matroska)) < 0)
            return res;
    }

    /* We now have a Matroska segment.
     * Seeks are from the beginning of the segment,
     * after the segment ID/length. */
    if ((res = ebml_read_master(matroska, &id)) < 0)
        return res;
2141
    matroska->segment_start = url_ftell(s->pb);
2142 2143 2144 2145 2146

    matroska->time_scale = 1000000;
    /* we've found our segment, start reading the different contents in here */
    while (res == 0) {
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2147
            res = AVERROR(EIO);
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
            break;
        } else if (matroska->level_up) {
            matroska->level_up--;
            break;
        }

        switch (id) {
            /* stream info */
            case MATROSKA_ID_INFO: {
                if ((res = ebml_read_master(matroska, &id)) < 0)
                    break;
                res = matroska_parse_info(matroska);
                break;
            }

            /* track info headers */
            case MATROSKA_ID_TRACKS: {
                if ((res = ebml_read_master(matroska, &id)) < 0)
                    break;
                res = matroska_parse_tracks(matroska);
                break;
            }

            /* stream index */
            case MATROSKA_ID_CUES: {
                if (!matroska->index_parsed) {
                    res = matroska_parse_index(matroska);
                } else
                    res = ebml_read_skip(matroska);
                break;
            }

            /* metadata */
            case MATROSKA_ID_TAGS: {
                if (!matroska->metadata_parsed) {
                    res = matroska_parse_metadata(matroska);
                } else
                    res = ebml_read_skip(matroska);
                break;
            }

            /* file index (if seekable, seek to Cues/Tags to parse it) */
            case MATROSKA_ID_SEEKHEAD: {
                if ((res = ebml_read_master(matroska, &id)) < 0)
                    break;
                res = matroska_parse_seekhead(matroska);
                break;
            }

2197 2198 2199 2200 2201
            case MATROSKA_ID_ATTACHMENTS: {
                res = matroska_parse_attachments(s);
                break;
            }

2202 2203 2204 2205 2206 2207 2208
            case MATROSKA_ID_CLUSTER: {
                /* Do not read the master - this will be done in the next
                 * call to matroska_read_packet. */
                res = 1;
                break;
            }

A
Anton Khirnov 已提交
2209 2210 2211 2212 2213
            case MATROSKA_ID_CHAPTERS: {
                res = matroska_parse_chapters(s);
                break;
            }

2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
            default:
                av_log(matroska->ctx, AV_LOG_INFO,
                       "Unknown matroska file header ID 0x%x\n", id);
            /* fall-through */

            case EBML_ID_VOID:
                res = ebml_read_skip(matroska);
                break;
        }

        if (matroska->level_up) {
            matroska->level_up--;
            break;
        }
    }

    /* Have we found a cluster? */
    if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
        int i, j;
        MatroskaTrack *track;
        AVStream *st;

        for (i = 0; i < matroska->num_tracks; i++) {
            enum CodecID codec_id = CODEC_ID_NONE;
            uint8_t *extradata = NULL;
            int extradata_size = 0;
            int extradata_offset = 0;
            track = matroska->tracks[i];

2243 2244
            /* Apply some sanity checks. */
            if (track->codec_id == NULL)
2245 2246
                continue;

2247
            for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
2248 2249 2250 2251 2252 2253 2254
                if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
                            strlen(ff_mkv_codec_tags[j].str))){
                    codec_id= ff_mkv_codec_tags[j].id;
                    break;
                }
            }

2255 2256 2257 2258
            st = track->stream = av_new_stream(s, matroska->num_streams++);
            if (st == NULL)
                return AVERROR(ENOMEM);

2259 2260 2261 2262 2263 2264 2265
            /* Set the FourCC from the CodecID. */
            /* This is the MS compatibility mode which stores a
             * BITMAPINFOHEADER in the CodecPrivate. */
            if (!strcmp(track->codec_id,
                        MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
                (track->codec_priv_size >= 40) &&
                (track->codec_priv != NULL)) {
2266
                MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2267 2268

                /* Offset of biCompression. Stored in LE. */
2269 2270
                vtrack->fourcc = AV_RL32(track->codec_priv + 16);
                codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282

            }

            /* This is the MS compatibility mode which stores a
             * WAVEFORMATEX in the CodecPrivate. */
            else if (!strcmp(track->codec_id,
                             MATROSKA_CODEC_ID_AUDIO_ACM) &&
                (track->codec_priv_size >= 18) &&
                (track->codec_priv != NULL)) {
                uint16_t tag;

                /* Offset of wFormatTag. Stored in LE. */
2283
                tag = AV_RL16(track->codec_priv);
2284 2285 2286 2287
                codec_id = codec_get_id(codec_wav_tags, tag);

            }

2288 2289 2290 2291 2292 2293 2294 2295 2296
            if (!strcmp(track->codec_id, "V_QUICKTIME") &&
                (track->codec_priv_size >= 86) &&
                (track->codec_priv != NULL)) {
                MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;

                vtrack->fourcc = AV_RL32(track->codec_priv);
                codec_id = codec_get_id(codec_movvideo_tags, vtrack->fourcc);
            }

2297 2298 2299 2300 2301 2302
            else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
                int profile = matroska_aac_profile(track->codec_id);
                int sri = matroska_aac_sri(audiotrack->internal_samplerate);
                extradata = av_malloc(5);
                if (extradata == NULL)
2303
                    return AVERROR(ENOMEM);
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
                extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
                extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
                if (strstr(track->codec_id, "SBR")) {
                    sri = matroska_aac_sri(audiotrack->samplerate);
                    extradata[2] = 0x56;
                    extradata[3] = 0xE5;
                    extradata[4] = 0x80 | (sri<<3);
                    extradata_size = 5;
                } else {
                    extradata_size = 2;
                }
            }

            else if (codec_id == CODEC_ID_TTA) {
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
                ByteIOContext b;
                extradata_size = 30;
                extradata = av_mallocz(extradata_size);
                if (extradata == NULL)
2323
                    return AVERROR(ENOMEM);
2324 2325
                init_put_byte(&b, extradata, extradata_size, 1,
                              NULL, NULL, NULL, NULL);
2326
                put_buffer(&b, "TTA1", 4);
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339
                put_le16(&b, 1);
                put_le16(&b, audiotrack->channels);
                put_le16(&b, audiotrack->bitdepth);
                put_le32(&b, audiotrack->samplerate);
                put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
            }

            else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
                     codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
                extradata_offset = 26;
                track->codec_priv_size -= extradata_offset;
            }

2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
            else if (codec_id == CODEC_ID_RA_144) {
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
                audiotrack->samplerate = 8000;
                audiotrack->channels = 1;
            }

            else if (codec_id == CODEC_ID_RA_288 ||
                     codec_id == CODEC_ID_COOK ||
                     codec_id == CODEC_ID_ATRAC3) {
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
                ByteIOContext b;

                init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
                              NULL, NULL, NULL, NULL);
                url_fskip(&b, 24);
                audiotrack->coded_framesize = get_be32(&b);
                url_fskip(&b, 12);
                audiotrack->sub_packet_h    = get_be16(&b);
                audiotrack->frame_size      = get_be16(&b);
                audiotrack->sub_packet_size = get_be16(&b);
                audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
                if (codec_id == CODEC_ID_RA_288) {
                    audiotrack->block_align = audiotrack->coded_framesize;
                    track->codec_priv_size = 0;
                } else {
                    audiotrack->block_align = audiotrack->sub_packet_size;
                    extradata_offset = 78;
                    track->codec_priv_size -= extradata_offset;
                }
            }

2371 2372 2373 2374 2375 2376
            if (codec_id == CODEC_ID_NONE) {
                av_log(matroska->ctx, AV_LOG_INFO,
                       "Unknown/unsupported CodecID %s.\n",
                       track->codec_id);
            }

2377
            av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2378 2379 2380

            st->codec->codec_id = codec_id;
            st->start_time = 0;
2381
            if (strcmp(track->language, "und"))
2382
                av_strlcpy(st->language, track->language, 4);
2383

2384
            if (track->flag_default)
2385 2386
                st->disposition |= AV_DISPOSITION_DEFAULT;

2387 2388
            if (track->default_duration)
                av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2389
                          track->default_duration, 1000000000, 30000);
2390 2391 2392 2393 2394 2395 2396

            if(extradata){
                st->codec->extradata = extradata;
                st->codec->extradata_size = extradata_size;
            } else if(track->codec_priv && track->codec_priv_size > 0){
                st->codec->extradata = av_malloc(track->codec_priv_size);
                if(st->codec->extradata == NULL)
2397
                    return AVERROR(ENOMEM);
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
                st->codec->extradata_size = track->codec_priv_size;
                memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
                       track->codec_priv_size);
            }

            if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
                MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;

                st->codec->codec_type = CODEC_TYPE_VIDEO;
                st->codec->codec_tag = videotrack->fourcc;
                st->codec->width = videotrack->pixel_width;
                st->codec->height = videotrack->pixel_height;
                if (videotrack->display_width == 0)
                    videotrack->display_width= videotrack->pixel_width;
                if (videotrack->display_height == 0)
                    videotrack->display_height= videotrack->pixel_height;
                av_reduce(&st->codec->sample_aspect_ratio.num,
                          &st->codec->sample_aspect_ratio.den,
                          st->codec->height * videotrack->display_width,
                          st->codec-> width * videotrack->display_height,
                          255);
                st->need_parsing = AVSTREAM_PARSE_HEADERS;
            } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;

                st->codec->codec_type = CODEC_TYPE_AUDIO;
                st->codec->sample_rate = audiotrack->samplerate;
                st->codec->channels = audiotrack->channels;
2426
                st->codec->block_align = audiotrack->block_align;
2427 2428 2429 2430 2431 2432 2433 2434 2435
            } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
                st->codec->codec_type = CODEC_TYPE_SUBTITLE;
            }

            /* What do we do with private data? E.g. for Vorbis. */
        }
        res = 0;
    }

2436 2437 2438 2439 2440 2441
    index_list = &matroska->index;
    index = index_list->elem;
    for (i=0; i<index_list->nb_elem; i++) {
        EbmlList *pos_list = &index[i].pos;
        MatroskaIndexPos *pos = pos_list->elem;
        for (j=0; j<pos_list->nb_elem; j++) {
2442
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
2443
                                                              pos[j].track);
2444 2445
            if (track && track->stream)
                av_add_index_entry(track->stream,
2446 2447
                                   pos[j].pos + matroska->segment_start,
                                   index[i].time*matroska->time_scale/AV_TIME_BASE,
2448
                                   0, 0, AVINDEX_KEYFRAME);
2449 2450 2451 2452 2453 2454 2455 2456 2457
        }
    }

    return res;
}

static int
matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
2458
                     int is_keyframe)
2459
{
2460
    MatroskaTrack *track;
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
    int res = 0;
    AVStream *st;
    AVPacket *pkt;
    uint8_t *origdata = data;
    int16_t block_time;
    uint32_t *lace_size = NULL;
    int n, flags, laces = 0;
    uint64_t num;

    /* first byte(s): tracknum */
    if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
        av_free(origdata);
        return res;
    }
    data += n;
    size -= n;

    /* fetch track from num */
    track = matroska_find_track_by_num(matroska, num);
2481
    if (size <= 3 || !track || !track->stream) {
2482
        av_log(matroska->ctx, AV_LOG_INFO,
2483
               "Invalid stream %"PRIu64" or size %u\n", num, size);
2484 2485 2486
        av_free(origdata);
        return res;
    }
2487
    st = track->stream;
2488 2489 2490 2491 2492
    if (st->discard >= AVDISCARD_ALL) {
        av_free(origdata);
        return res;
    }
    if (duration == AV_NOPTS_VALUE)
2493
        duration = track->default_duration / matroska->time_scale;
2494 2495

    /* block_time (relative to cluster time) */
2496
    block_time = AV_RB16(data);
2497
    data += 2;
A
Aurelien Jacobs 已提交
2498 2499
    flags = *data++;
    size -= 3;
2500
    if (is_keyframe == -1)
2501
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
2502 2503

    if (matroska->skip_to_keyframe) {
2504 2505
        if (!is_keyframe || st != matroska->skip_to_stream) {
            av_free(origdata);
2506
            return res;
2507
        }
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
        matroska->skip_to_keyframe = 0;
    }

    switch ((flags & 0x06) >> 1) {
        case 0x0: /* no lacing */
            laces = 1;
            lace_size = av_mallocz(sizeof(int));
            lace_size[0] = size;
            break;

        case 0x1: /* xiph lacing */
        case 0x2: /* fixed-size lacing */
        case 0x3: /* EBML lacing */
2521
            assert(size>0); // size <=3 is checked before size-=3 above
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589
            laces = (*data) + 1;
            data += 1;
            size -= 1;
            lace_size = av_mallocz(laces * sizeof(int));

            switch ((flags & 0x06) >> 1) {
                case 0x1: /* xiph lacing */ {
                    uint8_t temp;
                    uint32_t total = 0;
                    for (n = 0; res == 0 && n < laces - 1; n++) {
                        while (1) {
                            if (size == 0) {
                                res = -1;
                                break;
                            }
                            temp = *data;
                            lace_size[n] += temp;
                            data += 1;
                            size -= 1;
                            if (temp != 0xff)
                                break;
                        }
                        total += lace_size[n];
                    }
                    lace_size[n] = size - total;
                    break;
                }

                case 0x2: /* fixed-size lacing */
                    for (n = 0; n < laces; n++)
                        lace_size[n] = size / laces;
                    break;

                case 0x3: /* EBML lacing */ {
                    uint32_t total;
                    n = matroska_ebmlnum_uint(data, size, &num);
                    if (n < 0) {
                        av_log(matroska->ctx, AV_LOG_INFO,
                               "EBML block data error\n");
                        break;
                    }
                    data += n;
                    size -= n;
                    total = lace_size[0] = num;
                    for (n = 1; res == 0 && n < laces - 1; n++) {
                        int64_t snum;
                        int r;
                        r = matroska_ebmlnum_sint (data, size, &snum);
                        if (r < 0) {
                            av_log(matroska->ctx, AV_LOG_INFO,
                                   "EBML block data error\n");
                            break;
                        }
                        data += r;
                        size -= r;
                        lace_size[n] = lace_size[n - 1] + snum;
                        total += lace_size[n];
                    }
                    lace_size[n] = size - total;
                    break;
                }
            }
            break;
    }

    if (res == 0) {
        uint64_t timecode = AV_NOPTS_VALUE;

2590 2591
        if (cluster_time != (uint64_t)-1
            && (block_time >= 0 || cluster_time >= -block_time))
2592 2593 2594
            timecode = cluster_time + block_time;

        for (n = 0; n < laces; n++) {
A
Aurelien Jacobs 已提交
2595 2596 2597
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
                st->codec->codec_id == CODEC_ID_COOK ||
                st->codec->codec_id == CODEC_ID_ATRAC3) {
2598
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
A
Aurelien Jacobs 已提交
2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
                int a = st->codec->block_align;
                int sps = audiotrack->sub_packet_size;
                int cfs = audiotrack->coded_framesize;
                int h = audiotrack->sub_packet_h;
                int y = audiotrack->sub_packet_cnt;
                int w = audiotrack->frame_size;
                int x;

                if (!audiotrack->pkt_cnt) {
                    if (st->codec->codec_id == CODEC_ID_RA_288)
                        for (x=0; x<h/2; x++)
                            memcpy(audiotrack->buf+x*2*w+y*cfs,
                                   data+x*cfs, cfs);
                    else
                        for (x=0; x<w/sps; x++)
                            memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);

                    if (++audiotrack->sub_packet_cnt >= h) {
                        audiotrack->sub_packet_cnt = 0;
                        audiotrack->pkt_cnt = h*w / a;
2619
                    }
A
Aurelien Jacobs 已提交
2620 2621
                }
                while (audiotrack->pkt_cnt) {
A
Aurelien Jacobs 已提交
2622
                    pkt = av_mallocz(sizeof(AVPacket));
A
Aurelien Jacobs 已提交
2623 2624 2625
                    av_new_packet(pkt, a);
                    memcpy(pkt->data, audiotrack->buf
                           + a * (h*w / a - audiotrack->pkt_cnt--), a);
A
Aurelien Jacobs 已提交
2626
                    pkt->pos = pos;
2627
                    pkt->stream_index = st->index;
A
Aurelien Jacobs 已提交
2628
                    matroska_queue_packet(matroska, pkt);
2629
                }
A
Aurelien Jacobs 已提交
2630
            } else {
2631
                int offset = 0, pkt_size = lace_size[n];
2632
                uint8_t *pkt_data = data;
A
Aurelien Jacobs 已提交
2633

2634
                if (track->encoding_scope & 1) {
2635
                    offset = matroska_decode_buffer(&pkt_data, &pkt_size,
2636
                                                    track);
2637 2638
                    if (offset < 0)
                        continue;
2639 2640
                }

A
Aurelien Jacobs 已提交
2641 2642
                pkt = av_mallocz(sizeof(AVPacket));
                /* XXX: prevent data copy... */
2643
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
2644
                    av_free(pkt);
A
Aurelien Jacobs 已提交
2645 2646 2647 2648
                    res = AVERROR(ENOMEM);
                    n = laces-1;
                    break;
                }
2649
                if (offset)
2650
                    memcpy (pkt->data, track->encoding_settings, offset);
2651
                memcpy (pkt->data+offset, pkt_data, pkt_size);
A
Aurelien Jacobs 已提交
2652

A
Aurelien Jacobs 已提交
2653 2654 2655
                if (pkt_data != data)
                    av_free(pkt_data);

A
Aurelien Jacobs 已提交
2656 2657
                if (n == 0)
                    pkt->flags = is_keyframe;
2658
                pkt->stream_index = st->index;
A
Aurelien Jacobs 已提交
2659 2660 2661 2662 2663 2664 2665

                pkt->pts = timecode;
                pkt->pos = pos;
                pkt->duration = duration;

                matroska_queue_packet(matroska, pkt);
            }
2666

A
Aurelien Jacobs 已提交
2667 2668
            if (timecode != AV_NOPTS_VALUE)
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
            data += lace_size[n];
        }
    }

    av_free(lace_size);
    av_free(origdata);
    return res;
}

static int
matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
                           uint64_t              cluster_time)
{
    int res = 0;
    uint32_t id;
    int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
    uint64_t duration = AV_NOPTS_VALUE;
    uint8_t *data;
    int size = 0;
    int64_t pos = 0;

    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");

    while (res == 0) {
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2694
            res = AVERROR(EIO);
2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705
            break;
        } else if (matroska->level_up) {
            matroska->level_up--;
            break;
        }

        switch (id) {
            /* one block inside the group. Note, block parsing is one
             * of the harder things, so this code is a bit complicated.
             * See http://www.matroska.org/ for documentation. */
            case MATROSKA_ID_BLOCK: {
2706
                pos = url_ftell(matroska->ctx->pb);
2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
                res = ebml_read_binary(matroska, &id, &data, &size);
                break;
            }

            case MATROSKA_ID_BLOCKDURATION: {
                if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
                    break;
                break;
            }

            case MATROSKA_ID_BLOCKREFERENCE: {
                int64_t num;
                /* We've found a reference, so not even the first frame in
                 * the lace is a key frame. */
                is_keyframe = 0;
                if (last_num_packets != matroska->num_packets)
                    matroska->packets[last_num_packets]->flags = 0;
                if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
                    break;
                break;
            }

            default:
                av_log(matroska->ctx, AV_LOG_INFO,
                       "Unknown entry 0x%x in blockgroup data\n", id);
                /* fall-through */

            case EBML_ID_VOID:
                res = ebml_read_skip(matroska);
                break;
        }

        if (matroska->level_up) {
            matroska->level_up--;
            break;
        }
    }

    if (res)
        return res;

    if (size > 0)
        res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2750
                                   duration, is_keyframe);
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765

    return res;
}

static int
matroska_parse_cluster (MatroskaDemuxContext *matroska)
{
    int res = 0;
    uint32_t id;
    uint64_t cluster_time = 0;
    uint8_t *data;
    int64_t pos;
    int size;

    av_log(matroska->ctx, AV_LOG_DEBUG,
2766
           "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
2767 2768 2769

    while (res == 0) {
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2770
            res = AVERROR(EIO);
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
            break;
        } else if (matroska->level_up) {
            matroska->level_up--;
            break;
        }

        switch (id) {
            /* cluster timecode */
            case MATROSKA_ID_CLUSTERTIMECODE: {
                uint64_t num;
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
                    break;
                cluster_time = num;
                break;
            }

                /* a group of blocks inside a cluster */
            case MATROSKA_ID_BLOCKGROUP:
                if ((res = ebml_read_master(matroska, &id)) < 0)
                    break;
                res = matroska_parse_blockgroup(matroska, cluster_time);
                break;

            case MATROSKA_ID_SIMPLEBLOCK:
2795
                pos = url_ftell(matroska->ctx->pb);
2796 2797 2798 2799
                res = ebml_read_binary(matroska, &id, &data, &size);
                if (res == 0)
                    res = matroska_parse_block(matroska, data, size, pos,
                                               cluster_time, AV_NOPTS_VALUE,
2800
                                               -1);
2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
                break;

            default:
                av_log(matroska->ctx, AV_LOG_INFO,
                       "Unknown entry 0x%x in cluster data\n", id);
                /* fall-through */

            case EBML_ID_VOID:
                res = ebml_read_skip(matroska);
                break;
        }

        if (matroska->level_up) {
            matroska->level_up--;
            break;
        }
    }

    return res;
}

static int
matroska_read_packet (AVFormatContext *s,
                      AVPacket        *pkt)
{
    MatroskaDemuxContext *matroska = s->priv_data;
2827
    int res;
2828 2829 2830 2831 2832 2833 2834
    uint32_t id;

    /* Read stream until we have a packet queued. */
    while (matroska_deliver_packet(matroska, pkt)) {

        /* Have we already reached the end? */
        if (matroska->done)
2835
            return AVERROR(EIO);
2836

2837
        res = 0;
2838 2839
        while (res == 0) {
            if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2840
                return AVERROR(EIO);
2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
            } else if (matroska->level_up) {
                matroska->level_up--;
                break;
            }

            switch (id) {
                case MATROSKA_ID_CLUSTER:
                    if ((res = ebml_read_master(matroska, &id)) < 0)
                        break;
                    if ((res = matroska_parse_cluster(matroska)) == 0)
                        res = 1; /* Parsed one cluster, let's get out. */
                    break;

                default:
                case EBML_ID_VOID:
                    res = ebml_read_skip(matroska);
                    break;
            }

            if (matroska->level_up) {
                matroska->level_up--;
                break;
            }
        }

        if (res == -1)
            matroska->done = 1;
    }

    return 0;
}

static int
matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
                    int flags)
{
    MatroskaDemuxContext *matroska = s->priv_data;
    AVStream *st = s->streams[stream_index];
    int index;

    /* find index entry */
    index = av_index_search_timestamp(st, timestamp, flags);
    if (index < 0)
        return 0;

2886 2887
    matroska_clear_queue(matroska);

2888
    /* do the seek */
2889
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
2890 2891 2892
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
    matroska->skip_to_stream = st;
    matroska->peek_id = 0;
2893
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
2894 2895 2896 2897 2898 2899 2900 2901 2902
    return 0;
}

static int
matroska_read_close (AVFormatContext *s)
{
    MatroskaDemuxContext *matroska = s->priv_data;
    int n = 0;

2903
    matroska_clear_queue(matroska);
2904 2905 2906 2907 2908 2909 2910

    for (n = 0; n < matroska->num_tracks; n++) {
        MatroskaTrack *track = matroska->tracks[n];
        av_free(track->codec_id);
        av_free(track->codec_priv);
        av_free(track->name);

2911 2912 2913 2914 2915
        if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
            MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
            av_free(audiotrack->buf);
        }

2916 2917
        av_free(track);
    }
2918
    ebml_free(matroska_index, matroska);
2919 2920 2921 2922 2923 2924

    return 0;
}

AVInputFormat matroska_demuxer = {
    "matroska",
2925
    NULL_IF_CONFIG_SMALL("Matroska file format"),
2926 2927 2928 2929 2930 2931 2932
    sizeof(MatroskaDemuxContext),
    matroska_probe,
    matroska_read_header,
    matroska_read_packet,
    matroska_read_close,
    matroska_read_seek,
};