Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 95ec3d4c

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

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

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

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

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

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

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

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

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

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

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

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

    
148
    AVStream *stream;
149
    int64_t end_timecode;
150
    int ms_compat;
151
} MatroskaTrack;
152

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

    
159
    AVStream *stream;
160
} MatroskaAttachement;
161

    
162
typedef struct {
163
    uint64_t start;
164
    uint64_t end;
165
    uint64_t uid;
166
    char    *title;
167

    
168
    AVChapter *chapter;
169
} MatroskaChapter;
170

    
171
typedef struct {
172
    uint64_t track;
173
    uint64_t pos;
174
} MatroskaIndexPos;
175

    
176
typedef struct {
177
    uint64_t time;
178
    EbmlList pos;
179
} MatroskaIndex;
180

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

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

    
197
typedef struct {
198
    MatroskaTagTarget target;
199
    EbmlList tag;
200
} MatroskaTags;
201

    
202
typedef struct {
203
    uint64_t id;
204
    uint64_t pos;
205
} MatroskaSeekhead;
206

    
207
typedef struct {
208
    uint64_t start;
209
    uint64_t length;
210
} MatroskaLevel;
211

    
212
typedef struct {
213
    AVFormatContext *ctx;
214

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

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

    
231
    /* byte position of the segment inside the stream */
232
    int64_t segment_start;
233

    
234
    /* the packet queue */
235
    AVPacket **packets;
236
    int num_packets;
237
    AVPacket *prev_pkt;
238

    
239
    int done;
240

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

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

    
253
typedef struct {
254
    uint64_t timecode;
255
    EbmlList blocks;
256
} MatroskaCluster;
257

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
511
static const char *matroska_doctypes[] = { "matroska", "webm" };
512

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

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

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

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

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

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

    
574
    *number = total;
575

    
576
    return read;
577
}
578

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

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

    
601
    if (size > 8)
602
        return AVERROR_INVALIDDATA;
603

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

    
609
    return 0;
610
}
611

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

    
627
    return 0;
628
}
629

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

    
647
    return 0;
648
}
649

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

    
660
    bin->size = length;
661
    bin->pos  = url_ftell(pb);
662
    if (get_buffer(pb, bin->data, length) != length) {
663
        av_freep(&bin->data);
664
        return AVERROR(EIO);
665
    }
666

    
667
    return 0;
668
}
669

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

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

    
686
    level = &matroska->levels[matroska->num_levels++];
687
    level->start = url_ftell(pb);
688
    level->length = length;
689

    
690
    return 0;
691
}
692

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

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

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

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

    
721
    return res;
722
}
723

    
724
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
725
                           EbmlSyntax *syntax, void *data);
726

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

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

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

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

    
775
    while (!res && !ebml_level_end(matroska))
776
        res = ebml_parse(matroska, syntax, data);
777

    
778
    return res;
779
}
780

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

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

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

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

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

    
865

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

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

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

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

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

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

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

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

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

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

    
934
    if (pkt_size >= 10000000)
935
        return -1;
