Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ d2062ff6

History | View | Annotate | Download (88 KB)

1 b061d892 David Conrad
/*
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 6de4aece Reimar Döffinger
 * @file matroskadec.c
24 b061d892 David Conrad
 * 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 "intfloat_readwrite.h"
35
#include "matroska.h"
36
37
typedef struct Track {
38
    MatroskaTrackType type;
39
40
    /* Unique track number and track ID. stream_index is the index that
41
     * the calling app uses for this track. */
42 8d75b5a2 Aurelien Jacobs
    uint32_t num;
43
    uint32_t uid;
44 2def9cd9 Aurelien Jacobs
    int stream_index;
45 b061d892 David Conrad
46 8d75b5a2 Aurelien Jacobs
    char *name;
47 463d5bcc Aurelien Jacobs
    char language[4];
48 b061d892 David Conrad
49 8d75b5a2 Aurelien Jacobs
    char *codec_id;
50
    char *codec_name;
51 b061d892 David Conrad
52
    unsigned char *codec_priv;
53
    int codec_priv_size;
54
55
    uint64_t default_duration;
56
    MatroskaTrackFlags flags;
57
} MatroskaTrack;
58
59
typedef struct MatroskaVideoTrack {
60
    MatroskaTrack track;
61
62 8d75b5a2 Aurelien Jacobs
    int pixel_width;
63
    int pixel_height;
64
    int display_width;
65
    int display_height;
66 b061d892 David Conrad
67
    uint32_t fourcc;
68
69
    MatroskaAspectRatioMode ar_mode;
70
    MatroskaEyeMode eye_mode;
71
72
    //..
73
} MatroskaVideoTrack;
74
75
typedef struct MatroskaAudioTrack {
76
    MatroskaTrack track;
77
78 8d75b5a2 Aurelien Jacobs
    int channels;
79
    int bitdepth;
80
    int internal_samplerate;
81
    int samplerate;
82 eabb8ba4 Aurelien Jacobs
    int block_align;
83
84
    /* real audio header */
85
    int coded_framesize;
86
    int sub_packet_h;
87
    int frame_size;
88
    int sub_packet_size;
89
    int sub_packet_cnt;
90
    int pkt_cnt;
91
    uint8_t *buf;
92 b061d892 David Conrad
    //..
93
} MatroskaAudioTrack;
94
95
typedef struct MatroskaSubtitleTrack {
96
    MatroskaTrack track;
97
98 979c0910 Aurelien Jacobs
    int ass;
99 b061d892 David Conrad
    //..
100
} MatroskaSubtitleTrack;
101
102
#define MAX_TRACK_SIZE (FFMAX(FFMAX(sizeof(MatroskaVideoTrack), \
103
                                    sizeof(MatroskaAudioTrack)), \
104
                                    sizeof(MatroskaSubtitleTrack)))
105
106
typedef struct MatroskaLevel {
107 8d75b5a2 Aurelien Jacobs
    uint64_t start;
108
    uint64_t length;
109 b061d892 David Conrad
} MatroskaLevel;
110
111
typedef struct MatroskaDemuxIndex {
112
  uint64_t        pos;   /* of the corresponding *cluster*! */
113
  uint16_t        track; /* reference to 'num' */
114
  uint64_t        time;  /* in nanoseconds */
115
} MatroskaDemuxIndex;
116
117
typedef struct MatroskaDemuxContext {
118
    AVFormatContext *ctx;
119
120
    /* ebml stuff */
121
    int num_levels;
122
    MatroskaLevel levels[EBML_MAX_DEPTH];
123
    int level_up;
124
125
    /* matroska stuff */
126 8d75b5a2 Aurelien Jacobs
    char *writing_app;
127
    char *muxing_app;
128 b061d892 David Conrad
    int64_t created;
129
130
    /* timescale in the file */
131
    int64_t time_scale;
132
133
    /* num_streams is the number of streams that av_new_stream() was called
134
     * for ( = that are available to the calling program). */
135 8d75b5a2 Aurelien Jacobs
    int num_tracks;
136
    int num_streams;
137 b061d892 David Conrad
    MatroskaTrack *tracks[MAX_STREAMS];
138
139
    /* cache for ID peeking */
140
    uint32_t peek_id;
141
142
    /* byte position of the segment inside the stream */
143
    offset_t segment_start;
144
145
    /* The packet queue. */
146
    AVPacket **packets;
147
    int num_packets;
148
149
    /* have we already parse metadata/cues/clusters? */
150 8d75b5a2 Aurelien Jacobs
    int metadata_parsed;
151
    int index_parsed;
152
    int done;
153 b061d892 David Conrad
154
    /* The index for seeking. */
155
    int num_indexes;
156
    MatroskaDemuxIndex *index;
157
158
    /* What to skip before effectively reading a packet. */
159
    int skip_to_keyframe;
160
    AVStream *skip_to_stream;
161
} MatroskaDemuxContext;
162
163
/*
164
 * The first few functions handle EBML file parsing. The rest
165
 * is the document interpretation. Matroska really just is a
166
 * EBML file.
167
 */
168
169
/*
170
 * Return: the amount of levels in the hierarchy that the
171
 * current element lies higher than the previous one.
172
 * The opposite isn't done - that's auto-done using master
173
 * element reading.
174
 */
175
176
static int
177
ebml_read_element_level_up (MatroskaDemuxContext *matroska)
178
{
179
    ByteIOContext *pb = &matroska->ctx->pb;
180
    offset_t pos = url_ftell(pb);
181
    int num = 0;
182
183
    while (matroska->num_levels > 0) {
184
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
185
186
        if (pos >= level->start + level->length) {
187
            matroska->num_levels--;
188
            num++;
189
        } else {
190
            break;
191
        }
192
    }
193
194
    return num;
195
}
196
197
/*
198
 * Read: an "EBML number", which is defined as a variable-length
199
 * array of bytes. The first byte indicates the length by giving a
200
 * number of 0-bits followed by a one. The position of the first
201
 * "one" bit inside the first byte indicates the length of this
202
 * number.
203
 * Returns: num. of bytes read. < 0 on error.
204
 */
205
206
static int
207
ebml_read_num (MatroskaDemuxContext *matroska,
208
               int                   max_size,
209
               uint64_t             *number)
210
{
211
    ByteIOContext *pb = &matroska->ctx->pb;
212
    int len_mask = 0x80, read = 1, n = 1;
213
    int64_t total = 0;
214
215
    /* the first byte tells us the length in bytes - get_byte() can normally
216
     * return 0, but since that's not a valid first ebmlID byte, we can
217
     * use it safely here to catch EOS. */
218
    if (!(total = get_byte(pb))) {
219
        /* we might encounter EOS here */
220
        if (!url_feof(pb)) {
221
            offset_t pos = url_ftell(pb);
222
            av_log(matroska->ctx, AV_LOG_ERROR,
223
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
224
                   pos, pos);
225
        }
226 6f3e0b21 Panagiotis Issaris
        return AVERROR(EIO); /* EOS or actual I/O error */
227 b061d892 David Conrad
    }
228
229
    /* get the length of the EBML number */
230
    while (read <= max_size && !(total & len_mask)) {
231
        read++;
232
        len_mask >>= 1;
233
    }
234
    if (read > max_size) {
235
        offset_t pos = url_ftell(pb) - 1;
236
        av_log(matroska->ctx, AV_LOG_ERROR,
237
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
238
               (uint8_t) total, pos, pos);
239
        return AVERROR_INVALIDDATA;
240
    }
241
242
    /* read out length */
243
    total &= ~len_mask;
244
    while (n++ < read)
245
        total = (total << 8) | get_byte(pb);
246
247
    *number = total;
248
249
    return read;
250
}
251
252
/*
253
 * Read: the element content data ID.
254
 * Return: the number of bytes read or < 0 on error.
255
 */
256
257
static int
258
ebml_read_element_id (MatroskaDemuxContext *matroska,
259
                      uint32_t             *id,
260
                      int                  *level_up)
261
{
262
    int read;
263
    uint64_t total;
264
265
    /* if we re-call this, use our cached ID */
266
    if (matroska->peek_id != 0) {
267
        if (level_up)
268
            *level_up = 0;
269
        *id = matroska->peek_id;
270
        return 0;
271
    }
272
273
    /* read out the "EBML number", include tag in ID */
274
    if ((read = ebml_read_num(matroska, 4, &total)) < 0)
275
        return read;
276
    *id = matroska->peek_id  = total | (1 << (read * 7));
277
278
    /* level tracking */
279
    if (level_up)
280
        *level_up = ebml_read_element_level_up(matroska);
281
282
    return read;
283
}
284
285
/*
286
 * Read: element content length.
287
 * Return: the number of bytes read or < 0 on error.
288
 */
289
290
static int
291
ebml_read_element_length (MatroskaDemuxContext *matroska,
292
                          uint64_t             *length)
293
{
294
    /* clear cache since we're now beyond that data point */
295
    matroska->peek_id = 0;
296
297
    /* read out the "EBML number", include tag in ID */
298
    return ebml_read_num(matroska, 8, length);
299
}
300
301
/*
302
 * Return: the ID of the next element, or 0 on error.
303
 * Level_up contains the amount of levels that this
304
 * next element lies higher than the previous one.
305
 */
306
307
static uint32_t
308
ebml_peek_id (MatroskaDemuxContext *matroska,
309
              int                  *level_up)
310
{
311
    uint32_t id;
312
313
    if (ebml_read_element_id(matroska, &id, level_up) < 0)
314
        return 0;
315
316
    return id;
317
}
318
319
/*
320
 * Seek to a given offset.
321
 * 0 is success, -1 is failure.
322
 */
323
324
static int
325
ebml_read_seek (MatroskaDemuxContext *matroska,
326
                offset_t              offset)
327
{
328
    ByteIOContext *pb = &matroska->ctx->pb;
329
330
    /* clear ID cache, if any */
331
    matroska->peek_id = 0;
332
333
    return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
334
}
335
336
/*
337
 * Skip the next element.
338
 * 0 is success, -1 is failure.
339
 */
340
341
static int
342
ebml_read_skip (MatroskaDemuxContext *matroska)
343
{
344
    ByteIOContext *pb = &matroska->ctx->pb;
345
    uint32_t id;
346
    uint64_t length;
347
    int res;
348
349
    if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
350
        (res = ebml_read_element_length(matroska, &length)) < 0)
351
        return res;
352
353
    url_fskip(pb, length);
354
355
    return 0;
356
}
357
358
/*
359
 * Read the next element as an unsigned int.
360
 * 0 is success, < 0 is failure.
361
 */
362
363
static int
364
ebml_read_uint (MatroskaDemuxContext *matroska,
365
                uint32_t             *id,
366
                uint64_t             *num)
367
{
368
    ByteIOContext *pb = &matroska->ctx->pb;
369
    int n = 0, size, res;
370
    uint64_t rlength;
371
372
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
373
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
374
        return res;
375
    size = rlength;
376
    if (size < 1 || size > 8) {
377
        offset_t pos = url_ftell(pb);
378
        av_log(matroska->ctx, AV_LOG_ERROR,
379
               "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
380
                size, pos, pos);
381
        return AVERROR_INVALIDDATA;
382
    }
383
384
    /* big-endian ordening; build up number */
385
    *num = 0;
386
    while (n++ < size)
387
        *num = (*num << 8) | get_byte(pb);
388
389
    return 0;
390
}
391
392
/*
393
 * Read the next element as a signed int.
394
 * 0 is success, < 0 is failure.
395
 */
