Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ f06a4886

History | View | Annotate | Download (67.9 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
    int has_cluster_id;
213

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
411
static EbmlSyntax matroska_segment[] = {
412
    { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
413
    { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
414
    { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
415
    { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
416
    { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
417
    { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
418
    { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
419
    { MATROSKA_ID_CLUSTER,        EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
420
    { EBML_ID_VOID,               EBML_NONE },
421
    { 0 }
422
};
423

    
424
static EbmlSyntax matroska_segments[] = {
425
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
426
    { 0 }
427
};
428

    
429
/*
430
 * The first few functions handle EBML file parsing. The rest
431
 * is the document interpretation. Matroska really just is a
432
 * EBML file.
433
 */
434

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

    
442
static int
443
ebml_read_element_level_up (MatroskaDemuxContext *matroska)
444
{
445
    ByteIOContext *pb = matroska->ctx->pb;
446
    offset_t pos = url_ftell(pb);
447
    int num = 0;
448

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

    
452
        if (pos >= level->start + level->length) {
453
            matroska->num_levels--;
454
            num++;
455
        } else {
456
            break;
457
        }
458
    }
459

    
460
    return num;
461
}
462

    
463
/*
464
 * Read: an "EBML number", which is defined as a variable-length
465
 * array of bytes. The first byte indicates the length by giving a
466
 * number of 0-bits followed by a one. The position of the first
467
 * "one" bit inside the first byte indicates the length of this
468
 * number.
469
 * Returns: num. of bytes read. < 0 on error.
470
 */
471

    
472
static int
473
ebml_read_num (MatroskaDemuxContext *matroska,
474
               int                   max_size,
475
               uint64_t             *number)
476
{
477
    ByteIOContext *pb = matroska->ctx->pb;
478
    int len_mask = 0x80, read = 1, n = 1;
479
    int64_t total = 0;
480

    
481
    /* the first byte tells us the length in bytes - get_byte() can normally
482
     * return 0, but since that's not a valid first ebmlID byte, we can
483
     * use it safely here to catch EOS. */
484
    if (!(total = get_byte(pb))) {
485
        /* we might encounter EOS here */
486
        if (!url_feof(pb)) {
487
            offset_t pos = url_ftell(pb);
488
            av_log(matroska->ctx, AV_LOG_ERROR,
489
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
490
                   pos, pos);
491
        }
492
        return AVERROR(EIO); /* EOS or actual I/O error */
493
    }
494

    
495
    /* get the length of the EBML number */
496
    while (read <= max_size && !(total & len_mask)) {
497
        read++;
498
        len_mask >>= 1;
499
    }
500
    if (read > max_size) {
501
        offset_t pos = url_ftell(pb) - 1;
502
        av_log(matroska->ctx, AV_LOG_ERROR,
503
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
504
               (uint8_t) total, pos, pos);
505
        return AVERROR_INVALIDDATA;
506
    }
507

    
508
    /* read out length */
509
    total &= ~len_mask;
510
    while (n++ < read)
511
        total = (total << 8) | get_byte(pb);
512

    
513
    *number = total;
514

    
515
    return read;
516
}
517

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

    
523
static int
524
ebml_read_element_id (MatroskaDemuxContext *matroska,
525
                      uint32_t             *id,
526
                      int                  *level_up)
527
{
528
    int read;
529
    uint64_t total;
530

    
531
    /* if we re-call this, use our cached ID */
532
    if (matroska->peek_id != 0) {
533
        if (level_up)
534
            *level_up = 0;
535
        *id = matroska->peek_id;
536
        return 0;
537
    }
538

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

    
544
    /* level tracking */
545
    if (level_up)
546
        *level_up = ebml_read_element_level_up(matroska);
547

    
548
    return read;
549
}
550

    
551
/*
552
 * Read: element content length.
553
 * Return: the number of bytes read or < 0 on error.
554
 */
555

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

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

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

    
573
static uint32_t
574
ebml_peek_id (MatroskaDemuxContext *matroska,
575
              int                  *level_up)
576
{
577
    uint32_t id;
578

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

    
582
    return id;
583
}
584

    
585
/*
586
 * Seek to a given offset.
587
 * 0 is success, -1 is failure.
588
 */
589

    
590
static int
591
ebml_read_seek (MatroskaDemuxContext *matroska,
592
                offset_t              offset)
593
{
594
    ByteIOContext *pb = matroska->ctx->pb;
595

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

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

    
602
/*
603
 * Skip the next element.
604
 * 0 is success, -1 is failure.
605
 */
606

    
607
static int
608
ebml_read_skip (MatroskaDemuxContext *matroska)
609
{
610
    ByteIOContext *pb = matroska->ctx->pb;
611
    uint32_t id;
612
    uint64_t length;
613
    int res;
614

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

    
619
    url_fskip(pb, length);
620

    
621
    return 0;
622
}
623

    
624
/*
625
 * Read the next element as an unsigned int.
626
 * 0 is success, < 0 is failure.
627
 */
628

    
629
static int
630
ebml_read_uint (MatroskaDemuxContext *matroska,
631
                uint32_t             *id,
632
                uint64_t             *num)
633
{
634
    ByteIOContext *pb = matroska->ctx->pb;
635
    int n = 0, size, res;
636
    uint64_t rlength;
637

    
638
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
639
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
640
        return res;
641
    size = rlength;
642
    if (size < 1 || size > 8) {
643
        offset_t pos = url_ftell(pb);
644
        av_log(matroska->ctx, AV_LOG_ERROR,
645
               "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
646
                size, pos, pos);
647
        return AVERROR_INVALIDDATA;
648
    }
649

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

    
655
    return 0;
656
}
657

    
658
/*
659
 * Read the next element as a signed int.
660
 * 0 is success, < 0 is failure.
661
 */
662

    
663
static int
664
ebml_read_sint (MatroskaDemuxContext *matroska,
665
                uint32_t             *id,
666
                int64_t              *num)
667
{
668
    ByteIOContext *pb = matroska->ctx->pb;
669
    int size, n = 1, negative = 0, res;
670
    uint64_t rlength;
671

    
672
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
673
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
674
        return res;
675
    size = rlength;
676
    if (size < 1 || size > 8) {
677
        offset_t pos = url_ftell(pb);
678
        av_log(matroska->ctx, AV_LOG_ERROR,
679
               "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
680
                size, pos, pos);
681
        return AVERROR_INVALIDDATA;
682
    }
683
    if ((*num = get_byte(pb)) & 0x80) {
684
        negative = 1;
685
        *num &= ~0x80;
686
    }
687
    while (n++ < size)
688
        *num = (*num << 8) | get_byte(pb);
689

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

    
694
    return 0;
695
}
696

    
697
/*
698
 * Read the next element as a float.
699
 * 0 is success, < 0 is failure.
700
 */
701

    
702
static int
703
ebml_read_float (MatroskaDemuxContext *matroska,
704
                 uint32_t             *id,
705
                 double               *num)
706
{
707
    ByteIOContext *pb = matroska->ctx->pb;
708
    int size, res;
709
    uint64_t rlength;
710

    
711
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
712
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
713
        return res;
714
    size = rlength;
715

    
716
    if (size == 4) {
717
        *num= av_int2flt(get_be32(pb));
718
    } else if(size==8){
719
        *num= av_int2dbl(get_be64(pb));
720
    } else{
721
        offset_t pos = url_ftell(pb);
722
        av_log(matroska->ctx, AV_LOG_ERROR,
723
               "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
724
               size, pos, pos);
725
        return AVERROR_INVALIDDATA;
726
    }
727

    
728
    return 0;
729
}
730

    
731
/*
732
 * Read the next element as an ASCII string.
733
 * 0 is success, < 0 is failure.
734
 */
735

    
736
static int
737
ebml_read_ascii (MatroskaDemuxContext *matroska,
738
                 uint32_t             *id,
739
                 char                **str)
740
{
741
    ByteIOContext *pb = matroska->ctx->pb;
742
    int size, res;
743
    uint64_t rlength;
744

    
745
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
746
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
747
        return res;
748
    size = rlength;
749

    
750
    /* ebml strings are usually not 0-terminated, so we allocate one
751
     * byte more, read the string and NULL-terminate it ourselves. */
752
    if (size < 0 || !(*str = av_malloc(size + 1))) {
753
        av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
754
        return AVERROR(ENOMEM);
755
    }
756
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
757
        offset_t pos = url_ftell(pb);
758
        av_log(matroska->ctx, AV_LOG_ERROR,
759
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
760
        av_free(*str);
761
        return AVERROR(EIO);
762
    }
763
    (*str)[size] = '\0';
764

    
765
    return 0;
766
}
767

    
768
/*
769
 * Read the next element as a UTF-8 string.
770
 * 0 is success, < 0 is failure.
771
 */
772

    
773
static int
774
ebml_read_utf8 (MatroskaDemuxContext *matroska,
775
                uint32_t             *id,
776
                char                **str)
777
{
778
  return ebml_read_ascii(matroska, id, str);
779
}
780

    
781
/*
782
 * Read the next element, but only the header. The contents
783
 * are supposed to be sub-elements which can be read separately.
784
 * 0 is success, < 0 is failure.
785
 */
786

    
787
static int
788
ebml_read_master (MatroskaDemuxContext *matroska,
789
                  uint32_t             *id)
790
{
791
    ByteIOContext *pb = matroska->ctx->pb;
792
    uint64_t length;
793
    MatroskaLevel *level;
794
    int res;
795

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

    
800
    /* protect... (Heaven forbids that the '>' is true) */
801
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
802
        av_log(matroska->ctx, AV_LOG_ERROR,
803
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
804
        return AVERROR(ENOSYS);
805
    }
806

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

    
812
    return 0;
813
}
814

    
815
/*
816
 * Read the next element as binary data.
817
 * 0 is success, < 0 is failure.
818
 */
819

    
820
static int
821
ebml_read_binary (MatroskaDemuxContext *matroska,
822
                  uint32_t             *id,
823
                  uint8_t             **binary,
824
                  int                  *size)
825
{
826
    ByteIOContext *pb = matroska->ctx->pb;
827
    uint64_t rlength;
828
    int res;
829

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

    
835
    if (!(*binary = av_malloc(*size))) {
836
        av_log(matroska->ctx, AV_LOG_ERROR,
837
               "Memory allocation error\n");
838
        return AVERROR(ENOMEM);
839
    }
840

    
841
    if (get_buffer(pb, *binary, *size) != *size) {
842
        offset_t pos = url_ftell(pb);
843
        av_log(matroska->ctx, AV_LOG_ERROR,
844
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
845
        return AVERROR(EIO);
846
    }
847

    
848
    return 0;
849
}
850

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

    
857
static int
858
matroska_ebmlnum_uint (uint8_t  *data,
859
                       uint32_t  size,
860
                       uint64_t *num)
861
{
862
    int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
863
    uint64_t total;
864

    
865
    if (size <= 0)
866
        return AVERROR_INVALIDDATA;
867

    
868
    total = data[0];
869
    while (read <= 8 && !(total & len_mask)) {
870
        read++;
871
        len_mask >>= 1;
872
    }
873
    if (read > 8)
874
        return AVERROR_INVALIDDATA;
875

    
876
    if ((total &= (len_mask - 1)) == len_mask - 1)
877
        num_ffs++;
878
    if (size < read)
879
        return AVERROR_INVALIDDATA;
880
    while (n < read) {
881
        if (data[n] == 0xff)
882
            num_ffs++;
883
        total = (total << 8) | data[n];
884
        n++;
885
    }
886

    
887
    if (read == num_ffs)
888
        *num = (uint64_t)-1;
889
    else
890
        *num = total;
891

    
892
    return read;
893
}
894

    
895
/*
896
 * Same as above, but signed.
897
 */
898

    
899
static int
900
matroska_ebmlnum_sint (uint8_t  *data,
901
                       uint32_t  size,
902
                       int64_t  *num)
903
{
904
    uint64_t unum;
905
    int res;
906

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

    
911
    /* make signed (weird way) */
912
    if (unum == (uint64_t)-1)
913
        *num = INT64_MAX;
914
    else
915
        *num = unum - ((1LL << ((7 * res) - 1)) - 1);
916

    
917
    return res;
918
}
919

    
920

    
921
static MatroskaTrack *
922
matroska_find_track_by_num (MatroskaDemuxContext *matroska,
923
                            int                   num)
924
{
925
    MatroskaTrack *tracks = matroska->tracks.elem;
926
    int i;
927

    
928
    for (i=0; i < matroska->tracks.nb_elem; i++)
929
        if (tracks[i].num == num)
930
            return &tracks[i];
931

    
932
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
933
    return NULL;
934
}
935

    
936

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

    
942
static int
943
matroska_deliver_packet (MatroskaDemuxContext *matroska,
944
                         AVPacket             *pkt)
945
{
946
    if (matroska->num_packets > 0) {
947
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
948
        av_free(matroska->packets[0]);
949
        if (matroska->num_packets > 1) {
950
            memmove(&matroska->packets[0], &matroska->packets[1],
951
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
952
            matroska->packets =
953
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
954
                           sizeof(AVPacket *));
955
        } else {
956
            av_freep(&matroska->packets);
957
        }
958
        matroska->num_packets--;
959
        return 0;
960
    }
961

    
962
    return -1;
963
}
964

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

    
970
static void
971
matroska_queue_packet (MatroskaDemuxContext *matroska,
972
                       AVPacket             *pkt)
973
{
974
    matroska->packets =
975
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
976
                   sizeof(AVPacket *));
977
    matroska->packets[matroska->num_packets] = pkt;
978
    matroska->num_packets++;
979
}
980

    
981
/*
982
 * Free all packets in our internal queue.
983
 */
984
static void
985
matroska_clear_queue (MatroskaDemuxContext *matroska)
986
{
987
    if (matroska->packets) {
988
        int n;
989
        for (n = 0; n < matroska->num_packets; n++) {
990
            av_free_packet(matroska->packets[n]);
991
            av_free(matroska->packets[n]);
992
        }
993
        av_free(matroska->packets);
994
        matroska->packets = NULL;
995
        matroska->num_packets = 0;
996
    }
997
}
998

    
999

    
1000
/*
1001
 * Autodetecting...
1002
 */
1003

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

    
1011
    /* ebml header? */
1012
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
1013
        return 0;
1014

    
1015
    /* length of header */
1016
    total = p->buf[4];
1017
    while (size <= 8 && !(total & len_mask)) {
1018
        size++;
1019
        len_mask >>= 1;
1020
    }
1021
    if (size > 8)
1022
      return 0;
1023
    total &= (len_mask - 1);
1024
    while (n < size)
1025
        total = (total << 8) | p->buf[4 + n++];
1026

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

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

    
1039
    return 0;
1040
}
1041

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

    
1046
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1047
                      void *data, uint32_t expected_id, int once);
1048

    
1049
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
1050
                           EbmlSyntax *syntax, void *data)
1051
{
1052
    uint32_t id = syntax->id;
1053
    EbmlBin *bin;
1054
    int res;
1055

    
1056
    data = (char *)data + syntax->data_offset;
1057
    if (syntax->list_elem_size) {
1058
        EbmlList *list = data;
1059
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
1060
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
1061
        memset(data, 0, syntax->list_elem_size);
1062
        list->nb_elem++;
1063
    }
1064
    bin = data;
1065

    
1066
    switch (syntax->type) {
1067
    case EBML_UINT:  return ebml_read_uint (matroska, &id, data);
1068
    case EBML_FLOAT: return ebml_read_float(matroska, &id, data);
1069
    case EBML_STR:
1070
    case EBML_UTF8:  av_free(*(char **)data);
1071
                     return ebml_read_ascii(matroska, &id, data);
1072
    case EBML_BIN:   av_free(bin->data);
1073
                     bin->pos = url_ftell(matroska->ctx->pb);
1074
                     return ebml_read_binary(matroska, &id, &bin->data,
1075
                                                            &bin->size);
1076
    case EBML_NEST:  if ((res=ebml_read_master(matroska, &id)) < 0)
1077
                         return res;
1078
                     if (id == MATROSKA_ID_SEGMENT)
1079
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
1080
                     return ebml_parse(matroska, syntax->def.n, data, 0, 0);
1081
    case EBML_PASS:  return ebml_parse(matroska, syntax->def.n, data, 0, 1);
1082
    case EBML_STOP:  *(int *)data = 1;      return 1;
1083
    default:         return ebml_read_skip(matroska);
1084
    }
1085
}
1086

    
1087
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1088
                         uint32_t id, void *data)
1089
{
1090
    int i;
1091
    for (i=0; syntax[i].id; i++)
1092
        if (id == syntax[i].id)
1093
            break;
1094
    if (!syntax[i].id)
1095
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
1096
    return ebml_parse_elem(matroska, &syntax[i], data);
1097
}
1098

    
1099
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1100
                      void *data, uint32_t expected_id, int once)
1101
{
1102
    int i, res = 0;
1103
    uint32_t id = 0;
1104

    
1105
    for (i=0; syntax[i].id; i++)
1106
        switch (syntax[i].type) {
1107
        case EBML_UINT:
1108
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
1109
            break;
1110
        case EBML_FLOAT:
1111
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
1112
            break;
1113
        case EBML_STR:
1114
        case EBML_UTF8:
1115
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
1116
            break;
1117
        }
1118

    
1119
    if (expected_id) {
1120
        res = ebml_read_master(matroska, &id);
1121
        if (id != expected_id)
1122
            return AVERROR_INVALIDDATA;
1123
        if (id == MATROSKA_ID_SEGMENT)
1124
            matroska->segment_start = url_ftell(matroska->ctx->pb);
1125
    }
1126

    
1127
    while (!res) {
1128
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1129
            res = AVERROR(EIO);
1130
            break;
1131
        } else if (matroska->level_up) {
1132
            matroska->level_up--;
1133
            break;
1134
        }
1135

    
1136
        res = ebml_parse_id(matroska, syntax, id, data);
1137
        if (once)
1138
            break;
1139

    
1140

    
1141
        if (matroska->level_up) {
1142
            matroska->level_up--;
1143
            break;
1144
        }
1145
    }
1146

    
1147
    return res;
1148
}
1149

    
1150
static void ebml_free(EbmlSyntax *syntax, void *data)
1151
{
1152
    int i, j;
1153
    for (i=0; syntax[i].id; i++) {
1154
        void *data_off = (char *)data + syntax[i].data_offset;
1155
        switch (syntax[i].type) {
1156
        case EBML_STR:
1157
        case EBML_UTF8:  av_freep(data_off);                      break;
1158
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
1159
        case EBML_NEST:
1160
            if (syntax[i].list_elem_size) {
1161
                EbmlList *list = data_off;
1162
                char *ptr = list->elem;
1163
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1164
                    ebml_free(syntax[i].def.n, ptr);
1165
                av_free(list->elem);
1166
            } else
1167
                ebml_free(syntax[i].def.n, data_off);
1168
        default:  break;
1169
        }
1170
    }
1171
}
1172

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

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

    
1242
    *buf = pkt_data;
1243
    *buf_size = pkt_size;
1244
    return 0;
1245
 failed:
1246
    av_free(pkt_data);
1247
    return -1;
1248
}
1249

    
1250
static void
1251
matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1252
{
1253
    EbmlList *seekhead_list = &matroska->seekhead;
1254
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1255
    uint32_t peek_id_cache = matroska->peek_id;
1256
    uint32_t level_up = matroska->level_up;
1257
    offset_t before_pos = url_ftell(matroska->ctx->pb);
1258
    MatroskaLevel level;
1259
    int i;
1260

    
1261
    for (i=0; i<seekhead_list->nb_elem; i++) {
1262
        if (seekhead[i].pos <= before_pos
1263
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1264
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1265
            continue;
1266

    
1267
        /* seek */
1268
        if (ebml_read_seek(matroska,
1269
                           seekhead[i].pos+matroska->segment_start) < 0)
1270
            continue;
1271

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

    
1281
        level.start = 0;
1282
        level.length = (uint64_t)-1;
1283
        matroska->levels[matroska->num_levels] = level;
1284
        matroska->num_levels++;
1285

    
1286
        ebml_parse_id(matroska, matroska_segment, seekhead[i].id, matroska);
1287

    
1288
        /* remove dummy level */
1289
        while (matroska->num_levels) {
1290
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1291
            if (length == (uint64_t)-1)
1292
                break;
1293
        }
1294
    }
1295

    
1296
    /* seek back */
1297
    ebml_read_seek(matroska, before_pos);
1298
    matroska->peek_id = peek_id_cache;
1299
    matroska->level_up = level_up;
1300
}
1301

    
1302
static int
1303
matroska_aac_profile (char *codec_id)
1304
{
1305
    static const char *aac_profiles[] = {
1306
        "MAIN", "LC", "SSR"
1307
    };
1308
    int profile;
1309

    
1310
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1311
        if (strstr(codec_id, aac_profiles[profile]))
1312
            break;
1313
    return profile + 1;
1314
}
1315

    
1316
static int
1317
matroska_aac_sri (int samplerate)
1318
{
1319
    int sri;
1320

    
1321
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1322
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1323
            break;
1324
    return sri;
1325
}
1326

    
1327
static int
1328
matroska_read_header (AVFormatContext    *s,
1329
                      AVFormatParameters *ap)
1330
{
1331
    MatroskaDemuxContext *matroska = s->priv_data;
1332
    EbmlList *attachements_list = &matroska->attachments;
1333
    MatroskaAttachement *attachements;
1334
    EbmlList *chapters_list = &matroska->chapters;
1335
    MatroskaChapter *chapters;
1336
    MatroskaTrack *tracks;
1337
    EbmlList *index_list;
1338
    MatroskaIndex *index;
1339
    Ebml ebml = { 0 };
1340
    AVStream *st;
1341
    int i, j;
1342

    
1343
    matroska->ctx = s;
1344

    
1345
    /* First read the EBML header. */
1346
    if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
1347
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1348
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1349
        || ebml.doctype_version > 2) {
1350
        av_log(matroska->ctx, AV_LOG_ERROR,
1351
               "EBML header using unsupported features\n"
1352
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1353
               ebml.version, ebml.doctype, ebml.doctype_version);
1354
        return AVERROR_NOFMT;
1355
    }
1356
    ebml_free(ebml_syntax, &ebml);
1357

    
1358
    /* The next thing is a segment. */
1359
    if (ebml_parse(matroska, matroska_segments, matroska, 0, 1) < 0)
1360
        return -1;
1361
    matroska_execute_seekhead(matroska);
1362

    
1363
    /* Have we found a cluster? */
1364
    if (ebml_peek_id(matroska, NULL) != MATROSKA_ID_CLUSTER)
1365
        return -1;
1366

    
1367
    if (matroska->duration)
1368
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1369
                                  * 1000 / AV_TIME_BASE;
1370
    if (matroska->title)
1371
        strncpy(matroska->ctx->title, matroska->title,
1372
                sizeof(matroska->ctx->title)-1);
1373

    
1374
    tracks = matroska->tracks.elem;
1375
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1376
        MatroskaTrack *track = &tracks[i];
1377
        enum CodecID codec_id = CODEC_ID_NONE;
1378
        EbmlList *encodings_list = &tracks->encodings;
1379
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1380
        uint8_t *extradata = NULL;
1381
        int extradata_size = 0;
1382
        int extradata_offset = 0;
1383

    
1384
        /* Apply some sanity checks. */
1385
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1386
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1387
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1388
            av_log(matroska->ctx, AV_LOG_INFO,
1389
                   "Unknown or unsupported track type %"PRIu64"\n",
1390
                   track->type);
1391
            continue;
1392
        }
1393
        if (track->codec_id == NULL)
1394
            continue;
1395

    
1396
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1397
            if (!track->default_duration)
1398
                track->default_duration = 1000000000/track->video.frame_rate;
1399
            if (!track->video.display_width)
1400
                track->video.display_width = track->video.pixel_width;
1401
            if (!track->video.display_height)
1402
                track->video.display_height = track->video.pixel_height;
1403
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1404
            if (!track->audio.out_samplerate)
1405
                track->audio.out_samplerate = track->audio.samplerate;
1406
        }
1407
        if (encodings_list->nb_elem > 1) {
1408
            av_log(matroska->ctx, AV_LOG_ERROR,
1409
                   "Multiple combined encodings no supported");
1410
        } else if (encodings_list->nb_elem == 1) {
1411
            if (encodings[0].type ||
1412
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1413
#ifdef CONFIG_ZLIB
1414
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1415
#endif
1416
#ifdef CONFIG_BZLIB
1417
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1418
#endif
1419
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1420
                encodings[0].scope = 0;
1421
                av_log(matroska->ctx, AV_LOG_ERROR,
1422
                       "Unsupported encoding type");
1423
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1424
                uint8_t *codec_priv = track->codec_priv.data;
1425
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1426
                                                    &track->codec_priv.size,
1427
                                                    track);
1428
                if (offset < 0) {
1429
                    track->codec_priv.data = NULL;
1430
                    track->codec_priv.size = 0;
1431
                    av_log(matroska->ctx, AV_LOG_ERROR,
1432
                           "Failed to decode codec private data\n");
1433
                } else if (offset > 0) {
1434
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1435
                    memcpy(track->codec_priv.data,
1436
                           encodings[0].compression.settings.data, offset);
1437
                    memcpy(track->codec_priv.data+offset, codec_priv,
1438
                           track->codec_priv.size);
1439
                    track->codec_priv.size += offset;
1440
                }
1441
                if (codec_priv != track->codec_priv.data)
1442
                    av_free(codec_priv);
1443
            }
1444
        }