936

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

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

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

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

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

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

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

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

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

    
1108
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1109
{
1110
    EbmlList *seekhead_list = &matroska->seekhead;
1111
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1112
    uint32_t level_up = matroska->level_up;
1113
    int64_t before_pos = url_ftell(matroska->ctx->pb);
1114
    uint32_t saved_id = matroska->current_id;
1115
    MatroskaLevel level;
1116
    int i;
1117

    
1118
    // we should not do any seeking in the streaming case
1119
    if (url_is_streamed(matroska->ctx->pb) ||
1120
        (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1121
        return;
1122

    
1123
    for (i=0; i<seekhead_list->nb_elem; i++) {
1124
        int64_t offset = seekhead[i].pos + matroska->segment_start;
1125

    
1126
        if (seekhead[i].pos <= before_pos
1127
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1128
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1129
            continue;
1130

    
1131
        /* seek */
1132
        if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
1133
            continue;
1134

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

    
1144
        level.start = 0;
1145
        level.length = (uint64_t)-1;
1146
        matroska->levels[matroska->num_levels] = level;
1147
        matroska->num_levels++;
1148
        matroska->current_id = 0;
1149

    
1150
        ebml_parse(matroska, matroska_segment, matroska);
1151

    
1152
        /* remove dummy level */
1153
        while (matroska->num_levels) {
1154
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1155
            if (length == (uint64_t)-1)
1156
                break;
1157
        }
1158
    }
1159

    
1160
    /* seek back */
1161
    url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
1162
    matroska->level_up = level_up;
1163
    matroska->current_id = saved_id;
1164
}
1165

    
1166
static int matroska_aac_profile(char *codec_id)
1167
{
1168
    static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1169
    int profile;
1170

    
1171
    for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1172
        if (strstr(codec_id, aac_profiles[profile]))
1173
            break;
1174
    return profile + 1;
1175
}
1176

    
1177
static int matroska_aac_sri(int samplerate)
1178
{
1179
    int sri;
1180

    
1181
    for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
1182
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1183
            break;
1184
    return sri;
1185
}
1186

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

    
1203
    matroska->ctx = s;
1204

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

    
1224
    /* The next thing is a segment. */
1225
    if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1226
        return res;
1227
    matroska_execute_seekhead(matroska);
1228

    
1229
    if (!matroska->time_scale)
1230
        matroska->time_scale = 1000000;
1231
    if (matroska->duration)
1232
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1233
                                  * 1000 / AV_TIME_BASE;
1234
    av_metadata_set2(&s->metadata, "title", matroska->title, 0);
1235

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

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

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

    
1309
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1310
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1311
                        strlen(ff_mkv_codec_tags[j].str))){
1312
                codec_id= ff_mkv_codec_tags[j].id;
1313
                break;
1314
            }
1315
        }
1316

    
1317
        st = track->stream = av_new_stream(s, 0);
1318
        if (st == NULL)
1319
            return AVERROR(ENOMEM);
1320

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

    
1418
        if (codec_id == CODEC_ID_NONE)
1419
            av_log(matroska->ctx, AV_LOG_INFO,
1420
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1421

    
1422
        if (track->time_scale < 0.01)
1423
            track->time_scale = 1.0;
1424
        av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1425

    
1426
        st->codec->codec_id = codec_id;
1427
        st->start_time = 0;
1428
        if (strcmp(track->language, "und"))
1429
            av_metadata_set2(&st->metadata, "language", track->language, 0);
1430
        av_metadata_set2(&st->metadata, "title", track->name, 0);
1431

    
1432
        if (track->flag_default)
1433
            st->disposition |= AV_DISPOSITION_DEFAULT;
1434
        if (track->flag_forced)
1435
            st->disposition |= AV_DISPOSITION_FORCED;
1436

    
1437
        if (track->default_duration)
1438
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1439
                      track->default_duration, 1000000000, 30000);
1440

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

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

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

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

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

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

    
1545
    matroska_convert_tags(s);
1546

    
1547
    return 0;
1548
}
1549

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

    
1573
    return -1;
1574
}
1575

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

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

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

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

    
1626
    block_time = AV_RB16(data);
1627
    data += 2;
1628
    flags = *data++;
1629
    size -= 3;
1630
    if (is_keyframe == -1)
1631
        is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1632

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

    
1644
    if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1645
        if (!is_keyframe || timecode < matroska->skip_to_timecode)
1646
            return res;
1647
        matroska->skip_to_keyframe = 0;
1648
    }
1649

    
1650
    switch ((flags & 0x06) >> 1) {
1651
        case 0x0: /* no lacing */
1652
            laces = 1;
1653
            lace_size = av_mallocz(sizeof(int));
1654
            lace_size[0] = size;
1655
            break;
1656

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

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

    
1689
                case 0x2: /* fixed-size lacing */
1690
                    for (n = 0; n < laces; n++)
1691
                        lace_size[n] = size / laces;
1692
                    break;
1693

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

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

    
1741
                if (!track->audio.pkt_cnt) {
1742
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1743
                        for (x=0; x<h/2; x++)
1744
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1745
                                   data+x*cfs, cfs);
1746
                    else if (st->codec->codec_id == CODEC_ID_SIPR)
1747
                        memcpy(track->audio.buf + y*w, data, w);
1748
                    else
1749
                        for (x=0; x<w/sps; x++)
1750
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1751

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

    
1773
                if (pkt_size > size) {
1774
                    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1775
                    break;
1776
                }
1777

    
1778
                if (encodings && encodings->scope & 1) {
1779
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1780
                    if (offset < 0)
1781
                        continue;
1782
                }
1783

    
1784
                pkt = av_mallocz(sizeof(AVPacket));
1785
                /* XXX: prevent data copy... */
1786
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1787
                    av_free(pkt);
1788
                    res = AVERROR(ENOMEM);
1789
                    break;
1790
                }
