Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 209472b4

History | View | Annotate | Download (64.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 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 signed int.
693
 * 0 is success, < 0 is failure.
694
 */
695

    
696
static int
697
ebml_read_sint (MatroskaDemuxContext *matroska,
698
                uint32_t             *id,
699
                int64_t              *num)
700
{
701
    ByteIOContext *pb = matroska->ctx->pb;
702
    int size, n = 1, negative = 0, 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
    if (size < 1 || size > 8) {
710
        offset_t pos = url_ftell(pb);
711
        av_log(matroska->ctx, AV_LOG_ERROR,
712
               "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
713
                size, pos, pos);
714
        return AVERROR_INVALIDDATA;
715
    }
716
    if ((*num = get_byte(pb)) & 0x80) {
717
        negative = 1;
718
        *num &= ~0x80;
719
    }
720
    while (n++ < size)
721
        *num = (*num << 8) | get_byte(pb);
722

    
723
    /* make signed */
724
    if (negative)
725
        *num = *num - (1LL << ((8 * size) - 1));
726

    
727
    return 0;
728
}
729

    
730
/*
731
 * Read the next element as a float.
732
 * 0 is success, < 0 is failure.
733
 */
734

    
735
static int
736
ebml_read_float (MatroskaDemuxContext *matroska,
737
                 uint32_t             *id,
738
                 double               *num)
739
{
740
    ByteIOContext *pb = matroska->ctx->pb;
741
    int size, res;
742
    uint64_t rlength;
743

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

    
749
    if (size == 4) {
750
        *num= av_int2flt(get_be32(pb));
751
    } else if(size==8){
752
        *num= av_int2dbl(get_be64(pb));
753
    } else{
754
        offset_t pos = url_ftell(pb);
755
        av_log(matroska->ctx, AV_LOG_ERROR,
756
               "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
757
               size, pos, pos);
758
        return AVERROR_INVALIDDATA;
759
    }
760

    
761
    return 0;
762
}
763

    
764
/*
765
 * Read the next element as an ASCII string.
766
 * 0 is success, < 0 is failure.
767
 */
768

    
769
static int
770
ebml_read_ascii (MatroskaDemuxContext *matroska,
771
                 uint32_t             *id,
772
                 char                **str)
773
{
774
    ByteIOContext *pb = matroska->ctx->pb;
775
    int size, res;
776
    uint64_t rlength;
777

    
778
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
779
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
780
        return res;
781
    size = rlength;
782

    
783
    /* ebml strings are usually not 0-terminated, so we allocate one
784
     * byte more, read the string and NULL-terminate it ourselves. */
785
    if (size < 0 || !(*str = av_malloc(size + 1))) {
786
        av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
787
        return AVERROR(ENOMEM);
788
    }
789
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
790
        offset_t pos = url_ftell(pb);
791
        av_log(matroska->ctx, AV_LOG_ERROR,
792
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
793
        av_free(*str);
794
        return AVERROR(EIO);
795
    }
796
    (*str)[size] = '\0';
797

    
798
    return 0;
799
}
800

    
801
/*
802
 * Read the next element as a UTF-8 string.
803
 * 0 is success, < 0 is failure.
804
 */
805

    
806
static int
807
ebml_read_utf8 (MatroskaDemuxContext *matroska,
808
                uint32_t             *id,
809
                char                **str)
810
{
811
  return ebml_read_ascii(matroska, id, str);
812
}
813

    
814
/*
815
 * Read the next element, but only the header. The contents
816
 * are supposed to be sub-elements which can be read separately.
817
 * 0 is success, < 0 is failure.
818
 */
819

    
820
static int
821
ebml_read_master (MatroskaDemuxContext *matroska,
822
                  uint32_t             *id)
823
{
824
    ByteIOContext *pb = matroska->ctx->pb;
825
    uint64_t length;
826
    MatroskaLevel *level;
827
    int res;
828

    
829
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
830
        (res = ebml_read_element_length(matroska, &length)) < 0)
831
        return res;
832

    
833
    /* protect... (Heaven forbids that the '>' is true) */
834
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
835
        av_log(matroska->ctx, AV_LOG_ERROR,
836
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
837
        return AVERROR(ENOSYS);
838
    }
839

    
840
    /* remember level */
841
    level = &matroska->levels[matroska->num_levels++];
842
    level->start = url_ftell(pb);
843
    level->length = length;
844

    
845
    return 0;
846
}
847

    
848
/*
849
 * Read the next element as binary data.
850
 * 0 is success, < 0 is failure.
851
 */
852

    
853
static int
854
ebml_read_binary (MatroskaDemuxContext *matroska,
855
                  uint32_t             *id,
856
                  uint8_t             **binary,
857
                  int                  *size)
