Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 935ec5a1

History | View | Annotate | Download (104 KB)

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

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

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

    
45
typedef struct Track {
46
    MatroskaTrackType type;
47

    
48
    /* Unique track number and track ID. stream_index is the index that
49
     * the calling app uses for this track. */
50
    uint32_t num;
51
    uint32_t uid;
52
    int stream_index;
53

    
54
    char *name;
55
    char language[4];
56

    
57
    char *codec_id;
58

    
59
    unsigned char *codec_priv;
60
    int codec_priv_size;
61

    
62
    double time_scale;
63
    uint64_t default_duration;
64
    MatroskaTrackFlags flags;
65

    
66
    int encoding_scope;
67
    MatroskaTrackEncodingCompAlgo encoding_algo;
68
    uint8_t *encoding_settings;
69
    int encoding_settings_len;
70
} MatroskaTrack;
71

    
72
typedef struct MatroskaVideoTrack {
73
    MatroskaTrack track;
74

    
75
    int pixel_width;
76
    int pixel_height;
77
    int display_width;
78
    int display_height;
79

    
80
    uint32_t fourcc;
81

    
82
    //..
83
} MatroskaVideoTrack;
84

    
85
typedef struct MatroskaAudioTrack {
86
    MatroskaTrack track;
87

    
88
    int channels;
89
    int bitdepth;
90
    int internal_samplerate;
91
    int samplerate;
92
    int block_align;
93

    
94
    /* real audio header */
95
    int coded_framesize;
96
    int sub_packet_h;
97
    int frame_size;
98
    int sub_packet_size;
99
    int sub_packet_cnt;
100
    int pkt_cnt;
101
    uint8_t *buf;
102
    //..
103
} MatroskaAudioTrack;
104

    
105
typedef struct MatroskaSubtitleTrack {
106
    MatroskaTrack track;
107
    //..
108
} MatroskaSubtitleTrack;
109

    
110
#define MAX_TRACK_SIZE (FFMAX3(sizeof(MatroskaVideoTrack), \
111
                                    sizeof(MatroskaAudioTrack), \
112
                                    sizeof(MatroskaSubtitleTrack)))
113

    
114
typedef struct MatroskaLevel {
115
    uint64_t start;
116
    uint64_t length;
117
} MatroskaLevel;
118

    
119
typedef struct MatroskaDemuxIndex {
120
  uint64_t        pos;   /* of the corresponding *cluster*! */
121
  uint16_t        track; /* reference to 'num' */
122
  uint64_t        time;  /* in nanoseconds */
123
} MatroskaDemuxIndex;
124

    
125
typedef struct MatroskaDemuxContext {
126
    AVFormatContext *ctx;
127

    
128
    /* ebml stuff */
129
    int num_levels;
130
    MatroskaLevel levels[EBML_MAX_DEPTH];
131
    int level_up;
132

    
133
    /* timescale in the file */
134
    int64_t time_scale;
135

    
136
    /* num_streams is the number of streams that av_new_stream() was called
137
     * for ( = that are available to the calling program). */
138
    int num_tracks;
139
    int num_streams;
140
    MatroskaTrack *tracks[MAX_STREAMS];
141

    
142
    /* cache for ID peeking */
143
    uint32_t peek_id;
144

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

    
148
    /* The packet queue. */
149
    AVPacket **packets;
150
    int num_packets;
151

    
152
    /* have we already parse metadata/cues/clusters? */
153
    int metadata_parsed;
154
    int index_parsed;
155
    int done;
156

    
157
    /* The index for seeking. */
158
    int num_indexes;
159
    MatroskaDemuxIndex *index;
160

    
161
    /* What to skip before effectively reading a packet. */
162
    int skip_to_keyframe;
163
    AVStream *skip_to_stream;
164
} MatroskaDemuxContext;
165

    
166
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
167

    
168
/*
169
 * The first few functions handle EBML file parsing. The rest
170
 * is the document interpretation. Matroska really just is a
171
 * EBML file.
172
 */
173

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

    
181
static int
182
ebml_read_element_level_up (MatroskaDemuxContext *matroska)
183
{
184
    ByteIOContext *pb = matroska->ctx->pb;
185
    offset_t pos = url_ftell(pb);
186
    int num = 0;
187

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

    
191
        if (pos >= level->start + level->length) {
192
            matroska->num_levels--;
193
            num++;
194
        } else {
195
            break;
196
        }
197
    }
198

    
199
    return num;
200
}
201

    
202
/*
203
 * Read: an "EBML number", which is defined as a variable-length
204
 * array of bytes. The first byte indicates the length by giving a
205
 * number of 0-bits followed by a one. The position of the first
206
 * "one" bit inside the first byte indicates the length of this
207
 * number.
208
 * Returns: num. of bytes read. < 0 on error.
209
 */
210

    
211
static int
212
ebml_read_num (MatroskaDemuxContext *matroska,
213
               int                   max_size,
214
               uint64_t             *number)
215
{
216
    ByteIOContext *pb = matroska->ctx->pb;
217
    int len_mask = 0x80, read = 1, n = 1;
218
    int64_t total = 0;
219

    
220
    /* the first byte tells us the length in bytes - get_byte() can normally
221
     * return 0, but since that's not a valid first ebmlID byte, we can
222
     * use it safely here to catch EOS. */
223
    if (!(total = get_byte(pb))) {
224
        /* we might encounter EOS here */
225
        if (!url_feof(pb)) {
226
            offset_t pos = url_ftell(pb);
227
            av_log(matroska->ctx, AV_LOG_ERROR,
228
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
229
                   pos, pos);
230
        }
231
        return AVERROR(EIO); /* EOS or actual I/O error */
232
    }
233

    
234
    /* get the length of the EBML number */
235
    while (read <= max_size && !(total & len_mask)) {
236
        read++;
237
        len_mask >>= 1;
238
    }
239
    if (read > max_size) {
240
        offset_t pos = url_ftell(pb) - 1;
241
        av_log(matroska->ctx, AV_LOG_ERROR,
242
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
243
               (uint8_t) total, pos, pos);
244
        return AVERROR_INVALIDDATA;
245
    }
246

    
247
    /* read out length */
248
    total &= ~len_mask;
249
    while (n++ < read)
250
        total = (total << 8) | get_byte(pb);
251

    
252
    *number = total;
253

    
254
    return read;
255
}
256

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

    
262
static int
263
ebml_read_element_id (MatroskaDemuxContext *matroska,
264
                      uint32_t             *id,
265
                      int                  *level_up)
266
{
267
    int read;
268
    uint64_t total;
269

    
270
    /* if we re-call this, use our cached ID */
271
    if (matroska->peek_id != 0) {
272
        if (level_up)
273
            *level_up = 0;
274
        *id = matroska->peek_id;
275
        return 0;
276
    }
277

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

    
283
    /* level tracking */
284
    if (level_up)
285
        *level_up = ebml_read_element_level_up(matroska);
286

    
287
    return read;
288
}
289

    
290
/*
291
 * Read: element content length.
292
 * Return: the number of bytes read or < 0 on error.
293
 */
294

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

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

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

    
312
static uint32_t
313
ebml_peek_id (MatroskaDemuxContext *matroska,
314
              int                  *level_up)
315
{
316
    uint32_t id;
317

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

    
321
    return id;
322
}
323

    
324
/*
325
 * Seek to a given offset.
326
 * 0 is success, -1 is failure.
327
 */
328

    
329
static int
330
ebml_read_seek (MatroskaDemuxContext *matroska,
331
                offset_t              offset)
