Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 6314cca0

History | View | Annotate | Download (57.7 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: whether we reached the end of a level in the hierarchy or not
460
 */
461
static int ebml_level_end(MatroskaDemuxContext *matroska)
462
{
463
    ByteIOContext *pb = matroska->ctx->pb;
464
    offset_t pos = url_ftell(pb);
465

    
466
    if (matroska->num_levels > 0) {
467
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
468
        if (pos - level->start >= level->length) {
469
            matroska->num_levels--;
470
            return 1;
471
        }
472
    }
473
    return 0;
474
}
475

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

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

    
505
    /* get the length of the EBML number */
506
    while (read <= max_size && !(total & len_mask)) {
507
        read++;
508
        len_mask >>= 1;
509
    }
510
    if (read > max_size) {
511
        offset_t pos = url_ftell(pb) - 1;
512
        av_log(matroska->ctx, AV_LOG_ERROR,
513
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
514
               (uint8_t) total, pos, pos);
515
        return AVERROR_INVALIDDATA;
516
    }
517

    
518
    /* read out length */
519
    total &= ~len_mask;
520
    while (n++ < read)
521
        total = (total << 8) | get_byte(pb);
522

    
523
    *number = total;
524

    
525
    return read;
526
}
527

    
528
/*
529
 * Read: the element content data ID.
530
 * 0 is success, < 0 is failure.
531
 */
532
static int ebml_read_element_id(MatroskaDemuxContext *matroska, uint32_t *id)
533
{
534
    int read;
535
    uint64_t total;
536

    
537
    /* if we re-call this, use our cached ID */
538
    if (matroska->peek_id != 0) {
539
        *id = matroska->peek_id;
540
        return 0;
541
    }
542

    
543
    /* read out the "EBML number", include tag in ID */
544
    if ((read = ebml_read_num(matroska, 4, &total)) < 0)
545
        return read;
546
    *id = matroska->peek_id  = total | (1 << (read * 7));
547

    
548
    return 0;
549
}
550

    
551
/*
552
 * Read: element content length.
553
 * Return: the number of bytes read or < 0 on error.
554
 */
555
static int ebml_read_element_length(MatroskaDemuxContext *matroska,
556
                                    uint64_t *length)
557
{
558
    /* clear cache since we're now beyond that data point */
559
    matroska->peek_id = 0;
560

    
561
    /* read out the "EBML number", include tag in ID */
562
    return ebml_read_num(matroska, 8, length);
563
}
564

    
565
/*
566
 * Seek to a given offset.
567
 * 0 is success, -1 is failure.
568
 */
569
static int ebml_read_seek(MatroskaDemuxContext *matroska, offset_t offset)
570
{
571
    ByteIOContext *pb = matroska->ctx->pb;
572

    
573
    /* clear ID cache, if any */
574
    matroska->peek_id = 0;
575

    
576
    return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
577
}
578

    
579
/*
580
 * Read the next element as an unsigned int.
581
 * 0 is success, < 0 is failure.
582
 */
583
static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
584
{
585
    int n = 0;
586

    
587
    if (size < 1 || size > 8)
588
        return AVERROR_INVALIDDATA;
589

    
590
    /* big-endian ordening; build up number */
591
    *num = 0;
592
    while (n++ < size)
593
        *num = (*num << 8) | get_byte(pb);
594

    
595
    return 0;
596
}
597

    
598
/*
599
 * Read the next element as a float.
600
 * 0 is success, < 0 is failure.
601
 */
602
static int ebml_read_float(ByteIOContext *pb, int size, double *num)
603
{
604
    if (size == 4) {
605
        *num= av_int2flt(get_be32(pb));
606
    } else if(size==8){
607
        *num= av_int2dbl(get_be64(pb));
608
    } else
609
        return AVERROR_INVALIDDATA;
610

    
611
    return 0;
612
}
613

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

    
631
    return 0;
632
}
633

    
634
/*
635
 * Read the next element, but only the header. The contents
636
 * are supposed to be sub-elements which can be read separately.
637
 * 0 is success, < 0 is failure.
638
 */