1445

    
1446
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1447
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1448
                        strlen(ff_mkv_codec_tags[j].str))){
1449
                codec_id= ff_mkv_codec_tags[j].id;
1450
                break;
1451
            }
1452
        }
1453

    
1454
        st = track->stream = av_new_stream(s, matroska->num_streams++);
1455
        if (st == NULL)
1456
            return AVERROR(ENOMEM);
1457

    
1458
        /* Set the FourCC from the CodecID. */
1459
        /* This is the MS compatibility mode which stores a
1460
         * BITMAPINFOHEADER in the CodecPrivate. */
1461
        if (!strcmp(track->codec_id,
1462
                    MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
1463
            (track->codec_priv.size >= 40) &&
1464
            (track->codec_priv.data != NULL)) {
1465
            /* Offset of biCompression. Stored in LE. */
1466
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1467
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1468

    
1469
        }
1470

    
1471
        /* This is the MS compatibility mode which stores a
1472
         * WAVEFORMATEX in the CodecPrivate. */
1473
        else if (!strcmp(track->codec_id,
1474
                         MATROSKA_CODEC_ID_AUDIO_ACM) &&
1475
                 (track->codec_priv.size >= 18) &&
1476
                 (track->codec_priv.data != NULL)) {
1477
            /* Offset of wFormatTag. Stored in LE. */
1478
            uint16_t tag = AV_RL16(track->codec_priv.data);
1479
            codec_id = codec_get_id(codec_wav_tags, tag);
1480

    
1481
        }
1482

    
1483
        else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
1484
                 (track->codec_priv.size >= 86) &&
1485
                 (track->codec_priv.data != NULL)) {
1486
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1487
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1488
        }
