Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 131f1cb2

History | View | Annotate | Download (57.9 KB)

1
/*
2
 * Matroska file demuxer
3
 * Copyright (c) 2003-2008 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
 * totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28
 * Specs available on the Matroska project page: 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
    char *name;
168
    char *string;
169
    EbmlList sub;
170
} MatroskaTag;
171

    
172
typedef struct {
173
    uint64_t id;
174
    uint64_t pos;
175
} MatroskaSeekhead;
176

    
177
typedef struct {
178
    uint64_t start;
179
    uint64_t length;
180
} MatroskaLevel;
181

    
182
typedef struct {
183
    AVFormatContext *ctx;
184

    
185
    /* EBML stuff */
186
    int num_levels;
187
    MatroskaLevel levels[EBML_MAX_DEPTH];
188
    int level_up;
189

    
190
    uint64_t time_scale;
191
    double   duration;
192
    char    *title;
193
    EbmlList tracks;
194
    EbmlList attachments;
195
    EbmlList chapters;
196
    EbmlList index;
197
    EbmlList tags;
198
    EbmlList seekhead;
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_simpletag[] = {
401
    { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
402
    { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
403
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
404
    { MATROSKA_ID_TAGLANG,            EBML_NONE },
405
    { MATROSKA_ID_TAGDEFAULT,         EBML_NONE },
406
    { EBML_ID_VOID,                   EBML_NONE },
407
    { 0 }
408
};
409

    
410
static EbmlSyntax matroska_tag[] = {
411
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), 0, {.n=matroska_simpletag} },
412
    { MATROSKA_ID_TAGTARGETS,         EBML_NONE },
413
    { EBML_ID_VOID,                   EBML_NONE },
414
    { 0 }
415
};
416

    
417
static EbmlSyntax matroska_tags[] = {
418
    { MATROSKA_ID_TAG,                EBML_NEST, 0, offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
419
    { EBML_ID_VOID,                   EBML_NONE },
420
    { 0 }
421
};
422

    
423
static EbmlSyntax matroska_seekhead_entry[] = {
424
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
425
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
426
    { EBML_ID_VOID,                   EBML_NONE },
427
    { 0 }
428
};
429

    
430
static EbmlSyntax matroska_seekhead[] = {
431
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
432
    { EBML_ID_VOID,                   EBML_NONE },
433
    { 0 }
434
};
435

    
436
static EbmlSyntax matroska_segment[] = {
437
    { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
438
    { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
439
    { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
440
    { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
441
    { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
442
    { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
443
    { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
444
    { MATROSKA_ID_CLUSTER,        EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
445
    { EBML_ID_VOID,               EBML_NONE },
446
    { 0 }
447
};
448

    
449
static EbmlSyntax matroska_segments[] = {
450
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
451
    { 0 }
452
};
453

    
454
static EbmlSyntax matroska_blockgroup[] = {
455
    { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
456
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
457
    { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
458
    { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
459
    { EBML_ID_VOID,               EBML_NONE },
460
    { 0 }
461
};
462

    
463
static EbmlSyntax matroska_cluster[] = {
464
    { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
465
    { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
466
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
467
    { EBML_ID_VOID,               EBML_NONE },
468
    { 0 }
469
};
470

    
471
static EbmlSyntax matroska_clusters[] = {
472
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
473
    { 0 }
474
};
475

    
476
#define SIZE_OFF(x) sizeof(((AVFormatContext*)0)->x),offsetof(AVFormatContext,x)
477
const struct {
478
    const char name[16];
479
    int   size;
480
    int   offset;
481
} metadata[] = {
482
    { "TITLE",           SIZE_OFF(title)      },
483
    { "ARTIST",          SIZE_OFF(author)     },
484
    { "WRITTEN_BY",      SIZE_OFF(author)     },
485
    { "LEAD_PERFORMER",  SIZE_OFF(author)     },
486
    { "COPYRIGHT",       SIZE_OFF(copyright)  },
487
    { "COMMENT",         SIZE_OFF(comment)    },
488
    { "ALBUM",           SIZE_OFF(album)      },
489
    { "DATE_WRITTEN",    SIZE_OFF(year)       },
490
    { "DATE_RELEASED",   SIZE_OFF(year)       },
491
    { "PART_NUMBER",     SIZE_OFF(track)      },
492
    { "GENRE",           SIZE_OFF(genre)      },
493
};
494

    
495
/*
496
 * Return: Whether we reached the end of a level in the hierarchy or not.
497
 */
498
static int ebml_level_end(MatroskaDemuxContext *matroska)
499
{
500
    ByteIOContext *pb = matroska->ctx->pb;
501
    offset_t pos = url_ftell(pb);
502

    
503
    if (matroska->num_levels > 0) {
504
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
505
        if (pos - level->start >= level->length) {
506
            matroska->num_levels--;
507
            return 1;
508
        }
509
    }
510
    return 0;
511
}
512

    
513
/*
514
 * Read: an "EBML number", which is defined as a variable-length
515
 * array of bytes. The first byte indicates the length by giving a
516
 * number of 0-bits followed by a one. The position of the first
517
 * "one" bit inside the first byte indicates the length of this
518
 * number.
519
 * Returns: number of bytes read, < 0 on error
520
 */
521
static int ebml_read_num(MatroskaDemuxContext *matroska, ByteIOContext *pb,
522
                         int max_size, uint64_t *number)
523
{
524
    int len_mask = 0x80, read = 1, n = 1;
525
    int64_t total = 0;
526

    
527
    /* The first byte tells us the length in bytes - get_byte() can normally
528
     * return 0, but since that's not a valid first ebmlID byte, we can
529
     * use it safely here to catch EOS. */
530
    if (!(total = get_byte(pb))) {
531
        /* we might encounter EOS here */
532
        if (!url_feof(pb)) {
533
            offset_t pos = url_ftell(pb);
534
            av_log(matroska->ctx, AV_LOG_ERROR,
535
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
536
                   pos, pos);
537
        }
538
        return AVERROR(EIO); /* EOS or actual I/O error */
539
    }
540

    
541
    /* get the length of the EBML number */
542
    while (read <= max_size && !(total & len_mask)) {
543
        read++;
544
        len_mask >>= 1;
545
    }
546
    if (read > max_size) {
547
        offset_t pos = url_ftell(pb) - 1;
548
        av_log(matroska->ctx, AV_LOG_ERROR,
549
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
550
               (uint8_t) total, pos, pos);
551
        return AVERROR_INVALIDDATA;
552
    }
553

    
554
    /* read out length */
555
    total &= ~len_mask;
556
    while (n++ < read)
557
        total = (total << 8) | get_byte(pb);
558

    
559
    *number = total;
560

    
561
    return read;
562
}
563

    
564
/*
565
 * Read the next element as an unsigned int.
566
 * 0 is success, < 0 is failure.
567
 */
568
static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
569
{
570
    int n = 0;
571

    
572
    if (size < 1 || size > 8)
573
        return AVERROR_INVALIDDATA;
574

    
575
    /* big-endian ordering; build up number */
576
    *num = 0;
577
    while (n++ < size)
578
        *num = (*num << 8) | get_byte(pb);
579

    
580
    return 0;
581
}
582

    
583
/*
584
 * Read the next element as a float.
585
 * 0 is success, < 0 is failure.
586
 */
587
static int ebml_read_float(ByteIOContext *pb, int size, double *num)
588
{
589
    if (size == 4) {
590
        *num= av_int2flt(get_be32(pb));
591
    } else if(size==8){
592
        *num= av_int2dbl(get_be64(pb));
593
    } else
594
        return AVERROR_INVALIDDATA;
595

    
596
    return 0;
597
}
598

    
599
/*
600
 * Read the next element as an ASCII string.
601
 * 0 is success, < 0 is failure.
602
 */
603
static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
604
{
605
    av_free(*str);
606
    /* EBML strings are usually not 0-terminated, so we allocate one
607
     * byte more, read the string and NULL-terminate it ourselves. */
608
    if (!(*str = av_malloc(size + 1)))
609
        return AVERROR(ENOMEM);
610
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
611
        av_free(*str);
612
        return AVERROR(EIO);
613
    }
614
    (*str)[size] = '\0';
615

    
616
    return 0;
617
}
618

    
619
/*
620
 * Read the next element as binary data.
621
 * 0 is success, < 0 is failure.
622
 */
623
static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
624
{
625
    av_free(bin->data);
626
    if (!(bin->data = av_malloc(length)))
627
        return AVERROR(ENOMEM);
628

    
629
    bin->size = length;
630
    bin->pos  = url_ftell(pb);
631
    if (get_buffer(pb, bin->data, length) != length)
632
        return AVERROR(EIO);
633

    
634
    return 0;
635
}
636

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

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

    
653
    level = &matroska->levels[matroska->num_levels++];
654
    level->start = url_ftell(pb);
655
    level->length = length;
656

    
657
    return 0;
658
}
659

    
660
/*
661
 * Read signed/unsigned "EBML" numbers.
662
 * Return: number of bytes processed, < 0 on error
663
 */
664
static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
665
                                 uint8_t *data, uint32_t size, uint64_t *num)
666
{
667
    ByteIOContext pb;
668
    init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
669
    return ebml_read_num(matroska, &pb, 8, num);
670
}
671

    
672
/*
673
 * Same as above, but signed.
674
 */
675
static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
676
                                 uint8_t *data, uint32_t size, int64_t *num)
677
{
678
    uint64_t unum;
679
    int res;
680

    
681
    /* read as unsigned number first */
682
    if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
683
        return res;
684

    
685
    /* make signed (weird way) */
686
    *num = unum - ((1LL << (7*res - 1)) - 1);
687

    
688
    return res;
689
}
690

    
691
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
692
                           EbmlSyntax *syntax, void *data);
693

    
694
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
695
                         uint32_t id, void *data)
696
{
697
    int i;
698
    for (i=0; syntax[i].id; i++)
699
        if (id == syntax[i].id)
700
            break;
701
    if (!syntax[i].id)
702
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
703
    return ebml_parse_elem(matroska, &syntax[i], data);
704
}
705

    
706
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
707
                      void *data)
708
{
709
    uint64_t id;
710
    int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
711
    id |= 1 << 7*res;
712
    return res < 0 ? res : ebml_parse_id(matroska, syntax, id, data);
713
}
714

    
715
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
716
                           void *data)
717
{
718
    int i, res = 0;
719

    
720
    for (i=0; syntax[i].id; i++)
721
        switch (syntax[i].type) {
722
        case EBML_UINT:
723
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
724
            break;
725
        case EBML_FLOAT:
726
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
727
            break;
728
        case EBML_STR:
729
        case EBML_UTF8:
730
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
731
            break;
732
        }
733

    
734
    while (!res && !ebml_level_end(matroska))
735
        res = ebml_parse(matroska, syntax, data);
736

    
737
    return res;
738
}
739

    
740
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
741
                           EbmlSyntax *syntax, void *data)
742
{
743
    ByteIOContext *pb = matroska->ctx->pb;
744
    uint32_t id = syntax->id;
745
    uint64_t length;
746
    int res;
747

    
748
    data = (char *)data + syntax->data_offset;
749
    if (syntax->list_elem_size) {
750
        EbmlList *list = data;
751
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
752
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
753
        memset(data, 0, syntax->list_elem_size);
754
        list->nb_elem++;
755
    }
756

    
757
    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
758
        if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
759
            return res;
760

    
761
    switch (syntax->type) {
762
    case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
763
    case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
764
    case EBML_STR:
765
    case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
766
    case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
767
    case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
768
                         return res;
769
                     if (id == MATROSKA_ID_SEGMENT)
770
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
771
                     return ebml_parse_nest(matroska, syntax->def.n, data);
772
    case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
773
    case EBML_STOP:  *(int *)data = 1;      return 1;
774
    default:         url_fskip(pb, length); return 0;
775
    }
776
    if (res == AVERROR_INVALIDDATA)
777
        av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
778
    else if (res == AVERROR(EIO))
779
        av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
780
    return res;
781
}
782

    
783
static void ebml_free(EbmlSyntax *syntax, void *data)
784
{
785
    int i, j;
786
    for (i=0; syntax[i].id; i++) {
787
        void *data_off = (char *)data + syntax[i].data_offset;
788
        switch (syntax[i].type) {
789
        case EBML_STR:
790
        case EBML_UTF8:  av_freep(data_off);                      break;
791
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
792
        case EBML_NEST:
793
            if (syntax[i].list_elem_size) {
794
                EbmlList *list = data_off;
795
                char *ptr = list->elem;
796
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
797
                    ebml_free(syntax[i].def.n, ptr);
798
                av_free(list->elem);
799
            } else
800
                ebml_free(syntax[i].def.n, data_off);
801
        default:  break;
802
        }
803
    }
804
}
805

    
806

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

    
816
    /* EBML header? */
817
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
818
        return 0;
819

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

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

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

    
844
    return 0;
845
}
846

    
847
static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
848
                                                 int num)
849
{
850
    MatroskaTrack *tracks = matroska->tracks.elem;
851
    int i;
852

    
853
    for (i=0; i < matroska->tracks.nb_elem; i++)
854
        if (tracks[i].num == num)
855
            return &tracks[i];
856

    
857
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
858
    return NULL;
859
}
860

    
861
static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
862
                                  MatroskaTrack *track)
863
{
864
    MatroskaTrackEncoding *encodings = track->encodings.elem;
865
    uint8_t* data = *buf;
866
    int isize = *buf_size;
867
    uint8_t* pkt_data = NULL;
868
    int pkt_size = isize;
869
    int result = 0;
870
    int olen;
871

    
872
    switch (encodings[0].compression.algo) {
873
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
874
        return encodings[0].compression.settings.size;
875
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
876
        do {
877
            olen = pkt_size *= 3;
878
            pkt_data = av_realloc(pkt_data,
879
                                  pkt_size+LZO_OUTPUT_PADDING);
880
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
881
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
882
        if (result)
883
            goto failed;
884
        pkt_size -= olen;
885
        break;
886
#ifdef CONFIG_ZLIB
887
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
888
        z_stream zstream = {0};
889
        if (inflateInit(&zstream) != Z_OK)
890
            return -1;
891
        zstream.next_in = data;
892
        zstream.avail_in = isize;
893
        do {
894
            pkt_size *= 3;
895
            pkt_data = av_realloc(pkt_data, pkt_size);
896
            zstream.avail_out = pkt_size - zstream.total_out;
897
            zstream.next_out = pkt_data + zstream.total_out;
898
            result = inflate(&zstream, Z_NO_FLUSH);
899
        } while (result==Z_OK && pkt_size<10000000);
900
        pkt_size = zstream.total_out;
901
        inflateEnd(&zstream);
902
        if (result != Z_STREAM_END)
903
            goto failed;
904
        break;
905
    }
906
#endif
907
#ifdef CONFIG_BZLIB
908
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
909
        bz_stream bzstream = {0};
910
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
911
            return -1;
912
        bzstream.next_in = data;
913
        bzstream.avail_in = isize;
914
        do {
915
            pkt_size *= 3;
916
            pkt_data = av_realloc(pkt_data, pkt_size);
917
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
918
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
919
            result = BZ2_bzDecompress(&bzstream);
920
        } while (result==BZ_OK && pkt_size<10000000);
921
        pkt_size = bzstream.total_out_lo32;
922
        BZ2_bzDecompressEnd(&bzstream);
923
        if (result != BZ_STREAM_END)
924
            goto failed;
925
        break;
926
    }
927
#endif
928
    }
929

    
930
    *buf = pkt_data;
931
    *buf_size = pkt_size;
932
    return 0;
933
 failed:
934
    av_free(pkt_data);
935
    return -1;
936
}
937

    
938
static void matroska_convert_tags(AVFormatContext *s, EbmlList *list)
939
{
940
    MatroskaTag *tags = list->elem;
941
    int i, j;
942

    
943
    for (i=0; i < list->nb_elem; i++) {
944
        for (j=0; j < ARRAY_SIZE(metadata); j++){
945
            if (!strcmp(tags[i].name, metadata[j].name)) {
946
                int *ptr = (int *)((char *)s + metadata[j].offset);
947
                if (*ptr)  continue;
948
                if (metadata[j].size > sizeof(int))
949
                    av_strlcpy((char *)ptr, tags[i].string, metadata[j].size);
950
                else
951
                    *ptr = atoi(tags[i].string);
952
            }
953
        }
954
        if (tags[i].sub.nb_elem)
955
            matroska_convert_tags(s, &tags[i].sub);
956
    }
957
}
958

    
959
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
960
{
961
    EbmlList *seekhead_list = &matroska->seekhead;
962
    MatroskaSeekhead *seekhead = seekhead_list->elem;
963
    uint32_t level_up = matroska->level_up;
964
    offset_t before_pos = url_ftell(matroska->ctx->pb);
965
    MatroskaLevel level;
966
    int i;
967

    
968
    for (i=0; i<seekhead_list->nb_elem; i++) {
969
        offset_t offset = seekhead[i].pos + matroska->segment_start;
970

    
971
        if (seekhead[i].pos <= before_pos
972
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
973
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
974
            continue;
975

    
976
        /* seek */
977
        if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
978
            continue;
979

    
980
        /* We don't want to lose our seekhead level, so we add
981
         * a dummy. This is a crude hack. */
982
        if (matroska->num_levels == EBML_MAX_DEPTH) {
983
            av_log(matroska->ctx, AV_LOG_INFO,
984
                   "Max EBML element depth (%d) reached, "
985
                   "cannot parse further.\n", EBML_MAX_DEPTH);
986
            break;
987
        }
988

    
989
        level.start = 0;
990
        level.length = (uint64_t)-1;
991
        matroska->levels[matroska->num_levels] = level;
992
        matroska->num_levels++;
993

    
994
        ebml_parse(matroska, matroska_segment, matroska);
995

    
996
        /* remove dummy level */
997
        while (matroska->num_levels) {
998
            uint64_t length = matroska->levels[--matroska->num_levels].length;
999
            if (length == (uint64_t)-1)
1000
                break;
1001
        }
1002
    }
1003

    
1004
    /* seek back */
1005
    url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
1006
    matroska->level_up = level_up;
1007
}
1008

    
1009
static int matroska_aac_profile(char *codec_id)
1010
{
1011
    static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
1012
    int profile;
1013

    
1014
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1015
        if (strstr(codec_id, aac_profiles[profile]))
1016
            break;
1017
    return profile + 1;
1018
}
1019

    
1020
static int matroska_aac_sri(int samplerate)
1021
{
1022
    int sri;
1023

    
1024
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1025
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1026
            break;
1027
    return sri;
1028
}
1029

    
1030
static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1031
{
1032
    MatroskaDemuxContext *matroska = s->priv_data;
1033
    EbmlList *attachements_list = &matroska->attachments;
1034
    MatroskaAttachement *attachements;
1035
    EbmlList *chapters_list = &matroska->chapters;
1036
    MatroskaChapter *chapters;
1037
    MatroskaTrack *tracks;
1038
    EbmlList *index_list;
1039
    MatroskaIndex *index;
1040
    Ebml ebml = { 0 };
1041
    AVStream *st;
1042
    int i, j;
1043

    
1044
    matroska->ctx = s;
1045

    
1046
    /* First read the EBML header. */
1047
    if (ebml_parse(matroska, ebml_syntax, &ebml)
1048
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1049
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1050
        || ebml.doctype_version > 2) {
1051
        av_log(matroska->ctx, AV_LOG_ERROR,
1052
               "EBML header using unsupported features\n"
1053
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1054
               ebml.version, ebml.doctype, ebml.doctype_version);
1055
        return AVERROR_NOFMT;
1056
    }
1057
    ebml_free(ebml_syntax, &ebml);
1058

    
1059
    /* The next thing is a segment. */
1060
    if (ebml_parse(matroska, matroska_segments, matroska) < 0)
1061
        return -1;
1062
    matroska_execute_seekhead(matroska);
1063

    
1064
    if (matroska->duration)
1065
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1066
                                  * 1000 / AV_TIME_BASE;
1067
    if (matroska->title)
1068
        strncpy(matroska->ctx->title, matroska->title,
1069
                sizeof(matroska->ctx->title)-1);
1070
    matroska_convert_tags(s, &matroska->tags);
1071

    
1072
    tracks = matroska->tracks.elem;
1073
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1074
        MatroskaTrack *track = &tracks[i];
1075
        enum CodecID codec_id = CODEC_ID_NONE;
1076
        EbmlList *encodings_list = &tracks->encodings;
1077
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1078
        uint8_t *extradata = NULL;
1079
        int extradata_size = 0;
1080
        int extradata_offset = 0;
1081

    
1082
        /* Apply some sanity checks. */
1083
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1084
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1085
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1086
            av_log(matroska->ctx, AV_LOG_INFO,
1087
                   "Unknown or unsupported track type %"PRIu64"\n",
1088
                   track->type);
1089
            continue;
1090
        }
1091
        if (track->codec_id == NULL)
1092
            continue;
1093

    
1094
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1095
            if (!track->default_duration)
1096
                track->default_duration = 1000000000/track->video.frame_rate;
1097
            if (!track->video.display_width)
1098
                track->video.display_width = track->video.pixel_width;
1099
            if (!track->video.display_height)
1100
                track->video.display_height = track->video.pixel_height;
1101
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1102
            if (!track->audio.out_samplerate)
1103
                track->audio.out_samplerate = track->audio.samplerate;
1104
        }
1105
        if (encodings_list->nb_elem > 1) {
1106
            av_log(matroska->ctx, AV_LOG_ERROR,
1107
                   "Multiple combined encodings no supported");
1108
        } else if (encodings_list->nb_elem == 1) {
1109
            if (encodings[0].type ||
1110
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1111
#ifdef CONFIG_ZLIB
1112
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1113
#endif
1114
#ifdef CONFIG_BZLIB
1115
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1116
#endif
1117
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1118
                encodings[0].scope = 0;
1119
                av_log(matroska->ctx, AV_LOG_ERROR,
1120
                       "Unsupported encoding type");
1121
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1122
                uint8_t *codec_priv = track->codec_priv.data;
1123
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1124
                                                    &track->codec_priv.size,
1125
                                                    track);
1126
                if (offset < 0) {
1127
                    track->codec_priv.data = NULL;
1128
                    track->codec_priv.size = 0;
1129
                    av_log(matroska->ctx, AV_LOG_ERROR,
1130
                           "Failed to decode codec private data\n");
1131
                } else if (offset > 0) {
1132
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1133
                    memcpy(track->codec_priv.data,
1134
                           encodings[0].compression.settings.data, offset);
1135
                    memcpy(track->codec_priv.data+offset, codec_priv,
1136
                           track->codec_priv.size);
1137
                    track->codec_priv.size += offset;
1138
                }
1139
                if (codec_priv != track->codec_priv.data)
1140
                    av_free(codec_priv);
1141
            }
1142
        }