396
397
static int
398
ebml_read_sint (MatroskaDemuxContext *matroska,
399
                uint32_t             *id,
400
                int64_t              *num)
401
{
402
    ByteIOContext *pb = &matroska->ctx->pb;
403
    int size, n = 1, negative = 0, res;
404
    uint64_t rlength;
405
406
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
407
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
408
        return res;
409
    size = rlength;
410
    if (size < 1 || size > 8) {
411
        offset_t pos = url_ftell(pb);
412
        av_log(matroska->ctx, AV_LOG_ERROR,
413
               "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
414
                size, pos, pos);
415
        return AVERROR_INVALIDDATA;
416
    }
417
    if ((*num = get_byte(pb)) & 0x80) {
418
        negative = 1;
419
        *num &= ~0x80;
420
    }
421
    while (n++ < size)
422
        *num = (*num << 8) | get_byte(pb);
423
424
    /* make signed */
425
    if (negative)
426
        *num = *num - (1LL << ((8 * size) - 1));
427
428
    return 0;
429
}
430
431
/*
432
 * Read the next element as a float.
433
 * 0 is success, < 0 is failure.
434
 */
435
436
static int
437
ebml_read_float (MatroskaDemuxContext *matroska,
438
                 uint32_t             *id,
439
                 double               *num)
440
{
441
    ByteIOContext *pb = &matroska->ctx->pb;
442
    int size, res;
443
    uint64_t rlength;
444
445
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
446
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
447
        return res;
448
    size = rlength;
449
450
    if (size == 4) {
451
        *num= av_int2flt(get_be32(pb));
452
    } else if(size==8){
453
        *num= av_int2dbl(get_be64(pb));
454
    } else{
455
        offset_t pos = url_ftell(pb);
456
        av_log(matroska->ctx, AV_LOG_ERROR,
457
               "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
458
               size, pos, pos);
459
        return AVERROR_INVALIDDATA;
460
    }
461
462
    return 0;
463
}
464
465
/*
466
 * Read the next element as an ASCII string.
467
 * 0 is success, < 0 is failure.
468
 */
469
470
static int
471
ebml_read_ascii (MatroskaDemuxContext *matroska,
472
                 uint32_t             *id,
473
                 char                **str)
474
{
475
    ByteIOContext *pb = &matroska->ctx->pb;
476
    int size, res;
477
    uint64_t rlength;
478
479
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
480
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
481
        return res;
482
    size = rlength;
483
484
    /* ebml strings are usually not 0-terminated, so we allocate one
485
     * byte more, read the string and NULL-terminate it ourselves. */
486
    if (size < 0 || !(*str = av_malloc(size + 1))) {
487
        av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
488 769e10f0 Panagiotis Issaris
        return AVERROR(ENOMEM);
489 b061d892 David Conrad
    }
490
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
491
        offset_t pos = url_ftell(pb);
492
        av_log(matroska->ctx, AV_LOG_ERROR,
493
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
494 6f3e0b21 Panagiotis Issaris
        return AVERROR(EIO);
495 b061d892 David Conrad
    }
496
    (*str)[size] = '\0';
497
498
    return 0;
499
}
500
501
/*
502
 * Read the next element as a UTF-8 string.
503
 * 0 is success, < 0 is failure.
504
 */
505
506
static int
507
ebml_read_utf8 (MatroskaDemuxContext *matroska,
508
                uint32_t             *id,
509
                char                **str)
510
{
511
  return ebml_read_ascii(matroska, id, str);
512
}
513
514
/*
515
 * Read the next element as a date (nanoseconds since 1/1/2000).
516
 * 0 is success, < 0 is failure.
517
 */
518
519
static int
520
ebml_read_date (MatroskaDemuxContext *matroska,
521
                uint32_t             *id,
522
                int64_t              *date)
523
{
524
  return ebml_read_sint(matroska, id, date);
525
}
526
527
/*
528
 * Read the next element, but only the header. The contents
529
 * are supposed to be sub-elements which can be read separately.
530
 * 0 is success, < 0 is failure.
531
 */
532
533
static int
534
ebml_read_master (MatroskaDemuxContext *matroska,
535
                  uint32_t             *id)
536
{
537
    ByteIOContext *pb = &matroska->ctx->pb;
538
    uint64_t length;
539
    MatroskaLevel *level;
540
    int res;
541
542
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
543
        (res = ebml_read_element_length(matroska, &length)) < 0)
544
        return res;
545
546
    /* protect... (Heaven forbids that the '>' is true) */
547
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
548
        av_log(matroska->ctx, AV_LOG_ERROR,
549
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
550 85565db0 Panagiotis Issaris
        return AVERROR(ENOSYS);
551 b061d892 David Conrad
    }
552
553
    /* remember level */
554
    level = &matroska->levels[matroska->num_levels++];
555
    level->start = url_ftell(pb);
556
    level->length = length;
557
558
    return 0;
559
}
560
561
/*
562
 * Read the next element as binary data.
563
 * 0 is success, < 0 is failure.
564
 */
565
566
static int
567
ebml_read_binary (MatroskaDemuxContext *matroska,
568
                  uint32_t             *id,
569
                  uint8_t             **binary,
570
                  int                  *size)