1489

    
1490
        else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1491
            int profile = matroska_aac_profile(track->codec_id);
1492
            int sri = matroska_aac_sri(track->audio.samplerate);
1493
            extradata = av_malloc(5);
1494
            if (extradata == NULL)
1495
                return AVERROR(ENOMEM);
1496
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1497
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1498
            if (strstr(track->codec_id, "SBR")) {
1499
                sri = matroska_aac_sri(track->audio.out_samplerate);
1500
                extradata[2] = 0x56;
1501
                extradata[3] = 0xE5;
1502
                extradata[4] = 0x80 | (sri<<3);
1503
                extradata_size = 5;
1504
            } else {
1505
                extradata_size = 2;
1506
            }
1507
        }
1508

    
1509
        else if (codec_id == CODEC_ID_TTA) {
1510
            ByteIOContext b;
1511
            extradata_size = 30;
1512
            extradata = av_mallocz(extradata_size);
1513
            if (extradata == NULL)
1514
                return AVERROR(ENOMEM);
1515
            init_put_byte(&b, extradata, extradata_size, 1,
1516
                          NULL, NULL, NULL, NULL);
1517
            put_buffer(&b, "TTA1", 4);
1518
            put_le16(&b, 1);
1519
            put_le16(&b, track->audio.channels);
1520
            put_le16(&b, track->audio.bitdepth);
1521
            put_le32(&b, track->audio.out_samplerate);
1522
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1523
        }
