Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ fbb878ce

History | View | Annotate | Download (100 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

    
42
typedef struct Track {
43
    MatroskaTrackType type;
44

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

    
51
    char *name;
52
    char language[4];
53

    
54
    char *codec_id;
55
    char *codec_name;
56

    
57
    unsigned char *codec_priv;
58
    int codec_priv_size;
59

    
60
    uint64_t default_duration;
61
    MatroskaTrackFlags flags;
62

    
63
    int encoding_scope;
64
    MatroskaTrackEncodingCompAlgo encoding_algo;
65
    uint8_t *encoding_settings;
66
    int encoding_settings_len;
67
} MatroskaTrack;
68

    
69
typedef struct MatroskaVideoTrack {
70
    MatroskaTrack track;
71

    
72
    int pixel_width;
73
    int pixel_height;
74
    int display_width;
75
    int display_height;
76

    
77
    uint32_t fourcc;
78

    
79
    MatroskaAspectRatioMode ar_mode;
80
    MatroskaEyeMode eye_mode;
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
    /* matroska stuff */
134
    char *writing_app;
135
    char *muxing_app;
136
    int64_t created;
137

    
138
    /* timescale in the file */
139
    int64_t time_scale;
140

    
141
    /* num_streams is the number of streams that av_new_stream() was called
142
     * for ( = that are available to the calling program). */
143
    int num_tracks;
144
    int num_streams;
145
    MatroskaTrack *tracks[MAX_STREAMS];
146

    
147
    /* cache for ID peeking */
148
    uint32_t peek_id;
149

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

    
153
    /* The packet queue. */
154
    AVPacket **packets;
155
    int num_packets;
156

    
157
    /* have we already parse metadata/cues/clusters? */
158
    int metadata_parsed;
159
    int index_parsed;
160
    int done;
161

    
162
    /* The index for seeking. */
163
    int num_indexes;
164
    MatroskaDemuxIndex *index;
165

    
166
    /* What to skip before effectively reading a packet. */
167
    int skip_to_keyframe;
168
    AVStream *skip_to_stream;
169
} MatroskaDemuxContext;
170

    
171
/*
172
 * The first few functions handle EBML file parsing. The rest
173
 * is the document interpretation. Matroska really just is a
174
 * EBML file.
175
 */
176

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

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

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

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

    
202
    return num;
203
}
204

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

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

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

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

    
250
    /* read out length */
251
    total &= ~len_mask;
252
    while (n++ < read)
253
        total = (total << 8) | get_byte(pb);
254

    
255
    *number = total;
256

    
257
    return read;
258
}
259

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

    
265
static int
266
ebml_read_element_id (MatroskaDemuxContext *matroska,
267
                      uint32_t             *id,
268
                      int                  *level_up)
269
{
270
    int read;
271
    uint64_t total;
272

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

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

    
286
    /* level tracking */
287
    if (level_up)
288
        *level_up = ebml_read_element_level_up(matroska);
289

    
290
    return read;
291
}
292

    
293
/*
294
 * Read: element content length.
295
 * Return: the number of bytes read or < 0 on error.
296
 */
297

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

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

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

    
315
static uint32_t
316
ebml_peek_id (MatroskaDemuxContext *matroska,
317
              int                  *level_up)
318
{
319
    uint32_t id;
320

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

    
324
    return id;
325
}
326

    
327
/*
328
 * Seek to a given offset.
329
 * 0 is success, -1 is failure.
330
 */
331

    
332
static int
333
ebml_read_seek (MatroskaDemuxContext *matroska,
334
                offset_t              offset)
335
{
336
    ByteIOContext *pb = matroska->ctx->pb;
337

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

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

    
344
/*
345
 * Skip the next element.
346
 * 0 is success, -1 is failure.
347
 */
348

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

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

    
361
    url_fskip(pb, length);
362

    
363
    return 0;
364
}
365

    
366
/*
367
 * Read the next element as an unsigned int.
368
 * 0 is success, < 0 is failure.
369
 */
370

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

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

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

    
397
    return 0;
398
}
399

    
400
/*
401
 * Read the next element as a signed int.
402
 * 0 is success, < 0 is failure.
403
 */
404

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

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

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

    
436
    return 0;
437
}
438

    
439
/*
440
 * Read the next element as a float.
441
 * 0 is success, < 0 is failure.
442
 */
443

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

    
453
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
454
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
455
        return res;
456
    size = rlength;
457

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

    
470
    return 0;
471
}
472

    
473
/*
474
 * Read the next element as an ASCII string.
475
 * 0 is success, < 0 is failure.
476
 */
477

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

    
487
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
488
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
489
        return res;
490
    size = rlength;
491

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

    
506
    return 0;
507
}
508

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

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

    
522
/*
523
 * Read the next element as a date (nanoseconds since 1/1/2000).
524
 * 0 is success, < 0 is failure.
525
 */
526

    
527
static int
528
ebml_read_date (MatroskaDemuxContext *matroska,
529
                uint32_t             *id,
530
                int64_t              *date)
531
{
532
  return ebml_read_sint(matroska, id, date);
533
}
534

    
535
/*
536
 * Read the next element, but only the header. The contents
537
 * are supposed to be sub-elements which can be read separately.
538
 * 0 is success, < 0 is failure.
539
 */
540

    
541
static int
542
ebml_read_master (MatroskaDemuxContext *matroska,
543
                  uint32_t             *id)
544
{
545
    ByteIOContext *pb = matroska->ctx->pb;
546
    uint64_t length;
547
    MatroskaLevel *level;
548
    int res;
549

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

    
554
    /* protect... (Heaven forbids that the '>' is true) */
555
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
556
        av_log(matroska->ctx, AV_LOG_ERROR,
557
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
558
        return AVERROR(ENOSYS);
559
    }
560

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

    
566
    return 0;
567
}
568

    
569
/*
570
 * Read the next element as binary data.
571
 * 0 is success, < 0 is failure.
572
 */
573

    
574
static int
575
ebml_read_binary (MatroskaDemuxContext *matroska,
576
                  uint32_t             *id,
577
                  uint8_t             **binary,
578
                  int                  *size)