858
{
859
    ByteIOContext *pb = matroska->ctx->pb;
860
    uint64_t rlength;
861
    int res;
862

    
863
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
864
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
865
        return res;
866
    *size = rlength;
867

    
868
    if (!(*binary = av_malloc(*size))) {
869
        av_log(matroska->ctx, AV_LOG_ERROR,
870
               "Memory allocation error\n");
871
        return AVERROR(ENOMEM);
872
    }
873

    
874
    if (get_buffer(pb, *binary, *size) != *size) {
875
        offset_t pos = url_ftell(pb);
876
        av_log(matroska->ctx, AV_LOG_ERROR,
877
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
878
        return AVERROR(EIO);
879
    }
880

    
881
    return 0;
882
}
883

    
884
/*
885
 * Read signed/unsigned "EBML" numbers.
886
 * Return: number of bytes processed, < 0 on error.
887
 * XXX: use ebml_read_num().
888
 */
889

    
890
static int
891
matroska_ebmlnum_uint (uint8_t  *data,
892
                       uint32_t  size,
893
                       uint64_t *num)
894
{
895
    int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
896
    uint64_t total;
897

    
898
    if (size <= 0)
899
        return AVERROR_INVALIDDATA;
900

    
901
    total = data[0];
902
    while (read <= 8 && !(total & len_mask)) {
903
        read++;
904
        len_mask >>= 1;
905
    }
906
    if (read > 8)
907
        return AVERROR_INVALIDDATA;
908

    
909
    if ((total &= (len_mask - 1)) == len_mask - 1)
910
        num_ffs++;
911
    if (size < read)
912
        return AVERROR_INVALIDDATA;
913
    while (n < read) {
914
        if (data[n] == 0xff)
915
            num_ffs++;
916
        total = (total << 8) | data[n];
917
        n++;
918
    }
919

    
920
    if (read == num_ffs)
921
        *num = (uint64_t)-1;
922
    else
923
        *num = total;
924

    
925
    return read;
926
}
927

    
928
/*
929
 * Same as above, but signed.
930
 */
931

    
932
static int
933
matroska_ebmlnum_sint (uint8_t  *data,
934
                       uint32_t  size,
935
                       int64_t  *num)
936
{
937
    uint64_t unum;
938
    int res;
939

    
940
    /* read as unsigned number first */
941
    if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
942
        return res;
943

    
944
    /* make signed (weird way) */
945
    if (unum == (uint64_t)-1)
946
        *num = INT64_MAX;
947
    else
948
        *num = unum - ((1LL << ((7 * res) - 1)) - 1);
949

    
950
    return res;
951
}
952

    
953

    
954
static MatroskaTrack *
955
matroska_find_track_by_num (MatroskaDemuxContext *matroska,
956
                            int                   num)
957
{
958
    MatroskaTrack *tracks = matroska->tracks.elem;
959
    int i;
960

    
961
    for (i=0; i < matroska->tracks.nb_elem; i++)
962
        if (tracks[i].num == num)
963
            return &tracks[i];
964

    
965
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
966
    return NULL;
967
}
968

    
969

    
970
/*
971
 * Put one packet in an application-supplied AVPacket struct.
972
 * Returns 0 on success or -1 on failure.
973
 */
974

    
975
static int
976
matroska_deliver_packet (MatroskaDemuxContext *matroska,
977
                         AVPacket             *pkt)
978
{
979
    if (matroska->num_packets > 0) {
980
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
981
        av_free(matroska->packets[0]);
982
        if (matroska->num_packets > 1) {
983
            memmove(&matroska->packets[0], &matroska->packets[1],
984
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
985
            matroska->packets =
986
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
987
                           sizeof(AVPacket *));
988
        } else {
989
            av_freep(&matroska->packets);
990
        }
991
        matroska->num_packets--;
992
        return 0;
993
    }
994

    
995
    return -1;
996
}
997

    
998
/*
999
 * Put a packet into our internal queue. Will be delivered to the
1000
 * user/application during the next get_packet() call.
1001
 */
1002

    
1003
static void
1004
matroska_queue_packet (MatroskaDemuxContext *matroska,
1005
                       AVPacket             *pkt)
1006
{
1007
    matroska->packets =
1008
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
1009
                   sizeof(AVPacket *));
1010
    matroska->packets[matroska->num_packets] = pkt;
1011
    matroska->num_packets++;
1012
}
1013

    
1014
/*
1015
 * Free all packets in our internal queue.
1016
 */
1017
static void
1018
matroska_clear_queue (MatroskaDemuxContext *matroska)
1019
{
1020
    if (matroska->packets) {
1021
        int n;
1022
        for (n = 0; n < matroska->num_packets; n++) {
1023
            av_free_packet(matroska->packets[n]);
1024
            av_free(matroska->packets[n]);
1025
        }
1026
        av_free(matroska->packets);
1027
        matroska->packets = NULL;
1028
        matroska->num_packets = 0;
1029
    }
1030
}
1031

    
1032

    
1033
/*
1034
 * Autodetecting...
1035
 */
1036

    
1037
static int
1038
matroska_probe (AVProbeData *p)
1039
{
1040
    uint64_t total = 0;
1041
    int len_mask = 0x80, size = 1, n = 1;
1042
    uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
1043

    
1044
    /* ebml header? */
1045
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
1046
        return 0;
1047

    
1048
    /* length of header */
1049
    total = p->buf[4];
1050
    while (size <= 8 && !(total & len_mask)) {
1051
        size++;
1052
        len_mask >>= 1;
1053
    }
1054
    if (size > 8)
1055
      return 0;
1056
    total &= (len_mask - 1);
1057
    while (n < size)
1058
        total = (total << 8) | p->buf[4 + n++];
1059

    
1060
    /* does the probe data contain the whole header? */
1061
    if (p->buf_size < 4 + size + total)
1062
      return 0;
1063

    
1064
    /* the header must contain the document type 'matroska'. For now,
1065
     * we don't parse the whole header but simply check for the
1066
     * availability of that array of characters inside the header.
1067
     * Not fully fool-proof, but good enough. */
1068
    for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
1069
        if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
1070
            return AVPROBE_SCORE_MAX;
1071

    
1072
    return 0;
1073
}
1074

    
1075
/*
1076
 * From here on, it's all XML-style DTD stuff... Needs no comments.
1077
 */