1143

    
1144
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1145
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1146
                        strlen(ff_mkv_codec_tags[j].str))){
1147
                codec_id= ff_mkv_codec_tags[j].id;
1148
                break;
1149
            }
1150
        }
1151

    
1152
        st = track->stream = av_new_stream(s, 0);
1153
        if (st == NULL)
1154
            return AVERROR(ENOMEM);
1155

    
1156
        if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1157
            && track->codec_priv.size >= 40
1158
            && track->codec_priv.data != NULL) {
1159
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1160
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1161
        } else if (!strcmp(track->codec_id, "A_MS/ACM")
1162
                   && track->codec_priv.size >= 18
1163
                   && track->codec_priv.data != NULL) {
1164
            uint16_t tag = AV_RL16(track->codec_priv.data);
1165
            codec_id = codec_get_id(codec_wav_tags, tag);
1166
        } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1167
                   && (track->codec_priv.size >= 86)
1168
                   && (track->codec_priv.data != NULL)) {
1169
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1170
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1171
        } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1172
            int profile = matroska_aac_profile(track->codec_id);
1173
            int sri = matroska_aac_sri(track->audio.samplerate);
1174
            extradata = av_malloc(5);
1175
            if (extradata == NULL)
1176
                return AVERROR(ENOMEM);