1524

    
1525
        else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1526
                 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1527
            extradata_offset = 26;
1528
            track->codec_priv.size -= extradata_offset;
1529
        }
1530

    
1531
        else if (codec_id == CODEC_ID_RA_144) {
1532
            track->audio.out_samplerate = 8000;
1533
            track->audio.channels = 1;
1534
        }
1535

    
1536
        else if (codec_id == CODEC_ID_RA_288 ||
1537
                 codec_id == CODEC_ID_COOK ||
1538
                 codec_id == CODEC_ID_ATRAC3) {
1539
            ByteIOContext b;
1540

    
1541
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1542
                          0, NULL, NULL, NULL, NULL);
1543
            url_fskip(&b, 24);
1544
            track->audio.coded_framesize = get_be32(&b);
1545
            url_fskip(&b, 12);
1546
            track->audio.sub_packet_h    = get_be16(&b);
1547
            track->audio.frame_size      = get_be16(&b);
1548
            track->audio.sub_packet_size = get_be16(&b);
1549
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1550
            if (codec_id == CODEC_ID_RA_288) {
1551
                st->codec->block_align = track->audio.coded_framesize;
1552
                track->codec_priv.size = 0;
1553
            } else {
1554
                st->codec->block_align = track->audio.sub_packet_size;
1555
                extradata_offset = 78;
1556
                track->codec_priv.size -= extradata_offset;
1557
            }
