Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 1c0a4726

History | View | Annotate | Download (70.2 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
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
#include "internal.h"
34
#include "avio_internal.h"
35
/* For ff_codec_get_id(). */
36
#include "riff.h"
37
#include "isom.h"
38
#include "rm.h"
39
#include "matroska.h"
40
#include "libavcodec/mpeg4audio.h"
41
#include "libavutil/intfloat_readwrite.h"
42
#include "libavutil/intreadwrite.h"
43
#include "libavutil/avstring.h"
44
#include "libavutil/lzo.h"
45
#if CONFIG_ZLIB
46
#include <zlib.h>
47
#endif
48
#if CONFIG_BZLIB
49
#include <bzlib.h>
50
#endif
51

    
52
typedef enum {
53
    EBML_NONE,
54
    EBML_UINT,
55
    EBML_FLOAT,
56
    EBML_STR,
57
    EBML_UTF8,
58
    EBML_BIN,
59
    EBML_NEST,
60
    EBML_PASS,
61
    EBML_STOP,
62
    EBML_TYPE_COUNT
63
} EbmlType;
64

    
65
typedef const struct EbmlSyntax {
66
    uint32_t id;
67
    EbmlType type;
68
    int list_elem_size;
69
    int data_offset;
70
    union {
71
        uint64_t    u;
72
        double      f;
73
        const char *s;
74
        const struct EbmlSyntax *n;
75
    } def;
76
} EbmlSyntax;
77

    
78
typedef struct {
79
    int nb_elem;
80
    void *elem;
81
} EbmlList;
82

    
83
typedef struct {
84
    int      size;
85
    uint8_t *data;
86
    int64_t  pos;
87
} EbmlBin;
88

    
89
typedef struct {
90
    uint64_t version;
91
    uint64_t max_size;
92
    uint64_t id_length;
93
    char    *doctype;
94
    uint64_t doctype_version;
95
} Ebml;
96

    
97
typedef struct {
98
    uint64_t algo;
99
    EbmlBin  settings;
100
} MatroskaTrackCompression;
101

    
102
typedef struct {
103
    uint64_t scope;
104
    uint64_t type;
105
    MatroskaTrackCompression compression;
106
} MatroskaTrackEncoding;
107

    
108
typedef struct {
109
    double   frame_rate;
110
    uint64_t display_width;
111
    uint64_t display_height;
112
    uint64_t pixel_width;
113
    uint64_t pixel_height;
114
    uint64_t fourcc;
115
} MatroskaTrackVideo;
116

    
117
typedef struct {
118
    double   samplerate;
119
    double   out_samplerate;
120
    uint64_t bitdepth;
121
    uint64_t channels;
122

    
123
    /* real audio header (extracted from extradata) */
124
    int      coded_framesize;
125
    int      sub_packet_h;
126
    int      frame_size;
127
    int      sub_packet_size;
128
    int      sub_packet_cnt;
129
    int      pkt_cnt;
130
    uint64_t buf_timecode;
131
    uint8_t *buf;
132
} MatroskaTrackAudio;
133

    
134
typedef struct {
135
    uint64_t num;
136
    uint64_t uid;
137
    uint64_t type;
138
    char    *name;
139
    char    *codec_id;
140
    EbmlBin  codec_priv;
141
    char    *language;
142
    double time_scale;
143
    uint64_t default_duration;
144
    uint64_t flag_default;
145
    uint64_t flag_forced;
146
    MatroskaTrackVideo video;
147
    MatroskaTrackAudio audio;
148
    EbmlList encodings;
149

    
150
    AVStream *stream;
151
    int64_t end_timecode;
152
    int ms_compat;
153
} MatroskaTrack;
154

    
155
typedef struct {
156
    uint64_t uid;
157
    char *filename;
158
    char *mime;
159
    EbmlBin bin;
160

    
161
    AVStream *stream;
162
} MatroskaAttachement;
163

    
164
typedef struct {
165
    uint64_t start;
166
    uint64_t end;
167
    uint64_t uid;
168
    char    *title;
169

    
170
    AVChapter *chapter;
171
} MatroskaChapter;
172

    
173
typedef struct {
174
    uint64_t track;
175
    uint64_t pos;
176
} MatroskaIndexPos;
177

    
178
typedef struct {
179
    uint64_t time;
180
    EbmlList pos;
181
} MatroskaIndex;
182

    
183
typedef struct {
184
    char *name;
185
    char *string;
186
    char *lang;
187
    uint64_t def;
188
    EbmlList sub;
189
} MatroskaTag;
190

    
191
typedef struct {
192
    char    *type;
193
    uint64_t typevalue;
194
    uint64_t trackuid;
195
    uint64_t chapteruid;
196
    uint64_t attachuid;
197
} MatroskaTagTarget;
198

    
199
typedef struct {
200
    MatroskaTagTarget target;
201
    EbmlList tag;
202
} MatroskaTags;
203

    
204
typedef struct {
205
    uint64_t id;
206
    uint64_t pos;
207
} MatroskaSeekhead;
208

    
209
typedef struct {
210
    uint64_t start;
211
    uint64_t length;
212
} MatroskaLevel;
213

    
214
typedef struct {
215
    AVFormatContext *ctx;
216

    
217
    /* EBML stuff */
218
    int num_levels;
219
    MatroskaLevel levels[EBML_MAX_DEPTH];
220
    int level_up;
221
    uint32_t current_id;
222

    
223
    uint64_t time_scale;
224
    double   duration;
225
    char    *title;
226
    EbmlList tracks;
227
    EbmlList attachments;
228
    EbmlList chapters;
229
    EbmlList index;
230
    EbmlList tags;
231
    EbmlList seekhead;
232

    
233
    /* byte position of the segment inside the stream */
234
    int64_t segment_start;
235

    
236
    /* the packet queue */
237
    AVPacket **packets;
238
    int num_packets;
239
    AVPacket *prev_pkt;
240

    
241
    int done;
242

    
243
    /* What to skip before effectively reading a packet. */
244
    int skip_to_keyframe;
245
    uint64_t skip_to_timecode;
246
} MatroskaDemuxContext;
247

    
248
typedef struct {
249
    uint64_t duration;
250
    int64_t  reference;
251
    uint64_t non_simple;
252
    EbmlBin  bin;
253
} MatroskaBlock;
254

    
255
typedef struct {
256
    uint64_t timecode;
257
    EbmlList blocks;
258
} MatroskaCluster;
259

    
260
static EbmlSyntax ebml_header[] = {
261
    { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
262
    { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
263
    { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
264
    { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
265
    { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
266
    { EBML_ID_EBMLVERSION,            EBML_NONE },
267
    { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
268
    { 0 }
269
};
270

    
271
static EbmlSyntax ebml_syntax[] = {
272
    { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
273
    { 0 }
274
};
275

    
276
static EbmlSyntax matroska_info[] = {
277
    { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
278
    { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
279
    { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
280
    { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
281
    { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
282
    { MATROSKA_ID_DATEUTC,            EBML_NONE },
283
    { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
284
    { 0 }
285
};
286

    
287
static EbmlSyntax matroska_track_video[] = {
288
    { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
289
    { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
290
    { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
291
    { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
292
    { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
293
    { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
294
    { MATROSKA_ID_VIDEOPIXELCROPB,    EBML_NONE },
295
    { MATROSKA_ID_VIDEOPIXELCROPT,    EBML_NONE },
296
    { MATROSKA_ID_VIDEOPIXELCROPL,    EBML_NONE },
297
    { MATROSKA_ID_VIDEOPIXELCROPR,    EBML_NONE },
298
    { MATROSKA_ID_VIDEODISPLAYUNIT,   EBML_NONE },
299
    { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
300
    { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
301
    { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
302
    { 0 }
303
};
304

    
305
static EbmlSyntax matroska_track_audio[] = {
306
    { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
307
    { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
308
    { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
309
    { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
310
    { 0 }
311
};
312

    
313
static EbmlSyntax matroska_track_encoding_compression[] = {
314
    { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
315
    { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
316
    { 0 }
317
};
318

    
319
static EbmlSyntax matroska_track_encoding[] = {
320
    { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
321
    { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
322
    { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
323
    { MATROSKA_ID_ENCODINGORDER,      EBML_NONE },
324
    { 0 }
325
};
326

    
327
static EbmlSyntax matroska_track_encodings[] = {
328
    { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
329
    { 0 }
330
};
331

    
332
static EbmlSyntax matroska_track[] = {
333
    { MATROSKA_ID_TRACKNUMBER,          EBML_UINT, 0, offsetof(MatroskaTrack,num) },
334
    { MATROSKA_ID_TRACKNAME,            EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
335
    { MATROSKA_ID_TRACKUID,             EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
336
    { MATROSKA_ID_TRACKTYPE,            EBML_UINT, 0, offsetof(MatroskaTrack,type) },
337
    { MATROSKA_ID_CODECID,              EBML_STR,  0, offsetof(MatroskaTrack,codec_id) },
338
    { MATROSKA_ID_CODECPRIVATE,         EBML_BIN,  0, offsetof(MatroskaTrack,codec_priv) },
339
    { MATROSKA_ID_TRACKLANGUAGE,        EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
340
    { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
341
    { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
342
    { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
343
    { MATROSKA_ID_TRACKFLAGFORCED,      EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
344
    { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
345
    { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
346
    { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
347
    { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
348
    { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
349
    { MATROSKA_ID_CODECNAME,            EBML_NONE },
350
    { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
351
    { MATROSKA_ID_CODECINFOURL,         EBML_NONE },
352
    { MATROSKA_ID_CODECDOWNLOADURL,     EBML_NONE },
353
    { MATROSKA_ID_TRACKMINCACHE,        EBML_NONE },
354
    { MATROSKA_ID_TRACKMAXCACHE,        EBML_NONE },
355
    { MATROSKA_ID_TRACKMAXBLKADDID,     EBML_NONE },
356
    { 0 }
357
};
358

    
359
static EbmlSyntax matroska_tracks[] = {
360
    { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
361
    { 0 }
362
};
363

    
364
static EbmlSyntax matroska_attachment[] = {
365
    { MATROSKA_ID_FILEUID,            EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
366
    { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
367
    { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
368
    { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
369
    { MATROSKA_ID_FILEDESC,           EBML_NONE },
370
    { 0 }
371
};
372

    
373
static EbmlSyntax matroska_attachments[] = {
374
    { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
375
    { 0 }
376
};
377

    
378
static EbmlSyntax matroska_chapter_display[] = {
379
    { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
380
    { MATROSKA_ID_CHAPLANG,           EBML_NONE },
381
    { 0 }
382
};
383

    
384
static EbmlSyntax matroska_chapter_entry[] = {
385
    { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
386
    { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
387
    { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
388
    { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
389
    { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
390
    { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
391
    { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
392
    { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
393
    { 0 }
394
};
395

    
396
static EbmlSyntax matroska_chapter[] = {
397
    { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
398
    { MATROSKA_ID_EDITIONUID,         EBML_NONE },
399
    { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
400
    { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
401
    { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
402
    { 0 }
403
};
404

    
405
static EbmlSyntax matroska_chapters[] = {
406
    { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
407
    { 0 }
408
};
409

    
410
static EbmlSyntax matroska_index_pos[] = {
411
    { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
412
    { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
413
    { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
414
    { 0 }
415
};
416

    
417
static EbmlSyntax matroska_index_entry[] = {
418
    { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
419
    { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
420
    { 0 }
421
};
422

    
423
static EbmlSyntax matroska_index[] = {
424
    { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
425
    { 0 }
426
};
427

    
428
static EbmlSyntax matroska_simpletag[] = {
429
    { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
430
    { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
431
    { MATROSKA_ID_TAGLANG,            EBML_STR,  0, offsetof(MatroskaTag,lang), {.s="und"} },
432
    { MATROSKA_ID_TAGDEFAULT,         EBML_UINT, 0, offsetof(MatroskaTag,def) },
433
    { MATROSKA_ID_TAGDEFAULT_BUG,     EBML_UINT, 0, offsetof(MatroskaTag,def) },
434
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
435
    { 0 }
436
};
437

    
438
static EbmlSyntax matroska_tagtargets[] = {
439
    { MATROSKA_ID_TAGTARGETS_TYPE,      EBML_STR,  0, offsetof(MatroskaTagTarget,type) },
440
    { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
441
    { MATROSKA_ID_TAGTARGETS_TRACKUID,  EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
442
    { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
443
    { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
444
    { 0 }
445
};
446

    
447
static EbmlSyntax matroska_tag[] = {
448
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
449
    { MATROSKA_ID_TAGTARGETS,         EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
450
    { 0 }
451
};
452

    
453
static EbmlSyntax matroska_tags[] = {
454
    { MATROSKA_ID_TAG,                EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
455
    { 0 }
456
};
457

    
458
static EbmlSyntax matroska_seekhead_entry[] = {
459
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
460
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
461
    { 0 }
462
};
463

    
464
static EbmlSyntax matroska_seekhead[] = {
465
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
466
    { 0 }
467
};
468

    
469
static EbmlSyntax matroska_segment[] = {
470
    { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
471
    { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
472
    { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
473
    { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
474
    { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
475
    { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
476
    { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
477
    { MATROSKA_ID_CLUSTER,        EBML_STOP },
478
    { 0 }
479
};
480

    
481
static EbmlSyntax matroska_segments[] = {
482
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
483
    { 0 }
484
};
485

    
486
static EbmlSyntax matroska_blockgroup[] = {
487
    { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
488
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
489
    { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration) },
490
    { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
491
    { 1,                          EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
492
    { 0 }
493
};
494

    
495
static EbmlSyntax matroska_cluster[] = {
496
    { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
497
    { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
498
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
499
    { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
500
    { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
501
    { 0 }
502
};
503

    
504
static EbmlSyntax matroska_clusters[] = {
505
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
506
    { MATROSKA_ID_INFO,           EBML_NONE },
507
    { MATROSKA_ID_CUES,           EBML_NONE },
508
    { MATROSKA_ID_TAGS,           EBML_NONE },
509
    { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
510
    { 0 }
511
};
512

    
513
static const char *matroska_doctypes[] = { "matroska", "webm" };
514

    
515
/*
516
 * Return: Whether we reached the end of a level in the hierarchy or not.
517
 */
518
static int ebml_level_end(MatroskaDemuxContext *matroska)
519
{
520
    AVIOContext *pb = matroska->ctx->pb;
521
    int64_t pos = avio_tell(pb);
522

    
523
    if (matroska->num_levels > 0) {
524
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
525
        if (pos - level->start >= level->length || matroska->current_id) {
526
            matroska->num_levels--;
527
            return 1;
528
        }
529
    }
530
    return 0;
531
}
532

    
533
/*
534
 * Read: an "EBML number", which is defined as a variable-length
535
 * array of bytes. The first byte indicates the length by giving a
536
 * number of 0-bits followed by a one. The position of the first
537
 * "one" bit inside the first byte indicates the length of this
538
 * number.
539
 * Returns: number of bytes read, < 0 on error
540
 */
541
static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
542
                         int max_size, uint64_t *number)
543
{
544
    int read = 1, n = 1;
545
    uint64_t total = 0;
546

    
547
    /* The first byte tells us the length in bytes - avio_r8() can normally
548
     * return 0, but since that's not a valid first ebmlID byte, we can
549
     * use it safely here to catch EOS. */
550
    if (!(total = avio_r8(pb))) {
551
        /* we might encounter EOS here */
552
        if (!url_feof(pb)) {
553
            int64_t pos = avio_tell(pb);
554
            av_log(matroska->ctx, AV_LOG_ERROR,
555
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
556
                   pos, pos);
557
        }
558
        return AVERROR(EIO); /* EOS or actual I/O error */
559
    }
560

    
561
    /* get the length of the EBML number */
562
    read = 8 - ff_log2_tab[total];
563
    if (read > max_size) {
564
        int64_t pos = avio_tell(pb) - 1;
565
        av_log(matroska->ctx, AV_LOG_ERROR,
566
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
567
               (uint8_t) total, pos, pos);
568
        return AVERROR_INVALIDDATA;
569
    }
570

    
571
    /* read out length */
572
    total ^= 1 << ff_log2_tab[total];
573
    while (n++ < read)
574
        total = (total << 8) | avio_r8(pb);
575

    
576
    *number = total;
577

    
578
    return read;
579
}
580

    
581
/**
582
 * Read a EBML length value.
583
 * This needs special handling for the "unknown length" case which has multiple
584
 * encodings.
585
 */
586
static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
587
                            uint64_t *number)
588
{
589
    int res = ebml_read_num(matroska, pb, 8, number);
590
    if (res > 0 && *number + 1 == 1ULL << (7 * res))
591
        *number = 0xffffffffffffffULL;
592
    return res;
593
}
594

    
595
/*
596
 * Read the next element as an unsigned int.
597
 * 0 is success, < 0 is failure.
598
 */
599
static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
600
{
601
    int n = 0;
602

    
603
    if (size > 8)
604
        return AVERROR_INVALIDDATA;
605

    
606
    /* big-endian ordering; build up number */
607
    *num = 0;
608
    while (n++ < size)
609
        *num = (*num << 8) | avio_r8(pb);
610

    
611
    return 0;
612
}
613

    
614
/*
615
 * Read the next element as a float.
616
 * 0 is success, < 0 is failure.
617
 */
618
static int ebml_read_float(AVIOContext *pb, int size, double *num)
619
{
620
    if (size == 0) {
621
        *num = 0;
622
    } else if (size == 4) {
623
        *num= av_int2flt(avio_rb32(pb));
624
    } else if(size==8){
625
        *num= av_int2dbl(avio_rb64(pb));
626
    } else
627
        return AVERROR_INVALIDDATA;
628

    
629
    return 0;
630
}
631

    
632
/*
633
 * Read the next element as an ASCII string.
634
 * 0 is success, < 0 is failure.
635
 */
636
static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
637
{
638
    av_free(*str);
639
    /* EBML strings are usually not 0-terminated, so we allocate one
640
     * byte more, read the string and NULL-terminate it ourselves. */
641
    if (!(*str = av_malloc(size + 1)))
642
        return AVERROR(ENOMEM);
643
    if (avio_read(pb, (uint8_t *) *str, size) != size) {
644
        av_freep(str);
645
        return AVERROR(EIO);
646
    }
647
    (*str)[size] = '\0';
648

    
649
    return 0;
650
}
651

    
652
/*
653
 * Read the next element as binary data.
654
 * 0 is success, < 0 is failure.
655
 */
656
static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
657
{
658
    av_free(bin->data);
659
    if (!(bin->data = av_malloc(length)))
660
        return AVERROR(ENOMEM);
661

    
662
    bin->size = length;
663
    bin->pos  = avio_tell(pb);
664
    if (avio_read(pb, bin->data, length) != length) {
665
        av_freep(&bin->data);
666
        return AVERROR(EIO);
667
    }
668

    
669
    return 0;
670
}
671

    
672
/*
673
 * Read the next element, but only the header. The contents
674
 * are supposed to be sub-elements which can be read separately.
675
 * 0 is success, < 0 is failure.
676
 */
677
static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
678
{
679
    AVIOContext *pb = matroska->ctx->pb;
680
    MatroskaLevel *level;
681

    
682
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
683
        av_log(matroska->ctx, AV_LOG_ERROR,
684
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
685
        return AVERROR(ENOSYS);
686
    }
687

    
688
    level = &matroska->levels[matroska->num_levels++];
689
    level->start = avio_tell(pb);
690
    level->length = length;
691

    
692
    return 0;
693
}
694

    
695
/*
696
 * Read signed/unsigned "EBML" numbers.
697
 * Return: number of bytes processed, < 0 on error
698
 */
699
static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
700
                                 uint8_t *data, uint32_t size, uint64_t *num)
701
{
702
    AVIOContext pb;
703
    ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
704
    return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
705
}
706

    
707
/*
708
 * Same as above, but signed.
709
 */
710
static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
711
                                 uint8_t *data, uint32_t size, int64_t *num)
712
{
713
    uint64_t unum;
714
    int res;
715

    
716
    /* read as unsigned number first */
717
    if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
718
        return res;
719

    
720
    /* make signed (weird way) */
721
    *num = unum - ((1LL << (7*res - 1)) - 1);
722

    
723
    return res;
724
}
725

    
726
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
727
                           EbmlSyntax *syntax, void *data);
728

    
729
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
730
                         uint32_t id, void *data)
731
{
732
    int i;
733
    for (i=0; syntax[i].id; i++)
734
        if (id == syntax[i].id)
735
            break;
736
    if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
737
        matroska->num_levels > 0 &&
738
        matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
739
        return 0;  // we reached the end of an unknown size cluster
740
    if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
741
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
742
    return ebml_parse_elem(matroska, &syntax[i], data);
743
}
744

    
745
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
746
                      void *data)
747
{
748
    if (!matroska->current_id) {
749
        uint64_t id;
750
        int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
751
        if (res < 0)
752
            return res;
753
        matroska->current_id = id | 1 << 7*res;
754
    }
755
    return ebml_parse_id(matroska, syntax, matroska->current_id, data);
756
}
757

    
758
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
759
                           void *data)
760
{
761
    int i, res = 0;
762

    
763
    for (i=0; syntax[i].id; i++)
764
        switch (syntax[i].type) {
765
        case EBML_UINT:
766
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
767
            break;
768
        case EBML_FLOAT:
769
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
770
            break;
771
        case EBML_STR:
772
        case EBML_UTF8:
773
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
774
            break;
775
        }
776

    
777
    while (!res && !ebml_level_end(matroska))
778
        res = ebml_parse(matroska, syntax, data);
779

    
780
    return res;
781
}
782

    
783
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
784
                           EbmlSyntax *syntax, void *data)
785
{
786
    static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
787
        [EBML_UINT]  = 8,
788
        [EBML_FLOAT] = 8,
789
        // max. 16 MB for strings
790
        [EBML_STR]   = 0x1000000,
791
        [EBML_UTF8]  = 0x1000000,
792
        // max. 256 MB for binary data
793
        [EBML_BIN]   = 0x10000000,
794
        // no limits for anything else
795
    };
796
    AVIOContext *pb = matroska->ctx->pb;
797
    uint32_t id = syntax->id;
798
    uint64_t length;
799
    int res;
800

    
801
    data = (char *)data + syntax->data_offset;
802
    if (syntax->list_elem_size) {
803
        EbmlList *list = data;
804
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
805
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
806
        memset(data, 0, syntax->list_elem_size);
807
        list->nb_elem++;
808
    }
809

    
810
    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
811
        matroska->current_id = 0;
812
        if ((res = ebml_read_length(matroska, pb, &length)) < 0)
813
            return res;
814
        if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
815
            av_log(matroska->ctx, AV_LOG_ERROR,
816
                   "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
817
                   length, max_lengths[syntax->type], syntax->type);
818
            return AVERROR_INVALIDDATA;
819
        }
820
    }
821

    
822
    switch (syntax->type) {
823
    case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
824
    case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
825
    case EBML_STR:
826
    case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
827
    case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
828
    case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
829
                         return res;
830
                     if (id == MATROSKA_ID_SEGMENT)
831
                         matroska->segment_start = avio_tell(matroska->ctx->pb);
832
                     return ebml_parse_nest(matroska, syntax->def.n, data);
833
    case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
834
    case EBML_STOP:  return 1;
835
    default:         return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
836
    }
837
    if (res == AVERROR_INVALIDDATA)
838
        av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
839
    else if (res == AVERROR(EIO))
840
        av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
841
    return res;
842
}
843

    
844
static void ebml_free(EbmlSyntax *syntax, void *data)
845
{
846
    int i, j;
847
    for (i=0; syntax[i].id; i++) {
848
        void *data_off = (char *)data + syntax[i].data_offset;
849
        switch (syntax[i].type) {
850
        case EBML_STR:
851
        case EBML_UTF8:  av_freep(data_off);                      break;
852
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
853
        case EBML_NEST:
854
            if (syntax[i].list_elem_size) {
855
                EbmlList *list = data_off;
856
                char *ptr = list->elem;
857
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
858
                    ebml_free(syntax[i].def.n, ptr);
859
                av_free(list->elem);
860
            } else
861
                ebml_free(syntax[i].def.n, data_off);
862
        default:  break;
863
        }
864
    }
865
}
866

    
867

    
868
/*
869
 * Autodetecting...
870
 */
871
static int matroska_probe(AVProbeData *p)
872
{
873
    uint64_t total = 0;
874
    int len_mask = 0x80, size = 1, n = 1, i;
875

    
876
    /* EBML header? */
877
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
878
        return 0;
879

    
880
    /* length of header */
881
    total = p->buf[4];
882
    while (size <= 8 && !(total & len_mask)) {
883
        size++;
884
        len_mask >>= 1;
885
    }
886
    if (size > 8)
887
      return 0;
888
    total &= (len_mask - 1);
889
    while (n < size)
890
        total = (total << 8) | p->buf[4 + n++];
891

    
892
    /* Does the probe data contain the whole header? */
893
    if (p->buf_size < 4 + size + total)
894
      return 0;
895

    
896
    /* The header should contain a known document type. For now,
897
     * we don't parse the whole header but simply check for the
898
     * availability of that array of characters inside the header.
899
     * Not fully fool-proof, but good enough. */
900
    for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
901
        int probelen = strlen(matroska_doctypes[i]);
902
        for (n = 4+size; n <= 4+size+total-probelen; n++)
903
            if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
904
                return AVPROBE_SCORE_MAX;
905
    }
906

    
907
    // probably valid EBML header but no recognized doctype
908
    return AVPROBE_SCORE_MAX/2;
909
}
910

    
911
static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
912
                                                 int num)
913
{
914
    MatroskaTrack *tracks = matroska->tracks.elem;
915
    int i;
916

    
917
    for (i=0; i < matroska->tracks.nb_elem; i++)
918
        if (tracks[i].num == num)
919
            return &tracks[i];
920

    
921
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
922
    return NULL;
923
}
924

    
925
static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
926
                                  MatroskaTrack *track)
927
{
928
    MatroskaTrackEncoding *encodings = track->encodings.elem;
929
    uint8_t* data = *buf;
930
    int isize = *buf_size;
931
    uint8_t* pkt_data = NULL;
932
    int pkt_size = isize;
933
    int result = 0;
934
    int olen;
935

    
936
    if (pkt_size >= 10000000)
937
        return -1;
938

    
939
    switch (encodings[0].compression.algo) {
940
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
941
        return encodings[0].compression.settings.size;
942
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
943
        do {
944
            olen = pkt_size *= 3;
945
            pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
946
            result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
947
        } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
948
        if (result)
949
            goto failed;
950
        pkt_size -= olen;
951
        break;
952
#if CONFIG_ZLIB
953
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
954
        z_stream zstream = {0};
955
        if (inflateInit(&zstream) != Z_OK)
956
            return -1;
957
        zstream.next_in = data;
958
        zstream.avail_in = isize;
959
        do {
960
            pkt_size *= 3;
961
            pkt_data = av_realloc(pkt_data, pkt_size);
962
            zstream.avail_out = pkt_size - zstream.total_out;
963
            zstream.next_out = pkt_data + zstream.total_out;
964
            result = inflate(&zstream, Z_NO_FLUSH);
965
        } while (result==Z_OK && pkt_size<10000000);
966
        pkt_size = zstream.total_out;
967
        inflateEnd(&zstream);
968
        if (result != Z_STREAM_END)
969
            goto failed;
970
        break;
971
    }
972
#endif
973
#if CONFIG_BZLIB
974
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
975
        bz_stream bzstream = {0};
976
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
977
            return -1;
978
        bzstream.next_in = data;
979
        bzstream.avail_in = isize;
980
        do {
981
            pkt_size *= 3;
982
            pkt_data = av_realloc(pkt_data, pkt_size);
983
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
984
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
985
            result = BZ2_bzDecompress(&bzstream);
986
        } while (result==BZ_OK && pkt_size<10000000);
987
        pkt_size = bzstream.total_out_lo32;
988
        BZ2_bzDecompressEnd(&bzstream);
989
        if (result != BZ_STREAM_END)
990
            goto failed;
991
        break;
992
    }
993
#endif
994
    default:
995
        return -1;
996
    }
997

    
998
    *buf = pkt_data;
999
    *buf_size = pkt_size;
1000
    return 0;
1001
 failed:
1002
    av_free(pkt_data);
1003
    return -1;
1004
}
1005

    
1006
static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1007
                                    AVPacket *pkt, uint64_t display_duration)
1008
{
1009
    char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1010
    for (; *ptr!=',' && ptr<end-1; ptr++);
1011
    if (*ptr == ',')
1012
        layer = ++ptr;
1013
    for (; *ptr!=',' && ptr<end-1; ptr++);
1014
    if (*ptr == ',') {
1015
        int64_t end_pts = pkt->pts + display_duration;
1016
        int sc = matroska->time_scale * pkt->pts / 10000000;
1017
        int ec = matroska->time_scale * end_pts  / 10000000;
1018
        int sh, sm, ss, eh, em, es, len;
1019
        sh = sc/360000;  sc -= 360000*sh;
1020
        sm = sc/  6000;  sc -=   6000*sm;
1021
        ss = sc/   100;  sc -=    100*ss;
1022
        eh = ec/360000;  ec -= 360000*eh;
1023
        em = ec/  6000;  ec -=   6000*em;
1024
        es = ec/   100;  ec -=    100*es;
1025
        *ptr++ = '\0';
1026
        len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1027
        if (!(line = av_malloc(len)))
1028
            return;
1029
        snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1030
                 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1031
        av_free(pkt->data);
1032
        pkt->data = line;
1033
        pkt->size = strlen(line);
1034
    }
1035
}
1036

    
1037
static void matroska_merge_packets(AVPacket *out, AVPacket *in)
1038
{
1039
    out->data = av_realloc(out->data, out->size+in->size);
1040
    memcpy(out->data+out->size, in->data, in->size);
1041
    out->size += in->size;
1042
    av_destruct_packet(in);
1043
    av_free(in);
1044
}
1045

    
1046
static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1047
                                 AVMetadata **metadata, char *prefix)
1048
{
1049
    MatroskaTag *tags = list->elem;
1050
    char key[1024];
1051
    int i;
1052

    
1053
    for (i=0; i < list->nb_elem; i++) {
1054
        const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1055

    
1056
        if (!tags[i].name) {
1057
            av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1058
            continue;
1059
        }
1060
        if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1061
        else         av_strlcpy(key, tags[i].name, sizeof(key));
1062
        if (tags[i].def || !lang) {
1063
        av_metadata_set2(metadata, key, tags[i].string, 0);
1064
        if (tags[i].sub.nb_elem)
1065
            matroska_convert_tag(s, &tags[i].sub, metadata, key);
1066
        }
1067
        if (lang) {
1068
            av_strlcat(key, "-", sizeof(key));
1069
            av_strlcat(key, lang, sizeof(key));
1070
            av_metadata_set2(metadata, key, tags[i].string, 0);
1071
            if (tags[i].sub.nb_elem)
1072
                matroska_convert_tag(s, &tags[i].sub, metadata, key);
1073
        }
1074
    }
1075
    ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1076
}
1077

    
1078
static void matroska_convert_tags(AVFormatContext *s)
1079
{
1080
    MatroskaDemuxContext *matroska = s->priv_data;
1081
    MatroskaTags *tags = matroska->tags.elem;
1082
    int i, j;
1083

    
1084
    for (i=0; i < matroska->tags.nb_elem; i++) {
1085
        if (tags[i].target.attachuid) {
1086
            MatroskaAttachement *attachment = matroska->attachments.elem;
1087
            for (j=0; j<matroska->attachments.nb_elem; j++)
1088
                if (attachment[j].uid == tags[i].target.attachuid
1089
                    && attachment[j].stream)
1090
                    matroska_convert_tag(s, &tags[i].tag,
1091
                                         &attachment[j].stream->metadata, NULL);
1092
        } else if (tags[i].target.chapteruid) {
1093
            MatroskaChapter *chapter = matroska->chapters.elem;
1094
            for (j=0; j<matroska->chapters.nb_elem; j++)
1095
                if (chapter[j].uid == tags[i].target.chapteruid
1096
                    && chapter[j].chapter)
1097
                    matroska_convert_tag(s, &tags[i].tag,
1098
                                         &chapter[j].chapter->metadata, NULL);
1099
        } else if (tags[i].target.trackuid) {
1100
            MatroskaTrack *track = matroska->tracks.elem;
1101
            for (j=0; j<matroska->tracks.nb_elem; j++)
1102
                if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1103
                    matroska_convert_tag(s, &tags[i].tag,
1104
                                         &track[j].stream->metadata, NULL);
1105
        } else {
1106
            matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1107
                                 tags[i].target.type);
1108
        }
1109
    }
1110
}
1111

    
1112
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1113
{
1114
    EbmlList *seekhead_list = &matroska->seekhead;
1115
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1116
    uint32_t level_up = matroska->level_up;
1117
    int64_t before_pos = avio_tell(matroska->ctx->pb);
1118
    uint32_t saved_id = matroska->current_id;
1119
    MatroskaLevel level;
1120
    int i;
1121

    
1122
    // we should not do any seeking in the streaming case
1123
    if (url_is_streamed(matroska->ctx->pb) ||
1124
        (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1125
        return;
1126

    
1127
    for (i=0; i<seekhead_list->nb_elem; i++) {
1128
        int64_t offset = seekhead[i].pos + matroska->segment_start;
1129

    
1130
        if (seekhead[i].pos <= before_pos
1131
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1132
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1133
            continue;
1134

    
1135
        /* seek */
1136
        if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) != offset)
1137
            continue;
1138

    
1139
        /* We don't want to lose our seekhead level, so we add
1140
         * a dummy. This is a crude hack. */
1141
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1142
            av_log(matroska->ctx, AV_LOG_INFO,
1143
                   "Max EBML element depth (%d) reached, "
1144
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1145
            break;
1146
        }
1147

    
1148
        level.start = 0;
1149
        level.length = (uint64_t)-1;
1150
        matroska->levels[matroska->num_levels] = level;
1151
        matroska->num_levels++;
1152
        matroska->current_id = 0;
1153

    
1154
        ebml_parse(matroska, matroska_segment, matroska);
1155

    
1156
        /* remove dummy level */
1157
        while (matroska->num_levels) {
1158
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1159
            if (length == (uint64_t)-1)
1160
                break;
1161
        }
1162
    }
1163

    
1164
    /* seek back */
1165
    avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1166
    matroska->level_up = level_up;
1167
    matroska->current_id = saved_id;
1168
}
1169

    
1170
static int matroska_aac_profile(char *codec_id)
1171
{
1172
    static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1173
    int profile;
1174

    
1175
    for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1176
        if (strstr(codec_id, aac_profiles[profile]))
1177
            break;
1178
    return profile + 1;
1179
}
1180

    
1181
static int matroska_aac_sri(int samplerate)
1182
{
1183
    int sri;
1184

    
1185
    for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
1186
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1187
            break;
1188
    return sri;
1189
}
1190

    
1191
static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1192
{
1193
    MatroskaDemuxContext *matroska = s->priv_data;
1194
    EbmlList *attachements_list = &matroska->attachments;
1195
    MatroskaAttachement *attachements;
1196
    EbmlList *chapters_list = &matroska->chapters;
1197
    MatroskaChapter *chapters;
1198
    MatroskaTrack *tracks;
1199
    EbmlList *index_list;
1200
    MatroskaIndex *index;
1201
    int index_scale = 1;
1202
    uint64_t max_start = 0;
1203
    Ebml ebml = { 0 };
1204
    AVStream *st;
1205
    int i, j, res;
1206

    
1207
    matroska->ctx = s;
1208

    
1209
    /* First read the EBML header. */
1210
    if (ebml_parse(matroska, ebml_syntax, &ebml)
1211
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1212
        || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1213
        av_log(matroska->ctx, AV_LOG_ERROR,
1214
               "EBML header using unsupported features\n"
1215
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1216
               ebml.version, ebml.doctype, ebml.doctype_version);
1217
        ebml_free(ebml_syntax, &ebml);
1218
        return AVERROR_PATCHWELCOME;
1219
    }
1220
    for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1221
        if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1222
            break;
1223
    if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1224
        av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1225
    }
1226
    ebml_free(ebml_syntax, &ebml);
1227

    
1228
    /* The next thing is a segment. */
1229
    if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1230
        return res;
1231
    matroska_execute_seekhead(matroska);
1232

    
1233
    if (!matroska->time_scale)
1234
        matroska->time_scale = 1000000;
1235
    if (matroska->duration)
1236
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1237
                                  * 1000 / AV_TIME_BASE;
1238
    av_metadata_set2(&s->metadata, "title", matroska->title, 0);
1239

    
1240
    tracks = matroska->tracks.elem;
1241
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1242
        MatroskaTrack *track = &tracks[i];
1243
        enum CodecID codec_id = CODEC_ID_NONE;
1244
        EbmlList *encodings_list = &tracks->encodings;
1245
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1246
        uint8_t *extradata = NULL;
1247
        int extradata_size = 0;
1248
        int extradata_offset = 0;
1249
        AVIOContext b;
1250

    
1251
        /* Apply some sanity checks. */
1252
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1253
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1254
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1255
            av_log(matroska->ctx, AV_LOG_INFO,
1256
                   "Unknown or unsupported track type %"PRIu64"\n",
1257
                   track->type);
1258
            continue;
1259
        }
1260
        if (track->codec_id == NULL)
1261
            continue;
1262

    
1263
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1264
            if (!track->default_duration)
1265
                track->default_duration = 1000000000/track->video.frame_rate;
1266
            if (!track->video.display_width)
1267
                track->video.display_width = track->video.pixel_width;
1268
            if (!track->video.display_height)
1269
                track->video.display_height = track->video.pixel_height;
1270
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1271
            if (!track->audio.out_samplerate)
1272
                track->audio.out_samplerate = track->audio.samplerate;
1273
        }
1274
        if (encodings_list->nb_elem > 1) {
1275
            av_log(matroska->ctx, AV_LOG_ERROR,
1276
                   "Multiple combined encodings no supported");
1277
        } else if (encodings_list->nb_elem == 1) {
1278
            if (encodings[0].type ||
1279
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1280
#if CONFIG_ZLIB
1281
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1282
#endif
1283
#if CONFIG_BZLIB
1284
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1285
#endif
1286
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1287
                encodings[0].scope = 0;
1288
                av_log(matroska->ctx, AV_LOG_ERROR,
1289
                       "Unsupported encoding type");
1290
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1291
                uint8_t *codec_priv = track->codec_priv.data;
1292
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1293
                                                    &track->codec_priv.size,
1294
                                                    track);
1295
                if (offset < 0) {
1296
                    track->codec_priv.data = NULL;
1297
                    track->codec_priv.size = 0;
1298
                    av_log(matroska->ctx, AV_LOG_ERROR,
1299
                           "Failed to decode codec private data\n");
1300
                } else if (offset > 0) {
1301
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1302
                    memcpy(track->codec_priv.data,
1303
                           encodings[0].compression.settings.data, offset);
1304
                    memcpy(track->codec_priv.data+offset, codec_priv,
1305
                           track->codec_priv.size);
1306
                    track->codec_priv.size += offset;
1307
                }
1308
                if (codec_priv != track->codec_priv.data)
1309
                    av_free(codec_priv);
1310
            }
1311
        }
1312

    
1313
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1314
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1315
                        strlen(ff_mkv_codec_tags[j].str))){
1316
                codec_id= ff_mkv_codec_tags[j].id;
1317
                break;
1318
            }
1319
        }
1320

    
1321
        st = track->stream = av_new_stream(s, 0);
1322
        if (st == NULL)
1323
            return AVERROR(ENOMEM);
1324

    
1325
        if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1326
            && track->codec_priv.size >= 40
1327
            && track->codec_priv.data != NULL) {
1328
            track->ms_compat = 1;
1329
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1330
            codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1331
            extradata_offset = 40;
1332
        } else if (!strcmp(track->codec_id, "A_MS/ACM")
1333
                   && track->codec_priv.size >= 14
1334
                   && track->codec_priv.data != NULL) {
1335
            ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1336
                          URL_RDONLY, NULL, NULL, NULL, NULL);
1337
            ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1338
            codec_id = st->codec->codec_id;
1339
            extradata_offset = FFMIN(track->codec_priv.size, 18);
1340
        } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1341
                   && (track->codec_priv.size >= 86)
1342
                   && (track->codec_priv.data != NULL)) {
1343
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1344
            codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
1345
        } else if (codec_id == CODEC_ID_PCM_S16BE) {
1346
            switch (track->audio.bitdepth) {
1347
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1348
            case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
1349
            case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
1350
            }
1351
        } else if (codec_id == CODEC_ID_PCM_S16LE) {
1352
            switch (track->audio.bitdepth) {
1353
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1354
            case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
1355
            case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
1356
            }
1357
        } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1358
            codec_id = CODEC_ID_PCM_F64LE;
1359
        } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1360
            int profile = matroska_aac_profile(track->codec_id);
1361
            int sri = matroska_aac_sri(track->audio.samplerate);
1362
            extradata = av_malloc(5);
1363
            if (extradata == NULL)
1364
                return AVERROR(ENOMEM);
1365
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1366
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1367
            if (strstr(track->codec_id, "SBR")) {
1368
                sri = matroska_aac_sri(track->audio.out_samplerate);
1369
                extradata[2] = 0x56;
1370
                extradata[3] = 0xE5;
1371
                extradata[4] = 0x80 | (sri<<3);
1372
                extradata_size = 5;
1373
            } else
1374
                extradata_size = 2;
1375
        } else if (codec_id == CODEC_ID_TTA) {
1376
            extradata_size = 30;
1377
            extradata = av_mallocz(extradata_size);
1378
            if (extradata == NULL)
1379
                return AVERROR(ENOMEM);
1380
            ffio_init_context(&b, extradata, extradata_size, 1,
1381
                          NULL, NULL, NULL, NULL);
1382
            avio_write(&b, "TTA1", 4);
1383
            avio_wl16(&b, 1);
1384
            avio_wl16(&b, track->audio.channels);
1385
            avio_wl16(&b, track->audio.bitdepth);
1386
            avio_wl32(&b, track->audio.out_samplerate);
1387
            avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1388
        } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1389
                   codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1390
            extradata_offset = 26;
1391
        } else if (codec_id == CODEC_ID_RA_144) {
1392
            track->audio.out_samplerate = 8000;
1393
            track->audio.channels = 1;
1394
        } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1395
                   codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1396
            int flavor;
1397
            ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1398
                          0, NULL, NULL, NULL, NULL);
1399
            avio_skip(&b, 22);
1400
            flavor                       = avio_rb16(&b);
1401
            track->audio.coded_framesize = avio_rb32(&b);
1402
            avio_skip(&b, 12);
1403
            track->audio.sub_packet_h    = avio_rb16(&b);
1404
            track->audio.frame_size      = avio_rb16(&b);
1405
            track->audio.sub_packet_size = avio_rb16(&b);
1406
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1407
            if (codec_id == CODEC_ID_RA_288) {
1408
                st->codec->block_align = track->audio.coded_framesize;
1409
                track->codec_priv.size = 0;
1410
            } else {
1411
                if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1412
                    const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1413
                    track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1414
                    st->codec->bit_rate = sipr_bit_rate[flavor];
1415
                }
1416
                st->codec->block_align = track->audio.sub_packet_size;
1417
                extradata_offset = 78;
1418
            }
1419
        }
1420
        track->codec_priv.size -= extradata_offset;
1421

    
1422
        if (codec_id == CODEC_ID_NONE)
1423
            av_log(matroska->ctx, AV_LOG_INFO,
1424
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1425

    
1426
        if (track->time_scale < 0.01)
1427
            track->time_scale = 1.0;
1428
        av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1429

    
1430
        st->codec->codec_id = codec_id;
1431
        st->start_time = 0;
1432
        if (strcmp(track->language, "und"))
1433
            av_metadata_set2(&st->metadata, "language", track->language, 0);
1434
        av_metadata_set2(&st->metadata, "title", track->name, 0);
1435

    
1436
        if (track->flag_default)
1437
            st->disposition |= AV_DISPOSITION_DEFAULT;
1438
        if (track->flag_forced)
1439
            st->disposition |= AV_DISPOSITION_FORCED;
1440

    
1441
        if (track->default_duration)
1442
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1443
                      track->default_duration, 1000000000, 30000);
1444

    
1445
        if (!st->codec->extradata) {
1446
            if(extradata){
1447
                st->codec->extradata = extradata;
1448
                st->codec->extradata_size = extradata_size;
1449
            } else if(track->codec_priv.data && track->codec_priv.size > 0){
1450
                st->codec->extradata = av_mallocz(track->codec_priv.size +
1451
                                                  FF_INPUT_BUFFER_PADDING_SIZE);
1452
                if(st->codec->extradata == NULL)
1453
                    return AVERROR(ENOMEM);
1454
                st->codec->extradata_size = track->codec_priv.size;
1455
                memcpy(st->codec->extradata,
1456
                       track->codec_priv.data + extradata_offset,
1457
                       track->codec_priv.size);
1458
            }
1459
        }
1460

    
1461
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1462
            st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1463
            st->codec->codec_tag  = track->video.fourcc;
1464
            st->codec->width  = track->video.pixel_width;
1465
            st->codec->height = track->video.pixel_height;
1466
            av_reduce(&st->sample_aspect_ratio.num,
1467
                      &st->sample_aspect_ratio.den,
1468
                      st->codec->height * track->video.display_width,
1469
                      st->codec-> width * track->video.display_height,
1470
                      255);
1471
            if (st->codec->codec_id != CODEC_ID_H264)
1472
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1473
            if (track->default_duration)
1474
                st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
1475
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1476
            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1477
            st->codec->sample_rate = track->audio.out_samplerate;
1478
            st->codec->channels = track->audio.channels;
1479
            if (st->codec->codec_id != CODEC_ID_AAC)
1480
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1481
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1482
            st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1483
        }
1484
    }
1485

    
1486
    attachements = attachements_list->elem;
1487
    for (j=0; j<attachements_list->nb_elem; j++) {
1488
        if (!(attachements[j].filename && attachements[j].mime &&
1489
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1490
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1491
        } else {
1492
            AVStream *st = av_new_stream(s, 0);
1493
            if (st == NULL)
1494
                break;
1495
            av_metadata_set2(&st->metadata, "filename",attachements[j].filename, 0);
1496
            st->codec->codec_id = CODEC_ID_NONE;
1497
            st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1498
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1499
            if(st->codec->extradata == NULL)
1500
                break;
1501
            st->codec->extradata_size = attachements[j].bin.size;
1502
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1503

    
1504
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1505
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1506
                             strlen(ff_mkv_mime_tags[i].str))) {
1507
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1508
                    break;
1509
                }
1510
            }
1511
            attachements[j].stream = st;
1512
        }
1513
    }
1514

    
1515
    chapters = chapters_list->elem;
1516
    for (i=0; i<chapters_list->nb_elem; i++)
1517
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1518
            && (max_start==0 || chapters[i].start > max_start)) {
1519
            chapters[i].chapter =
1520
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1521
                           chapters[i].start, chapters[i].end,
1522
                           chapters[i].title);
1523
            av_metadata_set2(&chapters[i].chapter->metadata,
1524
                             "title", chapters[i].title, 0);
1525
            max_start = chapters[i].start;
1526
        }
1527

    
1528
    index_list = &matroska->index;
1529
    index = index_list->elem;
1530
    if (index_list->nb_elem
1531
        && index[0].time > 100000000000000/matroska->time_scale) {
1532
        av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1533
        index_scale = matroska->time_scale;
1534
    }
1535
    for (i=0; i<index_list->nb_elem; i++) {
1536
        EbmlList *pos_list = &index[i].pos;
1537
        MatroskaIndexPos *pos = pos_list->elem;
1538
        for (j=0; j<pos_list->nb_elem; j++) {
1539
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1540
                                                              pos[j].track);
1541
            if (track && track->stream)
1542
                av_add_index_entry(track->stream,
1543
                                   pos[j].pos + matroska->segment_start,
1544
                                   index[i].time/index_scale, 0, 0,
1545
                                   AVINDEX_KEYFRAME);
1546
        }
1547
    }
1548

    
1549
    matroska_convert_tags(s);
1550

    
1551
    return 0;
1552
}
1553

    
1554
/*
1555
 * Put one packet in an application-supplied AVPacket struct.
1556
 * Returns 0 on success or -1 on failure.
1557
 */
1558
static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1559
                                   AVPacket *pkt)
1560
{
1561
    if (matroska->num_packets > 0) {
1562
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1563
        av_free(matroska->packets[0]);
1564
        if (matroska->num_packets > 1) {
1565
            memmove(&matroska->packets[0], &matroska->packets[1],
1566
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
1567
            matroska->packets =
1568
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
1569
                           sizeof(AVPacket *));
1570
        } else {
1571
            av_freep(&matroska->packets);
1572
        }
1573
        matroska->num_packets--;
1574
        return 0;
1575
    }
1576

    
1577
    return -1;
1578
}
1579

    
1580
/*
1581
 * Free all packets in our internal queue.
1582
 */
1583
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1584
{
1585
    if (matroska->packets) {
1586
        int n;
1587
        for (n = 0; n < matroska->num_packets; n++) {
1588
            av_free_packet(matroska->packets[n]);
1589
            av_free(matroska->packets[n]);
1590
        }
1591
        av_freep(&matroska->packets);
1592
        matroska->num_packets = 0;
1593
    }
1594
}
1595

    
1596
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1597
                                int size, int64_t pos, uint64_t cluster_time,
1598
                                uint64_t duration, int is_keyframe,
1599
                                int64_t cluster_pos)
1600
{
1601
    uint64_t timecode = AV_NOPTS_VALUE;
1602
    MatroskaTrack *track;
1603
    int res = 0;
1604
    AVStream *st;
1605
    AVPacket *pkt;
1606
    int16_t block_time;
1607
    uint32_t *lace_size = NULL;
1608
    int n, flags, laces = 0;
1609
    uint64_t num;
1610

    
1611
    if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1612
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1613
        return res;
1614
    }
1615
    data += n;
1616
    size -= n;
1617

    
1618
    track = matroska_find_track_by_num(matroska, num);
1619
    if (size <= 3 || !track || !track->stream) {
1620
        av_log(matroska->ctx, AV_LOG_INFO,
1621
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1622
        return res;
1623
    }
1624
    st = track->stream;
1625
    if (st->discard >= AVDISCARD_ALL)
1626
        return res;
1627
    if (!duration)
1628
        duration = track->default_duration / matroska->time_scale;
1629

    
1630
    block_time = AV_RB16(data);
1631
    data += 2;
1632
    flags = *data++;
1633
    size -= 3;
1634
    if (is_keyframe == -1)
1635
        is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1636

    
1637
    if (cluster_time != (uint64_t)-1
1638
        && (block_time >= 0 || cluster_time >= -block_time)) {
1639
        timecode = cluster_time + block_time;
1640
        if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1641
            && timecode < track->end_timecode)
1642
            is_keyframe = 0;  /* overlapping subtitles are not key frame */
1643
        if (is_keyframe)
1644
            av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1645
        track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1646
    }
1647

    
1648
    if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1649
        if (!is_keyframe || timecode < matroska->skip_to_timecode)
1650
            return res;
1651
        matroska->skip_to_keyframe = 0;
1652
    }
1653

    
1654
    switch ((flags & 0x06) >> 1) {
1655
        case 0x0: /* no lacing */
1656
            laces = 1;
1657
            lace_size = av_mallocz(sizeof(int));
1658
            lace_size[0] = size;
1659
            break;
1660

    
1661
        case 0x1: /* Xiph lacing */
1662
        case 0x2: /* fixed-size lacing */
1663
        case 0x3: /* EBML lacing */
1664
            assert(size>0); // size <=3 is checked before size-=3 above
1665
            laces = (*data) + 1;
1666
            data += 1;
1667
            size -= 1;
1668
            lace_size = av_mallocz(laces * sizeof(int));
1669

    
1670
            switch ((flags & 0x06) >> 1) {
1671
                case 0x1: /* Xiph lacing */ {
1672
                    uint8_t temp;
1673
                    uint32_t total = 0;
1674
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1675
                        while (1) {
1676
                            if (size == 0) {
1677
                                res = -1;
1678
                                break;
1679
                            }
1680
                            temp = *data;
1681
                            lace_size[n] += temp;
1682
                            data += 1;
1683
                            size -= 1;
1684
                            if (temp != 0xff)
1685
                                break;
1686
                        }
1687
                        total += lace_size[n];
1688
                    }
1689
                    lace_size[n] = size - total;
1690
                    break;
1691
                }
1692

    
1693
                case 0x2: /* fixed-size lacing */
1694
                    for (n = 0; n < laces; n++)
1695
                        lace_size[n] = size / laces;
1696
                    break;
1697

    
1698
                case 0x3: /* EBML lacing */ {
1699
                    uint32_t total;
1700
                    n = matroska_ebmlnum_uint(matroska, data, size, &num);
1701
                    if (n < 0) {
1702
                        av_log(matroska->ctx, AV_LOG_INFO,
1703
                               "EBML block data error\n");
1704
                        break;
1705
                    }
1706
                    data += n;
1707
                    size -= n;
1708
                    total = lace_size[0] = num;
1709
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1710
                        int64_t snum;
1711
                        int r;
1712
                        r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1713
                        if (r < 0) {
1714
                            av_log(matroska->ctx, AV_LOG_INFO,
1715
                                   "EBML block data error\n");
1716
                            break;
1717
                        }
1718
                        data += r;
1719
                        size -= r;
1720
                        lace_size[n] = lace_size[n - 1] + snum;
1721
                        total += lace_size[n];
1722
                    }
1723
                    lace_size[n] = size - total;
1724
                    break;
1725
                }
1726
            }
1727
            break;
1728
    }
1729

    
1730
    if (res == 0) {
1731
        for (n = 0; n < laces; n++) {
1732
            if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1733
                 st->codec->codec_id == CODEC_ID_COOK ||
1734
                 st->codec->codec_id == CODEC_ID_SIPR ||
1735
                 st->codec->codec_id == CODEC_ID_ATRAC3) &&
1736
                 st->codec->block_align && track->audio.sub_packet_size) {
1737
                int a = st->codec->block_align;
1738
                int sps = track->audio.sub_packet_size;
1739
                int cfs = track->audio.coded_framesize;
1740
                int h = track->audio.sub_packet_h;
1741
                int y = track->audio.sub_packet_cnt;
1742
                int w = track->audio.frame_size;
1743
                int x;
1744

    
1745
                if (!track->audio.pkt_cnt) {
1746
                    if (track->audio.sub_packet_cnt == 0)
1747
                        track->audio.buf_timecode = timecode;
1748
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1749
                        for (x=0; x<h/2; x++)
1750
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1751
                                   data+x*cfs, cfs);
1752
                    else if (st->codec->codec_id == CODEC_ID_SIPR)
1753
                        memcpy(track->audio.buf + y*w, data, w);
1754
                    else
1755
                        for (x=0; x<w/sps; x++)
1756
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1757

    
1758
                    if (++track->audio.sub_packet_cnt >= h) {
1759
                        if (st->codec->codec_id == CODEC_ID_SIPR)
1760
                            ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1761
                        track->audio.sub_packet_cnt = 0;
1762
                        track->audio.pkt_cnt = h*w / a;
1763
                    }
1764
                }
1765
                while (track->audio.pkt_cnt) {
1766
                    pkt = av_mallocz(sizeof(AVPacket));
1767
                    av_new_packet(pkt, a);
1768
                    memcpy(pkt->data, track->audio.buf
1769
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1770
                    pkt->pts = track->audio.buf_timecode;
1771
                    track->audio.buf_timecode = AV_NOPTS_VALUE;
1772
                    pkt->pos = pos;
1773
                    pkt->stream_index = st->index;
1774
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1775
                }
1776
            } else {
1777
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1778
                int offset = 0, pkt_size = lace_size[n];
1779
                uint8_t *pkt_data = data;
1780

    
1781
                if (pkt_size > size) {
1782
                    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1783
                    break;
1784
                }
1785

    
1786
                if (encodings && encodings->scope & 1) {
1787
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1788
                    if (offset < 0)
1789
                        continue;
1790
                }
1791

    
1792
                pkt = av_mallocz(sizeof(AVPacket));
1793
                /* XXX: prevent data copy... */
1794
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1795
                    av_free(pkt);
1796
                    res = AVERROR(ENOMEM);
1797
                    break;
1798
                }
1799
                if (offset)
1800
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1801
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1802

    
1803
                if (pkt_data != data)
1804
                    av_free(pkt_data);
1805

    
1806
                if (n == 0)
1807
                    pkt->flags = is_keyframe;
1808
                pkt->stream_index = st->index;
1809

    
1810
                if (track->ms_compat)
1811
                    pkt->dts = timecode;
1812
                else
1813
                    pkt->pts = timecode;
1814
                pkt->pos = pos;
1815
                if (st->codec->codec_id == CODEC_ID_TEXT)
1816
                    pkt->convergence_duration = duration;
1817
                else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1818
                    pkt->duration = duration;
1819

    
1820
                if (st->codec->codec_id == CODEC_ID_SSA)
1821
                    matroska_fix_ass_packet(matroska, pkt, duration);
1822

    
1823
                if (matroska->prev_pkt &&
1824
                    timecode != AV_NOPTS_VALUE &&
1825
                    matroska->prev_pkt->pts == timecode &&
1826
                    matroska->prev_pkt->stream_index == st->index &&
1827
                    st->codec->codec_id == CODEC_ID_SSA)
1828
                    matroska_merge_packets(matroska->prev_pkt, pkt);
1829
                else {
1830
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1831
                    matroska->prev_pkt = pkt;
1832
                }
1833
            }
1834

    
1835
            if (timecode != AV_NOPTS_VALUE)
1836
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1837
            data += lace_size[n];
1838
            size -= lace_size[n];
1839
        }
1840
    }
1841

    
1842
    av_free(lace_size);
1843
    return res;
1844
}
1845

    
1846
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1847
{
1848
    MatroskaCluster cluster = { 0 };
1849
    EbmlList *blocks_list;
1850
    MatroskaBlock *blocks;
1851
    int i, res;
1852
    int64_t pos = avio_tell(matroska->ctx->pb);
1853
    matroska->prev_pkt = NULL;
1854
    if (matroska->current_id)
1855
        pos -= 4;  /* sizeof the ID which was already read */
1856
    res = ebml_parse(matroska, matroska_clusters, &cluster);
1857
    blocks_list = &cluster.blocks;
1858
    blocks = blocks_list->elem;
1859
    for (i=0; i<blocks_list->nb_elem; i++)
1860
        if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
1861
            int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
1862
            res=matroska_parse_block(matroska,
1863
                                     blocks[i].bin.data, blocks[i].bin.size,
1864
                                     blocks[i].bin.pos,  cluster.timecode,
1865
                                     blocks[i].duration, is_keyframe,
1866
                                     pos);
1867
        }
1868
    ebml_free(matroska_cluster, &cluster);
1869
    if (res < 0)  matroska->done = 1;
1870
    return res;
1871
}
1872

    
1873
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1874
{
1875
    MatroskaDemuxContext *matroska = s->priv_data;
1876

    
1877
    while (matroska_deliver_packet(matroska, pkt)) {
1878
        if (matroska->done)
1879
            return AVERROR_EOF;
1880
        matroska_parse_cluster(matroska);
1881
    }
1882

    
1883
    return 0;
1884
}
1885

    
1886
static int matroska_read_seek(AVFormatContext *s, int stream_index,
1887
                              int64_t timestamp, int flags)
1888
{
1889
    MatroskaDemuxContext *matroska = s->priv_data;
1890
    MatroskaTrack *tracks = matroska->tracks.elem;
1891
    AVStream *st = s->streams[stream_index];
1892
    int i, index, index_sub, index_min;
1893

    
1894
    if (!st->nb_index_entries)
1895
        return 0;
1896
    timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1897

    
1898
    if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1899
        avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1900
        while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1901
            matroska_clear_queue(matroska);
1902
            if (matroska_parse_cluster(matroska) < 0)
1903
                break;
1904
        }
1905
    }
1906

    
1907
    matroska_clear_queue(matroska);
1908
    if (index < 0)
1909
        return 0;
1910

    
1911
    index_min = index;
1912
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1913
        tracks[i].audio.pkt_cnt = 0;
1914
        tracks[i].audio.sub_packet_cnt = 0;
1915
        tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
1916
        tracks[i].end_timecode = 0;
1917
        if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1918
            && !tracks[i].stream->discard != AVDISCARD_ALL) {
1919
            index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1920
            if (index_sub >= 0
1921
                && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1922
                && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1923
                index_min = index_sub;
1924
        }
1925
    }
1926

    
1927
    avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
1928
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1929
    matroska->skip_to_timecode = st->index_entries[index].timestamp;
1930
    matroska->done = 0;
1931
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1932
    return 0;
1933
}
1934

    
1935
static int matroska_read_close(AVFormatContext *s)
1936
{
1937
    MatroskaDemuxContext *matroska = s->priv_data;
1938
    MatroskaTrack *tracks = matroska->tracks.elem;
1939
    int n;
1940

    
1941
    matroska_clear_queue(matroska);
1942

    
1943
    for (n=0; n < matroska->tracks.nb_elem; n++)
1944
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1945
            av_free(tracks[n].audio.buf);
1946
    ebml_free(matroska_segment, matroska);
1947

    
1948
    return 0;
1949
}
1950

    
1951
AVInputFormat ff_matroska_demuxer = {
1952
    "matroska,webm",
1953
    NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
1954
    sizeof(MatroskaDemuxContext),
1955
    matroska_probe,
1956
    matroska_read_header,
1957
    matroska_read_packet,
1958
    matroska_read_close,
1959
    matroska_read_seek,
1960
};