639
static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
640
{
641
    ByteIOContext *pb = matroska->ctx->pb;
642
    MatroskaLevel *level;
643

    
644
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
645
        av_log(matroska->ctx, AV_LOG_ERROR,
646
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
647
        return AVERROR(ENOSYS);
648
    }
649

    
650
    level = &matroska->levels[matroska->num_levels++];
651
    level->start = url_ftell(pb);
652
    level->length = length;
653

    
654
    return 0;
655
}
656

    
657
/*
658
 * Read the next element as binary data.
659
 * 0 is success, < 0 is failure.
660
 */
661
static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
662
{
663
    av_free(bin->data);
664
    if (!(bin->data = av_malloc(length)))
665
        return AVERROR(ENOMEM);
666

    
667
    bin->size = length;
668
    bin->pos  = url_ftell(pb);
669
    if (get_buffer(pb, bin->data, length) != length)
670
        return AVERROR(EIO);
671

    
672
    return 0;
673
}
674

    
675
/*
676
 * Read signed/unsigned "EBML" numbers.
677
 * Return: number of bytes processed, < 0 on error.
678
 * XXX: use ebml_read_num().
679
 */
680
static int matroska_ebmlnum_uint(uint8_t *data, uint32_t size, uint64_t *num)
681
{
682
    int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
683
    uint64_t total;
684

    
685
    if (size <= 0)
686
        return AVERROR_INVALIDDATA;
687

    
688
    total = data[0];
689
    while (read <= 8 && !(total & len_mask)) {
690
        read++;
691
        len_mask >>= 1;
692
    }
693
    if (read > 8)
694
        return AVERROR_INVALIDDATA;
695

    
696
    if ((total &= (len_mask - 1)) == len_mask - 1)
697
        num_ffs++;
698
    if (size < read)
699
        return AVERROR_INVALIDDATA;
700
    while (n < read) {
701
        if (data[n] == 0xff)
702
            num_ffs++;
703
        total = (total << 8) | data[n];
704
        n++;
705
    }
706

    
707
    if (read == num_ffs)
708
        *num = (uint64_t)-1;
709
    else
710
        *num = total;
711

    
712
    return read;
713
}
714

    
715
/*
716
 * Same as above, but signed.
717
 */
718
static int matroska_ebmlnum_sint(uint8_t *data, uint32_t size, int64_t *num)
719
{
720
    uint64_t unum;
721
    int res;
722

    
723
    /* read as unsigned number first */
724
    if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
725
        return res;
726

    
727
    /* make signed (weird way) */
728
    if (unum == (uint64_t)-1)
729
        *num = INT64_MAX;
730
    else
731
        *num = unum - ((1LL << ((7 * res) - 1)) - 1);
732

    
733
    return res;
734
}
735

    
736

    
737
static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
738
                                                 int num)
739
{
740
    MatroskaTrack *tracks = matroska->tracks.elem;
741
    int i;
742

    
743
    for (i=0; i < matroska->tracks.nb_elem; i++)
744
        if (tracks[i].num == num)
745
            return &tracks[i];
746

    
747
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
748
    return NULL;
749
}
750

    
751

    
752
/*
753
 * Put one packet in an application-supplied AVPacket struct.
754
 * Returns 0 on success or -1 on failure.
755
 */
756
static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
757
                                   AVPacket *pkt)
758
{
759
    if (matroska->num_packets > 0) {
760
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
761
        av_free(matroska->packets[0]);
762
        if (matroska->num_packets > 1) {
763
            memmove(&matroska->packets[0], &matroska->packets[1],
764
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
765
            matroska->packets =
766
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
767
                           sizeof(AVPacket *));
768
        } else {
769
            av_freep(&matroska->packets);
770
        }
771
        matroska->num_packets--;
772
        return 0;
773
    }
774

    
775
    return -1;
776
}
777

    
778
/*
779
 * Put a packet into our internal queue. Will be delivered to the
780
 * user/application during the next get_packet() call.
781
 */