579
{
580
    ByteIOContext *pb = matroska->ctx->pb;
581
    uint64_t rlength;
582
    int res;
583

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

    
589
    if (!(*binary = av_malloc(*size))) {
590
        av_log(matroska->ctx, AV_LOG_ERROR,
591
               "Memory allocation error\n");
592
        return AVERROR(ENOMEM);
593
    }
594

    
595
    if (get_buffer(pb, *binary, *size) != *size) {
596
        offset_t pos = url_ftell(pb);
597
        av_log(matroska->ctx, AV_LOG_ERROR,
598
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
599
        return AVERROR(EIO);
600
    }
601

    
602
    return 0;
603
}
604

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

    
611
static int
612
matroska_ebmlnum_uint (uint8_t  *data,
613
                       uint32_t  size,
614
                       uint64_t *num)
615
{
616
    int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
617
    uint64_t total;
618

    
619
    if (size <= 0)
620
        return AVERROR_INVALIDDATA;
621

    
622
    total = data[0];
623
    while (read <= 8 && !(total & len_mask)) {
624
        read++;
625
        len_mask >>= 1;
626
    }
627
    if (read > 8)
628
        return AVERROR_INVALIDDATA;
629

    
630
    if ((total &= (len_mask - 1)) == len_mask - 1)
631
        num_ffs++;
632
    if (size < read)
633
        return AVERROR_INVALIDDATA;
634
    while (n < read) {
635
        if (data[n] == 0xff)
636
            num_ffs++;
637
        total = (total << 8) | data[n];
638
        n++;
639
    }
640

    
641
    if (read == num_ffs)
642
        *num = (uint64_t)-1;
643
    else
644
        *num = total;
645

    
646
    return read;
647
}
648

    
649
/*
650
 * Same as above, but signed.
651
 */
652

    
653
static int
654
matroska_ebmlnum_sint (uint8_t  *data,
655
                       uint32_t  size,
656
                       int64_t  *num)
657
{
658
    uint64_t unum;
659
    int res;
660

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

    
665
    /* make signed (weird way) */
666
    if (unum == (uint64_t)-1)
667
        *num = INT64_MAX;
668
    else
669
        *num = unum - ((1LL << ((7 * res) - 1)) - 1);
670

    
671
    return res;
672
}
673

    
674
/*
675
 * Read an EBML header.
676
 * 0 is success, < 0 is failure.
677
 */
678

    
679
static int
680
ebml_read_header (MatroskaDemuxContext *matroska,
681
                  char                **doctype,
682
                  int                  *version)
683
{
684
    uint32_t id;
685
    int level_up, res = 0;
686

    
687
    /* default init */
688
    if (doctype)
689
        *doctype = NULL;
690
    if (version)
691
        *version = 1;
692

    
693
    if (!(id = ebml_peek_id(matroska, &level_up)) ||
694
        level_up != 0 || id != EBML_ID_HEADER) {
695
        av_log(matroska->ctx, AV_LOG_ERROR,
696
               "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
697
        return AVERROR_INVALIDDATA;
698
    }
699
    if ((res = ebml_read_master(matroska, &id)) < 0)
700
        return res;
701

    
702
    while (res == 0) {
703
        if (!(id = ebml_peek_id(matroska, &level_up)))
704
            return AVERROR(EIO);
705

    
706
        /* end-of-header */
707
        if (level_up)
708
            break;
709

    
710
        switch (id) {
711
            /* is our read version uptodate? */
712
            case EBML_ID_EBMLREADVERSION: {
713
                uint64_t num;
714

    
715
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
716
                    return res;
717
                if (num > EBML_VERSION) {
718
                    av_log(matroska->ctx, AV_LOG_ERROR,
719
                           "EBML version %"PRIu64" (> %d) is not supported\n",
720
                           num, EBML_VERSION);
721
                    return AVERROR_INVALIDDATA;
722
                }
723
                break;
724
            }
725

    
726
            /* we only handle 8 byte lengths at max */
727
            case EBML_ID_EBMLMAXSIZELENGTH: {
728
                uint64_t num;
729

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

    
741
            /* we handle 4 byte IDs at max */
742
            case EBML_ID_EBMLMAXIDLENGTH: {
743
                uint64_t num;
744

    
745
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
746
                    return res;
747
                if (num > sizeof(uint32_t)) {
748
                    av_log(matroska->ctx, AV_LOG_ERROR,
749
                           "IDs of size %"PRIu64" (> %zu) not supported\n",
750
                            num, sizeof(uint32_t));
751
                    return AVERROR_INVALIDDATA;
752
                }
753
                break;
754
            }
755

    
756
            case EBML_ID_DOCTYPE: {
757
                char *text;
758

    
759
                if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
760
                    return res;
761
                if (doctype) {
762
                    if (*doctype)
763
                        av_free(*doctype);
764
                    *doctype = text;
765
                } else
766
                    av_free(text);
767
                break;
768
            }
769

    
770
            case EBML_ID_DOCTYPEREADVERSION: {
771
                uint64_t num;
772

    
773
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
774
                    return res;
775
                if (version)
776
                    *version = num;
777
                break;
778
            }
779

    
780
            default:
781
                av_log(matroska->ctx, AV_LOG_INFO,
782
                       "Unknown data type 0x%x in EBML header", id);
783
                /* pass-through */
784

    
785
            case EBML_ID_VOID:
786
            /* we ignore these two, as they don't tell us anything we
787
             * care about */
788
            case EBML_ID_EBMLVERSION:
789
            case EBML_ID_DOCTYPEVERSION:
790
                res = ebml_read_skip (matroska);
791
                break;
792
        }
793
    }
794

    
795
    return 0;
796
}
797

    
798

    
799
static int
800
matroska_find_track_by_num (MatroskaDemuxContext *matroska,
801
                            int                   num)
802
{
803
    int i;
804

    
805
    for (i = 0; i < matroska->num_tracks; i++)
806
        if (matroska->tracks[i]->num == num)
807
            return i;
808

    
809
    return -1;
810
}
811

    
812

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

    
818
static int
819
matroska_deliver_packet (MatroskaDemuxContext *matroska,
820
                         AVPacket             *pkt)
821
{
822
    if (matroska->num_packets > 0) {
823
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
824
        av_free(matroska->packets[0]);
825
        if (matroska->num_packets > 1) {
826
            memmove(&matroska->packets[0], &matroska->packets[1],
827
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
828
            matroska->packets =
829
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
830
                           sizeof(AVPacket *));
831
        } else {
832
            av_freep(&matroska->packets);
833
        }
834
        matroska->num_packets--;
835
        return 0;
836
    }
837

    
838
    return -1;
839
}
840

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

    
846
static void
847
matroska_queue_packet (MatroskaDemuxContext *matroska,
848
                       AVPacket             *pkt)
849
{
850
    matroska->packets =
851
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
852
                   sizeof(AVPacket *));
853
    matroska->packets[matroska->num_packets] = pkt;
854
    matroska->num_packets++;
855
}
856

    
857
/*
858
 * Free all packets in our internal queue.
859
 */
860
static void
861
matroska_clear_queue (MatroskaDemuxContext *matroska)
862
{
863
    if (matroska->packets) {
864
        int n;
865
        for (n = 0; n < matroska->num_packets; n++) {
866
            av_free_packet(matroska->packets[n]);
867
            av_free(matroska->packets[n]);
868
        }
869
        av_free(matroska->packets);
870
        matroska->packets = NULL;
871
        matroska->num_packets = 0;
872
    }
873
}
874

    
875

    
876
/*
877
 * Autodetecting...
878
 */
879

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

    
887
    /* ebml header? */
888
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
889
        return 0;
890

    
891
    /* length of header */
892
    total = p->buf[4];
893
    while (size <= 8 && !(total & len_mask)) {
894
        size++;
895
        len_mask >>= 1;
896
    }
897
    if (size > 8)
898
      return 0;
899
    total &= (len_mask - 1);
900
    while (n < size)
901
        total = (total << 8) | p->buf[4 + n++];
902

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

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

    
915
    return 0;
916
}
917

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

    
922
static int
923
matroska_parse_info (MatroskaDemuxContext *matroska)
924
{
925
    int res = 0;
926
    uint32_t id;
927

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

    
930
    while (res == 0) {
931
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
932
            res = AVERROR(EIO);
933
            break;
934
        } else if (matroska->level_up) {
935
            matroska->level_up--;
936
            break;
937
        }
938

    
939
        switch (id) {
940
            /* cluster timecode */
941
            case MATROSKA_ID_TIMECODESCALE: {
942
                uint64_t num;
943
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
944
                    break;
945
                matroska->time_scale = num;
946
                break;
947
            }
948

    
949
            case MATROSKA_ID_DURATION: {
950
                double num;
951
                if ((res = ebml_read_float(matroska, &id, &num)) < 0)
952
                    break;
953
                matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
954
                break;
955
            }
956

    
957
            case MATROSKA_ID_TITLE: {
958
                char *text;
959
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
960
                    break;
961
                strncpy(matroska->ctx->title, text,
962
                        sizeof(matroska->ctx->title)-1);
963
                av_free(text);
964
                break;
965
            }
966

    
967
            case MATROSKA_ID_WRITINGAPP: {
968
                char *text;
969
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
970
                    break;
971
                matroska->writing_app = text;
972
                break;
973
            }
974

    
975
            case MATROSKA_ID_MUXINGAPP: {
976
                char *text;
977
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
978
                    break;
979
                matroska->muxing_app = text;
980
                break;
981
            }
982

    
983
            case MATROSKA_ID_DATEUTC: {
984
                int64_t time;
985
                if ((res = ebml_read_date(matroska, &id, &time)) < 0)
986
                    break;
987
                matroska->created = time;
988
                break;
989
            }
990

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

    
996
            case EBML_ID_VOID:
997
                res = ebml_read_skip(matroska);
998
                break;
999
        }
1000

    
1001
        if (matroska->level_up) {
1002
            matroska->level_up--;
1003
            break;
1004
        }
1005
    }
1006

    
1007
    return res;
1008
}
1009

    
1010
static int
1011
matroska_add_stream (MatroskaDemuxContext *matroska)
1012
{
1013
    int res = 0;
1014
    uint32_t id;
1015
    MatroskaTrack *track;
1016

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

    
1019
    /* Allocate a generic track. As soon as we know its type we'll realloc. */
1020
    track = av_mallocz(MAX_TRACK_SIZE);
1021
    matroska->num_tracks++;
1022
    strcpy(track->language, "eng");
1023

    
1024
    /* start with the master */
1025
    if ((res = ebml_read_master(matroska, &id)) < 0)
1026
        return res;
1027

    
1028
    /* try reading the trackentry headers */
1029
    while (res == 0) {
1030
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1031
            res = AVERROR(EIO);
1032
            break;
1033
        } else if (matroska->level_up > 0) {
1034
            matroska->level_up--;
1035
            break;
1036
        }
1037

    
1038
        switch (id) {
1039
            /* track number (unique stream ID) */
1040
            case MATROSKA_ID_TRACKNUMBER: {
1041
                uint64_t num;
1042
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1043
                    break;
1044
                track->num = num;
1045
                break;
1046
            }
1047

    
1048
            /* track UID (unique identifier) */
1049
            case MATROSKA_ID_TRACKUID: {
1050
                uint64_t num;
1051
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1052
                    break;
1053
                track->uid = num;
1054
                break;
1055
            }
1056

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

    
1069
                switch (track->type) {
1070
                    case MATROSKA_TRACK_TYPE_VIDEO:
1071
                    case MATROSKA_TRACK_TYPE_AUDIO:
1072
                    case MATROSKA_TRACK_TYPE_SUBTITLE:
1073
                        break;
1074
                    case MATROSKA_TRACK_TYPE_COMPLEX:
1075
                    case MATROSKA_TRACK_TYPE_LOGO:
1076
                    case MATROSKA_TRACK_TYPE_CONTROL:
1077
                    default:
1078
                        av_log(matroska->ctx, AV_LOG_INFO,
1079
                               "Unknown or unsupported track type 0x%x\n",
1080
                               track->type);
1081
                        track->type = MATROSKA_TRACK_TYPE_NONE;
1082
                        break;
1083
                }
1084
                matroska->tracks[matroska->num_tracks - 1] = track;
1085
                break;
1086
            }
1087

    
1088
            /* tracktype specific stuff for video */
1089
            case MATROSKA_ID_TRACKVIDEO: {
1090
                MatroskaVideoTrack *videotrack;
1091
                if (!track->type)
1092
                    track->type = MATROSKA_TRACK_TYPE_VIDEO;
1093
                if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1094
                    av_log(matroska->ctx, AV_LOG_INFO,
1095
                           "video data in non-video track - ignoring\n");
1096
                    res = AVERROR_INVALIDDATA;
1097
                    break;
1098
                } else if ((res = ebml_read_master(matroska, &id)) < 0)
1099
                    break;
1100
                videotrack = (MatroskaVideoTrack *)track;
1101

    
1102
                while (res == 0) {
1103
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1104
                        res = AVERROR(EIO);
1105
                        break;
1106
                    } else if (matroska->level_up > 0) {
1107
                        matroska->level_up--;
1108
                        break;
1109
                    }
1110

    
1111
                    switch (id) {
1112
                        /* fixme, this should be one-up, but I get it here */
1113
                        case MATROSKA_ID_TRACKDEFAULTDURATION: {
1114
                            uint64_t num;
1115
                            if ((res = ebml_read_uint (matroska, &id,
1116
                                                       &num)) < 0)
1117
                                break;
1118
                            track->default_duration = num;
1119
                            break;
1120
                        }
1121

    
1122
                        /* video framerate */
1123
                        case MATROSKA_ID_VIDEOFRAMERATE: {
1124
                            double num;
1125
                            if ((res = ebml_read_float(matroska, &id,
1126
                                                       &num)) < 0)
1127
                                break;
1128
                            if (!track->default_duration)
1129
                                track->default_duration = 1000000000/num;
1130
                            break;
1131
                        }
1132

    
1133
                        /* width of the size to display the video at */
1134
                        case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1135
                            uint64_t num;
1136
                            if ((res = ebml_read_uint(matroska, &id,
1137
                                                      &num)) < 0)
1138
                                break;
1139
                            videotrack->display_width = num;
1140
                            break;
1141
                        }
1142

    
1143
                        /* height of the size to display the video at */
1144
                        case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1145
                            uint64_t num;
1146
                            if ((res = ebml_read_uint(matroska, &id,
1147
                                                      &num)) < 0)
1148
                                break;
1149
                            videotrack->display_height = num;
1150
                            break;
1151
                        }
