Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ f7b9687c

History | View | Annotate | Download (58 KB)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
140
    AVStream *stream;
141
} MatroskaTrack;
142

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

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

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

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

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

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

    
176
typedef struct {
177
    AVFormatContext *ctx;
178

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

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

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

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

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

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

    
207
    int done;
208
    int has_cluster_id;
209

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
481
    return num;
482
}
483

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

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

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

    
526
    /* read out length */
527
    total &= ~len_mask;
528
    while (n++ < read)
529
        total = (total << 8) | get_byte(pb);
530

    
531
    *number = total;
532

    
533
    return read;
534
}
535

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

    
545
    /* if we re-call this, use our cached ID */
546
    if (matroska->peek_id != 0) {
547
        *id = matroska->peek_id;
548
        return 0;
549
    }
550

    
551
    /* read out the "EBML number", include tag in ID */
552
    if ((read = ebml_read_num(matroska, 4, &total)) < 0)
553
        return read;
554
    *id = matroska->peek_id  = total | (1 << (read * 7));
555

    
556
    return read;
557
}
558

    
559
/*
560
 * Read: element content length.
561
 * Return: the number of bytes read or < 0 on error.
562
 */
563
static int ebml_read_element_length(MatroskaDemuxContext *matroska,
564
                                    uint64_t *length)
565
{
566
    /* clear cache since we're now beyond that data point */
567
    matroska->peek_id = 0;
568

    
569
    /* read out the "EBML number", include tag in ID */
570
    return ebml_read_num(matroska, 8, length);
571
}
572

    
573
/*
574
 * Seek to a given offset.
575
 * 0 is success, -1 is failure.
576
 */
577
static int ebml_read_seek(MatroskaDemuxContext *matroska, offset_t offset)
578
{
579
    ByteIOContext *pb = matroska->ctx->pb;
580

    
581
    /* clear ID cache, if any */
582
    matroska->peek_id = 0;
583

    
584
    return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
585
}
586

    
587
/*
588
 * Read the next element as an unsigned int.
589
 * 0 is success, < 0 is failure.
590
 */
591
static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
592
{
593
    int n = 0;
594

    
595
    if (size < 1 || size > 8)
596
        return AVERROR_INVALIDDATA;
597

    
598
    /* big-endian ordening; build up number */
599
    *num = 0;
600
    while (n++ < size)
601
        *num = (*num << 8) | get_byte(pb);
602

    
603
    return 0;
604
}
605

    
606
/*
607
 * Read the next element as a float.
608
 * 0 is success, < 0 is failure.
609
 */
610
static int ebml_read_float(ByteIOContext *pb, int size, double *num)
611
{
612
    if (size == 4) {
613
        *num= av_int2flt(get_be32(pb));
614
    } else if(size==8){
615
        *num= av_int2dbl(get_be64(pb));
616
    } else
617
        return AVERROR_INVALIDDATA;
618

    
619
    return 0;
620
}
621

    
622
/*
623
 * Read the next element as an ASCII string.
624
 * 0 is success, < 0 is failure.
625
 */
626
static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
627
{
628
    av_free(*str);
629
    /* ebml strings are usually not 0-terminated, so we allocate one
630
     * byte more, read the string and NULL-terminate it ourselves. */
631
    if (!(*str = av_malloc(size + 1)))
632
        return AVERROR(ENOMEM);
633
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
634
        av_free(*str);
635
        return AVERROR(EIO);
636
    }
637
    (*str)[size] = '\0';
638

    
639
    return 0;
640
}
641

    
642
/*
643
 * Read the next element, but only the header. The contents
644
 * are supposed to be sub-elements which can be read separately.
645
 * 0 is success, < 0 is failure.
646
 */
647
static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
648
{
649
    ByteIOContext *pb = matroska->ctx->pb;
650
    MatroskaLevel *level;
651

    
652
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
653
        av_log(matroska->ctx, AV_LOG_ERROR,
654
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
655
        return AVERROR(ENOSYS);
656
    }
657

    
658
    level = &matroska->levels[matroska->num_levels++];
659
    level->start = url_ftell(pb);
660
    level->length = length;
661

    
662
    return 0;
663
}
664

    
665
/*
666
 * Read the next element as binary data.
667
 * 0 is success, < 0 is failure.
668
 */
669
static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
670
{
671
    av_free(bin->data);
672
    if (!(bin->data = av_malloc(length)))
673
        return AVERROR(ENOMEM);
674

    
675
    bin->size = length;
676
    bin->pos  = url_ftell(pb);
677
    if (get_buffer(pb, bin->data, length) != length)
678
        return AVERROR(EIO);
679

    
680
    return 0;
681
}
682

    
683
/*
684
 * Read signed/unsigned "EBML" numbers.
685
 * Return: number of bytes processed, < 0 on error.
686
 * XXX: use ebml_read_num().
687
 */