332
{
333
    ByteIOContext *pb = matroska->ctx->pb;
334

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

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

    
341
/*
342
 * Skip the next element.
343
 * 0 is success, -1 is failure.
344
 */
345

    
346
static int
347
ebml_read_skip (MatroskaDemuxContext *matroska)
348
{
349
    ByteIOContext *pb = matroska->ctx->pb;
350
    uint32_t id;
351
    uint64_t length;
352
    int res;
353

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

    
358
    url_fskip(pb, length);
359

    
360
    return 0;
361
}
362

    
363
/*
364
 * Read the next element as an unsigned int.
365
 * 0 is success, < 0 is failure.
366
 */
367

    
368
static int
369
ebml_read_uint (MatroskaDemuxContext *matroska,
370
                uint32_t             *id,
371
                uint64_t             *num)
372
{
373
    ByteIOContext *pb = matroska->ctx->pb;
374
    int n = 0, size, res;
375
    uint64_t rlength;
376

    
377
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
378
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
379
        return res;
380
    size = rlength;
381
    if (size < 1 || size > 8) {
382
        offset_t pos = url_ftell(pb);
383
        av_log(matroska->ctx, AV_LOG_ERROR,
384
               "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
385
                size, pos, pos);
386
        return AVERROR_INVALIDDATA;
387
    }
388

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

    
394
    return 0;
395
}
396

    
397
/*
398
 * Read the next element as a signed int.
399
 * 0 is success, < 0 is failure.
400
 */
401

    
402
static int
403
ebml_read_sint (MatroskaDemuxContext *matroska,
404
                uint32_t             *id,
405
                int64_t              *num)
406
{
407
    ByteIOContext *pb = matroska->ctx->pb;
408
    int size, n = 1, negative = 0, res;
409
    uint64_t rlength;
410

    
411
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
412
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
413
        return res;
414
    size = rlength;
415
    if (size < 1 || size > 8) {
416
        offset_t pos = url_ftell(pb);
417
        av_log(matroska->ctx, AV_LOG_ERROR,
418
               "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
419
                size, pos, pos);
420
        return AVERROR_INVALIDDATA;
421
    }
422
    if ((*num = get_byte(pb)) & 0x80) {
423
        negative = 1;
424
        *num &= ~0x80;
425
    }
426
    while (n++ < size)
427
        *num = (*num << 8) | get_byte(pb);
428

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

    
433
    return 0;
434
}
435

    
436
/*
437
 * Read the next element as a float.
438
 * 0 is success, < 0 is failure.
439
 */
440

    
441
static int
442
ebml_read_float (MatroskaDemuxContext *matroska,
443
                 uint32_t             *id,
444
                 double               *num)
445
{
446
    ByteIOContext *pb = matroska->ctx->pb;
447
    int size, res;
448
    uint64_t rlength;
449

    
450
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
451
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
452
        return res;
453
    size = rlength;
454

    
455
    if (size == 4) {
456
        *num= av_int2flt(get_be32(pb));
457
    } else if(size==8){
458
        *num= av_int2dbl(get_be64(pb));
459
    } else{
460
        offset_t pos = url_ftell(pb);
461
        av_log(matroska->ctx, AV_LOG_ERROR,
462
               "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
463
               size, pos, pos);
464
        return AVERROR_INVALIDDATA;
465
    }
466

    
467
    return 0;
468
}
469

    
470
/*
471
 * Read the next element as an ASCII string.
472
 * 0 is success, < 0 is failure.
473
 */
474

    
475
static int
476
ebml_read_ascii (MatroskaDemuxContext *matroska,
477
                 uint32_t             *id,
478
                 char                **str)
479
{
480
    ByteIOContext *pb = matroska->ctx->pb;
481
    int size, res;
482
    uint64_t rlength;
483

    
484
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
485
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
486
        return res;
487
    size = rlength;
488

    
489
    /* ebml strings are usually not 0-terminated, so we allocate one
490
     * byte more, read the string and NULL-terminate it ourselves. */
491
    if (size < 0 || !(*str = av_malloc(size + 1))) {
492
        av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
493
        return AVERROR(ENOMEM);
494
    }
495
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
496
        offset_t pos = url_ftell(pb);
497
        av_log(matroska->ctx, AV_LOG_ERROR,
498
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
499
        av_free(*str);
500
        return AVERROR(EIO);
501
    }
502
    (*str)[size] = '\0';
503

    
504
    return 0;
505
}
506

    
507
/*
508
 * Read the next element as a UTF-8 string.
509
 * 0 is success, < 0 is failure.
510
 */
511

    
512
static int
513
ebml_read_utf8 (MatroskaDemuxContext *matroska,
514
                uint32_t             *id,
515
                char                **str)
516
{
517
  return ebml_read_ascii(matroska, id, str);
518
}
519

    
520
/*
521
 * Read the next element, but only the header. The contents
522
 * are supposed to be sub-elements which can be read separately.
523
 * 0 is success, < 0 is failure.
524
 */
525

    
526
static int
527
ebml_read_master (MatroskaDemuxContext *matroska,
528
                  uint32_t             *id)
529
{
530
    ByteIOContext *pb = matroska->ctx->pb;
531
    uint64_t length;
532
    MatroskaLevel *level;
533
    int res;
534

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

    
539
    /* protect... (Heaven forbids that the '>' is true) */
540
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
541
        av_log(matroska->ctx, AV_LOG_ERROR,
542
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
543
        return AVERROR(ENOSYS);
544
    }
545

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

    
551
    return 0;
552
}
553

    
554
/*
555
 * Read the next element as binary data.
556
 * 0 is success, < 0 is failure.
557
 */
558

    
559
static int
560
ebml_read_binary (MatroskaDemuxContext *matroska,
561
                  uint32_t             *id,
562
                  uint8_t             **binary,
563
                  int                  *size)
564
{
565
    ByteIOContext *pb = matroska->ctx->pb;
566
    uint64_t rlength;
567
    int res;
568

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

    
574
    if (!(*binary = av_malloc(*size))) {
575
        av_log(matroska->ctx, AV_LOG_ERROR,
576
               "Memory allocation error\n");
577
        return AVERROR(ENOMEM);
578
    }
579

    
580
    if (get_buffer(pb, *binary, *size) != *size) {
581
        offset_t pos = url_ftell(pb);
582
        av_log(matroska->ctx, AV_LOG_ERROR,
583
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
584
        return AVERROR(EIO);
585
    }
586

    
587
    return 0;
588
}
589

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

    
596
static int
597
matroska_ebmlnum_uint (uint8_t  *data,
598
                       uint32_t  size,
599
                       uint64_t *num)
600
{
601
    int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
602
    uint64_t total;
603

    
604
    if (size <= 0)
605
        return AVERROR_INVALIDDATA;
606

    
607
    total = data[0];
608
    while (read <= 8 && !(total & len_mask)) {
609
        read++;
610
        len_mask >>= 1;
611
    }
612
    if (read > 8)
613
        return AVERROR_INVALIDDATA;
614

    
615
    if ((total &= (len_mask - 1)) == len_mask - 1)
616
        num_ffs++;
617
    if (size < read)
618
        return AVERROR_INVALIDDATA;
619
    while (n < read) {
620
        if (data[n] == 0xff)
621
            num_ffs++;
622
        total = (total << 8) | data[n];
623
        n++;
624
    }
625

    
626
    if (read == num_ffs)
627
        *num = (uint64_t)-1;
628
    else
629
        *num = total;
630

    
631
    return read;
632
}
633

    
634
/*
635
 * Same as above, but signed.
636
 */
637

    
638
static int
639
matroska_ebmlnum_sint (uint8_t  *data,
640
                       uint32_t  size,
641
                       int64_t  *num)
642
{
643
    uint64_t unum;
644
    int res;
645

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

    
650
    /* make signed (weird way) */
651
    if (unum == (uint64_t)-1)
652
        *num = INT64_MAX;
653
    else
654
        *num = unum - ((1LL << ((7 * res) - 1)) - 1);
655

    
656
    return res;
657
}
658

    
659
/*
660
 * Read an EBML header.
661
 * 0 is success, < 0 is failure.
662
 */
663

    
664
static int
665
ebml_read_header (MatroskaDemuxContext *matroska,
666
                  char                **doctype,
667
                  int                  *version)
668
{
669
    uint32_t id;
670
    int level_up, res = 0;
671

    
672
    /* default init */
673
    if (doctype)
674
        *doctype = NULL;
675
    if (version)
676
        *version = 1;
677

    
678
    if (!(id = ebml_peek_id(matroska, &level_up)) ||
679
        level_up != 0 || id != EBML_ID_HEADER) {
680
        av_log(matroska->ctx, AV_LOG_ERROR,
681
               "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
682
        return AVERROR_INVALIDDATA;
683
    }
684
    if ((res = ebml_read_master(matroska, &id)) < 0)
685
        return res;
686

    
687
    while (res == 0) {
688
        if (!(id = ebml_peek_id(matroska, &level_up)))
689
            return AVERROR(EIO);
690

    
691
        /* end-of-header */
692
        if (level_up)
693
            break;
694

    
695
        switch (id) {
696
            /* is our read version uptodate? */
697
            case EBML_ID_EBMLREADVERSION: {
698
                uint64_t num;
699

    
700
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
701
                    return res;
702
                if (num > EBML_VERSION) {
703
                    av_log(matroska->ctx, AV_LOG_ERROR,
704
                           "EBML version %"PRIu64" (> %d) is not supported\n",
705
                           num, EBML_VERSION);
706
                    return AVERROR_INVALIDDATA;
707
                }
708
                break;
709
            }
710

    
711
            /* we only handle 8 byte lengths at max */
712
            case EBML_ID_EBMLMAXSIZELENGTH: {
713
                uint64_t num;
714

    
715
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
716
                    return res;
717
                if (num > sizeof(uint64_t)) {
718
                    av_log(matroska->ctx, AV_LOG_ERROR,
719
                           "Integers of size %"PRIu64" (> %zd) not supported\n",
720
                           num, sizeof(uint64_t));
721
                    return AVERROR_INVALIDDATA;
722
                }
723
                break;
724
            }
725

    
726
            /* we handle 4 byte IDs at max */
727
            case EBML_ID_EBMLMAXIDLENGTH: {
728
                uint64_t num;
729

    
730
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
731
                    return res;
732
                if (num > sizeof(uint32_t)) {
733
                    av_log(matroska->ctx, AV_LOG_ERROR,
734
                           "IDs of size %"PRIu64" (> %zu) not supported\n",
735
                            num, sizeof(uint32_t));
736
                    return AVERROR_INVALIDDATA;
737
                }
738
                break;
739
            }
740

    
741
            case EBML_ID_DOCTYPE: {
742
                char *text;
743

    
744
                if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
745
                    return res;
746
                if (doctype) {
747
                    if (*doctype)
748
                        av_free(*doctype);
749
                    *doctype = text;
750
                } else
751
                    av_free(text);
752
                break;
753
            }
754

    
755
            case EBML_ID_DOCTYPEREADVERSION: {
756
                uint64_t num;
757

    
758
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
759
                    return res;
760
                if (version)
761
                    *version = num;
762
                break;
763
            }
764

    
765
            default:
766
                av_log(matroska->ctx, AV_LOG_INFO,
767
                       "Unknown data type 0x%x in EBML header", id);
768
                /* pass-through */
769

    
770
            case EBML_ID_VOID:
771
            /* we ignore these two, as they don't tell us anything we
772
             * care about */
773
            case EBML_ID_EBMLVERSION:
774
            case EBML_ID_DOCTYPEVERSION:
775
                res = ebml_read_skip (matroska);
776
                break;
777
        }
778
    }
779

    
780
    return 0;
781
}
782

    
783

    
784
static int
785
matroska_find_track_by_num (MatroskaDemuxContext *matroska,
786
                            int                   num)
787
{
788
    int i;
789

    
790
    for (i = 0; i < matroska->num_tracks; i++)
791
        if (matroska->tracks[i]->num == num)
792
            return i;
793

    
794
    return -1;
795
}
796

    
797

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

    
803
static int
804
matroska_deliver_packet (MatroskaDemuxContext *matroska,
805
                         AVPacket             *pkt)
806
{
807
    if (matroska->num_packets > 0) {
808
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
809
        av_free(matroska->packets[0]);
810
        if (matroska->num_packets > 1) {
811
            memmove(&matroska->packets[0], &matroska->packets[1],
812
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
813
            matroska->packets =
814
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
815
                           sizeof(AVPacket *));
816
        } else {
817
            av_freep(&matroska->packets);
818
        }
819
        matroska->num_packets--;
820
        return 0;
821
    }
822

    
823
    return -1;
824
}
825

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

    
831
static void
832
matroska_queue_packet (MatroskaDemuxContext *matroska,
833
                       AVPacket             *pkt)
834
{
835
    matroska->packets =
836
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
837
                   sizeof(AVPacket *));
838
    matroska->packets[matroska->num_packets] = pkt;
839
    matroska->num_packets++;
840
}
841

    
842
/*
843
 * Free all packets in our internal queue.
844
 */
845
static void
846
matroska_clear_queue (MatroskaDemuxContext *matroska)
847
{
848
    if (matroska->packets) {
849
        int n;
850
        for (n = 0; n < matroska->num_packets; n++) {
851
            av_free_packet(matroska->packets[n]);
852
            av_free(matroska->packets[n]);
853
        }
854
        av_free(matroska->packets);
855
        matroska->packets = NULL;
856
        matroska->num_packets = 0;
857
    }
858
}
859

    
860

    
861
/*
862
 * Autodetecting...
863
 */
864

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

    
872
    /* ebml header? */
873
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
874
        return 0;
875

    
876
    /* length of header */
877
    total = p->buf[4];
878
    while (size <= 8 && !(total & len_mask)) {
879
        size++;
880
        len_mask >>= 1;
881
    }
882
    if (size > 8)
883
      return 0;
884
    total &= (len_mask - 1);
885
    while (n < size)
886
        total = (total << 8) | p->buf[4 + n++];
887

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

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

    
900
    return 0;
901
}
902

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

    
907
static int
908
matroska_parse_info (MatroskaDemuxContext *matroska)
909
{
910
    int res = 0;
911
    uint32_t id;
912

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

    
915
    while (res == 0) {
916
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
917
            res = AVERROR(EIO);
918
            break;
919
        } else if (matroska->level_up) {
920
            matroska->level_up--;
921
            break;
922
        }
923

    
924
        switch (id) {
925
            /* cluster timecode */
926
            case MATROSKA_ID_TIMECODESCALE: {
927
                uint64_t num;
928
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
929
                    break;
930
                matroska->time_scale = num;
931
                break;
932
            }
933

    
934
            case MATROSKA_ID_DURATION: {
935
                double num;
936
                if ((res = ebml_read_float(matroska, &id, &num)) < 0)
937
                    break;
938
                matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
939
                break;
940
            }
941

    
942
            case MATROSKA_ID_TITLE: {
943
                char *text;
944
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
945
                    break;
946
                strncpy(matroska->ctx->title, text,
947
                        sizeof(matroska->ctx->title)-1);
948
                av_free(text);
949
                break;
950
            }
951

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

    
957
            case MATROSKA_ID_WRITINGAPP:
958
            case MATROSKA_ID_MUXINGAPP:
959
            case MATROSKA_ID_DATEUTC:
960
            case MATROSKA_ID_SEGMENTUID:
961
            case EBML_ID_VOID:
962
                res = ebml_read_skip(matroska);
963
                break;
964
        }
965

    
966
        if (matroska->level_up) {
967
            matroska->level_up--;
968
            break;
969
        }
970
    }
971

    
972
    return res;
973
}
974

    
975
static int
976
matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
977
{
978
    uint8_t* data = *buf;
979
    int isize = *buf_size;
980
    uint8_t* pkt_data = NULL;
981
    int pkt_size = isize;
982
    int result = 0;
983
    int olen;
984

    
985
    switch (track->encoding_algo) {
986
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
987
        return track->encoding_settings_len;
988
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
989
        do {
990
            olen = pkt_size *= 3;
991
            pkt_data = av_realloc(pkt_data,
992
                                  pkt_size+LZO_OUTPUT_PADDING);
993
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
994
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
995
        if (result)
996
            goto failed;
997
        pkt_size -= olen;
998
        break;
999
#ifdef CONFIG_ZLIB
1000
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1001
        z_stream zstream = {0};
1002
        if (inflateInit(&zstream) != Z_OK)
1003
            return -1;
1004
        zstream.next_in = data;
1005
        zstream.avail_in = isize;
1006
        do {
1007
            pkt_size *= 3;
1008
            pkt_data = av_realloc(pkt_data, pkt_size);
1009
            zstream.avail_out = pkt_size - zstream.total_out;
1010
            zstream.next_out = pkt_data + zstream.total_out;
1011
            result = inflate(&zstream, Z_NO_FLUSH);
1012
        } while (result==Z_OK && pkt_size<10000000);
1013
        pkt_size = zstream.total_out;
1014
        inflateEnd(&zstream);
1015
        if (result != Z_STREAM_END)
1016
            goto failed;
1017
        break;
1018
    }
1019
#endif
1020
#ifdef CONFIG_BZLIB
1021
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1022
        bz_stream bzstream = {0};
1023
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1024
            return -1;
1025
        bzstream.next_in = data;
1026
        bzstream.avail_in = isize;
1027
        do {
1028
            pkt_size *= 3;
1029
            pkt_data = av_realloc(pkt_data, pkt_size);
1030
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1031
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1032
            result = BZ2_bzDecompress(&bzstream);
1033
        } while (result==BZ_OK && pkt_size<10000000);
1034
        pkt_size = bzstream.total_out_lo32;
1035
        BZ2_bzDecompressEnd(&bzstream);
1036
        if (result != BZ_STREAM_END)
1037
            goto failed;
1038
        break;
1039
    }
1040
#endif
1041
    }