782
static void matroska_queue_packet(MatroskaDemuxContext *matroska, AVPacket *pkt)
783
{
784
    matroska->packets =
785
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
786
                   sizeof(AVPacket *));
787
    matroska->packets[matroska->num_packets] = pkt;
788
    matroska->num_packets++;
789
}
790

    
791
/*
792
 * Free all packets in our internal queue.
793
 */
794
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
795
{
796
    if (matroska->packets) {
797
        int n;
798
        for (n = 0; n < matroska->num_packets; n++) {
799
            av_free_packet(matroska->packets[n]);
800
            av_free(matroska->packets[n]);
801
        }
802
        av_free(matroska->packets);
803
        matroska->packets = NULL;
804
        matroska->num_packets = 0;
805
    }
806
}
807

    
808

    
809
/*
810
 * Autodetecting...
811
 */
812
static int matroska_probe(AVProbeData *p)
813
{
814
    uint64_t total = 0;
815
    int len_mask = 0x80, size = 1, n = 1;
816
    char probe_data[] = "matroska";
817

    
818
    /* ebml header? */
819
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
820
        return 0;
821

    
822
    /* length of header */
823
    total = p->buf[4];
824
    while (size <= 8 && !(total & len_mask)) {
825
        size++;
826
        len_mask >>= 1;
827
    }
828
    if (size > 8)
829
      return 0;
830
    total &= (len_mask - 1);
831
    while (n < size)
832
        total = (total << 8) | p->buf[4 + n++];
833

    
834
    /* does the probe data contain the whole header? */
835
    if (p->buf_size < 4 + size + total)
836
      return 0;
837

    
838
    /* the header must contain the document type 'matroska'. For now,
839
     * we don't parse the whole header but simply check for the
840
     * availability of that array of characters inside the header.
841
     * Not fully fool-proof, but good enough. */
842
    for (n = 4+size; n <= 4+size+total-(sizeof(probe_data)-1); n++)
843
        if (!memcmp(p->buf+n, probe_data, sizeof(probe_data)-1))
844
            return AVPROBE_SCORE_MAX;
845

    
846
    return 0;
847
}
848

    
849
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
850
                         uint32_t id, void *data);
851
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
852
                           void *data);
853

    
854
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
855
                           EbmlSyntax *syntax, void *data)
856
{
857
    ByteIOContext *pb = matroska->ctx->pb;
858
    uint32_t id = syntax->id;
859
    uint64_t length;
860
    int res;
861

    
862
    data = (char *)data + syntax->data_offset;
863
    if (syntax->list_elem_size) {
864
        EbmlList *list = data;
865
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
866
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
867
        memset(data, 0, syntax->list_elem_size);
868
        list->nb_elem++;
869
    }
870

    
871
    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
872
        if ((res = ebml_read_element_length(matroska, &length)) < 0)
873
            return res;
874

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

    
897
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
898
                         uint32_t id, void *data)
899
{
900
    int i;
901
    for (i=0; syntax[i].id; i++)
902
        if (id == syntax[i].id)
903
            break;
904
    if (!syntax[i].id)
905
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
906
    return ebml_parse_elem(matroska, &syntax[i], data);
907
}
908

    
909
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
910
                      void *data)
911
{
912
    uint32_t id;
913
    int res = ebml_read_element_id(matroska, &id);
914
    return res < 0 ? res : ebml_parse_id(matroska, syntax, id, data);
915
}
916

    
917
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
918
                           void *data)
919
{
920
    int i, res = 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 && !ebml_level_end(matroska))
937
        res = ebml_parse(matroska, syntax, data);
938

    
939
    return res;
940
}
941

    
942
static void ebml_free(EbmlSyntax *syntax, void *data)
943
{
944
    int i, j;
945
    for (i=0; syntax[i].id; i++) {
946
        void *data_off = (char *)data + syntax[i].data_offset;
947
        switch (syntax[i].type) {
948
        case EBML_STR:
949
        case EBML_UTF8:  av_freep(data_off);                      break;
950
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
951
        case EBML_NEST:
952
            if (syntax[i].list_elem_size) {
953
                EbmlList *list = data_off;
954
                char *ptr = list->elem;
955
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
956
                    ebml_free(syntax[i].def.n, ptr);
957
                av_free(list->elem);
958
            } else
959
                ebml_free(syntax[i].def.n, data_off);
960
        default:  break;
961
        }
962
    }
963
}
964

    
965
static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
966
                                  MatroskaTrack *track)