1152

    
1153
                        /* width of the video in the file */
1154
                        case MATROSKA_ID_VIDEOPIXELWIDTH: {
1155
                            uint64_t num;
1156
                            if ((res = ebml_read_uint(matroska, &id,
1157
                                                      &num)) < 0)
1158
                                break;
1159
                            videotrack->pixel_width = num;
1160
                            break;
1161
                        }
1162

    
1163
                        /* height of the video in the file */
1164
                        case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1165
                            uint64_t num;
1166
                            if ((res = ebml_read_uint(matroska, &id,
1167
                                                      &num)) < 0)
1168
                                break;
1169
                            videotrack->pixel_height = num;
1170
                            break;
1171
                        }
1172

    
1173
                        /* whether the video is interlaced */
1174
                        case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1175
                            uint64_t num;
1176
                            if ((res = ebml_read_uint(matroska, &id,
1177
                                                      &num)) < 0)
1178
                                break;
1179
                            if (num)
1180
                                track->flags |=
1181
                                    MATROSKA_VIDEOTRACK_INTERLACED;
1182
                            else
1183
                                track->flags &=
1184
                                    ~MATROSKA_VIDEOTRACK_INTERLACED;
1185
                            break;
1186
                        }
1187

    
1188
                        /* stereo mode (whether the video has two streams,
1189
                         * where one is for the left eye and the other for
1190
                         * the right eye, which creates a 3D-like
1191
                         * effect) */
1192
                        case MATROSKA_ID_VIDEOSTEREOMODE: {
1193
                            uint64_t num;
1194
                            if ((res = ebml_read_uint(matroska, &id,
1195
                                                      &num)) < 0)
1196
                                break;
1197
                            if (num != MATROSKA_EYE_MODE_MONO &&
1198
                                num != MATROSKA_EYE_MODE_LEFT &&
1199
                                num != MATROSKA_EYE_MODE_RIGHT &&
1200
                                num != MATROSKA_EYE_MODE_BOTH) {
1201
                                av_log(matroska->ctx, AV_LOG_INFO,
1202
                                       "Ignoring unknown eye mode 0x%x\n",
1203
                                       (uint32_t) num);
1204
                                break;
1205
                            }
1206
                            videotrack->eye_mode = num;
1207
                            break;
1208
                        }
1209

    
1210
                        /* aspect ratio behaviour */
1211
                        case MATROSKA_ID_VIDEOASPECTRATIO: {
1212
                            uint64_t num;
1213
                            if ((res = ebml_read_uint(matroska, &id,
1214
                                                      &num)) < 0)
1215
                                break;
1216
                            if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1217
                                num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1218
                                num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1219
                                av_log(matroska->ctx, AV_LOG_INFO,
1220
                                       "Ignoring unknown aspect ratio 0x%x\n",
1221
                                       (uint32_t) num);
1222
                                break;
1223
                            }
1224
                            videotrack->ar_mode = num;
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 EBML_ID_VOID:
1246
                            res = ebml_read_skip(matroska);
1247
                            break;
1248
                    }
1249

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

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

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

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

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

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

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

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

    
1330
                        case EBML_ID_VOID:
1331
                            res = ebml_read_skip(matroska);
1332
                            break;
1333
                    }
1334

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

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

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

    
1363
                /* name of the codec */
1364
            case MATROSKA_ID_CODECNAME: {
1365
                char *text;
1366
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1367
                    break;
1368
                track->codec_name = text;
1369
                break;
1370
            }
1371

    
1372
                /* name of this track */
1373
            case MATROSKA_ID_TRACKNAME: {
1374
                char *text;
1375
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1376
                    break;
1377
                track->name = text;
1378
                break;
1379
            }
1380

    
1381
                /* language (matters for audio/subtitles, mostly) */
1382
            case MATROSKA_ID_TRACKLANGUAGE: {
1383
                char *text, *end;
1384
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1385
                    break;
1386
                if ((end = strchr(text, '-')))
1387
                    *end = '\0';
1388
                if (strlen(text) == 3)
1389
                    strcpy(track->language, text);
1390
                av_free(text);
1391
                break;
1392
            }
1393

    
1394
                /* whether this is actually used */
1395
            case MATROSKA_ID_TRACKFLAGENABLED: {
1396
                uint64_t num;
1397
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1398
                    break;
1399
                if (num)
1400
                    track->flags |= MATROSKA_TRACK_ENABLED;
1401
                else
1402
                    track->flags &= ~MATROSKA_TRACK_ENABLED;
1403
                break;
1404
            }
1405

    
1406
                /* whether it's the default for this track type */
1407
            case MATROSKA_ID_TRACKFLAGDEFAULT: {
1408
                uint64_t num;
1409
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1410
                    break;
1411
                if (num)
1412
                    track->flags |= MATROSKA_TRACK_DEFAULT;
1413
                else
1414
                    track->flags &= ~MATROSKA_TRACK_DEFAULT;
1415
                break;
1416
            }
1417

    
1418
                /* lacing (like MPEG, where blocks don't end/start on frame
1419
                 * boundaries) */
1420
            case MATROSKA_ID_TRACKFLAGLACING: {
1421
                uint64_t num;
1422
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1423
                    break;
1424
                if (num)
1425
                    track->flags |= MATROSKA_TRACK_LACING;
1426
                else
1427
                    track->flags &= ~MATROSKA_TRACK_LACING;
1428
                break;
1429
            }
1430

    
1431
                /* default length (in time) of one data block in this track */
1432
            case MATROSKA_ID_TRACKDEFAULTDURATION: {
1433
                uint64_t num;
1434
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1435
                    break;
1436
                track->default_duration = num;
1437
                break;
1438
            }
1439

    
1440
            case MATROSKA_ID_TRACKCONTENTENCODINGS: {
1441
                if ((res = ebml_read_master(matroska, &id)) < 0)
1442
                    break;
1443

    
1444
                while (res == 0) {
1445
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1446
                        res = AVERROR(EIO);
1447
                        break;
1448
                    } else if (matroska->level_up > 0) {
1449
                        matroska->level_up--;
1450
                        break;
1451
                    }
1452

    
1453
                    switch (id) {
1454
                        case MATROSKA_ID_TRACKCONTENTENCODING: {
1455
                            int encoding_scope = 1;
1456
                            if ((res = ebml_read_master(matroska, &id)) < 0)
1457
                                break;
1458

    
1459
                            while (res == 0) {
1460
                                if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1461
                                    res = AVERROR(EIO);
1462
                                    break;
1463
                                } else if (matroska->level_up > 0) {
1464
                                    matroska->level_up--;
1465
                                    break;
1466
                                }
1467

    
1468
                                switch (id) {
1469
                                    case MATROSKA_ID_ENCODINGSCOPE: {
1470
                                        uint64_t num;
1471
                                        if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1472
                                            break;
1473
                                        encoding_scope = num;
1474
                                        break;
1475
                                    }
1476

    
1477
                                    case MATROSKA_ID_ENCODINGTYPE: {
1478
                                        uint64_t num;
1479
                                        if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1480
                                            break;
1481
                                        if (num)
1482
                                            av_log(matroska->ctx, AV_LOG_ERROR,
1483
                                                   "Unsupported encoding type");
1484
                                        break;
1485
                                    }
1486

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

    
1491
                                        while (res == 0) {
1492
                                            if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1493
                                                res = AVERROR(EIO);
1494
                                                break;
1495
                                            } else if (matroska->level_up > 0) {
1496
                                                matroska->level_up--;
1497
                                                break;
1498
                                            }
1499

    
1500
                                            switch (id) {
1501
                                                case MATROSKA_ID_ENCODINGCOMPALGO: {
1502
                                                    uint64_t num;
1503
                                                    if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1504
                                                        break;
1505
                                                    if (num != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1506
#ifdef CONFIG_ZLIB
1507
                                                        num != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1508
#endif
1509
                                                        num != MATROSKA_TRACK_ENCODING_COMP_LZO)
1510
                                                        av_log(matroska->ctx, AV_LOG_ERROR,
1511
                                                               "Unsupported compression algo");
1512
                                                    track->encoding_algo = num;
1513
                                                    break;
1514
                                                }
1515

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

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

    
1532
                                                case EBML_ID_VOID:
1533
                                                    res = ebml_read_skip(matroska);
1534
                                                    break;
1535
                                            }
1536

    
1537
                                            if (matroska->level_up) {
1538
                                                matroska->level_up--;
1539
                                                break;
1540
                                            }
1541
                                        }
1542
                                        break;
1543
                                    }
1544

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

    
1551
                                    case EBML_ID_VOID:
1552
                                        res = ebml_read_skip(matroska);
1553
                                        break;
1554
                                }
1555

    
1556
                                if (matroska->level_up) {
1557
                                    matroska->level_up--;
1558
                                    break;
1559
                                }
1560
                            }