1042

    
1043
    *buf = pkt_data;
1044
    *buf_size = pkt_size;
1045
    return 0;
1046
 failed:
1047
    av_free(pkt_data);
1048
    return -1;
1049
}
1050

    
1051
static int
1052
matroska_add_stream (MatroskaDemuxContext *matroska)
1053
{
1054
    int res = 0;
1055
    uint32_t id;
1056
    MatroskaTrack *track;
1057

    
1058
    /* start with the master */
1059
    if ((res = ebml_read_master(matroska, &id)) < 0)
1060
        return res;
1061

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

    
1064
    /* Allocate a generic track. */
1065
    track = av_mallocz(MAX_TRACK_SIZE);
1066
    track->time_scale = 1.0;
1067
    strcpy(track->language, "eng");
1068

    
1069
    /* try reading the trackentry headers */
1070
    while (res == 0) {
1071
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1072
            res = AVERROR(EIO);
1073
            break;
1074
        } else if (matroska->level_up > 0) {
1075
            matroska->level_up--;
1076
            break;
1077
        }
1078

    
1079
        switch (id) {
1080
            /* track number (unique stream ID) */
1081
            case MATROSKA_ID_TRACKNUMBER: {
1082
                uint64_t num;
1083
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1084
                    break;
1085
                track->num = num;
1086
                break;
1087
            }
1088

    
1089
            /* track UID (unique identifier) */
1090
            case MATROSKA_ID_TRACKUID: {
1091
                uint64_t num;
1092
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1093
                    break;
1094
                track->uid = num;
1095
                break;
1096
            }
1097

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

    
1110
                switch (track->type) {
1111
                    case MATROSKA_TRACK_TYPE_VIDEO:
1112
                    case MATROSKA_TRACK_TYPE_AUDIO:
1113
                    case MATROSKA_TRACK_TYPE_SUBTITLE:
1114
                        break;
1115
                    case MATROSKA_TRACK_TYPE_COMPLEX:
1116
                    case MATROSKA_TRACK_TYPE_LOGO:
1117
                    case MATROSKA_TRACK_TYPE_CONTROL:
1118
                    default:
1119
                        av_log(matroska->ctx, AV_LOG_INFO,
1120
                               "Unknown or unsupported track type 0x%x\n",
1121
                               track->type);
1122
                        track->type = MATROSKA_TRACK_TYPE_NONE;
1123
                        break;
1124
                }
1125
                break;
1126
            }
1127

    
1128
            /* tracktype specific stuff for video */
1129
            case MATROSKA_ID_TRACKVIDEO: {
1130
                MatroskaVideoTrack *videotrack;
1131
                if (!track->type)
1132
                    track->type = MATROSKA_TRACK_TYPE_VIDEO;
1133
                if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1134
                    av_log(matroska->ctx, AV_LOG_INFO,
1135
                           "video data in non-video track - ignoring\n");
1136
                    res = AVERROR_INVALIDDATA;
1137
                    break;
1138
                } else if ((res = ebml_read_master(matroska, &id)) < 0)
1139
                    break;
1140
                videotrack = (MatroskaVideoTrack *)track;
1141

    
1142
                while (res == 0) {
1143
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1144
                        res = AVERROR(EIO);
1145
                        break;
1146
                    } else if (matroska->level_up > 0) {
1147
                        matroska->level_up--;
1148
                        break;
1149
                    }
1150

    
1151
                    switch (id) {
1152
                        /* fixme, this should be one-up, but I get it here */
1153
                        case MATROSKA_ID_TRACKDEFAULTDURATION: {
1154
                            uint64_t num;
1155
                            if ((res = ebml_read_uint (matroska, &id,
1156
                                                       &num)) < 0)
1157
                                break;
1158
                            track->default_duration = num;
1159
                            break;
1160
                        }
1161

    
1162
                        /* video framerate */
1163
                        case MATROSKA_ID_VIDEOFRAMERATE: {
1164
                            double num;
1165
                            if ((res = ebml_read_float(matroska, &id,
1166
                                                       &num)) < 0)
1167
                                break;
1168
                            if (!track->default_duration)
1169
                                track->default_duration = 1000000000/num;
1170
                            break;
1171
                        }
1172

    
1173
                        /* width of the size to display the video at */
1174
                        case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1175
                            uint64_t num;
1176
                            if ((res = ebml_read_uint(matroska, &id,
1177
                                                      &num)) < 0)
1178
                                break;
1179
                            videotrack->display_width = num;
1180
                            break;
1181
                        }
1182

    
1183
                        /* height of the size to display the video at */
1184
                        case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1185
                            uint64_t num;
1186
                            if ((res = ebml_read_uint(matroska, &id,
1187
                                                      &num)) < 0)
1188
                                break;
1189
                            videotrack->display_height = num;
1190
                            break;
1191
                        }
1192

    
1193
                        /* width of the video in the file */
1194
                        case MATROSKA_ID_VIDEOPIXELWIDTH: {
1195
                            uint64_t num;
1196
                            if ((res = ebml_read_uint(matroska, &id,
1197
                                                      &num)) < 0)
1198
                                break;
1199
                            videotrack->pixel_width = num;
1200
                            break;
1201
                        }
1202

    
1203
                        /* height of the video in the file */
1204
                        case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1205
                            uint64_t num;
1206
                            if ((res = ebml_read_uint(matroska, &id,
1207
                                                      &num)) < 0)
1208
                                break;
1209
                            videotrack->pixel_height = num;
1210
                            break;
1211
                        }
1212

    
1213
                        /* whether the video is interlaced */
1214
                        case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1215
                            uint64_t num;
1216
                            if ((res = ebml_read_uint(matroska, &id,
1217
                                                      &num)) < 0)
1218
                                break;
1219
                            if (num)
1220
                                track->flags |=
1221
                                    MATROSKA_VIDEOTRACK_INTERLACED;
1222
                            else
1223
                                track->flags &=
1224
                                    ~MATROSKA_VIDEOTRACK_INTERLACED;
1225
                            break;
1226
                        }
1227

    
1228
                        /* colorspace (only matters for raw video)
1229
                         * fourcc */
1230
                        case MATROSKA_ID_VIDEOCOLORSPACE: {
1231
                            uint64_t num;
1232
                            if ((res = ebml_read_uint(matroska, &id,
1233
                                                      &num)) < 0)
1234
                                break;
1235
                            videotrack->fourcc = num;
1236
                            break;
1237
                        }
1238

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

    
1245
                        case MATROSKA_ID_VIDEOSTEREOMODE:
1246
                        case MATROSKA_ID_VIDEOASPECTRATIO:
1247
                        case EBML_ID_VOID:
1248
                            res = ebml_read_skip(matroska);
1249
                            break;
1250
                    }
1251

    
1252
                    if (matroska->level_up) {
1253
                        matroska->level_up--;
1254
                        break;
1255
                    }
1256
                }
1257
                break;
1258
            }
1259

    
1260
            /* tracktype specific stuff for audio */
1261
            case MATROSKA_ID_TRACKAUDIO: {
1262
                MatroskaAudioTrack *audiotrack;
1263
                if (!track->type)
1264
                    track->type = MATROSKA_TRACK_TYPE_AUDIO;
1265
                if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1266
                    av_log(matroska->ctx, AV_LOG_INFO,
1267
                           "audio data in non-audio track - ignoring\n");
1268
                    res = AVERROR_INVALIDDATA;
1269
                    break;
1270
                } else if ((res = ebml_read_master(matroska, &id)) < 0)
1271
                    break;
1272
                audiotrack = (MatroskaAudioTrack *)track;
1273
                audiotrack->channels = 1;
1274
                audiotrack->samplerate = 8000;
1275

    
1276
                while (res == 0) {
1277
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1278
                        res = AVERROR(EIO);
1279
                        break;
1280
                    } else if (matroska->level_up > 0) {
1281
                        matroska->level_up--;
1282
                        break;
1283
                    }
1284

    
1285
                    switch (id) {
1286
                        /* samplerate */
1287
                        case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1288
                            double num;
1289
                            if ((res = ebml_read_float(matroska, &id,
1290
                                                       &num)) < 0)
1291
                                break;
1292
                            audiotrack->internal_samplerate =
1293
                            audiotrack->samplerate = num;
1294
                            break;
1295
                        }
1296

    
1297
                        case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1298
                            double num;
1299
                            if ((res = ebml_read_float(matroska, &id,
1300
                                                       &num)) < 0)
1301
                                break;
1302
                            audiotrack->samplerate = num;
1303
                            break;
1304
                        }
1305

    
1306
                            /* bitdepth */
1307
                        case MATROSKA_ID_AUDIOBITDEPTH: {
1308
                            uint64_t num;
1309
                            if ((res = ebml_read_uint(matroska, &id,
1310
                                                      &num)) < 0)
1311
                                break;
1312
                            audiotrack->bitdepth = num;
1313
                            break;
1314
                        }
1315

    
1316
                            /* channels */