1791
                if (offset)
1792
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1793
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1794

    
1795
                if (pkt_data != data)
1796
                    av_free(pkt_data);
1797

    
1798
                if (n == 0)
1799
                    pkt->flags = is_keyframe;
1800
                pkt->stream_index = st->index;
1801

    
1802
                if (track->ms_compat)
1803
                    pkt->dts = timecode;
1804
                else
1805
                    pkt->pts = timecode;
1806
                pkt->pos = pos;
1807
                if (st->codec->codec_id == CODEC_ID_TEXT)
1808
                    pkt->convergence_duration = duration;
1809
                else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1810
                    pkt->duration = duration;
1811

    
1812
                if (st->codec->codec_id == CODEC_ID_SSA)
1813
                    matroska_fix_ass_packet(matroska, pkt, duration);
1814

    
1815
                if (matroska->prev_pkt &&
1816
                    timecode != AV_NOPTS_VALUE &&
1817
                    matroska->prev_pkt->pts == timecode &&
1818
                    matroska->prev_pkt->stream_index == st->index &&
1819
                    st->codec->codec_id == CODEC_ID_SSA)
1820
                    matroska_merge_packets(matroska->prev_pkt, pkt);
1821
                else {
1822
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1823
                    matroska->prev_pkt = pkt;
1824
                }
1825
            }
1826

    
1827
            if (timecode != AV_NOPTS_VALUE)
1828
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1829
            data += lace_size[n];
1830
            size -= lace_size[n];
1831
        }
1832
    }
1833

    
1834
    av_free(lace_size);
1835
    return res;
1836
}
1837

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

    
1865
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1866
{
1867
    MatroskaDemuxContext *matroska = s->priv_data;
1868

    
1869
    while (matroska_deliver_packet(matroska, pkt)) {
1870
        if (matroska->done)
1871
            return AVERROR_EOF;
1872
        matroska_parse_cluster(matroska);
1873
    }
1874

    
1875
    return 0;
1876
}
1877

    
1878
static int matroska_read_seek(AVFormatContext *s, int stream_index,
1879
                              int64_t timestamp, int flags)
1880
{
1881
    MatroskaDemuxContext *matroska = s->priv_data;
1882
    MatroskaTrack *tracks = matroska->tracks.elem;
1883
    AVStream *st = s->streams[stream_index];
1884
    int i, index, index_sub, index_min;
1885

    
1886
    if (!st->nb_index_entries)
1887
        return 0;
1888
    timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1889

    
1890
    if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1891
        url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1892
        while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1893
            matroska_clear_queue(matroska);
1894
            if (matroska_parse_cluster(matroska) < 0)
1895
                break;
1896
        }
1897
    }
1898

    
1899
    matroska_clear_queue(matroska);
1900
    if (index < 0)
1901
        return 0;
1902

    
1903
    index_min = index;
1904
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1905
        tracks[i].end_timecode = 0;
1906
        if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1907
            && !tracks[i].stream->discard != AVDISCARD_ALL) {
1908
            index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1909
            if (index_sub >= 0
1910
                && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1911
                && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1912
                index_min = index_sub;
1913
        }
1914
    }
1915

    
1916
    url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
1917
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1918
    matroska->skip_to_timecode = st->index_entries[index].timestamp;
1919
    matroska->done = 0;
1920
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1921
    return 0;
1922
}
1923

    
1924
static int matroska_read_close(AVFormatContext *s)
1925
{
1926
    MatroskaDemuxContext *matroska = s->priv_data;
1927
    MatroskaTrack *tracks = matroska->tracks.elem;
1928
    int n;
1929

    
1930
    matroska_clear_queue(matroska);
1931

    
1932
    for (n=0; n < matroska->tracks.nb_elem; n++)
1933
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1934
            av_free(tracks[n].audio.buf);
1935
    ebml_free(matroska_segment, matroska);
1936

    
1937
    return 0;
1938
}
1939

    
1940
AVInputFormat ff_matroska_demuxer = {
1941
    "matroska,webm",
1942
    NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
1943
    sizeof(MatroskaDemuxContext),
1944
    matroska_probe,
1945
    matroska_read_header,
1946
    matroska_read_packet,
1947
    matroska_read_close,
1948
    matroska_read_seek,
1949
};