Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ dfde36a3

History | View | Annotate | Download (61.5 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
        *id = matroska->peek_id;
554
        return 0;
555
    }
556

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

    
562
    /* level tracking */
563
    if (level_up)
564
        *level_up = ebml_read_element_level_up(matroska);
565

    
566
    return read;
567
}
568

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

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

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

    
595
    if (ebml_read_element_id(matroska, &id, level_up) < 0)
596
        return 0;
597

    
598
    return id;
599
}
600

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

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

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

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

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

    
633
    url_fskip(pb, length);
634

    
635
    return 0;
636
}
637

    
638
/*
639
 * Read the next element as an unsigned int.
640
 * 0 is success, < 0 is failure.
641
 */
642
static int
643
ebml_read_uint (MatroskaDemuxContext *matroska,
644
                uint32_t             *id,
645
                uint64_t             *num)
646
{
647
    ByteIOContext *pb = matroska->ctx->pb;
648
    int n = 0, size, res;
649
    uint64_t rlength;
650

    
651
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
652
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
653
        return res;
654
    size = rlength;
655
    if (size < 1 || size > 8) {
656
        offset_t pos = url_ftell(pb);
657
        av_log(matroska->ctx, AV_LOG_ERROR,
658
               "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
659
                size, pos, pos);
660
        return AVERROR_INVALIDDATA;
661
    }
662

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

    
668
    return 0;
669
}
670

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

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

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

    
701
    return 0;
702
}
703

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

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

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

    
737
    return 0;
738
}
739

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

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

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

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

    
768
    return 0;
769
}
770

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

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

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

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

    
803
    return 0;
804
}
805

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

    
819
    if (size <= 0)
820
        return AVERROR_INVALIDDATA;
821

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

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

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

    
846
    return read;
847
}
848

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

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

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

    
870
    return res;
871
}
872

    
873

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

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

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

    
889

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

    
914
    return -1;
915
}
916

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

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

    
950

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

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

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

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

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

    
989
    return 0;
990
}
991

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

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

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

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

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

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

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

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

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

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

    
1087
    return res;