1558
        }
1559

    
1560
        if (codec_id == CODEC_ID_NONE) {
1561
            av_log(matroska->ctx, AV_LOG_INFO,
1562
                   "Unknown/unsupported CodecID %s.\n",
1563
                   track->codec_id);
1564
        }
1565

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

    
1568
        st->codec->codec_id = codec_id;
1569
        st->start_time = 0;
1570
        if (strcmp(track->language, "und"))
1571
            av_strlcpy(st->language, track->language, 4);
1572

    
1573
        if (track->flag_default)
1574
            st->disposition |= AV_DISPOSITION_DEFAULT;
1575

    
1576
        if (track->default_duration)
1577
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1578
                      track->default_duration, 1000000000, 30000);
1579

    
1580
        if(extradata){
1581
            st->codec->extradata = extradata;
1582
            st->codec->extradata_size = extradata_size;
1583
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1584
            st->codec->extradata = av_malloc(track->codec_priv.size);
1585
            if(st->codec->extradata == NULL)
1586
                return AVERROR(ENOMEM);
1587
            st->codec->extradata_size = track->codec_priv.size;
1588
            memcpy(st->codec->extradata,
1589
                   track->codec_priv.data + extradata_offset,
1590
                   track->codec_priv.size);
1591
        }
1592

    
1593
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1594
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1595
            st->codec->codec_tag  = track->video.fourcc;