1177
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1178
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1179
            if (strstr(track->codec_id, "SBR")) {
1180
                sri = matroska_aac_sri(track->audio.out_samplerate);
1181
                extradata[2] = 0x56;
1182
                extradata[3] = 0xE5;
1183
                extradata[4] = 0x80 | (sri<<3);
1184
                extradata_size = 5;
1185
            } else
1186
                extradata_size = 2;
1187
        } else if (codec_id == CODEC_ID_TTA) {
1188
            ByteIOContext b;
1189
            extradata_size = 30;
1190
            extradata = av_mallocz(extradata_size);
1191
            if (extradata == NULL)
1192
                return AVERROR(ENOMEM);
1193
            init_put_byte(&b, extradata, extradata_size, 1,
1194
                          NULL, NULL, NULL, NULL);
1195
            put_buffer(&b, "TTA1", 4);
1196
            put_le16(&b, 1);
1197
            put_le16(&b, track->audio.channels);
1198
            put_le16(&b, track->audio.bitdepth);
1199
            put_le32(&b, track->audio.out_samplerate);
1200
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1201
        } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1202
                   codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1203
            extradata_offset = 26;
1204
            track->codec_priv.size -= extradata_offset;
1205
        } else if (codec_id == CODEC_ID_RA_144) {
1206
            track->audio.out_samplerate = 8000;
1207
            track->audio.channels = 1;
1208
        } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1209
                   codec_id == CODEC_ID_ATRAC3) {
1210
            ByteIOContext b;
1211

    
1212
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1213
                          0, NULL, NULL, NULL, NULL);