1561

    
1562
                            track->encoding_scope = encoding_scope;
1563
                            break;
1564
                        }
1565

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

    
1572
                        case EBML_ID_VOID:
1573
                            res = ebml_read_skip(matroska);
1574
                            break;
1575
                    }
1576

    
1577
                    if (matroska->level_up) {
1578
                        matroska->level_up--;
1579
                        break;
1580
                    }
1581
                }
1582
                break;
1583
            }
1584

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

    
1590
            case EBML_ID_VOID:
1591
            /* we ignore these because they're nothing useful. */
1592
            case MATROSKA_ID_CODECINFOURL:
1593
            case MATROSKA_ID_CODECDOWNLOADURL:
1594
            case MATROSKA_ID_TRACKMINCACHE:
1595
            case MATROSKA_ID_TRACKMAXCACHE:
1596
                res = ebml_read_skip(matroska);
1597
                break;
1598
        }
1599

    
1600
        if (matroska->level_up) {
1601
            matroska->level_up--;
1602
            break;
1603
        }
1604
    }
1605

    
1606
    return res;
1607
}
1608

    
1609
static int
1610
matroska_parse_tracks (MatroskaDemuxContext *matroska)
1611
{
1612
    int res = 0;
1613
    uint32_t id;
1614

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

    
1617
    while (res == 0) {
1618
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1619
            res = AVERROR(EIO);
1620
            break;
1621
        } else if (matroska->level_up) {
1622
            matroska->level_up--;
1623
            break;
1624
        }
1625

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

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

    
1637
            case EBML_ID_VOID:
1638
                res = ebml_read_skip(matroska);
1639
                break;
1640
        }
1641

    
1642
        if (matroska->level_up) {
1643
            matroska->level_up--;
1644
            break;
1645
        }
1646
    }
1647

    
1648
    return res;
1649
}
1650

    
1651
static int
1652
matroska_parse_index (MatroskaDemuxContext *matroska)
1653
{
1654
    int res = 0;
1655
    uint32_t id;
1656
    MatroskaDemuxIndex idx;
1657

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

    
1660
    while (res == 0) {
1661
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1662
            res = AVERROR(EIO);
1663
            break;
1664
        } else if (matroska->level_up) {
1665
            matroska->level_up--;
1666
            break;
1667
        }
1668

    
1669
        switch (id) {
1670
            /* one single index entry ('point') */
1671
            case MATROSKA_ID_POINTENTRY:
1672
                if ((res = ebml_read_master(matroska, &id)) < 0)
1673
                    break;
1674

    
1675
                /* in the end, we hope to fill one entry with a
1676
                 * timestamp, a file position and a tracknum */
1677
                idx.pos   = (uint64_t) -1;
1678
                idx.time  = (uint64_t) -1;
1679
                idx.track = (uint16_t) -1;
1680

    
1681
                while (res == 0) {
1682
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1683
                        res = AVERROR(EIO);
1684
                        break;
1685
                    } else if (matroska->level_up) {
1686
                        matroska->level_up--;
1687
                        break;
1688
                    }
1689

    
1690
                    switch (id) {
1691
                        /* one single index entry ('point') */
1692
                        case MATROSKA_ID_CUETIME: {
1693
                            uint64_t time;
1694
                            if ((res = ebml_read_uint(matroska, &id,
1695
                                                      &time)) < 0)
1696
                                break;
1697
                            idx.time = time * matroska->time_scale;
1698
                            break;
1699
                        }
1700

    
1701
                        /* position in the file + track to which it
1702
                         * belongs */
1703
                        case MATROSKA_ID_CUETRACKPOSITION:
1704
                            if ((res = ebml_read_master(matroska, &id)) < 0)
1705
                                break;
1706

    
1707
                            while (res == 0) {
1708
                                if (!(id = ebml_peek_id (matroska,
1709
                                                    &matroska->level_up))) {
1710
                                    res = AVERROR(EIO);
1711
                                    break;
1712
                                } else if (matroska->level_up) {
1713
                                    matroska->level_up--;
1714
                                    break;
1715
                                }
1716

    
1717
                                switch (id) {
1718
                                    /* track number */
1719
                                    case MATROSKA_ID_CUETRACK: {
1720
                                        uint64_t num;
1721
                                        if ((res = ebml_read_uint(matroska,
1722
                                                          &id, &num)) < 0)
1723
                                            break;
1724
                                        idx.track = num;
1725
                                        break;
1726
                                    }
1727

    
1728
                                        /* position in file */
1729
                                    case MATROSKA_ID_CUECLUSTERPOSITION: {
1730
                                        uint64_t num;
1731
                                        if ((res = ebml_read_uint(matroska,
1732
                                                          &id, &num)) < 0)
1733
                                            break;
1734
                                        idx.pos = num+matroska->segment_start;
1735
                                        break;
1736
                                    }
1737

    
1738
                                    default:
1739
                                        av_log(matroska->ctx, AV_LOG_INFO,
1740
                                               "Unknown entry 0x%x in "
1741
                                               "CuesTrackPositions\n", id);
1742
                                        /* fall-through */
1743

    
1744
                                    case EBML_ID_VOID:
1745
                                        res = ebml_read_skip(matroska);
1746
                                        break;
1747
                                }
1748

    
1749
                                if (matroska->level_up) {
1750
                                    matroska->level_up--;
1751
                                    break;
1752
                                }
1753
                            }
1754

    
1755
                            break;
1756

    
1757
                        default:
1758
                            av_log(matroska->ctx, AV_LOG_INFO,
1759
                                   "Unknown entry 0x%x in cuespoint "
1760
                                   "index\n", id);
1761
                            /* fall-through */
1762

    
1763
                        case EBML_ID_VOID:
1764
                            res = ebml_read_skip(matroska);
1765
                            break;
1766
                    }
1767

    
1768
                    if (matroska->level_up) {
1769
                        matroska->level_up--;
1770
                        break;
1771
                    }
1772
                }
1773

    
1774
                /* so let's see if we got what we wanted */
1775
                if (idx.pos   != (uint64_t) -1 &&
1776
                    idx.time  != (uint64_t) -1 &&
1777
                    idx.track != (uint16_t) -1) {
1778
                    if (matroska->num_indexes % 32 == 0) {
1779
                        /* re-allocate bigger index */
1780
                        matroska->index =
1781
                            av_realloc(matroska->index,
1782
                                       (matroska->num_indexes + 32) *
1783
                                       sizeof(MatroskaDemuxIndex));
1784
                    }
1785
                    matroska->index[matroska->num_indexes] = idx;
1786
                    matroska->num_indexes++;
1787
                }
1788
                break;
1789

    
1790
            default:
1791
                av_log(matroska->ctx, AV_LOG_INFO,
1792
                       "Unknown entry 0x%x in cues header\n", id);
1793
                /* fall-through */
1794

    
1795
            case EBML_ID_VOID:
1796
                res = ebml_read_skip(matroska);
1797
                break;
1798
        }
1799

    
1800
        if (matroska->level_up) {
1801
            matroska->level_up--;
1802
            break;
1803
        }
1804
    }
1805

    
1806
    return res;
1807
}
1808

    
1809
static int
1810
matroska_parse_metadata (MatroskaDemuxContext *matroska)
1811
{
1812
    int res = 0;
1813
    uint32_t id;
1814

    
1815
    while (res == 0) {
1816
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1817
            res = AVERROR(EIO);
1818
            break;
1819
        } else if (matroska->level_up) {
1820
            matroska->level_up--;
1821
            break;
1822
        }
1823

    
1824
        switch (id) {
1825
            /* Hm, this is unsupported... */
1826
            default:
1827
                av_log(matroska->ctx, AV_LOG_INFO,
1828
                       "Unknown entry 0x%x in metadata header\n", id);
1829
                /* fall-through */
1830

    
1831
            case EBML_ID_VOID:
1832
                res = ebml_read_skip(matroska);
1833
                break;
1834
        }
1835

    
1836
        if (matroska->level_up) {
1837
            matroska->level_up--;
1838
            break;
1839
        }
1840
    }
1841

    
1842
    return res;