967
{
968
    MatroskaTrackEncoding *encodings = track->encodings.elem;
969
    uint8_t* data = *buf;
970
    int isize = *buf_size;
971
    uint8_t* pkt_data = NULL;
972
    int pkt_size = isize;
973
    int result = 0;
974
    int olen;
975

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

    
1034
    *buf = pkt_data;
1035
    *buf_size = pkt_size;
1036
    return 0;
1037
 failed:
1038
    av_free(pkt_data);
1039
    return -1;
1040
}
1041

    
1042
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1043
{
1044
    EbmlList *seekhead_list = &matroska->seekhead;
1045
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1046
    uint32_t peek_id_cache = matroska->peek_id;
1047
    uint32_t level_up = matroska->level_up;
1048
    offset_t before_pos = url_ftell(matroska->ctx->pb);
1049
    MatroskaLevel level;
1050
    int i;
1051

    
1052
    for (i=0; i<seekhead_list->nb_elem; i++) {
1053
        if (seekhead[i].pos <= before_pos
1054
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1055
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1056
            continue;
1057

    
1058
        /* seek */
1059
        if (ebml_read_seek(matroska,
1060
                           seekhead[i].pos+matroska->segment_start) < 0)
1061
            continue;
1062

    
1063
        /* we don't want to lose our seekhead level, so we add
1064
         * a dummy. This is a crude hack. */
1065
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1066
            av_log(matroska->ctx, AV_LOG_INFO,
1067
                   "Max EBML element depth (%d) reached, "
1068
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1069
            break;
1070
        }
1071

    
1072
        level.start = 0;
1073
        level.length = (uint64_t)-1;
1074
        matroska->levels[matroska->num_levels] = level;
1075
        matroska->num_levels++;
1076

    
1077
        ebml_parse(matroska, matroska_segment, matroska);
1078

    
1079
        /* remove dummy level */
1080
        while (matroska->num_levels) {
1081
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1082
            if (length == (uint64_t)-1)
1083
                break;
1084
        }
1085
    }
1086

    
1087
    /* seek back */
1088
    ebml_read_seek(matroska, before_pos);
1089
    matroska->peek_id = peek_id_cache;
1090
    matroska->level_up = level_up;
1091
}
1092

    
1093
static int matroska_aac_profile(char *codec_id)
1094
{
1095
    static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
1096
    int profile;
1097

    
1098
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1099
        if (strstr(codec_id, aac_profiles[profile]))
1100
            break;
1101
    return profile + 1;
1102
}
1103

    
1104
static int matroska_aac_sri(int samplerate)
1105
{
1106
    int sri;
1107

    
1108
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1109
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1110
            break;
1111
    return sri;
1112
}
1113

    
1114
static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1115
{
1116
    MatroskaDemuxContext *matroska = s->priv_data;
1117
    EbmlList *attachements_list = &matroska->attachments;
1118
    MatroskaAttachement *attachements;
1119
    EbmlList *chapters_list = &matroska->chapters;
1120
    MatroskaChapter *chapters;
1121
    MatroskaTrack *tracks;
1122
    EbmlList *index_list;
1123
    MatroskaIndex *index;
1124
    Ebml ebml = { 0 };
1125
    AVStream *st;
1126
    int i, j;
1127

    
1128
    matroska->ctx = s;
1129

    
1130
    /* First read the EBML header. */
1131
    if (ebml_parse(matroska, ebml_syntax, &ebml)
1132
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1133
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1134
        || ebml.doctype_version > 2) {
1135
        av_log(matroska->ctx, AV_LOG_ERROR,
1136
               "EBML header using unsupported features\n"
1137
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1138
               ebml.version, ebml.doctype, ebml.doctype_version);
1139
        return AVERROR_NOFMT;
1140
    }
1141
    ebml_free(ebml_syntax, &ebml);
1142

    
1143
    /* The next thing is a segment. */
1144
    if (ebml_parse(matroska, matroska_segments, matroska) < 0)
1145
        return -1;
1146
    matroska_execute_seekhead(matroska);
1147

    
1148
    if (matroska->duration)
1149
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1150
                                  * 1000 / AV_TIME_BASE;
1151
    if (matroska->title)
1152
        strncpy(matroska->ctx->title, matroska->title,
1153
                sizeof(matroska->ctx->title)-1);
1154

    
1155
    tracks = matroska->tracks.elem;
1156
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1157
        MatroskaTrack *track = &tracks[i];
1158
        enum CodecID codec_id = CODEC_ID_NONE;
1159
        EbmlList *encodings_list = &tracks->encodings;
1160
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1161
        uint8_t *extradata = NULL;
1162
        int extradata_size = 0;
1163
        int extradata_offset = 0;
1164

    
1165
        /* Apply some sanity checks. */
1166
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1167
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1168
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1169
            av_log(matroska->ctx, AV_LOG_INFO,
1170
                   "Unknown or unsupported track type %"PRIu64"\n",
1171
                   track->type);
1172
            continue;
1173
        }
1174
        if (track->codec_id == NULL)
1175
            continue;
1176

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

    
1227
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1228
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1229
                        strlen(ff_mkv_codec_tags[j].str))){
1230
                codec_id= ff_mkv_codec_tags[j].id;
1231
                break;
1232
            }