1317
                        case MATROSKA_ID_AUDIOCHANNELS: {
1318
                            uint64_t num;
1319
                            if ((res = ebml_read_uint(matroska, &id,
1320
                                                      &num)) < 0)
1321
                                break;
1322
                            audiotrack->channels = num;
1323
                            break;
1324
                        }
1325

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

    
1332
                        case EBML_ID_VOID:
1333
                            res = ebml_read_skip(matroska);
1334
                            break;
1335
                    }
1336

    
1337
                    if (matroska->level_up) {
1338
                        matroska->level_up--;
1339
                        break;
1340
                    }
1341
                }
1342
                break;
1343
            }
1344

    
1345
                /* codec identifier */
1346
            case MATROSKA_ID_CODECID: {
1347
                char *text;
1348
                if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1349
                    break;
1350
                track->codec_id = text;
1351
                break;
1352
            }
1353

    
1354
                /* codec private data */
1355
            case MATROSKA_ID_CODECPRIVATE: {
1356
                uint8_t *data;
1357
                int size;
1358
                if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1359
                    break;
1360
                track->codec_priv = data;
1361
                track->codec_priv_size = size;
1362
                break;
1363
            }
1364

    
1365
                /* name of this track */
1366
            case MATROSKA_ID_TRACKNAME: {
1367
                char *text;
1368
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1369
                    break;
1370
                track->name = text;
1371
                break;
1372
            }
1373

    
1374
                /* language (matters for audio/subtitles, mostly) */
1375
            case MATROSKA_ID_TRACKLANGUAGE: {
1376
                char *text, *end;
1377
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1378
                    break;
1379
                if ((end = strchr(text, '-')))
1380
                    *end = '\0';
1381
                if (strlen(text) == 3)
1382
                    strcpy(track->language, text);
1383
                av_free(text);
1384
                break;
1385
            }
1386

    
1387
                /* whether this is actually used */
1388
            case MATROSKA_ID_TRACKFLAGENABLED: {
1389
                uint64_t num;
1390
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1391
                    break;
1392
                if (num)
1393
                    track->flags |= MATROSKA_TRACK_ENABLED;
1394
                else
1395
                    track->flags &= ~MATROSKA_TRACK_ENABLED;
1396
                break;
1397
            }
1398

    
1399
                /* whether it's the default for this track type */
1400
            case MATROSKA_ID_TRACKFLAGDEFAULT: {
1401
                uint64_t num;
1402
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1403
                    break;
1404
                if (num)
1405
                    track->flags |= MATROSKA_TRACK_DEFAULT;
1406
                else
1407
                    track->flags &= ~MATROSKA_TRACK_DEFAULT;
1408
                break;
1409
            }
1410

    
1411
                /* lacing (like MPEG, where blocks don't end/start on frame
1412
                 * boundaries) */
1413
            case MATROSKA_ID_TRACKFLAGLACING: {
1414
                uint64_t num;
1415
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1416
                    break;
1417
                if (num)
1418
                    track->flags |= MATROSKA_TRACK_LACING;
1419
                else
1420
                    track->flags &= ~MATROSKA_TRACK_LACING;
1421
                break;
1422
            }
1423

    
1424
                /* default length (in time) of one data block in this track */
1425
            case MATROSKA_ID_TRACKDEFAULTDURATION: {
1426
                uint64_t num;
1427
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1428
                    break;
1429
                track->default_duration = num;
1430
                break;
1431
            }
1432

    
1433
            case MATROSKA_ID_TRACKCONTENTENCODINGS: {
1434
                if ((res = ebml_read_master(matroska, &id)) < 0)
1435
                    break;
1436

    
1437
                while (res == 0) {
1438
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1439
                        res = AVERROR(EIO);
1440
                        break;
1441
                    } else if (matroska->level_up > 0) {
1442
                        matroska->level_up--;
1443
                        break;
1444
                    }
1445

    
1446
                    switch (id) {
1447
                        case MATROSKA_ID_TRACKCONTENTENCODING: {
1448
                            int encoding_scope = 1;
1449
                            if ((res = ebml_read_master(matroska, &id)) < 0)
1450
                                break;
1451

    
1452
                            while (res == 0) {
1453
                                if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1454
                                    res = AVERROR(EIO);
1455
                                    break;
1456
                                } else if (matroska->level_up > 0) {
1457
                                    matroska->level_up--;
1458
                                    break;
1459
                                }
1460

    
1461
                                switch (id) {
1462
                                    case MATROSKA_ID_ENCODINGSCOPE: {
1463
                                        uint64_t num;
1464
                                        if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1465
                                            break;
1466
                                        encoding_scope = num;
1467
                                        break;
1468
                                    }
1469

    
1470
                                    case MATROSKA_ID_ENCODINGTYPE: {
1471
                                        uint64_t num;
1472
                                        if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1473
                                            break;
1474
                                        if (num)
1475
                                            av_log(matroska->ctx, AV_LOG_ERROR,
1476
                                                   "Unsupported encoding type");
1477
                                        break;
1478
                                    }
1479

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

    
1484
                                        while (res == 0) {
1485
                                            if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1486
                                                res = AVERROR(EIO);
1487
                                                break;
1488
                                            } else if (matroska->level_up > 0) {
1489
                                                matroska->level_up--;
1490
                                                break;
1491
                                            }
1492

    
1493
                                            switch (id) {
1494
                                                case MATROSKA_ID_ENCODINGCOMPALGO: {
1495
                                                    uint64_t num;
1496
                                                    if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1497
                                                        break;
1498
                                                    if (num != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1499
#ifdef CONFIG_ZLIB
1500
                                                        num != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1501
#endif
1502
#ifdef CONFIG_BZLIB
1503
                                                        num != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1504
#endif
1505
                                                        num != MATROSKA_TRACK_ENCODING_COMP_LZO)
1506
                                                        av_log(matroska->ctx, AV_LOG_ERROR,
1507
                                                               "Unsupported compression algo\n");
1508
                                                    track->encoding_algo = num;
1509
                                                    break;
1510
                                                }
1511

    
1512
                                                case MATROSKA_ID_ENCODINGCOMPSETTINGS: {
1513
                                                    uint8_t *data;
1514
                                                    int size;
1515
                                                    if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1516
                                                        break;
1517
                                                    track->encoding_settings = data;
1518
                                                    track->encoding_settings_len = size;
1519
                                                    break;
1520
                                                }
1521

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

    
1528
                                                case EBML_ID_VOID:
1529
                                                    res = ebml_read_skip(matroska);
1530
                                                    break;
1531
                                            }
1532

    
1533
                                            if (matroska->level_up) {
1534
                                                matroska->level_up--;
1535
                                                break;
1536
                                            }
1537
                                        }
1538
                                        break;
1539
                                    }
1540

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

    
1547
                                    case EBML_ID_VOID:
1548
                                        res = ebml_read_skip(matroska);
1549
                                        break;
1550
                                }
1551

    
1552
                                if (matroska->level_up) {
1553
                                    matroska->level_up--;
1554
                                    break;
1555
                                }
1556
                            }
1557

    
1558
                            track->encoding_scope = encoding_scope;
1559
                            break;
1560
                        }
1561

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

    
1568
                        case EBML_ID_VOID:
1569
                            res = ebml_read_skip(matroska);
1570
                            break;
1571
                    }
1572

    
1573
                    if (matroska->level_up) {
1574
                        matroska->level_up--;
1575
                        break;
1576
                    }
1577
                }
1578
                break;
1579
            }
1580

    
1581
            case MATROSKA_ID_TRACKTIMECODESCALE: {
1582
                double num;
1583
                if ((res = ebml_read_float(matroska, &id, &num)) < 0)
1584
                    break;
1585
                track->time_scale = num;
1586
                break;
1587
            }
1588

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

    
1594
            case EBML_ID_VOID:
1595
            /* we ignore these because they're nothing useful. */
1596
            case MATROSKA_ID_TRACKFLAGFORCED:
1597
            case MATROSKA_ID_CODECNAME:
1598
            case MATROSKA_ID_CODECDECODEALL:
1599
            case MATROSKA_ID_CODECINFOURL:
1600
            case MATROSKA_ID_CODECDOWNLOADURL:
1601
            case MATROSKA_ID_TRACKMINCACHE:
1602
            case MATROSKA_ID_TRACKMAXCACHE:
1603
                res = ebml_read_skip(matroska);
1604
                break;
1605
        }
1606

    
1607
        if (matroska->level_up) {
1608
            matroska->level_up--;
1609
            break;
1610
        }
1611
    }
1612

    
1613
    if (track->type && matroska->num_tracks < ARRAY_SIZE(matroska->tracks)) {
1614
        matroska->tracks[matroska->num_tracks++] = track;
1615
    } else {
1616
        av_free(track);
1617
    }
1618
    return res;
1619
}
1620

    
1621
static int
1622
matroska_parse_tracks (MatroskaDemuxContext *matroska)
1623
{
1624
    int res = 0;
1625
    uint32_t id;
1626

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

    
1629
    while (res == 0) {
1630
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1631
            res = AVERROR(EIO);
1632
            break;
1633
        } else if (matroska->level_up) {
1634
            matroska->level_up--;
1635
            break;
1636
        }
1637

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

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

    
1649
            case EBML_ID_VOID:
1650
                res = ebml_read_skip(matroska);
1651
                break;
1652
        }
1653

    
1654
        if (matroska->level_up) {
1655
            matroska->level_up--;
1656
            break;
1657
        }
1658
    }
1659

    
1660
    return res;