1843
}
1844

    
1845
static int
1846
matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1847
{
1848
    int res = 0;
1849
    uint32_t id;
1850

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

    
1853
    while (res == 0) {
1854
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1855
            res = AVERROR(EIO);
1856
            break;
1857
        } else if (matroska->level_up) {
1858
            matroska->level_up--;
1859
            break;
1860
        }
1861

    
1862
        switch (id) {
1863
            case MATROSKA_ID_SEEKENTRY: {
1864
                uint32_t seek_id = 0, peek_id_cache = 0;
1865
                uint64_t seek_pos = (uint64_t) -1, t;
1866

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

    
1870
                while (res == 0) {
1871
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1872
                        res = AVERROR(EIO);
1873
                        break;
1874
                    } else if (matroska->level_up) {
1875
                        matroska->level_up--;
1876
                        break;
1877
                    }
1878

    
1879
                    switch (id) {
1880
                        case MATROSKA_ID_SEEKID:
1881
                            res = ebml_read_uint(matroska, &id, &t);
1882
                            seek_id = t;
1883
                            break;
1884

    
1885
                        case MATROSKA_ID_SEEKPOSITION:
1886
                            res = ebml_read_uint(matroska, &id, &seek_pos);
1887
                            break;
1888

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

    
1894
                        case EBML_ID_VOID:
1895
                            res = ebml_read_skip(matroska);
1896
                            break;
1897
                    }
1898

    
1899
                    if (matroska->level_up) {
1900
                        matroska->level_up--;
1901
                        break;
1902
                    }
1903
                }
1904

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

    
1912
                switch (seek_id) {
1913
                    case MATROSKA_ID_CUES:
1914
                    case MATROSKA_ID_TAGS: {
1915
                        uint32_t level_up = matroska->level_up;
1916
                        offset_t before_pos;
1917
                        uint64_t length;
1918
                        MatroskaLevel level;
1919

    
1920
                        /* remember the peeked ID and the current position */
1921
                        peek_id_cache = matroska->peek_id;
1922
                        before_pos = url_ftell(matroska->ctx->pb);
1923

    
1924
                        /* seek */
1925
                        if ((res = ebml_read_seek(matroska, seek_pos +
1926
                                               matroska->segment_start)) < 0)
1927
                            goto finish;
1928

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

    
1938
                        level.start = 0;
1939
                        level.length = (uint64_t)-1;
1940
                        matroska->levels[matroska->num_levels] = level;
1941
                        matroska->num_levels++;
1942

    
1943
                        /* check ID */
1944
                        if (!(id = ebml_peek_id (matroska,
1945
                                                 &matroska->level_up)))
1946
                            goto finish;
1947
                        if (id != seek_id) {
1948
                            av_log(matroska->ctx, AV_LOG_INFO,
1949
                                   "We looked for ID=0x%x but got "
1950
                                   "ID=0x%x (pos=%"PRIu64")",
1951
                                   seek_id, id, seek_pos +
1952
                                   matroska->segment_start);
1953
                            goto finish;
1954
                        }
1955

    
1956
                        /* read master + parse */
1957
                        if ((res = ebml_read_master(matroska, &id)) < 0)
1958
                            goto finish;
1959
                        switch (id) {
1960
                            case MATROSKA_ID_CUES:
1961
                                if (!(res = matroska_parse_index(matroska)) ||
1962
                                    url_feof(matroska->ctx->pb)) {
1963
                                    matroska->index_parsed = 1;
1964
                                    res = 0;
1965
                                }
1966
                                break;
1967
                            case MATROSKA_ID_TAGS:
1968
                                if (!(res = matroska_parse_metadata(matroska)) ||
1969
                                   url_feof(matroska->ctx->pb)) {
1970
                                    matroska->metadata_parsed = 1;
1971
                                    res = 0;
1972
                                }
1973
                                break;
1974
                        }
1975

    
1976
                    finish:
1977
                        /* remove dummy level */
1978
                        while (matroska->num_levels) {
1979
                            matroska->num_levels--;
1980
                            length =
1981
                                matroska->levels[matroska->num_levels].length;
1982
                            if (length == (uint64_t)-1)
1983
                                break;
1984
                        }
1985

    
1986
                        /* seek back */
1987
                        if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1988
                            return res;
1989
                        matroska->peek_id = peek_id_cache;
1990
                        matroska->level_up = level_up;
1991
                        break;
1992
                    }
1993

    
1994
                    default:
1995
                        av_log(matroska->ctx, AV_LOG_INFO,
1996
                               "Ignoring seekhead entry for ID=0x%x\n",
1997
                               seek_id);
1998
                        break;
1999
                }
2000

    
2001
                break;
2002
            }
2003

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

    
2009
            case EBML_ID_VOID:
2010
                res = ebml_read_skip(matroska);
2011
                break;
2012
        }
2013

    
2014
        if (matroska->level_up) {
2015
            matroska->level_up--;
2016
            break;
2017
        }
2018
    }
2019

    
2020
    return res;
2021
}
2022

    
2023
static int
2024
matroska_parse_attachments(AVFormatContext *s)
2025
{
2026
    MatroskaDemuxContext *matroska = s->priv_data;
2027
    int res = 0;
2028
    uint32_t id;
2029

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

    
2032
    while (res == 0) {
2033
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2034
            res = AVERROR(EIO);
2035
            break;
2036
        } else if (matroska->level_up) {
2037
            matroska->level_up--;
2038
            break;
2039
        }
2040

    
2041
        switch (id) {
2042
        case MATROSKA_ID_ATTACHEDFILE: {
2043
            char* name = NULL;
2044
            char* mime = NULL;
2045
            uint8_t* data = NULL;
2046
            int i, data_size = 0;
2047
            AVStream *st;
2048

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

    
2052
            while (res == 0) {
2053
                if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2054
                    res = AVERROR(EIO);
2055
                    break;
2056
                } else if (matroska->level_up) {
2057
                    matroska->level_up--;
2058
                    break;
2059
                }
2060

    
2061
                switch (id) {
2062
                case MATROSKA_ID_FILENAME:
2063
                    res = ebml_read_utf8 (matroska, &id, &name);
2064
                    break;
2065

    
2066
                case MATROSKA_ID_FILEMIMETYPE:
2067
                    res = ebml_read_ascii (matroska, &id, &mime);
2068
                    break;
2069

    
2070
                case MATROSKA_ID_FILEDATA:
2071
                    res = ebml_read_binary(matroska, &id, &data, &data_size);
2072
                    break;
2073

    
2074
                default:
2075
                    av_log(matroska->ctx, AV_LOG_INFO,
2076
                           "Unknown attachedfile ID 0x%x\n", id);
2077
                case EBML_ID_VOID:
2078
                    res = ebml_read_skip(matroska);
2079
                    break;
2080
                }
2081

    
2082
                if (matroska->level_up) {
2083
                    matroska->level_up--;
2084
                    break;
2085
                }
2086
            }
2087

    
2088
            if (!(name && mime && data && data_size > 0)) {
2089
                av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
2090
                break;
2091
            }
2092

    
2093
            st = av_new_stream(s, matroska->num_streams++);
2094
            if (st == NULL)
2095
                return AVERROR(ENOMEM);
2096
            st->filename = av_strdup(name);
2097
            st->codec->codec_id = CODEC_ID_NONE;
2098
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
2099
            st->codec->extradata = av_malloc(data_size);
2100
            if(st->codec->extradata == NULL)
2101
                return AVERROR(ENOMEM);
2102
            st->codec->extradata_size = data_size;
2103
            memcpy(st->codec->extradata, data, data_size);
2104

    
2105
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
2106
                if (!strncmp(ff_mkv_mime_tags[i].str, mime,
2107
                             strlen(ff_mkv_mime_tags[i].str))) {
2108
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
2109
                    break;
2110
                }
2111
            }
2112

    
2113
            av_log(matroska->ctx, AV_LOG_DEBUG, "new attachment: %s, %s, size %d \n", name, mime, data_size);
2114
            break;
2115
        }
2116

    
2117
        default:
2118
            av_log(matroska->ctx, AV_LOG_INFO,
2119
                   "Unknown attachments ID 0x%x\n", id);
2120
            /* fall-through */
2121

    
2122
        case EBML_ID_VOID:
2123
            res = ebml_read_skip(matroska);
2124
            break;
2125
        }
2126

    
2127
        if (matroska->level_up) {
2128
            matroska->level_up--;
2129
            break;
2130
        }
2131
    }
2132

    
2133
    return res;
2134
}
2135

    
2136
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
2137

    
2138
static int
2139
matroska_aac_profile (char *codec_id)
2140
{
2141
    static const char *aac_profiles[] = {
2142
        "MAIN", "LC", "SSR"
2143
    };
2144
    int profile;
2145

    
2146
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2147
        if (strstr(codec_id, aac_profiles[profile]))
2148
            break;
2149
    return profile + 1;
2150
}
2151

    
2152
static int
2153
matroska_aac_sri (int samplerate)
2154
{
2155
    int sri;
2156

    
2157
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
2158
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
2159
            break;
2160
    return sri;
2161
}
2162

    
2163
static int
2164
matroska_read_header (AVFormatContext    *s,
2165
                      AVFormatParameters *ap)