1078

    
1079
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1080
                      void *data, uint32_t expected_id, int once);
1081

    
1082
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
1083
                           EbmlSyntax *syntax, void *data)
1084
{
1085
    uint32_t id = syntax->id;
1086
    EbmlBin *bin;
1087
    int res;
1088

    
1089
    data = (char *)data + syntax->data_offset;
1090
    if (syntax->list_elem_size) {
1091
        EbmlList *list = data;
1092
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
1093
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
1094
        memset(data, 0, syntax->list_elem_size);
1095
        list->nb_elem++;
1096
    }
1097
    bin = data;
1098

    
1099
    switch (syntax->type) {
1100
    case EBML_UINT:  return ebml_read_uint (matroska, &id, data);
1101
    case EBML_FLOAT: return ebml_read_float(matroska, &id, data);
1102
    case EBML_STR:
1103
    case EBML_UTF8:  av_free(*(char **)data);
1104
                     return ebml_read_ascii(matroska, &id, data);
1105
    case EBML_BIN:   av_free(bin->data);
1106
                     bin->pos = url_ftell(matroska->ctx->pb);
1107
                     return ebml_read_binary(matroska, &id, &bin->data,
1108
                                                            &bin->size);
1109
    case EBML_NEST:  if ((res=ebml_read_master(matroska, &id)) < 0)
1110
                         return res;
1111
                     if (id == MATROSKA_ID_SEGMENT)
1112
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
1113
                     return ebml_parse(matroska, syntax->def.n, data, 0, 0);
1114
    case EBML_PASS:  return ebml_parse(matroska, syntax->def.n, data, 0, 1);
1115
    case EBML_STOP:  *(int *)data = 1;      return 1;
1116
    default:         return ebml_read_skip(matroska);
1117
    }
1118
}
1119

    
1120
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1121
                         uint32_t id, void *data)
1122
{
1123
    int i;
1124
    for (i=0; syntax[i].id; i++)
1125
        if (id == syntax[i].id)
1126
            break;
1127
    if (!syntax[i].id)
1128
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
1129
    return ebml_parse_elem(matroska, &syntax[i], data);
1130
}
1131

    
1132
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1133
                      void *data, uint32_t expected_id, int once)
1134
{
1135
    int i, res = 0;
1136
    uint32_t id = 0;
1137

    
1138
    for (i=0; syntax[i].id; i++)
1139
        switch (syntax[i].type) {
1140
        case EBML_UINT:
1141
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
1142
            break;
1143
        case EBML_FLOAT:
1144
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
1145
            break;
1146
        case EBML_STR:
1147
        case EBML_UTF8:
1148
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
1149
            break;
1150
        }
1151

    
1152
    if (expected_id) {
1153
        res = ebml_read_master(matroska, &id);
1154
        if (id != expected_id)
1155
            return AVERROR_INVALIDDATA;
1156
        if (id == MATROSKA_ID_SEGMENT)
1157
            matroska->segment_start = url_ftell(matroska->ctx->pb);
1158
    }
1159

    
1160
    while (!res) {
1161
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1162
            res = AVERROR(EIO);
1163
            break;
1164
        } else if (matroska->level_up) {
1165
            matroska->level_up--;
1166
            break;
1167
        }
1168

    
1169
        res = ebml_parse_id(matroska, syntax, id, data);
1170
        if (once)
1171
            break;
1172

    
1173

    
1174
        if (matroska->level_up) {
1175
            matroska->level_up--;
1176
            break;
1177
        }
1178
    }
1179

    
1180
    return res;
1181
}
1182

    
1183
static void ebml_free(EbmlSyntax *syntax, void *data)
1184
{
1185
    int i, j;
1186
    for (i=0; syntax[i].id; i++) {
1187
        void *data_off = (char *)data + syntax[i].data_offset;
1188
        switch (syntax[i].type) {
1189
        case EBML_STR:
1190
        case EBML_UTF8:  av_freep(data_off);                      break;
1191
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
1192
        case EBML_NEST:
1193
            if (syntax[i].list_elem_size) {
1194
                EbmlList *list = data_off;
1195
                char *ptr = list->elem;
1196
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1197
                    ebml_free(syntax[i].def.n, ptr);
1198
                av_free(list->elem);
1199
            } else
1200
                ebml_free(syntax[i].def.n, data_off);
1201
        default:  break;
1202
        }
1203
    }
1204
}
1205

    
1206
static int
1207
matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
1208
{
1209
    MatroskaTrackEncoding *encodings = track->encodings.elem;
1210
    uint8_t* data = *buf;
1211
    int isize = *buf_size;
1212
    uint8_t* pkt_data = NULL;
1213
    int pkt_size = isize;
1214
    int result = 0;
1215
    int olen;
1216

    
1217
    switch (encodings[0].compression.algo) {
1218
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1219
        return encodings[0].compression.settings.size;
1220
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
1221
        do {
1222
            olen = pkt_size *= 3;
1223
            pkt_data = av_realloc(pkt_data,
1224
                                  pkt_size+LZO_OUTPUT_PADDING);
1225
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
1226
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
1227
        if (result)
1228
            goto failed;
1229
        pkt_size -= olen;
1230
        break;
1231
#ifdef CONFIG_ZLIB
1232
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1233
        z_stream zstream = {0};
1234
        if (inflateInit(&zstream) != Z_OK)
1235
            return -1;
1236
        zstream.next_in = data;
1237
        zstream.avail_in = isize;
1238
        do {
1239
            pkt_size *= 3;
1240
            pkt_data = av_realloc(pkt_data, pkt_size);
1241
            zstream.avail_out = pkt_size - zstream.total_out;
1242
            zstream.next_out = pkt_data + zstream.total_out;
1243
            result = inflate(&zstream, Z_NO_FLUSH);
1244
        } while (result==Z_OK && pkt_size<10000000);
1245
        pkt_size = zstream.total_out;
1246
        inflateEnd(&zstream);
1247
        if (result != Z_STREAM_END)
1248
            goto failed;
1249
        break;
1250
    }
1251
#endif
1252
#ifdef CONFIG_BZLIB
1253
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1254
        bz_stream bzstream = {0};
1255
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1256
            return -1;
1257
        bzstream.next_in = data;
1258
        bzstream.avail_in = isize;
1259
        do {
1260
            pkt_size *= 3;
1261
            pkt_data = av_realloc(pkt_data, pkt_size);
1262
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1263
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1264
            result = BZ2_bzDecompress(&bzstream);
1265
        } while (result==BZ_OK && pkt_size<10000000);
1266
        pkt_size = bzstream.total_out_lo32;
1267
        BZ2_bzDecompressEnd(&bzstream);
1268
        if (result != BZ_STREAM_END)
1269
            goto failed;
1270
        break;
1271
    }
1272
#endif
1273
    }