1088
}
1089

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

    
1113
static int
1114
matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
1115
{
1116
    MatroskaTrackEncoding *encodings = track->encodings.elem;
1117
    uint8_t* data = *buf;
1118
    int isize = *buf_size;
1119
    uint8_t* pkt_data = NULL;
1120
    int pkt_size = isize;
1121
    int result = 0;
1122
    int olen;
1123

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

    
1182
    *buf = pkt_data;
1183
    *buf_size = pkt_size;
1184
    return 0;
1185
 failed:
1186
    av_free(pkt_data);
1187
    return -1;
1188
}
1189

    
1190
static void
1191
matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1192
{
1193
    EbmlList *seekhead_list = &matroska->seekhead;
1194
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1195
    uint32_t peek_id_cache = matroska->peek_id;
1196
    uint32_t level_up = matroska->level_up;
1197
    offset_t before_pos = url_ftell(matroska->ctx->pb);
1198
    MatroskaLevel level;
1199
    int i;
1200

    
1201
    for (i=0; i<seekhead_list->nb_elem; i++) {
1202
        if (seekhead[i].pos <= before_pos
1203
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1204
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1205
            continue;
1206

    
1207
        /* seek */
1208
        if (ebml_read_seek(matroska,
1209
                           seekhead[i].pos+matroska->segment_start) < 0)
1210
            continue;
1211

    
1212
        /* we don't want to lose our seekhead level, so we add
1213
         * a dummy. This is a crude hack. */
1214
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1215
            av_log(matroska->ctx, AV_LOG_INFO,
1216
                   "Max EBML element depth (%d) reached, "
1217
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1218
            break;
1219
        }
1220

    
1221
        level.start = 0;
1222
        level.length = (uint64_t)-1;
1223
        matroska->levels[matroska->num_levels] = level;
1224
        matroska->num_levels++;
1225

    
1226
        ebml_parse_id(matroska, matroska_segment, seekhead[i].id, matroska);
1227

    
1228
        /* remove dummy level */
1229
        while (matroska->num_levels) {
1230
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1231
            if (length == (uint64_t)-1)
1232
                break;
1233
        }
1234
    }
1235

    
1236
    /* seek back */
1237
    ebml_read_seek(matroska, before_pos);
1238
    matroska->peek_id = peek_id_cache;
1239
    matroska->level_up = level_up;
1240
}
1241

    
1242
static int
1243
matroska_aac_profile (char *codec_id)
1244
{
1245
    static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
1246
    int profile;
1247

    
1248
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1249
        if (strstr(codec_id, aac_profiles[profile]))
1250
            break;
1251
    return profile + 1;
1252
}
1253

    
1254
static int
1255
matroska_aac_sri (int samplerate)
1256
{
1257
    int sri;
1258

    
1259
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1260
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1261
            break;
1262
    return sri;
1263
}
1264

    
1265
static int
1266
matroska_read_header (AVFormatContext    *s,
1267
                      AVFormatParameters *ap)
1268
{
1269
    MatroskaDemuxContext *matroska = s->priv_data;
1270
    EbmlList *attachements_list = &matroska->attachments;
1271
    MatroskaAttachement *attachements;
1272
    EbmlList *chapters_list = &matroska->chapters;
1273
    MatroskaChapter *chapters;
1274
    MatroskaTrack *tracks;
1275
    EbmlList *index_list;
1276
    MatroskaIndex *index;
1277
    Ebml ebml = { 0 };
1278
    AVStream *st;
1279
    int i, j;
1280

    
1281
    matroska->ctx = s;
1282

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

    
1296
    /* The next thing is a segment. */
1297
    if (ebml_parse(matroska, matroska_segments, matroska, 0, 1) < 0)
1298
        return -1;
1299
    matroska_execute_seekhead(matroska);
1300

    
1301
    if (matroska->duration)
1302
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1303
                                  * 1000 / AV_TIME_BASE;
1304
    if (matroska->title)
1305
        strncpy(matroska->ctx->title, matroska->title,
1306
                sizeof(matroska->ctx->title)-1);
1307

    
1308
    tracks = matroska->tracks.elem;
1309
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1310
        MatroskaTrack *track = &tracks[i];
1311
        enum CodecID codec_id = CODEC_ID_NONE;
1312
        EbmlList *encodings_list = &tracks->encodings;
1313
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1314
        uint8_t *extradata = NULL;
1315
        int extradata_size = 0;
1316
        int extradata_offset = 0;
1317

    
1318
        /* Apply some sanity checks. */
1319
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1320
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1321
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1322
            av_log(matroska->ctx, AV_LOG_INFO,
1323
                   "Unknown or unsupported track type %"PRIu64"\n",
1324
                   track->type);
1325
            continue;
1326
        }
1327
        if (track->codec_id == NULL)
1328
            continue;
1329

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

    
1380
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1381
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1382
                        strlen(ff_mkv_codec_tags[j].str))){
1383
                codec_id= ff_mkv_codec_tags[j].id;
1384
                break;
1385
            }
1386
        }
1387

    
1388
        st = track->stream = av_new_stream(s, matroska->num_streams++);
1389
        if (st == NULL)
1390
            return AVERROR(ENOMEM);
1391

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

    
1448
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1449
                          0, NULL, NULL, NULL, NULL);
1450
            url_fskip(&b, 24);
1451
            track->audio.coded_framesize = get_be32(&b);
1452
            url_fskip(&b, 12);
1453
            track->audio.sub_packet_h    = get_be16(&b);
1454
            track->audio.frame_size      = get_be16(&b);
1455
            track->audio.sub_packet_size = get_be16(&b);
1456
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1457
            if (codec_id == CODEC_ID_RA_288) {
1458
                st->codec->block_align = track->audio.coded_framesize;
1459
                track->codec_priv.size = 0;
1460
            } else {
1461
                st->codec->block_align = track->audio.sub_packet_size;
1462
                extradata_offset = 78;
1463
                track->codec_priv.size -= extradata_offset;
1464
            }
1465
        }
1466

    
1467
        if (codec_id == CODEC_ID_NONE)
1468
            av_log(matroska->ctx, AV_LOG_INFO,
1469
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1470

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

    
1473
        st->codec->codec_id = codec_id;
1474
        st->start_time = 0;
1475
        if (strcmp(track->language, "und"))
1476
            av_strlcpy(st->language, track->language, 4);
1477

    
1478
        if (track->flag_default)
1479
            st->disposition |= AV_DISPOSITION_DEFAULT;
1480

    
1481
        if (track->default_duration)
1482
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1483
                      track->default_duration, 1000000000, 30000);