571
{
572
    ByteIOContext *pb = &matroska->ctx->pb;
573
    uint64_t rlength;
574
    int res;
575
576
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
577
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
578
        return res;
579
    *size = rlength;
580
581
    if (!(*binary = av_malloc(*size))) {
582
        av_log(matroska->ctx, AV_LOG_ERROR,
583
               "Memory allocation error\n");
584 769e10f0 Panagiotis Issaris
        return AVERROR(ENOMEM);
585 b061d892 David Conrad
    }
586
587
    if (get_buffer(pb, *binary, *size) != *size) {
588
        offset_t pos = url_ftell(pb);
589
        av_log(matroska->ctx, AV_LOG_ERROR,
590
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
591 6f3e0b21 Panagiotis Issaris
        return AVERROR(EIO);
592 b061d892 David Conrad
    }
593
594
    return 0;
595
}
596
597
/*
598
 * Read signed/unsigned "EBML" numbers.
599
 * Return: number of bytes processed, < 0 on error.
600
 * XXX: use ebml_read_num().
601
 */
602
603
static int
604
matroska_ebmlnum_uint (uint8_t  *data,
605
                       uint32_t  size,
606
                       uint64_t *num)
607
{
608
    int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
609
    uint64_t total;
610
611
    if (size <= 0)
612
        return AVERROR_INVALIDDATA;
613
614
    total = data[0];
615
    while (read <= 8 && !(total & len_mask)) {
616
        read++;
617
        len_mask >>= 1;
618
    }
619
    if (read > 8)
620
        return AVERROR_INVALIDDATA;
621
622
    if ((total &= (len_mask - 1)) == len_mask - 1)
623
        num_ffs++;
624
    if (size < read)
625
        return AVERROR_INVALIDDATA;
626
    while (n < read) {
627
        if (data[n] == 0xff)
628
            num_ffs++;
629
        total = (total << 8) | data[n];
630
        n++;
631
    }
632
633
    if (read == num_ffs)
634
        *num = (uint64_t)-1;
635
    else
636
        *num = total;
637
638
    return read;
639
}
640
641
/*
642
 * Same as above, but signed.
643
 */
644
645
static int
646
matroska_ebmlnum_sint (uint8_t  *data,
647
                       uint32_t  size,
648
                       int64_t  *num)
649
{
650
    uint64_t unum;
651
    int res;
652
653
    /* read as unsigned number first */
654
    if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
655
        return res;
656
657
    /* make signed (weird way) */
658
    if (unum == (uint64_t)-1)
659
        *num = INT64_MAX;
660
    else
661
        *num = unum - ((1LL << ((7 * res) - 1)) - 1);
662
663
    return res;
664
}
665
666
/*
667
 * Read an EBML header.
668
 * 0 is success, < 0 is failure.
669
 */
670
671
static int
672
ebml_read_header (MatroskaDemuxContext *matroska,
673
                  char                **doctype,
674
                  int                  *version)
675
{
676
    uint32_t id;
677
    int level_up, res = 0;
678
679
    /* default init */
680
    if (doctype)
681
        *doctype = NULL;
682
    if (version)
683
        *version = 1;
684
685
    if (!(id = ebml_peek_id(matroska, &level_up)) ||
686
        level_up != 0 || id != EBML_ID_HEADER) {
687
        av_log(matroska->ctx, AV_LOG_ERROR,
688
               "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
689
        return AVERROR_INVALIDDATA;
690
    }
691
    if ((res = ebml_read_master(matroska, &id)) < 0)
692
        return res;
693
694
    while (res == 0) {
695
        if (!(id = ebml_peek_id(matroska, &level_up)))
696 6f3e0b21 Panagiotis Issaris
            return AVERROR(EIO);
697 b061d892 David Conrad
698
        /* end-of-header */
699
        if (level_up)
700
            break;
701
702
        switch (id) {
703
            /* is our read version uptodate? */
704
            case EBML_ID_EBMLREADVERSION: {
705
                uint64_t num;
706
707
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
708
                    return res;
709
                if (num > EBML_VERSION) {
710
                    av_log(matroska->ctx, AV_LOG_ERROR,
711
                           "EBML version %"PRIu64" (> %d) is not supported\n",
712
                           num, EBML_VERSION);
713
                    return AVERROR_INVALIDDATA;
714
                }
715
                break;
716
            }
717
718
            /* we only handle 8 byte lengths at max */
719
            case EBML_ID_EBMLMAXSIZELENGTH: {
720
                uint64_t num;
721
722
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
723
                    return res;
724
                if (num > sizeof(uint64_t)) {
725
                    av_log(matroska->ctx, AV_LOG_ERROR,
726
                           "Integers of size %"PRIu64" (> %zd) not supported\n",
727
                           num, sizeof(uint64_t));
728
                    return AVERROR_INVALIDDATA;
729
                }
730
                break;
731
            }
732
733
            /* we handle 4 byte IDs at max */
734
            case EBML_ID_EBMLMAXIDLENGTH: {
735
                uint64_t num;
736
737
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
738
                    return res;
739
                if (num > sizeof(uint32_t)) {
740
                    av_log(matroska->ctx, AV_LOG_ERROR,
741
                           "IDs of size %"PRIu64" (> %zu) not supported\n",
742
                            num, sizeof(uint32_t));
743
                    return AVERROR_INVALIDDATA;
744
                }
745
                break;
746
            }
747
748
            case EBML_ID_DOCTYPE: {
749
                char *text;
750
751
                if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
752
                    return res;
753
                if (doctype) {
754
                    if (*doctype)
755
                        av_free(*doctype);
756
                    *doctype = text;
757
                } else
758
                    av_free(text);
759
                break;
760
            }
761
762
            case EBML_ID_DOCTYPEREADVERSION: {
763
                uint64_t num;
764
765
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
766
                    return res;
767
                if (version)
768
                    *version = num;
769
                break;
770
            }
771
772
            default:
773
                av_log(matroska->ctx, AV_LOG_INFO,
774
                       "Unknown data type 0x%x in EBML header", id);
775
                /* pass-through */
776
777
            case EBML_ID_VOID:
778
            /* we ignore these two, as they don't tell us anything we
779
             * care about */
780
            case EBML_ID_EBMLVERSION:
781
            case EBML_ID_DOCTYPEVERSION:
782
                res = ebml_read_skip (matroska);
783
                break;
784
        }
785
    }
786
787
    return 0;
788
}
789
790
791
static int
792
matroska_find_track_by_num (MatroskaDemuxContext *matroska,
793
                            int                   num)
794
{
795
    int i;
796
797
    for (i = 0; i < matroska->num_tracks; i++)
798
        if (matroska->tracks[i]->num == num)
799
            return i;
800
801
    return -1;
802
}
803
804
805
/*
806
 * Put one packet in an application-supplied AVPacket struct.
807
 * Returns 0 on success or -1 on failure.
808
 */
809
810
static int
811
matroska_deliver_packet (MatroskaDemuxContext *matroska,
812
                         AVPacket             *pkt)
813
{
814
    if (matroska->num_packets > 0) {
815
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
816
        av_free(matroska->packets[0]);
817
        if (matroska->num_packets > 1) {
818
            memmove(&matroska->packets[0], &matroska->packets[1],
819
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
820
            matroska->packets =
821
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
822
                           sizeof(AVPacket *));
823
        } else {
824
            av_freep(&matroska->packets);
825
        }
826
        matroska->num_packets--;
827
        return 0;
828
    }
829
830
    return -1;
831
}
832
833
/*
834
 * Put a packet into our internal queue. Will be delivered to the
835
 * user/application during the next get_packet() call.
836
 */
837
838
static void
839
matroska_queue_packet (MatroskaDemuxContext *matroska,
840
                       AVPacket             *pkt)
841
{
842
    matroska->packets =
843
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
844
                   sizeof(AVPacket *));
845
    matroska->packets[matroska->num_packets] = pkt;
846
    matroska->num_packets++;
847
}
848
849
850
/*
851
 * Autodetecting...
852
 */
853
854
static int
855
matroska_probe (AVProbeData *p)
856
{
857
    uint64_t total = 0;
858
    int len_mask = 0x80, size = 1, n = 1;
859
    uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
860
861
    /* ebml header? */
862 2ce746c6 Aurelien Jacobs
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
863 b061d892 David Conrad
        return 0;
864
865
    /* length of header */
866
    total = p->buf[4];
867
    while (size <= 8 && !(total & len_mask)) {
868
        size++;
869
        len_mask >>= 1;
870
    }
871
    if (size > 8)
872
      return 0;
873
    total &= (len_mask - 1);
874
    while (n < size)
875
        total = (total << 8) | p->buf[4 + n++];
876
877
    /* does the probe data contain the whole header? */
878
    if (p->buf_size < 4 + size + total)
879
      return 0;
880
881
    /* the header must contain the document type 'matroska'. For now,
882
     * we don't parse the whole header but simply check for the
883
     * availability of that array of characters inside the header.
884
     * Not fully fool-proof, but good enough. */
885
    for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
886
        if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
887
            return AVPROBE_SCORE_MAX;
888
889
    return 0;
890
}
891
892
/*
893
 * From here on, it's all XML-style DTD stuff... Needs no comments.
894
 */
895
896
static int
897
matroska_parse_info (MatroskaDemuxContext *matroska)
898
{
899
    int res = 0;
900
    uint32_t id;
901
902
    av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
903
904
    while (res == 0) {
905
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
906 6f3e0b21 Panagiotis Issaris
            res = AVERROR(EIO);
907 b061d892 David Conrad
            break;
908
        } else if (matroska->level_up) {
909
            matroska->level_up--;
910
            break;
911
        }
912
913
        switch (id) {
914
            /* cluster timecode */
915
            case MATROSKA_ID_TIMECODESCALE: {
916
                uint64_t num;
917
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
918
                    break;
919
                matroska->time_scale = num;
920
                break;
921
            }
922
923
            case MATROSKA_ID_DURATION: {
924
                double num;
925
                if ((res = ebml_read_float(matroska, &id, &num)) < 0)
926
                    break;
927
                matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
928
                break;
929
            }
930
931
            case MATROSKA_ID_TITLE: {
932
                char *text;
933
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
934
                    break;
935
                strncpy(matroska->ctx->title, text,
936
                        sizeof(matroska->ctx->title)-1);
937
                av_free(text);
938
                break;
939
            }
940
941
            case MATROSKA_ID_WRITINGAPP: {
942
                char *text;
943
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
944
                    break;
945
                matroska->writing_app = text;
946
                break;
947
            }
948
949
            case MATROSKA_ID_MUXINGAPP: {
950
                char *text;
951
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
952
                    break;
953
                matroska->muxing_app = text;
954
                break;
955
            }
956
957
            case MATROSKA_ID_DATEUTC: {
958
                int64_t time;
959
                if ((res = ebml_read_date(matroska, &id, &time)) < 0)
960
                    break;
961
                matroska->created = time;
962
                break;
963
            }
964
965
            default:
966
                av_log(matroska->ctx, AV_LOG_INFO,
967
                       "Unknown entry 0x%x in info header\n", id);
968
                /* fall-through */
969
970
            case EBML_ID_VOID:
971
                res = ebml_read_skip(matroska);
972
                break;
973
        }
974
975
        if (matroska->level_up) {
976
            matroska->level_up--;
977
            break;
978
        }
979
    }
980
981
    return res;
982
}
983
984
static int
985
matroska_add_stream (MatroskaDemuxContext *matroska)
986
{
987
    int res = 0;
988
    uint32_t id;
989
    MatroskaTrack *track;
990
991
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
992
993
    /* Allocate a generic track. As soon as we know its type we'll realloc. */
994
    track = av_mallocz(MAX_TRACK_SIZE);
995
    matroska->num_tracks++;
996 463d5bcc Aurelien Jacobs
    strcpy(track->language, "eng");
997 b061d892 David Conrad
998
    /* start with the master */
999
    if ((res = ebml_read_master(matroska, &id)) < 0)
1000
        return res;
1001
1002
    /* try reading the trackentry headers */
1003
    while (res == 0) {
1004
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1005 6f3e0b21 Panagiotis Issaris
            res = AVERROR(EIO);
1006 b061d892 David Conrad
            break;
1007
        } else if (matroska->level_up > 0) {
1008
            matroska->level_up--;
1009
            break;
1010
        }
1011
1012
        switch (id) {
1013
            /* track number (unique stream ID) */
1014
            case MATROSKA_ID_TRACKNUMBER: {
1015
                uint64_t num;
1016
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1017
                    break;
1018
                track->num = num;
1019
                break;
1020
            }
1021
1022
            /* track UID (unique identifier) */
1023
            case MATROSKA_ID_TRACKUID: {
1024
                uint64_t num;
1025
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1026
                    break;
1027
                track->uid = num;
1028
                break;
1029
            }
1030
1031
            /* track type (video, audio, combined, subtitle, etc.) */
1032
            case MATROSKA_ID_TRACKTYPE: {
1033
                uint64_t num;
1034
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1035
                    break;
1036
                if (track->type && track->type != num) {
1037
                    av_log(matroska->ctx, AV_LOG_INFO,
1038
                           "More than one tracktype in an entry - skip\n");
1039
                    break;
1040
                }
1041
                track->type = num;
1042
1043
                switch (track->type) {
1044
                    case MATROSKA_TRACK_TYPE_VIDEO:
1045
                    case MATROSKA_TRACK_TYPE_AUDIO:
1046
                    case MATROSKA_TRACK_TYPE_SUBTITLE:
1047
                        break;
1048
                    case MATROSKA_TRACK_TYPE_COMPLEX:
1049
                    case MATROSKA_TRACK_TYPE_LOGO:
1050
                    case MATROSKA_TRACK_TYPE_CONTROL:
1051
                    default:
1052
                        av_log(matroska->ctx, AV_LOG_INFO,
1053
                               "Unknown or unsupported track type 0x%x\n",
1054
                               track->type);
1055
                        track->type = 0;
1056
                        break;
1057
                }
1058
                matroska->tracks[matroska->num_tracks - 1] = track;
1059
                break;
1060
            }
1061
1062
            /* tracktype specific stuff for video */
1063
            case MATROSKA_ID_TRACKVIDEO: {
1064
                MatroskaVideoTrack *videotrack;
1065
                if (!track->type)
1066
                    track->type = MATROSKA_TRACK_TYPE_VIDEO;
1067
                if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1068
                    av_log(matroska->ctx, AV_LOG_INFO,
1069
                           "video data in non-video track - ignoring\n");
1070
                    res = AVERROR_INVALIDDATA;
1071
                    break;
1072
                } else if ((res = ebml_read_master(matroska, &id)) < 0)
1073
                    break;
1074
                videotrack = (MatroskaVideoTrack *)track;
1075
1076
                while (res == 0) {
1077
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1078 6f3e0b21 Panagiotis Issaris
                        res = AVERROR(EIO);
1079 b061d892 David Conrad
                        break;
1080
                    } else if (matroska->level_up > 0) {
1081
                        matroska->level_up--;
1082
                        break;
1083
                    }
1084
1085
                    switch (id) {
1086
                        /* fixme, this should be one-up, but I get it here */
1087
                        case MATROSKA_ID_TRACKDEFAULTDURATION: {
1088
                            uint64_t num;
1089
                            if ((res = ebml_read_uint (matroska, &id,
1090
                                                       &num)) < 0)
1091
                                break;
1092
                            track->default_duration = num/matroska->time_scale;
1093
                            break;
1094
                        }
1095
1096
                        /* video framerate */
1097
                        case MATROSKA_ID_VIDEOFRAMERATE: {
1098
                            double num;
1099
                            if ((res = ebml_read_float(matroska, &id,
1100
                                                       &num)) < 0)
1101
                                break;
1102
                            track->default_duration = 1000000000/(matroska->time_scale*num);
1103
                            break;
1104
                        }
1105
1106
                        /* width of the size to display the video at */
1107
                        case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1108
                            uint64_t num;
1109
                            if ((res = ebml_read_uint(matroska, &id,
1110
                                                      &num)) < 0)
1111
                                break;
1112
                            videotrack->display_width = num;
1113
                            break;
1114
                        }
1115
1116
                        /* height of the size to display the video at */
1117
                        case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1118
                            uint64_t num;
1119
                            if ((res = ebml_read_uint(matroska, &id,
1120
                                                      &num)) < 0)
1121
                                break;
1122
                            videotrack->display_height = num;
1123
                            break;
1124
                        }
1125
1126
                        /* width of the video in the file */
1127
                        case MATROSKA_ID_VIDEOPIXELWIDTH: {
1128
                            uint64_t num;
1129
                            if ((res = ebml_read_uint(matroska, &id,
1130
                                                      &num)) < 0)
1131
                                break;
1132
                            videotrack->pixel_width = num;
1133
                            break;
1134
                        }
1135
1136
                        /* height of the video in the file */
1137
                        case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1138
                            uint64_t num;
1139
                            if ((res = ebml_read_uint(matroska, &id,
1140
                                                      &num)) < 0)
1141
                                break;
1142
                            videotrack->pixel_height = num;
1143
                            break;
1144
                        }
1145
1146
                        /* whether the video is interlaced */
1147
                        case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1148
                            uint64_t num;
1149
                            if ((res = ebml_read_uint(matroska, &id,
1150
                                                      &num)) < 0)
1151
                                break;
1152
                            if (num)
1153
                                track->flags |=
1154
                                    MATROSKA_VIDEOTRACK_INTERLACED;
1155
                            else