1214
            url_fskip(&b, 24);
1215
            track->audio.coded_framesize = get_be32(&b);
1216
            url_fskip(&b, 12);
1217
            track->audio.sub_packet_h    = get_be16(&b);
1218
            track->audio.frame_size      = get_be16(&b);
1219
            track->audio.sub_packet_size = get_be16(&b);
1220
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1221
            if (codec_id == CODEC_ID_RA_288) {
1222
                st->codec->block_align = track->audio.coded_framesize;
1223
                track->codec_priv.size = 0;
1224
            } else {
1225
                st->codec->block_align = track->audio.sub_packet_size;
1226
                extradata_offset = 78;
1227
                track->codec_priv.size -= extradata_offset;
1228
            }
1229
        }
1230

    
1231
        if (codec_id == CODEC_ID_NONE)
1232
            av_log(matroska->ctx, AV_LOG_INFO,
1233
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1234

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

    
1237
        st->codec->codec_id = codec_id;
1238
        st->start_time = 0;
1239
        if (strcmp(track->language, "und"))
1240
            av_strlcpy(st->language, track->language, 4);
1241

    
1242
        if (track->flag_default)
1243
            st->disposition |= AV_DISPOSITION_DEFAULT;
1244

    
1245
        if (track->default_duration)
1246
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1247
                      track->default_duration, 1000000000, 30000);
