Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 3143f133

History | View | Annotate | Download (63.2 KB)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
140
    AVStream *stream;
141
} MatroskaTrack;
142

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

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

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

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

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

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

    
176
typedef struct MatroskaDemuxContext {
177
    AVFormatContext *ctx;
178

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

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

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

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

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

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

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

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

    
219
typedef struct {
220
    uint64_t duration;
221
    int64_t  reference;
222
    EbmlBin  bin;
223
} MatroskaBlock;
224

    
225
typedef struct {
226
    uint64_t timecode;
227
    EbmlList blocks;
228
} MatroskaCluster;
229

    
230
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
231

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

    
244
static EbmlSyntax ebml_syntax[] = {
245
    { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
246
    { 0 }
247
};
248

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

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

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

    
284
static EbmlSyntax matroska_track_encoding_compression[] = {
285
    { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
286
    { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
287
    { EBML_ID_VOID,                   EBML_NONE },
288
    { 0 }
289
};
290

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

    
299
static EbmlSyntax matroska_track_encodings[] = {
300
    { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
301
    { EBML_ID_VOID,                   EBML_NONE },
302
    { 0 }
303
};
304

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

    
332
static EbmlSyntax matroska_tracks[] = {
333
    { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
334
    { EBML_ID_VOID,                   EBML_NONE },
335
    { 0 }
336
};
337

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

    
347
static EbmlSyntax matroska_attachments[] = {
348
    { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
349
    { EBML_ID_VOID,                   EBML_NONE },
350
    { 0 }
351
};
352

    
353
static EbmlSyntax matroska_chapter_display[] = {
354
    { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
355
    { EBML_ID_VOID,                   EBML_NONE },
356
    { 0 }
357
};
358

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

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

    
378
static EbmlSyntax matroska_chapters[] = {
379
    { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
380
    { EBML_ID_VOID,                   EBML_NONE },
381
    { 0 }
382
};
383

    
384
static EbmlSyntax matroska_index_pos[] = {
385
    { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
386
    { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
387
    { EBML_ID_VOID,                   EBML_NONE },
388
    { 0 }
389
};
390

    
391
static EbmlSyntax matroska_index_entry[] = {
392
    { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
393
    { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
394
    { EBML_ID_VOID,                   EBML_NONE },
395
    { 0 }
396
};
397

    
398
static EbmlSyntax matroska_index[] = {
399
    { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
400
    { EBML_ID_VOID,                   EBML_NONE },
401
    { 0 }
402
};
403

    
404
static EbmlSyntax matroska_tags[] = {
405
    { EBML_ID_VOID,                   EBML_NONE },
406
    { 0 }
407
};
408

    
409
static EbmlSyntax matroska_seekhead_entry[] = {
410
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
411
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
412
    { EBML_ID_VOID,                   EBML_NONE },
413
    { 0 }
414
};
415

    
416
static EbmlSyntax matroska_seekhead[] = {
417
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
418
    { EBML_ID_VOID,                   EBML_NONE },
419
    { 0 }
420
};
421

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

    
435
static EbmlSyntax matroska_segments[] = {
436
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
437
    { 0 }
438
};
439

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

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

    
457
static EbmlSyntax matroska_clusters[] = {
458
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
459
    { 0 }
460
};
461

    
462
/*
463
 * The first few functions handle EBML file parsing. The rest
464
 * is the document interpretation. Matroska really just is a
465
 * EBML file.
466
 */
467

    
468
/*
469
 * Return: the amount of levels in the hierarchy that the
470
 * current element lies higher than the previous one.
471
 * The opposite isn't done - that's auto-done using master
472
 * element reading.
473
 */
474

    
475
static int
476
ebml_read_element_level_up (MatroskaDemuxContext *matroska)
477
{
478
    ByteIOContext *pb = matroska->ctx->pb;
479
    offset_t pos = url_ftell(pb);
480
    int num = 0;
481

    
482
    while (matroska->num_levels > 0) {
483
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
484

    
485
        if (pos >= level->start + level->length) {
486
            matroska->num_levels--;
487
            num++;
488
        } else {
489
            break;
490
        }
491
    }
492

    
493
    return num;
494
}
495

    
496
/*
497
 * Read: an "EBML number", which is defined as a variable-length
498
 * array of bytes. The first byte indicates the length by giving a
499
 * number of 0-bits followed by a one. The position of the first
500
 * "one" bit inside the first byte indicates the length of this
501
 * number.
502
 * Returns: num. of bytes read. < 0 on error.
503
 */
504

    
505
static int
506
ebml_read_num (MatroskaDemuxContext *matroska,
507
               int                   max_size,
508
               uint64_t             *number)
509
{
510
    ByteIOContext *pb = matroska->ctx->pb;
511
    int len_mask = 0x80, read = 1, n = 1;
512
    int64_t total = 0;
513

    
514
    /* the first byte tells us the length in bytes - get_byte() can normally
515
     * return 0, but since that's not a valid first ebmlID byte, we can
516
     * use it safely here to catch EOS. */
517
    if (!(total = get_byte(pb))) {
518
        /* we might encounter EOS here */
519
        if (!url_feof(pb)) {
520
            offset_t pos = url_ftell(pb);
521
            av_log(matroska->ctx, AV_LOG_ERROR,
522
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
523
                   pos, pos);
524
        }
525
        return AVERROR(EIO); /* EOS or actual I/O error */
526
    }
527

    
528
    /* get the length of the EBML number */
529
    while (read <= max_size && !(total & len_mask)) {
530
        read++;
531
        len_mask >>= 1;
532
    }
533
    if (read > max_size) {
534
        offset_t pos = url_ftell(pb) - 1;
535
        av_log(matroska->ctx, AV_LOG_ERROR,
536
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
537
               (uint8_t) total, pos, pos);
538
        return AVERROR_INVALIDDATA;
539
    }
540

    
541
    /* read out length */
542
    total &= ~len_mask;
543
    while (n++ < read)
544
        total = (total << 8) | get_byte(pb);
545

    
546
    *number = total;
547

    
548
    return read;
549
}
550

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

    
556
static int
557
ebml_read_element_id (MatroskaDemuxContext *matroska,
558
                      uint32_t             *id,
559
                      int                  *level_up)
560
{
561
    int read;
562
    uint64_t total;
563

    
564
    /* if we re-call this, use our cached ID */
565
    if (matroska->peek_id != 0) {
566
        if (level_up)
567
            *level_up = 0;
568
        *id = matroska->peek_id;
569
        return 0;
570
    }
571

    
572
    /* read out the "EBML number", include tag in ID */
573
    if ((read = ebml_read_num(matroska, 4, &total)) < 0)
574
        return read;
575
    *id = matroska->peek_id  = total | (1 << (read * 7));
576

    
577
    /* level tracking */
578
    if (level_up)
579
        *level_up = ebml_read_element_level_up(matroska);
580

    
581
    return read;
582
}
583

    
584
/*
585
 * Read: element content length.
586
 * Return: the number of bytes read or < 0 on error.
587
 */
588

    
589
static int
590
ebml_read_element_length (MatroskaDemuxContext *matroska,
591
                          uint64_t             *length)
592
{
593
    /* clear cache since we're now beyond that data point */
594
    matroska->peek_id = 0;
595

    
596
    /* read out the "EBML number", include tag in ID */
597
    return ebml_read_num(matroska, 8, length);
598
}
599

    
600
/*
601
 * Return: the ID of the next element, or 0 on error.
602
 * Level_up contains the amount of levels that this
603
 * next element lies higher than the previous one.
604
 */
605

    
606
static uint32_t
607
ebml_peek_id (MatroskaDemuxContext *matroska,
608
              int                  *level_up)
609
{
610
    uint32_t id;
611

    
612
    if (ebml_read_element_id(matroska, &id, level_up) < 0)
613
        return 0;
614

    
615
    return id;
616
}
617

    
618
/*
619
 * Seek to a given offset.
620
 * 0 is success, -1 is failure.
621
 */
622

    
623
static int
624
ebml_read_seek (MatroskaDemuxContext *matroska,
625
                offset_t              offset)
626
{
627
    ByteIOContext *pb = matroska->ctx->pb;
628

    
629
    /* clear ID cache, if any */
630
    matroska->peek_id = 0;
631

    
632
    return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
633
}
634

    
635
/*
636
 * Skip the next element.
637
 * 0 is success, -1 is failure.
638
 */
639

    
640
static int
641
ebml_read_skip (MatroskaDemuxContext *matroska)
642
{
643
    ByteIOContext *pb = matroska->ctx->pb;
644
    uint32_t id;
645
    uint64_t length;
646
    int res;
647

    
648
    if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
649
        (res = ebml_read_element_length(matroska, &length)) < 0)
650
        return res;
651

    
652
    url_fskip(pb, length);
653

    
654
    return 0;
655
}
656

    
657
/*
658
 * Read the next element as an unsigned int.
659
 * 0 is success, < 0 is failure.
660
 */
661

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

    
671
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
672
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
673
        return res;
674
    size = rlength;
675
    if (size < 1 || size > 8) {
676
        offset_t pos = url_ftell(pb);
677
        av_log(matroska->ctx, AV_LOG_ERROR,
678
               "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
679
                size, pos, pos);
680
        return AVERROR_INVALIDDATA;
681
    }
682

    
683
    /* big-endian ordening; build up number */
684
    *num = 0;
685
    while (n++ < size)
686
        *num = (*num << 8) | get_byte(pb);
687

    
688
    return 0;
689
}
690

    
691
/*
692
 * Read the next element as a float.
693
 * 0 is success, < 0 is failure.
694
 */
695

    
696
static int
697
ebml_read_float (MatroskaDemuxContext *matroska,
698
                 uint32_t             *id,
699
                 double               *num)
700
{
701
    ByteIOContext *pb = matroska->ctx->pb;
702
    int size, res;
703
    uint64_t rlength;
704

    
705
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
706
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
707
        return res;
708
    size = rlength;
709

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

    
722
    return 0;
723
}
724

    
725
/*
726
 * Read the next element as an ASCII string.
727
 * 0 is success, < 0 is failure.
728
 */
729

    
730
static int
731
ebml_read_ascii (MatroskaDemuxContext *matroska,
732
                 uint32_t             *id,
733
                 char                **str)
734
{
735
    ByteIOContext *pb = matroska->ctx->pb;
736
    int size, res;
737
    uint64_t rlength;
738

    
739
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
740
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
741
        return res;
742
    size = rlength;
743

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

    
759
    return 0;
760
}
761

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

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

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

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

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

    
793
    return 0;
794
}
795

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

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

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

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

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

    
829
    return 0;
830
}
831

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

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

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

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

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

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

    
873
    return read;
874
}
875

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

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

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

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

    
898
    return res;
899
}
900

    
901

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

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

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

    
917

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

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

    
943
    return -1;
944
}
945

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

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

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

    
980

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

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

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

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

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

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

    
1020
    return 0;
1021
}
1022

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

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

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

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

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

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

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

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

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

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

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

    
1121

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

    
1128
    return res;
1129
}
1130

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

    
1154
static int
1155
matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
1156
{
1157
    MatroskaTrackEncoding *encodings = track->encodings.elem;
1158
    uint8_t* data = *buf;
1159
    int isize = *buf_size;
1160
    uint8_t* pkt_data = NULL;
1161
    int pkt_size = isize;
1162
    int result = 0;
1163
    int olen;
1164

    
1165
    switch (encodings[0].compression.algo) {
1166
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1167
        return encodings[0].compression.settings.size;
1168
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
1169
        do {
1170
            olen = pkt_size *= 3;
1171
            pkt_data = av_realloc(pkt_data,
1172
                                  pkt_size+LZO_OUTPUT_PADDING);
1173
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
1174
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
1175
        if (result)
1176
            goto failed;
1177
        pkt_size -= olen;
1178
        break;
1179
#ifdef CONFIG_ZLIB
1180
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1181
        z_stream zstream = {0};
1182
        if (inflateInit(&zstream) != Z_OK)
1183
            return -1;
1184
        zstream.next_in = data;
1185
        zstream.avail_in = isize;
1186
        do {
1187
            pkt_size *= 3;
1188
            pkt_data = av_realloc(pkt_data, pkt_size);
1189
            zstream.avail_out = pkt_size - zstream.total_out;
1190
            zstream.next_out = pkt_data + zstream.total_out;
1191
            result = inflate(&zstream, Z_NO_FLUSH);
1192
        } while (result==Z_OK && pkt_size<10000000);
1193
        pkt_size = zstream.total_out;
1194
        inflateEnd(&zstream);
1195
        if (result != Z_STREAM_END)
1196
            goto failed;
1197
        break;
1198
    }
1199
#endif
1200
#ifdef CONFIG_BZLIB
1201
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1202
        bz_stream bzstream = {0};
1203
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1204
            return -1;
1205
        bzstream.next_in = data;
1206
        bzstream.avail_in = isize;
1207
        do {
1208
            pkt_size *= 3;
1209
            pkt_data = av_realloc(pkt_data, pkt_size);
1210
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1211
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1212
            result = BZ2_bzDecompress(&bzstream);
1213
        } while (result==BZ_OK && pkt_size<10000000);
1214
        pkt_size = bzstream.total_out_lo32;
1215
        BZ2_bzDecompressEnd(&bzstream);
1216
        if (result != BZ_STREAM_END)
1217
            goto failed;
1218
        break;
1219
    }
1220
#endif
1221
    }
1222

    
1223
    *buf = pkt_data;
1224
    *buf_size = pkt_size;
1225
    return 0;
1226
 failed:
1227
    av_free(pkt_data);
1228
    return -1;
1229
}
1230

    
1231
static void
1232
matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1233
{
1234
    EbmlList *seekhead_list = &matroska->seekhead;
1235
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1236
    uint32_t peek_id_cache = matroska->peek_id;
1237
    uint32_t level_up = matroska->level_up;
1238
    offset_t before_pos = url_ftell(matroska->ctx->pb);
1239
    MatroskaLevel level;
1240
    int i;
1241

    
1242
    for (i=0; i<seekhead_list->nb_elem; i++) {
1243
        if (seekhead[i].pos <= before_pos
1244
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1245
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1246
            continue;
1247

    
1248
        /* seek */
1249
        if (ebml_read_seek(matroska,
1250
                           seekhead[i].pos+matroska->segment_start) < 0)
1251
            continue;
1252

    
1253
        /* we don't want to lose our seekhead level, so we add
1254
         * a dummy. This is a crude hack. */
1255
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1256
            av_log(matroska->ctx, AV_LOG_INFO,
1257
                   "Max EBML element depth (%d) reached, "
1258
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1259
            break;
1260
        }
1261

    
1262
        level.start = 0;
1263
        level.length = (uint64_t)-1;
1264
        matroska->levels[matroska->num_levels] = level;
1265
        matroska->num_levels++;
1266

    
1267
        ebml_parse_id(matroska, matroska_segment, seekhead[i].id, matroska);
1268

    
1269
        /* remove dummy level */
1270
        while (matroska->num_levels) {
1271
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1272
            if (length == (uint64_t)-1)
1273
                break;
1274
        }
1275
    }
1276

    
1277
    /* seek back */
1278
    ebml_read_seek(matroska, before_pos);
1279
    matroska->peek_id = peek_id_cache;
1280
    matroska->level_up = level_up;
1281
}
1282

    
1283
static int
1284
matroska_aac_profile (char *codec_id)
1285
{
1286
    static const char *aac_profiles[] = {
1287
        "MAIN", "LC", "SSR"
1288
    };
1289
    int profile;
1290

    
1291
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1292
        if (strstr(codec_id, aac_profiles[profile]))
1293
            break;
1294
    return profile + 1;
1295
}
1296

    
1297
static int
1298
matroska_aac_sri (int samplerate)
1299
{
1300
    int sri;
1301

    
1302
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1303
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1304
            break;
1305
    return sri;
1306
}
1307

    
1308
static int
1309
matroska_read_header (AVFormatContext    *s,
1310
                      AVFormatParameters *ap)
1311
{
1312
    MatroskaDemuxContext *matroska = s->priv_data;
1313
    EbmlList *attachements_list = &matroska->attachments;
1314
    MatroskaAttachement *attachements;
1315
    EbmlList *chapters_list = &matroska->chapters;
1316
    MatroskaChapter *chapters;
1317
    MatroskaTrack *tracks;
1318
    EbmlList *index_list;
1319
    MatroskaIndex *index;
1320
    Ebml ebml = { 0 };
1321
    AVStream *st;
1322
    int i, j;
1323

    
1324
    matroska->ctx = s;
1325

    
1326
    /* First read the EBML header. */
1327
    if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
1328
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1329
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1330
        || ebml.doctype_version > 2) {
1331
        av_log(matroska->ctx, AV_LOG_ERROR,
1332
               "EBML header using unsupported features\n"
1333
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1334
               ebml.version, ebml.doctype, ebml.doctype_version);
1335
        return AVERROR_NOFMT;
1336
    }
1337
    ebml_free(ebml_syntax, &ebml);
1338

    
1339
    /* The next thing is a segment. */
1340
    if (ebml_parse(matroska, matroska_segments, matroska, 0, 1) < 0)
1341
        return -1;
1342
    matroska_execute_seekhead(matroska);
1343

    
1344
    /* Have we found a cluster? */
1345
    if (ebml_peek_id(matroska, NULL) != MATROSKA_ID_CLUSTER)
1346
        return -1;
1347

    
1348
    if (matroska->duration)
1349
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1350
                                  * 1000 / AV_TIME_BASE;
1351
    if (matroska->title)
1352
        strncpy(matroska->ctx->title, matroska->title,
1353
                sizeof(matroska->ctx->title)-1);
1354

    
1355
    tracks = matroska->tracks.elem;
1356
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1357
        MatroskaTrack *track = &tracks[i];
1358
        enum CodecID codec_id = CODEC_ID_NONE;
1359
        EbmlList *encodings_list = &tracks->encodings;
1360
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1361
        uint8_t *extradata = NULL;
1362
        int extradata_size = 0;
1363
        int extradata_offset = 0;
1364

    
1365
        /* Apply some sanity checks. */
1366
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1367
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1368
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1369
            av_log(matroska->ctx, AV_LOG_INFO,
1370
                   "Unknown or unsupported track type %"PRIu64"\n",
1371
                   track->type);
1372
            continue;
1373
        }
1374
        if (track->codec_id == NULL)
1375
            continue;
1376

    
1377
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1378
            if (!track->default_duration)
1379
                track->default_duration = 1000000000/track->video.frame_rate;
1380
            if (!track->video.display_width)
1381
                track->video.display_width = track->video.pixel_width;
1382
            if (!track->video.display_height)
1383
                track->video.display_height = track->video.pixel_height;
1384
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1385
            if (!track->audio.out_samplerate)
1386
                track->audio.out_samplerate = track->audio.samplerate;
1387
        }
1388
        if (encodings_list->nb_elem > 1) {
1389
            av_log(matroska->ctx, AV_LOG_ERROR,
1390
                   "Multiple combined encodings no supported");
1391
        } else if (encodings_list->nb_elem == 1) {
1392
            if (encodings[0].type ||
1393
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1394
#ifdef CONFIG_ZLIB
1395
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1396
#endif
1397
#ifdef CONFIG_BZLIB
1398
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1399
#endif
1400
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1401
                encodings[0].scope = 0;
1402
                av_log(matroska->ctx, AV_LOG_ERROR,
1403
                       "Unsupported encoding type");
1404
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1405
                uint8_t *codec_priv = track->codec_priv.data;
1406
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1407
                                                    &track->codec_priv.size,
1408
                                                    track);
1409
                if (offset < 0) {
1410
                    track->codec_priv.data = NULL;
1411
                    track->codec_priv.size = 0;
1412
                    av_log(matroska->ctx, AV_LOG_ERROR,
1413
                           "Failed to decode codec private data\n");
1414
                } else if (offset > 0) {
1415
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1416
                    memcpy(track->codec_priv.data,
1417
                           encodings[0].compression.settings.data, offset);
1418
                    memcpy(track->codec_priv.data+offset, codec_priv,
1419
                           track->codec_priv.size);
1420
                    track->codec_priv.size += offset;
1421
                }
1422
                if (codec_priv != track->codec_priv.data)
1423
                    av_free(codec_priv);
1424
            }
1425
        }
1426

    
1427
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1428
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1429
                        strlen(ff_mkv_codec_tags[j].str))){
1430
                codec_id= ff_mkv_codec_tags[j].id;
1431
                break;
1432
            }