688
static int matroska_ebmlnum_uint(uint8_t *data, uint32_t size, uint64_t *num)
689
{
690
    int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
691
    uint64_t total;
692

    
693
    if (size <= 0)
694
        return AVERROR_INVALIDDATA;
695

    
696
    total = data[0];
697
    while (read <= 8 && !(total & len_mask)) {
698
        read++;
699
        len_mask >>= 1;
700
    }
701
    if (read > 8)
702
        return AVERROR_INVALIDDATA;
703

    
704
    if ((total &= (len_mask - 1)) == len_mask - 1)
705
        num_ffs++;
706
    if (size < read)
707
        return AVERROR_INVALIDDATA;
708
    while (n < read) {
709
        if (data[n] == 0xff)
710
            num_ffs++;
711
        total = (total << 8) | data[n];
712
        n++;
713
    }
714

    
715
    if (read == num_ffs)
716
        *num = (uint64_t)-1;
717
    else
718
        *num = total;
719

    
720
    return read;
721
}
722

    
723
/*
724
 * Same as above, but signed.
725
 */
726
static int matroska_ebmlnum_sint(uint8_t *data, uint32_t size, int64_t *num)
727
{
728
    uint64_t unum;
729
    int res;
730

    
731
    /* read as unsigned number first */
732
    if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
733
        return res;
734

    
735
    /* make signed (weird way) */
736
    if (unum == (uint64_t)-1)
737
        *num = INT64_MAX;
738
    else
739
        *num = unum - ((1LL << ((7 * res) - 1)) - 1);
740

    
741
    return res;
742
}
743

    
744

    
745
static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
746
                                                 int num)
747
{
748
    MatroskaTrack *tracks = matroska->tracks.elem;
749
    int i;
750

    
751
    for (i=0; i < matroska->tracks.nb_elem; i++)
752
        if (tracks[i].num == num)
753
            return &tracks[i];
754

    
755
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
756
    return NULL;
757
}
758

    
759

    
760
/*
761
 * Put one packet in an application-supplied AVPacket struct.
762
 * Returns 0 on success or -1 on failure.
763
 */
764
static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
765
                                   AVPacket *pkt)
766
{
767
    if (matroska->num_packets > 0) {
768
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
769
        av_free(matroska->packets[0]);
770
        if (matroska->num_packets > 1) {
771
            memmove(&matroska->packets[0], &matroska->packets[1],
772
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
773
            matroska->packets =
774
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
775
                           sizeof(AVPacket *));
776
        } else {
777
            av_freep(&matroska->packets);
778
        }
779
        matroska->num_packets--;
780
        return 0;
781
    }
782

    
783
    return -1;
784
}
785

    
786
/*
787
 * Put a packet into our internal queue. Will be delivered to the
788
 * user/application during the next get_packet() call.
789
 */
790
static void matroska_queue_packet(MatroskaDemuxContext *matroska, AVPacket *pkt)
791
{
792
    matroska->packets =
793
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
794
                   sizeof(AVPacket *));
795
    matroska->packets[matroska->num_packets] = pkt;
796
    matroska->num_packets++;
797
}
798

    
799
/*
800
 * Free all packets in our internal queue.
801
 */
802
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
803
{
804
    if (matroska->packets) {
805
        int n;
806
        for (n = 0; n < matroska->num_packets; n++) {
807
            av_free_packet(matroska->packets[n]);
808
            av_free(matroska->packets[n]);
809
        }
810
        av_free(matroska->packets);
811
        matroska->packets = NULL;
812
        matroska->num_packets = 0;
813
    }
814
}
815

    
816

    
817
/*
818
 * Autodetecting...
819
 */
820
static int matroska_probe(AVProbeData *p)
821
{
822
    uint64_t total = 0;
823
    int len_mask = 0x80, size = 1, n = 1;
824
    char probe_data[] = "matroska";
825

    
826
    /* ebml header? */
827
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
828
        return 0;
829

    
830
    /* length of header */
831
    total = p->buf[4];
832
    while (size <= 8 && !(total & len_mask)) {
833
        size++;
834
        len_mask >>= 1;
835
    }
836
    if (size > 8)
837
      return 0;
838
    total &= (len_mask - 1);
839
    while (n < size)
840
        total = (total << 8) | p->buf[4 + n++];
841

    
842
    /* does the probe data contain the whole header? */
843
    if (p->buf_size < 4 + size + total)
844
      return 0;
845

    
846
    /* the header must contain the document type 'matroska'. For now,
847
     * we don't parse the whole header but simply check for the
848
     * availability of that array of characters inside the header.
849
     * Not fully fool-proof, but good enough. */
850
    for (n = 4+size; n <= 4+size+total-(sizeof(probe_data)-1); n++)
851
        if (!memcmp(p->buf+n, probe_data, sizeof(probe_data)-1))
852
            return AVPROBE_SCORE_MAX;
853

    
854
    return 0;
855
}
856

    
857
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
858
                      void *data, int once);
859

    
860
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
861
                           EbmlSyntax *syntax, void *data)