1248

    
1249
        if(extradata){
1250
            st->codec->extradata = extradata;
1251
            st->codec->extradata_size = extradata_size;
1252
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1253
            st->codec->extradata = av_malloc(track->codec_priv.size);
1254
            if(st->codec->extradata == NULL)
1255
                return AVERROR(ENOMEM);
1256
            st->codec->extradata_size = track->codec_priv.size;
1257
            memcpy(st->codec->extradata,
1258
                   track->codec_priv.data + extradata_offset,
1259
                   track->codec_priv.size);
1260
        }
1261

    
1262
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1263
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1264
            st->codec->codec_tag  = track->video.fourcc;
1265
            st->codec->width  = track->video.pixel_width;
1266
            st->codec->height = track->video.pixel_height;
1267
            av_reduce(&st->codec->sample_aspect_ratio.num,
1268
                      &st->codec->sample_aspect_ratio.den,
1269
                      st->codec->height * track->video.display_width,
1270
                      st->codec-> width * track->video.display_height,
1271
                      255);
1272
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1273
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1274
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1275
            st->codec->sample_rate = track->audio.out_samplerate;
1276
            st->codec->channels = track->audio.channels;
1277
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1278
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1279
        }
1280
    }
1281

    
1282
    attachements = attachements_list->elem;
