Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ e7d4b743

History | View | Annotate | Download (61.7 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 <stdio.h>
32
#include "avformat.h"
33
/* For codec_get_id(). */
34
#include "riff.h"
35
#include "isom.h"
36
#include "matroska.h"
37
#include "libavcodec/mpeg4audio.h"
38
#include "libavutil/intfloat_readwrite.h"
39
#include "libavutil/avstring.h"
40
#include "libavutil/lzo.h"
41
#ifdef CONFIG_ZLIB
42
#include <zlib.h>
43
#endif
44
#ifdef CONFIG_BZLIB
45
#include <bzlib.h>
46
#endif
47

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

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

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

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

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

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

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

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

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

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

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

    
141
    AVStream *stream;
142
    int64_t end_timecode;
143
} MatroskaTrack;
144

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

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

    
158
typedef struct {
159
    uint64_t track;
160
    uint64_t pos;
161
} MatroskaIndexPos;
162

    
163
typedef struct {
164
    uint64_t time;
165
    EbmlList pos;
166
} MatroskaIndex;
167

    
168
typedef struct {
169
    char *name;
170
    char *string;
171
    EbmlList sub;
172
} MatroskaTag;
173

    
174
typedef struct {
175
    uint64_t id;
176
    uint64_t pos;
177
} MatroskaSeekhead;
178

    
179
typedef struct {
180
    uint64_t start;
181
    uint64_t length;
182
} MatroskaLevel;
183

    
184
typedef struct {
185
    AVFormatContext *ctx;
186

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

    
192
    uint64_t time_scale;
193
    double   duration;
194
    char    *title;
195
    EbmlList tracks;
196
    EbmlList attachments;
197
    EbmlList chapters;
198
    EbmlList index;
199
    EbmlList tags;
200
    EbmlList seekhead;
201

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

    
205
    /* the packet queue */
206
    AVPacket **packets;
207
    int num_packets;
208

    
209
    int done;
210
    int has_cluster_id;
211

    
212
    /* What to skip before effectively reading a packet. */
213
    int skip_to_keyframe;
214
    uint64_t skip_to_timecode;
215
} MatroskaDemuxContext;
216

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

    
223
typedef struct {
224
    uint64_t timecode;
225
    EbmlList blocks;
226
} MatroskaCluster;
227

    
228
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
229

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

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

    
246
static EbmlSyntax matroska_info[] = {
247
    { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
248
    { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
249
    { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
250
    { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
251
    { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
252
    { MATROSKA_ID_DATEUTC,            EBML_NONE },
253
    { MATROSKA_ID_SEGMENTUID,         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_VIDEOPIXELCROPB,    EBML_NONE },
265
    { MATROSKA_ID_VIDEOPIXELCROPT,    EBML_NONE },
266
    { MATROSKA_ID_VIDEOPIXELCROPL,    EBML_NONE },
267
    { MATROSKA_ID_VIDEOPIXELCROPR,    EBML_NONE },
268
    { MATROSKA_ID_VIDEODISPLAYUNIT,   EBML_NONE },
269
    { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
270
    { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
271
    { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
272
    { 0 }
273
};
274

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

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

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

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

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

    
329
static EbmlSyntax matroska_tracks[] = {
330
    { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
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_FILEDESC,           EBML_NONE },
339
    { MATROSKA_ID_FILEUID,            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
    { 0 }
346
};
347

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

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

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

    
375
static EbmlSyntax matroska_chapters[] = {
376
    { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
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
    { MATROSKA_ID_CUEBLOCKNUMBER,     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
    { 0 }
391
};
392

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

    
398
static EbmlSyntax matroska_simpletag[] = {
399
    { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
400
    { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
401
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
402
    { MATROSKA_ID_TAGLANG,            EBML_NONE },
403
    { MATROSKA_ID_TAGDEFAULT,         EBML_NONE },
404
    { 0 }
405
};
406

    
407
static EbmlSyntax matroska_tag[] = {
408
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), 0, {.n=matroska_simpletag} },
409
    { MATROSKA_ID_TAGTARGETS,         EBML_NONE },
410
    { 0 }
411
};
412

    
413
static EbmlSyntax matroska_tags[] = {
414
    { MATROSKA_ID_TAG,                EBML_NEST, 0, offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
415
    { 0 }
416
};
417

    
418
static EbmlSyntax matroska_seekhead_entry[] = {
419
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
420
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
421
    { 0 }
422
};
423

    
424
static EbmlSyntax matroska_seekhead[] = {
425
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
426
    { 0 }
427
};
428

    
429
static EbmlSyntax matroska_segment[] = {
430
    { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
431
    { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
432
    { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
433
    { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
434
    { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
435
    { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
436
    { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
437
    { MATROSKA_ID_CLUSTER,        EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
438
    { 0 }
439
};
440

    
441
static EbmlSyntax matroska_segments[] = {
442
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
443
    { 0 }
444
};
445

    
446
static EbmlSyntax matroska_blockgroup[] = {
447
    { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
448
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
449
    { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
450
    { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
451
    { 0 }
452
};
453

    
454
static EbmlSyntax matroska_cluster[] = {
455
    { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
456
    { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
457
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
458
    { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
459
    { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
460
    { 0 }
461
};
462

    
463
static EbmlSyntax matroska_clusters[] = {
464
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
465
    { MATROSKA_ID_INFO,           EBML_NONE },
466
    { MATROSKA_ID_CUES,           EBML_NONE },
467
    { MATROSKA_ID_TAGS,           EBML_NONE },
468
    { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
469
    { 0 }
470
};
471

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

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

    
499
    if (matroska->num_levels > 0) {
500
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
501
        if (pos - level->start >= level->length) {
502
            matroska->num_levels--;
503
            return 1;
504
        }
505
    }
506
    return 0;
507
}
508

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

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

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

    
550
    /* read out length */
551
    total &= ~len_mask;
552
    while (n++ < read)
553
        total = (total << 8) | get_byte(pb);
554

    
555
    *number = total;
556

    
557
    return read;
558
}
559

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

    
568
    if (size < 1 || size > 8)
569
        return AVERROR_INVALIDDATA;
570

    
571
    /* big-endian ordering; build up number */
572
    *num = 0;
573
    while (n++ < size)
574
        *num = (*num << 8) | get_byte(pb);
575

    
576
    return 0;
577
}
578

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

    
592
    return 0;
593
}
594

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

    
612
    return 0;
613
}
614

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

    
625
    bin->size = length;
626
    bin->pos  = url_ftell(pb);
627
    if (get_buffer(pb, bin->data, length) != length)
628
        return AVERROR(EIO);
629

    
630
    return 0;
631
}
632

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

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

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

    
653
    return 0;
654
}
655

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

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

    
677
    /* read as unsigned number first */
678
    if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
679
        return res;
680

    
681
    /* make signed (weird way) */
682
    *num = unum - ((1LL << (7*res - 1)) - 1);
683

    
684
    return res;
685
}
686

    
687
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
688
                           EbmlSyntax *syntax, void *data);
689

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

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

    
711
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
712
                           void *data)
713
{
714
    int i, res = 0;
715

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

    
730
    while (!res && !ebml_level_end(matroska))
731
        res = ebml_parse(matroska, syntax, data);
732

    
733
    return res;
734
}
735

    
736
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
737
                           EbmlSyntax *syntax, void *data)
738
{
739
    ByteIOContext *pb = matroska->ctx->pb;
740
    uint32_t id = syntax->id;
741
    uint64_t length;
742
    int res;
743

    
744
    data = (char *)data + syntax->data_offset;
745
    if (syntax->list_elem_size) {
746
        EbmlList *list = data;
747
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
748
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
749
        memset(data, 0, syntax->list_elem_size);
750
        list->nb_elem++;
751
    }
752

    
753
    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
754
        if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
755
            return res;
756

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

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

    
802

    
803
/*
804
 * Autodetecting...
805
 */
806
static int matroska_probe(AVProbeData *p)
807
{
808
    uint64_t total = 0;
809
    int len_mask = 0x80, size = 1, n = 1;
810
    static const char probe_data[] = "matroska";
811

    
812
    /* EBML header? */
813
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
814
        return 0;
815

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

    
828
    /* Does the probe data contain the whole header? */
829
    if (p->buf_size < 4 + size + total)
830
      return 0;
831

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

    
840
    return 0;
841
}
842

    
843
static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
844
                                                 int num)
845
{
846
    MatroskaTrack *tracks = matroska->tracks.elem;
847
    int i;
848

    
849
    for (i=0; i < matroska->tracks.nb_elem; i++)
850
        if (tracks[i].num == num)
851
            return &tracks[i];
852

    
853
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
854
    return NULL;
855
}
856

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

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

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

    
936
static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
937
                                    AVPacket *pkt, uint64_t display_duration)
938
{
939
    char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
940
    for (; *ptr!=',' && ptr<end-1; ptr++);
941
    if (*ptr == ',')
942
        layer = ++ptr;
943
    for (; *ptr!=',' && ptr<end-1; ptr++);
944
    if (*ptr == ',') {
945
        int64_t end_pts = pkt->pts + display_duration;
946
        int sc = matroska->time_scale * pkt->pts / 10000000;
947
        int ec = matroska->time_scale * end_pts  / 10000000;
948
        int sh, sm, ss, eh, em, es, len;
949
        sh = sc/360000;  sc -= 360000*sh;
950
        sm = sc/  6000;  sc -=   6000*sm;
951
        ss = sc/   100;  sc -=    100*ss;
952
        eh = ec/360000;  ec -= 360000*eh;
953
        em = ec/  6000;  ec -=   6000*em;
954
        es = ec/   100;  ec -=    100*es;
955
        *ptr++ = '\0';
956
        len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
957
        if (!(line = av_malloc(len)))
958
            return;
959
        snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s",
960
                 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
961
        av_free(pkt->data);
962
        pkt->data = line;
963
        pkt->size = strlen(line);
964
    }
965
}
966

    
967
static void matroska_convert_tags(AVFormatContext *s, EbmlList *list)
968
{
969
    MatroskaTag *tags = list->elem;
970
    int i, j;
971

    
972
    for (i=0; i < list->nb_elem; i++) {
973
        for (j=0; j < ARRAY_SIZE(metadata); j++){
974
            if (!strcmp(tags[i].name, metadata[j].name)) {
975
                int *ptr = (int *)((char *)s + metadata[j].offset);
976
                if (*ptr)  continue;
977
                if (metadata[j].size > sizeof(int))
978
                    av_strlcpy((char *)ptr, tags[i].string, metadata[j].size);
979
                else
980
                    *ptr = atoi(tags[i].string);
981
            }
982
        }
983
        if (tags[i].sub.nb_elem)
984
            matroska_convert_tags(s, &tags[i].sub);
985
    }
986
}
987

    
988
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
989
{
990
    EbmlList *seekhead_list = &matroska->seekhead;
991
    MatroskaSeekhead *seekhead = seekhead_list->elem;
992
    uint32_t level_up = matroska->level_up;
993
    offset_t before_pos = url_ftell(matroska->ctx->pb);
994
    MatroskaLevel level;
995
    int i;
996

    
997
    for (i=0; i<seekhead_list->nb_elem; i++) {
998
        offset_t offset = seekhead[i].pos + matroska->segment_start;
999

    
1000
        if (seekhead[i].pos <= before_pos
1001
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1002
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1003
            continue;
1004

    
1005
        /* seek */
1006
        if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
1007
            continue;
1008

    
1009
        /* We don't want to lose our seekhead level, so we add
1010
         * a dummy. This is a crude hack. */
1011
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1012
            av_log(matroska->ctx, AV_LOG_INFO,
1013
                   "Max EBML element depth (%d) reached, "
1014
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1015
            break;
1016
        }
1017

    
1018
        level.start = 0;
1019
        level.length = (uint64_t)-1;
1020
        matroska->levels[matroska->num_levels] = level;
1021
        matroska->num_levels++;
1022

    
1023
        ebml_parse(matroska, matroska_segment, matroska);
1024

    
1025
        /* remove dummy level */
1026
        while (matroska->num_levels) {
1027
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1028
            if (length == (uint64_t)-1)
1029
                break;
1030
        }
1031
    }
1032

    
1033
    /* seek back */
1034
    url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
1035
    matroska->level_up = level_up;
1036
}
1037

    
1038
static int matroska_aac_profile(char *codec_id)
1039
{
1040
    static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1041
    int profile;
1042

    
1043
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1044
        if (strstr(codec_id, aac_profiles[profile]))
1045
            break;
1046
    return profile + 1;
1047
}
1048

    
1049
static int matroska_aac_sri(int samplerate)
1050
{
1051
    int sri;
1052

    
1053
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1054
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1055
            break;
1056
    return sri;
1057
}
1058

    
1059
static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1060
{
1061
    MatroskaDemuxContext *matroska = s->priv_data;
1062
    EbmlList *attachements_list = &matroska->attachments;
1063
    MatroskaAttachement *attachements;
1064
    EbmlList *chapters_list = &matroska->chapters;
1065
    MatroskaChapter *chapters;
1066
    MatroskaTrack *tracks;
1067
    EbmlList *index_list;
1068
    MatroskaIndex *index;
1069
    Ebml ebml = { 0 };
1070
    AVStream *st;
1071
    int i, j;
1072

    
1073
    matroska->ctx = s;
1074

    
1075
    /* First read the EBML header. */
1076
    if (ebml_parse(matroska, ebml_syntax, &ebml)
1077
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1078
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1079
        || ebml.doctype_version > 2) {
1080
        av_log(matroska->ctx, AV_LOG_ERROR,
1081
               "EBML header using unsupported features\n"
1082
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1083
               ebml.version, ebml.doctype, ebml.doctype_version);
1084
        return AVERROR_NOFMT;
1085
    }
1086
    ebml_free(ebml_syntax, &ebml);
1087

    
1088
    /* The next thing is a segment. */
1089
    if (ebml_parse(matroska, matroska_segments, matroska) < 0)
1090
        return -1;
1091
    matroska_execute_seekhead(matroska);
1092

    
1093
    if (matroska->duration)
1094
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1095
                                  * 1000 / AV_TIME_BASE;
1096
    if (matroska->title)
1097
        strncpy(matroska->ctx->title, matroska->title,
1098
                sizeof(matroska->ctx->title)-1);
1099
    matroska_convert_tags(s, &matroska->tags);
1100

    
1101
    tracks = matroska->tracks.elem;
1102
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1103
        MatroskaTrack *track = &tracks[i];
1104
        enum CodecID codec_id = CODEC_ID_NONE;
1105
        EbmlList *encodings_list = &tracks->encodings;
1106
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1107
        uint8_t *extradata = NULL;
1108
        int extradata_size = 0;
1109
        int extradata_offset = 0;
1110

    
1111
        /* Apply some sanity checks. */
1112
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1113
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1114
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1115
            av_log(matroska->ctx, AV_LOG_INFO,
1116
                   "Unknown or unsupported track type %"PRIu64"\n",
1117
                   track->type);
1118
            continue;
1119
        }
1120
        if (track->codec_id == NULL)
1121
            continue;
1122

    
1123
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1124
            if (!track->default_duration)
1125
                track->default_duration = 1000000000/track->video.frame_rate;
1126
            if (!track->video.display_width)
1127
                track->video.display_width = track->video.pixel_width;
1128
            if (!track->video.display_height)
1129
                track->video.display_height = track->video.pixel_height;
1130
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1131
            if (!track->audio.out_samplerate)
1132
                track->audio.out_samplerate = track->audio.samplerate;
1133
        }
1134
        if (encodings_list->nb_elem > 1) {
1135
            av_log(matroska->ctx, AV_LOG_ERROR,
1136
                   "Multiple combined encodings no supported");
1137
        } else if (encodings_list->nb_elem == 1) {
1138
            if (encodings[0].type ||
1139
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1140
#ifdef CONFIG_ZLIB
1141
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1142
#endif
1143
#ifdef CONFIG_BZLIB
1144
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1145
#endif
1146
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1147
                encodings[0].scope = 0;
1148
                av_log(matroska->ctx, AV_LOG_ERROR,
1149
                       "Unsupported encoding type");
1150
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1151
                uint8_t *codec_priv = track->codec_priv.data;
1152
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1153
                                                    &track->codec_priv.size,
1154
                                                    track);
1155
                if (offset < 0) {
1156
                    track->codec_priv.data = NULL;
1157
                    track->codec_priv.size = 0;
1158
                    av_log(matroska->ctx, AV_LOG_ERROR,
1159
                           "Failed to decode codec private data\n");
1160
                } else if (offset > 0) {
1161
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1162
                    memcpy(track->codec_priv.data,
1163
                           encodings[0].compression.settings.data, offset);
1164
                    memcpy(track->codec_priv.data+offset, codec_priv,
1165
                           track->codec_priv.size);
1166
                    track->codec_priv.size += offset;
1167
                }
1168
                if (codec_priv != track->codec_priv.data)
1169
                    av_free(codec_priv);
1170
            }
1171
        }
1172

    
1173
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1174
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1175
                        strlen(ff_mkv_codec_tags[j].str))){
1176
                codec_id= ff_mkv_codec_tags[j].id;
1177
                break;
1178
            }
1179
        }
1180

    
1181
        st = track->stream = av_new_stream(s, 0);
1182
        if (st == NULL)
1183
            return AVERROR(ENOMEM);
1184

    
1185
        if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1186
            && track->codec_priv.size >= 40
1187
            && track->codec_priv.data != NULL) {
1188
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1189
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1190
        } else if (!strcmp(track->codec_id, "A_MS/ACM")
1191
                   && track->codec_priv.size >= 18
1192
                   && track->codec_priv.data != NULL) {
1193
            uint16_t tag = AV_RL16(track->codec_priv.data);
1194
            codec_id = codec_get_id(codec_wav_tags, tag);
1195
        } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1196
                   && (track->codec_priv.size >= 86)
1197
                   && (track->codec_priv.data != NULL)) {
1198
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1199
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1200
        } else if (codec_id == CODEC_ID_PCM_S16BE) {
1201
            switch (track->audio.bitdepth) {
1202
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1203
            case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
1204
            case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
1205
            }
1206
        } else if (codec_id == CODEC_ID_PCM_S16LE) {
1207
            switch (track->audio.bitdepth) {
1208
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1209
            case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
1210
            case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
1211
            }
1212
        } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1213
            codec_id = CODEC_ID_PCM_F64LE;
1214
        } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1215
            int profile = matroska_aac_profile(track->codec_id);
1216
            int sri = matroska_aac_sri(track->audio.samplerate);
1217
            extradata = av_malloc(5);
1218
            if (extradata == NULL)
1219
                return AVERROR(ENOMEM);
1220
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1221
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1222
            if (strstr(track->codec_id, "SBR")) {
1223
                sri = matroska_aac_sri(track->audio.out_samplerate);
1224
                extradata[2] = 0x56;
1225
                extradata[3] = 0xE5;
1226
                extradata[4] = 0x80 | (sri<<3);
1227
                extradata_size = 5;
1228
            } else
1229
                extradata_size = 2;
1230
        } else if (codec_id == CODEC_ID_TTA) {
1231
            ByteIOContext b;
1232
            extradata_size = 30;
1233
            extradata = av_mallocz(extradata_size);
1234
            if (extradata == NULL)
1235
                return AVERROR(ENOMEM);
1236
            init_put_byte(&b, extradata, extradata_size, 1,
1237
                          NULL, NULL, NULL, NULL);
1238
            put_buffer(&b, "TTA1", 4);
1239
            put_le16(&b, 1);
1240
            put_le16(&b, track->audio.channels);
1241
            put_le16(&b, track->audio.bitdepth);
1242
            put_le32(&b, track->audio.out_samplerate);
1243
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1244
        } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1245
                   codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1246
            extradata_offset = 26;
1247
            track->codec_priv.size -= extradata_offset;
1248
        } else if (codec_id == CODEC_ID_RA_144) {
1249
            track->audio.out_samplerate = 8000;
1250
            track->audio.channels = 1;
1251
        } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1252
                   codec_id == CODEC_ID_ATRAC3) {
1253
            ByteIOContext b;
1254

    
1255
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1256
                          0, NULL, NULL, NULL, NULL);
1257
            url_fskip(&b, 24);
1258
            track->audio.coded_framesize = get_be32(&b);
1259
            url_fskip(&b, 12);
1260
            track->audio.sub_packet_h    = get_be16(&b);
1261
            track->audio.frame_size      = get_be16(&b);
1262
            track->audio.sub_packet_size = get_be16(&b);
1263
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1264
            if (codec_id == CODEC_ID_RA_288) {
1265
                st->codec->block_align = track->audio.coded_framesize;
1266
                track->codec_priv.size = 0;
1267
            } else {
1268
                st->codec->block_align = track->audio.sub_packet_size;
1269
                extradata_offset = 78;
1270
                track->codec_priv.size -= extradata_offset;
1271
            }
1272
        }
1273

    
1274
        if (codec_id == CODEC_ID_NONE)
1275
            av_log(matroska->ctx, AV_LOG_INFO,
1276
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1277

    
1278
        if (track->time_scale < 0.01)
1279
            track->time_scale = 1.0;
1280
        av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1281

    
1282
        st->codec->codec_id = codec_id;
1283
        st->start_time = 0;
1284
        if (strcmp(track->language, "und"))
1285
            av_strlcpy(st->language, track->language, 4);
1286

    
1287
        if (track->flag_default)
1288
            st->disposition |= AV_DISPOSITION_DEFAULT;
1289

    
1290
        if (track->default_duration)
1291
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1292
                      track->default_duration, 1000000000, 30000);
1293

    
1294
        if(extradata){
1295
            st->codec->extradata = extradata;
1296
            st->codec->extradata_size = extradata_size;
1297
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1298
            st->codec->extradata = av_malloc(track->codec_priv.size);
1299
            if(st->codec->extradata == NULL)
1300
                return AVERROR(ENOMEM);
1301
            st->codec->extradata_size = track->codec_priv.size;
1302
            memcpy(st->codec->extradata,
1303
                   track->codec_priv.data + extradata_offset,
1304
                   track->codec_priv.size);
1305
        }
1306

    
1307
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1308
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1309
            st->codec->codec_tag  = track->video.fourcc;
1310
            st->codec->width  = track->video.pixel_width;
1311
            st->codec->height = track->video.pixel_height;
1312
            av_reduce(&st->sample_aspect_ratio.num,
1313
                      &st->sample_aspect_ratio.den,
1314
                      st->codec->height * track->video.display_width,
1315
                      st->codec-> width * track->video.display_height,
1316
                      255);
1317
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1318
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1319
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1320
            st->codec->sample_rate = track->audio.out_samplerate;
1321
            st->codec->channels = track->audio.channels;
1322
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1323
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1324
        }
1325
    }
1326

    
1327
    attachements = attachements_list->elem;
1328
    for (j=0; j<attachements_list->nb_elem; j++) {
1329
        if (!(attachements[j].filename && attachements[j].mime &&
1330
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1331
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1332
        } else {
1333
            AVStream *st = av_new_stream(s, 0);
1334
            if (st == NULL)
1335
                break;
1336
            st->filename          = av_strdup(attachements[j].filename);
1337
            st->codec->codec_id = CODEC_ID_NONE;
1338
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1339
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1340
            if(st->codec->extradata == NULL)
1341
                break;
1342
            st->codec->extradata_size = attachements[j].bin.size;
1343
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1344

    
1345
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1346
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1347
                             strlen(ff_mkv_mime_tags[i].str))) {
1348
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1349
                    break;
1350
                }
1351
            }
1352
        }
1353
    }
1354

    
1355
    chapters = chapters_list->elem;
1356
    for (i=0; i<chapters_list->nb_elem; i++)
1357
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1358
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1359
                           chapters[i].start, chapters[i].end,
1360
                           chapters[i].title);