1433
        }
1434

    
1435
        st = track->stream = av_new_stream(s, matroska->num_streams++);
1436
        if (st == NULL)
1437
            return AVERROR(ENOMEM);
1438

    
1439
        /* Set the FourCC from the CodecID. */
1440
        /* This is the MS compatibility mode which stores a
1441
         * BITMAPINFOHEADER in the CodecPrivate. */
1442
        if (!strcmp(track->codec_id,
1443
                    MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
1444
            (track->codec_priv.size >= 40) &&
1445
            (track->codec_priv.data != NULL)) {
1446
            /* Offset of biCompression. Stored in LE. */
1447
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1448
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1449

    
1450
        }
1451

    
1452
        /* This is the MS compatibility mode which stores a
1453
         * WAVEFORMATEX in the CodecPrivate. */
1454
        else if (!strcmp(track->codec_id,
1455
                         MATROSKA_CODEC_ID_AUDIO_ACM) &&
1456
                 (track->codec_priv.size >= 18) &&
1457
                 (track->codec_priv.data != NULL)) {
1458
            /* Offset of wFormatTag. Stored in LE. */
1459
            uint16_t tag = AV_RL16(track->codec_priv.data);
1460
            codec_id = codec_get_id(codec_wav_tags, tag);
1461

    
1462
        }
1463

    
1464
        else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
1465
                 (track->codec_priv.size >= 86) &&
1466
                 (track->codec_priv.data != NULL)) {
1467
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1468
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1469
        }