2166
{
2167
    MatroskaDemuxContext *matroska = s->priv_data;
2168
    char *doctype;
2169
    int version, last_level, res = 0;
2170
    uint32_t id;
2171

    
2172
    matroska->ctx = s;
2173

    
2174
    /* First read the EBML header. */
2175
    doctype = NULL;
2176
    if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2177
        return res;
2178
    if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2179
        av_log(matroska->ctx, AV_LOG_ERROR,
2180
               "Wrong EBML doctype ('%s' != 'matroska').\n",
2181
               doctype ? doctype : "(none)");
2182
        if (doctype)
2183
            av_free(doctype);
2184
        return AVERROR_NOFMT;
2185
    }
2186
    av_free(doctype);
2187
    if (version > 2) {
2188
        av_log(matroska->ctx, AV_LOG_ERROR,
2189
               "Matroska demuxer version 2 too old for file version %d\n",
2190
               version);
2191
        return AVERROR_NOFMT;
2192
    }
2193

    
2194
    /* The next thing is a segment. */
2195
    while (1) {
2196
        if (!(id = ebml_peek_id(matroska, &last_level)))
2197
            return AVERROR(EIO);
2198
        if (id == MATROSKA_ID_SEGMENT)
2199
            break;
2200

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

    
2209
    /* We now have a Matroska segment.
2210
     * Seeks are from the beginning of the segment,
2211
     * after the segment ID/length. */
2212
    if ((res = ebml_read_master(matroska, &id)) < 0)
2213
        return res;
2214
    matroska->segment_start = url_ftell(s->pb);
2215

    
2216
    matroska->time_scale = 1000000;
2217
    /* we've found our segment, start reading the different contents in here */
2218
    while (res == 0) {
2219
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2220
            res = AVERROR(EIO);
2221
            break;
2222
        } else if (matroska->level_up) {
2223
            matroska->level_up--;
2224
            break;
2225
        }
2226

    
2227
        switch (id) {
2228
            /* stream info */
2229
            case MATROSKA_ID_INFO: {
2230
                if ((res = ebml_read_master(matroska, &id)) < 0)
2231
                    break;
2232
                res = matroska_parse_info(matroska);
2233
                break;
2234
            }
2235

    
2236
            /* track info headers */
2237
            case MATROSKA_ID_TRACKS: {
2238
                if ((res = ebml_read_master(matroska, &id)) < 0)
2239
                    break;
2240
                res = matroska_parse_tracks(matroska);
2241
                break;
2242
            }
2243

    
2244
            /* stream index */
2245
            case MATROSKA_ID_CUES: {
2246
                if (!matroska->index_parsed) {
2247
                    if ((res = ebml_read_master(matroska, &id)) < 0)
2248
                        break;
2249
                    res = matroska_parse_index(matroska);
2250
                } else
2251
                    res = ebml_read_skip(matroska);
2252
                break;
2253
            }
2254

    
2255
            /* metadata */
2256
            case MATROSKA_ID_TAGS: {
2257
                if (!matroska->metadata_parsed) {
2258
                    if ((res = ebml_read_master(matroska, &id)) < 0)
2259
                        break;
2260
                    res = matroska_parse_metadata(matroska);
2261
                } else
2262
                    res = ebml_read_skip(matroska);
2263
                break;
2264
            }
2265

    
2266
            /* file index (if seekable, seek to Cues/Tags to parse it) */
2267
            case MATROSKA_ID_SEEKHEAD: {
2268
                if ((res = ebml_read_master(matroska, &id)) < 0)
2269
                    break;
2270
                res = matroska_parse_seekhead(matroska);
2271
                break;
2272
            }
2273

    
2274
            case MATROSKA_ID_ATTACHMENTS: {
2275
                if ((res = ebml_read_master(matroska, &id)) < 0)
2276
                    break;
2277
                res = matroska_parse_attachments(s);
2278
                break;
2279
            }
2280

    
2281
            case MATROSKA_ID_CLUSTER: {
2282
                /* Do not read the master - this will be done in the next
2283
                 * call to matroska_read_packet. */
2284
                res = 1;
2285
                break;
2286
            }
2287

    
2288
            default:
2289
                av_log(matroska->ctx, AV_LOG_INFO,
2290
                       "Unknown matroska file header ID 0x%x\n", id);
2291
            /* fall-through */
2292

    
2293
            case EBML_ID_VOID:
2294
                res = ebml_read_skip(matroska);
2295
                break;
2296
        }
2297

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

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

    
2310
        for (i = 0; i < matroska->num_tracks; i++) {
2311
            enum CodecID codec_id = CODEC_ID_NONE;
2312
            uint8_t *extradata = NULL;
2313
            int extradata_size = 0;
2314
            int extradata_offset = 0;
2315
            track = matroska->tracks[i];
2316
            track->stream_index = -1;
2317

    
2318
            /* Apply some sanity checks. */
2319
            if (track->codec_id == NULL)
2320
                continue;
2321

    
2322
            for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
2323
                if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2324
                            strlen(ff_mkv_codec_tags[j].str))){
2325
                    codec_id= ff_mkv_codec_tags[j].id;
2326
                    break;
2327
                }
2328
            }
2329

    
2330
            /* Set the FourCC from the CodecID. */
2331
            /* This is the MS compatibility mode which stores a
2332
             * BITMAPINFOHEADER in the CodecPrivate. */
2333
            if (!strcmp(track->codec_id,
2334
                        MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2335
                (track->codec_priv_size >= 40) &&
2336
                (track->codec_priv != NULL)) {
2337
                MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2338

    
2339
                /* Offset of biCompression. Stored in LE. */
2340
                vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2341
                codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2342

    
2343
            }
2344

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

    
2353
                /* Offset of wFormatTag. Stored in LE. */
2354
                tag = AV_RL16(track->codec_priv);
2355
                codec_id = codec_get_id(codec_wav_tags, tag);
2356

    
2357
            }
2358

    
2359
            else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2360
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2361
                int profile = matroska_aac_profile(track->codec_id);
2362
                int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2363
                extradata = av_malloc(5);
2364
                if (extradata == NULL)
2365
                    return AVERROR(ENOMEM);
2366
                extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2367
                extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2368
                if (strstr(track->codec_id, "SBR")) {
2369
                    sri = matroska_aac_sri(audiotrack->samplerate);
2370
                    extradata[2] = 0x56;
2371
                    extradata[3] = 0xE5;
2372
                    extradata[4] = 0x80 | (sri<<3);
2373
                    extradata_size = 5;
2374
                } else {
2375
                    extradata_size = 2;
2376
                }
2377
            }
2378

    
2379
            else if (codec_id == CODEC_ID_TTA) {
2380
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2381
                ByteIOContext b;
2382
                extradata_size = 30;
2383
                extradata = av_mallocz(extradata_size);
2384
                if (extradata == NULL)
2385
                    return AVERROR(ENOMEM);
2386
                init_put_byte(&b, extradata, extradata_size, 1,
2387
                              NULL, NULL, NULL, NULL);
2388
                put_buffer(&b, "TTA1", 4);
2389
                put_le16(&b, 1);
2390
                put_le16(&b, audiotrack->channels);
2391
                put_le16(&b, audiotrack->bitdepth);
2392
                put_le32(&b, audiotrack->samplerate);
2393
                put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2394
            }
2395

    
2396
            else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2397
                     codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2398
                extradata_offset = 26;
2399
                track->codec_priv_size -= extradata_offset;
2400
            }
2401

    
2402
            else if (codec_id == CODEC_ID_RA_144) {
2403
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2404
                audiotrack->samplerate = 8000;
2405
                audiotrack->channels = 1;
2406
            }
2407

    
2408
            else if (codec_id == CODEC_ID_RA_288 ||
2409
                     codec_id == CODEC_ID_COOK ||
2410
                     codec_id == CODEC_ID_ATRAC3) {
2411
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2412
                ByteIOContext b;
2413

    
2414
                init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2415
                              NULL, NULL, NULL, NULL);
2416
                url_fskip(&b, 24);
2417
                audiotrack->coded_framesize = get_be32(&b);
2418
                url_fskip(&b, 12);
2419
                audiotrack->sub_packet_h    = get_be16(&b);
2420
                audiotrack->frame_size      = get_be16(&b);
2421
                audiotrack->sub_packet_size = get_be16(&b);
2422
                audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2423
                if (codec_id == CODEC_ID_RA_288) {
2424
                    audiotrack->block_align = audiotrack->coded_framesize;
2425
                    track->codec_priv_size = 0;
2426
                } else {
2427
                    audiotrack->block_align = audiotrack->sub_packet_size;
2428
                    extradata_offset = 78;
2429
                    track->codec_priv_size -= extradata_offset;
2430
                }
2431
            }
2432

    
2433
            if (codec_id == CODEC_ID_NONE) {
2434
                av_log(matroska->ctx, AV_LOG_INFO,
2435
                       "Unknown/unsupported CodecID %s.\n",
2436
                       track->codec_id);
2437
            }
2438

    
2439
            track->stream_index = matroska->num_streams;
2440

    
2441
            matroska->num_streams++;
2442
            st = av_new_stream(s, track->stream_index);
2443
            if (st == NULL)
2444
                return AVERROR(ENOMEM);
2445
            av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2446

    
2447
            st->codec->codec_id = codec_id;
2448
            st->start_time = 0;
2449
            if (strcmp(track->language, "und"))
2450
                strcpy(st->language, track->language);
2451

    
2452
            if (track->flags & MATROSKA_TRACK_DEFAULT)
2453
                st->disposition |= AV_DISPOSITION_DEFAULT;
2454

    
2455
            if (track->default_duration)
2456
                av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2457
                          track->default_duration, 1000000000, 30000);