1283
    for (j=0; j<attachements_list->nb_elem; j++) {
1284
        if (!(attachements[j].filename && attachements[j].mime &&
1285
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1286
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1287
        } else {
1288
            AVStream *st = av_new_stream(s, 0);
1289
            if (st == NULL)
1290
                break;
1291
            st->filename          = av_strdup(attachements[j].filename);
1292
            st->codec->codec_id = CODEC_ID_NONE;
1293
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1294
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1295
            if(st->codec->extradata == NULL)
1296
                break;
1297
            st->codec->extradata_size = attachements[j].bin.size;
1298
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1299

    
1300
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1301
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1302
                             strlen(ff_mkv_mime_tags[i].str))) {
1303
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1304
                    break;
1305
                }
1306
            }
1307
        }
1308
    }
1309

    
1310
    chapters = chapters_list->elem;
1311
    for (i=0; i<chapters_list->nb_elem; i++)
1312
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1313
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1314
                           chapters[i].start, chapters[i].end,
1315
                           chapters[i].title);
1316

    
1317
    index_list = &matroska->index;
1318
    index = index_list->elem;
1319
    for (i=0; i<index_list->nb_elem; i++) {
1320
        EbmlList *pos_list = &index[i].pos;
1321
        MatroskaIndexPos *pos = pos_list->elem;
1322
        for (j=0; j<pos_list->nb_elem; j++) {
1323
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1324
                                                              pos[j].track);
1325
            if (track && track->stream)
1326
                av_add_index_entry(track->stream,
1327
                                   pos[j].pos + matroska->segment_start,
1328
                                   index[i].time*matroska->time_scale/AV_TIME_BASE,
1329
                                   0, 0, AVINDEX_KEYFRAME);
1330
        }
1331
    }
1332

    
1333
    return 0;
1334
}
1335

    
1336
/*
1337
 * Put one packet in an application-supplied AVPacket struct.
1338
 * Returns 0 on success or -1 on failure.
1339
 */
1340
static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1341
                                   AVPacket *pkt)
1342
{
1343
    if (matroska->num_packets > 0) {
1344
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1345
        av_free(matroska->packets[0]);
1346
        if (matroska->num_packets > 1) {
1347
            memmove(&matroska->packets[0], &matroska->packets[1],
1348
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
1349
            matroska->packets =
1350
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
1351
                           sizeof(AVPacket *));
1352
        } else {
1353
            av_freep(&matroska->packets);
1354
        }
1355
        matroska->num_packets--;
1356
        return 0;
1357
    }
1358

    
1359
    return -1;
1360
}
1361

    
1362
/*
1363
 * Free all packets in our internal queue.
1364
 */