1274

    
1275
    *buf = pkt_data;
1276
    *buf_size = pkt_size;
1277
    return 0;
1278
 failed:
1279
    av_free(pkt_data);
1280
    return -1;
1281
}
1282

    
1283
static void
1284
matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1285
{
1286
    EbmlList *seekhead_list = &matroska->seekhead;
1287
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1288
    uint32_t peek_id_cache = matroska->peek_id;
1289
    uint32_t level_up = matroska->level_up;
1290
    offset_t before_pos = url_ftell(matroska->ctx->pb);
1291
    MatroskaLevel level;
1292
    int i;
1293

    
1294
    for (i=0; i<seekhead_list->nb_elem; i++) {
1295
        if (seekhead[i].pos <= before_pos
1296
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1297
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1298
            continue;
1299

    
1300
        /* seek */
1301
        if (ebml_read_seek(matroska,
1302
                           seekhead[i].pos+matroska->segment_start) < 0)
1303
            continue;
1304

    
1305
        /* we don't want to lose our seekhead level, so we add
1306
         * a dummy. This is a crude hack. */
1307
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1308
            av_log(matroska->ctx, AV_LOG_INFO,
1309
                   "Max EBML element depth (%d) reached, "
1310
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1311
            break;
1312
        }
1313

    
1314
        level.start = 0;
1315
        level.length = (uint64_t)-1;
1316
        matroska->levels[matroska->num_levels] = level;
1317
        matroska->num_levels++;
1318

    
1319
        ebml_parse_id(matroska, matroska_segment, seekhead[i].id, matroska);
1320

    
1321
        /* remove dummy level */
1322
        while (matroska->num_levels) {
1323
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1324
            if (length == (uint64_t)-1)
1325
                break;
1326
        }
1327
    }
1328

    
1329
    /* seek back */
1330
    ebml_read_seek(matroska, before_pos);
1331
    matroska->peek_id = peek_id_cache;
1332
    matroska->level_up = level_up;
1333
}
1334

    
1335
static int
1336
matroska_aac_profile (char *codec_id)
1337
{
1338
    static const char *aac_profiles[] = {
1339
        "MAIN", "LC", "SSR"
1340
    };
1341
    int profile;
1342

    
1343
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1344
        if (strstr(codec_id, aac_profiles[profile]))
1345
            break;
1346
    return profile + 1;
1347
}
1348

    
1349
static int
1350
matroska_aac_sri (int samplerate)
1351
{
1352
    int sri;
1353

    
1354
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1355
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1356
            break;
1357
    return sri;
1358
}
1359

    
1360
static int
1361
matroska_read_header (AVFormatContext    *s,
1362
                      AVFormatParameters *ap)
1363
{
1364
    MatroskaDemuxContext *matroska = s->priv_data;
1365
    EbmlList *attachements_list = &matroska->attachments;
1366
    MatroskaAttachement *attachements;
1367
    EbmlList *chapters_list = &matroska->chapters;
1368
    MatroskaChapter *chapters;
1369
    MatroskaTrack *tracks;
1370
    EbmlList *index_list;
1371
    MatroskaIndex *index;
1372
    Ebml ebml = { 0 };
1373
    AVStream *st;
1374
    int i, j;
1375

    
1376
    matroska->ctx = s;
1377

    
1378
    /* First read the EBML header. */
1379
    if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
1380
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1381
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1382
        || ebml.doctype_version > 2) {
1383
        av_log(matroska->ctx, AV_LOG_ERROR,
1384
               "EBML header using unsupported features\n"
1385
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1386
               ebml.version, ebml.doctype, ebml.doctype_version);
1387
        return AVERROR_NOFMT;
1388
    }
1389
    ebml_free(ebml_syntax, &ebml);
1390

    
1391
    /* The next thing is a segment. */
1392
    if (ebml_parse(matroska, matroska_segments, matroska, 0, 1) < 0)
1393
        return -1;
1394
    matroska_execute_seekhead(matroska);
1395

    
1396
    /* Have we found a cluster? */
1397
    if (ebml_peek_id(matroska, NULL) != MATROSKA_ID_CLUSTER)
1398
        return -1;
1399

    
1400
    if (matroska->duration)
1401
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1402
                                  * 1000 / AV_TIME_BASE;
1403
    if (matroska->title)
1404
        strncpy(matroska->ctx->title, matroska->title,
1405
                sizeof(matroska->ctx->title)-1);
1406

    
1407
    tracks = matroska->tracks.elem;
1408
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1409
        MatroskaTrack *track = &tracks[i];
1410
        enum CodecID codec_id = CODEC_ID_NONE;
1411
        EbmlList *encodings_list = &tracks->encodings;
1412
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1413
        uint8_t *extradata = NULL;
1414
        int extradata_size = 0;
1415
        int extradata_offset = 0;
1416

    
1417
        /* Apply some sanity checks. */
1418
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1419
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1420
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1421
            av_log(matroska->ctx, AV_LOG_INFO,
1422
                   "Unknown or unsupported track type %"PRIu64"\n",
1423
                   track->type);
1424
            continue;
1425
        }