1470

    
1471
        else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1472
            int profile = matroska_aac_profile(track->codec_id);
1473
            int sri = matroska_aac_sri(track->audio.samplerate);
1474
            extradata = av_malloc(5);
1475
            if (extradata == NULL)
1476
                return AVERROR(ENOMEM);
1477
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1478
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1479
            if (strstr(track->codec_id, "SBR")) {
1480
                sri = matroska_aac_sri(track->audio.out_samplerate);
1481
                extradata[2] = 0x56;
1482
                extradata[3] = 0xE5;
1483
                extradata[4] = 0x80 | (sri<<3);
1484
                extradata_size = 5;
1485
            } else {
1486
                extradata_size = 2;
1487
            }
1488
        }
1489

    
1490
        else if (codec_id == CODEC_ID_TTA) {
1491
            ByteIOContext b;
1492
            extradata_size = 30;
1493
            extradata = av_mallocz(extradata_size);
1494
            if (extradata == NULL)
1495
                return AVERROR(ENOMEM);
1496
            init_put_byte(&b, extradata, extradata_size, 1,
1497
                          NULL, NULL, NULL, NULL);
1498
            put_buffer(&b, "TTA1", 4);
1499
            put_le16(&b, 1);
1500
            put_le16(&b, track->audio.channels);
1501
            put_le16(&b, track->audio.bitdepth);
1502
            put_le32(&b, track->audio.out_samplerate);
1503
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1504
        }