1361

    
1362
    index_list = &matroska->index;
1363
    index = index_list->elem;
1364
    for (i=0; i<index_list->nb_elem; i++) {
1365
        EbmlList *pos_list = &index[i].pos;
1366
        MatroskaIndexPos *pos = pos_list->elem;
1367
        for (j=0; j<pos_list->nb_elem; j++) {
1368
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1369
                                                              pos[j].track);
1370
            if (track && track->stream)
1371
                av_add_index_entry(track->stream,
1372
                                   pos[j].pos + matroska->segment_start,
1373
                                   index[i].time, 0, 0, AVINDEX_KEYFRAME);
1374
        }
1375
    }
1376

    
1377
    return 0;
1378
}
1379

    
1380
/*
1381
 * Put one packet in an application-supplied AVPacket struct.
1382
 * Returns 0 on success or -1 on failure.
1383
 */
1384
static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1385
                                   AVPacket *pkt)
1386
{
1387
    if (matroska->num_packets > 0) {
1388
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1389
        av_free(matroska->packets[0]);
1390
        if (matroska->num_packets > 1) {
1391
            memmove(&matroska->packets[0], &matroska->packets[1],
1392
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
1393
            matroska->packets =
1394
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
1395
                           sizeof(AVPacket *));
1396
        } else {
1397
            av_freep(&matroska->packets);
1398
        }
1399
        matroska->num_packets--;
1400
        return 0;
1401
    }
1402

    
1403
    return -1;
1404
}
1405

    
1406
/*
1407
 * Free all packets in our internal queue.
1408
 */
