Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 051ef5ce

History | View | Annotate | Download (61.6 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 {
172
    uint64_t start;
173
    uint64_t length;
174
} MatroskaLevel;
175

    
176
typedef struct {
177
    AVFormatContext *ctx;
178

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

    
184
    uint64_t time_scale;
185
    double   duration;
186
    char    *title;
187
    EbmlList tracks;
188
    EbmlList attachments;
189
    EbmlList chapters;
190
    EbmlList index;
191
    EbmlList seekhead;
192

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

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

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

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

    
207
    int done;
208
    int has_cluster_id;
209

    
210
    /* What to skip before effectively reading a packet. */
211
    int skip_to_keyframe;
212
    AVStream *skip_to_stream;
213
} MatroskaDemuxContext;
214

    
215
typedef struct {
216
    uint64_t duration;
217
    int64_t  reference;
218
    EbmlBin  bin;
219
} MatroskaBlock;
220

    
221
typedef struct {
222
    uint64_t timecode;
223
    EbmlList blocks;
224
} MatroskaCluster;
225

    
226
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
227

    
228
static EbmlSyntax ebml_header[] = {
229
    { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
230
    { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
231
    { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
232
    { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
233
    { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
234
    { EBML_ID_EBMLVERSION,            EBML_NONE },
235
    { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
236
    { EBML_ID_VOID,                   EBML_NONE },
237
    { 0 }
238
};
239

    
240
static EbmlSyntax ebml_syntax[] = {
241
    { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
242
    { 0 }
243
};
244

    
245
static EbmlSyntax matroska_info[] = {
246
    { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
247
    { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
248
    { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
249
    { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
250
    { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
251
    { MATROSKA_ID_DATEUTC,            EBML_NONE },
252
    { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
253
    { EBML_ID_VOID,                   EBML_NONE },
254
    { 0 }
255
};
256

    
257
static EbmlSyntax matroska_track_video[] = {
258
    { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
259
    { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
260
    { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
261
    { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
262
    { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
263
    { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
264
    { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
265
    { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
266
    { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
267
    { EBML_ID_VOID,                   EBML_NONE },
268
    { 0 }
269
};
270

    
271
static EbmlSyntax matroska_track_audio[] = {
272
    { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
273
    { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
274
    { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
275
    { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
276
    { EBML_ID_VOID,                   EBML_NONE },
277
    { 0 }
278
};
279

    
280
static EbmlSyntax matroska_track_encoding_compression[] = {
281
    { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
282
    { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
283
    { EBML_ID_VOID,                   EBML_NONE },
284
    { 0 }
285
};
286

    
287
static EbmlSyntax matroska_track_encoding[] = {
288
    { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
289
    { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
290
    { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
291
    { EBML_ID_VOID,                   EBML_NONE },
292
    { 0 }
293
};
294

    
295
static EbmlSyntax matroska_track_encodings[] = {
296
    { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
297
    { EBML_ID_VOID,                   EBML_NONE },
298
    { 0 }
299
};
300

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

    
328
static EbmlSyntax matroska_tracks[] = {
329
    { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
330
    { EBML_ID_VOID,                   EBML_NONE },
331
    { 0 }
332
};
333

    
334
static EbmlSyntax matroska_attachment[] = {
335
    { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
336
    { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
337
    { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
338
    { MATROSKA_ID_FILEUID,            EBML_NONE },
339
    { EBML_ID_VOID,                   EBML_NONE },
340
    { 0 }
341
};
342

    
343
static EbmlSyntax matroska_attachments[] = {
344
    { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
345
    { EBML_ID_VOID,                   EBML_NONE },
346
    { 0 }
347
};
348

    
349
static EbmlSyntax matroska_chapter_display[] = {
350
    { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
351
    { EBML_ID_VOID,                   EBML_NONE },
352
    { 0 }
353
};
354

    
355
static EbmlSyntax matroska_chapter_entry[] = {
356
    { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
357
    { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
358
    { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
359
    { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
360
    { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
361
    { EBML_ID_VOID,                   EBML_NONE },
362
    { 0 }
363
};
364

    
365
static EbmlSyntax matroska_chapter[] = {
366
    { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
367
    { MATROSKA_ID_EDITIONUID,         EBML_NONE },
368
    { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
369
    { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
370
    { EBML_ID_VOID,                   EBML_NONE },
371
    { 0 }
372
};
373

    
374
static EbmlSyntax matroska_chapters[] = {
375
    { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
376
    { EBML_ID_VOID,                   EBML_NONE },
377
    { 0 }
378
};
379

    
380
static EbmlSyntax matroska_index_pos[] = {
381
    { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
382
    { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
383
    { EBML_ID_VOID,                   EBML_NONE },
384
    { 0 }
385
};
386

    
387
static EbmlSyntax matroska_index_entry[] = {
388
    { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
389
    { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
390
    { EBML_ID_VOID,                   EBML_NONE },
391
    { 0 }
392
};
393

    
394
static EbmlSyntax matroska_index[] = {
395
    { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
396
    { EBML_ID_VOID,                   EBML_NONE },
397
    { 0 }
398
};
399

    
400
static EbmlSyntax matroska_tags[] = {
401
    { EBML_ID_VOID,                   EBML_NONE },
402
    { 0 }
403
};
404

    
405
static EbmlSyntax matroska_seekhead_entry[] = {
406
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
407
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
408
    { EBML_ID_VOID,                   EBML_NONE },
409
    { 0 }
410
};
411

    
412
static EbmlSyntax matroska_seekhead[] = {
413
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
414
    { EBML_ID_VOID,                   EBML_NONE },
415
    { 0 }
416
};
417

    
418
static EbmlSyntax matroska_segment[] = {
419
    { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
420
    { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
421
    { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
422
    { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
423
    { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
424
    { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
425
    { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
426
    { MATROSKA_ID_CLUSTER,        EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
427
    { EBML_ID_VOID,               EBML_NONE },
428
    { 0 }
429
};
430

    
431
static EbmlSyntax matroska_segments[] = {
432
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
433
    { 0 }
434
};
435

    
436
static EbmlSyntax matroska_blockgroup[] = {
437
    { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
438
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
439
    { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
440
    { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
441
    { EBML_ID_VOID,               EBML_NONE },
442
    { 0 }
443
};
444

    
445
static EbmlSyntax matroska_cluster[] = {
446
    { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
447
    { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
448
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
449
    { EBML_ID_VOID,               EBML_NONE },
450
    { 0 }
451
};
452

    
453
static EbmlSyntax matroska_clusters[] = {
454
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
455
    { 0 }
456
};
457

    
458
/*
459
 * Return: the amount of levels in the hierarchy that the
460
 * current element lies higher than the previous one.
461
 * The opposite isn't done - that's auto-done using master
462
 * element reading.
463
 */
464
static int
465
ebml_read_element_level_up (MatroskaDemuxContext *matroska)
466
{
467
    ByteIOContext *pb = matroska->ctx->pb;
468
    offset_t pos = url_ftell(pb);
469
    int num = 0;
470

    
471
    while (matroska->num_levels > 0) {
472
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
473

    
474
        if (pos >= level->start + level->length) {
475
            matroska->num_levels--;
476
            num++;
477
        } else {
478
            break;
479
        }
480
    }
481

    
482
    return num;
483
}
484

    
485
/*
486
 * Read: an "EBML number", which is defined as a variable-length
487
 * array of bytes. The first byte indicates the length by giving a
488
 * number of 0-bits followed by a one. The position of the first
489
 * "one" bit inside the first byte indicates the length of this
490
 * number.
491
 * Returns: num. of bytes read. < 0 on error.
492
 */
493
static int
494
ebml_read_num (MatroskaDemuxContext *matroska,
495
               int                   max_size,
496
               uint64_t             *number)
497
{
498
    ByteIOContext *pb = matroska->ctx->pb;
499
    int len_mask = 0x80, read = 1, n = 1;
500
    int64_t total = 0;
501

    
502
    /* the first byte tells us the length in bytes - get_byte() can normally
503
     * return 0, but since that's not a valid first ebmlID byte, we can
504
     * use it safely here to catch EOS. */
505
    if (!(total = get_byte(pb))) {
506
        /* we might encounter EOS here */
507
        if (!url_feof(pb)) {
508
            offset_t pos = url_ftell(pb);
509
            av_log(matroska->ctx, AV_LOG_ERROR,
510
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
511
                   pos, pos);
512
        }
513
        return AVERROR(EIO); /* EOS or actual I/O error */
514
    }
515

    
516
    /* get the length of the EBML number */
517
    while (read <= max_size && !(total & len_mask)) {
518
        read++;
519
        len_mask >>= 1;
520
    }
521
    if (read > max_size) {
522
        offset_t pos = url_ftell(pb) - 1;
523
        av_log(matroska->ctx, AV_LOG_ERROR,
524
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
525
               (uint8_t) total, pos, pos);
526
        return AVERROR_INVALIDDATA;
527
    }
528

    
529
    /* read out length */
530
    total &= ~len_mask;
531
    while (n++ < read)
532
        total = (total << 8) | get_byte(pb);
533

    
534
    *number = total;
535

    
536
    return read;
537
}
538

    
539
/*
540
 * Read: the element content data ID.
541
 * Return: the number of bytes read or < 0 on error.
542
 */
543
static int
544
ebml_read_element_id (MatroskaDemuxContext *matroska,
545
                      uint32_t             *id,
546
                      int                  *level_up)
547
{
548
    int read;
549
    uint64_t total;
550

    
551
    /* if we re-call this, use our cached ID */
552
    if (matroska->peek_id != 0) {
553
        if (level_up)
554
            *level_up = 0;
555
        *id = matroska->peek_id;
556
        return 0;
557
    }
558

    
559
    /* read out the "EBML number", include tag in ID */
560
    if ((read = ebml_read_num(matroska, 4, &total)) < 0)
561
        return read;
562
    *id = matroska->peek_id  = total | (1 << (read * 7));
563

    
564
    /* level tracking */
565
    if (level_up)
566
        *level_up = ebml_read_element_level_up(matroska);
567

    
568
    return read;
569
}
570

    
571
/*
572
 * Read: element content length.
573
 * Return: the number of bytes read or < 0 on error.
574
 */
575
static int
576
ebml_read_element_length (MatroskaDemuxContext *matroska,
577
                          uint64_t             *length)
578
{
579
    /* clear cache since we're now beyond that data point */
580
    matroska->peek_id = 0;
581

    
582
    /* read out the "EBML number", include tag in ID */
583
    return ebml_read_num(matroska, 8, length);
584
}
585

    
586
/*
587
 * Return: the ID of the next element, or 0 on error.
588
 * Level_up contains the amount of levels that this
589
 * next element lies higher than the previous one.
590
 */
591
static uint32_t
592
ebml_peek_id (MatroskaDemuxContext *matroska,
593
              int                  *level_up)
594
{
595
    uint32_t id;
596

    
597
    if (ebml_read_element_id(matroska, &id, level_up) < 0)
598
        return 0;
599

    
600
    return id;
601
}
602

    
603
/*
604
 * Seek to a given offset.
605
 * 0 is success, -1 is failure.
606
 */
607
static int
608
ebml_read_seek (MatroskaDemuxContext *matroska,
609
                offset_t              offset)
610
{
611
    ByteIOContext *pb = matroska->ctx->pb;
612

    
613
    /* clear ID cache, if any */
614
    matroska->peek_id = 0;
615

    
616
    return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
617
}
618

    
619
/*
620
 * Skip the next element.
621
 * 0 is success, -1 is failure.
622
 */
623
static int
624
ebml_read_skip (MatroskaDemuxContext *matroska)
625
{
626
    ByteIOContext *pb = matroska->ctx->pb;
627
    uint32_t id;
628
    uint64_t length;
629
    int res;
630

    
631
    if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
632
        (res = ebml_read_element_length(matroska, &length)) < 0)
633
        return res;
634

    
635
    url_fskip(pb, length);
636

    
637
    return 0;
638
}
639

    
640
/*
641
 * Read the next element as an unsigned int.
642
 * 0 is success, < 0 is failure.
643
 */
644
static int
645
ebml_read_uint (MatroskaDemuxContext *matroska,
646
                uint32_t             *id,
647
                uint64_t             *num)
648
{
649
    ByteIOContext *pb = matroska->ctx->pb;
650
    int n = 0, size, 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 uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
661
                size, pos, pos);
662
        return AVERROR_INVALIDDATA;
663
    }
664

    
665
    /* big-endian ordening; build up number */
666
    *num = 0;
667
    while (n++ < size)
668
        *num = (*num << 8) | get_byte(pb);
669

    
670
    return 0;
671
}
672

    
673
/*
674
 * Read the next element as a float.
675
 * 0 is success, < 0 is failure.
676
 */
677
static int
678
ebml_read_float (MatroskaDemuxContext *matroska,
679
                 uint32_t             *id,
680
                 double               *num)
681
{
682
    ByteIOContext *pb = matroska->ctx->pb;
683
    int size, res;
684
    uint64_t rlength;
685

    
686
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
687
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
688
        return res;
689
    size = rlength;
690

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

    
703
    return 0;
704
}
705

    
706
/*
707
 * Read the next element as an ASCII string.
708
 * 0 is success, < 0 is failure.
709
 */
710
static int
711
ebml_read_ascii (MatroskaDemuxContext *matroska,
712
                 uint32_t             *id,
713
                 char                **str)
714
{
715
    ByteIOContext *pb = matroska->ctx->pb;
716
    int size, res;
717
    uint64_t rlength;
718

    
719
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
720
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
721
        return res;
722
    size = rlength;
723

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

    
739
    return 0;
740
}
741

    
742
/*
743
 * Read the next element, but only the header. The contents
744
 * are supposed to be sub-elements which can be read separately.
745
 * 0 is success, < 0 is failure.
746
 */
747
static int
748
ebml_read_master (MatroskaDemuxContext *matroska,
749
                  uint32_t             *id)
750
{
751
    ByteIOContext *pb = matroska->ctx->pb;
752
    uint64_t length;
753
    MatroskaLevel *level;
754
    int res;
755

    
756
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
757
        (res = ebml_read_element_length(matroska, &length)) < 0)
758
        return res;
759

    
760
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
761
        av_log(matroska->ctx, AV_LOG_ERROR,
762
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
763
        return AVERROR(ENOSYS);
764
    }
765

    
766
    level = &matroska->levels[matroska->num_levels++];
767
    level->start = url_ftell(pb);
768
    level->length = length;
769

    
770
    return 0;
771
}
772

    
773
/*
774
 * Read the next element as binary data.
775
 * 0 is success, < 0 is failure.
776
 */
777
static int
778
ebml_read_binary (MatroskaDemuxContext *matroska,
779
                  uint32_t             *id,
780
                  uint8_t             **binary,
781
                  int                  *size)
782
{
783
    ByteIOContext *pb = matroska->ctx->pb;
784
    uint64_t rlength;
785
    int res;
786

    
787
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
788
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
789
        return res;
790
    *size = rlength;
791

    
792
    if (!(*binary = av_malloc(*size))) {
793
        av_log(matroska->ctx, AV_LOG_ERROR,
794
               "Memory allocation error\n");
795
        return AVERROR(ENOMEM);
796
    }
797

    
798
    if (get_buffer(pb, *binary, *size) != *size) {
799
        offset_t pos = url_ftell(pb);
800
        av_log(matroska->ctx, AV_LOG_ERROR,
801
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
802
        return AVERROR(EIO);
803
    }
804

    
805
    return 0;
806
}
807

    
808
/*
809
 * Read signed/unsigned "EBML" numbers.
810
 * Return: number of bytes processed, < 0 on error.
811
 * XXX: use ebml_read_num().
812
 */
813
static int
814
matroska_ebmlnum_uint (uint8_t  *data,
815
                       uint32_t  size,
816
                       uint64_t *num)
817
{
818
    int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
819
    uint64_t total;
820

    
821
    if (size <= 0)
822
        return AVERROR_INVALIDDATA;
823

    
824
    total = data[0];
825
    while (read <= 8 && !(total & len_mask)) {
826
        read++;
827
        len_mask >>= 1;
828
    }
829
    if (read > 8)
830
        return AVERROR_INVALIDDATA;
831

    
832
    if ((total &= (len_mask - 1)) == len_mask - 1)
833
        num_ffs++;
834
    if (size < read)
835
        return AVERROR_INVALIDDATA;
836
    while (n < read) {
837
        if (data[n] == 0xff)
838
            num_ffs++;
839
        total = (total << 8) | data[n];
840
        n++;
841
    }
842

    
843
    if (read == num_ffs)
844
        *num = (uint64_t)-1;
845
    else
846
        *num = total;
847

    
848
    return read;
849
}
850

    
851
/*
852
 * Same as above, but signed.
853
 */
854
static int
855
matroska_ebmlnum_sint (uint8_t  *data,
856
                       uint32_t  size,
857
                       int64_t  *num)
858
{
859
    uint64_t unum;
860
    int res;
861

    
862
    /* read as unsigned number first */
863
    if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
864
        return res;
865

    
866
    /* make signed (weird way) */
867
    if (unum == (uint64_t)-1)
868
        *num = INT64_MAX;
869
    else
870
        *num = unum - ((1LL << ((7 * res) - 1)) - 1);
871

    
872
    return res;
873
}
874

    
875

    
876
static MatroskaTrack *
877
matroska_find_track_by_num (MatroskaDemuxContext *matroska,
878
                            int                   num)
879
{
880
    MatroskaTrack *tracks = matroska->tracks.elem;
881
    int i;
882

    
883
    for (i=0; i < matroska->tracks.nb_elem; i++)
884
        if (tracks[i].num == num)
885
            return &tracks[i];
886

    
887
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
888
    return NULL;
889
}
890

    
891

    
892
/*
893
 * Put one packet in an application-supplied AVPacket struct.
894
 * Returns 0 on success or -1 on failure.
895
 */
896
static int
897
matroska_deliver_packet (MatroskaDemuxContext *matroska,
898
                         AVPacket             *pkt)
899
{
900
    if (matroska->num_packets > 0) {
901
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
902
        av_free(matroska->packets[0]);
903
        if (matroska->num_packets > 1) {
904
            memmove(&matroska->packets[0], &matroska->packets[1],
905
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
906
            matroska->packets =
907
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
908
                           sizeof(AVPacket *));
909
        } else {
910
            av_freep(&matroska->packets);
911
        }
912
        matroska->num_packets--;
913
        return 0;
914
    }
915

    
916
    return -1;
917
}
918

    
919
/*
920
 * Put a packet into our internal queue. Will be delivered to the
921
 * user/application during the next get_packet() call.
922
 */
923
static void
924
matroska_queue_packet (MatroskaDemuxContext *matroska,
925
                       AVPacket             *pkt)
926
{
927
    matroska->packets =
928
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
929
                   sizeof(AVPacket *));
930
    matroska->packets[matroska->num_packets] = pkt;
931
    matroska->num_packets++;
932
}
933

    
934
/*
935
 * Free all packets in our internal queue.
936
 */
937
static void
938
matroska_clear_queue (MatroskaDemuxContext *matroska)
939
{
940
    if (matroska->packets) {
941
        int n;
942
        for (n = 0; n < matroska->num_packets; n++) {
943
            av_free_packet(matroska->packets[n]);
944
            av_free(matroska->packets[n]);
945
        }
946
        av_free(matroska->packets);
947
        matroska->packets = NULL;
948
        matroska->num_packets = 0;
949
    }
950
}
951

    
952

    
953
/*
954
 * Autodetecting...
955
 */
956
static int
957
matroska_probe (AVProbeData *p)
958
{
959
    uint64_t total = 0;
960
    int len_mask = 0x80, size = 1, n = 1;
961
    uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
962

    
963
    /* ebml header? */
964
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
965
        return 0;
966

    
967
    /* length of header */
968
    total = p->buf[4];
969
    while (size <= 8 && !(total & len_mask)) {
970
        size++;
971
        len_mask >>= 1;
972
    }
973
    if (size > 8)
974
      return 0;
975
    total &= (len_mask - 1);
976
    while (n < size)
977
        total = (total << 8) | p->buf[4 + n++];
978

    
979
    /* does the probe data contain the whole header? */
980
    if (p->buf_size < 4 + size + total)
981
      return 0;
982

    
983
    /* the header must contain the document type 'matroska'. For now,
984
     * we don't parse the whole header but simply check for the
985
     * availability of that array of characters inside the header.
986
     * Not fully fool-proof, but good enough. */
987
    for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
988
        if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
989
            return AVPROBE_SCORE_MAX;
990

    
991
    return 0;
992
}
993

    
994
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
995
                      void *data, uint32_t expected_id, int once);
996

    
997
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
998
                           EbmlSyntax *syntax, void *data)
999
{
1000
    uint32_t id = syntax->id;
1001
    EbmlBin *bin;
1002
    int res;
1003

    
1004
    data = (char *)data + syntax->data_offset;
1005
    if (syntax->list_elem_size) {
1006
        EbmlList *list = data;
1007
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
1008
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
1009
        memset(data, 0, syntax->list_elem_size);
1010
        list->nb_elem++;
1011
    }
1012
    bin = data;
1013

    
1014
    switch (syntax->type) {
1015
    case EBML_UINT:  return ebml_read_uint (matroska, &id, data);
1016
    case EBML_FLOAT: return ebml_read_float(matroska, &id, data);
1017
    case EBML_STR:
1018
    case EBML_UTF8:  av_free(*(char **)data);
1019
                     return ebml_read_ascii(matroska, &id, data);
1020
    case EBML_BIN:   av_free(bin->data);
1021
                     bin->pos = url_ftell(matroska->ctx->pb);
1022
                     return ebml_read_binary(matroska, &id, &bin->data,
1023
                                                            &bin->size);
1024
    case EBML_NEST:  if ((res=ebml_read_master(matroska, &id)) < 0)
1025
                         return res;
1026
                     if (id == MATROSKA_ID_SEGMENT)
1027
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
1028
                     return ebml_parse(matroska, syntax->def.n, data, 0, 0);
1029
    case EBML_PASS:  return ebml_parse(matroska, syntax->def.n, data, 0, 1);
1030
    case EBML_STOP:  *(int *)data = 1;      return 1;
1031
    default:         return ebml_read_skip(matroska);
1032
    }
1033
}
1034

    
1035
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1036
                         uint32_t id, void *data)
1037
{
1038
    int i;
1039
    for (i=0; syntax[i].id; i++)
1040
        if (id == syntax[i].id)
1041
            break;
1042
    if (!syntax[i].id)
1043
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
1044
    return ebml_parse_elem(matroska, &syntax[i], data);
1045
}
1046

    
1047
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1048
                      void *data, uint32_t expected_id, int once)
1049
{
1050
    int i, res = 0;
1051
    uint32_t id = 0;
1052

    
1053
    for (i=0; syntax[i].id; i++)
1054
        switch (syntax[i].type) {
1055
        case EBML_UINT:
1056
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
1057
            break;
1058
        case EBML_FLOAT:
1059
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
1060
            break;
1061
        case EBML_STR:
1062
        case EBML_UTF8:
1063
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
1064
            break;
1065
        }
1066

    
1067
    if (expected_id) {
1068
        res = ebml_read_master(matroska, &id);
1069
        if (id != expected_id)
1070
            return AVERROR_INVALIDDATA;
1071
        if (id == MATROSKA_ID_SEGMENT)
1072
            matroska->segment_start = url_ftell(matroska->ctx->pb);
1073
    }
1074

    
1075
    while (!res) {
1076
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1077
            res = AVERROR(EIO);
1078
            break;
1079
        } else if (matroska->level_up) {
1080
            matroska->level_up--;
1081
            break;
1082
        }
1083

    
1084
        res = ebml_parse_id(matroska, syntax, id, data);
1085
        if (once)
1086
            break;
1087

    
1088
        if (matroska->level_up) {
1089
            matroska->level_up--;
1090
            break;
1091
        }
1092
    }
1093

    
1094
    return res;
1095
}
1096

    
1097
static void ebml_free(EbmlSyntax *syntax, void *data)
1098
{
1099
    int i, j;
1100
    for (i=0; syntax[i].id; i++) {
1101
        void *data_off = (char *)data + syntax[i].data_offset;
1102
        switch (syntax[i].type) {
1103
        case EBML_STR:
1104
        case EBML_UTF8:  av_freep(data_off);                      break;
1105
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
1106
        case EBML_NEST:
1107
            if (syntax[i].list_elem_size) {
1108
                EbmlList *list = data_off;
1109
                char *ptr = list->elem;
1110
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1111
                    ebml_free(syntax[i].def.n, ptr);
1112
                av_free(list->elem);
1113
            } else
1114
                ebml_free(syntax[i].def.n, data_off);
1115
        default:  break;
1116
        }
1117
    }
1118
}
1119

    
1120
static int
1121
matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
1122
{
1123
    MatroskaTrackEncoding *encodings = track->encodings.elem;
1124
    uint8_t* data = *buf;
1125
    int isize = *buf_size;
1126
    uint8_t* pkt_data = NULL;
1127
    int pkt_size = isize;
1128
    int result = 0;
1129
    int olen;
1130

    
1131
    switch (encodings[0].compression.algo) {
1132
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1133
        return encodings[0].compression.settings.size;
1134
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
1135
        do {
1136
            olen = pkt_size *= 3;
1137
            pkt_data = av_realloc(pkt_data,
1138
                                  pkt_size+LZO_OUTPUT_PADDING);
1139
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
1140
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
1141
        if (result)
1142
            goto failed;
1143
        pkt_size -= olen;
1144
        break;
1145
#ifdef CONFIG_ZLIB
1146
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1147
        z_stream zstream = {0};
1148
        if (inflateInit(&zstream) != Z_OK)
1149
            return -1;
1150
        zstream.next_in = data;
1151
        zstream.avail_in = isize;
1152
        do {
1153
            pkt_size *= 3;
1154
            pkt_data = av_realloc(pkt_data, pkt_size);
1155
            zstream.avail_out = pkt_size - zstream.total_out;
1156
            zstream.next_out = pkt_data + zstream.total_out;
1157
            result = inflate(&zstream, Z_NO_FLUSH);
1158
        } while (result==Z_OK && pkt_size<10000000);
1159
        pkt_size = zstream.total_out;
1160
        inflateEnd(&zstream);
1161
        if (result != Z_STREAM_END)
1162
            goto failed;
1163
        break;
1164
    }
1165
#endif
1166
#ifdef CONFIG_BZLIB
1167
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1168
        bz_stream bzstream = {0};
1169
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1170
            return -1;
1171
        bzstream.next_in = data;
1172
        bzstream.avail_in = isize;
1173
        do {
1174
            pkt_size *= 3;
1175
            pkt_data = av_realloc(pkt_data, pkt_size);
1176
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1177
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1178
            result = BZ2_bzDecompress(&bzstream);
1179
        } while (result==BZ_OK && pkt_size<10000000);
1180
        pkt_size = bzstream.total_out_lo32;
1181
        BZ2_bzDecompressEnd(&bzstream);
1182
        if (result != BZ_STREAM_END)
1183
            goto failed;
1184
        break;
1185
    }
1186
#endif
1187
    }
1188

    
1189
    *buf = pkt_data;
1190
    *buf_size = pkt_size;
1191
    return 0;
1192
 failed:
1193
    av_free(pkt_data);
1194
    return -1;
1195
}
1196

    
1197
static void
1198
matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1199
{
1200
    EbmlList *seekhead_list = &matroska->seekhead;
1201
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1202
    uint32_t peek_id_cache = matroska->peek_id;
1203
    uint32_t level_up = matroska->level_up;
1204
    offset_t before_pos = url_ftell(matroska->ctx->pb);
1205
    MatroskaLevel level;
1206
    int i;
1207

    
1208
    for (i=0; i<seekhead_list->nb_elem; i++) {
1209
        if (seekhead[i].pos <= before_pos
1210
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1211
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1212
            continue;
1213

    
1214
        /* seek */
1215
        if (ebml_read_seek(matroska,
1216
                           seekhead[i].pos+matroska->segment_start) < 0)
1217
            continue;
1218

    
1219
        /* we don't want to lose our seekhead level, so we add
1220
         * a dummy. This is a crude hack. */
1221
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1222
            av_log(matroska->ctx, AV_LOG_INFO,
1223
                   "Max EBML element depth (%d) reached, "
1224
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1225
            break;
1226
        }
1227

    
1228
        level.start = 0;
1229
        level.length = (uint64_t)-1;
1230
        matroska->levels[matroska->num_levels] = level;
1231
        matroska->num_levels++;
1232

    
1233
        ebml_parse_id(matroska, matroska_segment, seekhead[i].id, matroska);
1234

    
1235
        /* remove dummy level */
1236
        while (matroska->num_levels) {
1237
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1238
            if (length == (uint64_t)-1)
1239
                break;
1240
        }
1241
    }
1242

    
1243
    /* seek back */
1244
    ebml_read_seek(matroska, before_pos);
1245
    matroska->peek_id = peek_id_cache;
1246
    matroska->level_up = level_up;
1247
}
1248

    
1249
static int
1250
matroska_aac_profile (char *codec_id)
1251
{
1252
    static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
1253
    int profile;
1254

    
1255
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1256
        if (strstr(codec_id, aac_profiles[profile]))
1257
            break;
1258
    return profile + 1;
1259
}
1260

    
1261
static int
1262
matroska_aac_sri (int samplerate)
1263
{
1264
    int sri;
1265

    
1266
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1267
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1268
            break;
1269
    return sri;
1270
}
1271

    
1272
static int
1273
matroska_read_header (AVFormatContext    *s,
1274
                      AVFormatParameters *ap)
1275
{
1276
    MatroskaDemuxContext *matroska = s->priv_data;
1277
    EbmlList *attachements_list = &matroska->attachments;
1278
    MatroskaAttachement *attachements;
1279
    EbmlList *chapters_list = &matroska->chapters;
1280
    MatroskaChapter *chapters;
1281
    MatroskaTrack *tracks;
1282
    EbmlList *index_list;
1283
    MatroskaIndex *index;
1284
    Ebml ebml = { 0 };
1285
    AVStream *st;
1286
    int i, j;
1287

    
1288
    matroska->ctx = s;
1289

    
1290
    /* First read the EBML header. */
1291
    if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
1292
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1293
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1294
        || ebml.doctype_version > 2) {
1295
        av_log(matroska->ctx, AV_LOG_ERROR,
1296
               "EBML header using unsupported features\n"
1297
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1298
               ebml.version, ebml.doctype, ebml.doctype_version);
1299
        return AVERROR_NOFMT;
1300
    }
1301
    ebml_free(ebml_syntax, &ebml);
1302

    
1303
    /* The next thing is a segment. */
1304
    if (ebml_parse(matroska, matroska_segments, matroska, 0, 1) < 0)
1305
        return -1;
1306
    matroska_execute_seekhead(matroska);
1307

    
1308
    if (matroska->duration)
1309
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1310
                                  * 1000 / AV_TIME_BASE;
1311
    if (matroska->title)
1312
        strncpy(matroska->ctx->title, matroska->title,
1313
                sizeof(matroska->ctx->title)-1);
1314

    
1315
    tracks = matroska->tracks.elem;
1316
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1317
        MatroskaTrack *track = &tracks[i];
1318
        enum CodecID codec_id = CODEC_ID_NONE;
1319
        EbmlList *encodings_list = &tracks->encodings;
1320
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1321
        uint8_t *extradata = NULL;
1322
        int extradata_size = 0;
1323
        int extradata_offset = 0;
1324

    
1325
        /* Apply some sanity checks. */
1326
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1327
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1328
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1329
            av_log(matroska->ctx, AV_LOG_INFO,
1330
                   "Unknown or unsupported track type %"PRIu64"\n",
1331
                   track->type);
1332
            continue;
1333
        }
1334
        if (track->codec_id == NULL)
1335
            continue;
1336

    
1337
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1338
            if (!track->default_duration)
1339
                track->default_duration = 1000000000/track->video.frame_rate;
1340
            if (!track->video.display_width)
1341
                track->video.display_width = track->video.pixel_width;
1342
            if (!track->video.display_height)
1343
                track->video.display_height = track->video.pixel_height;
1344
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1345
            if (!track->audio.out_samplerate)
1346
                track->audio.out_samplerate = track->audio.samplerate;
1347
        }
1348
        if (encodings_list->nb_elem > 1) {
1349
            av_log(matroska->ctx, AV_LOG_ERROR,
1350
                   "Multiple combined encodings no supported");
1351
        } else if (encodings_list->nb_elem == 1) {
1352
            if (encodings[0].type ||
1353
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1354
#ifdef CONFIG_ZLIB
1355
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1356
#endif
1357
#ifdef CONFIG_BZLIB
1358
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1359
#endif
1360
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1361
                encodings[0].scope = 0;
1362
                av_log(matroska->ctx, AV_LOG_ERROR,
1363
                       "Unsupported encoding type");
1364
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1365
                uint8_t *codec_priv = track->codec_priv.data;
1366
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1367
                                                    &track->codec_priv.size,
1368
                                                    track);
1369
                if (offset < 0) {
1370
                    track->codec_priv.data = NULL;
1371
                    track->codec_priv.size = 0;
1372
                    av_log(matroska->ctx, AV_LOG_ERROR,
1373
                           "Failed to decode codec private data\n");
1374
                } else if (offset > 0) {
1375
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1376
                    memcpy(track->codec_priv.data,
1377
                           encodings[0].compression.settings.data, offset);
1378
                    memcpy(track->codec_priv.data+offset, codec_priv,
1379
                           track->codec_priv.size);
1380
                    track->codec_priv.size += offset;
1381
                }
1382
                if (codec_priv != track->codec_priv.data)
1383
                    av_free(codec_priv);
1384
            }
1385
        }
1386

    
1387
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1388
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1389
                        strlen(ff_mkv_codec_tags[j].str))){
1390
                codec_id= ff_mkv_codec_tags[j].id;
1391
                break;
1392
            }
1393
        }
1394

    
1395
        st = track->stream = av_new_stream(s, matroska->num_streams++);
1396
        if (st == NULL)
1397
            return AVERROR(ENOMEM);
1398

    
1399
        if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)
1400
            && track->codec_priv.size >= 40
1401
            && track->codec_priv.data != NULL) {
1402
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1403
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1404
        } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_AUDIO_ACM)
1405
                   && track->codec_priv.size >= 18
1406
                   && track->codec_priv.data != NULL) {
1407
            uint16_t tag = AV_RL16(track->codec_priv.data);
1408
            codec_id = codec_get_id(codec_wav_tags, tag);
1409
        } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1410
                   && (track->codec_priv.size >= 86)
1411
                   && (track->codec_priv.data != NULL)) {
1412
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1413
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1414
        } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1415
            int profile = matroska_aac_profile(track->codec_id);
1416
            int sri = matroska_aac_sri(track->audio.samplerate);
1417
            extradata = av_malloc(5);
1418
            if (extradata == NULL)
1419
                return AVERROR(ENOMEM);
1420
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1421
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1422
            if (strstr(track->codec_id, "SBR")) {
1423
                sri = matroska_aac_sri(track->audio.out_samplerate);
1424
                extradata[2] = 0x56;
1425
                extradata[3] = 0xE5;
1426
                extradata[4] = 0x80 | (sri<<3);
1427
                extradata_size = 5;
1428
            } else
1429
                extradata_size = 2;
1430
        } else if (codec_id == CODEC_ID_TTA) {
1431
            ByteIOContext b;
1432
            extradata_size = 30;
1433
            extradata = av_mallocz(extradata_size);
1434
            if (extradata == NULL)
1435
                return AVERROR(ENOMEM);
1436
            init_put_byte(&b, extradata, extradata_size, 1,
1437
                          NULL, NULL, NULL, NULL);
1438
            put_buffer(&b, "TTA1", 4);
1439
            put_le16(&b, 1);
1440
            put_le16(&b, track->audio.channels);
1441
            put_le16(&b, track->audio.bitdepth);
1442
            put_le32(&b, track->audio.out_samplerate);
1443
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1444
        } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1445
                   codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1446
            extradata_offset = 26;
1447
            track->codec_priv.size -= extradata_offset;
1448
        } else if (codec_id == CODEC_ID_RA_144) {
1449
            track->audio.out_samplerate = 8000;
1450
            track->audio.channels = 1;
1451
        } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1452
                   codec_id == CODEC_ID_ATRAC3) {
1453
            ByteIOContext b;
1454

    
1455
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1456
                          0, NULL, NULL, NULL, NULL);
1457
            url_fskip(&b, 24);
1458
            track->audio.coded_framesize = get_be32(&b);
1459
            url_fskip(&b, 12);
1460
            track->audio.sub_packet_h    = get_be16(&b);
1461
            track->audio.frame_size      = get_be16(&b);
1462
            track->audio.sub_packet_size = get_be16(&b);
1463
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1464
            if (codec_id == CODEC_ID_RA_288) {
1465
                st->codec->block_align = track->audio.coded_framesize;
1466
                track->codec_priv.size = 0;
1467
            } else {
1468
                st->codec->block_align = track->audio.sub_packet_size;
1469
                extradata_offset = 78;
1470
                track->codec_priv.size -= extradata_offset;
1471
            }
1472
        }
1473

    
1474
        if (codec_id == CODEC_ID_NONE)
1475
            av_log(matroska->ctx, AV_LOG_INFO,
1476
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1477

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

    
1480
        st->codec->codec_id = codec_id;
1481
        st->start_time = 0;
1482
        if (strcmp(track->language, "und"))
1483
            av_strlcpy(st->language, track->language, 4);
1484

    
1485
        if (track->flag_default)
1486
            st->disposition |= AV_DISPOSITION_DEFAULT;
1487

    
1488
        if (track->default_duration)
1489
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1490
                      track->default_duration, 1000000000, 30000);
1491

    
1492
        if(extradata){
1493
            st->codec->extradata = extradata;
1494
            st->codec->extradata_size = extradata_size;
1495
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1496
            st->codec->extradata = av_malloc(track->codec_priv.size);
1497
            if(st->codec->extradata == NULL)
1498
                return AVERROR(ENOMEM);
1499
            st->codec->extradata_size = track->codec_priv.size;
1500
            memcpy(st->codec->extradata,
1501
                   track->codec_priv.data + extradata_offset,
1502
                   track->codec_priv.size);
1503
        }
1504

    
1505
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1506
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1507
            st->codec->codec_tag  = track->video.fourcc;
1508
            st->codec->width  = track->video.pixel_width;
1509
            st->codec->height = track->video.pixel_height;
1510
            av_reduce(&st->codec->sample_aspect_ratio.num,
1511
                      &st->codec->sample_aspect_ratio.den,
1512
                      st->codec->height * track->video.display_width,
1513
                      st->codec-> width * track->video.display_height,
1514
                      255);
1515
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1516
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1517
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1518
            st->codec->sample_rate = track->audio.out_samplerate;
1519
            st->codec->channels = track->audio.channels;
1520
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1521
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1522
        }
1523
    }
1524

    
1525
    attachements = attachements_list->elem;
1526
    for (j=0; j<attachements_list->nb_elem; j++) {
1527
        if (!(attachements[j].filename && attachements[j].mime &&
1528
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1529
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1530
        } else {
1531
            AVStream *st = av_new_stream(s, matroska->num_streams++);
1532
            if (st == NULL)
1533
                break;
1534
            st->filename          = av_strdup(attachements[j].filename);
1535
            st->codec->codec_id = CODEC_ID_NONE;
1536
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1537
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1538
            if(st->codec->extradata == NULL)
1539
                break;
1540
            st->codec->extradata_size = attachements[j].bin.size;
1541
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1542

    
1543
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1544
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1545
                             strlen(ff_mkv_mime_tags[i].str))) {
1546
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1547
                    break;
1548
                }
1549
            }
1550
        }
1551
    }
1552

    
1553
    chapters = chapters_list->elem;
1554
    for (i=0; i<chapters_list->nb_elem; i++)
1555
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1556
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1557
                           chapters[i].start, chapters[i].end,
1558
                           chapters[i].title);
1559

    
1560
    index_list = &matroska->index;
1561
    index = index_list->elem;
1562
    for (i=0; i<index_list->nb_elem; i++) {
1563
        EbmlList *pos_list = &index[i].pos;
1564
        MatroskaIndexPos *pos = pos_list->elem;
1565
        for (j=0; j<pos_list->nb_elem; j++) {
1566
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1567
                                                              pos[j].track);
1568
            if (track && track->stream)
1569
                av_add_index_entry(track->stream,
1570
                                   pos[j].pos + matroska->segment_start,
1571
                                   index[i].time*matroska->time_scale/AV_TIME_BASE,
1572
                                   0, 0, AVINDEX_KEYFRAME);
1573
        }
1574
    }
1575

    
1576
    return 0;
1577
}
1578

    
1579
static int
1580
matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
1581
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
1582
                     int is_keyframe)
1583
{
1584
    MatroskaTrack *track;
1585
    int res = 0;
1586
    AVStream *st;
1587
    AVPacket *pkt;
1588
    int16_t block_time;
1589
    uint32_t *lace_size = NULL;
1590
    int n, flags, laces = 0;
1591
    uint64_t num;
1592

    
1593
    if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1594
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1595
        return res;
1596
    }
1597
    data += n;
1598
    size -= n;
1599

    
1600
    track = matroska_find_track_by_num(matroska, num);
1601
    if (size <= 3 || !track || !track->stream) {
1602
        av_log(matroska->ctx, AV_LOG_INFO,
1603
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1604
        return res;
1605
    }
1606
    st = track->stream;
1607
    if (st->discard >= AVDISCARD_ALL)
1608
        return res;
1609
    if (duration == AV_NOPTS_VALUE)
1610
        duration = track->default_duration / matroska->time_scale;
1611

    
1612
    block_time = AV_RB16(data);
1613
    data += 2;
1614
    flags = *data++;
1615
    size -= 3;
1616
    if (is_keyframe == -1)
1617
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1618

    
1619
    if (matroska->skip_to_keyframe) {
1620
        if (!is_keyframe || st != matroska->skip_to_stream)
1621
            return res;
1622
        matroska->skip_to_keyframe = 0;
1623
    }
1624

    
1625
    switch ((flags & 0x06) >> 1) {
1626
        case 0x0: /* no lacing */
1627
            laces = 1;
1628
            lace_size = av_mallocz(sizeof(int));
1629
            lace_size[0] = size;
1630
            break;
1631

    
1632
        case 0x1: /* xiph lacing */
1633
        case 0x2: /* fixed-size lacing */
1634
        case 0x3: /* EBML lacing */
1635
            assert(size>0); // size <=3 is checked before size-=3 above
1636
            laces = (*data) + 1;
1637
            data += 1;
1638
            size -= 1;
1639
            lace_size = av_mallocz(laces * sizeof(int));
1640

    
1641
            switch ((flags & 0x06) >> 1) {
1642
                case 0x1: /* xiph lacing */ {
1643
                    uint8_t temp;
1644
                    uint32_t total = 0;
1645
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1646
                        while (1) {
1647
                            if (size == 0) {
1648
                                res = -1;
1649
                                break;
1650
                            }
1651
                            temp = *data;
1652
                            lace_size[n] += temp;
1653
                            data += 1;
1654
                            size -= 1;
1655
                            if (temp != 0xff)
1656
                                break;
1657
                        }
1658
                        total += lace_size[n];
1659
                    }
1660
                    lace_size[n] = size - total;
1661
                    break;
1662
                }
1663

    
1664
                case 0x2: /* fixed-size lacing */
1665
                    for (n = 0; n < laces; n++)
1666
                        lace_size[n] = size / laces;
1667
                    break;
1668

    
1669
                case 0x3: /* EBML lacing */ {
1670
                    uint32_t total;
1671
                    n = matroska_ebmlnum_uint(data, size, &num);
1672
                    if (n < 0) {
1673
                        av_log(matroska->ctx, AV_LOG_INFO,
1674
                               "EBML block data error\n");
1675
                        break;
1676
                    }
1677
                    data += n;
1678
                    size -= n;
1679
                    total = lace_size[0] = num;
1680
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1681
                        int64_t snum;
1682
                        int r;
1683
                        r = matroska_ebmlnum_sint (data, size, &snum);
1684
                        if (r < 0) {
1685
                            av_log(matroska->ctx, AV_LOG_INFO,
1686
                                   "EBML block data error\n");
1687
                            break;
1688
                        }
1689
                        data += r;
1690
                        size -= r;
1691
                        lace_size[n] = lace_size[n - 1] + snum;
1692
                        total += lace_size[n];
1693
                    }
1694
                    lace_size[n] = size - total;
1695
                    break;
1696
                }
1697
            }
1698
            break;
1699
    }
1700

    
1701
    if (res == 0) {
1702
        uint64_t timecode = AV_NOPTS_VALUE;
1703

    
1704
        if (cluster_time != (uint64_t)-1
1705
            && (block_time >= 0 || cluster_time >= -block_time))
1706
            timecode = cluster_time + block_time;
1707

    
1708
        for (n = 0; n < laces; n++) {
1709
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1710
                st->codec->codec_id == CODEC_ID_COOK ||
1711
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1712
                int a = st->codec->block_align;
1713
                int sps = track->audio.sub_packet_size;
1714
                int cfs = track->audio.coded_framesize;
1715
                int h = track->audio.sub_packet_h;
1716
                int y = track->audio.sub_packet_cnt;
1717
                int w = track->audio.frame_size;
1718
                int x;
1719

    
1720
                if (!track->audio.pkt_cnt) {
1721
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1722
                        for (x=0; x<h/2; x++)
1723
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1724
                                   data+x*cfs, cfs);
1725
                    else
1726
                        for (x=0; x<w/sps; x++)
1727
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1728

    
1729
                    if (++track->audio.sub_packet_cnt >= h) {
1730
                        track->audio.sub_packet_cnt = 0;
1731
                        track->audio.pkt_cnt = h*w / a;
1732
                    }
1733
                }
1734
                while (track->audio.pkt_cnt) {
1735
                    pkt = av_mallocz(sizeof(AVPacket));
1736
                    av_new_packet(pkt, a);
1737
                    memcpy(pkt->data, track->audio.buf
1738
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1739
                    pkt->pos = pos;
1740
                    pkt->stream_index = st->index;
1741
                    matroska_queue_packet(matroska, pkt);
1742
                }
1743
            } else {
1744
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1745
                int offset = 0, pkt_size = lace_size[n];
1746
                uint8_t *pkt_data = data;
1747

    
1748
                if (encodings && encodings->scope & 1) {
1749
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1750
                    if (offset < 0)
1751
                        continue;
1752
                }
1753

    
1754
                pkt = av_mallocz(sizeof(AVPacket));
1755
                /* XXX: prevent data copy... */
1756
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1757
                    av_free(pkt);
1758
                    res = AVERROR(ENOMEM);
1759
                    n = laces-1;
1760
                    break;
1761
                }
1762
                if (offset)
1763
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1764
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1765

    
1766
                if (pkt_data != data)
1767
                    av_free(pkt_data);
1768

    
1769
                if (n == 0)
1770
                    pkt->flags = is_keyframe;
1771
                pkt->stream_index = st->index;
1772

    
1773
                pkt->pts = timecode;
1774
                pkt->pos = pos;
1775
                pkt->duration = duration;
1776

    
1777
                matroska_queue_packet(matroska, pkt);
1778
            }
1779

    
1780
            if (timecode != AV_NOPTS_VALUE)
1781
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1782
            data += lace_size[n];
1783
        }
1784
    }
1785

    
1786
    av_free(lace_size);
1787
    return res;
1788
}
1789

    
1790
static int
1791
matroska_parse_cluster (MatroskaDemuxContext *matroska)
1792
{
1793
    MatroskaCluster cluster = { 0 };
1794
    EbmlList *blocks_list;
1795
    MatroskaBlock *blocks;
1796
    int i, res = ebml_parse(matroska, matroska_clusters, &cluster, 0, 1);
1797
    blocks_list = &cluster.blocks;
1798
    blocks = blocks_list->elem;
1799
    for (i=0; !res && i<blocks_list->nb_elem; i++)
1800
        if (blocks[i].bin.size > 0)
1801
            res=matroska_parse_block(matroska,
1802
                                     blocks[i].bin.data, blocks[i].bin.size,
1803
                                     blocks[i].bin.pos,  cluster.timecode,
1804
                                     blocks[i].duration, !blocks[i].reference);
1805
    ebml_free(matroska_cluster, &cluster);
1806
    return res;
1807
}
1808

    
1809
static int
1810
matroska_read_packet (AVFormatContext *s,
1811
                      AVPacket        *pkt)
1812
{
1813
    MatroskaDemuxContext *matroska = s->priv_data;
1814

    
1815
    while (matroska_deliver_packet(matroska, pkt)) {
1816
        if (matroska->done)
1817
            return AVERROR(EIO);
1818
        if (matroska_parse_cluster(matroska) < 0)
1819
            matroska->done = 1;
1820
    }
1821

    
1822
    return 0;
1823
}
1824

    
1825
static int
1826
matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
1827
                    int flags)
1828
{
1829
    MatroskaDemuxContext *matroska = s->priv_data;
1830
    AVStream *st = s->streams[stream_index];
1831
    int index;
1832

    
1833
    index = av_index_search_timestamp(st, timestamp, flags);
1834
    if (index < 0)
1835
        return 0;
1836

    
1837
    matroska_clear_queue(matroska);
1838

    
1839
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1840
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1841
    matroska->skip_to_stream = st;
1842
    matroska->peek_id = 0;
1843
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1844
    return 0;
1845
}
1846

    
1847
static int
1848
matroska_read_close (AVFormatContext *s)
1849
{
1850
    MatroskaDemuxContext *matroska = s->priv_data;
1851
    MatroskaTrack *tracks = matroska->tracks.elem;
1852
    int n;
1853

    
1854
    matroska_clear_queue(matroska);
1855

    
1856
    for (n=0; n < matroska->tracks.nb_elem; n++)
1857
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1858
            av_free(tracks[n].audio.buf);
1859
    ebml_free(matroska_segment, matroska);
1860

    
1861
    return 0;
1862
}
1863

    
1864
AVInputFormat matroska_demuxer = {
1865
    "matroska",
1866
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1867
    sizeof(MatroskaDemuxContext),
1868
    matroska_probe,
1869
    matroska_read_header,
1870
    matroska_read_packet,
1871
    matroska_read_close,
1872
    matroska_read_seek,
1873
};