1156
                                track->flags &=
1157
                                    ~MATROSKA_VIDEOTRACK_INTERLACED;
1158
                            break;
1159
                        }
1160
1161
                        /* stereo mode (whether the video has two streams,
1162
                         * where one is for the left eye and the other for
1163
                         * the right eye, which creates a 3D-like
1164
                         * effect) */
1165
                        case MATROSKA_ID_VIDEOSTEREOMODE: {
1166
                            uint64_t num;
1167
                            if ((res = ebml_read_uint(matroska, &id,
1168
                                                      &num)) < 0)
1169
                                break;
1170
                            if (num != MATROSKA_EYE_MODE_MONO &&
1171
                                num != MATROSKA_EYE_MODE_LEFT &&
1172
                                num != MATROSKA_EYE_MODE_RIGHT &&
1173
                                num != MATROSKA_EYE_MODE_BOTH) {
1174
                                av_log(matroska->ctx, AV_LOG_INFO,
1175
                                       "Ignoring unknown eye mode 0x%x\n",
1176
                                       (uint32_t) num);
1177
                                break;
1178
                            }
1179
                            videotrack->eye_mode = num;
1180
                            break;
1181
                        }
1182
1183
                        /* aspect ratio behaviour */
1184
                        case MATROSKA_ID_VIDEOASPECTRATIO: {
1185
                            uint64_t num;
1186
                            if ((res = ebml_read_uint(matroska, &id,
1187
                                                      &num)) < 0)
1188
                                break;
1189
                            if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1190
                                num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1191
                                num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1192
                                av_log(matroska->ctx, AV_LOG_INFO,
1193
                                       "Ignoring unknown aspect ratio 0x%x\n",
1194
                                       (uint32_t) num);
1195
                                break;
1196
                            }
1197
                            videotrack->ar_mode = num;
1198
                            break;
1199
                        }
1200
1201
                        /* colourspace (only matters for raw video)
1202
                         * fourcc */
1203
                        case MATROSKA_ID_VIDEOCOLOURSPACE: {
1204
                            uint64_t num;
1205
                            if ((res = ebml_read_uint(matroska, &id,
1206
                                                      &num)) < 0)
1207
                                break;
1208
                            videotrack->fourcc = num;
1209
                            break;
1210
                        }
1211
1212
                        default:
1213
                            av_log(matroska->ctx, AV_LOG_INFO,
1214
                                   "Unknown video track header entry "
1215
                                   "0x%x - ignoring\n", id);
1216
                            /* pass-through */
1217
1218
                        case EBML_ID_VOID:
1219
                            res = ebml_read_skip(matroska);
1220
                            break;
1221
                    }
1222
1223
                    if (matroska->level_up) {
1224
                        matroska->level_up--;
1225
                        break;
1226
                    }
1227
                }
1228
                break;
1229
            }
1230
1231
            /* tracktype specific stuff for audio */
1232
            case MATROSKA_ID_TRACKAUDIO: {
1233
                MatroskaAudioTrack *audiotrack;
1234
                if (!track->type)
1235
                    track->type = MATROSKA_TRACK_TYPE_AUDIO;
1236
                if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1237
                    av_log(matroska->ctx, AV_LOG_INFO,
1238
                           "audio data in non-audio track - ignoring\n");
1239
                    res = AVERROR_INVALIDDATA;
1240
                    break;
1241
                } else if ((res = ebml_read_master(matroska, &id)) < 0)
1242
                    break;
1243
                audiotrack = (MatroskaAudioTrack *)track;
1244
                audiotrack->channels = 1;
1245
                audiotrack->samplerate = 8000;
1246
1247
                while (res == 0) {
1248
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1249 6f3e0b21 Panagiotis Issaris
                        res = AVERROR(EIO);
1250 b061d892 David Conrad
                        break;
1251
                    } else if (matroska->level_up > 0) {
1252
                        matroska->level_up--;
1253
                        break;
1254
                    }
1255
1256
                    switch (id) {
1257
                        /* samplerate */
1258
                        case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1259
                            double num;
1260
                            if ((res = ebml_read_float(matroska, &id,
1261
                                                       &num)) < 0)
1262
                                break;
1263
                            audiotrack->internal_samplerate =
1264
                            audiotrack->samplerate = num;
1265
                            break;
1266
                        }
1267
1268
                        case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1269
                            double num;
1270
                            if ((res = ebml_read_float(matroska, &id,
1271
                                                       &num)) < 0)
1272
                                break;
1273
                            audiotrack->samplerate = num;
1274
                            break;
1275
                        }
1276
1277
                            /* bitdepth */
1278
                        case MATROSKA_ID_AUDIOBITDEPTH: {
1279
                            uint64_t num;
1280
                            if ((res = ebml_read_uint(matroska, &id,
1281
                                                      &num)) < 0)
1282
                                break;
1283
                            audiotrack->bitdepth = num;
1284
                            break;
1285
                        }
1286
1287
                            /* channels */
1288
                        case MATROSKA_ID_AUDIOCHANNELS: {
1289
                            uint64_t num;
1290
                            if ((res = ebml_read_uint(matroska, &id,
1291
                                                      &num)) < 0)
1292
                                break;
1293
                            audiotrack->channels = num;
1294
                            break;
1295
                        }
1296
1297
                        default:
1298
                            av_log(matroska->ctx, AV_LOG_INFO,
1299
                                   "Unknown audio track header entry "
1300
                                   "0x%x - ignoring\n", id);
1301
                            /* pass-through */
1302
1303
                        case EBML_ID_VOID:
1304
                            res = ebml_read_skip(matroska);
1305
                            break;
1306
                    }
1307
1308
                    if (matroska->level_up) {
1309
                        matroska->level_up--;
1310
                        break;
1311
                    }
1312
                }
1313
                break;
1314
            }
1315
1316
                /* codec identifier */
1317
            case MATROSKA_ID_CODECID: {
1318
                char *text;
1319
                if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1320
                    break;
1321
                track->codec_id = text;
1322
                break;
1323
            }
1324
1325
                /* codec private data */
1326
            case MATROSKA_ID_CODECPRIVATE: {
1327
                uint8_t *data;
1328
                int size;
1329
                if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1330
                    break;
1331
                track->codec_priv = data;
1332
                track->codec_priv_size = size;
1333
                break;
1334
            }
1335
1336
                /* name of the codec */
1337
            case MATROSKA_ID_CODECNAME: {
1338
                char *text;
1339
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1340
                    break;
1341
                track->codec_name = text;
1342
                break;
1343
            }
1344
1345
                /* name of this track */
1346
            case MATROSKA_ID_TRACKNAME: {
1347
                char *text;
1348
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1349
                    break;
1350
                track->name = text;
1351
                break;
1352
            }
1353
1354
                /* language (matters for audio/subtitles, mostly) */
1355
            case MATROSKA_ID_TRACKLANGUAGE: {
1356 463d5bcc Aurelien Jacobs
                char *text, *end;
1357 b061d892 David Conrad
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1358
                    break;
1359 463d5bcc Aurelien Jacobs
                if ((end = strchr(text, '-')))
1360
                    *end = '\0';
1361
                if (strlen(text) == 3)
1362
                    strcpy(track->language, text);
1363
                av_free(text);
1364 b061d892 David Conrad
                break;
1365
            }
1366
1367
                /* whether this is actually used */
1368
            case MATROSKA_ID_TRACKFLAGENABLED: {
1369
                uint64_t num;
1370
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1371
                    break;
1372
                if (num)
1373
                    track->flags |= MATROSKA_TRACK_ENABLED;
1374
                else
1375
                    track->flags &= ~MATROSKA_TRACK_ENABLED;
1376
                break;
1377
            }
1378
1379
                /* whether it's the default for this track type */
1380
            case MATROSKA_ID_TRACKFLAGDEFAULT: {
1381
                uint64_t num;
1382
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1383
                    break;
1384
                if (num)
1385
                    track->flags |= MATROSKA_TRACK_DEFAULT;
1386
                else
1387
                    track->flags &= ~MATROSKA_TRACK_DEFAULT;
1388
                break;
1389
            }
1390
1391
                /* lacing (like MPEG, where blocks don't end/start on frame
1392
                 * boundaries) */
1393
            case MATROSKA_ID_TRACKFLAGLACING: {
1394
                uint64_t num;
1395
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1396
                    break;
1397
                if (num)
1398
                    track->flags |= MATROSKA_TRACK_LACING;
1399
                else
1400
                    track->flags &= ~MATROSKA_TRACK_LACING;
1401
                break;
1402
            }
1403
1404
                /* default length (in time) of one data block in this track */
1405
            case MATROSKA_ID_TRACKDEFAULTDURATION: {
1406
                uint64_t num;
1407
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1408
                    break;
1409
                track->default_duration = num / matroska->time_scale;
1410
                break;
1411
            }
1412
1413
            default:
1414
                av_log(matroska->ctx, AV_LOG_INFO,
1415
                       "Unknown track header entry 0x%x - ignoring\n", id);
1416
                /* pass-through */
1417
1418
            case EBML_ID_VOID:
1419
            /* we ignore these because they're nothing useful. */
1420
            case MATROSKA_ID_CODECINFOURL:
1421
            case MATROSKA_ID_CODECDOWNLOADURL:
1422
            case MATROSKA_ID_TRACKMINCACHE:
1423
            case MATROSKA_ID_TRACKMAXCACHE:
1424
                res = ebml_read_skip(matroska);
1425
                break;
1426
        }
1427
1428
        if (matroska->level_up) {
1429
            matroska->level_up--;
1430
            break;
1431
        }
1432
    }
1433
1434
    return res;
1435
}
1436
1437
static int
1438
matroska_parse_tracks (MatroskaDemuxContext *matroska)
1439
{
1440
    int res = 0;
1441
    uint32_t id;
1442
1443
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1444
1445
    while (res == 0) {
1446
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1447 6f3e0b21 Panagiotis Issaris
            res = AVERROR(EIO);
1448 b061d892 David Conrad
            break;
1449
        } else if (matroska->level_up) {
1450
            matroska->level_up--;
1451
            break;
1452
        }
1453
1454
        switch (id) {
1455
            /* one track within the "all-tracks" header */
1456
            case MATROSKA_ID_TRACKENTRY:
1457
                res = matroska_add_stream(matroska);
1458
                break;
1459
1460
            default:
1461
                av_log(matroska->ctx, AV_LOG_INFO,
1462
                       "Unknown entry 0x%x in track header\n", id);
1463
                /* fall-through */
1464
1465
            case EBML_ID_VOID:
1466
                res = ebml_read_skip(matroska);
1467
                break;
1468
        }
1469
1470
        if (matroska->level_up) {
1471
            matroska->level_up--;
1472
            break;
1473
        }
1474
    }
1475
1476
    return res;