1596
            st->codec->width  = track->video.pixel_width;
1597
            st->codec->height = track->video.pixel_height;
1598
            av_reduce(&st->codec->sample_aspect_ratio.num,
1599
                      &st->codec->sample_aspect_ratio.den,
1600
                      st->codec->height * track->video.display_width,
1601
                      st->codec-> width * track->video.display_height,
1602
                      255);
1603
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1604
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1605
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1606
            st->codec->sample_rate = track->audio.out_samplerate;
1607
            st->codec->channels = track->audio.channels;
1608
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1609
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1610
        }
1611

    
1612
        /* What do we do with private data? E.g. for Vorbis. */
1613
    }
1614

    
1615
    attachements = attachements_list->elem;
1616
    for (j=0; j<attachements_list->nb_elem; j++) {
1617
        if (!(attachements[j].filename && attachements[j].mime &&
1618
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1619
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1620
        } else {
1621
            AVStream *st = av_new_stream(s, matroska->num_streams++);
1622
            if (st == NULL)
1623
                break;
1624
            st->filename          = av_strdup(attachements[j].filename);
1625
            st->codec->codec_id = CODEC_ID_NONE;
1626
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1627
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1628
            if(st->codec->extradata == NULL)
1629
                break;
1630
            st->codec->extradata_size = attachements[j].bin.size;
1631
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1632

    
1633
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1634
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1635
                             strlen(ff_mkv_mime_tags[i].str))) {
1636
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1637
                    break;
1638
                }
1639
            }
1640
        }
1641
    }
1642

    
1643
    chapters = chapters_list->elem;
1644
    for (i=0; i<chapters_list->nb_elem; i++)
1645
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1646
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1647
                           chapters[i].start, chapters[i].end,
1648
                           chapters[i].title);
1649

    
1650
    index_list = &matroska->index;
1651
    index = index_list->elem;
1652
    for (i=0; i<index_list->nb_elem; i++) {
1653
        EbmlList *pos_list = &index[i].pos;
1654
        MatroskaIndexPos *pos = pos_list->elem;
1655
        for (j=0; j<pos_list->nb_elem; j++) {
1656
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1657
                                                              pos[j].track);
1658
            if (track && track->stream)
1659
                av_add_index_entry(track->stream,
1660
                                   pos[j].pos + matroska->segment_start,
1661
                                   index[i].time*matroska->time_scale/AV_TIME_BASE,
1662
                                   0, 0, AVINDEX_KEYFRAME);
1663
        }
1664
    }
1665

    
1666
    return 0;
1667
}
1668

    
1669
static int
1670
matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
1671
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
1672
                     int is_keyframe)