1661
}
1662

    
1663
static int
1664
matroska_parse_index (MatroskaDemuxContext *matroska)
1665
{
1666
    int res = 0;
1667
    uint32_t id;
1668
    MatroskaDemuxIndex idx;
1669

    
1670
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1671

    
1672
    while (res == 0) {
1673
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1674
            res = AVERROR(EIO);
1675
            break;
1676
        } else if (matroska->level_up) {
1677
            matroska->level_up--;
1678
            break;
1679
        }
1680

    
1681
        switch (id) {
1682
            /* one single index entry ('point') */
1683
            case MATROSKA_ID_POINTENTRY:
1684
                if ((res = ebml_read_master(matroska, &id)) < 0)
1685
                    break;
1686

    
1687
                /* in the end, we hope to fill one entry with a
1688
                 * timestamp, a file position and a tracknum */
1689
                idx.pos   = (uint64_t) -1;
1690
                idx.time  = (uint64_t) -1;
1691
                idx.track = (uint16_t) -1;
1692

    
1693
                while (res == 0) {
1694
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1695
                        res = AVERROR(EIO);
1696
                        break;
1697
                    } else if (matroska->level_up) {
1698
                        matroska->level_up--;
1699
                        break;
1700
                    }
1701

    
1702
                    switch (id) {
1703
                        /* one single index entry ('point') */
1704
                        case MATROSKA_ID_CUETIME: {
1705
                            uint64_t time;
1706
                            if ((res = ebml_read_uint(matroska, &id,
1707
                                                      &time)) < 0)
1708
                                break;
1709
                            idx.time = time * matroska->time_scale;
1710
                            break;
1711
                        }
1712

    
1713
                        /* position in the file + track to which it
1714
                         * belongs */
1715
                        case MATROSKA_ID_CUETRACKPOSITION:
1716
                            if ((res = ebml_read_master(matroska, &id)) < 0)
1717
                                break;
1718

    
1719
                            while (res == 0) {
1720
                                if (!(id = ebml_peek_id (matroska,
1721
                                                    &matroska->level_up))) {
1722
                                    res = AVERROR(EIO);
1723
                                    break;
1724
                                } else if (matroska->level_up) {
1725
                                    matroska->level_up--;
1726
                                    break;
1727
                                }
1728

    
1729
                                switch (id) {
1730
                                    /* track number */
1731
                                    case MATROSKA_ID_CUETRACK: {
1732
                                        uint64_t num;
1733
                                        if ((res = ebml_read_uint(matroska,
1734
                                                          &id, &num)) < 0)
1735
                                            break;
1736
                                        idx.track = num;
1737
                                        break;
1738
                                    }
1739

    
1740
                                        /* position in file */
1741
                                    case MATROSKA_ID_CUECLUSTERPOSITION: {
1742
                                        uint64_t num;
1743
                                        if ((res = ebml_read_uint(matroska,
1744
                                                          &id, &num)) < 0)
1745
                                            break;
1746
                                        idx.pos = num+matroska->segment_start;
1747
                                        break;
1748
                                    }
1749

    
1750
                                    default:
1751
                                        av_log(matroska->ctx, AV_LOG_INFO,
1752
                                               "Unknown entry 0x%x in "
1753
                                               "CuesTrackPositions\n", id);
1754
                                        /* fall-through */
1755

    
1756
                                    case EBML_ID_VOID:
1757
                                        res = ebml_read_skip(matroska);
1758
                                        break;
1759
                                }
1760

    
1761
                                if (matroska->level_up) {
1762
                                    matroska->level_up--;
1763
                                    break;
1764
                                }
1765
                            }
1766

    
1767
                            break;
1768

    
1769
                        default:
1770
                            av_log(matroska->ctx, AV_LOG_INFO,
1771
                                   "Unknown entry 0x%x in cuespoint "
1772
                                   "index\n", id);
1773
                            /* fall-through */
1774

    
1775
                        case EBML_ID_VOID:
1776
                            res = ebml_read_skip(matroska);
1777
                            break;
1778
                    }
1779

    
1780
                    if (matroska->level_up) {
1781
                        matroska->level_up--;
1782
                        break;
1783
                    }
1784
                }
1785

    
1786
                /* so let's see if we got what we wanted */
1787
                if (idx.pos   != (uint64_t) -1 &&
1788
                    idx.time  != (uint64_t) -1 &&
1789
                    idx.track != (uint16_t) -1) {
1790
                    if (matroska->num_indexes % 32 == 0) {
1791
                        /* re-allocate bigger index */
1792
                        matroska->index =
1793
                            av_realloc(matroska->index,
1794
                                       (matroska->num_indexes + 32) *
1795
                                       sizeof(MatroskaDemuxIndex));
1796
                    }
1797
                    matroska->index[matroska->num_indexes] = idx;
1798
                    matroska->num_indexes++;
1799
                }
1800
                break;
1801

    
1802
            default:
1803
                av_log(matroska->ctx, AV_LOG_INFO,
1804
                       "Unknown entry 0x%x in cues header\n", id);
1805
                /* fall-through */
1806

    
1807
            case EBML_ID_VOID:
1808
                res = ebml_read_skip(matroska);
1809
                break;
1810
        }
1811

    
1812
        if (matroska->level_up) {
1813
            matroska->level_up--;
1814
            break;
1815
        }
1816
    }
1817

    
1818
    return res;
1819
}
1820

    
1821
static int
1822
matroska_parse_metadata (MatroskaDemuxContext *matroska)
1823
{
1824
    int res = 0;
1825
    uint32_t id;
1826

    
1827
    while (res == 0) {
1828
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1829
            res = AVERROR(EIO);
1830
            break;
1831
        } else if (matroska->level_up) {
1832
            matroska->level_up--;
1833
            break;
1834
        }
1835

    
1836
        switch (id) {
1837
            /* Hm, this is unsupported... */
1838
            default:
1839
                av_log(matroska->ctx, AV_LOG_INFO,
1840
                       "Unknown entry 0x%x in metadata header\n", id);
1841
                /* fall-through */
1842

    
1843
            case EBML_ID_VOID:
1844
                res = ebml_read_skip(matroska);
1845
                break;
1846
        }
1847

    
1848
        if (matroska->level_up) {
1849
            matroska->level_up--;
1850
            break;
1851
        }
1852
    }
1853

    
1854
    return res;
1855
}
1856

    
1857
static int
1858
matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1859
{
1860
    int res = 0;
1861
    uint32_t id;
1862

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

    
1865
    while (res == 0) {
1866
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1867
            res = AVERROR(EIO);
1868
            break;
1869
        } else if (matroska->level_up) {
1870
            matroska->level_up--;
1871
            break;
1872
        }
1873

    
1874
        switch (id) {
1875
            case MATROSKA_ID_SEEKENTRY: {
1876
                uint32_t seek_id = 0, peek_id_cache = 0;
1877
                uint64_t seek_pos = (uint64_t) -1, t;
1878
                int dummy_level = 0;
1879

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

    
1883
                while (res == 0) {
1884
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1885
                        res = AVERROR(EIO);
1886
                        break;
1887
                    } else if (matroska->level_up) {
1888
                        matroska->level_up--;
1889
                        break;
1890
                    }
1891

    
1892
                    switch (id) {
1893
                        case MATROSKA_ID_SEEKID:
1894
                            res = ebml_read_uint(matroska, &id, &t);
1895
                            seek_id = t;
1896
                            break;
1897

    
1898
                        case MATROSKA_ID_SEEKPOSITION:
1899
                            res = ebml_read_uint(matroska, &id, &seek_pos);
1900
                            break;
1901

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

    
1907
                        case EBML_ID_VOID:
1908
                            res = ebml_read_skip(matroska);
1909
                            break;
1910
                    }
1911

    
1912
                    if (matroska->level_up) {
1913
                        matroska->level_up--;
1914
                        break;
1915
                    }
1916
                }
1917

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

    
1925
                switch (seek_id) {
1926
                    case MATROSKA_ID_CUES:
1927
                    case MATROSKA_ID_TAGS: {
1928
                        uint32_t level_up = matroska->level_up;
1929
                        offset_t before_pos;
1930
                        uint64_t length;
1931
                        MatroskaLevel level;
1932

    
1933
                        /* remember the peeked ID and the current position */
1934
                        peek_id_cache = matroska->peek_id;
1935
                        before_pos = url_ftell(matroska->ctx->pb);
1936

    
1937
                        /* seek */
1938
                        if ((res = ebml_read_seek(matroska, seek_pos +
1939
                                               matroska->segment_start)) < 0)
1940
                            goto finish;
1941

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

    
1951
                        level.start = 0;
1952
                        level.length = (uint64_t)-1;
1953
                        matroska->levels[matroska->num_levels] = level;
1954
                        matroska->num_levels++;
1955
                        dummy_level = 1;
1956

    
1957
                        /* check ID */
1958
                        if (!(id = ebml_peek_id (matroska,
1959
                                                 &matroska->level_up)))
1960
                            goto finish;
1961
                        if (id != seek_id) {
1962
                            av_log(matroska->ctx, AV_LOG_INFO,
1963
                                   "We looked for ID=0x%x but got "
1964
                                   "ID=0x%x (pos=%"PRIu64")",
1965
                                   seek_id, id, seek_pos +
1966
                                   matroska->segment_start);
1967
                            goto finish;
1968
                        }
1969

    
1970
                        /* read master + parse */
1971
                        if ((res = ebml_read_master(matroska, &id)) < 0)
1972
                            goto finish;
1973
                        switch (id) {
1974
                            case MATROSKA_ID_CUES:
1975
                                if (!(res = matroska_parse_index(matroska)) ||
1976
                                    url_feof(matroska->ctx->pb)) {
1977
                                    matroska->index_parsed = 1;
1978
                                    res = 0;
1979
                                }
1980
                                break;
1981
                            case MATROSKA_ID_TAGS:
1982
                                if (!(res = matroska_parse_metadata(matroska)) ||
1983
                                   url_feof(matroska->ctx->pb)) {
1984
                                    matroska->metadata_parsed = 1;
1985
                                    res = 0;
1986
                                }
1987
                                break;
1988
                        }
1989

    
1990
                    finish:
1991
                        /* remove dummy level */
1992
                        if (dummy_level)
1993
                            while (matroska->num_levels) {
1994
                                matroska->num_levels--;
1995
                                length =
1996
                                  matroska->levels[matroska->num_levels].length;
1997
                                if (length == (uint64_t)-1)
1998
                                    break;
1999
                            }
2000

    
2001
                        /* seek back */
2002
                        if ((res = ebml_read_seek(matroska, before_pos)) < 0)
2003
                            return res;
2004
                        matroska->peek_id = peek_id_cache;
2005
                        matroska->level_up = level_up;
2006
                        break;
2007
                    }
2008

    
2009
                    default:
2010
                        av_log(matroska->ctx, AV_LOG_INFO,
2011
                               "Ignoring seekhead entry for ID=0x%x\n",
2012
                               seek_id);
2013
                        break;
2014
                }
2015

    
2016
                break;
2017
            }
2018

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

    
2024
            case EBML_ID_VOID:
2025
                res = ebml_read_skip(matroska);
2026
                break;
2027
        }
2028

    
2029
        if (matroska->level_up) {
2030
            matroska->level_up--;
2031
            break;
2032
        }
2033
    }
2034

    
2035
    return res;
2036
}
2037

    
2038
static int
2039
matroska_parse_attachments(AVFormatContext *s)
2040
{
2041
    MatroskaDemuxContext *matroska = s->priv_data;
2042
    int res = 0;
2043
    uint32_t id;
2044

    
2045
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing attachments...\n");
2046

    
2047
    while (res == 0) {
2048
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2049
            res = AVERROR(EIO);
2050
            break;
2051
        } else if (matroska->level_up) {
2052
            matroska->level_up--;
2053
            break;
2054
        }
2055

    
2056
        switch (id) {
2057
        case MATROSKA_ID_ATTACHEDFILE: {
2058
            char* name = NULL;
2059
            char* mime = NULL;
2060
            uint8_t* data = NULL;
2061
            int i, data_size = 0;
2062
            AVStream *st;
2063

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

    
2067
            while (res == 0) {
2068
                if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2069
                    res = AVERROR(EIO);
2070
                    break;
2071
                } else if (matroska->level_up) {
2072
                    matroska->level_up--;
2073
                    break;
2074
                }
2075

    
2076
                switch (id) {
2077
                case MATROSKA_ID_FILENAME:
2078
                    res = ebml_read_utf8 (matroska, &id, &name);
2079
                    break;
2080

    
2081
                case MATROSKA_ID_FILEMIMETYPE:
2082
                    res = ebml_read_ascii (matroska, &id, &mime);
2083
                    break;
2084

    
2085
                case MATROSKA_ID_FILEDATA:
2086
                    res = ebml_read_binary(matroska, &id, &data, &data_size);
2087
                    break;
2088

    
2089
                default:
2090
                    av_log(matroska->ctx, AV_LOG_INFO,
2091
                           "Unknown attachedfile ID 0x%x\n", id);
2092
                case MATROSKA_ID_FILEUID:
2093
                case EBML_ID_VOID:
2094
                    res = ebml_read_skip(matroska);
2095
                    break;
2096
                }
2097

    
2098
                if (matroska->level_up) {
2099
                    matroska->level_up--;
2100
                    break;
2101
                }
2102
            }
2103

    
2104
            if (!(name && mime && data && data_size > 0)) {
2105
                av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
2106
                break;
2107
            }
2108

    
2109
            st = av_new_stream(s, matroska->num_streams++);
2110
            if (st == NULL)
2111
                return AVERROR(ENOMEM);
2112
            st->filename = av_strdup(name);
2113
            st->codec->codec_id = CODEC_ID_NONE;
2114
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
2115
            st->codec->extradata = av_malloc(data_size);
2116
            if(st->codec->extradata == NULL)
2117
                return AVERROR(ENOMEM);
2118
            st->codec->extradata_size = data_size;
2119
            memcpy(st->codec->extradata, data, data_size);
2120

    
2121
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
2122
                if (!strncmp(ff_mkv_mime_tags[i].str, mime,
2123
                             strlen(ff_mkv_mime_tags[i].str))) {
2124
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
2125
                    break;
2126
                }
2127
            }
2128

    
2129
            av_log(matroska->ctx, AV_LOG_DEBUG, "new attachment: %s, %s, size %d \n", name, mime, data_size);
2130
            break;
2131
        }