1477
}
1478
1479
static int
1480
matroska_parse_index (MatroskaDemuxContext *matroska)
1481
{
1482
    int res = 0;
1483
    uint32_t id;
1484
    MatroskaDemuxIndex idx;
1485
1486
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1487
1488
    while (res == 0) {
1489
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1490 6f3e0b21 Panagiotis Issaris
            res = AVERROR(EIO);
1491 b061d892 David Conrad
            break;
1492
        } else if (matroska->level_up) {
1493
            matroska->level_up--;
1494
            break;
1495
        }
1496
1497
        switch (id) {
1498
            /* one single index entry ('point') */
1499
            case MATROSKA_ID_POINTENTRY:
1500
                if ((res = ebml_read_master(matroska, &id)) < 0)
1501
                    break;
1502
1503
                /* in the end, we hope to fill one entry with a
1504
                 * timestamp, a file position and a tracknum */
1505
                idx.pos   = (uint64_t) -1;
1506
                idx.time  = (uint64_t) -1;
1507
                idx.track = (uint16_t) -1;
1508
1509
                while (res == 0) {
1510
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1511 6f3e0b21 Panagiotis Issaris
                        res = AVERROR(EIO);
1512 b061d892 David Conrad
                        break;
1513
                    } else if (matroska->level_up) {
1514
                        matroska->level_up--;
1515
                        break;
1516
                    }
1517
1518
                    switch (id) {
1519
                        /* one single index entry ('point') */
1520
                        case MATROSKA_ID_CUETIME: {
1521
                            uint64_t time;
1522
                            if ((res = ebml_read_uint(matroska, &id,
1523
                                                      &time)) < 0)
1524
                                break;
1525
                            idx.time = time * matroska->time_scale;
1526
                            break;
1527
                        }
1528
1529
                        /* position in the file + track to which it
1530
                         * belongs */
1531
                        case MATROSKA_ID_CUETRACKPOSITION:
1532
                            if ((res = ebml_read_master(matroska, &id)) < 0)
1533
                                break;
1534
1535
                            while (res == 0) {
1536
                                if (!(id = ebml_peek_id (matroska,
1537
                                                    &matroska->level_up))) {
1538 6f3e0b21 Panagiotis Issaris
                                    res = AVERROR(EIO);
1539 b061d892 David Conrad
                                    break;
1540
                                } else if (matroska->level_up) {
1541
                                    matroska->level_up--;
1542
                                    break;
1543
                                }
1544
1545
                                switch (id) {
1546
                                    /* track number */
1547
                                    case MATROSKA_ID_CUETRACK: {
1548
                                        uint64_t num;
1549
                                        if ((res = ebml_read_uint(matroska,
1550
                                                          &id, &num)) < 0)
1551
                                            break;
1552
                                        idx.track = num;
1553
                                        break;
1554
                                    }
1555
1556
                                        /* position in file */
1557
                                    case MATROSKA_ID_CUECLUSTERPOSITION: {
1558
                                        uint64_t num;
1559
                                        if ((res = ebml_read_uint(matroska,
1560
                                                          &id, &num)) < 0)
1561
                                            break;
1562
                                        idx.pos = num+matroska->segment_start;
1563
                                        break;
1564
                                    }
1565
1566
                                    default:
1567
                                        av_log(matroska->ctx, AV_LOG_INFO,
1568
                                               "Unknown entry 0x%x in "
1569
                                               "CuesTrackPositions\n", id);
1570
                                        /* fall-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
1583
                            break;
1584
1585
                        default:
1586
                            av_log(matroska->ctx, AV_LOG_INFO,
1587
                                   "Unknown entry 0x%x in cuespoint "
1588
                                   "index\n", id);
1589
                            /* fall-through */
1590
1591
                        case EBML_ID_VOID:
1592
                            res = ebml_read_skip(matroska);
1593
                            break;
1594
                    }
1595
1596
                    if (matroska->level_up) {
1597
                        matroska->level_up--;
1598
                        break;
1599
                    }
1600
                }
1601
1602
                /* so let's see if we got what we wanted */
1603
                if (idx.pos   != (uint64_t) -1 &&
1604
                    idx.time  != (uint64_t) -1 &&
1605
                    idx.track != (uint16_t) -1) {
1606
                    if (matroska->num_indexes % 32 == 0) {
1607
                        /* re-allocate bigger index */
1608
                        matroska->index =
1609
                            av_realloc(matroska->index,
1610
                                       (matroska->num_indexes + 32) *
1611
                                       sizeof(MatroskaDemuxIndex));
1612
                    }
1613
                    matroska->index[matroska->num_indexes] = idx;
1614
                    matroska->num_indexes++;
1615
                }
1616
                break;
1617
1618
            default:
1619
                av_log(matroska->ctx, AV_LOG_INFO,
1620
                       "Unknown entry 0x%x in cues header\n", id);
1621
                /* fall-through */
1622
1623
            case EBML_ID_VOID:
1624
                res = ebml_read_skip(matroska);
1625
                break;
1626
        }
1627
1628
        if (matroska->level_up) {
1629
            matroska->level_up--;
1630
            break;
1631
        }
1632
    }
1633
1634
    return res;
1635
}
1636
1637
static int
1638
matroska_parse_metadata (MatroskaDemuxContext *matroska)
1639
{
1640
    int res = 0;
1641
    uint32_t id;
1642
1643
    while (res == 0) {
1644
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1645 6f3e0b21 Panagiotis Issaris
            res = AVERROR(EIO);
1646 b061d892 David Conrad
            break;
1647
        } else if (matroska->level_up) {
1648
            matroska->level_up--;
1649
            break;
1650
        }
1651
1652
        switch (id) {
1653
            /* Hm, this is unsupported... */
1654
            default:
1655
                av_log(matroska->ctx, AV_LOG_INFO,
1656
                       "Unknown entry 0x%x in metadata header\n", id);
1657
                /* fall-through */
1658
1659
            case EBML_ID_VOID:
1660
                res = ebml_read_skip(matroska);
1661
                break;
1662
        }
1663
1664
        if (matroska->level_up) {
1665
            matroska->level_up--;
1666
            break;
1667
        }
1668
    }
1669
1670
    return res;
1671
}
1672
1673
static int
1674
matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1675
{
1676
    int res = 0;
1677
    uint32_t id;
1678
1679
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1680
1681
    while (res == 0) {
1682
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1683 6f3e0b21 Panagiotis Issaris
            res = AVERROR(EIO);
1684 b061d892 David Conrad
            break;
1685
        } else if (matroska->level_up) {
1686
            matroska->level_up--;
1687
            break;
1688
        }
1689
1690
        switch (id) {
1691
            case MATROSKA_ID_SEEKENTRY: {
1692
                uint32_t seek_id = 0, peek_id_cache = 0;
1693
                uint64_t seek_pos = (uint64_t) -1, t;
1694
1695
                if ((res = ebml_read_master(matroska, &id)) < 0)
1696
                    break;
1697
1698
                while (res == 0) {
1699
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1700 6f3e0b21 Panagiotis Issaris
                        res = AVERROR(EIO);
1701 b061d892 David Conrad
                        break;
1702
                    } else if (matroska->level_up) {
1703
                        matroska->level_up--;
1704
                        break;
1705
                    }
1706
1707
                    switch (id) {
1708
                        case MATROSKA_ID_SEEKID:
1709
                            res = ebml_read_uint(matroska, &id, &t);
1710
                            seek_id = t;
1711
                            break;
1712
1713
                        case MATROSKA_ID_SEEKPOSITION:
1714
                            res = ebml_read_uint(matroska, &id, &seek_pos);
1715
                            break;
1716
1717
                        default:
1718
                            av_log(matroska->ctx, AV_LOG_INFO,
1719
                                   "Unknown seekhead ID 0x%x\n", id);
1720
                            /* fall-through */
1721
1722
                        case EBML_ID_VOID:
1723
                            res = ebml_read_skip(matroska);
1724
                            break;
1725
                    }
1726
1727
                    if (matroska->level_up) {
1728
                        matroska->level_up--;
1729
                        break;
1730
                    }
1731
                }
1732
1733
                if (!seek_id || seek_pos == (uint64_t) -1) {
1734
                    av_log(matroska->ctx, AV_LOG_INFO,
1735
                           "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1736
                           seek_id, seek_pos);
1737
                    break;
1738
                }
1739
1740
                switch (seek_id) {
1741
                    case MATROSKA_ID_CUES:
1742
                    case MATROSKA_ID_TAGS: {
1743
                        uint32_t level_up = matroska->level_up;
1744
                        offset_t before_pos;
1745
                        uint64_t length;
1746
                        MatroskaLevel level;
1747
1748
                        /* remember the peeked ID and the current position */
1749
                        peek_id_cache = matroska->peek_id;
1750
                        before_pos = url_ftell(&matroska->ctx->pb);
1751
1752
                        /* seek */
1753
                        if ((res = ebml_read_seek(matroska, seek_pos +
1754
                                               matroska->segment_start)) < 0)
1755
                            return res;
1756
1757
                        /* we don't want to lose our seekhead level, so we add
1758
                         * a dummy. This is a crude hack. */
1759
                        if (matroska->num_levels == EBML_MAX_DEPTH) {
1760
                            av_log(matroska->ctx, AV_LOG_INFO,
1761
                                   "Max EBML element depth (%d) reached, "
1762
                                   "cannot parse further.\n", EBML_MAX_DEPTH);
1763
                            return AVERROR_UNKNOWN;
1764
                        }
1765
1766
                        level.start = 0;
1767
                        level.length = (uint64_t)-1;
1768
                        matroska->levels[matroska->num_levels] = level;
1769
                        matroska->num_levels++;
1770
1771
                        /* check ID */
1772
                        if (!(id = ebml_peek_id (matroska,
1773
                                                 &matroska->level_up)))
1774
                            goto finish;
1775
                        if (id != seek_id) {
1776
                            av_log(matroska->ctx, AV_LOG_INFO,
1777
                                   "We looked for ID=0x%x but got "
1778
                                   "ID=0x%x (pos=%"PRIu64")",
1779
                                   seek_id, id, seek_pos +
1780
                                   matroska->segment_start);
1781
                            goto finish;
1782
                        }
1783
1784
                        /* read master + parse */
1785
                        if ((res = ebml_read_master(matroska, &id)) < 0)
1786
                            goto finish;
1787
                        switch (id) {
1788
                            case MATROSKA_ID_CUES:
1789
                                if (!(res = matroska_parse_index(matroska)) ||
1790
                                    url_feof(&matroska->ctx->pb)) {
1791
                                    matroska->index_parsed = 1;
1792
                                    res = 0;
1793
                                }
1794
                                break;
1795
                            case MATROSKA_ID_TAGS:
1796
                                if (!(res = matroska_parse_metadata(matroska)) ||
1797
                                   url_feof(&matroska->ctx->pb)) {
1798
                                    matroska->metadata_parsed = 1;
1799
                                    res = 0;
1800
                                }
1801
                                break;
1802
                        }
1803
1804
                    finish:
1805
                        /* remove dummy level */
1806
                        while (matroska->num_levels) {
1807
                            matroska->num_levels--;
1808
                            length =
1809
                                matroska->levels[matroska->num_levels].length;
1810
                            if (length == (uint64_t)-1)
1811
                                break;
1812
                        }
1813
1814
                        /* seek back */
1815
                        if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1816
                            return res;
1817
                        matroska->peek_id = peek_id_cache;
1818
                        matroska->level_up = level_up;
1819
                        break;
1820
                    }
1821
1822
                    default:
1823
                        av_log(matroska->ctx, AV_LOG_INFO,
1824
                               "Ignoring seekhead entry for ID=0x%x\n",
1825
                               seek_id);
1826
                        break;
1827
                }
1828
1829
                break;
1830
            }
1831
1832
            default:
1833
                av_log(matroska->ctx, AV_LOG_INFO,
1834
                       "Unknown seekhead ID 0x%x\n", id);
1835
                /* fall-through */
1836
1837
            case EBML_ID_VOID:
1838
                res = ebml_read_skip(matroska);
1839
                break;
1840
        }