862
{
863
    ByteIOContext *pb = matroska->ctx->pb;
864
    uint32_t id = syntax->id;
865
    uint64_t length;
866
    int res;
867

    
868
    data = (char *)data + syntax->data_offset;
869
    if (syntax->list_elem_size) {
870
        EbmlList *list = data;
871
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
872
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
873
        memset(data, 0, syntax->list_elem_size);
874
        list->nb_elem++;
875
    }
876

    
877
    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
878
        if ((res = ebml_read_element_id(matroska, &id)) < 0 ||
879
            (res = ebml_read_element_length(matroska, &length)) < 0)
880
            return res;
881

    
882
    switch (syntax->type) {
883
    case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
884
    case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
885
    case EBML_STR:
886
    case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
887
    case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
888
    case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
889
                         return res;
890
                     if (id == MATROSKA_ID_SEGMENT)
891
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
892
                     return ebml_parse(matroska, syntax->def.n, data, 0);
893
    case EBML_PASS:  return ebml_parse(matroska, syntax->def.n, data, 1);
894
    case EBML_STOP:  *(int *)data = 1;      return 1;
895
    default:         url_fskip(pb, length); return 0;
896
    }
897
    if (res == AVERROR_INVALIDDATA)
898
        av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
899
    else if (res == AVERROR(EIO))
900
        av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
901
    return res;
902
}
903

    
904
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
905
                         uint32_t id, void *data)
906
{
907
    int i;
908
    for (i=0; syntax[i].id; i++)
909
        if (id == syntax[i].id)
910
            break;
911
    if (!syntax[i].id)
912
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
913
    return ebml_parse_elem(matroska, &syntax[i], data);
914
}
915

    
916
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
917
                      void *data, int once)
918
{
919
    int i, res = 0, res2;
920
    uint32_t id = 0;
921

    
922
    for (i=0; syntax[i].id; i++)
923
        switch (syntax[i].type) {
924
        case EBML_UINT:
925
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
926
            break;
927
        case EBML_FLOAT:
928
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
929
            break;
930
        case EBML_STR:
931
        case EBML_UTF8:
932
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
933
            break;
934
        }
935

    
936
    while (!res) {
937
        res2 = ebml_read_element_id(matroska, &id);
938
        if (res2 < 0)
939
            break;
940
        if (res2 > 0)
941
            matroska->level_up = ebml_read_element_level_up(matroska);
942
        if (matroska->level_up) {
943
            matroska->level_up--;
944
            break;
945
        }
946

    
947
        res = ebml_parse_id(matroska, syntax, id, data);
948
        if (once)
949
            break;
950
    }
951

    
952
    return res;
953
}
954

    
955
static void ebml_free(EbmlSyntax *syntax, void *data)
956
{
957
    int i, j;
958
    for (i=0; syntax[i].id; i++) {
959
        void *data_off = (char *)data + syntax[i].data_offset;
960
        switch (syntax[i].type) {
961
        case EBML_STR:
962
        case EBML_UTF8:  av_freep(data_off);                      break;
963
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
964
        case EBML_NEST:
965
            if (syntax[i].list_elem_size) {
966
                EbmlList *list = data_off;
967
                char *ptr = list->elem;
968
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
969
                    ebml_free(syntax[i].def.n, ptr);
970
                av_free(list->elem);
971
            } else
972
                ebml_free(syntax[i].def.n, data_off);
973
        default:  break;
974
        }
975
    }
976
}
977

    
978
static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
979
                                  MatroskaTrack *track)
980
{
981
    MatroskaTrackEncoding *encodings = track->encodings.elem;
982
    uint8_t* data = *buf;
983
    int isize = *buf_size;
984
    uint8_t* pkt_data = NULL;
985
    int pkt_size = isize;
986
    int result = 0;
987
    int olen;
988

    
989
    switch (encodings[0].compression.algo) {
990
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
991
        return encodings[0].compression.settings.size;
992
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
993
        do {
994
            olen = pkt_size *= 3;
995
            pkt_data = av_realloc(pkt_data,
996
                                  pkt_size+LZO_OUTPUT_PADDING);
997
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
998
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
999
        if (result)
1000
            goto failed;
1001
        pkt_size -= olen;
1002
        break;
1003
#ifdef CONFIG_ZLIB
1004
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1005
        z_stream zstream = {0};
1006
        if (inflateInit(&zstream) != Z_OK)
1007
            return -1;
1008
        zstream.next_in = data;
1009
        zstream.avail_in = isize;
1010
        do {
1011
            pkt_size *= 3;
1012
            pkt_data = av_realloc(pkt_data, pkt_size);
1013
            zstream.avail_out = pkt_size - zstream.total_out;
1014
            zstream.next_out = pkt_data + zstream.total_out;
1015
            result = inflate(&zstream, Z_NO_FLUSH);
1016
        } while (result==Z_OK && pkt_size<10000000);
1017
        pkt_size = zstream.total_out;
1018
        inflateEnd(&zstream);
1019
        if (result != Z_STREAM_END)
1020
            goto failed;
1021
        break;
1022
    }
1023
#endif
1024
#ifdef CONFIG_BZLIB
1025
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1026
        bz_stream bzstream = {0};
1027
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1028
            return -1;
1029
        bzstream.next_in = data;
1030
        bzstream.avail_in = isize;
1031
        do {
1032
            pkt_size *= 3;
1033
            pkt_data = av_realloc(pkt_data, pkt_size);
1034
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1035
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1036
            result = BZ2_bzDecompress(&bzstream);
1037
        } while (result==BZ_OK && pkt_size<10000000);
1038
        pkt_size = bzstream.total_out_lo32;
1039
        BZ2_bzDecompressEnd(&bzstream);
1040
        if (result != BZ_STREAM_END)
1041
            goto failed;
1042
        break;
1043
    }
1044
#endif
1045
    }