1505

    
1506
        else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1507
                 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1508
            extradata_offset = 26;
1509
            track->codec_priv.size -= extradata_offset;
1510
        }
1511

    
1512
        else if (codec_id == CODEC_ID_RA_144) {
1513
            track->audio.out_samplerate = 8000;
1514
            track->audio.channels = 1;
1515
        }
1516

    
1517
        else if (codec_id == CODEC_ID_RA_288 ||
1518
                 codec_id == CODEC_ID_COOK ||
1519
                 codec_id == CODEC_ID_ATRAC3) {
1520
            ByteIOContext b;
1521

    
1522
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1523
                          0, NULL, NULL, NULL, NULL);
1524
            url_fskip(&b, 24);
1525
            track->audio.coded_framesize = get_be32(&b);
1526
            url_fskip(&b, 12);
1527
            track->audio.sub_packet_h    = get_be16(&b);
1528
            track->audio.frame_size      = get_be16(&b);
1529
            track->audio.sub_packet_size = get_be16(&b);
1530
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1531
            if (codec_id == CODEC_ID_RA_288) {
1532
                st->codec->block_align = track->audio.coded_framesize;
1533
                track->codec_priv.size = 0;
1534
            } else {
1535
                st->codec->block_align = track->audio.sub_packet_size;
1536
                extradata_offset = 78;
1537
                track->codec_priv.size -= extradata_offset;
1538
            }