1841
1842
        if (matroska->level_up) {
1843
            matroska->level_up--;
1844
            break;
1845
        }
1846
    }
1847
1848
    return res;
1849
}
1850
1851
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
1852
1853
static int
1854
matroska_aac_profile (char *codec_id)
1855
{
1856
    static const char *aac_profiles[] = {
1857
        "MAIN", "LC", "SSR"
1858
    };
1859
    int profile;
1860
1861
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1862
        if (strstr(codec_id, aac_profiles[profile]))
1863
            break;
1864
    return profile + 1;
1865
}
1866
1867
static int
1868
matroska_aac_sri (int samplerate)
1869
{
1870
    static const int aac_sample_rates[] = {
1871
        96000, 88200, 64000, 48000, 44100, 32000,
1872
        24000, 22050, 16000, 12000, 11025,  8000,
1873
    };
1874
    int sri;
1875
1876
    for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
1877
        if (aac_sample_rates[sri] == samplerate)
1878
            break;
1879
    return sri;
1880
}
1881
1882
static int
1883
matroska_read_header (AVFormatContext    *s,
1884
                      AVFormatParameters *ap)
1885
{
1886
    MatroskaDemuxContext *matroska = s->priv_data;
1887
    char *doctype;
1888
    int version, last_level, res = 0;
1889
    uint32_t id;
1890
1891
    matroska->ctx = s;
1892
1893
    /* First read the EBML header. */
1894
    doctype = NULL;
1895
    if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
1896
        return res;
1897
    if ((doctype == NULL) || strcmp(doctype, "matroska")) {
1898
        av_log(matroska->ctx, AV_LOG_ERROR,
1899
               "Wrong EBML doctype ('%s' != 'matroska').\n",
1900
               doctype ? doctype : "(none)");
1901
        if (doctype)
1902
            av_free(doctype);
1903
        return AVERROR_NOFMT;
1904
    }
1905
    av_free(doctype);
1906
    if (version > 2) {
1907
        av_log(matroska->ctx, AV_LOG_ERROR,
1908
               "Matroska demuxer version 2 too old for file version %d\n",
1909
               version);
1910
        return AVERROR_NOFMT;
1911
    }
1912
1913
    /* The next thing is a segment. */
1914
    while (1) {
1915
        if (!(id = ebml_peek_id(matroska, &last_level)))
1916 6f3e0b21 Panagiotis Issaris
            return AVERROR(EIO);
1917 b061d892 David Conrad
        if (id == MATROSKA_ID_SEGMENT)
1918
            break;
1919
1920
        /* oi! */
1921
        av_log(matroska->ctx, AV_LOG_INFO,
1922
               "Expected a Segment ID (0x%x), but received 0x%x!\n",
1923
               MATROSKA_ID_SEGMENT, id);
1924
        if ((res = ebml_read_skip(matroska)) < 0)
1925
            return res;
1926
    }
1927
1928
    /* We now have a Matroska segment.
1929
     * Seeks are from the beginning of the segment,
1930
     * after the segment ID/length. */
1931
    if ((res = ebml_read_master(matroska, &id)) < 0)
1932
        return res;
1933
    matroska->segment_start = url_ftell(&s->pb);
1934
1935
    matroska->time_scale = 1000000;
1936
    /* we've found our segment, start reading the different contents in here */
1937
    while (res == 0) {
1938
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1939 6f3e0b21 Panagiotis Issaris
            res = AVERROR(EIO);
1940 b061d892 David Conrad
            break;
1941
        } else if (matroska->level_up) {
1942
            matroska->level_up--;
1943
            break;
1944
        }
1945
1946
        switch (id) {
1947
            /* stream info */
1948
            case MATROSKA_ID_INFO: {
1949
                if ((res = ebml_read_master(matroska, &id)) < 0)
1950
                    break;
1951
                res = matroska_parse_info(matroska);
1952
                break;
1953
            }
1954
1955
            /* track info headers */
1956
            case MATROSKA_ID_TRACKS: {
1957
                if ((res = ebml_read_master(matroska, &id)) < 0)
1958
                    break;
1959
                res = matroska_parse_tracks(matroska);
1960
                break;
1961
            }
1962
1963
            /* stream index */
1964
            case MATROSKA_ID_CUES: {
1965
                if (!matroska->index_parsed) {
1966
                    if ((res = ebml_read_master(matroska, &id)) < 0)
1967
                        break;
1968
                    res = matroska_parse_index(matroska);
1969
                } else
1970
                    res = ebml_read_skip(matroska);
1971
                break;
1972
            }
1973
1974
            /* metadata */
1975
            case MATROSKA_ID_TAGS: {
1976
                if (!matroska->metadata_parsed) {
1977
                    if ((res = ebml_read_master(matroska, &id)) < 0)
1978
                        break;
1979
                    res = matroska_parse_metadata(matroska);
1980
                } else
1981
                    res = ebml_read_skip(matroska);
1982
                break;
1983
            }
1984
1985
            /* file index (if seekable, seek to Cues/Tags to parse it) */
1986
            case MATROSKA_ID_SEEKHEAD: {
1987
                if ((res = ebml_read_master(matroska, &id)) < 0)
1988
                    break;
1989
                res = matroska_parse_seekhead(matroska);
1990
                break;
1991
            }
1992
1993
            case MATROSKA_ID_CLUSTER: {
1994
                /* Do not read the master - this will be done in the next
1995
                 * call to matroska_read_packet. */
1996
                res = 1;
1997
                break;
1998
            }
1999
2000
            default:
2001
                av_log(matroska->ctx, AV_LOG_INFO,
2002
                       "Unknown matroska file header ID 0x%x\n", id);
2003
            /* fall-through */
2004
2005
            case EBML_ID_VOID:
2006
                res = ebml_read_skip(matroska);
2007
                break;
2008
        }
2009
2010
        if (matroska->level_up) {
2011
            matroska->level_up--;
2012
            break;
2013
        }
2014
    }
2015
2016
    /* Have we found a cluster? */
2017
    if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2018
        int i, j;
2019
        MatroskaTrack *track;
2020
        AVStream *st;
2021
2022
        for (i = 0; i < matroska->num_tracks; i++) {
2023
            enum CodecID codec_id = CODEC_ID_NONE;
2024
            uint8_t *extradata = NULL;
2025
            int extradata_size = 0;
2026
            int extradata_offset = 0;
2027
            track = matroska->tracks[i];
2028 2def9cd9 Aurelien Jacobs
            track->stream_index = -1;
2029 b061d892 David Conrad
2030 f7e97aaf Aurelien Jacobs
            /* Apply some sanity checks. */
2031
            if (track->codec_id == NULL)
2032 b061d892 David Conrad
                continue;
2033
2034
            for(j=0; ff_mkv_codec_tags[j].str; j++){
2035
                if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2036
                            strlen(ff_mkv_codec_tags[j].str))){
2037
                    codec_id= ff_mkv_codec_tags[j].id;
2038
                    break;
2039
                }
2040
            }
2041
2042
            /* Set the FourCC from the CodecID. */
2043
            /* This is the MS compatibility mode which stores a
2044
             * BITMAPINFOHEADER in the CodecPrivate. */
2045
            if (!strcmp(track->codec_id,
2046
                        MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2047
                (track->codec_priv_size >= 40) &&
2048
                (track->codec_priv != NULL)) {
2049 2ce746c6 Aurelien Jacobs
                MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2050 b061d892 David Conrad
2051
                /* Offset of biCompression. Stored in LE. */
2052 2ce746c6 Aurelien Jacobs
                vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2053
                codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2054 b061d892 David Conrad
2055
            }
2056
2057
            /* This is the MS compatibility mode which stores a
2058
             * WAVEFORMATEX in the CodecPrivate. */
2059
            else if (!strcmp(track->codec_id,
2060
                             MATROSKA_CODEC_ID_AUDIO_ACM) &&
2061
                (track->codec_priv_size >= 18) &&
2062
                (track->codec_priv != NULL)) {
2063
                uint16_t tag;
2064
2065
                /* Offset of wFormatTag. Stored in LE. */
2066 2ce746c6 Aurelien Jacobs
                tag = AV_RL16(track->codec_priv);
2067 b061d892 David Conrad
                codec_id = codec_get_id(codec_wav_tags, tag);
2068
2069
            }
2070
2071
            else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2072
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2073
                int profile = matroska_aac_profile(track->codec_id);
2074
                int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2075
                extradata = av_malloc(5);
2076
                if (extradata == NULL)
2077 769e10f0 Panagiotis Issaris
                    return AVERROR(ENOMEM);
2078 b061d892 David Conrad
                extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2079
                extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2080
                if (strstr(track->codec_id, "SBR")) {
2081
                    sri = matroska_aac_sri(audiotrack->samplerate);
2082
                    extradata[2] = 0x56;
2083
                    extradata[3] = 0xE5;
2084
                    extradata[4] = 0x80 | (sri<<3);
2085
                    extradata_size = 5;
2086
                } else {
2087
                    extradata_size = 2;
2088
                }
2089
                track->default_duration = 1024*1000 / audiotrack->internal_samplerate;
2090
            }
2091
2092
            else if (codec_id == CODEC_ID_TTA) {
2093
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2094
                ByteIOContext b;
2095
                extradata_size = 30;
2096
                extradata = av_mallocz(extradata_size);
2097
                if (extradata == NULL)
2098 769e10f0 Panagiotis Issaris
                    return AVERROR(ENOMEM);
2099 b061d892 David Conrad
                init_put_byte(&b, extradata, extradata_size, 1,
2100
                              NULL, NULL, NULL, NULL);
2101
                put_buffer(&b, (uint8_t *) "TTA1", 4);
2102
                put_le16(&b, 1);
2103
                put_le16(&b, audiotrack->channels);
2104
                put_le16(&b, audiotrack->bitdepth);
2105
                put_le32(&b, audiotrack->samplerate);
2106
                put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2107
            }
2108
2109
            else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2110
                     codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2111
                extradata_offset = 26;
2112
                track->codec_priv_size -= extradata_offset;
2113
                track->flags |= MATROSKA_TRACK_REAL_V;
2114
            }
2115
2116 eabb8ba4 Aurelien Jacobs
            else if (codec_id == CODEC_ID_RA_144) {
2117
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2118
                audiotrack->samplerate = 8000;
2119
                audiotrack->channels = 1;
2120
            }
2121
2122
            else if (codec_id == CODEC_ID_RA_288 ||
2123
                     codec_id == CODEC_ID_COOK ||
2124
                     codec_id == CODEC_ID_ATRAC3) {
2125
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2126
                ByteIOContext b;
2127
2128
                init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2129
                              NULL, NULL, NULL, NULL);
2130
                url_fskip(&b, 24);
2131
                audiotrack->coded_framesize = get_be32(&b);
2132
                url_fskip(&b, 12);
2133
                audiotrack->sub_packet_h    = get_be16(&b);
2134
                audiotrack->frame_size      = get_be16(&b);
2135
                audiotrack->sub_packet_size = get_be16(&b);
2136
                audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2137
                if (codec_id == CODEC_ID_RA_288) {
2138
                    audiotrack->block_align = audiotrack->coded_framesize;
2139
                    track->codec_priv_size = 0;
2140
                } else {
2141
                    audiotrack->block_align = audiotrack->sub_packet_size;
2142
                    extradata_offset = 78;
2143
                    track->codec_priv_size -= extradata_offset;
2144
                }