1046

    
1047
    *buf = pkt_data;
1048
    *buf_size = pkt_size;
1049
    return 0;
1050
 failed:
1051
    av_free(pkt_data);
1052
    return -1;
1053
}
1054

    
1055
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1056
{
1057
    EbmlList *seekhead_list = &matroska->seekhead;
1058
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1059
    uint32_t peek_id_cache = matroska->peek_id;
1060
    uint32_t level_up = matroska->level_up;
1061
    offset_t before_pos = url_ftell(matroska->ctx->pb);
1062
    MatroskaLevel level;
1063
    int i;
1064

    
1065
    for (i=0; i<seekhead_list->nb_elem; i++) {
1066
        if (seekhead[i].pos <= before_pos
1067
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1068
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1069
            continue;
1070

    
1071
        /* seek */
1072
        if (ebml_read_seek(matroska,
1073
                           seekhead[i].pos+matroska->segment_start) < 0)
1074
            continue;
1075

    
1076
        /* we don't want to lose our seekhead level, so we add
1077
         * a dummy. This is a crude hack. */
1078
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1079
            av_log(matroska->ctx, AV_LOG_INFO,
1080
                   "Max EBML element depth (%d) reached, "
1081
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1082
            break;
1083
        }
1084

    
1085
        level.start = 0;
1086
        level.length = (uint64_t)-1;
1087
        matroska->levels[matroska->num_levels] = level;
1088
        matroska->num_levels++;
1089

    
1090
        ebml_parse_id(matroska, matroska_segment, seekhead[i].id, matroska);
1091

    
1092
        /* remove dummy level */
1093
        while (matroska->num_levels) {
1094
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1095
            if (length == (uint64_t)-1)
1096
                break;
1097
        }
1098
    }
1099

    
1100
    /* seek back */
1101
    ebml_read_seek(matroska, before_pos);
1102
    matroska->peek_id = peek_id_cache;
1103
    matroska->level_up = level_up;
1104
}
1105

    
1106
static int matroska_aac_profile(char *codec_id)
1107
{
1108
    static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
1109
    int profile;
1110

    
1111
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1112
        if (strstr(codec_id, aac_profiles[profile]))
1113
            break;
1114
    return profile + 1;
1115
}
1116

    
1117
static int matroska_aac_sri(int samplerate)
1118
{
1119
    int sri;
1120

    
1121
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1122
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1123
            break;
1124
    return sri;
1125
}
1126

    
1127
static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1128
{
1129
    MatroskaDemuxContext *matroska = s->priv_data;
1130
    EbmlList *attachements_list = &matroska->attachments;
1131
    MatroskaAttachement *attachements;
1132
    EbmlList *chapters_list = &matroska->chapters;
1133
    MatroskaChapter *chapters;
1134
    MatroskaTrack *tracks;
1135
    EbmlList *index_list;
1136
    MatroskaIndex *index;
1137
    Ebml ebml = { 0 };
1138
    AVStream *st;
1139
    int i, j;
1140

    
1141
    matroska->ctx = s;
1142

    
1143
    /* First read the EBML header. */
1144
    if (ebml_parse(matroska, ebml_syntax, &ebml, 1)
1145
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1146
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1147
        || ebml.doctype_version > 2) {
1148
        av_log(matroska->ctx, AV_LOG_ERROR,
1149
               "EBML header using unsupported features\n"
1150
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1151
               ebml.version, ebml.doctype, ebml.doctype_version);
1152
        return AVERROR_NOFMT;
1153
    }
1154
    ebml_free(ebml_syntax, &ebml);
1155

    
1156
    /* The next thing is a segment. */
1157
    if (ebml_parse(matroska, matroska_segments, matroska, 1) < 0)
1158
        return -1;
1159
    matroska_execute_seekhead(matroska);
1160

    
1161
    if (matroska->duration)
1162
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1163
                                  * 1000 / AV_TIME_BASE;
1164
    if (matroska->title)
1165
        strncpy(matroska->ctx->title, matroska->title,
1166
                sizeof(matroska->ctx->title)-1);
1167

    
1168
    tracks = matroska->tracks.elem;
1169
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1170
        MatroskaTrack *track = &tracks[i];
1171
        enum CodecID codec_id = CODEC_ID_NONE;
1172
        EbmlList *encodings_list = &tracks->encodings;
1173
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1174
        uint8_t *extradata = NULL;
1175
        int extradata_size = 0;
1176
        int extradata_offset = 0;
1177

    
1178
        /* Apply some sanity checks. */
1179
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1180
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1181
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1182
            av_log(matroska->ctx, AV_LOG_INFO,
1183
                   "Unknown or unsupported track type %"PRIu64"\n",
1184
                   track->type);
1185
            continue;
1186
        }
1187
        if (track->codec_id == NULL)
1188
            continue;
1189

    
1190
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1191
            if (!track->default_duration)
1192
                track->default_duration = 1000000000/track->video.frame_rate;
1193
            if (!track->video.display_width)
1194
                track->video.display_width = track->video.pixel_width;
1195
            if (!track->video.display_height)
1196
                track->video.display_height = track->video.pixel_height;
1197
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1198
            if (!track->audio.out_samplerate)
1199
                track->audio.out_samplerate = track->audio.samplerate;
1200
        }