1426
        if (track->codec_id == NULL)
1427
            continue;
1428

    
1429
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1430
            if (!track->default_duration)
1431
                track->default_duration = 1000000000/track->video.frame_rate;
1432
            if (!track->video.display_width)
1433
                track->video.display_width = track->video.pixel_width;
1434
            if (!track->video.display_height)
1435
                track->video.display_height = track->video.pixel_height;
1436
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1437
            if (!track->audio.out_samplerate)
1438
                track->audio.out_samplerate = track->audio.samplerate;
1439
        }
1440
        if (encodings_list->nb_elem > 1) {
1441
            av_log(matroska->ctx, AV_LOG_ERROR,
1442
                   "Multiple combined encodings no supported");
1443
        } else if (encodings_list->nb_elem == 1) {
1444
            if (encodings[0].type ||
1445
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1446
#ifdef CONFIG_ZLIB
1447
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1448
#endif
1449
#ifdef CONFIG_BZLIB
1450
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1451
#endif
1452
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1453
                encodings[0].scope = 0;
1454
                av_log(matroska->ctx, AV_LOG_ERROR,
1455
                       "Unsupported encoding type");
1456
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1457
                uint8_t *codec_priv = track->codec_priv.data;
1458
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1459
                                                    &track->codec_priv.size,
1460
                                                    track);
1461
                if (offset < 0) {
1462
                    track->codec_priv.data = NULL;
1463
                    track->codec_priv.size = 0;
1464
                    av_log(matroska->ctx, AV_LOG_ERROR,
1465
                           "Failed to decode codec private data\n");
1466
                } else if (offset > 0) {
1467
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1468
                    memcpy(track->codec_priv.data,
1469
                           encodings[0].compression.settings.data, offset);
1470
                    memcpy(track->codec_priv.data+offset, codec_priv,
1471
                           track->codec_priv.size);
1472
                    track->codec_priv.size += offset;
1473
                }
1474
                if (codec_priv != track->codec_priv.data)
1475
                    av_free(codec_priv);
1476
            }
1477
        }
1478

    
1479
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1480
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1481
                        strlen(ff_mkv_codec_tags[j].str))){
1482
                codec_id= ff_mkv_codec_tags[j].id;
1483
                break;
1484
            }
1485
        }
1486

    
1487
        st = track->stream = av_new_stream(s, matroska->num_streams++);
1488
        if (st == NULL)
1489
            return AVERROR(ENOMEM);
1490

    
1491
        /* Set the FourCC from the CodecID. */
1492
        /* This is the MS compatibility mode which stores a
1493
         * BITMAPINFOHEADER in the CodecPrivate. */
1494
        if (!strcmp(track->codec_id,
1495
                    MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
1496
            (track->codec_priv.size >= 40) &&
1497
            (track->codec_priv.data != NULL)) {
1498
            /* Offset of biCompression. Stored in LE. */
1499
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1500
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1501

    
1502
        }
1503

    
1504
        /* This is the MS compatibility mode which stores a
1505
         * WAVEFORMATEX in the CodecPrivate. */
1506
        else if (!strcmp(track->codec_id,
1507
                         MATROSKA_CODEC_ID_AUDIO_ACM) &&
1508
                 (track->codec_priv.size >= 18) &&
1509
                 (track->codec_priv.data != NULL)) {
1510
            /* Offset of wFormatTag. Stored in LE. */
1511
            uint16_t tag = AV_RL16(track->codec_priv.data);
1512
            codec_id = codec_get_id(codec_wav_tags, tag);
1513

    
1514
        }
1515

    
1516
        else if (!strcmp(track->codec_id, "V_QUICKTIME") &&
1517
                 (track->codec_priv.size >= 86) &&
1518
                 (track->codec_priv.data != NULL)) {
1519
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1520
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1521
        }
1522

    
1523
        else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1524
            int profile = matroska_aac_profile(track->codec_id);
1525
            int sri = matroska_aac_sri(track->audio.samplerate);
1526
            extradata = av_malloc(5);
1527
            if (extradata == NULL)
1528
                return AVERROR(ENOMEM);
1529
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1530
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1531
            if (strstr(track->codec_id, "SBR")) {
1532
                sri = matroska_aac_sri(track->audio.out_samplerate);
1533
                extradata[2] = 0x56;
1534
                extradata[3] = 0xE5;
1535
                extradata[4] = 0x80 | (sri<<3);
1536
                extradata_size = 5;
1537
            } else {
1538
                extradata_size = 2;
1539
            }
1540
        }