2145
            }
2146
2147 979c0910 Aurelien Jacobs
            else if (codec_id == CODEC_ID_TEXT) {
2148
                MatroskaSubtitleTrack *subtrack=(MatroskaSubtitleTrack *)track;
2149
                if (!strcmp(track->codec_id, "S_TEXT/ASS") ||
2150 ee8c87b5 Aurelien Jacobs
                    !strcmp(track->codec_id, "S_TEXT/SSA") ||
2151
                    !strcmp(track->codec_id, "S_ASS") ||
2152
                    !strcmp(track->codec_id, "S_SSA"))
2153 979c0910 Aurelien Jacobs
                    subtrack->ass = 1;
2154
            }
2155
2156 b061d892 David Conrad
            if (codec_id == CODEC_ID_NONE) {
2157
                av_log(matroska->ctx, AV_LOG_INFO,
2158
                       "Unknown/unsupported CodecID %s.\n",
2159
                       track->codec_id);
2160
            }
2161
2162
            track->stream_index = matroska->num_streams;
2163
2164
            matroska->num_streams++;
2165
            st = av_new_stream(s, track->stream_index);
2166
            if (st == NULL)
2167 769e10f0 Panagiotis Issaris
                return AVERROR(ENOMEM);
2168 b061d892 David Conrad
            av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2169
2170
            st->codec->codec_id = codec_id;
2171
            st->start_time = 0;
2172 463d5bcc Aurelien Jacobs
            if (strcmp(track->language, "und"))
2173
                strcpy(st->language, track->language);
2174 b061d892 David Conrad
2175
            if (track->default_duration)
2176
                av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2177
                          track->default_duration, 1000, 30000);
2178
2179
            if(extradata){
2180
                st->codec->extradata = extradata;
2181
                st->codec->extradata_size = extradata_size;
2182
            } else if(track->codec_priv && track->codec_priv_size > 0){
2183
                st->codec->extradata = av_malloc(track->codec_priv_size);
2184
                if(st->codec->extradata == NULL)
2185 769e10f0 Panagiotis Issaris
                    return AVERROR(ENOMEM);
2186 b061d892 David Conrad
                st->codec->extradata_size = track->codec_priv_size;
2187
                memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2188
                       track->codec_priv_size);
2189
            }
2190
2191
            if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2192
                MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2193
2194
                st->codec->codec_type = CODEC_TYPE_VIDEO;
2195
                st->codec->codec_tag = videotrack->fourcc;
2196
                st->codec->width = videotrack->pixel_width;
2197
                st->codec->height = videotrack->pixel_height;
2198
                if (videotrack->display_width == 0)
2199
                    videotrack->display_width= videotrack->pixel_width;
2200
                if (videotrack->display_height == 0)
2201
                    videotrack->display_height= videotrack->pixel_height;
2202
                av_reduce(&st->codec->sample_aspect_ratio.num,
2203
                          &st->codec->sample_aspect_ratio.den,
2204
                          st->codec->height * videotrack->display_width,
2205
                          st->codec-> width * videotrack->display_height,
2206
                          255);
2207
                st->need_parsing = AVSTREAM_PARSE_HEADERS;
2208
            } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2209
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2210
2211
                st->codec->codec_type = CODEC_TYPE_AUDIO;
2212
                st->codec->sample_rate = audiotrack->samplerate;
2213
                st->codec->channels = audiotrack->channels;
2214 eabb8ba4 Aurelien Jacobs
                st->codec->block_align = audiotrack->block_align;
2215 b061d892 David Conrad
            } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2216
                st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2217
            }
2218
2219
            /* What do we do with private data? E.g. for Vorbis. */
2220
        }
2221
        res = 0;
2222
    }
2223
2224
    if (matroska->index_parsed) {
2225
        int i, track, stream;
2226
        for (i=0; i<matroska->num_indexes; i++) {
2227
            MatroskaDemuxIndex *idx = &matroska->index[i];
2228
            track = matroska_find_track_by_num(matroska, idx->track);
2229
            stream = matroska->tracks[track]->stream_index;
2230 2def9cd9 Aurelien Jacobs
            if (stream >= 0)
2231 ffaa3ecb Aurelien Jacobs
                av_add_index_entry(matroska->ctx->streams[stream],
2232
                                   idx->pos, idx->time/matroska->time_scale,
2233
                                   0, 0, AVINDEX_KEYFRAME);
2234 b061d892 David Conrad
        }
2235
    }
2236
2237
    return res;
2238
}
2239
2240
static inline int
2241
rv_offset(uint8_t *data, int slice, int slices)
2242
{
2243
    return AV_RL32(data+8*slice+4) + 8*slices;
2244
}
2245
2246
static int
2247
matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2248
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
2249
                     int is_keyframe, int is_bframe)
2250
{
2251
    int res = 0;
2252
    int track;
2253
    AVStream *st;
2254
    AVPacket *pkt;
2255
    uint8_t *origdata = data;
2256
    int16_t block_time;
2257
    uint32_t *lace_size = NULL;
2258
    int n, flags, laces = 0;
2259
    uint64_t num;
2260
2261
    /* first byte(s): tracknum */
2262
    if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2263
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2264
        av_free(origdata);
2265
        return res;
2266
    }
2267
    data += n;
2268
    size -= n;
2269
2270
    /* fetch track from num */
2271
    track = matroska_find_track_by_num(matroska, num);
2272
    if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2273
        av_log(matroska->ctx, AV_LOG_INFO,
2274
               "Invalid stream %d or size %u\n", track, size);
2275
        av_free(origdata);
2276
        return res;
2277
    }
2278 2def9cd9 Aurelien Jacobs
    if (matroska->tracks[track]->stream_index < 0)
2279
        return res;
2280 b061d892 David Conrad
    st = matroska->ctx->streams[matroska->tracks[track]->stream_index];
2281
    if (st->discard >= AVDISCARD_ALL) {
2282
        av_free(origdata);
2283
        return res;
2284
    }
2285
    if (duration == AV_NOPTS_VALUE)
2286
        duration = matroska->tracks[track]->default_duration;
2287
2288
    /* block_time (relative to cluster time) */
2289 2ce746c6 Aurelien Jacobs
    block_time = AV_RB16(data);
2290 b061d892 David Conrad
    data += 2;
2291 1607c534 Aurelien Jacobs
    flags = *data++;
2292
    size -= 3;
2293 b061d892 David Conrad
    if (is_keyframe == -1)
2294
        is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;
2295
2296
    if (matroska->skip_to_keyframe) {
2297
        if (!is_keyframe || st != matroska->skip_to_stream)
2298
            return res;
2299
        matroska->skip_to_keyframe = 0;
2300
    }
2301
2302
    switch ((flags & 0x06) >> 1) {
2303
        case 0x0: /* no lacing */
2304
            laces = 1;
2305
            lace_size = av_mallocz(sizeof(int));
2306
            lace_size[0] = size;
2307
            break;
2308
2309
        case 0x1: /* xiph lacing */
2310
        case 0x2: /* fixed-size lacing */
2311
        case 0x3: /* EBML lacing */
2312
            if (size == 0) {
2313
                res = -1;
2314
                break;
2315
            }
2316
            laces = (*data) + 1;
2317
            data += 1;
2318
            size -= 1;
2319
            lace_size = av_mallocz(laces * sizeof(int));
2320
2321
            switch ((flags & 0x06) >> 1) {
2322
                case 0x1: /* xiph lacing */ {
2323
                    uint8_t temp;
2324
                    uint32_t total = 0;
2325
                    for (n = 0; res == 0 && n < laces - 1; n++) {
2326
                        while (1) {
2327
                            if (size == 0) {
2328
                                res = -1;
2329
                                break;
2330
                            }
2331
                            temp = *data;
2332
                            lace_size[n] += temp;
2333
                            data += 1;
2334
                            size -= 1;
2335
                            if (temp != 0xff)
2336
                                break;
2337
                        }
2338
                        total += lace_size[n];
2339
                    }
2340
                    lace_size[n] = size - total;
2341
                    break;
2342
                }
2343
2344
                case 0x2: /* fixed-size lacing */
2345
                    for (n = 0; n < laces; n++)
2346
                        lace_size[n] = size / laces;
2347
                    break;
2348
2349
                case 0x3: /* EBML lacing */ {
2350
                    uint32_t total;
2351
                    n = matroska_ebmlnum_uint(data, size, &num);
2352
                    if (n < 0) {
2353
                        av_log(matroska->ctx, AV_LOG_INFO,
2354
                               "EBML block data error\n");
2355
                        break;
2356
                    }
2357
                    data += n;
2358
                    size -= n;
2359
                    total = lace_size[0] = num;
2360
                    for (n = 1; res == 0 && n < laces - 1; n++) {
2361
                        int64_t snum;
2362
                        int r;
2363
                        r = matroska_ebmlnum_sint (data, size, &snum);
2364
                        if (r < 0) {
2365
                            av_log(matroska->ctx, AV_LOG_INFO,
2366
                                   "EBML block data error\n");
2367
                            break;
2368
                        }
2369
                        data += r;
2370
                        size -= r;
2371
                        lace_size[n] = lace_size[n - 1] + snum;
2372
                        total += lace_size[n];
2373
                    }
2374
                    lace_size[n] = size - total;
2375
                    break;
2376
                }
2377
            }
2378
            break;
2379
    }