2132

    
2133
        default:
2134
            av_log(matroska->ctx, AV_LOG_INFO,
2135
                   "Unknown attachments ID 0x%x\n", id);
2136
            /* fall-through */
2137

    
2138
        case EBML_ID_VOID:
2139
            res = ebml_read_skip(matroska);
2140
            break;
2141
        }
2142

    
2143
        if (matroska->level_up) {
2144
            matroska->level_up--;
2145
            break;
2146
        }
2147
    }
2148

    
2149
    return res;
2150
}
2151

    
2152
static int
2153
matroska_parse_chapters(AVFormatContext *s)
2154
{
2155
    MatroskaDemuxContext *matroska = s->priv_data;
2156
    int res = 0;
2157
    uint32_t id;
2158

    
2159
    av_log(s, AV_LOG_DEBUG, "parsing chapters...\n");
2160

    
2161
    while (res == 0) {
2162
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2163
            res = AVERROR(EIO);
2164
            break;
2165
        } else if (matroska->level_up) {
2166
            matroska->level_up--;
2167
            break;
2168
        }
2169

    
2170
        switch (id) {
2171
        case MATROSKA_ID_EDITIONENTRY: {
2172
            uint64_t end = AV_NOPTS_VALUE, start = AV_NOPTS_VALUE;
2173
            int64_t uid= -1;
2174
            char* title = NULL;
2175
            /* if there is more than one chapter edition
2176
               we take only the first one */
2177
            if(s->chapters) {
2178
                    ebml_read_skip(matroska);
2179
                    break;
2180
            }
2181

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

    
2185
            while (res == 0) {
2186
                if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2187
                    res = AVERROR(EIO);
2188
                    break;
2189
                } else if (matroska->level_up) {
2190
                    matroska->level_up--;
2191
                    break;
2192
                }
2193

    
2194
                switch (id) {
2195
                case MATROSKA_ID_CHAPTERATOM:
2196
                    if ((res = ebml_read_master(matroska, &id)) < 0)
2197
                        break;
2198

    
2199
                    while (res == 0) {
2200
                        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2201
                            res = AVERROR(EIO);
2202
                            break;
2203
                        } else if (matroska->level_up) {
2204
                            matroska->level_up--;
2205
                            break;
2206
                        }
2207

    
2208
                        switch (id) {
2209
                        case MATROSKA_ID_CHAPTERTIMEEND:
2210
                            res = ebml_read_uint(matroska, &id, &end);
2211
                            break;
2212

    
2213
                        case MATROSKA_ID_CHAPTERTIMESTART:
2214
                            res = ebml_read_uint(matroska, &id, &start);
2215
                            break;
2216

    
2217
                        case MATROSKA_ID_CHAPTERDISPLAY:
2218
                            if ((res = ebml_read_master(matroska, &id)) < 0)
2219
                                break;
2220

    
2221
                            while (res == 0) {
2222
                                if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2223
                                    res = AVERROR(EIO);
2224
                                    break;
2225
                                } else if (matroska->level_up) {
2226
                                    matroska->level_up--;
2227
                                    break;
2228
                                }
2229

    
2230
                                switch (id) {
2231
                                case MATROSKA_ID_CHAPSTRING:
2232
                                    res = ebml_read_utf8(matroska, &id, &title);
2233
                                    break;
2234

    
2235
                                default:
2236
                                    av_log(s, AV_LOG_INFO, "Ignoring unknown Chapter display ID 0x%x\n", id);
2237
                                case EBML_ID_VOID:
2238
                                    res = ebml_read_skip(matroska);
2239
                                    break;
2240
                                }
2241

    
2242
                                if (matroska->level_up) {
2243
                                    matroska->level_up--;
2244
                                    break;
2245
                                }
2246
                            }
2247
                            break;
2248

    
2249
                        case MATROSKA_ID_CHAPTERUID:
2250
                            res = ebml_read_uint(matroska, &id, &uid);
2251
                            break;
2252
                        default:
2253
                            av_log(s, AV_LOG_INFO, "Ignoring unknown Chapter atom ID 0x%x\n", id);
2254
                        case MATROSKA_ID_CHAPTERFLAGHIDDEN:
2255
                        case EBML_ID_VOID:
2256
                            res = ebml_read_skip(matroska);
2257
                            break;
2258
                        }
2259

    
2260
                        if (matroska->level_up) {
2261
                            matroska->level_up--;
2262
                            break;
2263
                        }
2264
                    }
2265

    
2266
                    if (start != AV_NOPTS_VALUE && uid != -1) {
2267
                        if(!ff_new_chapter(s, uid, (AVRational){1, 1000000000}, start, end, title))
2268
                            res= AVERROR(ENOMEM);
2269
                    }
2270
                    av_free(title);
2271
                    break;
2272

    
2273
                default:
2274
                    av_log(s, AV_LOG_INFO, "Ignoring unknown Edition entry ID 0x%x\n", id);
2275
                case MATROSKA_ID_EDITIONUID:
2276
                case MATROSKA_ID_EDITIONFLAGHIDDEN:
2277
                case MATROSKA_ID_EDITIONFLAGDEFAULT:
2278
                case EBML_ID_VOID:
2279
                    res = ebml_read_skip(matroska);
2280
                    break;
2281
                }
2282

    
2283

    
2284
                if (matroska->level_up) {
2285
                    matroska->level_up--;
2286
                    break;
2287
                }
2288
            }
2289
        break;
2290
        }
2291

    
2292
        default:
2293
            av_log(s, AV_LOG_INFO, "Expected an Edition entry (0x%x), but found 0x%x\n", MATROSKA_ID_EDITIONENTRY, id);
2294
        case EBML_ID_VOID:
2295
            res = ebml_read_skip(matroska);
2296
            break;
2297
        }
2298

    
2299
        if (matroska->level_up) {
2300
            matroska->level_up--;
2301
            break;
2302
        }
2303
    }
2304

    
2305
    return res;
2306
}
2307

    
2308
static int
2309
matroska_aac_profile (char *codec_id)
2310
{
2311
    static const char *aac_profiles[] = {
2312
        "MAIN", "LC", "SSR"
2313
    };
2314
    int profile;
2315

    
2316
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2317
        if (strstr(codec_id, aac_profiles[profile]))
2318
            break;
2319
    return profile + 1;
2320
}
2321

    
2322
static int
2323
matroska_aac_sri (int samplerate)
2324
{
2325
    int sri;
2326

    
2327
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
2328
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
2329
            break;
2330
    return sri;
2331
}
2332

    
2333
static int
2334
matroska_read_header (AVFormatContext    *s,
2335
                      AVFormatParameters *ap)
2336
{
2337
    MatroskaDemuxContext *matroska = s->priv_data;
2338
    char *doctype;
2339
    int version, last_level, res = 0;
2340
    uint32_t id;
2341

    
2342
    matroska->ctx = s;
2343

    
2344
    /* First read the EBML header. */
2345
    doctype = NULL;
2346
    if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2347
        return res;
2348
    if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2349
        av_log(matroska->ctx, AV_LOG_ERROR,
2350
               "Wrong EBML doctype ('%s' != 'matroska').\n",
2351
               doctype ? doctype : "(none)");
2352
        if (doctype)
2353
            av_free(doctype);
2354
        return AVERROR_NOFMT;
2355
    }
2356
    av_free(doctype);
2357
    if (version > 2) {
2358
        av_log(matroska->ctx, AV_LOG_ERROR,
2359
               "Matroska demuxer version 2 too old for file version %d\n",
2360
               version);
2361
        return AVERROR_NOFMT;
2362
    }
2363

    
2364
    /* The next thing is a segment. */
2365
    while (1) {
2366
        if (!(id = ebml_peek_id(matroska, &last_level)))
2367
            return AVERROR(EIO);
2368
        if (id == MATROSKA_ID_SEGMENT)
2369
            break;
2370

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

    
2379
    /* We now have a Matroska segment.
2380
     * Seeks are from the beginning of the segment,
2381
     * after the segment ID/length. */
2382
    if ((res = ebml_read_master(matroska, &id)) < 0)
2383
        return res;
2384
    matroska->segment_start = url_ftell(s->pb);
2385

    
2386
    matroska->time_scale = 1000000;
2387
    /* we've found our segment, start reading the different contents in here */
2388
    while (res == 0) {
2389
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2390
            res = AVERROR(EIO);
2391
            break;
2392
        } else if (matroska->level_up) {
2393
            matroska->level_up--;
2394
            break;
2395
        }
2396

    
2397
        switch (id) {
2398
            /* stream info */
2399
            case MATROSKA_ID_INFO: {
2400
                if ((res = ebml_read_master(matroska, &id)) < 0)
2401
                    break;
2402
                res = matroska_parse_info(matroska);
2403
                break;
2404
            }
2405

    
2406
            /* track info headers */
2407
            case MATROSKA_ID_TRACKS: {
2408
                if ((res = ebml_read_master(matroska, &id)) < 0)
2409
                    break;
2410
                res = matroska_parse_tracks(matroska);
2411
                break;
2412
            }
2413

    
2414
            /* stream index */
2415
            case MATROSKA_ID_CUES: {
2416
                if (!matroska->index_parsed) {
2417
                    if ((res = ebml_read_master(matroska, &id)) < 0)
2418
                        break;
2419
                    res = matroska_parse_index(matroska);
2420
                } else
2421
                    res = ebml_read_skip(matroska);
2422
                break;
2423
            }
2424

    
2425
            /* metadata */
2426
            case MATROSKA_ID_TAGS: {
2427
                if (!matroska->metadata_parsed) {
2428
                    if ((res = ebml_read_master(matroska, &id)) < 0)
2429
                        break;
2430
                    res = matroska_parse_metadata(matroska);
2431
                } else
2432
                    res = ebml_read_skip(matroska);
2433
                break;
2434
            }
2435

    
2436
            /* file index (if seekable, seek to Cues/Tags to parse it) */
2437
            case MATROSKA_ID_SEEKHEAD: {
2438
                if ((res = ebml_read_master(matroska, &id)) < 0)
2439
                    break;
2440
                res = matroska_parse_seekhead(matroska);
2441
                break;
2442
            }
2443

    
2444
            case MATROSKA_ID_ATTACHMENTS: {
2445
                if ((res = ebml_read_master(matroska, &id)) < 0)
2446
                    break;
2447
                res = matroska_parse_attachments(s);
2448
                break;
2449
            }
2450

    
2451
            case MATROSKA_ID_CLUSTER: {
2452
                /* Do not read the master - this will be done in the next
2453
                 * call to matroska_read_packet. */
2454
                res = 1;
2455
                break;
2456
            }
2457

    
2458
            case MATROSKA_ID_CHAPTERS: {
2459
                if ((res = ebml_read_master(matroska, &id)) < 0)
2460
                    return res;
2461
                res = matroska_parse_chapters(s);
2462
                break;
2463
            }
2464

    
2465
            default:
2466
                av_log(matroska->ctx, AV_LOG_INFO,
2467
                       "Unknown matroska file header ID 0x%x\n", id);
2468
            /* fall-through */
2469

    
2470
            case EBML_ID_VOID:
2471
                res = ebml_read_skip(matroska);
2472
                break;
2473
        }
2474

    
2475
        if (matroska->level_up) {
2476
            matroska->level_up--;
2477
            break;
2478
        }
2479
    }