1673
{
1674
    MatroskaTrack *track;
1675
    int res = 0;
1676
    AVStream *st;
1677
    AVPacket *pkt;
1678
    uint8_t *origdata = data;
1679
    int16_t block_time;
1680
    uint32_t *lace_size = NULL;
1681
    int n, flags, laces = 0;
1682
    uint64_t num;
1683

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

    
1693
    /* fetch track from num */
1694
    track = matroska_find_track_by_num(matroska, num);
1695
    if (size <= 3 || !track || !track->stream) {
1696
        av_log(matroska->ctx, AV_LOG_INFO,
1697
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1698
        av_free(origdata);
1699
        return res;
1700
    }
1701
    st = track->stream;
1702
    if (st->discard >= AVDISCARD_ALL) {
1703
        av_free(origdata);
1704
        return res;
1705
    }
1706
    if (duration == AV_NOPTS_VALUE)
1707
        duration = track->default_duration / matroska->time_scale;
1708

    
1709
    /* block_time (relative to cluster time) */
1710
    block_time = AV_RB16(data);
1711
    data += 2;
1712
    flags = *data++;
1713
    size -= 3;
1714
    if (is_keyframe == -1)
1715
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1716

    
1717
    if (matroska->skip_to_keyframe) {
1718
        if (!is_keyframe || st != matroska->skip_to_stream) {
1719
            av_free(origdata);
1720
            return res;
1721
        }
1722
        matroska->skip_to_keyframe = 0;
1723
    }
1724

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

    
1732
        case 0x1: /* xiph lacing */
1733
        case 0x2: /* fixed-size lacing */
1734
        case 0x3: /* EBML lacing */
1735
            assert(size>0); // size <=3 is checked before size-=3 above
1736
            laces = (*data) + 1;
1737
            data += 1;
1738
            size -= 1;
1739
            lace_size = av_mallocz(laces * sizeof(int));
1740

    
1741
            switch ((flags & 0x06) >> 1) {
1742
                case 0x1: /* xiph lacing */ {
1743
                    uint8_t temp;
1744
                    uint32_t total = 0;
1745
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1746
                        while (1) {
1747
                            if (size == 0) {
1748
                                res = -1;
1749
                                break;
1750
                            }
1751
                            temp = *data;
1752
                            lace_size[n] += temp;
1753
                            data += 1;
1754
                            size -= 1;
1755
                            if (temp != 0xff)
1756
                                break;
1757
                        }
1758
                        total += lace_size[n];
1759
                    }
1760
                    lace_size[n] = size - total;
1761
                    break;
1762
                }
1763

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

    
1769
                case 0x3: /* EBML lacing */ {
1770
                    uint32_t total;
1771
                    n = matroska_ebmlnum_uint(data, size, &num);
1772
                    if (n < 0) {
1773
                        av_log(matroska->ctx, AV_LOG_INFO,
1774
                               "EBML block data error\n");
1775
                        break;
1776
                    }
1777
                    data += n;
1778
                    size -= n;
1779
                    total = lace_size[0] = num;
1780
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1781
                        int64_t snum;
1782
                        int r;
1783
                        r = matroska_ebmlnum_sint (data, size, &snum);
1784
                        if (r < 0) {
1785
                            av_log(matroska->ctx, AV_LOG_INFO,
1786
                                   "EBML block data error\n");
1787
                            break;
1788
                        }
1789
                        data += r;
1790
                        size -= r;
1791
                        lace_size[n] = lace_size[n - 1] + snum;
1792
                        total += lace_size[n];
1793
                    }
1794
                    lace_size[n] = size - total;
1795
                    break;
1796
                }
1797
            }
1798
            break;
1799
    }
1800

    
1801
    if (res == 0) {
1802
        uint64_t timecode = AV_NOPTS_VALUE;
1803

    
1804
        if (cluster_time != (uint64_t)-1
1805
            && (block_time >= 0 || cluster_time >= -block_time))
1806
            timecode = cluster_time + block_time;
1807

    
1808
        for (n = 0; n < laces; n++) {
1809
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1810
                st->codec->codec_id == CODEC_ID_COOK ||
1811
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1812
                int a = st->codec->block_align;
1813
                int sps = track->audio.sub_packet_size;
1814
                int cfs = track->audio.coded_framesize;
1815
                int h = track->audio.sub_packet_h;
1816
                int y = track->audio.sub_packet_cnt;
1817
                int w = track->audio.frame_size;
1818
                int x;
1819

    
1820
                if (!track->audio.pkt_cnt) {
1821
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1822
                        for (x=0; x<h/2; x++)
1823
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1824
                                   data+x*cfs, cfs);
1825
                    else
1826
                        for (x=0; x<w/sps; x++)
1827
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1828

    
1829
                    if (++track->audio.sub_packet_cnt >= h) {
1830
                        track->audio.sub_packet_cnt = 0;
1831
                        track->audio.pkt_cnt = h*w / a;
1832
                    }
1833
                }
1834
                while (track->audio.pkt_cnt) {
1835
                    pkt = av_mallocz(sizeof(AVPacket));
1836
                    av_new_packet(pkt, a);
1837
                    memcpy(pkt->data, track->audio.buf
1838
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1839
                    pkt->pos = pos;
1840
                    pkt->stream_index = st->index;
1841
                    matroska_queue_packet(matroska, pkt);
1842
                }
1843
            } else {
1844
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1845
                int offset = 0, pkt_size = lace_size[n];
1846
                uint8_t *pkt_data = data;
1847

    
1848
                if (encodings && encodings->scope & 1) {
1849
                    offset = matroska_decode_buffer(&pkt_data, &pkt_size,
1850
                                                    track);
1851
                    if (offset < 0)
1852
                        continue;
1853
                }
1854

    
1855
                pkt = av_mallocz(sizeof(AVPacket));
1856
                /* XXX: prevent data copy... */
1857
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1858
                    av_free(pkt);
1859
                    res = AVERROR(ENOMEM);
1860
                    n = laces-1;
1861
                    break;
1862
                }
1863
                if (offset)
1864
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1865
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1866

    
1867
                if (pkt_data != data)
1868
                    av_free(pkt_data);
1869

    
1870
                if (n == 0)
1871
                    pkt->flags = is_keyframe;
1872
                pkt->stream_index = st->index;
1873

    
1874
                pkt->pts = timecode;
1875
                pkt->pos = pos;
1876
                pkt->duration = duration;
1877

    
1878
                matroska_queue_packet(matroska, pkt);
1879
            }
1880

    
1881
            if (timecode != AV_NOPTS_VALUE)
1882
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1883
            data += lace_size[n];
1884
        }
1885
    }
1886

    
1887
    av_free(lace_size);
1888
    av_free(origdata);
1889
    return res;
1890
}
1891

    
1892
static int
1893
matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
1894
                           uint64_t              cluster_time)