1541

    
1542
        else if (codec_id == CODEC_ID_TTA) {
1543
            ByteIOContext b;
1544
            extradata_size = 30;
1545
            extradata = av_mallocz(extradata_size);
1546
            if (extradata == NULL)
1547
                return AVERROR(ENOMEM);
1548
            init_put_byte(&b, extradata, extradata_size, 1,
1549
                          NULL, NULL, NULL, NULL);
1550
            put_buffer(&b, "TTA1", 4);
1551
            put_le16(&b, 1);
1552
            put_le16(&b, track->audio.channels);
1553
            put_le16(&b, track->audio.bitdepth);
1554
            put_le32(&b, track->audio.out_samplerate);
1555
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1556
        }
1557

    
1558
        else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1559
                 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1560
            extradata_offset = 26;
1561
            track->codec_priv.size -= extradata_offset;
1562
        }
1563

    
1564
        else if (codec_id == CODEC_ID_RA_144) {
1565
            track->audio.out_samplerate = 8000;
1566
            track->audio.channels = 1;
1567
        }
1568

    
1569
        else if (codec_id == CODEC_ID_RA_288 ||
1570
                 codec_id == CODEC_ID_COOK ||
1571
                 codec_id == CODEC_ID_ATRAC3) {
1572
            ByteIOContext b;
1573

    
1574
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1575
                          0, NULL, NULL, NULL, NULL);
1576
            url_fskip(&b, 24);
1577
            track->audio.coded_framesize = get_be32(&b);
1578
            url_fskip(&b, 12);
1579
            track->audio.sub_packet_h    = get_be16(&b);
1580
            track->audio.frame_size      = get_be16(&b);
1581
            track->audio.sub_packet_size = get_be16(&b);
1582
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1583
            if (codec_id == CODEC_ID_RA_288) {
1584
                st->codec->block_align = track->audio.coded_framesize;
1585
                track->codec_priv.size = 0;
1586
            } else {
1587
                st->codec->block_align = track->audio.sub_packet_size;
1588
                extradata_offset = 78;
1589
                track->codec_priv.size -= extradata_offset;
1590
            }
1591
        }
1592

    
1593
        if (codec_id == CODEC_ID_NONE) {
1594
            av_log(matroska->ctx, AV_LOG_INFO,
1595
                   "Unknown/unsupported CodecID %s.\n",
1596
                   track->codec_id);
1597
        }
1598

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

    
1601
        st->codec->codec_id = codec_id;
1602
        st->start_time = 0;
1603
        if (strcmp(track->language, "und"))
1604
            av_strlcpy(st->language, track->language, 4);
1605

    
1606
        if (track->flag_default)
1607
            st->disposition |= AV_DISPOSITION_DEFAULT;
1608

    
1609
        if (track->default_duration)
1610
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1611
                      track->default_duration, 1000000000, 30000);
1612

    
1613
        if(extradata){
1614
            st->codec->extradata = extradata;
1615
            st->codec->extradata_size = extradata_size;
1616
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1617
            st->codec->extradata = av_malloc(track->codec_priv.size);
1618
            if(st->codec->extradata == NULL)
1619
                return AVERROR(ENOMEM);
1620
            st->codec->extradata_size = track->codec_priv.size;
1621
            memcpy(st->codec->extradata,
1622
                   track->codec_priv.data + extradata_offset,
1623
                   track->codec_priv.size);
1624
        }
1625

    
1626
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1627
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1628
            st->codec->codec_tag  = track->video.fourcc;
1629
            st->codec->width  = track->video.pixel_width;
1630
            st->codec->height = track->video.pixel_height;
1631
            av_reduce(&st->codec->sample_aspect_ratio.num,
1632
                      &st->codec->sample_aspect_ratio.den,
1633
                      st->codec->height * track->video.display_width,
1634
                      st->codec-> width * track->video.display_height,
1635
                      255);
1636
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1637
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1638
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1639
            st->codec->sample_rate = track->audio.out_samplerate;
1640
            st->codec->channels = track->audio.channels;
1641
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1642
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1643
        }
1644

    
1645
        /* What do we do with private data? E.g. for Vorbis. */
1646
    }
1647

    
1648
    attachements = attachements_list->elem;
1649
    for (j=0; j<attachements_list->nb_elem; j++) {
1650
        if (!(attachements[j].filename && attachements[j].mime &&
1651
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1652
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1653
        } else {
1654
            AVStream *st = av_new_stream(s, matroska->num_streams++);
1655
            if (st == NULL)
1656
                break;
1657
            st->filename          = av_strdup(attachements[j].filename);
1658
            st->codec->codec_id = CODEC_ID_NONE;
1659
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1660
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1661
            if(st->codec->extradata == NULL)
1662
                break;
1663
            st->codec->extradata_size = attachements[j].bin.size;
1664
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1665

    
1666
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1667
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1668
                             strlen(ff_mkv_mime_tags[i].str))) {
1669
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1670
                    break;
1671
                }
1672
            }
1673
        }
1674
    }
1675

    
1676
    chapters = chapters_list->elem;
1677
    for (i=0; i<chapters_list->nb_elem; i++)
1678
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1679
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1680
                           chapters[i].start, chapters[i].end,
1681
                           chapters[i].title);
1682

    
1683
    index_list = &matroska->index;
1684
    index = index_list->elem;