1365
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1366
{
1367
    if (matroska->packets) {
1368
        int n;
1369
        for (n = 0; n < matroska->num_packets; n++) {
1370
            av_free_packet(matroska->packets[n]);
1371
            av_free(matroska->packets[n]);
1372
        }
1373
        av_freep(&matroska->packets);
1374
        matroska->num_packets = 0;
1375
    }
1376
}
1377

    
1378
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1379
                                int size, int64_t pos, uint64_t cluster_time,
1380
                                uint64_t duration, int is_keyframe)
1381
{
1382
    MatroskaTrack *track;
1383
    int res = 0;
1384
    AVStream *st;
1385
    AVPacket *pkt;
1386
    int16_t block_time;
1387
    uint32_t *lace_size = NULL;
1388
    int n, flags, laces = 0;
1389
    uint64_t num;
1390

    
1391
    if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1392
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1393
        return res;
1394
    }
1395
    data += n;
1396
    size -= n;
1397

    
1398
    track = matroska_find_track_by_num(matroska, num);
1399
    if (size <= 3 || !track || !track->stream) {
1400
        av_log(matroska->ctx, AV_LOG_INFO,
1401
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1402
        return res;
1403
    }
1404
    st = track->stream;
1405
    if (st->discard >= AVDISCARD_ALL)
1406
        return res;
1407
    if (duration == AV_NOPTS_VALUE)
1408
        duration = track->default_duration / matroska->time_scale;
1409

    
1410
    block_time = AV_RB16(data);
1411
    data += 2;
1412
    flags = *data++;
1413
    size -= 3;
1414
    if (is_keyframe == -1)
1415
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1416

    
1417
    if (matroska->skip_to_keyframe) {
1418
        if (!is_keyframe || st != matroska->skip_to_stream)
1419
            return res;
1420
        matroska->skip_to_keyframe = 0;
1421
    }
1422

    
1423
    switch ((flags & 0x06) >> 1) {
1424
        case 0x0: /* no lacing */
1425
            laces = 1;
1426
            lace_size = av_mallocz(sizeof(int));
1427
            lace_size[0] = size;
1428
            break;
1429

    
1430
        case 0x1: /* Xiph lacing */
1431
        case 0x2: /* fixed-size lacing */
1432
        case 0x3: /* EBML lacing */
1433
            assert(size>0); // size <=3 is checked before size-=3 above
1434
            laces = (*data) + 1;
1435
            data += 1;
1436
            size -= 1;
1437
            lace_size = av_mallocz(laces * sizeof(int));
1438

    
1439
            switch ((flags & 0x06) >> 1) {
1440
                case 0x1: /* Xiph lacing */ {
1441
                    uint8_t temp;
1442
                    uint32_t total = 0;
1443
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1444
                        while (1) {
1445
                            if (size == 0) {
1446
                                res = -1;
1447
                                break;
1448
                            }
1449
                            temp = *data;
1450
                            lace_size[n] += temp;
1451
                            data += 1;
1452
                            size -= 1;
1453
                            if (temp != 0xff)
1454
                                break;
1455
                        }
1456
                        total += lace_size[n];
1457
                    }
1458
                    lace_size[n] = size - total;
1459
                    break;
1460
                }
1461

    
1462
                case 0x2: /* fixed-size lacing */
1463
                    for (n = 0; n < laces; n++)
1464
                        lace_size[n] = size / laces;
1465
                    break;
1466

    
1467
                case 0x3: /* EBML lacing */ {
1468
                    uint32_t total;
1469
                    n = matroska_ebmlnum_uint(matroska, data, size, &num);
1470
                    if (n < 0) {
1471
                        av_log(matroska->ctx, AV_LOG_INFO,
1472
                               "EBML block data error\n");
1473
                        break;
1474
                    }
1475
                    data += n;
1476
                    size -= n;
1477
                    total = lace_size[0] = num;
1478
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1479
                        int64_t snum;
1480
                        int r;
1481
                        r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1482
                        if (r < 0) {
1483
                            av_log(matroska->ctx, AV_LOG_INFO,
1484
                                   "EBML block data error\n");
1485
                            break;
1486
                        }
1487
                        data += r;
1488
                        size -= r;
1489
                        lace_size[n] = lace_size[n - 1] + snum;
1490
                        total += lace_size[n];
1491
                    }
1492
                    lace_size[n] = size - total;
1493
                    break;
1494
                }
1495
            }
1496
            break;
1497
    }