1539
        }
1540

    
1541
        if (codec_id == CODEC_ID_NONE) {
1542
            av_log(matroska->ctx, AV_LOG_INFO,
1543
                   "Unknown/unsupported CodecID %s.\n",
1544
                   track->codec_id);
1545
        }
1546

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

    
1549
        st->codec->codec_id = codec_id;
1550
        st->start_time = 0;
1551
        if (strcmp(track->language, "und"))
1552
            av_strlcpy(st->language, track->language, 4);
1553

    
1554
        if (track->flag_default)
1555
            st->disposition |= AV_DISPOSITION_DEFAULT;
1556

    
1557
        if (track->default_duration)
1558
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1559
                      track->default_duration, 1000000000, 30000);
1560

    
1561
        if(extradata){
1562
            st->codec->extradata = extradata;
1563
            st->codec->extradata_size = extradata_size;
1564
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1565
            st->codec->extradata = av_malloc(track->codec_priv.size);
1566
            if(st->codec->extradata == NULL)
1567
                return AVERROR(ENOMEM);
1568
            st->codec->extradata_size = track->codec_priv.size;
1569
            memcpy(st->codec->extradata,
1570
                   track->codec_priv.data + extradata_offset,
1571
                   track->codec_priv.size);
1572
        }
1573

    
1574
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1575
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1576
            st->codec->codec_tag  = track->video.fourcc;