1233
        }
1234

    
1235
        st = track->stream = av_new_stream(s, matroska->num_streams++);
1236
        if (st == NULL)
1237
            return AVERROR(ENOMEM);
1238

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

    
1295
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1296
                          0, NULL, NULL, NULL, NULL);
1297
            url_fskip(&b, 24);
1298
            track->audio.coded_framesize = get_be32(&b);
1299
            url_fskip(&b, 12);
1300
            track->audio.sub_packet_h    = get_be16(&b);
1301
            track->audio.frame_size      = get_be16(&b);
1302
            track->audio.sub_packet_size = get_be16(&b);
1303
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1304
            if (codec_id == CODEC_ID_RA_288) {
1305
                st->codec->block_align = track->audio.coded_framesize;
1306
                track->codec_priv.size = 0;
1307
            } else {
1308
                st->codec->block_align = track->audio.sub_packet_size;
1309
                extradata_offset = 78;
1310
                track->codec_priv.size -= extradata_offset;
1311
            }
1312
        }
1313

    
1314
        if (codec_id == CODEC_ID_NONE)
1315
            av_log(matroska->ctx, AV_LOG_INFO,
1316
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1317

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

    
1320
        st->codec->codec_id = codec_id;
1321
        st->start_time = 0;
1322
        if (strcmp(track->language, "und"))
1323
            av_strlcpy(st->language, track->language, 4);
1324

    
1325
        if (track->flag_default)
1326
            st->disposition |= AV_DISPOSITION_DEFAULT;
1327

    
1328
        if (track->default_duration)
1329
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1330
                      track->default_duration, 1000000000, 30000);
1331

    
1332
        if(extradata){
1333
            st->codec->extradata = extradata;
1334
            st->codec->extradata_size = extradata_size;
1335
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1336
            st->codec->extradata = av_malloc(track->codec_priv.size);
1337
            if(st->codec->extradata == NULL)
1338
                return AVERROR(ENOMEM);
1339
            st->codec->extradata_size = track->codec_priv.size;
1340
            memcpy(st->codec->extradata,
1341
                   track->codec_priv.data + extradata_offset,
1342
                   track->codec_priv.size);
1343
        }
1344

    
1345
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1346
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1347
            st->codec->codec_tag  = track->video.fourcc;
1348
            st->codec->width  = track->video.pixel_width;
1349
            st->codec->height = track->video.pixel_height;