1484

    
1485
        if(extradata){
1486
            st->codec->extradata = extradata;
1487
            st->codec->extradata_size = extradata_size;
1488
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1489
            st->codec->extradata = av_malloc(track->codec_priv.size);
1490
            if(st->codec->extradata == NULL)
1491
                return AVERROR(ENOMEM);
1492
            st->codec->extradata_size = track->codec_priv.size;
1493
            memcpy(st->codec->extradata,
1494
                   track->codec_priv.data + extradata_offset,
1495
                   track->codec_priv.size);
1496
        }
1497

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

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

    
1536
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1537
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1538
                             strlen(ff_mkv_mime_tags[i].str))) {
1539
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1540
                    break;
1541
                }
1542
            }
1543
        }
1544
    }
1545

    
1546
    chapters = chapters_list->elem;
1547
    for (i=0; i<chapters_list->nb_elem; i++)
1548
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1549
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1550
                           chapters[i].start, chapters[i].end,
1551
                           chapters[i].title);
1552

    
1553
    index_list = &matroska->index;
1554
    index = index_list->elem;
1555
    for (i=0; i<index_list->nb_elem; i++) {
1556
        EbmlList *pos_list = &index[i].pos;
1557
        MatroskaIndexPos *pos = pos_list->elem;
1558
        for (j=0; j<pos_list->nb_elem; j++) {
1559
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1560
                                                              pos[j].track);
1561
            if (track && track->stream)
1562
                av_add_index_entry(track->stream,
1563
                                   pos[j].pos + matroska->segment_start,
1564
                                   index[i].time*matroska->time_scale/AV_TIME_BASE,
1565
                                   0, 0, AVINDEX_KEYFRAME);
1566
        }
1567
    }
1568

    
1569
    return 0;
1570
}
1571

    
1572
static int
1573
matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
1574
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
1575
                     int is_keyframe)
1576
{
1577
    MatroskaTrack *track;
1578
    int res = 0;
1579
    AVStream *st;
1580
    AVPacket *pkt;
1581
    int16_t block_time;
1582
    uint32_t *lace_size = NULL;
1583
    int n, flags, laces = 0;
1584
    uint64_t num;
1585

    
1586
    if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1587
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1588
        return res;
1589
    }
1590
    data += n;
1591
    size -= n;
1592

    
1593
    track = matroska_find_track_by_num(matroska, num);