2480

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

    
2487
        for (i = 0; i < matroska->num_tracks; i++) {
2488
            enum CodecID codec_id = CODEC_ID_NONE;
2489
            uint8_t *extradata = NULL;
2490
            int extradata_size = 0;
2491
            int extradata_offset = 0;
2492
            track = matroska->tracks[i];
2493
            track->stream_index = -1;
2494

    
2495
            /* Apply some sanity checks. */
2496
            if (track->codec_id == NULL)
2497
                continue;
2498

    
2499
            for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
2500
                if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2501
                            strlen(ff_mkv_codec_tags[j].str))){
2502
                    codec_id= ff_mkv_codec_tags[j].id;
2503
                    break;
2504
                }
2505
            }
2506

    
2507
            /* Set the FourCC from the CodecID. */
2508
            /* This is the MS compatibility mode which stores a
2509
             * BITMAPINFOHEADER in the CodecPrivate. */
2510
            if (!strcmp(track->codec_id,
2511
                        MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2512
                (track->codec_priv_size >= 40) &&
2513
                (track->codec_priv != NULL)) {
2514
                MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2515

    
2516
                /* Offset of biCompression. Stored in LE. */
2517
                vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2518
                codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2519

    
2520
            }
2521

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

    
2530
                /* Offset of wFormatTag. Stored in LE. */
2531
                tag = AV_RL16(track->codec_priv);
2532
                codec_id = codec_get_id(codec_wav_tags, tag);
2533

    
2534
            }
2535

    
2536
            else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2537
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2538
                int profile = matroska_aac_profile(track->codec_id);
2539
                int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2540
                extradata = av_malloc(5);
2541
                if (extradata == NULL)
2542
                    return AVERROR(ENOMEM);
2543
                extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2544
                extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2545
                if (strstr(track->codec_id, "SBR")) {
2546
                    sri = matroska_aac_sri(audiotrack->samplerate);
2547
                    extradata[2] = 0x56;
2548
                    extradata[3] = 0xE5;
2549
                    extradata[4] = 0x80 | (sri<<3);
2550
                    extradata_size = 5;
2551
                } else {
2552
                    extradata_size = 2;
2553
                }
2554
            }
2555

    
2556
            else if (codec_id == CODEC_ID_TTA) {
2557
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2558
                ByteIOContext b;
2559
                extradata_size = 30;
2560
                extradata = av_mallocz(extradata_size);
2561
                if (extradata == NULL)
2562
                    return AVERROR(ENOMEM);
2563
                init_put_byte(&b, extradata, extradata_size, 1,
2564
                              NULL, NULL, NULL, NULL);
2565
                put_buffer(&b, "TTA1", 4);
2566
                put_le16(&b, 1);
2567
                put_le16(&b, audiotrack->channels);
2568
                put_le16(&b, audiotrack->bitdepth);
2569
                put_le32(&b, audiotrack->samplerate);
2570
                put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2571
            }
2572

    
2573
            else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2574
                     codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2575
                extradata_offset = 26;
2576
                track->codec_priv_size -= extradata_offset;
2577
            }
2578

    
2579
            else if (codec_id == CODEC_ID_RA_144) {
2580
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2581
                audiotrack->samplerate = 8000;
2582
                audiotrack->channels = 1;
2583
            }
2584

    
2585
            else if (codec_id == CODEC_ID_RA_288 ||
2586
                     codec_id == CODEC_ID_COOK ||
2587
                     codec_id == CODEC_ID_ATRAC3) {
2588
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2589
                ByteIOContext b;
2590

    
2591
                init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2592
                              NULL, NULL, NULL, NULL);
2593
                url_fskip(&b, 24);
2594
                audiotrack->coded_framesize = get_be32(&b);
2595
                url_fskip(&b, 12);
2596
                audiotrack->sub_packet_h    = get_be16(&b);
2597
                audiotrack->frame_size      = get_be16(&b);
2598
                audiotrack->sub_packet_size = get_be16(&b);
2599
                audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2600
                if (codec_id == CODEC_ID_RA_288) {
2601
                    audiotrack->block_align = audiotrack->coded_framesize;
2602
                    track->codec_priv_size = 0;
2603
                } else {
2604
                    audiotrack->block_align = audiotrack->sub_packet_size;
2605
                    extradata_offset = 78;
2606
                    track->codec_priv_size -= extradata_offset;
2607
                }
2608
            }
2609

    
2610
            if (codec_id == CODEC_ID_NONE) {
2611
                av_log(matroska->ctx, AV_LOG_INFO,
2612
                       "Unknown/unsupported CodecID %s.\n",
2613
                       track->codec_id);
2614
            }
2615

    
2616
            track->stream_index = matroska->num_streams;
2617

    
2618
            matroska->num_streams++;
2619
            st = av_new_stream(s, track->stream_index);
2620
            if (st == NULL)
2621
                return AVERROR(ENOMEM);
2622
            av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2623

    
2624
            st->codec->codec_id = codec_id;
2625
            st->start_time = 0;
2626
            if (strcmp(track->language, "und"))
2627
                strcpy(st->language, track->language);
2628

    
2629
            if (track->flags & MATROSKA_TRACK_DEFAULT)
2630
                st->disposition |= AV_DISPOSITION_DEFAULT;
2631

    
2632
            if (track->default_duration)
2633
                av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2634
                          track->default_duration, 1000000000, 30000);
2635

    
2636
            if(extradata){
2637
                st->codec->extradata = extradata;
2638
                st->codec->extradata_size = extradata_size;
2639
            } else if(track->codec_priv && track->codec_priv_size > 0){
2640
                st->codec->extradata = av_malloc(track->codec_priv_size);
2641
                if(st->codec->extradata == NULL)
2642
                    return AVERROR(ENOMEM);
2643
                st->codec->extradata_size = track->codec_priv_size;
2644
                memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2645
                       track->codec_priv_size);
2646
            }
2647

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

    
2651
                st->codec->codec_type = CODEC_TYPE_VIDEO;
2652
                st->codec->codec_tag = videotrack->fourcc;
2653
                st->codec->width = videotrack->pixel_width;
2654
                st->codec->height = videotrack->pixel_height;
2655
                if (videotrack->display_width == 0)
2656
                    videotrack->display_width= videotrack->pixel_width;
2657
                if (videotrack->display_height == 0)
2658
                    videotrack->display_height= videotrack->pixel_height;
2659
                av_reduce(&st->codec->sample_aspect_ratio.num,
2660
                          &st->codec->sample_aspect_ratio.den,
2661
                          st->codec->height * videotrack->display_width,
2662
                          st->codec-> width * videotrack->display_height,
2663
                          255);
2664
                st->need_parsing = AVSTREAM_PARSE_HEADERS;
2665
            } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2666
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2667

    
2668
                st->codec->codec_type = CODEC_TYPE_AUDIO;
2669
                st->codec->sample_rate = audiotrack->samplerate;
2670
                st->codec->channels = audiotrack->channels;
2671
                st->codec->block_align = audiotrack->block_align;
2672
            } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2673
                st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2674
            }
2675

    
2676
            /* What do we do with private data? E.g. for Vorbis. */
2677
        }
2678
        res = 0;
2679
    }
2680

    
2681
    if (matroska->index_parsed) {
2682
        int i, track, stream;
2683
        for (i=0; i<matroska->num_indexes; i++) {
2684
            MatroskaDemuxIndex *idx = &matroska->index[i];
2685
            track = matroska_find_track_by_num(matroska, idx->track);
2686
            if (track < 0)  continue;
2687
            stream = matroska->tracks[track]->stream_index;
2688
            if (stream >= 0 && stream < matroska->ctx->nb_streams)
2689
                av_add_index_entry(matroska->ctx->streams[stream],
2690
                                   idx->pos, idx->time/AV_TIME_BASE,
2691
                                   0, 0, AVINDEX_KEYFRAME);
2692
        }
2693
    }
2694

    
2695
    return res;
2696
}
2697

    
2698
static int
2699
matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2700
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
2701
                     int is_keyframe, int is_bframe)
2702
{
2703
    int res = 0;
2704
    int track;
2705
    AVStream *st;
2706
    AVPacket *pkt;
2707
    uint8_t *origdata = data;
2708
    int16_t block_time;
2709
    uint32_t *lace_size = NULL;
2710
    int n, flags, laces = 0;
2711
    uint64_t num;
2712
    int stream_index;
2713

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

    
2723
    /* fetch track from num */
2724
    track = matroska_find_track_by_num(matroska, num);
2725
    if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2726
        av_log(matroska->ctx, AV_LOG_INFO,
2727
               "Invalid stream %d or size %u\n", track, size);
2728
        av_free(origdata);
2729
        return res;
2730
    }
2731
    stream_index = matroska->tracks[track]->stream_index;
2732
    if (stream_index < 0 || stream_index >= matroska->ctx->nb_streams) {
2733
        av_free(origdata);
2734
        return res;
2735
    }
2736
    st = matroska->ctx->streams[stream_index];
2737
    if (st->discard >= AVDISCARD_ALL) {
2738
        av_free(origdata);
2739
        return res;
2740
    }
2741
    if (duration == AV_NOPTS_VALUE)
2742
        duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2743

    
2744
    /* block_time (relative to cluster time) */
2745
    block_time = AV_RB16(data);
2746
    data += 2;
2747
    flags = *data++;
2748
    size -= 3;
2749
    if (is_keyframe == -1)
2750
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
2751

    
2752
    if (matroska->skip_to_keyframe) {
2753
        if (!is_keyframe || st != matroska->skip_to_stream) {
2754
            av_free(origdata);
2755
            return res;
2756
        }
2757
        matroska->skip_to_keyframe = 0;
2758
    }
2759

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

    
2767
        case 0x1: /* xiph lacing */
2768
        case 0x2: /* fixed-size lacing */
2769
        case 0x3: /* EBML lacing */
2770
            assert(size>0); // size <=3 is checked before size-=3 above
2771
            laces = (*data) + 1;
2772
            data += 1;
2773
            size -= 1;
2774
            lace_size = av_mallocz(laces * sizeof(int));