1201
        if (encodings_list->nb_elem > 1) {
1202
            av_log(matroska->ctx, AV_LOG_ERROR,
1203
                   "Multiple combined encodings no supported");
1204
        } else if (encodings_list->nb_elem == 1) {
1205
            if (encodings[0].type ||
1206
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1207
#ifdef CONFIG_ZLIB
1208
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1209
#endif
1210
#ifdef CONFIG_BZLIB
1211
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1212
#endif
1213
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1214
                encodings[0].scope = 0;
1215
                av_log(matroska->ctx, AV_LOG_ERROR,
1216
                       "Unsupported encoding type");
1217
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1218
                uint8_t *codec_priv = track->codec_priv.data;
1219
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1220
                                                    &track->codec_priv.size,
1221
                                                    track);
1222
                if (offset < 0) {
1223
                    track->codec_priv.data = NULL;
1224
                    track->codec_priv.size = 0;
1225
                    av_log(matroska->ctx, AV_LOG_ERROR,
1226
                           "Failed to decode codec private data\n");
1227
                } else if (offset > 0) {
1228
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1229
                    memcpy(track->codec_priv.data,
1230
                           encodings[0].compression.settings.data, offset);
1231
                    memcpy(track->codec_priv.data+offset, codec_priv,
1232
                           track->codec_priv.size);
1233
                    track->codec_priv.size += offset;
1234
                }
1235
                if (codec_priv != track->codec_priv.data)
1236
                    av_free(codec_priv);
1237
            }
1238
        }
1239

    
1240
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1241
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1242
                        strlen(ff_mkv_codec_tags[j].str))){
1243
                codec_id= ff_mkv_codec_tags[j].id;
1244
                break;
1245
            }
1246
        }
1247

    
1248
        st = track->stream = av_new_stream(s, matroska->num_streams++);
1249
        if (st == NULL)
1250
            return AVERROR(ENOMEM);
1251

    
1252
        if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)
1253
            && track->codec_priv.size >= 40
1254
            && track->codec_priv.data != NULL) {
1255
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1256
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1257
        } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_AUDIO_ACM)
1258
                   && track->codec_priv.size >= 18
1259
                   && track->codec_priv.data != NULL) {
1260
            uint16_t tag = AV_RL16(track->codec_priv.data);
1261
            codec_id = codec_get_id(codec_wav_tags, tag);
1262
        } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1263
                   && (track->codec_priv.size >= 86)
1264
                   && (track->codec_priv.data != NULL)) {
1265
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1266
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1267
        } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1268
            int profile = matroska_aac_profile(track->codec_id);
1269
            int sri = matroska_aac_sri(track->audio.samplerate);
1270
            extradata = av_malloc(5);
1271
            if (extradata == NULL)
1272
                return AVERROR(ENOMEM);
1273
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1274
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1275
            if (strstr(track->codec_id, "SBR")) {
1276
                sri = matroska_aac_sri(track->audio.out_samplerate);
1277
                extradata[2] = 0x56;
1278
                extradata[3] = 0xE5;
1279
                extradata[4] = 0x80 | (sri<<3);
1280
                extradata_size = 5;
1281
            } else
1282
                extradata_size = 2;
1283
        } else if (codec_id == CODEC_ID_TTA) {
1284
            ByteIOContext b;
1285
            extradata_size = 30;
1286
            extradata = av_mallocz(extradata_size);
1287
            if (extradata == NULL)
1288
                return AVERROR(ENOMEM);
1289
            init_put_byte(&b, extradata, extradata_size, 1,
1290
                          NULL, NULL, NULL, NULL);
1291
            put_buffer(&b, "TTA1", 4);
1292
            put_le16(&b, 1);
1293
            put_le16(&b, track->audio.channels);
1294
            put_le16(&b, track->audio.bitdepth);
1295
            put_le32(&b, track->audio.out_samplerate);
1296
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1297
        } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1298
                   codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1299
            extradata_offset = 26;