2380
2381
    if (res == 0) {
2382
        int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
2383
        uint64_t timecode = AV_NOPTS_VALUE;
2384
2385 9c3e2f78 Aurelien Jacobs
        if (cluster_time != (uint64_t)-1
2386
            && (block_time >= 0 || cluster_time >= -block_time))
2387 b061d892 David Conrad
            timecode = cluster_time + block_time;
2388
2389
        for (n = 0; n < laces; n++) {
2390
            int slice, slices = 1;
2391
2392
            if (real_v) {
2393
                slices = *data++ + 1;
2394
                lace_size[n]--;
2395
            }
2396
2397
            for (slice=0; slice<slices; slice++) {
2398
                int slice_size, slice_offset = 0;
2399
                if (real_v)
2400
                    slice_offset = rv_offset(data, slice, slices);
2401
                if (slice+1 == slices)
2402
                    slice_size = lace_size[n] - slice_offset;
2403
                else
2404
                    slice_size = rv_offset(data, slice+1, slices) - slice_offset;
2405 eabb8ba4 Aurelien Jacobs
2406
                if (st->codec->codec_id == CODEC_ID_RA_288 ||
2407
                    st->codec->codec_id == CODEC_ID_COOK ||
2408
                    st->codec->codec_id == CODEC_ID_ATRAC3) {
2409
                    MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2410
                    int a = st->codec->block_align;
2411
                    int sps = audiotrack->sub_packet_size;
2412
                    int cfs = audiotrack->coded_framesize;
2413
                    int h = audiotrack->sub_packet_h;
2414
                    int y = audiotrack->sub_packet_cnt;
2415
                    int w = audiotrack->frame_size;
2416
                    int x;
2417
2418
                    if (!audiotrack->pkt_cnt) {
2419
                        if (st->codec->codec_id == CODEC_ID_RA_288)
2420
                            for (x=0; x<h/2; x++)
2421
                                memcpy(audiotrack->buf+x*2*w+y*cfs,
2422
                                       data+x*cfs, cfs);
2423
                        else
2424
                            for (x=0; x<w/sps; x++)
2425
                                memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2426
2427
                        if (++audiotrack->sub_packet_cnt >= h) {
2428
                            audiotrack->sub_packet_cnt = 0;
2429
                            audiotrack->pkt_cnt = h*w / a;
2430
                        }
2431
                    }
2432
                    while (audiotrack->pkt_cnt) {
2433
                        pkt = av_mallocz(sizeof(AVPacket));
2434
                        av_new_packet(pkt, a);
2435
                        memcpy(pkt->data, audiotrack->buf
2436
                               + a * (h*w / a - audiotrack->pkt_cnt--), a);
2437
                        pkt->pos = pos;
2438
                        pkt->stream_index = matroska->tracks[track]->stream_index;
2439
                        matroska_queue_packet(matroska, pkt);
2440
                    }
2441
                } else {
2442 979c0910 Aurelien Jacobs
                    int offset = 0;
2443
2444
                    if (st->codec->codec_id == CODEC_ID_TEXT
2445
                        && ((MatroskaSubtitleTrack *)(matroska->tracks[track]))->ass) {
2446
                        int i;
2447
                        for (i=0; i<8 && data[slice_offset+offset]; offset++)
2448
                            if (data[slice_offset+offset] == ',')
2449
                                i++;
2450
                    }
2451
2452 77abe5e8 Aurelien Jacobs
                    pkt = av_mallocz(sizeof(AVPacket));
2453
                    /* XXX: prevent data copy... */
2454 979c0910 Aurelien Jacobs
                    if (av_new_packet(pkt, slice_size-offset) < 0) {
2455 769e10f0 Panagiotis Issaris
                        res = AVERROR(ENOMEM);
2456 77abe5e8 Aurelien Jacobs
                        n = laces-1;
2457
                        break;
2458
                    }
2459 979c0910 Aurelien Jacobs
                    memcpy (pkt->data, data+slice_offset+offset, slice_size-offset);
2460 b061d892 David Conrad
2461 77abe5e8 Aurelien Jacobs
                    if (n == 0)
2462
                        pkt->flags = is_keyframe;
2463
                    pkt->stream_index = matroska->tracks[track]->stream_index;
2464 b061d892 David Conrad
2465 77abe5e8 Aurelien Jacobs
                    pkt->pts = timecode;
2466
                    pkt->pos = pos;
2467
                    pkt->duration = duration;
2468 b061d892 David Conrad
2469 77abe5e8 Aurelien Jacobs
                    matroska_queue_packet(matroska, pkt);
2470 eabb8ba4 Aurelien Jacobs
                }
2471 b061d892 David Conrad
2472
                if (timecode != AV_NOPTS_VALUE)
2473
                    timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2474
            }
2475
            data += lace_size[n];
2476
        }
2477
    }
2478
2479
    av_free(lace_size);
2480
    av_free(origdata);
2481
    return res;
2482
}
2483
2484
static int
2485
matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2486
                           uint64_t              cluster_time)
2487
{
2488
    int res = 0;
2489
    uint32_t id;
2490
    int is_bframe = 0;
2491
    int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2492
    uint64_t duration = AV_NOPTS_VALUE;
2493
    uint8_t *data;
2494
    int size = 0;
2495
    int64_t pos = 0;
2496
2497
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2498
2499
    while (res == 0) {
2500
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2501 6f3e0b21 Panagiotis Issaris
            res = AVERROR(EIO);
2502 b061d892 David Conrad
            break;
2503
        } else if (matroska->level_up) {
2504
            matroska->level_up--;
2505
            break;
2506
        }
2507
2508
        switch (id) {
2509
            /* one block inside the group. Note, block parsing is one
2510
             * of the harder things, so this code is a bit complicated.
2511
             * See http://www.matroska.org/ for documentation. */
2512
            case MATROSKA_ID_BLOCK: {
2513
                pos = url_ftell(&matroska->ctx->pb);
2514
                res = ebml_read_binary(matroska, &id, &data, &size);
2515
                break;
2516
            }
2517
2518
            case MATROSKA_ID_BLOCKDURATION: {
2519
                if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2520
                    break;
2521
                break;
2522
            }
2523
2524
            case MATROSKA_ID_BLOCKREFERENCE: {
2525
                int64_t num;
2526
                /* We've found a reference, so not even the first frame in
2527
                 * the lace is a key frame. */
2528
                is_keyframe = 0;
2529
                if (last_num_packets != matroska->num_packets)
2530
                    matroska->packets[last_num_packets]->flags = 0;
2531
                if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2532
                    break;
2533
                if (num > 0)
2534
                    is_bframe = 1;
2535
                break;
2536
            }
2537
2538
            default:
2539
                av_log(matroska->ctx, AV_LOG_INFO,
2540
                       "Unknown entry 0x%x in blockgroup data\n", id);
2541
                /* fall-through */
2542
2543
            case EBML_ID_VOID:
2544
                res = ebml_read_skip(matroska);
2545
                break;
2546
        }
2547
2548
        if (matroska->level_up) {
2549
            matroska->level_up--;
2550
            break;
2551
        }
2552
    }
2553
2554
    if (res)
2555
        return res;
2556
2557
    if (size > 0)
2558
        res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2559
                                   duration, is_keyframe, is_bframe);
2560
2561
    return res;
2562
}
2563
2564
static int
2565
matroska_parse_cluster (MatroskaDemuxContext *matroska)
2566
{
2567
    int res = 0;
2568
    uint32_t id;
2569
    uint64_t cluster_time = 0;
2570
    uint8_t *data;
2571
    int64_t pos;
2572
    int size;
2573
2574
    av_log(matroska->ctx, AV_LOG_DEBUG,
2575
           "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2576
2577
    while (res == 0) {
2578
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2579 6f3e0b21 Panagiotis Issaris
            res = AVERROR(EIO);
2580 b061d892 David Conrad
            break;
2581
        } else if (matroska->level_up) {
2582
            matroska->level_up--;
2583
            break;
2584
        }
2585
2586
        switch (id) {
2587
            /* cluster timecode */
2588
            case MATROSKA_ID_CLUSTERTIMECODE: {
2589
                uint64_t num;
2590
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2591
                    break;
2592
                cluster_time = num;
2593
                break;
2594
            }
2595
2596
                /* a group of blocks inside a cluster */
2597
            case MATROSKA_ID_BLOCKGROUP:
2598
                if ((res = ebml_read_master(matroska, &id)) < 0)
2599
                    break;
2600
                res = matroska_parse_blockgroup(matroska, cluster_time);
2601
                break;
2602
2603
            case MATROSKA_ID_SIMPLEBLOCK:
2604
                pos = url_ftell(&matroska->ctx->pb);
2605
                res = ebml_read_binary(matroska, &id, &data, &size);
2606
                if (res == 0)
2607
                    res = matroska_parse_block(matroska, data, size, pos,
2608
                                               cluster_time, AV_NOPTS_VALUE,
2609
                                               -1, 0);
2610
                break;
2611
2612
            default:
2613
                av_log(matroska->ctx, AV_LOG_INFO,
2614
                       "Unknown entry 0x%x in cluster data\n", id);
2615
                /* fall-through */
2616
2617
            case EBML_ID_VOID:
2618
                res = ebml_read_skip(matroska);
2619
                break;
2620
        }
2621
2622
        if (matroska->level_up) {
2623
            matroska->level_up--;
2624
            break;
2625
        }
2626
    }
2627
2628
    return res;
2629
}
2630
2631
static int
2632
matroska_read_packet (AVFormatContext *s,
2633
                      AVPacket        *pkt)
2634
{
2635
    MatroskaDemuxContext *matroska = s->priv_data;
2636 407a3d94 Aurelien Jacobs
    int res;
2637 b061d892 David Conrad
    uint32_t id;
2638
2639
    /* Read stream until we have a packet queued. */
2640
    while (matroska_deliver_packet(matroska, pkt)) {
2641
2642
        /* Have we already reached the end? */
2643
        if (matroska->done)
2644 6f3e0b21 Panagiotis Issaris
            return AVERROR(EIO);
2645 b061d892 David Conrad
2646 407a3d94 Aurelien Jacobs
        res = 0;
2647 b061d892 David Conrad
        while (res == 0) {
2648
            if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2649 6f3e0b21 Panagiotis Issaris
                return AVERROR(EIO);
2650 b061d892 David Conrad
            } else if (matroska->level_up) {
2651
                matroska->level_up--;
2652
                break;
2653
            }
2654
2655
            switch (id) {
2656
                case MATROSKA_ID_CLUSTER:
2657
                    if ((res = ebml_read_master(matroska, &id)) < 0)
2658
                        break;
2659
                    if ((res = matroska_parse_cluster(matroska)) == 0)
2660
                        res = 1; /* Parsed one cluster, let's get out. */
2661
                    break;
2662
2663
                default:
2664
                case EBML_ID_VOID:
2665
                    res = ebml_read_skip(matroska);
2666
                    break;
2667
            }
2668
2669
            if (matroska->level_up) {
2670
                matroska->level_up--;
2671
                break;
2672
            }
2673
        }
2674
2675
        if (res == -1)
2676
            matroska->done = 1;
2677
    }
2678
2679
    return 0;
2680
}
2681
2682
static int
2683
matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2684
                    int flags)
2685
{
2686
    MatroskaDemuxContext *matroska = s->priv_data;
2687
    AVStream *st = s->streams[stream_index];
2688
    int index;
2689
2690
    /* find index entry */
2691
    index = av_index_search_timestamp(st, timestamp, flags);
2692
    if (index < 0)
2693
        return 0;
2694
2695
    /* do the seek */
2696
    url_fseek(&s->pb, st->index_entries[index].pos, SEEK_SET);
2697
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2698
    matroska->skip_to_stream = st;
2699
    matroska->num_packets = 0;
2700
    matroska->peek_id = 0;
2701
    return 0;
2702
}
2703
2704
static int
2705
matroska_read_close (AVFormatContext *s)
2706
{
2707
    MatroskaDemuxContext *matroska = s->priv_data;
2708
    int n = 0;
2709
2710
    av_free(matroska->writing_app);
2711
    av_free(matroska->muxing_app);
2712
    av_free(matroska->index);
2713
2714
    if (matroska->packets != NULL) {
2715
        for (n = 0; n < matroska->num_packets; n++) {
2716
            av_free_packet(matroska->packets[n]);
2717
            av_free(matroska->packets[n]);
2718
        }
2719
        av_free(matroska->packets);
2720
    }
2721
2722
    for (n = 0; n < matroska->num_tracks; n++) {
2723
        MatroskaTrack *track = matroska->tracks[n];
2724
        av_free(track->codec_id);
2725
        av_free(track->codec_name);
2726
        av_free(track->codec_priv);
2727
        av_free(track->name);
2728
2729 eabb8ba4 Aurelien Jacobs
        if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2730
            MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2731
            av_free(audiotrack->buf);
2732
        }
2733
2734 b061d892 David Conrad
        av_free(track);
2735
    }
2736
2737
    return 0;
2738
}
2739
2740
AVInputFormat matroska_demuxer = {
2741
    "matroska",
2742
    "Matroska file format",
2743
    sizeof(MatroskaDemuxContext),
2744
    matroska_probe,
2745
    matroska_read_header,
2746
    matroska_read_packet,
2747
    matroska_read_close,
2748
    matroska_read_seek,
2749
};