Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ d88d806b

History | View | Annotate | Download (72.3 KB)

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

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

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

    
47
typedef enum {
48
    EBML_NONE,
49
    EBML_UINT,
50
    EBML_FLOAT,
51
    EBML_STR,
52
    EBML_UTF8,
53
    EBML_BIN,
54
    EBML_NEST,
55
    EBML_PASS,
56
    EBML_STOP,
57
} EbmlType;
58

    
59
typedef const struct EbmlSyntax {
60
    uint32_t id;
61
    EbmlType type;
62
    int list_elem_size;
63
    int data_offset;
64
    union {
65
        uint64_t    u;
66
        double      f;
67
        const char *s;
68
        const struct EbmlSyntax *n;
69
    } def;
70
} EbmlSyntax;
71

    
72
typedef struct {
73
    int nb_elem;
74
    void *elem;
75
} EbmlList;
76

    
77
typedef struct {
78
    int      size;
79
    uint8_t *data;
80
    int64_t  pos;
81
} EbmlBin;
82

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

    
91
typedef struct {
92
    uint64_t algo;
93
    EbmlBin  settings;
94
} MatroskaTrackCompression;
95

    
96
typedef struct {
97
    uint64_t scope;
98
    uint64_t type;
99
    MatroskaTrackCompression compression;
100
} MatroskaTrackEncoding;
101

    
102
typedef struct {
103
    double   frame_rate;
104
    uint64_t display_width;
105
    uint64_t display_height;
106
    uint64_t pixel_width;
107
    uint64_t pixel_height;
108
    uint64_t fourcc;
109
} MatroskaTrackVideo;
110

    
111
typedef struct {
112
    double   samplerate;
113
    double   out_samplerate;
114
    uint64_t bitdepth;
115
    uint64_t channels;
116

    
117
    /* real audio header (extracted from extradata) */
118
    int      coded_framesize;
119
    int      sub_packet_h;
120
    int      frame_size;
121
    int      sub_packet_size;
122
    int      sub_packet_cnt;
123
    int      pkt_cnt;
124
    uint8_t *buf;
125
} MatroskaTrackAudio;
126

    
127
typedef struct {
128
    uint64_t num;
129
    uint64_t type;
130
    char    *codec_id;
131
    EbmlBin  codec_priv;
132
    char    *language;
133
    double time_scale;
134
    uint64_t default_duration;
135
    uint64_t flag_default;
136
    MatroskaTrackVideo video;
137
    MatroskaTrackAudio audio;
138
    EbmlList encodings;
139

    
140
    AVStream *stream;
141
} MatroskaTrack;
142

    
143
typedef struct {
144
    char *filename;
145
    char *mime;
146
    EbmlBin bin;
147
} MatroskaAttachement;
148

    
149
typedef struct {
150
    uint64_t start;
151
    uint64_t end;
152
    uint64_t uid;
153
    char    *title;
154
} MatroskaChapter;
155

    
156
typedef struct {
157
    uint64_t track;
158
    uint64_t pos;
159
} MatroskaIndexPos;
160

    
161
typedef struct {
162
    uint64_t time;
163
    EbmlList pos;
164
} MatroskaIndex;
165

    
166
typedef struct {
167
    uint64_t id;
168
    uint64_t pos;
169
} MatroskaSeekhead;
170

    
171
typedef struct MatroskaLevel {
172
    uint64_t start;
173
    uint64_t length;
174
} MatroskaLevel;
175

    
176
typedef struct MatroskaDemuxContext {
177
    AVFormatContext *ctx;
178

    
179
    /* ebml stuff */
180
    int num_levels;
181
    MatroskaLevel levels[EBML_MAX_DEPTH];
182
    int level_up;
183

    
184
    /* timescale in the file */
185
    uint64_t time_scale;
186
    double   duration;
187
    char    *title;
188
    EbmlList tracks;
189
    EbmlList attachments;
190
    EbmlList chapters;
191
    EbmlList index;
192
    EbmlList seekhead;
193

    
194
    /* num_streams is the number of streams that av_new_stream() was called
195
     * for ( = that are available to the calling program). */
196
    int num_streams;
197

    
198
    /* cache for ID peeking */
199
    uint32_t peek_id;
200

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

    
204
    /* The packet queue. */
205
    AVPacket **packets;
206
    int num_packets;
207

    
208
    /* have we already parse metadata/cues/clusters? */
209
    int metadata_parsed;
210
    int index_parsed;
211
    int done;
212

    
213
    /* What to skip before effectively reading a packet. */
214
    int skip_to_keyframe;
215
    AVStream *skip_to_stream;
216
} MatroskaDemuxContext;
217

    
218
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
219

    
220
static EbmlSyntax ebml_header[] = {
221
    { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
222
    { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
223
    { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
224
    { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
225
    { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
226
    { EBML_ID_EBMLVERSION,            EBML_NONE },
227
    { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
228
    { EBML_ID_VOID,                   EBML_NONE },
229
    { 0 }
230
};
231

    
232
static EbmlSyntax ebml_syntax[] = {
233
    { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
234
    { 0 }
235
};
236

    
237
static EbmlSyntax matroska_info[] = {
238
    { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
239
    { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
240
    { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
241
    { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
242
    { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
243
    { MATROSKA_ID_DATEUTC,            EBML_NONE },
244
    { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
245
    { EBML_ID_VOID,                   EBML_NONE },
246
    { 0 }
247
};
248

    
249
static EbmlSyntax matroska_track_video[] = {
250
    { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
251
    { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
252
    { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
253
    { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
254
    { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
255
    { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
256
    { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
257
    { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
258
    { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
259
    { EBML_ID_VOID,                   EBML_NONE },
260
    { 0 }
261
};
262

    
263
static EbmlSyntax matroska_track_audio[] = {
264
    { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
265
    { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
266
    { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
267
    { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
268
    { EBML_ID_VOID,                   EBML_NONE },
269
    { 0 }
270
};
271

    
272
static EbmlSyntax matroska_track_encoding_compression[] = {
273
    { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
274
    { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
275
    { EBML_ID_VOID,                   EBML_NONE },
276
    { 0 }
277
};
278

    
279
static EbmlSyntax matroska_track_encoding[] = {
280
    { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
281
    { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
282
    { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
283
    { EBML_ID_VOID,                   EBML_NONE },
284
    { 0 }
285
};
286

    
287
static EbmlSyntax matroska_track_encodings[] = {
288
    { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
289
    { EBML_ID_VOID,                   EBML_NONE },
290
    { 0 }
291
};
292

    
293
static EbmlSyntax matroska_track[] = {
294
    { MATROSKA_ID_TRACKNUMBER,          EBML_UINT, 0, offsetof(MatroskaTrack,num) },
295
    { MATROSKA_ID_TRACKTYPE,            EBML_UINT, 0, offsetof(MatroskaTrack,type) },
296
    { MATROSKA_ID_CODECID,              EBML_STR,  0, offsetof(MatroskaTrack,codec_id) },
297
    { MATROSKA_ID_CODECPRIVATE,         EBML_BIN,  0, offsetof(MatroskaTrack,codec_priv) },
298
    { MATROSKA_ID_TRACKLANGUAGE,        EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
299
    { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
300
    { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
301
    { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
302
    { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
303
    { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
304
    { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
305
    { MATROSKA_ID_TRACKUID,             EBML_NONE },
306
    { MATROSKA_ID_TRACKNAME,            EBML_NONE },
307
    { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
308
    { MATROSKA_ID_TRACKFLAGFORCED,      EBML_NONE },
309
    { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
310
    { MATROSKA_ID_CODECNAME,            EBML_NONE },
311
    { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
312
    { MATROSKA_ID_CODECINFOURL,         EBML_NONE },
313
    { MATROSKA_ID_CODECDOWNLOADURL,     EBML_NONE },
314
    { MATROSKA_ID_TRACKMINCACHE,        EBML_NONE },
315
    { MATROSKA_ID_TRACKMAXCACHE,        EBML_NONE },
316
    { EBML_ID_VOID,                     EBML_NONE },
317
    { 0 }
318
};
319

    
320
static EbmlSyntax matroska_tracks[] = {
321
    { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
322
    { EBML_ID_VOID,                   EBML_NONE },
323
    { 0 }
324
};
325

    
326
static EbmlSyntax matroska_attachment[] = {
327
    { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
328
    { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
329
    { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
330
    { MATROSKA_ID_FILEUID,            EBML_NONE },
331
    { EBML_ID_VOID,                   EBML_NONE },
332
    { 0 }
333
};
334

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

    
341
static EbmlSyntax matroska_chapter_display[] = {
342
    { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
343
    { EBML_ID_VOID,                   EBML_NONE },
344
    { 0 }
345
};
346

    
347
static EbmlSyntax matroska_chapter_entry[] = {
348
    { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
349
    { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
350
    { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
351
    { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
352
    { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
353
    { EBML_ID_VOID,                   EBML_NONE },
354
    { 0 }
355
};
356

    
357
static EbmlSyntax matroska_chapter[] = {
358
    { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
359
    { MATROSKA_ID_EDITIONUID,         EBML_NONE },
360
    { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
361
    { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
362
    { EBML_ID_VOID,                   EBML_NONE },
363
    { 0 }
364
};
365

    
366
static EbmlSyntax matroska_chapters[] = {
367
    { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
368
    { EBML_ID_VOID,                   EBML_NONE },
369
    { 0 }
370
};
371

    
372
static EbmlSyntax matroska_index_pos[] = {
373
    { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
374
    { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
375
    { EBML_ID_VOID,                   EBML_NONE },
376
    { 0 }
377
};
378

    
379
static EbmlSyntax matroska_index_entry[] = {
380
    { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
381
    { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
382
    { EBML_ID_VOID,                   EBML_NONE },
383
    { 0 }
384
};
385

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

    
392
static EbmlSyntax matroska_tags[] = {
393
    { EBML_ID_VOID,                   EBML_NONE },
394
    { 0 }
395
};
396

    
397
static EbmlSyntax matroska_seekhead_entry[] = {
398
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
399
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
400
    { EBML_ID_VOID,                   EBML_NONE },
401
    { 0 }
402
};
403

    
404
static EbmlSyntax matroska_seekhead[] = {
405
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
406
    { EBML_ID_VOID,                   EBML_NONE },
407
    { 0 }
408
};
409

    
410
/*
411
 * The first few functions handle EBML file parsing. The rest
412
 * is the document interpretation. Matroska really just is a
413
 * EBML file.
414
 */
415

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

    
423
static int
424
ebml_read_element_level_up (MatroskaDemuxContext *matroska)
425
{
426
    ByteIOContext *pb = matroska->ctx->pb;
427
    offset_t pos = url_ftell(pb);
428
    int num = 0;
429

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

    
433
        if (pos >= level->start + level->length) {
434
            matroska->num_levels--;
435
            num++;
436
        } else {
437
            break;
438
        }
439
    }
440

    
441
    return num;
442
}
443

    
444
/*
445
 * Read: an "EBML number", which is defined as a variable-length
446
 * array of bytes. The first byte indicates the length by giving a
447
 * number of 0-bits followed by a one. The position of the first
448
 * "one" bit inside the first byte indicates the length of this
449
 * number.
450
 * Returns: num. of bytes read. < 0 on error.
451
 */
452

    
453
static int
454
ebml_read_num (MatroskaDemuxContext *matroska,
455
               int                   max_size,
456
               uint64_t             *number)
457
{
458
    ByteIOContext *pb = matroska->ctx->pb;
459
    int len_mask = 0x80, read = 1, n = 1;
460
    int64_t total = 0;
461

    
462
    /* the first byte tells us the length in bytes - get_byte() can normally
463
     * return 0, but since that's not a valid first ebmlID byte, we can
464
     * use it safely here to catch EOS. */
465
    if (!(total = get_byte(pb))) {
466
        /* we might encounter EOS here */
467
        if (!url_feof(pb)) {
468
            offset_t pos = url_ftell(pb);
469
            av_log(matroska->ctx, AV_LOG_ERROR,
470
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
471
                   pos, pos);
472
        }
473
        return AVERROR(EIO); /* EOS or actual I/O error */
474
    }
475

    
476
    /* get the length of the EBML number */
477
    while (read <= max_size && !(total & len_mask)) {
478
        read++;
479
        len_mask >>= 1;
480
    }
481
    if (read > max_size) {
482
        offset_t pos = url_ftell(pb) - 1;
483
        av_log(matroska->ctx, AV_LOG_ERROR,
484
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
485
               (uint8_t) total, pos, pos);
486
        return AVERROR_INVALIDDATA;
487
    }
488

    
489
    /* read out length */
490
    total &= ~len_mask;
491
    while (n++ < read)
492
        total = (total << 8) | get_byte(pb);
493

    
494
    *number = total;
495

    
496
    return read;
497
}
498

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

    
504
static int
505
ebml_read_element_id (MatroskaDemuxContext *matroska,
506
                      uint32_t             *id,
507
                      int                  *level_up)
508
{
509
    int read;
510
    uint64_t total;
511

    
512
    /* if we re-call this, use our cached ID */
513
    if (matroska->peek_id != 0) {
514
        if (level_up)
515
            *level_up = 0;
516
        *id = matroska->peek_id;
517
        return 0;
518
    }
519

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

    
525
    /* level tracking */
526
    if (level_up)
527
        *level_up = ebml_read_element_level_up(matroska);
528

    
529
    return read;
530
}
531

    
532
/*
533
 * Read: element content length.
534
 * Return: the number of bytes read or < 0 on error.
535
 */
536

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

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

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

    
554
static uint32_t
555
ebml_peek_id (MatroskaDemuxContext *matroska,
556
              int                  *level_up)
557
{
558
    uint32_t id;
559

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

    
563
    return id;
564
}
565

    
566
/*
567
 * Seek to a given offset.
568
 * 0 is success, -1 is failure.
569
 */
570

    
571
static int
572
ebml_read_seek (MatroskaDemuxContext *matroska,
573
                offset_t              offset)
574
{
575
    ByteIOContext *pb = matroska->ctx->pb;
576

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

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

    
583
/*
584
 * Skip the next element.
585
 * 0 is success, -1 is failure.
586
 */
587

    
588
static int
589
ebml_read_skip (MatroskaDemuxContext *matroska)
590
{
591
    ByteIOContext *pb = matroska->ctx->pb;
592
    uint32_t id;
593
    uint64_t length;
594
    int res;
595

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

    
600
    url_fskip(pb, length);
601

    
602
    return 0;
603
}
604

    
605
/*
606
 * Read the next element as an unsigned int.
607
 * 0 is success, < 0 is failure.
608
 */
609

    
610
static int
611
ebml_read_uint (MatroskaDemuxContext *matroska,
612
                uint32_t             *id,
613
                uint64_t             *num)
614
{
615
    ByteIOContext *pb = matroska->ctx->pb;
616
    int n = 0, size, res;
617
    uint64_t rlength;
618

    
619
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
620
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
621
        return res;
622
    size = rlength;
623
    if (size < 1 || size > 8) {
624
        offset_t pos = url_ftell(pb);
625
        av_log(matroska->ctx, AV_LOG_ERROR,
626
               "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
627
                size, pos, pos);
628
        return AVERROR_INVALIDDATA;
629
    }
630

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

    
636
    return 0;
637
}
638

    
639
/*
640
 * Read the next element as a signed int.
641
 * 0 is success, < 0 is failure.
642
 */
643

    
644
static int
645
ebml_read_sint (MatroskaDemuxContext *matroska,
646
                uint32_t             *id,
647
                int64_t              *num)
648
{
649
    ByteIOContext *pb = matroska->ctx->pb;
650
    int size, n = 1, negative = 0, res;
651
    uint64_t rlength;
652

    
653
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
654
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
655
        return res;
656
    size = rlength;
657
    if (size < 1 || size > 8) {
658
        offset_t pos = url_ftell(pb);
659
        av_log(matroska->ctx, AV_LOG_ERROR,
660
               "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
661
                size, pos, pos);
662
        return AVERROR_INVALIDDATA;
663
    }
664
    if ((*num = get_byte(pb)) & 0x80) {
665
        negative = 1;
666
        *num &= ~0x80;
667
    }
668
    while (n++ < size)
669
        *num = (*num << 8) | get_byte(pb);
670

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

    
675
    return 0;
676
}
677

    
678
/*
679
 * Read the next element as a float.
680
 * 0 is success, < 0 is failure.
681
 */
682

    
683
static int
684
ebml_read_float (MatroskaDemuxContext *matroska,
685
                 uint32_t             *id,
686
                 double               *num)
687
{
688
    ByteIOContext *pb = matroska->ctx->pb;
689
    int size, res;
690
    uint64_t rlength;
691

    
692
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
693
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
694
        return res;
695
    size = rlength;
696

    
697
    if (size == 4) {
698
        *num= av_int2flt(get_be32(pb));
699
    } else if(size==8){
700
        *num= av_int2dbl(get_be64(pb));
701
    } else{
702
        offset_t pos = url_ftell(pb);
703
        av_log(matroska->ctx, AV_LOG_ERROR,
704
               "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
705
               size, pos, pos);
706
        return AVERROR_INVALIDDATA;
707
    }
708

    
709
    return 0;
710
}
711

    
712
/*
713
 * Read the next element as an ASCII string.
714
 * 0 is success, < 0 is failure.
715
 */
716

    
717
static int
718
ebml_read_ascii (MatroskaDemuxContext *matroska,
719
                 uint32_t             *id,
720
                 char                **str)
721
{
722
    ByteIOContext *pb = matroska->ctx->pb;
723
    int size, res;
724
    uint64_t rlength;
725

    
726
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
727
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
728
        return res;
729
    size = rlength;
730

    
731
    /* ebml strings are usually not 0-terminated, so we allocate one
732
     * byte more, read the string and NULL-terminate it ourselves. */
733
    if (size < 0 || !(*str = av_malloc(size + 1))) {
734
        av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
735
        return AVERROR(ENOMEM);
736
    }
737
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
738
        offset_t pos = url_ftell(pb);
739
        av_log(matroska->ctx, AV_LOG_ERROR,
740
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
741
        av_free(*str);
742
        return AVERROR(EIO);
743
    }
744
    (*str)[size] = '\0';
745

    
746
    return 0;
747
}
748

    
749
/*
750
 * Read the next element as a UTF-8 string.
751
 * 0 is success, < 0 is failure.
752
 */
753

    
754
static int
755
ebml_read_utf8 (MatroskaDemuxContext *matroska,
756
                uint32_t             *id,
757
                char                **str)
758
{
759
  return ebml_read_ascii(matroska, id, str);
760
}
761

    
762
/*
763
 * Read the next element, but only the header. The contents
764
 * are supposed to be sub-elements which can be read separately.
765
 * 0 is success, < 0 is failure.
766
 */
767

    
768
static int
769
ebml_read_master (MatroskaDemuxContext *matroska,
770
                  uint32_t             *id)
771
{
772
    ByteIOContext *pb = matroska->ctx->pb;
773
    uint64_t length;
774
    MatroskaLevel *level;
775
    int res;
776

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

    
781
    /* protect... (Heaven forbids that the '>' is true) */
782
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
783
        av_log(matroska->ctx, AV_LOG_ERROR,
784
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
785
        return AVERROR(ENOSYS);
786
    }
787

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

    
793
    return 0;
794
}
795

    
796
/*
797
 * Read the next element as binary data.
798
 * 0 is success, < 0 is failure.
799
 */
800

    
801
static int
802
ebml_read_binary (MatroskaDemuxContext *matroska,
803
                  uint32_t             *id,
804
                  uint8_t             **binary,
805
                  int                  *size)
806
{
807
    ByteIOContext *pb = matroska->ctx->pb;
808
    uint64_t rlength;
809
    int res;
810

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

    
816
    if (!(*binary = av_malloc(*size))) {
817
        av_log(matroska->ctx, AV_LOG_ERROR,
818
               "Memory allocation error\n");
819
        return AVERROR(ENOMEM);
820
    }
821

    
822
    if (get_buffer(pb, *binary, *size) != *size) {
823
        offset_t pos = url_ftell(pb);
824
        av_log(matroska->ctx, AV_LOG_ERROR,
825
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
826
        return AVERROR(EIO);
827
    }
828

    
829
    return 0;
830
}
831

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

    
838
static int
839
matroska_ebmlnum_uint (uint8_t  *data,
840
                       uint32_t  size,
841
                       uint64_t *num)
842
{
843
    int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
844
    uint64_t total;
845

    
846
    if (size <= 0)
847
        return AVERROR_INVALIDDATA;
848

    
849
    total = data[0];
850
    while (read <= 8 && !(total & len_mask)) {
851
        read++;
852
        len_mask >>= 1;
853
    }
854
    if (read > 8)
855
        return AVERROR_INVALIDDATA;
856

    
857
    if ((total &= (len_mask - 1)) == len_mask - 1)
858
        num_ffs++;
859
    if (size < read)
860
        return AVERROR_INVALIDDATA;
861
    while (n < read) {
862
        if (data[n] == 0xff)
863
            num_ffs++;
864
        total = (total << 8) | data[n];
865
        n++;
866
    }
867

    
868
    if (read == num_ffs)
869
        *num = (uint64_t)-1;
870
    else
871
        *num = total;
872

    
873
    return read;
874
}
875

    
876
/*
877
 * Same as above, but signed.
878
 */
879

    
880
static int
881
matroska_ebmlnum_sint (uint8_t  *data,
882
                       uint32_t  size,
883
                       int64_t  *num)
884
{
885
    uint64_t unum;
886
    int res;
887

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

    
892
    /* make signed (weird way) */
893
    if (unum == (uint64_t)-1)
894
        *num = INT64_MAX;
895
    else
896
        *num = unum - ((1LL << ((7 * res) - 1)) - 1);
897

    
898
    return res;
899
}
900

    
901

    
902
static MatroskaTrack *
903
matroska_find_track_by_num (MatroskaDemuxContext *matroska,
904
                            int                   num)
905
{
906
    MatroskaTrack *tracks = matroska->tracks.elem;
907
    int i;
908

    
909
    for (i=0; i < matroska->tracks.nb_elem; i++)
910
        if (tracks[i].num == num)
911
            return &tracks[i];
912

    
913
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
914
    return NULL;
915
}
916

    
917

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

    
923
static int
924
matroska_deliver_packet (MatroskaDemuxContext *matroska,
925
                         AVPacket             *pkt)
926
{
927
    if (matroska->num_packets > 0) {
928
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
929
        av_free(matroska->packets[0]);
930
        if (matroska->num_packets > 1) {
931
            memmove(&matroska->packets[0], &matroska->packets[1],
932
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
933
            matroska->packets =
934
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
935
                           sizeof(AVPacket *));
936
        } else {
937
            av_freep(&matroska->packets);
938
        }
939
        matroska->num_packets--;
940
        return 0;
941
    }
942

    
943
    return -1;
944
}
945

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

    
951
static void
952
matroska_queue_packet (MatroskaDemuxContext *matroska,
953
                       AVPacket             *pkt)
954
{
955
    matroska->packets =
956
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
957
                   sizeof(AVPacket *));
958
    matroska->packets[matroska->num_packets] = pkt;
959
    matroska->num_packets++;
960
}
961

    
962
/*
963
 * Free all packets in our internal queue.
964
 */
965
static void
966
matroska_clear_queue (MatroskaDemuxContext *matroska)
967
{
968
    if (matroska->packets) {
969
        int n;
970
        for (n = 0; n < matroska->num_packets; n++) {
971
            av_free_packet(matroska->packets[n]);
972
            av_free(matroska->packets[n]);
973
        }
974
        av_free(matroska->packets);
975
        matroska->packets = NULL;
976
        matroska->num_packets = 0;
977
    }
978
}
979

    
980

    
981
/*
982
 * Autodetecting...
983
 */
984

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

    
992
    /* ebml header? */
993
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
994
        return 0;
995

    
996
    /* length of header */
997
    total = p->buf[4];
998
    while (size <= 8 && !(total & len_mask)) {
999
        size++;
1000
        len_mask >>= 1;
1001
    }
1002
    if (size > 8)
1003
      return 0;
1004
    total &= (len_mask - 1);
1005
    while (n < size)
1006
        total = (total << 8) | p->buf[4 + n++];
1007

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

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

    
1020
    return 0;
1021
}
1022

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

    
1027
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1028
                      void *data, uint32_t expected_id, int once);
1029

    
1030
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
1031
                           EbmlSyntax *syntax, void *data)
1032
{
1033
    uint32_t id = syntax->id;
1034
    EbmlBin *bin;
1035
    int res;
1036

    
1037
    data = (char *)data + syntax->data_offset;
1038
    if (syntax->list_elem_size) {
1039
        EbmlList *list = data;
1040
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
1041
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
1042
        memset(data, 0, syntax->list_elem_size);
1043
        list->nb_elem++;
1044
    }
1045
    bin = data;
1046

    
1047
    switch (syntax->type) {
1048
    case EBML_UINT:  return ebml_read_uint (matroska, &id, data);
1049
    case EBML_FLOAT: return ebml_read_float(matroska, &id, data);
1050
    case EBML_STR:
1051
    case EBML_UTF8:  av_free(*(char **)data);
1052
                     return ebml_read_ascii(matroska, &id, data);
1053
    case EBML_BIN:   av_free(bin->data);
1054
                     bin->pos = url_ftell(matroska->ctx->pb);
1055
                     return ebml_read_binary(matroska, &id, &bin->data,
1056
                                                            &bin->size);
1057
    case EBML_NEST:  if ((res=ebml_read_master(matroska, &id)) < 0)
1058
                         return res;
1059
                     if (id == MATROSKA_ID_SEGMENT)
1060
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
1061
                     return ebml_parse(matroska, syntax->def.n, data, 0, 0);
1062
    case EBML_PASS:  return ebml_parse(matroska, syntax->def.n, data, 0, 1);
1063
    case EBML_STOP:  *(int *)data = 1;      return 1;
1064
    default:         return ebml_read_skip(matroska);
1065
    }
1066
}
1067

    
1068
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1069
                         uint32_t id, void *data)
1070
{
1071
    int i;
1072
    for (i=0; syntax[i].id; i++)
1073
        if (id == syntax[i].id)
1074
            break;
1075
    if (!syntax[i].id)
1076
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
1077
    return ebml_parse_elem(matroska, &syntax[i], data);
1078
}
1079

    
1080
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1081
                      void *data, uint32_t expected_id, int once)
1082
{
1083
    int i, res = 0;
1084
    uint32_t id = 0;
1085

    
1086
    for (i=0; syntax[i].id; i++)
1087
        switch (syntax[i].type) {
1088
        case EBML_UINT:
1089
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
1090
            break;
1091
        case EBML_FLOAT:
1092
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
1093
            break;
1094
        case EBML_STR:
1095
        case EBML_UTF8:
1096
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
1097
            break;
1098
        }
1099

    
1100
    if (expected_id) {
1101
        res = ebml_read_master(matroska, &id);
1102
        if (id != expected_id)
1103
            return AVERROR_INVALIDDATA;
1104
        if (id == MATROSKA_ID_SEGMENT)
1105
            matroska->segment_start = url_ftell(matroska->ctx->pb);
1106
    }
1107

    
1108
    while (!res) {
1109
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1110
            res = AVERROR(EIO);
1111
            break;
1112
        } else if (matroska->level_up) {
1113
            matroska->level_up--;
1114
            break;
1115
        }
1116

    
1117
        res = ebml_parse_id(matroska, syntax, id, data);
1118
        if (once)
1119
            break;
1120

    
1121

    
1122
        if (matroska->level_up) {
1123
            matroska->level_up--;
1124
            break;
1125
        }
1126
    }
1127

    
1128
    return res;
1129
}
1130

    
1131
static void ebml_free(EbmlSyntax *syntax, void *data)
1132
{
1133
    int i, j;
1134
    for (i=0; syntax[i].id; i++) {
1135
        void *data_off = (char *)data + syntax[i].data_offset;
1136
        switch (syntax[i].type) {
1137
        case EBML_STR:
1138
        case EBML_UTF8:  av_freep(data_off);                      break;
1139
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
1140
        case EBML_NEST:
1141
            if (syntax[i].list_elem_size) {
1142
                EbmlList *list = data_off;
1143
                char *ptr = list->elem;
1144
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1145
                    ebml_free(syntax[i].def.n, ptr);
1146
                av_free(list->elem);
1147
            } else
1148
                ebml_free(syntax[i].def.n, data_off);
1149
        default:  break;
1150
        }
1151
    }
1152
}
1153

    
1154
static int
1155
matroska_parse_info (MatroskaDemuxContext *matroska)
1156
{
1157
    int res = ebml_parse(matroska, matroska_info, matroska, MATROSKA_ID_INFO, 0);
1158

    
1159
    if (matroska->duration)
1160
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1161
                                  * 1000 / AV_TIME_BASE;
1162
    if (matroska->title)
1163
        strncpy(matroska->ctx->title, matroska->title,
1164
                sizeof(matroska->ctx->title)-1);
1165

    
1166
    return res;
1167
}
1168

    
1169
static int
1170
matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
1171
{
1172
    MatroskaTrackEncoding *encodings = track->encodings.elem;
1173
    uint8_t* data = *buf;
1174
    int isize = *buf_size;
1175
    uint8_t* pkt_data = NULL;
1176
    int pkt_size = isize;
1177
    int result = 0;
1178
    int olen;
1179

    
1180
    switch (encodings[0].compression.algo) {
1181
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1182
        return encodings[0].compression.settings.size;
1183
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
1184
        do {
1185
            olen = pkt_size *= 3;
1186
            pkt_data = av_realloc(pkt_data,
1187
                                  pkt_size+LZO_OUTPUT_PADDING);
1188
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
1189
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
1190
        if (result)
1191
            goto failed;
1192
        pkt_size -= olen;
1193
        break;
1194
#ifdef CONFIG_ZLIB
1195
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1196
        z_stream zstream = {0};
1197
        if (inflateInit(&zstream) != Z_OK)
1198
            return -1;
1199
        zstream.next_in = data;
1200
        zstream.avail_in = isize;
1201
        do {
1202
            pkt_size *= 3;
1203
            pkt_data = av_realloc(pkt_data, pkt_size);
1204
            zstream.avail_out = pkt_size - zstream.total_out;
1205
            zstream.next_out = pkt_data + zstream.total_out;
1206
            result = inflate(&zstream, Z_NO_FLUSH);
1207
        } while (result==Z_OK && pkt_size<10000000);
1208
        pkt_size = zstream.total_out;
1209
        inflateEnd(&zstream);
1210
        if (result != Z_STREAM_END)
1211
            goto failed;
1212
        break;
1213
    }
1214
#endif
1215
#ifdef CONFIG_BZLIB
1216
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1217
        bz_stream bzstream = {0};
1218
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1219
            return -1;
1220
        bzstream.next_in = data;
1221
        bzstream.avail_in = isize;
1222
        do {
1223
            pkt_size *= 3;
1224
            pkt_data = av_realloc(pkt_data, pkt_size);
1225
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1226
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1227
            result = BZ2_bzDecompress(&bzstream);
1228
        } while (result==BZ_OK && pkt_size<10000000);
1229
        pkt_size = bzstream.total_out_lo32;
1230
        BZ2_bzDecompressEnd(&bzstream);
1231
        if (result != BZ_STREAM_END)
1232
            goto failed;
1233
        break;
1234
    }
1235
#endif
1236
    }
1237

    
1238
    *buf = pkt_data;
1239
    *buf_size = pkt_size;
1240
    return 0;
1241
 failed:
1242
    av_free(pkt_data);
1243
    return -1;
1244
}
1245

    
1246
static int
1247
matroska_parse_tracks (MatroskaDemuxContext *matroska)
1248
{
1249
    MatroskaTrack *tracks;
1250
    int i, res;
1251

    
1252
    res = ebml_parse(matroska, matroska_tracks, matroska, MATROSKA_ID_TRACKS, 0);
1253

    
1254
    tracks = matroska->tracks.elem;
1255
    for (i=0; i<matroska->tracks.nb_elem; i++) {
1256
        MatroskaTrack *track = &tracks[i];
1257
        EbmlList *encodings_list = &tracks->encodings;
1258
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1259

    
1260
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1261
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1262
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1263
            av_log(matroska->ctx, AV_LOG_INFO,
1264
                   "Unknown or unsupported track type %"PRIu64"\n",
1265
                   track->type);
1266
            continue;
1267
        }
1268

    
1269
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1270
            if (!track->default_duration)
1271
                track->default_duration = 1000000000/track->video.frame_rate;
1272
            if (!track->video.display_width)
1273
                track->video.display_width = track->video.pixel_width;
1274
            if (!track->video.display_height)
1275
                track->video.display_height = track->video.pixel_height;
1276
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1277
            if (!track->audio.out_samplerate)
1278
                track->audio.out_samplerate = track->audio.samplerate;
1279
        }
1280
        if (encodings_list->nb_elem > 1) {
1281
            av_log(matroska->ctx, AV_LOG_ERROR,
1282
                   "Multiple combined encodings no supported");
1283
        } else if (encodings_list->nb_elem == 1) {
1284
            if (encodings[0].type ||
1285
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1286
#ifdef CONFIG_ZLIB
1287
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1288
#endif
1289
#ifdef CONFIG_BZLIB
1290
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1291
#endif
1292
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1293
                encodings[0].scope = 0;
1294
                av_log(matroska->ctx, AV_LOG_ERROR,
1295
                       "Unsupported encoding type");
1296
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1297
                uint8_t *codec_priv = track->codec_priv.data;
1298
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1299
                                                    &track->codec_priv.size,
1300
                                                    track);
1301
                if (offset < 0) {
1302
                    track->codec_priv.data = NULL;
1303
                    track->codec_priv.size = 0;
1304
                    av_log(matroska->ctx, AV_LOG_ERROR,
1305
                           "Failed to decode codec private data\n");
1306
                } else if (offset > 0) {
1307
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1308
                    memcpy(track->codec_priv.data,
1309
                           encodings[0].compression.settings.data, offset);
1310
                    memcpy(track->codec_priv.data+offset, codec_priv,
1311
                           track->codec_priv.size);
1312
                    track->codec_priv.size += offset;
1313
                }
1314
                if (codec_priv != track->codec_priv.data)
1315
                    av_free(codec_priv);
1316
            }
1317
        }
1318
    }
1319

    
1320
    return res;
1321
}
1322

    
1323
static int
1324
matroska_parse_index (MatroskaDemuxContext *matroska)
1325
{
1326
    return ebml_parse(matroska, matroska_index, matroska, MATROSKA_ID_CUES, 0);
1327
}
1328

    
1329
static int
1330
matroska_parse_metadata (MatroskaDemuxContext *matroska)
1331
{
1332
    return ebml_parse(matroska, matroska_tags, matroska, MATROSKA_ID_TAGS, 0);
1333
}
1334

    
1335
static int
1336
matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1337
{
1338
    return ebml_parse(matroska, matroska_seekhead, matroska, MATROSKA_ID_SEEKHEAD, 0);
1339
}
1340

    
1341
static void
1342
matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1343
{
1344
    EbmlList *seekhead_list = &matroska->seekhead;
1345
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1346
    uint32_t peek_id_cache = matroska->peek_id;
1347
    uint32_t level_up = matroska->level_up;
1348
    offset_t before_pos = url_ftell(matroska->ctx->pb);
1349
    MatroskaLevel level;
1350
    uint32_t id;
1351
    int i, res;
1352

    
1353
    for (i=0; i<seekhead_list->nb_elem; i++) {
1354
        if (seekhead[i].pos <= before_pos
1355
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1356
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1357
            continue;
1358

    
1359
        /* seek */
1360
        if (ebml_read_seek(matroska,
1361
                           seekhead[i].pos+matroska->segment_start) < 0)
1362
            continue;
1363

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

    
1373
        level.start = 0;
1374
        level.length = (uint64_t)-1;
1375
        matroska->levels[matroska->num_levels] = level;
1376
        matroska->num_levels++;
1377

    
1378
        /* check ID */
1379
        if (!(id = ebml_peek_id (matroska,
1380
                                 &matroska->level_up)))
1381
            goto finish;
1382
        if (id != seekhead[i].id) {
1383
            av_log(matroska->ctx, AV_LOG_INFO,
1384
                   "We looked for ID=0x%x but got "
1385
                   "ID=0x%x (pos=%"PRIu64")",
1386
                   (int)seekhead[i].id, id, seekhead[i].pos +
1387
                   matroska->segment_start);
1388
            goto finish;
1389
        }
1390

    
1391
        /* read master + parse */
1392
        switch (id) {
1393
        case MATROSKA_ID_CUES:
1394
            if (!(res = matroska_parse_index(matroska)) ||
1395
                url_feof(matroska->ctx->pb)) {
1396
                matroska->index_parsed = 1;
1397
                res = 0;
1398
            }
1399
            break;
1400
        case MATROSKA_ID_TAGS:
1401
            if (!(res = matroska_parse_metadata(matroska)) ||
1402
                url_feof(matroska->ctx->pb)) {
1403
                matroska->metadata_parsed = 1;
1404
                res = 0;
1405
            }
1406
            break;
1407
        }
1408

    
1409
    finish:
1410
        /* remove dummy level */
1411
        while (matroska->num_levels) {
1412
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1413
            if (length == (uint64_t)-1)
1414
                break;
1415
        }
1416
    }
1417

    
1418
    /* seek back */
1419
    ebml_read_seek(matroska, before_pos);
1420
    matroska->peek_id = peek_id_cache;
1421
    matroska->level_up = level_up;
1422
}
1423

    
1424
static int
1425
matroska_parse_attachments(AVFormatContext *s)
1426
{
1427
    MatroskaDemuxContext *matroska = s->priv_data;
1428
    EbmlList *attachements_list = &matroska->attachments;
1429
    MatroskaAttachement *attachements;
1430
    int i, j, res;
1431

    
1432
    res = ebml_parse(matroska, matroska_attachments, matroska, MATROSKA_ID_ATTACHMENTS, 0);
1433

    
1434
    attachements = attachements_list->elem;
1435
    for (j=0; j<attachements_list->nb_elem; j++) {
1436
        if (!(attachements[j].filename && attachements[j].mime &&
1437
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1438
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1439
        } else {
1440
            AVStream *st = av_new_stream(s, matroska->num_streams++);
1441
            if (st == NULL)
1442
                break;
1443
            st->filename          = av_strdup(attachements[j].filename);
1444
            st->codec->codec_id = CODEC_ID_NONE;
1445
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1446
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1447
            if(st->codec->extradata == NULL)
1448
                break;
1449
            st->codec->extradata_size = attachements[j].bin.size;
1450
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1451

    
1452
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1453
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1454
                             strlen(ff_mkv_mime_tags[i].str))) {
1455
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1456
                    break;
1457
                }
1458
            }
1459
        }
1460
    }
1461

    
1462
    return res;
1463
}
1464

    
1465
static int
1466
matroska_parse_chapters(AVFormatContext *s)
1467
{
1468
    MatroskaDemuxContext *matroska = s->priv_data;
1469
    EbmlList *chapters_list = &matroska->chapters;
1470
    MatroskaChapter *chapters;
1471
    int i, res;
1472

    
1473
    res = ebml_parse(matroska, matroska_chapters, matroska, MATROSKA_ID_CHAPTERS, 0);
1474

    
1475
    chapters = chapters_list->elem;
1476
    for (i=0; i<chapters_list->nb_elem; i++)
1477
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1478
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1479
                           chapters[i].start, chapters[i].end,
1480
                           chapters[i].title);
1481

    
1482
    return res;
1483
}
1484

    
1485
static int
1486
matroska_aac_profile (char *codec_id)
1487
{
1488
    static const char *aac_profiles[] = {
1489
        "MAIN", "LC", "SSR"
1490
    };
1491
    int profile;
1492

    
1493
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1494
        if (strstr(codec_id, aac_profiles[profile]))
1495
            break;
1496
    return profile + 1;
1497
}
1498

    
1499
static int
1500
matroska_aac_sri (int samplerate)
1501
{
1502
    int sri;
1503

    
1504
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1505
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1506
            break;
1507
    return sri;
1508
}
1509

    
1510
static int
1511
matroska_read_header (AVFormatContext    *s,
1512
                      AVFormatParameters *ap)
1513
{
1514
    MatroskaDemuxContext *matroska = s->priv_data;
1515
    MatroskaTrack *tracks;
1516
    EbmlList *index_list;
1517
    MatroskaIndex *index;
1518
    int i, j, last_level, res = 0;
1519
    Ebml ebml = { 0 };
1520
    AVStream *st;
1521
    uint32_t id;
1522

    
1523
    matroska->ctx = s;
1524

    
1525
    /* First read the EBML header. */
1526
    if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
1527
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1528
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1529
        || ebml.doctype_version > 2) {
1530
        av_log(matroska->ctx, AV_LOG_ERROR,
1531
               "EBML header using unsupported features\n"
1532
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1533
               ebml.version, ebml.doctype, ebml.doctype_version);
1534
        return AVERROR_NOFMT;
1535
    }
1536
    ebml_free(ebml_syntax, &ebml);
1537

    
1538
    /* The next thing is a segment. */
1539
    while (1) {
1540
        if (!(id = ebml_peek_id(matroska, &last_level)))
1541
            return AVERROR(EIO);
1542
        if (id == MATROSKA_ID_SEGMENT)
1543
            break;
1544

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

    
1553
    /* We now have a Matroska segment.
1554
     * Seeks are from the beginning of the segment,
1555
     * after the segment ID/length. */
1556
    if ((res = ebml_read_master(matroska, &id)) < 0)
1557
        return res;
1558
    matroska->segment_start = url_ftell(s->pb);
1559

    
1560
    matroska->time_scale = 1000000;
1561
    /* we've found our segment, start reading the different contents in here */
1562
    while (res == 0) {
1563
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1564
            res = AVERROR(EIO);
1565
            break;
1566
        } else if (matroska->level_up) {
1567
            matroska->level_up--;
1568
            break;
1569
        }
1570

    
1571
        switch (id) {
1572
            /* stream info */
1573
            case MATROSKA_ID_INFO: {
1574
                res = matroska_parse_info(matroska);
1575
                break;
1576
            }
1577

    
1578
            /* track info headers */
1579
            case MATROSKA_ID_TRACKS: {
1580
                res = matroska_parse_tracks(matroska);
1581
                break;
1582
            }
1583

    
1584
            /* stream index */
1585
            case MATROSKA_ID_CUES: {
1586
                if (!matroska->index_parsed) {
1587
                    res = matroska_parse_index(matroska);
1588
                } else
1589
                    res = ebml_read_skip(matroska);
1590
                break;
1591
            }
1592

    
1593
            /* metadata */
1594
            case MATROSKA_ID_TAGS: {
1595
                if (!matroska->metadata_parsed) {
1596
                    res = matroska_parse_metadata(matroska);
1597
                } else
1598
                    res = ebml_read_skip(matroska);
1599
                break;
1600
            }
1601

    
1602
            /* file index (if seekable, seek to Cues/Tags to parse it) */
1603
            case MATROSKA_ID_SEEKHEAD: {
1604
                res = matroska_parse_seekhead(matroska);
1605
                break;
1606
            }
1607

    
1608
            case MATROSKA_ID_ATTACHMENTS: {
1609
                res = matroska_parse_attachments(s);
1610
                break;
1611
            }
1612

    
1613
            case MATROSKA_ID_CLUSTER: {
1614
                /* Do not read the master - this will be done in the next
1615
                 * call to matroska_read_packet. */
1616
                res = 1;
1617
                break;
1618
            }
1619

    
1620
            case MATROSKA_ID_CHAPTERS: {
1621
                res = matroska_parse_chapters(s);
1622
                break;
1623
            }
1624

    
1625
            default:
1626
                av_log(matroska->ctx, AV_LOG_INFO,
1627
                       "Unknown matroska file header ID 0x%x\n", id);
1628
            /* fall-through */
1629

    
1630
            case EBML_ID_VOID:
1631
                res = ebml_read_skip(matroska);
1632
                break;
1633
        }
1634

    
1635
        if (matroska->level_up) {
1636
            matroska->level_up--;
1637
            break;
1638
        }
1639
    }
1640
    matroska_execute_seekhead(matroska);
1641

    
1642
    /* Have we found a cluster? */
1643
    if (ebml_peek_id(matroska, NULL) != MATROSKA_ID_CLUSTER)
1644
        return -1;
1645

    
1646
    tracks = matroska->tracks.elem;
1647
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1648
        MatroskaTrack *track = &tracks[i];
1649
        enum CodecID codec_id = CODEC_ID_NONE;
1650
        uint8_t *extradata = NULL;
1651
        int extradata_size = 0;
1652
        int extradata_offset = 0;
1653

    
1654
        /* Apply some sanity checks. */
1655
        if (track->codec_id == NULL)
1656
            continue;
1657

    
1658
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1659
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1660
                        strlen(ff_mkv_codec_tags[j].str))){
1661
                codec_id= ff_mkv_codec_tags[j].id;
1662
                break;
1663
            }
1664
        }
1665

    
1666
        st = track->stream = av_new_stream(s, matroska->num_streams++);
1667
        if (st == NULL)
1668
            return AVERROR(ENOMEM);
1669

    
1670
        /* Set the FourCC from the CodecID. */
1671
        /* This is the MS compatibility mode which stores a
1672
         * BITMAPINFOHEADER in the CodecPrivate. */
1673
        if (!strcmp(track->codec_id,
1674
                    MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
1675
            (track->codec_priv.size >= 40) &&
1676
            (track->codec_priv.data != NULL)) {
1677
            /* Offset of biCompression. Stored in LE. */
1678
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1679
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1680

    
1681
        }
1682

    
1683
        /* This is the MS compatibility mode which stores a
1684
         * WAVEFORMATEX in the CodecPrivate. */
1685
        else if (!strcmp(track->codec_id,
1686
                         MATROSKA_CODEC_ID_AUDIO_ACM) &&
1687
                 (track->codec_priv.size >= 18) &&
1688
                 (track->codec_priv.data != NULL)) {
1689
            /* Offset of wFormatTag. Stored in LE. */
1690
            uint16_t tag = AV_RL16(track->codec_priv.data);
1691
            codec_id = codec_get_id(codec_wav_tags, tag);
1692

    
1693
        }
1694

    
1695
        else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
1696
                 (track->codec_priv.size >= 86) &&
1697
                 (track->codec_priv.data != NULL)) {
1698
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1699
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1700
        }
1701

    
1702
        else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1703
            int profile = matroska_aac_profile(track->codec_id);
1704
            int sri = matroska_aac_sri(track->audio.samplerate);
1705
            extradata = av_malloc(5);
1706
            if (extradata == NULL)
1707
                return AVERROR(ENOMEM);
1708
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1709
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1710
            if (strstr(track->codec_id, "SBR")) {
1711
                sri = matroska_aac_sri(track->audio.out_samplerate);
1712
                extradata[2] = 0x56;
1713
                extradata[3] = 0xE5;
1714
                extradata[4] = 0x80 | (sri<<3);
1715
                extradata_size = 5;
1716
            } else {
1717
                extradata_size = 2;
1718
            }
1719
        }
1720

    
1721
        else if (codec_id == CODEC_ID_TTA) {
1722
            ByteIOContext b;
1723
            extradata_size = 30;
1724
            extradata = av_mallocz(extradata_size);
1725
            if (extradata == NULL)
1726
                return AVERROR(ENOMEM);
1727
            init_put_byte(&b, extradata, extradata_size, 1,
1728
                          NULL, NULL, NULL, NULL);
1729
            put_buffer(&b, "TTA1", 4);
1730
            put_le16(&b, 1);
1731
            put_le16(&b, track->audio.channels);
1732
            put_le16(&b, track->audio.bitdepth);
1733
            put_le32(&b, track->audio.out_samplerate);
1734
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1735
        }
1736

    
1737
        else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1738
                 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1739
            extradata_offset = 26;
1740
            track->codec_priv.size -= extradata_offset;
1741
        }
1742

    
1743
        else if (codec_id == CODEC_ID_RA_144) {
1744
            track->audio.out_samplerate = 8000;
1745
            track->audio.channels = 1;
1746
        }
1747

    
1748
        else if (codec_id == CODEC_ID_RA_288 ||
1749
                 codec_id == CODEC_ID_COOK ||
1750
                 codec_id == CODEC_ID_ATRAC3) {
1751
            ByteIOContext b;
1752

    
1753
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1754
                          0, NULL, NULL, NULL, NULL);
1755
            url_fskip(&b, 24);
1756
            track->audio.coded_framesize = get_be32(&b);
1757
            url_fskip(&b, 12);
1758
            track->audio.sub_packet_h    = get_be16(&b);
1759
            track->audio.frame_size      = get_be16(&b);
1760
            track->audio.sub_packet_size = get_be16(&b);
1761
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1762
            if (codec_id == CODEC_ID_RA_288) {
1763
                st->codec->block_align = track->audio.coded_framesize;
1764
                track->codec_priv.size = 0;
1765
            } else {
1766
                st->codec->block_align = track->audio.sub_packet_size;
1767
                extradata_offset = 78;
1768
                track->codec_priv.size -= extradata_offset;
1769
            }
1770
        }
1771

    
1772
        if (codec_id == CODEC_ID_NONE) {
1773
            av_log(matroska->ctx, AV_LOG_INFO,
1774
                   "Unknown/unsupported CodecID %s.\n",
1775
                   track->codec_id);
1776
        }
1777

    
1778
        av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1779

    
1780
        st->codec->codec_id = codec_id;
1781
        st->start_time = 0;
1782
        if (strcmp(track->language, "und"))
1783
            av_strlcpy(st->language, track->language, 4);
1784

    
1785
        if (track->flag_default)
1786
            st->disposition |= AV_DISPOSITION_DEFAULT;
1787

    
1788
        if (track->default_duration)
1789
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1790
                      track->default_duration, 1000000000, 30000);
1791

    
1792
        if(extradata){
1793
            st->codec->extradata = extradata;
1794
            st->codec->extradata_size = extradata_size;
1795
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1796
            st->codec->extradata = av_malloc(track->codec_priv.size);
1797
            if(st->codec->extradata == NULL)
1798
                return AVERROR(ENOMEM);
1799
            st->codec->extradata_size = track->codec_priv.size;
1800
            memcpy(st->codec->extradata,
1801
                   track->codec_priv.data + extradata_offset,
1802
                   track->codec_priv.size);
1803
        }
1804

    
1805
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1806
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1807
            st->codec->codec_tag  = track->video.fourcc;
1808
            st->codec->width  = track->video.pixel_width;
1809
            st->codec->height = track->video.pixel_height;
1810
            av_reduce(&st->codec->sample_aspect_ratio.num,
1811
                      &st->codec->sample_aspect_ratio.den,
1812
                      st->codec->height * track->video.display_width,
1813
                      st->codec-> width * track->video.display_height,
1814
                      255);
1815
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1816
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1817
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1818
            st->codec->sample_rate = track->audio.out_samplerate;
1819
            st->codec->channels = track->audio.channels;
1820
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1821
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1822
        }
1823

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

    
1828
    index_list = &matroska->index;
1829
    index = index_list->elem;
1830
    for (i=0; i<index_list->nb_elem; i++) {
1831
        EbmlList *pos_list = &index[i].pos;
1832
        MatroskaIndexPos *pos = pos_list->elem;
1833
        for (j=0; j<pos_list->nb_elem; j++) {
1834
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1835
                                                              pos[j].track);
1836
            if (track && track->stream)
1837
                av_add_index_entry(track->stream,
1838
                                   pos[j].pos + matroska->segment_start,
1839
                                   index[i].time*matroska->time_scale/AV_TIME_BASE,
1840
                                   0, 0, AVINDEX_KEYFRAME);
1841
        }
1842
    }
1843

    
1844
    return res;
1845
}
1846

    
1847
static int
1848
matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
1849
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
1850
                     int is_keyframe)
1851
{
1852
    MatroskaTrack *track;
1853
    int res = 0;
1854
    AVStream *st;
1855
    AVPacket *pkt;
1856
    uint8_t *origdata = data;
1857
    int16_t block_time;
1858
    uint32_t *lace_size = NULL;
1859
    int n, flags, laces = 0;
1860
    uint64_t num;
1861

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

    
1871
    /* fetch track from num */
1872
    track = matroska_find_track_by_num(matroska, num);
1873
    if (size <= 3 || !track || !track->stream) {
1874
        av_log(matroska->ctx, AV_LOG_INFO,
1875
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1876
        av_free(origdata);
1877
        return res;
1878
    }
1879
    st = track->stream;
1880
    if (st->discard >= AVDISCARD_ALL) {
1881
        av_free(origdata);
1882
        return res;
1883
    }
1884
    if (duration == AV_NOPTS_VALUE)
1885
        duration = track->default_duration / matroska->time_scale;
1886

    
1887
    /* block_time (relative to cluster time) */
1888
    block_time = AV_RB16(data);
1889
    data += 2;
1890
    flags = *data++;
1891
    size -= 3;
1892
    if (is_keyframe == -1)
1893
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1894

    
1895
    if (matroska->skip_to_keyframe) {
1896
        if (!is_keyframe || st != matroska->skip_to_stream) {
1897
            av_free(origdata);
1898
            return res;
1899
        }
1900
        matroska->skip_to_keyframe = 0;
1901
    }
1902

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

    
1910
        case 0x1: /* xiph lacing */
1911
        case 0x2: /* fixed-size lacing */
1912
        case 0x3: /* EBML lacing */
1913
            assert(size>0); // size <=3 is checked before size-=3 above
1914
            laces = (*data) + 1;
1915
            data += 1;
1916
            size -= 1;
1917
            lace_size = av_mallocz(laces * sizeof(int));
1918

    
1919
            switch ((flags & 0x06) >> 1) {
1920
                case 0x1: /* xiph lacing */ {
1921
                    uint8_t temp;
1922
                    uint32_t total = 0;
1923
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1924
                        while (1) {
1925
                            if (size == 0) {
1926
                                res = -1;
1927
                                break;
1928
                            }
1929
                            temp = *data;
1930
                            lace_size[n] += temp;
1931
                            data += 1;
1932
                            size -= 1;
1933
                            if (temp != 0xff)
1934
                                break;
1935
                        }
1936
                        total += lace_size[n];
1937
                    }
1938
                    lace_size[n] = size - total;
1939
                    break;
1940
                }
1941

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

    
1947
                case 0x3: /* EBML lacing */ {
1948
                    uint32_t total;
1949
                    n = matroska_ebmlnum_uint(data, size, &num);
1950
                    if (n < 0) {
1951
                        av_log(matroska->ctx, AV_LOG_INFO,
1952
                               "EBML block data error\n");
1953
                        break;
1954
                    }
1955
                    data += n;
1956
                    size -= n;
1957
                    total = lace_size[0] = num;
1958
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1959
                        int64_t snum;
1960
                        int r;
1961
                        r = matroska_ebmlnum_sint (data, size, &snum);
1962
                        if (r < 0) {
1963
                            av_log(matroska->ctx, AV_LOG_INFO,
1964
                                   "EBML block data error\n");
1965
                            break;
1966
                        }
1967
                        data += r;
1968
                        size -= r;
1969
                        lace_size[n] = lace_size[n - 1] + snum;
1970
                        total += lace_size[n];
1971
                    }
1972
                    lace_size[n] = size - total;
1973
                    break;
1974
                }
1975
            }
1976
            break;
1977
    }
1978

    
1979
    if (res == 0) {
1980
        uint64_t timecode = AV_NOPTS_VALUE;
1981

    
1982
        if (cluster_time != (uint64_t)-1
1983
            && (block_time >= 0 || cluster_time >= -block_time))
1984
            timecode = cluster_time + block_time;
1985

    
1986
        for (n = 0; n < laces; n++) {
1987
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1988
                st->codec->codec_id == CODEC_ID_COOK ||
1989
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1990
                int a = st->codec->block_align;
1991
                int sps = track->audio.sub_packet_size;
1992
                int cfs = track->audio.coded_framesize;
1993
                int h = track->audio.sub_packet_h;
1994
                int y = track->audio.sub_packet_cnt;
1995
                int w = track->audio.frame_size;
1996
                int x;
1997

    
1998
                if (!track->audio.pkt_cnt) {
1999
                    if (st->codec->codec_id == CODEC_ID_RA_288)
2000
                        for (x=0; x<h/2; x++)
2001
                            memcpy(track->audio.buf+x*2*w+y*cfs,
2002
                                   data+x*cfs, cfs);
2003
                    else
2004
                        for (x=0; x<w/sps; x++)
2005
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2006

    
2007
                    if (++track->audio.sub_packet_cnt >= h) {
2008
                        track->audio.sub_packet_cnt = 0;
2009
                        track->audio.pkt_cnt = h*w / a;
2010
                    }
2011
                }
2012
                while (track->audio.pkt_cnt) {
2013
                    pkt = av_mallocz(sizeof(AVPacket));
2014
                    av_new_packet(pkt, a);
2015
                    memcpy(pkt->data, track->audio.buf
2016
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
2017
                    pkt->pos = pos;
2018
                    pkt->stream_index = st->index;
2019
                    matroska_queue_packet(matroska, pkt);
2020
                }
2021
            } else {
2022
                MatroskaTrackEncoding *encodings = track->encodings.elem;
2023
                int offset = 0, pkt_size = lace_size[n];
2024
                uint8_t *pkt_data = data;
2025

    
2026
                if (encodings && encodings->scope & 1) {
2027
                    offset = matroska_decode_buffer(&pkt_data, &pkt_size,
2028
                                                    track);
2029
                    if (offset < 0)
2030
                        continue;
2031
                }
2032

    
2033
                pkt = av_mallocz(sizeof(AVPacket));
2034
                /* XXX: prevent data copy... */
2035
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
2036
                    av_free(pkt);
2037
                    res = AVERROR(ENOMEM);
2038
                    n = laces-1;
2039
                    break;
2040
                }
2041
                if (offset)
2042
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
2043
                memcpy (pkt->data+offset, pkt_data, pkt_size);
2044

    
2045
                if (pkt_data != data)
2046
                    av_free(pkt_data);
2047

    
2048
                if (n == 0)
2049
                    pkt->flags = is_keyframe;
2050
                pkt->stream_index = st->index;
2051

    
2052
                pkt->pts = timecode;
2053
                pkt->pos = pos;
2054
                pkt->duration = duration;
2055

    
2056
                matroska_queue_packet(matroska, pkt);
2057
            }
2058

    
2059
            if (timecode != AV_NOPTS_VALUE)
2060
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2061
            data += lace_size[n];
2062
        }
2063
    }
2064

    
2065
    av_free(lace_size);
2066
    av_free(origdata);
2067
    return res;
2068
}
2069

    
2070
static int
2071
matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2072
                           uint64_t              cluster_time)
2073
{
2074
    int res = 0;
2075
    uint32_t id;
2076
    int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2077
    uint64_t duration = AV_NOPTS_VALUE;
2078
    uint8_t *data;
2079
    int size = 0;
2080
    int64_t pos = 0;
2081

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

    
2084
    while (res == 0) {
2085
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2086
            res = AVERROR(EIO);
2087
            break;
2088
        } else if (matroska->level_up) {
2089
            matroska->level_up--;
2090
            break;
2091
        }
2092

    
2093
        switch (id) {
2094
            /* one block inside the group. Note, block parsing is one
2095
             * of the harder things, so this code is a bit complicated.
2096
             * See http://www.matroska.org/ for documentation. */
2097
            case MATROSKA_ID_BLOCK: {
2098
                pos = url_ftell(matroska->ctx->pb);
2099
                res = ebml_read_binary(matroska, &id, &data, &size);
2100
                break;
2101
            }
2102

    
2103
            case MATROSKA_ID_BLOCKDURATION: {
2104
                if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2105
                    break;
2106
                break;
2107
            }
2108

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

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

    
2126
            case EBML_ID_VOID:
2127
                res = ebml_read_skip(matroska);
2128
                break;
2129
        }
2130

    
2131
        if (matroska->level_up) {
2132
            matroska->level_up--;
2133
            break;
2134
        }
2135
    }
2136

    
2137
    if (res)
2138
        return res;
2139

    
2140
    if (size > 0)
2141
        res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2142
                                   duration, is_keyframe);
2143

    
2144
    return res;
2145
}
2146

    
2147
static int
2148
matroska_parse_cluster (MatroskaDemuxContext *matroska)
2149
{
2150
    int res = 0;
2151
    uint32_t id;
2152
    uint64_t cluster_time = 0;
2153
    uint8_t *data;
2154
    int64_t pos;
2155
    int size;
2156

    
2157
    av_log(matroska->ctx, AV_LOG_DEBUG,
2158
           "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
2159

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

    
2169
        switch (id) {
2170
            /* cluster timecode */
2171
            case MATROSKA_ID_CLUSTERTIMECODE: {
2172
                uint64_t num;
2173
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2174
                    break;
2175
                cluster_time = num;
2176
                break;
2177
            }
2178

    
2179
                /* a group of blocks inside a cluster */
2180
            case MATROSKA_ID_BLOCKGROUP:
2181
                if ((res = ebml_read_master(matroska, &id)) < 0)
2182
                    break;
2183
                res = matroska_parse_blockgroup(matroska, cluster_time);
2184
                break;
2185

    
2186
            case MATROSKA_ID_SIMPLEBLOCK:
2187
                pos = url_ftell(matroska->ctx->pb);
2188
                res = ebml_read_binary(matroska, &id, &data, &size);
2189
                if (res == 0)
2190
                    res = matroska_parse_block(matroska, data, size, pos,
2191
                                               cluster_time, AV_NOPTS_VALUE,
2192
                                               -1);
2193
                break;
2194

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

    
2200
            case EBML_ID_VOID:
2201
                res = ebml_read_skip(matroska);
2202
                break;
2203
        }
2204

    
2205
        if (matroska->level_up) {
2206
            matroska->level_up--;
2207
            break;
2208
        }
2209
    }
2210

    
2211
    return res;
2212
}
2213

    
2214
static int
2215
matroska_read_packet (AVFormatContext *s,
2216
                      AVPacket        *pkt)
2217
{
2218
    MatroskaDemuxContext *matroska = s->priv_data;
2219
    int res;
2220
    uint32_t id;
2221

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

    
2225
        /* Have we already reached the end? */
2226
        if (matroska->done)
2227
            return AVERROR(EIO);
2228

    
2229
        res = 0;
2230
        while (res == 0) {
2231
            if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2232
                return AVERROR(EIO);
2233
            } else if (matroska->level_up) {
2234
                matroska->level_up--;
2235
                break;
2236
            }
2237

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

    
2246
                default:
2247
                case EBML_ID_VOID:
2248
                    res = ebml_read_skip(matroska);
2249
                    break;
2250
            }
2251

    
2252
            if (matroska->level_up) {
2253
                matroska->level_up--;
2254
                break;
2255
            }
2256
        }
2257

    
2258
        if (res == -1)
2259
            matroska->done = 1;
2260
    }
2261

    
2262
    return 0;
2263
}
2264

    
2265
static int
2266
matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2267
                    int flags)
2268
{
2269
    MatroskaDemuxContext *matroska = s->priv_data;
2270
    AVStream *st = s->streams[stream_index];
2271
    int index;
2272

    
2273
    /* find index entry */
2274
    index = av_index_search_timestamp(st, timestamp, flags);
2275
    if (index < 0)
2276
        return 0;
2277

    
2278
    matroska_clear_queue(matroska);
2279

    
2280
    /* do the seek */
2281
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
2282
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2283
    matroska->skip_to_stream = st;
2284
    matroska->peek_id = 0;
2285
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
2286
    return 0;
2287
}
2288

    
2289
static int
2290
matroska_read_close (AVFormatContext *s)
2291
{
2292
    MatroskaDemuxContext *matroska = s->priv_data;
2293
    MatroskaTrack *tracks = matroska->tracks.elem;
2294
    int n = 0;
2295

    
2296
    matroska_clear_queue(matroska);
2297

    
2298
    for (n=0; n < matroska->tracks.nb_elem; n++)
2299
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2300
            av_free(tracks[n].audio.buf);
2301
    ebml_free(matroska_tracks, matroska);
2302
    ebml_free(matroska_index, matroska);
2303

    
2304
    return 0;
2305
}
2306

    
2307
AVInputFormat matroska_demuxer = {
2308
    "matroska",
2309
    NULL_IF_CONFIG_SMALL("Matroska file format"),
2310
    sizeof(MatroskaDemuxContext),
2311
    matroska_probe,
2312
    matroska_read_header,
2313
    matroska_read_packet,
2314
    matroska_read_close,
2315
    matroska_read_seek,
2316
};