2458

    
2459
            if(extradata){
2460
                st->codec->extradata = extradata;
2461
                st->codec->extradata_size = extradata_size;
2462
            } else if(track->codec_priv && track->codec_priv_size > 0){
2463
                st->codec->extradata = av_malloc(track->codec_priv_size);
2464
                if(st->codec->extradata == NULL)
2465
                    return AVERROR(ENOMEM);
2466
                st->codec->extradata_size = track->codec_priv_size;
2467
                memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2468
                       track->codec_priv_size);
2469
            }
2470

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

    
2474
                st->codec->codec_type = CODEC_TYPE_VIDEO;
2475
                st->codec->codec_tag = videotrack->fourcc;
2476
                st->codec->width = videotrack->pixel_width;
2477
                st->codec->height = videotrack->pixel_height;
2478
                if (videotrack->display_width == 0)
2479
                    videotrack->display_width= videotrack->pixel_width;
2480
                if (videotrack->display_height == 0)
2481
                    videotrack->display_height= videotrack->pixel_height;
2482
                av_reduce(&st->codec->sample_aspect_ratio.num,
2483
                          &st->codec->sample_aspect_ratio.den,
2484
                          st->codec->height * videotrack->display_width,
2485
                          st->codec-> width * videotrack->display_height,
2486
                          255);
2487
                st->need_parsing = AVSTREAM_PARSE_HEADERS;
2488
            } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2489
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2490

    
2491
                st->codec->codec_type = CODEC_TYPE_AUDIO;
2492
                st->codec->sample_rate = audiotrack->samplerate;
2493
                st->codec->channels = audiotrack->channels;
2494
                st->codec->block_align = audiotrack->block_align;
2495
            } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2496
                st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2497
            }
2498

    
2499
            /* What do we do with private data? E.g. for Vorbis. */
2500
        }
2501
        res = 0;
2502
    }
2503

    
2504
    if (matroska->index_parsed) {
2505
        int i, track, stream;
2506
        for (i=0; i<matroska->num_indexes; i++) {
2507
            MatroskaDemuxIndex *idx = &matroska->index[i];
2508
            track = matroska_find_track_by_num(matroska, idx->track);
2509
            if (track < 0)  continue;
2510
            stream = matroska->tracks[track]->stream_index;
2511
            if (stream >= 0 && stream < matroska->ctx->nb_streams)
2512
                av_add_index_entry(matroska->ctx->streams[stream],
2513
                                   idx->pos, idx->time/matroska->time_scale,
2514
                                   0, 0, AVINDEX_KEYFRAME);
2515
        }
2516
    }
2517

    
2518
    return res;
2519
}
2520

    
2521
static int
2522
matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2523
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
2524
                     int is_keyframe, int is_bframe)
2525
{
2526
    int res = 0;
2527
    int track;
2528
    AVStream *st;
2529
    AVPacket *pkt;
2530
    uint8_t *origdata = data;
2531
    int16_t block_time;
2532
    uint32_t *lace_size = NULL;
2533
    int n, flags, laces = 0;
2534
    uint64_t num;
2535
    int stream_index;
2536

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

    
2546
    /* fetch track from num */
2547
    track = matroska_find_track_by_num(matroska, num);
2548
    if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2549
        av_log(matroska->ctx, AV_LOG_INFO,
2550
               "Invalid stream %d or size %u\n", track, size);
2551
        av_free(origdata);
2552
        return res;
2553
    }
2554
    stream_index = matroska->tracks[track]->stream_index;
2555
    if (stream_index < 0 || stream_index >= matroska->ctx->nb_streams) {
2556
        av_free(origdata);
2557
        return res;
2558
    }
2559
    st = matroska->ctx->streams[stream_index];
2560
    if (st->discard >= AVDISCARD_ALL) {
2561
        av_free(origdata);
2562
        return res;
2563
    }
2564
    if (duration == AV_NOPTS_VALUE)
2565
        duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2566

    
2567
    /* block_time (relative to cluster time) */
2568
    block_time = AV_RB16(data);
2569
    data += 2;
2570
    flags = *data++;
2571
    size -= 3;
2572
    if (is_keyframe == -1)
2573
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
2574

    
2575
    if (matroska->skip_to_keyframe) {
2576
        if (!is_keyframe || st != matroska->skip_to_stream) {
2577
            av_free(origdata);
2578
            return res;
2579
        }
2580
        matroska->skip_to_keyframe = 0;
2581
    }
2582

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

    
2590
        case 0x1: /* xiph lacing */
2591
        case 0x2: /* fixed-size lacing */
2592
        case 0x3: /* EBML lacing */
2593
            if (size == 0) {
2594
                res = -1;
2595
                break;
2596
            }
2597
            laces = (*data) + 1;
2598
            data += 1;
2599
            size -= 1;
2600
            lace_size = av_mallocz(laces * sizeof(int));
2601

    
2602
            switch ((flags & 0x06) >> 1) {
2603
                case 0x1: /* xiph lacing */ {
2604
                    uint8_t temp;
2605
                    uint32_t total = 0;
2606
                    for (n = 0; res == 0 && n < laces - 1; n++) {
2607
                        while (1) {
2608
                            if (size == 0) {
2609
                                res = -1;
2610
                                break;
2611
                            }
2612
                            temp = *data;
2613
                            lace_size[n] += temp;
2614
                            data += 1;
2615
                            size -= 1;
2616
                            if (temp != 0xff)
2617
                                break;
2618
                        }
2619
                        total += lace_size[n];
2620
                    }
2621
                    lace_size[n] = size - total;
2622
                    break;
2623
                }
2624

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

    
2630
                case 0x3: /* EBML lacing */ {
2631
                    uint32_t total;
2632
                    n = matroska_ebmlnum_uint(data, size, &num);
2633
                    if (n < 0) {
2634
                        av_log(matroska->ctx, AV_LOG_INFO,
2635
                               "EBML block data error\n");
2636
                        break;
2637
                    }
2638
                    data += n;
2639
                    size -= n;
2640
                    total = lace_size[0] = num;
2641
                    for (n = 1; res == 0 && n < laces - 1; n++) {
2642
                        int64_t snum;
2643
                        int r;
2644
                        r = matroska_ebmlnum_sint (data, size, &snum);
2645
                        if (r < 0) {
2646
                            av_log(matroska->ctx, AV_LOG_INFO,
2647
                                   "EBML block data error\n");
2648
                            break;
2649
                        }
2650
                        data += r;
2651
                        size -= r;
2652
                        lace_size[n] = lace_size[n - 1] + snum;
2653
                        total += lace_size[n];
2654
                    }
2655
                    lace_size[n] = size - total;
2656
                    break;
2657
                }
2658
            }
2659
            break;
2660
    }
2661

    
2662
    if (res == 0) {
2663
        uint64_t timecode = AV_NOPTS_VALUE;
2664

    
2665
        if (cluster_time != (uint64_t)-1
2666
            && (block_time >= 0 || cluster_time >= -block_time))
2667
            timecode = cluster_time + block_time;
2668

    
2669
        for (n = 0; n < laces; n++) {
2670
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
2671
                st->codec->codec_id == CODEC_ID_COOK ||
2672
                st->codec->codec_id == CODEC_ID_ATRAC3) {
2673
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2674
                int a = st->codec->block_align;
2675
                int sps = audiotrack->sub_packet_size;
2676
                int cfs = audiotrack->coded_framesize;
2677
                int h = audiotrack->sub_packet_h;
2678
                int y = audiotrack->sub_packet_cnt;
2679
                int w = audiotrack->frame_size;
2680
                int x;
2681

    
2682
                if (!audiotrack->pkt_cnt) {
2683
                    if (st->codec->codec_id == CODEC_ID_RA_288)
2684
                        for (x=0; x<h/2; x++)
2685
                            memcpy(audiotrack->buf+x*2*w+y*cfs,
2686
                                   data+x*cfs, cfs);
2687
                    else
2688
                        for (x=0; x<w/sps; x++)
2689
                            memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2690

    
2691
                    if (++audiotrack->sub_packet_cnt >= h) {
2692
                        audiotrack->sub_packet_cnt = 0;
2693
                        audiotrack->pkt_cnt = h*w / a;
2694
                    }
2695
                }
2696
                while (audiotrack->pkt_cnt) {
2697
                    pkt = av_mallocz(sizeof(AVPacket));
2698
                    av_new_packet(pkt, a);
2699
                    memcpy(pkt->data, audiotrack->buf
2700
                           + a * (h*w / a - audiotrack->pkt_cnt--), a);
2701
                    pkt->pos = pos;
2702
                    pkt->stream_index = stream_index;
2703
                    matroska_queue_packet(matroska, pkt);
2704
                }
2705
            } else {
2706
                int result, offset = 0, ilen, olen, pkt_size = lace_size[n];
2707
                uint8_t *pkt_data = data;
2708

    
2709
                if (matroska->tracks[track]->encoding_scope & 1) {
2710
                    switch (matroska->tracks[track]->encoding_algo) {
2711
                    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
2712
                        offset = matroska->tracks[track]->encoding_settings_len;
2713
                        break;
2714
                    case MATROSKA_TRACK_ENCODING_COMP_LZO:
2715
                        pkt_data = NULL;
2716
                        do {
2717
                            ilen = lace_size[n];
2718
                            olen = pkt_size *= 3;
2719
                            pkt_data = av_realloc(pkt_data,
2720
                                                  pkt_size+LZO_OUTPUT_PADDING);
2721
                            result = lzo1x_decode(pkt_data, &olen, data, &ilen);
2722
                        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
2723
                        if (result) {
2724
                            av_free(pkt_data);
2725
                            continue;
2726
                        }
2727
                        pkt_size -= olen;
2728
                        break;
2729
#ifdef CONFIG_ZLIB
2730
                    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
2731
                        z_stream zstream = {0};
2732
                        pkt_data = NULL;
2733
                        if (inflateInit(&zstream) != Z_OK)
2734
                            continue;
2735
                        zstream.next_in = data;
2736
                        zstream.avail_in = lace_size[n];
2737
                        do {
2738
                            pkt_size *= 3;
2739
                            pkt_data = av_realloc(pkt_data, pkt_size);
2740
                            zstream.avail_out = pkt_size - zstream.total_out;
2741
                            zstream.next_out = pkt_data + zstream.total_out;
2742
                            result = inflate(&zstream, Z_NO_FLUSH);
2743
                        } while (result==Z_OK && pkt_size<10000000);
2744
                        pkt_size = zstream.total_out;
2745
                        inflateEnd(&zstream);
2746
                        if (result != Z_STREAM_END) {
2747
                            av_free(pkt_data);
2748
                            continue;
2749
                        }
2750
                        break;
2751
                    }
2752
#endif
2753
                    }
2754
                }
2755

    
2756
                pkt = av_mallocz(sizeof(AVPacket));
2757
                /* XXX: prevent data copy... */
2758
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
2759
                    res = AVERROR(ENOMEM);
2760
                    n = laces-1;
2761
                    break;
2762
                }
2763
                if (offset)
2764
                    memcpy (pkt->data, matroska->tracks[track]->encoding_settings, offset);
2765
                memcpy (pkt->data+offset, pkt_data, pkt_size);
2766

    
2767
                if (n == 0)
2768
                    pkt->flags = is_keyframe;
2769
                pkt->stream_index = stream_index;
2770

    
2771
                pkt->pts = timecode;
2772
                pkt->pos = pos;
2773
                pkt->duration = duration;
2774

    
2775
                matroska_queue_packet(matroska, pkt);
2776
            }