1594
    if (size <= 3 || !track || !track->stream) {
1595
        av_log(matroska->ctx, AV_LOG_INFO,
1596
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1597
        return res;
1598
    }
1599
    st = track->stream;
1600
    if (st->discard >= AVDISCARD_ALL)
1601
        return res;
1602
    if (duration == AV_NOPTS_VALUE)
1603
        duration = track->default_duration / matroska->time_scale;
1604

    
1605
    block_time = AV_RB16(data);
1606
    data += 2;
1607
    flags = *data++;
1608
    size -= 3;
1609
    if (is_keyframe == -1)
1610
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1611

    
1612
    if (matroska->skip_to_keyframe) {
1613
        if (!is_keyframe || st != matroska->skip_to_stream)
1614
            return res;
1615
        matroska->skip_to_keyframe = 0;
1616
    }
1617

    
1618
    switch ((flags & 0x06) >> 1) {
1619
        case 0x0: /* no lacing */
1620
            laces = 1;
1621
            lace_size = av_mallocz(sizeof(int));
1622
            lace_size[0] = size;
1623
            break;
1624

    
1625
        case 0x1: /* xiph lacing */
1626
        case 0x2: /* fixed-size lacing */
1627
        case 0x3: /* EBML lacing */
1628
            assert(size>0); // size <=3 is checked before size-=3 above
1629
            laces = (*data) + 1;
1630
            data += 1;
1631
            size -= 1;
1632
            lace_size = av_mallocz(laces * sizeof(int));
1633

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

    
1657
                case 0x2: /* fixed-size lacing */
1658
                    for (n = 0; n < laces; n++)
1659
                        lace_size[n] = size / laces;
1660
                    break;
1661

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

    
1694
    if (res == 0) {
1695
        uint64_t timecode = AV_NOPTS_VALUE;
1696

    
1697
        if (cluster_time != (uint64_t)-1
1698
            && (block_time >= 0 || cluster_time >= -block_time))
1699
            timecode = cluster_time + block_time;
1700

    
1701
        for (n = 0; n < laces; n++) {
1702
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1703
                st->codec->codec_id == CODEC_ID_COOK ||
1704
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1705
                int a = st->codec->block_align;
1706
                int sps = track->audio.sub_packet_size;
1707
                int cfs = track->audio.coded_framesize;
1708
                int h = track->audio.sub_packet_h;
1709
                int y = track->audio.sub_packet_cnt;
1710
                int w = track->audio.frame_size;
1711
                int x;
1712

    
1713
                if (!track->audio.pkt_cnt) {
1714
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1715
                        for (x=0; x<h/2; x++)
1716
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1717
                                   data+x*cfs, cfs);
1718
                    else
1719
                        for (x=0; x<w/sps; x++)
1720
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1721

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

    
1741
                if (encodings && encodings->scope & 1) {
1742
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1743
                    if (offset < 0)
1744
                        continue;
1745
                }
1746

    
1747
                pkt = av_mallocz(sizeof(AVPacket));
1748
                /* XXX: prevent data copy... */
1749
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1750
                    av_free(pkt);
1751
                    res = AVERROR(ENOMEM);
1752
                    n = laces-1;
1753
                    break;
1754
                }
1755
                if (offset)
1756
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1757
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1758

    
1759
                if (pkt_data != data)
1760
                    av_free(pkt_data);
1761

    
1762
                if (n == 0)
1763
                    pkt->flags = is_keyframe;
1764
                pkt->stream_index = st->index;
1765

    
1766
                pkt->pts = timecode;
1767
                pkt->pos = pos;
1768
                pkt->duration = duration;
1769

    
1770
                matroska_queue_packet(matroska, pkt);
1771
            }
1772

    
1773
            if (timecode != AV_NOPTS_VALUE)
1774
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1775
            data += lace_size[n];
1776
        }
1777
    }
1778

    
1779
    av_free(lace_size);
1780
    return res;
1781
}
1782

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

    
1802
static int
1803
matroska_read_packet (AVFormatContext *s,
1804
                      AVPacket        *pkt)
1805
{
1806
    MatroskaDemuxContext *matroska = s->priv_data;
1807

    
1808
    while (matroska_deliver_packet(matroska, pkt)) {
1809
        if (matroska->done)
1810
            return AVERROR(EIO);
1811
        if (matroska_parse_cluster(matroska) < 0)
1812
            matroska->done = 1;
1813
    }
1814

    
1815
    return 0;
1816
}
1817

    
1818
static int
1819
matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
1820
                    int flags)
1821
{
1822
    MatroskaDemuxContext *matroska = s->priv_data;
1823
    AVStream *st = s->streams[stream_index];
1824
    int index;
1825

    
1826
    index = av_index_search_timestamp(st, timestamp, flags);
1827
    if (index < 0)
1828
        return 0;
1829

    
1830
    matroska_clear_queue(matroska);
1831

    
1832
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1833
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1834
    matroska->skip_to_stream = st;
1835
    matroska->peek_id = 0;
1836
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1837
    return 0;
1838
}
1839

    
1840
static int
1841
matroska_read_close (AVFormatContext *s)
1842
{
1843
    MatroskaDemuxContext *matroska = s->priv_data;
1844
    MatroskaTrack *tracks = matroska->tracks.elem;
1845
    int n;
1846

    
1847
    matroska_clear_queue(matroska);
1848

    
1849
    for (n=0; n < matroska->tracks.nb_elem; n++)
1850
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1851
            av_free(tracks[n].audio.buf);
1852
    ebml_free(matroska_segment, matroska);
1853

    
1854
    return 0;
1855
}
1856

    
1857
AVInputFormat matroska_demuxer = {
1858
    "matroska",
1859
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1860
    sizeof(MatroskaDemuxContext),
1861
    matroska_probe,
1862
    matroska_read_header,
1863
    matroska_read_packet,
1864
    matroska_read_close,
1865
    matroska_read_seek,
1866
};