1300
            track->codec_priv.size -= extradata_offset;
1301
        } else if (codec_id == CODEC_ID_RA_144) {
1302
            track->audio.out_samplerate = 8000;
1303
            track->audio.channels = 1;
1304
        } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1305
                   codec_id == CODEC_ID_ATRAC3) {
1306
            ByteIOContext b;
1307

    
1308
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1309
                          0, NULL, NULL, NULL, NULL);
1310
            url_fskip(&b, 24);
1311
            track->audio.coded_framesize = get_be32(&b);
1312
            url_fskip(&b, 12);
1313
            track->audio.sub_packet_h    = get_be16(&b);
1314
            track->audio.frame_size      = get_be16(&b);
1315
            track->audio.sub_packet_size = get_be16(&b);
1316
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1317
            if (codec_id == CODEC_ID_RA_288) {
1318
                st->codec->block_align = track->audio.coded_framesize;
1319
                track->codec_priv.size = 0;
1320
            } else {
1321
                st->codec->block_align = track->audio.sub_packet_size;
1322
                extradata_offset = 78;
1323
                track->codec_priv.size -= extradata_offset;
1324
            }
1325
        }
1326

    
1327
        if (codec_id == CODEC_ID_NONE)
1328
            av_log(matroska->ctx, AV_LOG_INFO,
1329
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1330

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

    
1333
        st->codec->codec_id = codec_id;
1334
        st->start_time = 0;
1335
        if (strcmp(track->language, "und"))
1336
            av_strlcpy(st->language, track->language, 4);
1337

    
1338
        if (track->flag_default)
1339
            st->disposition |= AV_DISPOSITION_DEFAULT;
1340

    
1341
        if (track->default_duration)
1342
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1343
                      track->default_duration, 1000000000, 30000);
1344

    
1345
        if(extradata){
1346
            st->codec->extradata = extradata;
1347
            st->codec->extradata_size = extradata_size;
1348
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1349
            st->codec->extradata = av_malloc(track->codec_priv.size);
1350
            if(st->codec->extradata == NULL)
1351
                return AVERROR(ENOMEM);
1352
            st->codec->extradata_size = track->codec_priv.size;
1353
            memcpy(st->codec->extradata,
1354
                   track->codec_priv.data + extradata_offset,
1355
                   track->codec_priv.size);
1356
        }
1357

    
1358
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1359
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1360
            st->codec->codec_tag  = track->video.fourcc;
1361
            st->codec->width  = track->video.pixel_width;
1362
            st->codec->height = track->video.pixel_height;
1363
            av_reduce(&st->codec->sample_aspect_ratio.num,
1364
                      &st->codec->sample_aspect_ratio.den,
1365
                      st->codec->height * track->video.display_width,
1366
                      st->codec-> width * track->video.display_height,
1367
                      255);
1368
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1369
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1370
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1371
            st->codec->sample_rate = track->audio.out_samplerate;
1372
            st->codec->channels = track->audio.channels;
1373
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1374
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1375
        }
1376
    }
1377

    
1378
    attachements = attachements_list->elem;
1379
    for (j=0; j<attachements_list->nb_elem; j++) {
1380
        if (!(attachements[j].filename && attachements[j].mime &&
1381
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1382
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1383
        } else {
1384
            AVStream *st = av_new_stream(s, matroska->num_streams++);
1385
            if (st == NULL)
1386
                break;
1387
            st->filename          = av_strdup(attachements[j].filename);
1388
            st->codec->codec_id = CODEC_ID_NONE;
1389
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1390
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1391
            if(st->codec->extradata == NULL)
1392
                break;
1393
            st->codec->extradata_size = attachements[j].bin.size;
1394
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1395

    
1396
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1397
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1398
                             strlen(ff_mkv_mime_tags[i].str))) {
1399
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1400
                    break;
1401
                }
1402
            }
1403
        }
1404
    }
1405

    
1406
    chapters = chapters_list->elem;
1407
    for (i=0; i<chapters_list->nb_elem; i++)
1408
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1409
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1410
                           chapters[i].start, chapters[i].end,
1411
                           chapters[i].title);
1412

    
1413
    index_list = &matroska->index;
1414
    index = index_list->elem;
1415
    for (i=0; i<index_list->nb_elem; i++) {
1416
        EbmlList *pos_list = &index[i].pos;
1417
        MatroskaIndexPos *pos = pos_list->elem;
1418
        for (j=0; j<pos_list->nb_elem; j++) {
1419
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1420
                                                              pos[j].track);
1421
            if (track && track->stream)
1422
                av_add_index_entry(track->stream,
1423
                                   pos[j].pos + matroska->segment_start,
1424
                                   index[i].time*matroska->time_scale/AV_TIME_BASE,
1425
                                   0, 0, AVINDEX_KEYFRAME);
1426
        }
1427
    }
1428

    
1429
    return 0;