1409
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1410
{
1411
    if (matroska->packets) {
1412
        int n;
1413
        for (n = 0; n < matroska->num_packets; n++) {
1414
            av_free_packet(matroska->packets[n]);
1415
            av_free(matroska->packets[n]);
1416
        }
1417
        av_freep(&matroska->packets);
1418
        matroska->num_packets = 0;
1419
    }
1420
}
1421

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

    
1437
    if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1438
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1439
        return res;
1440
    }
1441
    data += n;
1442
    size -= n;
1443

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

    
1456
    block_time = AV_RB16(data);
1457
    data += 2;
1458
    flags = *data++;
1459
    size -= 3;
1460
    if (is_keyframe == -1)
1461
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1462

    
1463
    if (cluster_time != (uint64_t)-1
1464
        && (block_time >= 0 || cluster_time >= -block_time)) {
1465
        timecode = cluster_time + block_time;
1466
        if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1467
            && timecode < track->end_timecode)
1468
            is_keyframe = 0;  /* overlapping subtitles are not key frame */
1469
        if (is_keyframe)
1470
            av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1471
        track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1472
    }
1473

    
1474
    if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1475
        if (!is_keyframe || timecode < matroska->skip_to_timecode)
1476
            return res;
1477
        matroska->skip_to_keyframe = 0;