1350
            av_reduce(&st->codec->sample_aspect_ratio.num,
1351
                      &st->codec->sample_aspect_ratio.den,
1352
                      st->codec->height * track->video.display_width,
1353
                      st->codec-> width * track->video.display_height,
1354
                      255);
1355
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1356
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1357
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1358
            st->codec->sample_rate = track->audio.out_samplerate;
1359
            st->codec->channels = track->audio.channels;
1360
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1361
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1362
        }
1363
    }
1364

    
1365
    attachements = attachements_list->elem;
1366
    for (j=0; j<attachements_list->nb_elem; j++) {
1367
        if (!(attachements[j].filename && attachements[j].mime &&
1368
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1369
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1370
        } else {
1371
            AVStream *st = av_new_stream(s, matroska->num_streams++);
1372
            if (st == NULL)
1373
                break;
1374
            st->filename          = av_strdup(attachements[j].filename);
1375
            st->codec->codec_id = CODEC_ID_NONE;
1376
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1377
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1378
            if(st->codec->extradata == NULL)
1379
                break;
1380
            st->codec->extradata_size = attachements[j].bin.size;
1381
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1382

    
1383
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1384
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1385
                             strlen(ff_mkv_mime_tags[i].str))) {
1386
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1387
                    break;
1388
                }
1389
            }
1390
        }
1391
    }
1392

    
1393
    chapters = chapters_list->elem;
1394
    for (i=0; i<chapters_list->nb_elem; i++)
1395
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1396
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1397
                           chapters[i].start, chapters[i].end,
1398
                           chapters[i].title);
1399

    
1400
    index_list = &matroska->index;
1401
    index = index_list->elem;
1402
    for (i=0; i<index_list->nb_elem; i++) {
1403
        EbmlList *pos_list = &index[i].pos;
1404
        MatroskaIndexPos *pos = pos_list->elem;
1405
        for (j=0; j<pos_list->nb_elem; j++) {
1406
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1407
                                                              pos[j].track);
1408
            if (track && track->stream)
1409
                av_add_index_entry(track->stream,
1410
                                   pos[j].pos + matroska->segment_start,
1411
                                   index[i].time*matroska->time_scale/AV_TIME_BASE,
1412
                                   0, 0, AVINDEX_KEYFRAME);
1413
        }
1414
    }
1415

    
1416
    return 0;
1417
}
1418

    
1419
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1420
                                int size, int64_t pos, uint64_t cluster_time,
1421
                                uint64_t duration, int is_keyframe)
1422
{
1423
    MatroskaTrack *track;
1424
    int res = 0;
1425
    AVStream *st;
1426
    AVPacket *pkt;
1427
    int16_t block_time;
1428
    uint32_t *lace_size = NULL;
1429
    int n, flags, laces = 0;
1430
    uint64_t num;
1431

    
1432
    if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1433
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1434
        return res;
1435
    }
1436
    data += n;
1437
    size -= n;
1438

    
1439
    track = matroska_find_track_by_num(matroska, num);