2775

    
2776
            switch ((flags & 0x06) >> 1) {
2777
                case 0x1: /* xiph lacing */ {
2778
                    uint8_t temp;
2779
                    uint32_t total = 0;
2780
                    for (n = 0; res == 0 && n < laces - 1; n++) {
2781
                        while (1) {
2782
                            if (size == 0) {
2783
                                res = -1;
2784
                                break;
2785
                            }
2786
                            temp = *data;
2787
                            lace_size[n] += temp;
2788
                            data += 1;
2789
                            size -= 1;
2790
                            if (temp != 0xff)
2791
                                break;
2792
                        }
2793
                        total += lace_size[n];
2794
                    }
2795
                    lace_size[n] = size - total;
2796
                    break;
2797
                }
2798

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

    
2804
                case 0x3: /* EBML lacing */ {
2805
                    uint32_t total;
2806
                    n = matroska_ebmlnum_uint(data, size, &num);
2807
                    if (n < 0) {
2808
                        av_log(matroska->ctx, AV_LOG_INFO,
2809
                               "EBML block data error\n");
2810
                        break;
2811
                    }
2812
                    data += n;
2813
                    size -= n;
2814
                    total = lace_size[0] = num;
2815
                    for (n = 1; res == 0 && n < laces - 1; n++) {
2816
                        int64_t snum;
2817
                        int r;
2818
                        r = matroska_ebmlnum_sint (data, size, &snum);
2819
                        if (r < 0) {
2820
                            av_log(matroska->ctx, AV_LOG_INFO,
2821
                                   "EBML block data error\n");
2822
                            break;
2823
                        }
2824
                        data += r;
2825
                        size -= r;
2826
                        lace_size[n] = lace_size[n - 1] + snum;
2827
                        total += lace_size[n];
2828
                    }
2829
                    lace_size[n] = size - total;
2830
                    break;
2831
                }
2832
            }
2833
            break;
2834
    }
2835

    
2836
    if (res == 0) {
2837
        uint64_t timecode = AV_NOPTS_VALUE;
2838

    
2839
        if (cluster_time != (uint64_t)-1
2840
            && (block_time >= 0 || cluster_time >= -block_time))
2841
            timecode = cluster_time + block_time;
2842

    
2843
        for (n = 0; n < laces; n++) {
2844
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
2845
                st->codec->codec_id == CODEC_ID_COOK ||
2846
                st->codec->codec_id == CODEC_ID_ATRAC3) {
2847
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2848
                int a = st->codec->block_align;
2849
                int sps = audiotrack->sub_packet_size;
2850
                int cfs = audiotrack->coded_framesize;
2851
                int h = audiotrack->sub_packet_h;
2852
                int y = audiotrack->sub_packet_cnt;
2853
                int w = audiotrack->frame_size;
2854
                int x;
2855

    
2856
                if (!audiotrack->pkt_cnt) {
2857
                    if (st->codec->codec_id == CODEC_ID_RA_288)
2858
                        for (x=0; x<h/2; x++)
2859
                            memcpy(audiotrack->buf+x*2*w+y*cfs,
2860
                                   data+x*cfs, cfs);
2861
                    else
2862
                        for (x=0; x<w/sps; x++)
2863
                            memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2864

    
2865
                    if (++audiotrack->sub_packet_cnt >= h) {
2866
                        audiotrack->sub_packet_cnt = 0;
2867
                        audiotrack->pkt_cnt = h*w / a;
2868
                    }
2869
                }
2870
                while (audiotrack->pkt_cnt) {
2871
                    pkt = av_mallocz(sizeof(AVPacket));
2872
                    av_new_packet(pkt, a);
2873
                    memcpy(pkt->data, audiotrack->buf
2874
                           + a * (h*w / a - audiotrack->pkt_cnt--), a);
2875
                    pkt->pos = pos;
2876
                    pkt->stream_index = stream_index;
2877
                    matroska_queue_packet(matroska, pkt);
2878
                }
2879
            } else {
2880
                int offset = 0, pkt_size = lace_size[n];
2881
                uint8_t *pkt_data = data;
2882

    
2883
                if (matroska->tracks[track]->encoding_scope & 1) {
2884
                    offset = matroska_decode_buffer(&pkt_data, &pkt_size,
2885
                                                    matroska->tracks[track]);
2886
                    if (offset < 0)
2887
                        continue;
2888
                }
2889

    
2890
                pkt = av_mallocz(sizeof(AVPacket));
2891
                /* XXX: prevent data copy... */
2892
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
2893
                    av_free(pkt);
2894
                    res = AVERROR(ENOMEM);
2895
                    n = laces-1;
2896
                    break;
2897
                }
2898
                if (offset)
2899
                    memcpy (pkt->data, matroska->tracks[track]->encoding_settings, offset);
2900
                memcpy (pkt->data+offset, pkt_data, pkt_size);
2901

    
2902
                if (pkt_data != data)
2903
                    av_free(pkt_data);
2904

    
2905
                if (n == 0)
2906
                    pkt->flags = is_keyframe;
2907
                pkt->stream_index = stream_index;
2908

    
2909
                pkt->pts = timecode;
2910
                pkt->pos = pos;
2911
                pkt->duration = duration;
2912

    
2913
                matroska_queue_packet(matroska, pkt);
2914
            }
2915

    
2916
            if (timecode != AV_NOPTS_VALUE)
2917
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2918
            data += lace_size[n];
2919
        }
2920
    }
2921

    
2922
    av_free(lace_size);
2923
    av_free(origdata);
2924
    return res;
2925
}
2926

    
2927
static int
2928
matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2929
                           uint64_t              cluster_time)
2930
{
2931
    int res = 0;
2932
    uint32_t id;
2933
    int is_bframe = 0;
2934
    int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2935
    uint64_t duration = AV_NOPTS_VALUE;
2936
    uint8_t *data;
2937
    int size = 0;
2938
    int64_t pos = 0;
2939

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

    
2942
    while (res == 0) {
2943
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2944
            res = AVERROR(EIO);
2945
            break;
2946
        } else if (matroska->level_up) {
2947
            matroska->level_up--;
2948
            break;
2949
        }
2950

    
2951
        switch (id) {
2952
            /* one block inside the group. Note, block parsing is one
2953
             * of the harder things, so this code is a bit complicated.
2954
             * See http://www.matroska.org/ for documentation. */
2955
            case MATROSKA_ID_BLOCK: {
2956
                pos = url_ftell(matroska->ctx->pb);
2957
                res = ebml_read_binary(matroska, &id, &data, &size);
2958
                break;
2959
            }
2960

    
2961
            case MATROSKA_ID_BLOCKDURATION: {
2962
                if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2963
                    break;
2964
                break;
2965
            }
2966

    
2967
            case MATROSKA_ID_BLOCKREFERENCE: {
2968
                int64_t num;
2969
                /* We've found a reference, so not even the first frame in
2970
                 * the lace is a key frame. */
2971
                is_keyframe = 0;
2972
                if (last_num_packets != matroska->num_packets)
2973
                    matroska->packets[last_num_packets]->flags = 0;
2974
                if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2975
                    break;
2976
                if (num > 0)
2977
                    is_bframe = 1;
2978
                break;
2979
            }
2980

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

    
2986
            case EBML_ID_VOID:
2987
                res = ebml_read_skip(matroska);
2988
                break;
2989
        }
2990

    
2991
        if (matroska->level_up) {
2992
            matroska->level_up--;
2993
            break;
2994
        }
2995
    }
2996

    
2997
    if (res)
2998
        return res;
2999

    
3000
    if (size > 0)
3001
        res = matroska_parse_block(matroska, data, size, pos, cluster_time,
3002
                                   duration, is_keyframe, is_bframe);
3003

    
3004
    return res;
3005
}
3006

    
3007
static int
3008
matroska_parse_cluster (MatroskaDemuxContext *matroska)
3009
{
3010
    int res = 0;
3011
    uint32_t id;
3012
    uint64_t cluster_time = 0;
3013
    uint8_t *data;
3014
    int64_t pos;
3015
    int size;
3016

    
3017
    av_log(matroska->ctx, AV_LOG_DEBUG,
3018
           "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
3019

    
3020
    while (res == 0) {
3021
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
3022
            res = AVERROR(EIO);
3023
            break;
3024
        } else if (matroska->level_up) {
3025
            matroska->level_up--;
3026
            break;
3027
        }
3028

    
3029
        switch (id) {
3030
            /* cluster timecode */
3031
            case MATROSKA_ID_CLUSTERTIMECODE: {
3032
                uint64_t num;
3033
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
3034
                    break;
3035
                cluster_time = num;
3036
                break;
3037
            }
3038

    
3039
                /* a group of blocks inside a cluster */
3040
            case MATROSKA_ID_BLOCKGROUP:
3041
                if ((res = ebml_read_master(matroska, &id)) < 0)
3042
                    break;
3043
                res = matroska_parse_blockgroup(matroska, cluster_time);
3044
                break;
3045

    
3046
            case MATROSKA_ID_SIMPLEBLOCK:
3047
                pos = url_ftell(matroska->ctx->pb);
3048
                res = ebml_read_binary(matroska, &id, &data, &size);
3049
                if (res == 0)
3050
                    res = matroska_parse_block(matroska, data, size, pos,
3051
                                               cluster_time, AV_NOPTS_VALUE,
3052
                                               -1, 0);
3053
                break;
3054

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

    
3060
            case EBML_ID_VOID:
3061
                res = ebml_read_skip(matroska);
3062
                break;
3063
        }
3064

    
3065
        if (matroska->level_up) {
3066
            matroska->level_up--;
3067
            break;
3068
        }
3069
    }
3070

    
3071
    return res;
3072
}
3073

    
3074
static int
3075
matroska_read_packet (AVFormatContext *s,
3076
                      AVPacket        *pkt)
3077
{
3078
    MatroskaDemuxContext *matroska = s->priv_data;
3079
    int res;
3080
    uint32_t id;
3081

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

    
3085
        /* Have we already reached the end? */
3086
        if (matroska->done)
3087
            return AVERROR(EIO);
3088

    
3089
        res = 0;
3090
        while (res == 0) {
3091
            if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
3092
                return AVERROR(EIO);
3093
            } else if (matroska->level_up) {
3094
                matroska->level_up--;
3095
                break;
3096
            }
3097

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

    
3106
                default:
3107
                case EBML_ID_VOID:
3108
                    res = ebml_read_skip(matroska);
3109
                    break;
3110
            }
3111

    
3112
            if (matroska->level_up) {
3113
                matroska->level_up--;
3114
                break;
3115
            }
3116
        }
3117

    
3118
        if (res == -1)
3119
            matroska->done = 1;
3120
    }
3121

    
3122
    return 0;
3123
}
3124

    
3125
static int
3126
matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
3127
                    int flags)
3128
{
3129
    MatroskaDemuxContext *matroska = s->priv_data;
3130
    AVStream *st = s->streams[stream_index];
3131
    int index;
3132

    
3133
    /* find index entry */
3134
    index = av_index_search_timestamp(st, timestamp, flags);
3135
    if (index < 0)
3136
        return 0;
3137

    
3138
    matroska_clear_queue(matroska);
3139

    
3140
    /* do the seek */
3141
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
3142
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
3143
    matroska->skip_to_stream = st;
3144
    matroska->peek_id = 0;
3145
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
3146
    return 0;
3147
}
3148

    
3149
static int
3150
matroska_read_close (AVFormatContext *s)
3151
{
3152
    MatroskaDemuxContext *matroska = s->priv_data;
3153
    int n = 0;
3154

    
3155
    av_free(matroska->index);
3156

    
3157
    matroska_clear_queue(matroska);
3158

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

    
3165
        if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
3166
            MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
3167
            av_free(audiotrack->buf);
3168
        }
3169

    
3170
        av_free(track);
3171
    }
3172

    
3173
    return 0;
3174
}
3175

    
3176
AVInputFormat matroska_demuxer = {
3177
    "matroska",
3178
    NULL_IF_CONFIG_SMALL("Matroska file format"),
3179
    sizeof(MatroskaDemuxContext),
3180
    matroska_probe,
3181
    matroska_read_header,
3182
    matroska_read_packet,
3183
    matroska_read_close,
3184
    matroska_read_seek,
3185
};