1498

    
1499
    if (res == 0) {
1500
        uint64_t timecode = AV_NOPTS_VALUE;
1501

    
1502
        if (cluster_time != (uint64_t)-1
1503
            && (block_time >= 0 || cluster_time >= -block_time))
1504
            timecode = cluster_time + block_time;
1505

    
1506
        for (n = 0; n < laces; n++) {
1507
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1508
                st->codec->codec_id == CODEC_ID_COOK ||
1509
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1510
                int a = st->codec->block_align;
1511
                int sps = track->audio.sub_packet_size;
1512
                int cfs = track->audio.coded_framesize;
1513
                int h = track->audio.sub_packet_h;
1514
                int y = track->audio.sub_packet_cnt;
1515
                int w = track->audio.frame_size;
1516
                int x;
1517

    
1518
                if (!track->audio.pkt_cnt) {
1519
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1520
                        for (x=0; x<h/2; x++)
1521
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1522
                                   data+x*cfs, cfs);
1523
                    else
1524
                        for (x=0; x<w/sps; x++)
1525
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1526

    
1527
                    if (++track->audio.sub_packet_cnt >= h) {
1528
                        track->audio.sub_packet_cnt = 0;
1529
                        track->audio.pkt_cnt = h*w / a;
1530
                    }
1531
                }
1532
                while (track->audio.pkt_cnt) {
1533
                    pkt = av_mallocz(sizeof(AVPacket));
1534
                    av_new_packet(pkt, a);
1535
                    memcpy(pkt->data, track->audio.buf
1536
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1537
                    pkt->pos = pos;
1538
                    pkt->stream_index = st->index;
1539
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1540
                }
1541
            } else {
1542
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1543
                int offset = 0, pkt_size = lace_size[n];
1544
                uint8_t *pkt_data = data;
1545

    
1546
                if (encodings && encodings->scope & 1) {
1547
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1548
                    if (offset < 0)
1549
                        continue;
1550
                }
1551

    
1552
                pkt = av_mallocz(sizeof(AVPacket));
1553
                /* XXX: prevent data copy... */
1554
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1555
                    av_free(pkt);
1556
                    res = AVERROR(ENOMEM);
1557
                    n = laces-1;
1558
                    break;
1559
                }
1560
                if (offset)
1561
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1562
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1563

    
1564
                if (pkt_data != data)
1565
                    av_free(pkt_data);
1566

    
1567
                if (n == 0)
1568
                    pkt->flags = is_keyframe;
1569
                pkt->stream_index = st->index;
1570

    
1571
                pkt->pts = timecode;
1572
                pkt->pos = pos;
1573
                pkt->duration = duration;
1574

    
1575
                dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
1576
            }
1577

    
1578
            if (timecode != AV_NOPTS_VALUE)
1579
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1580
            data += lace_size[n];
1581
        }
1582
    }
1583

    
1584
    av_free(lace_size);
1585
    return res;
1586
}
1587

    
1588
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1589
{
1590
    MatroskaCluster cluster = { 0 };
1591
    EbmlList *blocks_list;
1592
    MatroskaBlock *blocks;
1593
    int i, res;
1594
    if (matroska->has_cluster_id){
1595
        /* For the first cluster we parse, its ID was already read as
1596
           part of matroska_read_header(), so don't read it again */
1597
        res = ebml_parse_id(matroska, matroska_clusters,
1598
                            MATROSKA_ID_CLUSTER, &cluster);
1599
        matroska->has_cluster_id = 0;
1600
    } else
1601
        res = ebml_parse(matroska, matroska_clusters, &cluster);
1602
    blocks_list = &cluster.blocks;
1603
    blocks = blocks_list->elem;
1604
    for (i=0; i<blocks_list->nb_elem; i++)
1605
        if (blocks[i].bin.size > 0)
1606
            res=matroska_parse_block(matroska,
1607
                                     blocks[i].bin.data, blocks[i].bin.size,
1608
                                     blocks[i].bin.pos,  cluster.timecode,
1609
                                     blocks[i].duration, !blocks[i].reference);
1610
    ebml_free(matroska_cluster, &cluster);
1611
    return res;
1612
}
1613

    
1614
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1615
{
1616
    MatroskaDemuxContext *matroska = s->priv_data;
1617

    
1618
    while (matroska_deliver_packet(matroska, pkt)) {
1619
        if (matroska->done)
1620
            return AVERROR(EIO);
1621
        if (matroska_parse_cluster(matroska) < 0)
1622
            matroska->done = 1;
1623
    }
1624

    
1625
    return 0;
1626
}
1627

    
1628
static int matroska_read_seek(AVFormatContext *s, int stream_index,
1629
                              int64_t timestamp, int flags)
1630
{
1631
    MatroskaDemuxContext *matroska = s->priv_data;
1632
    AVStream *st = s->streams[stream_index];
1633
    int index;
1634

    
1635
    index = av_index_search_timestamp(st, timestamp, flags);
1636
    if (index < 0)
1637
        return 0;
1638

    
1639
    matroska_clear_queue(matroska);
1640

    
1641
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1642
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1643
    matroska->skip_to_stream = st;
1644
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1645
    return 0;
1646
}
1647

    
1648
static int matroska_read_close(AVFormatContext *s)
1649
{
1650
    MatroskaDemuxContext *matroska = s->priv_data;
1651
    MatroskaTrack *tracks = matroska->tracks.elem;
1652
    int n;
1653

    
1654
    matroska_clear_queue(matroska);
1655

    
1656
    for (n=0; n < matroska->tracks.nb_elem; n++)
1657
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1658
            av_free(tracks[n].audio.buf);
1659
    ebml_free(matroska_segment, matroska);
1660

    
1661
    return 0;
1662
}
1663

    
1664
AVInputFormat matroska_demuxer = {
1665
    "matroska",
1666
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1667
    sizeof(MatroskaDemuxContext),
1668
    matroska_probe,
1669
    matroska_read_header,
1670
    matroska_read_packet,
1671
    matroska_read_close,
1672
    matroska_read_seek,
1673
};