1478
    }
1479

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

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

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

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

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

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

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

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

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

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

    
1615
                if (pkt_data != data)
1616
                    av_free(pkt_data);
1617

    
1618
                if (n == 0)
1619
                    pkt->flags = is_keyframe;
1620
                pkt->stream_index = st->index;
1621

    
1622
                pkt->pts = timecode;
1623
                pkt->pos = pos;
1624
                if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE)
1625
                    pkt->convergence_duration = duration;
1626
                else
1627
                    pkt->duration = duration;
1628

    
1629
                if (st->codec->codec_id == CODEC_ID_SSA)
1630
                    matroska_fix_ass_packet(matroska, pkt, duration);
1631

    
1632
                dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
1633
            }
1634

    
1635
            if (timecode != AV_NOPTS_VALUE)
1636
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1637
            data += lace_size[n];
1638
        }
1639
    }
1640

    
1641
    av_free(lace_size);
1642
    return res;
1643
}
1644

    
1645
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1646
{
1647
    MatroskaCluster cluster = { 0 };
1648
    EbmlList *blocks_list;
1649
    MatroskaBlock *blocks;
1650
    int i, res;
1651
    offset_t pos = url_ftell(matroska->ctx->pb);
1652
    if (matroska->has_cluster_id){
1653
        /* For the first cluster we parse, its ID was already read as
1654
           part of matroska_read_header(), so don't read it again */
1655
        res = ebml_parse_id(matroska, matroska_clusters,
1656
                            MATROSKA_ID_CLUSTER, &cluster);
1657
        pos -= 4;  /* sizeof the ID which was already read */
1658
        matroska->has_cluster_id = 0;
1659
    } else
1660
        res = ebml_parse(matroska, matroska_clusters, &cluster);
1661
    blocks_list = &cluster.blocks;
1662
    blocks = blocks_list->elem;
1663
    for (i=0; i<blocks_list->nb_elem; i++)
1664
        if (blocks[i].bin.size > 0)
1665
            res=matroska_parse_block(matroska,
1666
                                     blocks[i].bin.data, blocks[i].bin.size,
1667
                                     blocks[i].bin.pos,  cluster.timecode,
1668
                                     blocks[i].duration, !blocks[i].reference,
1669
                                     pos);
1670
    ebml_free(matroska_cluster, &cluster);
1671
    if (res < 0)  matroska->done = 1;
1672
    return res;
1673
}
1674

    
1675
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1676
{
1677
    MatroskaDemuxContext *matroska = s->priv_data;
1678

    
1679
    while (matroska_deliver_packet(matroska, pkt)) {
1680
        if (matroska->done)
1681
            return AVERROR(EIO);
1682
        matroska_parse_cluster(matroska);
1683
    }
1684

    
1685
    return 0;
1686
}
1687

    
1688
static int matroska_read_seek(AVFormatContext *s, int stream_index,
1689
                              int64_t timestamp, int flags)