1440
    if (size <= 3 || !track || !track->stream) {
1441
        av_log(matroska->ctx, AV_LOG_INFO,
1442
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1443
        return res;
1444
    }
1445
    st = track->stream;
1446
    if (st->discard >= AVDISCARD_ALL)
1447
        return res;
1448
    if (duration == AV_NOPTS_VALUE)
1449
        duration = track->default_duration / matroska->time_scale;
1450

    
1451
    block_time = AV_RB16(data);
1452
    data += 2;
1453
    flags = *data++;
1454
    size -= 3;
1455
    if (is_keyframe == -1)
1456
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1457

    
1458
    if (matroska->skip_to_keyframe) {
1459
        if (!is_keyframe || st != matroska->skip_to_stream)
1460
            return res;
1461
        matroska->skip_to_keyframe = 0;
1462
    }
1463

    
1464
    switch ((flags & 0x06) >> 1) {
1465
        case 0x0: /* no lacing */
1466
            laces = 1;
1467
            lace_size = av_mallocz(sizeof(int));
1468
            lace_size[0] = size;
1469
            break;
1470

    
1471
        case 0x1: /* xiph lacing */
1472
        case 0x2: /* fixed-size lacing */
1473
        case 0x3: /* EBML lacing */
1474
            assert(size>0); // size <=3 is checked before size-=3 above
1475
            laces = (*data) + 1;
1476
            data += 1;
1477
            size -= 1;
1478
            lace_size = av_mallocz(laces * sizeof(int));
1479

    
1480
            switch ((flags & 0x06) >> 1) {
1481
                case 0x1: /* xiph lacing */ {
1482
                    uint8_t temp;
1483
                    uint32_t total = 0;
1484
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1485
                        while (1) {
1486
                            if (size == 0) {
1487
                                res = -1;
1488
                                break;
1489
                            }
1490
                            temp = *data;
1491
                            lace_size[n] += temp;
1492
                            data += 1;
1493
                            size -= 1;
1494
                            if (temp != 0xff)
1495
                                break;
1496
                        }
1497
                        total += lace_size[n];
1498
                    }
1499
                    lace_size[n] = size - total;
1500
                    break;
1501
                }
1502

    
1503
                case 0x2: /* fixed-size lacing */
1504
                    for (n = 0; n < laces; n++)
1505
                        lace_size[n] = size / laces;
1506
                    break;
1507

    
1508
                case 0x3: /* EBML lacing */ {
1509
                    uint32_t total;
1510
                    n = matroska_ebmlnum_uint(data, size, &num);
1511
                    if (n < 0) {
1512
                        av_log(matroska->ctx, AV_LOG_INFO,
1513
                               "EBML block data error\n");
1514
                        break;
1515
                    }
1516
                    data += n;
1517
                    size -= n;
1518
                    total = lace_size[0] = num;
1519
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1520
                        int64_t snum;
1521
                        int r;
1522
                        r = matroska_ebmlnum_sint (data, size, &snum);
1523
                        if (r < 0) {
1524
                            av_log(matroska->ctx, AV_LOG_INFO,
1525
                                   "EBML block data error\n");
1526
                            break;
1527
                        }
1528
                        data += r;
1529
                        size -= r;
1530
                        lace_size[n] = lace_size[n - 1] + snum;
1531
                        total += lace_size[n];
1532
                    }
1533
                    lace_size[n] = size - total;
1534
                    break;
1535
                }
1536
            }
1537
            break;
1538
    }
1539

    
1540
    if (res == 0) {
1541
        uint64_t timecode = AV_NOPTS_VALUE;
1542

    
1543
        if (cluster_time != (uint64_t)-1
1544
            && (block_time >= 0 || cluster_time >= -block_time))
1545
            timecode = cluster_time + block_time;
1546

    
1547
        for (n = 0; n < laces; n++) {
1548
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1549
                st->codec->codec_id == CODEC_ID_COOK ||
1550
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1551
                int a = st->codec->block_align;
1552
                int sps = track->audio.sub_packet_size;
1553
                int cfs = track->audio.coded_framesize;
1554
                int h = track->audio.sub_packet_h;
1555
                int y = track->audio.sub_packet_cnt;
1556
                int w = track->audio.frame_size;
1557
                int x;
1558

    
1559
                if (!track->audio.pkt_cnt) {
1560
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1561
                        for (x=0; x<h/2; x++)
1562
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1563
                                   data+x*cfs, cfs);
1564
                    else
1565
                        for (x=0; x<w/sps; x++)
1566
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1567

    
1568
                    if (++track->audio.sub_packet_cnt >= h) {
1569
                        track->audio.sub_packet_cnt = 0;
1570
                        track->audio.pkt_cnt = h*w / a;
1571
                    }
1572
                }
1573
                while (track->audio.pkt_cnt) {
1574
                    pkt = av_mallocz(sizeof(AVPacket));
1575
                    av_new_packet(pkt, a);
1576
                    memcpy(pkt->data, track->audio.buf
1577
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1578
                    pkt->pos = pos;
1579
                    pkt->stream_index = st->index;
1580
                    matroska_queue_packet(matroska, pkt);
1581
                }
1582
            } else {
1583
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1584
                int offset = 0, pkt_size = lace_size[n];
1585
                uint8_t *pkt_data = data;
1586

    
1587
                if (encodings && encodings->scope & 1) {
1588
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1589
                    if (offset < 0)
1590
                        continue;
1591
                }
1592

    
1593
                pkt = av_mallocz(sizeof(AVPacket));
1594
                /* XXX: prevent data copy... */
1595
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1596
                    av_free(pkt);
1597
                    res = AVERROR(ENOMEM);
1598
                    n = laces-1;
1599
                    break;
1600
                }
1601
                if (offset)
1602
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1603
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1604

    
1605
                if (pkt_data != data)
1606
                    av_free(pkt_data);
1607

    
1608
                if (n == 0)
1609
                    pkt->flags = is_keyframe;
1610
                pkt->stream_index = st->index;
1611

    
1612
                pkt->pts = timecode;
1613
                pkt->pos = pos;
1614
                pkt->duration = duration;
1615

    
1616
                matroska_queue_packet(matroska, pkt);
1617
            }