2777

    
2778
            if (timecode != AV_NOPTS_VALUE)
2779
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2780
            data += lace_size[n];
2781
        }
2782
    }
2783

    
2784
    av_free(lace_size);
2785
    av_free(origdata);
2786
    return res;
2787
}
2788

    
2789
static int
2790
matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2791
                           uint64_t              cluster_time)
2792
{
2793
    int res = 0;
2794
    uint32_t id;
2795
    int is_bframe = 0;
2796
    int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2797
    uint64_t duration = AV_NOPTS_VALUE;
2798
    uint8_t *data;
2799
    int size = 0;
2800
    int64_t pos = 0;
2801

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

    
2804
    while (res == 0) {
2805
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2806
            res = AVERROR(EIO);
2807
            break;
2808
        } else if (matroska->level_up) {
2809
            matroska->level_up--;
2810
            break;
2811
        }
2812

    
2813
        switch (id) {
2814
            /* one block inside the group. Note, block parsing is one
2815
             * of the harder things, so this code is a bit complicated.
2816
             * See http://www.matroska.org/ for documentation. */
2817
            case MATROSKA_ID_BLOCK: {
2818
                pos = url_ftell(matroska->ctx->pb);
2819
                res = ebml_read_binary(matroska, &id, &data, &size);
2820
                break;
2821
            }
2822

    
2823
            case MATROSKA_ID_BLOCKDURATION: {
2824
                if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2825
                    break;
2826
                break;
2827
            }
2828

    
2829
            case MATROSKA_ID_BLOCKREFERENCE: {
2830
                int64_t num;
2831
                /* We've found a reference, so not even the first frame in
2832
                 * the lace is a key frame. */
2833
                is_keyframe = 0;
2834
                if (last_num_packets != matroska->num_packets)
2835
                    matroska->packets[last_num_packets]->flags = 0;
2836
                if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2837
                    break;
2838
                if (num > 0)
2839
                    is_bframe = 1;
2840
                break;
2841
            }
2842

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

    
2848
            case EBML_ID_VOID:
2849
                res = ebml_read_skip(matroska);
2850
                break;
2851
        }
2852

    
2853
        if (matroska->level_up) {
2854
            matroska->level_up--;
2855
            break;
2856
        }
2857
    }
2858

    
2859
    if (res)
2860
        return res;
2861

    
2862
    if (size > 0)
2863
        res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2864
                                   duration, is_keyframe, is_bframe);
2865

    
2866
    return res;
2867
}
2868

    
2869
static int
2870
matroska_parse_cluster (MatroskaDemuxContext *matroska)
2871
{
2872
    int res = 0;
2873
    uint32_t id;
2874
    uint64_t cluster_time = 0;
2875
    uint8_t *data;
2876
    int64_t pos;
2877
    int size;
2878

    
2879
    av_log(matroska->ctx, AV_LOG_DEBUG,
2880
           "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
2881

    
2882
    while (res == 0) {
2883
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2884
            res = AVERROR(EIO);
2885
            break;
2886
        } else if (matroska->level_up) {
2887
            matroska->level_up--;
2888
            break;
2889
        }
2890

    
2891
        switch (id) {
2892
            /* cluster timecode */
2893
            case MATROSKA_ID_CLUSTERTIMECODE: {
2894
                uint64_t num;
2895
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2896
                    break;
2897
                cluster_time = num;
2898
                break;
2899
            }
2900

    
2901
                /* a group of blocks inside a cluster */
2902
            case MATROSKA_ID_BLOCKGROUP:
2903
                if ((res = ebml_read_master(matroska, &id)) < 0)
2904
                    break;
2905
                res = matroska_parse_blockgroup(matroska, cluster_time);
2906
                break;
2907

    
2908
            case MATROSKA_ID_SIMPLEBLOCK:
2909
                pos = url_ftell(matroska->ctx->pb);
2910
                res = ebml_read_binary(matroska, &id, &data, &size);
2911
                if (res == 0)
2912
                    res = matroska_parse_block(matroska, data, size, pos,
2913
                                               cluster_time, AV_NOPTS_VALUE,
2914
                                               -1, 0);
2915
                break;
2916

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

    
2922
            case EBML_ID_VOID:
2923
                res = ebml_read_skip(matroska);
2924
                break;
2925
        }
2926

    
2927
        if (matroska->level_up) {
2928
            matroska->level_up--;
2929
            break;
2930
        }
2931
    }
2932

    
2933
    return res;
2934
}
2935

    
2936
static int
2937
matroska_read_packet (AVFormatContext *s,
2938
                      AVPacket        *pkt)
2939
{
2940
    MatroskaDemuxContext *matroska = s->priv_data;
2941
    int res;
2942
    uint32_t id;
2943

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

    
2947
        /* Have we already reached the end? */
2948
        if (matroska->done)
2949
            return AVERROR(EIO);
2950

    
2951
        res = 0;
2952
        while (res == 0) {
2953
            if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2954
                return AVERROR(EIO);
2955
            } else if (matroska->level_up) {
2956
                matroska->level_up--;
2957
                break;
2958
            }
2959

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

    
2968
                default:
2969
                case EBML_ID_VOID:
2970
                    res = ebml_read_skip(matroska);
2971
                    break;
2972
            }
2973

    
2974
            if (matroska->level_up) {
2975
                matroska->level_up--;
2976
                break;
2977
            }
2978
        }
2979

    
2980
        if (res == -1)
2981
            matroska->done = 1;
2982
    }
2983

    
2984
    return 0;
2985
}
2986

    
2987
static int
2988
matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2989
                    int flags)
2990
{
2991
    MatroskaDemuxContext *matroska = s->priv_data;
2992
    AVStream *st = s->streams[stream_index];
2993
    int index;
2994

    
2995
    /* find index entry */
2996
    index = av_index_search_timestamp(st, timestamp, flags);
2997
    if (index < 0)
2998
        return 0;
2999

    
3000
    matroska_clear_queue(matroska);
3001

    
3002
    /* do the seek */
3003
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
3004
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
3005
    matroska->skip_to_stream = st;
3006
    matroska->peek_id = 0;
3007
    return 0;
3008
}
3009

    
3010
static int
3011
matroska_read_close (AVFormatContext *s)
3012
{
3013
    MatroskaDemuxContext *matroska = s->priv_data;
3014
    int n = 0;
3015

    
3016
    av_free(matroska->writing_app);
3017
    av_free(matroska->muxing_app);
3018
    av_free(matroska->index);
3019

    
3020
    matroska_clear_queue(matroska);
3021

    
3022
    for (n = 0; n < matroska->num_tracks; n++) {
3023
        MatroskaTrack *track = matroska->tracks[n];
3024
        av_free(track->codec_id);
3025
        av_free(track->codec_name);
3026
        av_free(track->codec_priv);
3027
        av_free(track->name);
3028

    
3029
        if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
3030
            MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
3031
            av_free(audiotrack->buf);
3032
        }
3033

    
3034
        av_free(track);
3035
    }
3036

    
3037
    return 0;
3038
}
3039

    
3040
AVInputFormat matroska_demuxer = {
3041
    "matroska",
3042
    "Matroska file format",
3043
    sizeof(MatroskaDemuxContext),
3044
    matroska_probe,
3045
    matroska_read_header,
3046
    matroska_read_packet,
3047
    matroska_read_close,
3048
    matroska_read_seek,
3049
};