1690
{
1691
    MatroskaDemuxContext *matroska = s->priv_data;
1692
    MatroskaTrack *tracks = matroska->tracks.elem;
1693
    AVStream *st = s->streams[stream_index];
1694
    int i, index, index_sub, index_min;
1695

    
1696
    if (!st->nb_index_entries)
1697
        return 0;
1698
    timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1699

    
1700
    if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1701
        url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1702
        while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1703
            matroska_clear_queue(matroska);
1704
            if (matroska_parse_cluster(matroska) < 0)
1705
                break;
1706
        }
1707
    }
1708

    
1709
    matroska_clear_queue(matroska);
1710
    if (index < 0)
1711
        return 0;
1712

    
1713
    index_min = index;
1714
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1715
        tracks[i].end_timecode = 0;
1716
        if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1717
            && !tracks[i].stream->discard != AVDISCARD_ALL) {
1718
            index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1719
            if (index_sub >= 0
1720
                && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1721
                && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1722
                index_min = index_sub;
1723
        }
1724
    }
1725

    
1726
    url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
1727
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1728
    matroska->skip_to_timecode = st->index_entries[index].timestamp;
1729
    matroska->done = 0;
1730
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1731
    return 0;
1732
}
1733

    
1734
static int matroska_read_close(AVFormatContext *s)
1735
{
1736
    MatroskaDemuxContext *matroska = s->priv_data;
1737
    MatroskaTrack *tracks = matroska->tracks.elem;
1738
    int n;
1739

    
1740
    matroska_clear_queue(matroska);
1741

    
1742
    for (n=0; n < matroska->tracks.nb_elem; n++)
1743
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1744
            av_free(tracks[n].audio.buf);
1745
    ebml_free(matroska_segment, matroska);
1746

    
1747
    return 0;
1748
}
1749

    
1750
AVInputFormat matroska_demuxer = {
1751
    "matroska",
1752
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1753
    sizeof(MatroskaDemuxContext),
1754
    matroska_probe,
1755
    matroska_read_header,
1756
    matroska_read_packet,
1757
    matroska_read_close,
1758
    matroska_read_seek,
1759
};