1685
    for (i=0; i<index_list->nb_elem; i++) {
1686
        EbmlList *pos_list = &index[i].pos;
1687
        MatroskaIndexPos *pos = pos_list->elem;
1688
        for (j=0; j<pos_list->nb_elem; j++) {
1689
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1690
                                                              pos[j].track);
1691
            if (track && track->stream)
1692
                av_add_index_entry(track->stream,
1693
                                   pos[j].pos + matroska->segment_start,
1694
                                   index[i].time*matroska->time_scale/AV_TIME_BASE,
1695
                                   0, 0, AVINDEX_KEYFRAME);
1696
        }
1697
    }
1698

    
1699
    return 0;
1700
}
1701

    
1702
static int
1703
matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
1704
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
1705
                     int is_keyframe)
1706
{
1707
    MatroskaTrack *track;
1708
    int res = 0;
1709
    AVStream *st;
1710
    AVPacket *pkt;
1711
    int16_t block_time;
1712
    uint32_t *lace_size = NULL;
1713
    int n, flags, laces = 0;
1714
    uint64_t num;
1715

    
1716
    /* first byte(s): tracknum */
1717
    if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1718
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1719
        return res;
1720
    }
1721
    data += n;
1722
    size -= n;
1723

    
1724
    /* fetch track from num */
1725
    track = matroska_find_track_by_num(matroska, num);
1726
    if (size <= 3 || !track || !track->stream) {
1727
        av_log(matroska->ctx, AV_LOG_INFO,
1728
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1729
        return res;
1730
    }
1731
    st = track->stream;
1732
    if (st->discard >= AVDISCARD_ALL) {
1733
        return res;
1734
    }
1735
    if (duration == AV_NOPTS_VALUE)
1736
        duration = track->default_duration / matroska->time_scale;
1737

    
1738
    /* block_time (relative to cluster time) */
1739
    block_time = AV_RB16(data);
1740
    data += 2;
1741
    flags = *data++;
1742
    size -= 3;
1743
    if (is_keyframe == -1)
1744
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1745

    
1746
    if (matroska->skip_to_keyframe) {
1747
        if (!is_keyframe || st != matroska->skip_to_stream) {
1748
            return res;
1749
        }
1750
        matroska->skip_to_keyframe = 0;
1751
    }
1752

    
1753
    switch ((flags & 0x06) >> 1) {
1754
        case 0x0: /* no lacing */
1755
            laces = 1;
1756
            lace_size = av_mallocz(sizeof(int));
1757
            lace_size[0] = size;
1758
            break;
1759

    
1760
        case 0x1: /* xiph lacing */
1761
        case 0x2: /* fixed-size lacing */
1762
        case 0x3: /* EBML lacing */
1763
            assert(size>0); // size <=3 is checked before size-=3 above
1764
            laces = (*data) + 1;
1765
            data += 1;
1766
            size -= 1;
1767
            lace_size = av_mallocz(laces * sizeof(int));
1768

    
1769
            switch ((flags & 0x06) >> 1) {
1770
                case 0x1: /* xiph lacing */ {
1771
                    uint8_t temp;
1772
                    uint32_t total = 0;
1773
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1774
                        while (1) {
1775
                            if (size == 0) {
1776
                                res = -1;
1777
                                break;
1778
                            }
1779
                            temp = *data;
1780
                            lace_size[n] += temp;
1781
                            data += 1;
1782
                            size -= 1;
1783
                            if (temp != 0xff)
1784
                                break;
1785
                        }
1786
                        total += lace_size[n];
1787
                    }
1788
                    lace_size[n] = size - total;
1789
                    break;
1790
                }
1791

    
1792
                case 0x2: /* fixed-size lacing */
1793
                    for (n = 0; n < laces; n++)
1794
                        lace_size[n] = size / laces;
1795
                    break;
1796

    
1797
                case 0x3: /* EBML lacing */ {
1798
                    uint32_t total;
1799
                    n = matroska_ebmlnum_uint(data, size, &num);
1800
                    if (n < 0) {
1801
                        av_log(matroska->ctx, AV_LOG_INFO,
1802
                               "EBML block data error\n");
1803
                        break;
1804
                    }
1805
                    data += n;
1806
                    size -= n;
1807
                    total = lace_size[0] = num;
1808
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1809
                        int64_t snum;
1810
                        int r;
1811
                        r = matroska_ebmlnum_sint (data, size, &snum);
1812
                        if (r < 0) {
1813
                            av_log(matroska->ctx, AV_LOG_INFO,
1814
                                   "EBML block data error\n");
1815
                            break;
1816
                        }
1817
                        data += r;
1818
                        size -= r;
1819
                        lace_size[n] = lace_size[n - 1] + snum;
1820
                        total += lace_size[n];
1821
                    }
1822
                    lace_size[n] = size - total;
1823
                    break;
1824
                }
1825
            }
1826
            break;
1827
    }