1618

    
1619
            if (timecode != AV_NOPTS_VALUE)
1620
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1621
            data += lace_size[n];
1622
        }
1623
    }
1624

    
1625
    av_free(lace_size);
1626
    return res;
1627
}
1628

    
1629
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1630
{
1631
    MatroskaCluster cluster = { 0 };
1632
    EbmlList *blocks_list;
1633
    MatroskaBlock *blocks;
1634
    int i, res = ebml_parse(matroska, matroska_clusters, &cluster);
1635
    blocks_list = &cluster.blocks;
1636
    blocks = blocks_list->elem;
1637
    for (i=0; !res && i<blocks_list->nb_elem; i++)
1638
        if (blocks[i].bin.size > 0)
1639
            res=matroska_parse_block(matroska,
1640
                                     blocks[i].bin.data, blocks[i].bin.size,
1641
                                     blocks[i].bin.pos,  cluster.timecode,
1642
                                     blocks[i].duration, !blocks[i].reference);
1643
    ebml_free(matroska_cluster, &cluster);
1644
    return res;
1645
}
1646

    
1647
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1648
{
1649
    MatroskaDemuxContext *matroska = s->priv_data;
1650

    
1651
    while (matroska_deliver_packet(matroska, pkt)) {
1652
        if (matroska->done)
1653
            return AVERROR(EIO);
1654
        if (matroska_parse_cluster(matroska) < 0)
1655
            matroska->done = 1;
1656
    }
1657

    
1658
    return 0;
1659
}
1660

    
1661
static int matroska_read_seek(AVFormatContext *s, int stream_index,
1662
                              int64_t timestamp, int flags)
1663
{
1664
    MatroskaDemuxContext *matroska = s->priv_data;
1665
    AVStream *st = s->streams[stream_index];
1666
    int index;
1667

    
1668
    index = av_index_search_timestamp(st, timestamp, flags);
1669
    if (index < 0)
1670
        return 0;
1671

    
1672
    matroska_clear_queue(matroska);
1673

    
1674
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1675
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1676
    matroska->skip_to_stream = st;
1677
    matroska->peek_id = 0;
1678
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1679
    return 0;
1680
}
1681

    
1682
static int matroska_read_close(AVFormatContext *s)
1683
{
1684
    MatroskaDemuxContext *matroska = s->priv_data;
1685
    MatroskaTrack *tracks = matroska->tracks.elem;
1686
    int n;
1687

    
1688
    matroska_clear_queue(matroska);
1689

    
1690
    for (n=0; n < matroska->tracks.nb_elem; n++)
1691
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1692
            av_free(tracks[n].audio.buf);
1693
    ebml_free(matroska_segment, matroska);
1694

    
1695
    return 0;
1696
}
1697

    
1698
AVInputFormat matroska_demuxer = {
1699
    "matroska",
1700
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1701
    sizeof(MatroskaDemuxContext),
1702
    matroska_probe,
1703
    matroska_read_header,
1704
    matroska_read_packet,
1705
    matroska_read_close,
1706
    matroska_read_seek,
1707
};