1577
            st->codec->width  = track->video.pixel_width;
1578
            st->codec->height = track->video.pixel_height;
1579
            av_reduce(&st->codec->sample_aspect_ratio.num,
1580
                      &st->codec->sample_aspect_ratio.den,
1581
                      st->codec->height * track->video.display_width,
1582
                      st->codec-> width * track->video.display_height,
1583
                      255);
1584
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1585
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1586
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1587
            st->codec->sample_rate = track->audio.out_samplerate;
1588
            st->codec->channels = track->audio.channels;
1589
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1590
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1591
        }
1592

    
1593
        /* What do we do with private data? E.g. for Vorbis. */
1594
    }
1595

    
1596
    attachements = attachements_list->elem;
1597
    for (j=0; j<attachements_list->nb_elem; j++) {
1598
        if (!(attachements[j].filename && attachements[j].mime &&
1599
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1600
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1601
        } else {
1602
            AVStream *st = av_new_stream(s, matroska->num_streams++);
1603
            if (st == NULL)
1604
                break;
1605
            st->filename          = av_strdup(attachements[j].filename);
1606
            st->codec->codec_id = CODEC_ID_NONE;
1607
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1608
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1609
            if(st->codec->extradata == NULL)
1610
                break;
1611
            st->codec->extradata_size = attachements[j].bin.size;
1612
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1613

    
1614
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1615
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1616
                             strlen(ff_mkv_mime_tags[i].str))) {
1617
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1618
                    break;
1619
                }
1620
            }
1621
        }
1622
    }
1623

    
1624
    chapters = chapters_list->elem;
1625
    for (i=0; i<chapters_list->nb_elem; i++)
1626
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1627
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1628
                           chapters[i].start, chapters[i].end,
1629
                           chapters[i].title);
1630

    
1631
    index_list = &matroska->index;
1632
    index = index_list->elem;
1633
    for (i=0; i<index_list->nb_elem; i++) {
1634
        EbmlList *pos_list = &index[i].pos;
1635
        MatroskaIndexPos *pos = pos_list->elem;
1636
        for (j=0; j<pos_list->nb_elem; j++) {
1637
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1638
                                                              pos[j].track);
1639
            if (track && track->stream)
1640
                av_add_index_entry(track->stream,
1641
                                   pos[j].pos + matroska->segment_start,
1642
                                   index[i].time*matroska->time_scale/AV_TIME_BASE,
1643
                                   0, 0, AVINDEX_KEYFRAME);
1644
        }
1645
    }
1646

    
1647
    return 0;
1648
}
1649

    
1650
static int
1651
matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
1652
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
1653
                     int is_keyframe)
1654
{
1655
    MatroskaTrack *track;
1656
    int res = 0;
1657
    AVStream *st;
1658
    AVPacket *pkt;
1659
    int16_t block_time;
1660
    uint32_t *lace_size = NULL;
1661
    int n, flags, laces = 0;
1662
    uint64_t num;
1663

    
1664
    /* first byte(s): tracknum */
1665
    if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1666
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1667
        return res;
1668
    }
1669
    data += n;