1828

    
1829
    if (res == 0) {
1830
        uint64_t timecode = AV_NOPTS_VALUE;
1831

    
1832
        if (cluster_time != (uint64_t)-1
1833
            && (block_time >= 0 || cluster_time >= -block_time))
1834
            timecode = cluster_time + block_time;
1835

    
1836
        for (n = 0; n < laces; n++) {
1837
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1838
                st->codec->codec_id == CODEC_ID_COOK ||
1839
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1840
                int a = st->codec->block_align;
1841
                int sps = track->audio.sub_packet_size;
1842
                int cfs = track->audio.coded_framesize;
1843
                int h = track->audio.sub_packet_h;
1844
                int y = track->audio.sub_packet_cnt;
1845
                int w = track->audio.frame_size;
1846
                int x;
1847

    
1848
                if (!track->audio.pkt_cnt) {
1849
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1850
                        for (x=0; x<h/2; x++)
1851
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1852
                                   data+x*cfs, cfs);
1853
                    else
1854
                        for (x=0; x<w/sps; x++)
1855
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1856

    
1857
                    if (++track->audio.sub_packet_cnt >= h) {
1858
                        track->audio.sub_packet_cnt = 0;
1859
                        track->audio.pkt_cnt = h*w / a;
1860
                    }
1861
                }
1862
                while (track->audio.pkt_cnt) {
1863
                    pkt = av_mallocz(sizeof(AVPacket));
1864
                    av_new_packet(pkt, a);
1865
                    memcpy(pkt->data, track->audio.buf
1866
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1867
                    pkt->pos = pos;
1868
                    pkt->stream_index = st->index;
1869
                    matroska_queue_packet(matroska, pkt);
1870
                }
1871
            } else {
1872
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1873
                int offset = 0, pkt_size = lace_size[n];
1874
                uint8_t *pkt_data = data;
1875

    
1876
                if (encodings && encodings->scope & 1) {
1877
                    offset = matroska_decode_buffer(&pkt_data, &pkt_size,
1878
                                                    track);
1879
                    if (offset < 0)
1880
                        continue;
1881
                }
1882

    
1883
                pkt = av_mallocz(sizeof(AVPacket));
1884
                /* XXX: prevent data copy... */
1885
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1886
                    av_free(pkt);
1887
                    res = AVERROR(ENOMEM);
1888
                    n = laces-1;
1889
                    break;
1890
                }
1891
                if (offset)
1892
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1893
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1894

    
1895
                if (pkt_data != data)
1896
                    av_free(pkt_data);
1897

    
1898
                if (n == 0)
1899
                    pkt->flags = is_keyframe;
1900
                pkt->stream_index = st->index;
1901

    
1902
                pkt->pts = timecode;
1903
                pkt->pos = pos;
1904
                pkt->duration = duration;
1905

    
1906
                matroska_queue_packet(matroska, pkt);
1907
            }
1908

    
1909
            if (timecode != AV_NOPTS_VALUE)
1910
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1911
            data += lace_size[n];
1912
        }
1913
    }
1914

    
1915
    av_free(lace_size);
1916
    return res;
1917
}
1918

    
1919
static int
1920
matroska_parse_cluster (MatroskaDemuxContext *matroska)
1921
{
1922
    MatroskaCluster cluster = { 0 };
1923
    EbmlList *blocks_list;
1924
    MatroskaBlock *blocks;
1925
    int i, res = ebml_parse(matroska, matroska_clusters, &cluster, 0, 1);
1926
    blocks_list = &cluster.blocks;
1927
    blocks = blocks_list->elem;
1928
    for (i=0; !res && i<blocks_list->nb_elem; i++)
1929
        if (blocks[i].bin.size > 0)
1930
            res=matroska_parse_block(matroska,
1931
                                     blocks[i].bin.data, blocks[i].bin.size,
1932
                                     blocks[i].bin.pos,  cluster.timecode,
1933
                                     blocks[i].duration, !blocks[i].reference);
1934
    ebml_free(matroska_cluster, &cluster);
1935
    return res;
1936
}
1937

    
1938
static int
1939
matroska_read_packet (AVFormatContext *s,
1940
                      AVPacket        *pkt)
1941
{
1942
    MatroskaDemuxContext *matroska = s->priv_data;
1943

    
1944
    /* Read stream until we have a packet queued. */
1945
    while (matroska_deliver_packet(matroska, pkt)) {
1946

    
1947
        /* Have we already reached the end? */
1948
        if (matroska->done)
1949
            return AVERROR(EIO);
1950

    
1951
        if (matroska_parse_cluster(matroska) < 0)
1952
            matroska->done = 1;
1953
    }
1954

    
1955
    return 0;
1956
}
1957

    
1958
static int
1959
matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
1960
                    int flags)
1961
{
1962
    MatroskaDemuxContext *matroska = s->priv_data;
1963
    AVStream *st = s->streams[stream_index];
1964
    int index;
1965

    
1966
    /* find index entry */
1967
    index = av_index_search_timestamp(st, timestamp, flags);
1968
    if (index < 0)
1969
        return 0;
1970

    
1971
    matroska_clear_queue(matroska);
1972

    
1973
    /* do the seek */
1974
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1975
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1976
    matroska->skip_to_stream = st;
1977
    matroska->peek_id = 0;
1978
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1979
    return 0;
1980
}
1981

    
1982
static int
1983
matroska_read_close (AVFormatContext *s)
1984
{
1985
    MatroskaDemuxContext *matroska = s->priv_data;
1986
    MatroskaTrack *tracks = matroska->tracks.elem;
1987
    int n = 0;
1988

    
1989
    matroska_clear_queue(matroska);
1990

    
1991
    for (n=0; n < matroska->tracks.nb_elem; n++)
1992
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1993
            av_free(tracks[n].audio.buf);
1994
    ebml_free(matroska_segment, matroska);
1995

    
1996
    return 0;
1997
}
1998

    
1999
AVInputFormat matroska_demuxer = {
2000
    "matroska",
2001
    NULL_IF_CONFIG_SMALL("Matroska file format"),
2002
    sizeof(MatroskaDemuxContext),
2003
    matroska_probe,
2004
    matroska_read_header,
2005
    matroska_read_packet,
2006
    matroska_read_close,
2007
    matroska_read_seek,
2008
};