1430
}
1431

    
1432
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1433
                                int size, int64_t pos, uint64_t cluster_time,
1434
                                uint64_t duration, int is_keyframe)
1435
{
1436
    MatroskaTrack *track;
1437
    int res = 0;
1438
    AVStream *st;
1439
    AVPacket *pkt;
1440
    int16_t block_time;
1441
    uint32_t *lace_size = NULL;
1442
    int n, flags, laces = 0;
1443
    uint64_t num;
1444

    
1445
    if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1446
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1447
        return res;
1448
    }
1449
    data += n;
1450
    size -= n;
1451

    
1452
    track = matroska_find_track_by_num(matroska, num);
1453
    if (size <= 3 || !track || !track->stream) {
1454
        av_log(matroska->ctx, AV_LOG_INFO,
1455
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1456
        return res;
1457
    }
1458
    st = track->stream;
1459
    if (st->discard >= AVDISCARD_ALL)
1460
        return res;
1461
    if (duration == AV_NOPTS_VALUE)
1462
        duration = track->default_duration / matroska->time_scale;
1463

    
1464
    block_time = AV_RB16(data);
1465
    data += 2;
1466
    flags = *data++;
1467
    size -= 3;
1468
    if (is_keyframe == -1)
1469
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1470

    
1471
    if (matroska->skip_to_keyframe) {
1472
        if (!is_keyframe || st != matroska->skip_to_stream)
1473
            return res;
1474
        matroska->skip_to_keyframe = 0;
1475
    }
1476

    
1477
    switch ((flags & 0x06) >> 1) {
1478
        case 0x0: /* no lacing */
1479
            laces = 1;
1480
            lace_size = av_mallocz(sizeof(int));
1481
            lace_size[0] = size;
1482
            break;
1483

    
1484
        case 0x1: /* xiph lacing */
1485
        case 0x2: /* fixed-size lacing */
1486
        case 0x3: /* EBML lacing */
1487
            assert(size>0); // size <=3 is checked before size-=3 above
1488
            laces = (*data) + 1;
1489
            data += 1;
1490
            size -= 1;
1491
            lace_size = av_mallocz(laces * sizeof(int));
1492

    
1493
            switch ((flags & 0x06) >> 1) {
1494
                case 0x1: /* xiph lacing */ {
1495
                    uint8_t temp;
1496
                    uint32_t total = 0;
1497
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1498
                        while (1) {
1499
                            if (size == 0) {
1500
                                res = -1;
1501
                                break;
1502
                            }
1503
                            temp = *data;
1504
                            lace_size[n] += temp;
1505
                            data += 1;
1506
                            size -= 1;
1507
                            if (temp != 0xff)
1508
                                break;
1509
                        }
1510
                        total += lace_size[n];
1511
                    }
1512
                    lace_size[n] = size - total;
1513
                    break;
1514
                }
1515

    
1516
                case 0x2: /* fixed-size lacing */
1517
                    for (n = 0; n < laces; n++)
1518
                        lace_size[n] = size / laces;
1519
                    break;
1520

    
1521
                case 0x3: /* EBML lacing */ {
1522
                    uint32_t total;
1523
                    n = matroska_ebmlnum_uint(data, size, &num);
1524
                    if (n < 0) {
1525
                        av_log(matroska->ctx, AV_LOG_INFO,
1526
                               "EBML block data error\n");
1527
                        break;
1528
                    }
1529
                    data += n;
1530
                    size -= n;
1531
                    total = lace_size[0] = num;
1532
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1533
                        int64_t snum;
1534
                        int r;
1535
                        r = matroska_ebmlnum_sint (data, size, &snum);
1536
                        if (r < 0) {
1537
                            av_log(matroska->ctx, AV_LOG_INFO,
1538
                                   "EBML block data error\n");
1539
                            break;
1540
                        }
1541
                        data += r;
1542
                        size -= r;
1543
                        lace_size[n] = lace_size[n - 1] + snum;
1544
                        total += lace_size[n];
1545
                    }
1546
                    lace_size[n] = size - total;
1547
                    break;
1548
                }
1549
            }
1550
            break;
1551
    }