1670
    size -= n;
1671

    
1672
    /* fetch track from num */
1673
    track = matroska_find_track_by_num(matroska, num);
1674
    if (size <= 3 || !track || !track->stream) {
1675
        av_log(matroska->ctx, AV_LOG_INFO,
1676
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1677
        return res;
1678
    }
1679
    st = track->stream;
1680
    if (st->discard >= AVDISCARD_ALL) {
1681
        return res;
1682
    }
1683
    if (duration == AV_NOPTS_VALUE)
1684
        duration = track->default_duration / matroska->time_scale;
1685

    
1686
    /* block_time (relative to cluster time) */
1687
    block_time = AV_RB16(data);
1688
    data += 2;
1689
    flags = *data++;
1690
    size -= 3;
1691
    if (is_keyframe == -1)
1692
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1693

    
1694
    if (matroska->skip_to_keyframe) {
1695
        if (!is_keyframe || st != matroska->skip_to_stream) {
1696
            return res;
1697
        }
1698
        matroska->skip_to_keyframe = 0;
1699
    }
1700

    
1701
    switch ((flags & 0x06) >> 1) {
1702
        case 0x0: /* no lacing */
1703
            laces = 1;
1704
            lace_size = av_mallocz(sizeof(int));
1705
            lace_size[0] = size;
1706
            break;
1707

    
1708
        case 0x1: /* xiph lacing */
1709
        case 0x2: /* fixed-size lacing */
1710
        case 0x3: /* EBML lacing */
1711
            assert(size>0); // size <=3 is checked before size-=3 above
1712
            laces = (*data) + 1;
1713
            data += 1;
1714
            size -= 1;
1715
            lace_size = av_mallocz(laces * sizeof(int));
1716

    
1717
            switch ((flags & 0x06) >> 1) {
1718
                case 0x1: /* xiph lacing */ {
1719
                    uint8_t temp;
1720
                    uint32_t total = 0;
1721
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1722
                        while (1) {
1723
                            if (size == 0) {
1724
                                res = -1;
1725
                                break;
1726
                            }
1727
                            temp = *data;
1728
                            lace_size[n] += temp;
1729
                            data += 1;
1730
                            size -= 1;
1731
                            if (temp != 0xff)
1732
                                break;
1733
                        }
1734
                        total += lace_size[n];
1735
                    }
1736
                    lace_size[n] = size - total;
1737
                    break;
1738
                }
1739

    
1740
                case 0x2: /* fixed-size lacing */
1741
                    for (n = 0; n < laces; n++)
1742
                        lace_size[n] = size / laces;
1743
                    break;
1744

    
1745
                case 0x3: /* EBML lacing */ {
1746
                    uint32_t total;
1747
                    n = matroska_ebmlnum_uint(data, size, &num);
1748
                    if (n < 0) {
1749
                        av_log(matroska->ctx, AV_LOG_INFO,
1750
                               "EBML block data error\n");
1751
                        break;
1752
                    }
1753
                    data += n;
1754
                    size -= n;
1755
                    total = lace_size[0] = num;
1756
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1757
                        int64_t snum;
1758
                        int r;
1759
                        r = matroska_ebmlnum_sint (data, size, &snum);
1760
                        if (r < 0) {
1761
                            av_log(matroska->ctx, AV_LOG_INFO,
1762
                                   "EBML block data error\n");
1763
                            break;
1764
                        }
1765
                        data += r;
1766
                        size -= r;
1767
                        lace_size[n] = lace_size[n - 1] + snum;
1768
                        total += lace_size[n];
1769
                    }
1770
                    lace_size[n] = size - total;
1771
                    break;
1772
                }
1773
            }
1774
            break;
1775
    }