1895
{
1896
    int res = 0;
1897
    uint32_t id;
1898
    int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
1899
    uint64_t duration = AV_NOPTS_VALUE;
1900
    uint8_t *data;
1901
    int size = 0;
1902
    int64_t pos = 0;
1903

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

    
1906
    while (res == 0) {
1907
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1908
            res = AVERROR(EIO);
1909
            break;
1910
        } else if (matroska->level_up) {
1911
            matroska->level_up--;
1912
            break;
1913
        }
1914

    
1915
        switch (id) {
1916
            /* one block inside the group. Note, block parsing is one
1917
             * of the harder things, so this code is a bit complicated.
1918
             * See http://www.matroska.org/ for documentation. */
1919
            case MATROSKA_ID_BLOCK: {
1920
                pos = url_ftell(matroska->ctx->pb);
1921
                res = ebml_read_binary(matroska, &id, &data, &size);
1922
                break;
1923
            }
1924

    
1925
            case MATROSKA_ID_BLOCKDURATION: {
1926
                if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
1927
                    break;
1928
                break;
1929
            }
1930

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

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

    
1948
            case EBML_ID_VOID:
1949
                res = ebml_read_skip(matroska);
1950
                break;
1951
        }
1952

    
1953
        if (matroska->level_up) {
1954
            matroska->level_up--;
1955
            break;
1956
        }
1957
    }
1958

    
1959
    if (res)
1960
        return res;
1961

    
1962
    if (size > 0)
1963
        res = matroska_parse_block(matroska, data, size, pos, cluster_time,
1964
                                   duration, is_keyframe);
1965

    
1966
    return res;
1967
}
1968

    
1969
static int
1970
matroska_parse_cluster (MatroskaDemuxContext *matroska)
1971
{
1972
    int res = 0;
1973
    uint32_t id;
1974
    uint64_t cluster_time = 0;
1975
    uint8_t *data;
1976
    int64_t pos;
1977
    int size;
1978

    
1979
    av_log(matroska->ctx, AV_LOG_DEBUG,
1980
           "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
1981

    
1982
    while (res == 0) {
1983
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1984
            res = AVERROR(EIO);
1985
            break;
1986
        } else if (matroska->level_up) {
1987
            matroska->level_up--;
1988
            break;
1989
        }
1990

    
1991
        switch (id) {
1992
            /* cluster timecode */
1993
            case MATROSKA_ID_CLUSTERTIMECODE: {
1994
                uint64_t num;
1995
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1996
                    break;
1997
                cluster_time = num;
1998
                break;
1999
            }
2000

    
2001
                /* a group of blocks inside a cluster */
2002
            case MATROSKA_ID_BLOCKGROUP:
2003
                if ((res = ebml_read_master(matroska, &id)) < 0)
2004
                    break;
2005
                res = matroska_parse_blockgroup(matroska, cluster_time);
2006
                break;
2007

    
2008
            case MATROSKA_ID_SIMPLEBLOCK:
2009
                pos = url_ftell(matroska->ctx->pb);
2010
                res = ebml_read_binary(matroska, &id, &data, &size);
2011
                if (res == 0)
2012
                    res = matroska_parse_block(matroska, data, size, pos,
2013
                                               cluster_time, AV_NOPTS_VALUE,
2014
                                               -1);
2015
                break;
2016

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

    
2022
            case EBML_ID_VOID:
2023
                res = ebml_read_skip(matroska);
2024
                break;
2025
        }
2026

    
2027
        if (matroska->level_up) {
2028
            matroska->level_up--;
2029
            break;
2030
        }
2031
    }
2032

    
2033
    return res;
2034
}
2035

    
2036
static int
2037
matroska_read_packet (AVFormatContext *s,
2038
                      AVPacket        *pkt)
2039
{
2040
    MatroskaDemuxContext *matroska = s->priv_data;
2041
    int res;
2042
    uint32_t id;
2043

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

    
2047
        /* Have we already reached the end? */
2048
        if (matroska->done)
2049
            return AVERROR(EIO);
2050

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

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

    
2068
                default:
2069
                case EBML_ID_VOID:
2070
                    res = ebml_read_skip(matroska);
2071
                    break;
2072
            }
2073

    
2074
            if (matroska->level_up) {
2075
                matroska->level_up--;
2076
                break;
2077
            }
2078
        }
2079

    
2080
        if (res == -1)
2081
            matroska->done = 1;
2082
    }
2083

    
2084
    return 0;
2085
}
2086

    
2087
static int
2088
matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2089
                    int flags)
2090
{
2091
    MatroskaDemuxContext *matroska = s->priv_data;
2092
    AVStream *st = s->streams[stream_index];
2093
    int index;
2094

    
2095
    /* find index entry */
2096
    index = av_index_search_timestamp(st, timestamp, flags);
2097
    if (index < 0)
2098
        return 0;
2099

    
2100
    matroska_clear_queue(matroska);
2101

    
2102
    /* do the seek */
2103
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
2104
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2105
    matroska->skip_to_stream = st;
2106
    matroska->peek_id = 0;
2107
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
2108
    return 0;
2109
}
2110

    
2111
static int
2112
matroska_read_close (AVFormatContext *s)
2113
{
2114
    MatroskaDemuxContext *matroska = s->priv_data;
2115
    MatroskaTrack *tracks = matroska->tracks.elem;
2116
    int n = 0;
2117

    
2118
    matroska_clear_queue(matroska);
2119

    
2120
    for (n=0; n < matroska->tracks.nb_elem; n++)
2121
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2122
            av_free(tracks[n].audio.buf);
2123
    ebml_free(matroska_segment, matroska);
2124

    
2125
    return 0;
2126
}
2127

    
2128
AVInputFormat matroska_demuxer = {
2129
    "matroska",
2130
    NULL_IF_CONFIG_SMALL("Matroska file format"),
2131
    sizeof(MatroskaDemuxContext),
2132
    matroska_probe,
2133
    matroska_read_header,
2134
    matroska_read_packet,
2135
    matroska_read_close,
2136
    matroska_read_seek,
2137
};