1552

    
1553
    if (res == 0) {
1554
        uint64_t timecode = AV_NOPTS_VALUE;
1555

    
1556
        if (cluster_time != (uint64_t)-1
1557
            && (block_time >= 0 || cluster_time >= -block_time))
1558
            timecode = cluster_time + block_time;
1559

    
1560
        for (n = 0; n < laces; n++) {
1561
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1562
                st->codec->codec_id == CODEC_ID_COOK ||
1563
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1564
                int a = st->codec->block_align;
1565
                int sps = track->audio.sub_packet_size;
1566
                int cfs = track->audio.coded_framesize;
1567
                int h = track->audio.sub_packet_h;
1568
                int y = track->audio.sub_packet_cnt;
1569
                int w = track->audio.frame_size;
1570
                int x;
1571

    
1572
                if (!track->audio.pkt_cnt) {
1573
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1574
                        for (x=0; x<h/2; x++)
1575
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1576
                                   data+x*cfs, cfs);
1577
                    else
1578
                        for (x=0; x<w/sps; x++)
1579
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1580

    
1581
                    if (++track->audio.sub_packet_cnt >= h) {
1582
                        track->audio.sub_packet_cnt = 0;
1583
                        track->audio.pkt_cnt = h*w / a;
1584
                    }
1585
                }
1586
                while (track->audio.pkt_cnt) {
1587
                    pkt = av_mallocz(sizeof(AVPacket));
1588
                    av_new_packet(pkt, a);
1589
                    memcpy(pkt->data, track->audio.buf
1590
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1591
                    pkt->pos = pos;
1592
                    pkt->stream_index = st->index;
1593
                    matroska_queue_packet(matroska, pkt);
1594
                }
1595
            } else {
1596
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1597
                int offset = 0, pkt_size = lace_size[n];
1598
                uint8_t *pkt_data = data;
1599

    
1600
                if (encodings && encodings->scope & 1) {
1601
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1602
                    if (offset < 0)
1603
                        continue;
1604
                }
1605

    
1606
                pkt = av_mallocz(sizeof(AVPacket));
1607
                /* XXX: prevent data copy... */
1608
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1609
                    av_free(pkt);
1610
                    res = AVERROR(ENOMEM);
1611
                    n = laces-1;
1612
                    break;
1613
                }
1614
                if (offset)
1615
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1616
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1617

    
1618
                if (pkt_data != data)
1619
                    av_free(pkt_data);
1620

    
1621
                if (n == 0)
1622
                    pkt->flags = is_keyframe;
1623
                pkt->stream_index = st->index;
1624

    
1625
                pkt->pts = timecode;
1626
                pkt->pos = pos;
1627
                pkt->duration = duration;
1628

    
1629
                matroska_queue_packet(matroska, pkt);
1630
            }
1631

    
1632
            if (timecode != AV_NOPTS_VALUE)
1633
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1634
            data += lace_size[n];
1635
        }
1636
    }
1637

    
1638
    av_free(lace_size);
1639
    return res;
1640
}
1641

    
1642
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1643
{
1644
    MatroskaCluster cluster = { 0 };
1645
    EbmlList *blocks_list;
1646
    MatroskaBlock *blocks;
1647
    int i, res = ebml_parse(matroska, matroska_clusters, &cluster, 1);
1648
    blocks_list = &cluster.blocks;
1649
    blocks = blocks_list->elem;
1650
    for (i=0; !res && i<blocks_list->nb_elem; i++)
1651
        if (blocks[i].bin.size > 0)
1652
            res=matroska_parse_block(matroska,
1653
                                     blocks[i].bin.data, blocks[i].bin.size,
1654
                                     blocks[i].bin.pos,  cluster.timecode,
1655
                                     blocks[i].duration, !blocks[i].reference);
1656
    ebml_free(matroska_cluster, &cluster);
1657
    return res;
1658
}
1659

    
1660
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1661
{
1662
    MatroskaDemuxContext *matroska = s->priv_data;
1663

    
1664
    while (matroska_deliver_packet(matroska, pkt)) {
1665
        if (matroska->done)
1666
            return AVERROR(EIO);
1667
        if (matroska_parse_cluster(matroska) < 0)
1668
            matroska->done = 1;
1669
    }
1670

    
1671
    return 0;
1672
}
1673

    
1674
static int matroska_read_seek(AVFormatContext *s, int stream_index,
1675
                              int64_t timestamp, int flags)
1676
{
1677
    MatroskaDemuxContext *matroska = s->priv_data;
1678
    AVStream *st = s->streams[stream_index];
1679
    int index;
1680

    
1681
    index = av_index_search_timestamp(st, timestamp, flags);
1682
    if (index < 0)
1683
        return 0;
1684

    
1685
    matroska_clear_queue(matroska);
1686

    
1687
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1688
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1689
    matroska->skip_to_stream = st;
1690
    matroska->peek_id = 0;
1691
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1692
    return 0;
1693
}
1694

    
1695
static int matroska_read_close(AVFormatContext *s)
1696
{
1697
    MatroskaDemuxContext *matroska = s->priv_data;
1698
    MatroskaTrack *tracks = matroska->tracks.elem;
1699
    int n;
1700

    
1701
    matroska_clear_queue(matroska);
1702

    
1703
    for (n=0; n < matroska->tracks.nb_elem; n++)
1704
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1705
            av_free(tracks[n].audio.buf);
1706
    ebml_free(matroska_segment, matroska);
1707

    
1708
    return 0;
1709
}
1710

    
1711
AVInputFormat matroska_demuxer = {
1712
    "matroska",
1713
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1714
    sizeof(MatroskaDemuxContext),
1715
    matroska_probe,
1716
    matroska_read_header,
1717
    matroska_read_packet,
1718
    matroska_read_close,
1719
    matroska_read_seek,
1720
};