1776

    
1777
    if (res == 0) {
1778
        uint64_t timecode = AV_NOPTS_VALUE;
1779

    
1780
        if (cluster_time != (uint64_t)-1
1781
            && (block_time >= 0 || cluster_time >= -block_time))
1782
            timecode = cluster_time + block_time;
1783

    
1784
        for (n = 0; n < laces; n++) {
1785
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1786
                st->codec->codec_id == CODEC_ID_COOK ||
1787
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1788
                int a = st->codec->block_align;
1789
                int sps = track->audio.sub_packet_size;
1790
                int cfs = track->audio.coded_framesize;
1791
                int h = track->audio.sub_packet_h;
1792
                int y = track->audio.sub_packet_cnt;
1793
                int w = track->audio.frame_size;
1794
                int x;
1795

    
1796
                if (!track->audio.pkt_cnt) {
1797
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1798
                        for (x=0; x<h/2; x++)
1799
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1800
                                   data+x*cfs, cfs);
1801
                    else
1802
                        for (x=0; x<w/sps; x++)
1803
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1804

    
1805
                    if (++track->audio.sub_packet_cnt >= h) {
1806
                        track->audio.sub_packet_cnt = 0;
1807
                        track->audio.pkt_cnt = h*w / a;
1808
                    }
1809
                }
1810
                while (track->audio.pkt_cnt) {
1811
                    pkt = av_mallocz(sizeof(AVPacket));
1812
                    av_new_packet(pkt, a);
1813
                    memcpy(pkt->data, track->audio.buf
1814
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1815
                    pkt->pos = pos;
1816
                    pkt->stream_index = st->index;
1817
                    matroska_queue_packet(matroska, pkt);
1818
                }
1819
            } else {
1820
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1821
                int offset = 0, pkt_size = lace_size[n];
1822
                uint8_t *pkt_data = data;
1823

    
1824
                if (encodings && encodings->scope & 1) {
1825
                    offset = matroska_decode_buffer(&pkt_data, &pkt_size,
1826
                                                    track);
1827
                    if (offset < 0)
1828
                        continue;
1829
                }
1830

    
1831
                pkt = av_mallocz(sizeof(AVPacket));
1832
                /* XXX: prevent data copy... */
1833
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1834
                    av_free(pkt);
1835
                    res = AVERROR(ENOMEM);
1836
                    n = laces-1;
1837
                    break;
1838
                }
1839
                if (offset)
1840
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1841
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1842

    
1843
                if (pkt_data != data)
1844
                    av_free(pkt_data);
1845

    
1846
                if (n == 0)
1847
                    pkt->flags = is_keyframe;
1848
                pkt->stream_index = st->index;
1849

    
1850
                pkt->pts = timecode;
1851
                pkt->pos = pos;
1852
                pkt->duration = duration;
1853

    
1854
                matroska_queue_packet(matroska, pkt);
1855
            }
1856

    
1857
            if (timecode != AV_NOPTS_VALUE)
1858
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1859
            data += lace_size[n];
1860
        }
1861
    }
1862

    
1863
    av_free(lace_size);
1864
    return res;
1865
}
1866

    
1867
static int
1868
matroska_parse_cluster (MatroskaDemuxContext *matroska)
1869
{
1870
    MatroskaCluster cluster = { 0 };
1871
    EbmlList *blocks_list;
1872
    MatroskaBlock *blocks;
1873
    int i, res = ebml_parse(matroska, matroska_clusters, &cluster, 0, 1);
1874
    blocks_list = &cluster.blocks;
1875
    blocks = blocks_list->elem;
1876
    for (i=0; !res && i<blocks_list->nb_elem; i++)
1877
        if (blocks[i].bin.size > 0)
1878
            res=matroska_parse_block(matroska,
1879
                                     blocks[i].bin.data, blocks[i].bin.size,
1880
                                     blocks[i].bin.pos,  cluster.timecode,
1881
                                     blocks[i].duration, !blocks[i].reference);
1882
    ebml_free(matroska_cluster, &cluster);
1883
    return res;
1884
}
1885

    
1886
static int
1887
matroska_read_packet (AVFormatContext *s,
1888
                      AVPacket        *pkt)
1889
{
1890
    MatroskaDemuxContext *matroska = s->priv_data;
1891

    
1892
    /* Read stream until we have a packet queued. */
1893
    while (matroska_deliver_packet(matroska, pkt)) {
1894

    
1895
        /* Have we already reached the end? */
1896
        if (matroska->done)
1897
            return AVERROR(EIO);
1898

    
1899
        if (matroska_parse_cluster(matroska) < 0)
1900
            matroska->done = 1;
1901
    }
1902

    
1903
    return 0;
1904
}
1905

    
1906
static int
1907
matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
1908
                    int flags)
1909
{
1910
    MatroskaDemuxContext *matroska = s->priv_data;
1911
    AVStream *st = s->streams[stream_index];
1912
    int index;
1913

    
1914
    /* find index entry */
1915
    index = av_index_search_timestamp(st, timestamp, flags);
1916
    if (index < 0)
1917
        return 0;
1918

    
1919
    matroska_clear_queue(matroska);
1920

    
1921
    /* do the seek */
1922
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1923
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1924
    matroska->skip_to_stream = st;
1925
    matroska->peek_id = 0;
1926
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1927
    return 0;
1928
}
1929

    
1930
static int
1931
matroska_read_close (AVFormatContext *s)
1932
{
1933
    MatroskaDemuxContext *matroska = s->priv_data;
1934
    MatroskaTrack *tracks = matroska->tracks.elem;
1935
    int n = 0;
1936

    
1937
    matroska_clear_queue(matroska);
1938

    
1939
    for (n=0; n < matroska->tracks.nb_elem; n++)
1940
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1941
            av_free(tracks[n].audio.buf);
1942
    ebml_free(matroska_segment, matroska);
1943

    
1944
    return 0;
1945
}
1946

    
1947
AVInputFormat matroska_demuxer = {
1948
    "matroska",
1949
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1950
    sizeof(MatroskaDemuxContext),
1951
    matroska_probe,
1952
    matroska_read_header,
1953
    matroska_read_packet,
1954
    matroska_read_close,
1955
    matroska_read_seek,
1956
};