Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 6b10228a

History | View | Annotate | Download (66.9 KB)

1
/*
2
 * Matroska file demuxer
3
 * Copyright (c) 2003-2008 The FFmpeg Project
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
/**
23
 * @file libavformat/matroskadec.c
24
 * Matroska file demuxer
25
 * by Ronald Bultje <rbultje@ronald.bitfreak.net>
26
 * with a little help from Moritz Bunkus <moritz@bunkus.org>
27
 * totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28
 * Specs available on the Matroska project page: http://www.matroska.org/.
29
 */
30

    
31
#include <stdio.h>
32
#include "avformat.h"
33
/* For ff_codec_get_id(). */
34
#include "riff.h"
35
#include "isom.h"
36
#include "rm.h"
37
#include "matroska.h"
38
#include "libavcodec/mpeg4audio.h"
39
#include "libavutil/intfloat_readwrite.h"
40
#include "libavutil/intreadwrite.h"
41
#include "libavutil/avstring.h"
42
#include "libavutil/lzo.h"
43
#if CONFIG_ZLIB
44
#include <zlib.h>
45
#endif
46
#if CONFIG_BZLIB
47
#include <bzlib.h>
48
#endif
49

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

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

    
75
typedef struct {
76
    int nb_elem;
77
    void *elem;
78
} EbmlList;
79

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

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

    
94
typedef struct {
95
    uint64_t algo;
96
    EbmlBin  settings;
97
} MatroskaTrackCompression;
98

    
99
typedef struct {
100
    uint64_t scope;
101
    uint64_t type;
102
    MatroskaTrackCompression compression;
103
} MatroskaTrackEncoding;
104

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

    
114
typedef struct {
115
    double   samplerate;
116
    double   out_samplerate;
117
    uint64_t bitdepth;
118
    uint64_t channels;
119

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

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

    
145
    AVStream *stream;
146
    int64_t end_timecode;
147
    int ms_compat;
148
} MatroskaTrack;
149

    
150
typedef struct {
151
    uint64_t uid;
152
    char *filename;
153
    char *mime;
154
    EbmlBin bin;
155

    
156
    AVStream *stream;
157
} MatroskaAttachement;
158

    
159
typedef struct {
160
    uint64_t start;
161
    uint64_t end;
162
    uint64_t uid;
163
    char    *title;
164

    
165
    AVChapter *chapter;
166
} MatroskaChapter;
167

    
168
typedef struct {
169
    uint64_t track;
170
    uint64_t pos;
171
} MatroskaIndexPos;
172

    
173
typedef struct {
174
    uint64_t time;
175
    EbmlList pos;
176
} MatroskaIndex;
177

    
178
typedef struct {
179
    char *name;
180
    char *string;
181
    char *lang;
182
    uint64_t def;
183
    EbmlList sub;
184
} MatroskaTag;
185

    
186
typedef struct {
187
    char    *type;
188
    uint64_t typevalue;
189
    uint64_t trackuid;
190
    uint64_t chapteruid;
191
    uint64_t attachuid;
192
} MatroskaTagTarget;
193

    
194
typedef struct {
195
    MatroskaTagTarget target;
196
    EbmlList tag;
197
} MatroskaTags;
198

    
199
typedef struct {
200
    uint64_t id;
201
    uint64_t pos;
202
} MatroskaSeekhead;
203

    
204
typedef struct {
205
    uint64_t start;
206
    uint64_t length;
207
} MatroskaLevel;
208

    
209
typedef struct {
210
    AVFormatContext *ctx;
211

    
212
    /* EBML stuff */
213
    int num_levels;
214
    MatroskaLevel levels[EBML_MAX_DEPTH];
215
    int level_up;
216

    
217
    uint64_t time_scale;
218
    double   duration;
219
    char    *title;
220
    EbmlList tracks;
221
    EbmlList attachments;
222
    EbmlList chapters;
223
    EbmlList index;
224
    EbmlList tags;
225
    EbmlList seekhead;
226

    
227
    /* byte position of the segment inside the stream */
228
    int64_t segment_start;
229

    
230
    /* the packet queue */
231
    AVPacket **packets;
232
    int num_packets;
233
    AVPacket *prev_pkt;
234

    
235
    int done;
236
    int has_cluster_id;
237

    
238
    /* What to skip before effectively reading a packet. */
239
    int skip_to_keyframe;
240
    uint64_t skip_to_timecode;
241
} MatroskaDemuxContext;
242

    
243
typedef struct {
244
    uint64_t duration;
245
    int64_t  reference;
246
    uint64_t non_simple;
247
    EbmlBin  bin;
248
} MatroskaBlock;
249

    
250
typedef struct {
251
    uint64_t timecode;
252
    EbmlList blocks;
253
} MatroskaCluster;
254

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

    
266
static EbmlSyntax ebml_syntax[] = {
267
    { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
268
    { 0 }
269
};
270

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

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

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

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

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

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

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

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

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

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

    
373
static EbmlSyntax matroska_chapter_display[] = {
374
    { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
375
    { MATROSKA_ID_CHAPLANG,           EBML_NONE },
376
    { 0 }
377
};
378

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

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

    
400
static EbmlSyntax matroska_chapters[] = {
401
    { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
402
    { 0 }
403
};
404

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

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

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

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

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

    
441
static EbmlSyntax matroska_tag[] = {
442
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
443
    { MATROSKA_ID_TAGTARGETS,         EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
444
    { 0 }
445
};
446

    
447
static EbmlSyntax matroska_tags[] = {
448
    { MATROSKA_ID_TAG,                EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
449
    { 0 }
450
};
451

    
452
static EbmlSyntax matroska_seekhead_entry[] = {
453
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
454
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
455
    { 0 }
456
};
457

    
458
static EbmlSyntax matroska_seekhead[] = {
459
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
460
    { 0 }
461
};
462

    
463
static EbmlSyntax matroska_segment[] = {
464
    { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
465
    { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
466
    { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
467
    { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
468
    { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
469
    { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
470
    { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
471
    { MATROSKA_ID_CLUSTER,        EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
472
    { 0 }
473
};
474

    
475
static EbmlSyntax matroska_segments[] = {
476
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
477
    { 0 }
478
};
479

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

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

    
498
static EbmlSyntax matroska_clusters[] = {
499
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
500
    { MATROSKA_ID_INFO,           EBML_NONE },
501
    { MATROSKA_ID_CUES,           EBML_NONE },
502
    { MATROSKA_ID_TAGS,           EBML_NONE },
503
    { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
504
    { 0 }
505
};
506

    
507
/*
508
 * Return: Whether we reached the end of a level in the hierarchy or not.
509
 */
510
static int ebml_level_end(MatroskaDemuxContext *matroska)
511
{
512
    ByteIOContext *pb = matroska->ctx->pb;
513
    int64_t pos = url_ftell(pb);
514

    
515
    if (matroska->num_levels > 0) {
516
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
517
        if (pos - level->start >= level->length) {
518
            matroska->num_levels--;
519
            return 1;
520
        }
521
    }
522
    return 0;
523
}
524

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

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

    
553
    /* get the length of the EBML number */
554
    while (read <= max_size && !(total & len_mask)) {
555
        read++;
556
        len_mask >>= 1;
557
    }
558
    if (read > max_size) {
559
        int64_t pos = url_ftell(pb) - 1;
560
        av_log(matroska->ctx, AV_LOG_ERROR,
561
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
562
               (uint8_t) total, pos, pos);
563
        return AVERROR_INVALIDDATA;
564
    }
565

    
566
    /* read out length */
567
    total &= ~len_mask;
568
    while (n++ < read)
569
        total = (total << 8) | get_byte(pb);
570

    
571
    *number = total;
572

    
573
    return read;
574
}
575

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

    
584
    if (size < 1 || size > 8)
585
        return AVERROR_INVALIDDATA;
586

    
587
    /* big-endian ordering; build up number */
588
    *num = 0;
589
    while (n++ < size)
590
        *num = (*num << 8) | get_byte(pb);
591

    
592
    return 0;
593
}
594

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

    
608
    return 0;
609
}
610

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

    
628
    return 0;
629
}
630

    
631
/*
632
 * Read the next element as binary data.
633
 * 0 is success, < 0 is failure.
634
 */
635
static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
636
{
637
    av_free(bin->data);
638
    if (!(bin->data = av_malloc(length)))
639
        return AVERROR(ENOMEM);
640

    
641
    bin->size = length;
642
    bin->pos  = url_ftell(pb);
643
    if (get_buffer(pb, bin->data, length) != length)
644
        return AVERROR(EIO);
645

    
646
    return 0;
647
}
648

    
649
/*
650
 * Read the next element, but only the header. The contents
651
 * are supposed to be sub-elements which can be read separately.
652
 * 0 is success, < 0 is failure.
653
 */
654
static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
655
{
656
    ByteIOContext *pb = matroska->ctx->pb;
657
    MatroskaLevel *level;
658

    
659
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
660
        av_log(matroska->ctx, AV_LOG_ERROR,
661
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
662
        return AVERROR(ENOSYS);
663
    }
664

    
665
    level = &matroska->levels[matroska->num_levels++];
666
    level->start = url_ftell(pb);
667
    level->length = length;
668

    
669
    return 0;
670
}
671

    
672
/*
673
 * Read signed/unsigned "EBML" numbers.
674
 * Return: number of bytes processed, < 0 on error
675
 */
676
static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
677
                                 uint8_t *data, uint32_t size, uint64_t *num)
678
{
679
    ByteIOContext pb;
680
    init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
681
    return ebml_read_num(matroska, &pb, 8, num);
682
}
683

    
684
/*
685
 * Same as above, but signed.
686
 */
687
static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
688
                                 uint8_t *data, uint32_t size, int64_t *num)
689
{
690
    uint64_t unum;
691
    int res;
692

    
693
    /* read as unsigned number first */
694
    if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
695
        return res;
696

    
697
    /* make signed (weird way) */
698
    *num = unum - ((1LL << (7*res - 1)) - 1);
699

    
700
    return res;
701
}
702

    
703
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
704
                           EbmlSyntax *syntax, void *data);
705

    
706
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
707
                         uint32_t id, void *data)
708
{
709
    int i;
710
    for (i=0; syntax[i].id; i++)
711
        if (id == syntax[i].id)
712
            break;
713
    if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
714
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
715
    return ebml_parse_elem(matroska, &syntax[i], data);
716
}
717

    
718
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
719
                      void *data)
720
{
721
    uint64_t id;
722
    int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
723
    id |= 1 << 7*res;
724
    return res < 0 ? res : ebml_parse_id(matroska, syntax, id, data);
725
}
726

    
727
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
728
                           void *data)
729
{
730
    int i, res = 0;
731

    
732
    for (i=0; syntax[i].id; i++)
733
        switch (syntax[i].type) {
734
        case EBML_UINT:
735
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
736
            break;
737
        case EBML_FLOAT:
738
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
739
            break;
740
        case EBML_STR:
741
        case EBML_UTF8:
742
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
743
            break;
744
        }
745

    
746
    while (!res && !ebml_level_end(matroska))
747
        res = ebml_parse(matroska, syntax, data);
748

    
749
    return res;
750
}
751

    
752
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
753
                           EbmlSyntax *syntax, void *data)
754
{
755
    ByteIOContext *pb = matroska->ctx->pb;
756
    uint32_t id = syntax->id;
757
    uint64_t length;
758
    int res;
759

    
760
    data = (char *)data + syntax->data_offset;
761
    if (syntax->list_elem_size) {
762
        EbmlList *list = data;
763
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
764
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
765
        memset(data, 0, syntax->list_elem_size);
766
        list->nb_elem++;
767
    }
768

    
769
    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
770
        if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
771
            return res;
772

    
773
    switch (syntax->type) {
774
    case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
775
    case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
776
    case EBML_STR:
777
    case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
778
    case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
779
    case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
780
                         return res;
781
                     if (id == MATROSKA_ID_SEGMENT)
782
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
783
                     return ebml_parse_nest(matroska, syntax->def.n, data);
784
    case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
785
    case EBML_STOP:  *(int *)data = 1;      return 1;
786
    default:         return url_fseek(pb,length,SEEK_CUR)<0 ? AVERROR(EIO) : 0;
787
    }
788
    if (res == AVERROR_INVALIDDATA)
789
        av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
790
    else if (res == AVERROR(EIO))
791
        av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
792
    return res;
793
}
794

    
795
static void ebml_free(EbmlSyntax *syntax, void *data)
796
{
797
    int i, j;
798
    for (i=0; syntax[i].id; i++) {
799
        void *data_off = (char *)data + syntax[i].data_offset;
800
        switch (syntax[i].type) {
801
        case EBML_STR:
802
        case EBML_UTF8:  av_freep(data_off);                      break;
803
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
804
        case EBML_NEST:
805
            if (syntax[i].list_elem_size) {
806
                EbmlList *list = data_off;
807
                char *ptr = list->elem;
808
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
809
                    ebml_free(syntax[i].def.n, ptr);
810
                av_free(list->elem);
811
            } else
812
                ebml_free(syntax[i].def.n, data_off);
813
        default:  break;
814
        }
815
    }
816
}
817

    
818

    
819
/*
820
 * Autodetecting...
821
 */
822
static int matroska_probe(AVProbeData *p)
823
{
824
    uint64_t total = 0;
825
    int len_mask = 0x80, size = 1, n = 1;
826
    static const char probe_data[] = "matroska";
827

    
828
    /* EBML header? */
829
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
830
        return 0;
831

    
832
    /* length of header */
833
    total = p->buf[4];
834
    while (size <= 8 && !(total & len_mask)) {
835
        size++;
836
        len_mask >>= 1;
837
    }
838
    if (size > 8)
839
      return 0;
840
    total &= (len_mask - 1);
841
    while (n < size)
842
        total = (total << 8) | p->buf[4 + n++];
843

    
844
    /* Does the probe data contain the whole header? */
845
    if (p->buf_size < 4 + size + total)
846
      return 0;
847

    
848
    /* The header must contain the document type 'matroska'. For now,
849
     * we don't parse the whole header but simply check for the
850
     * availability of that array of characters inside the header.
851
     * Not fully fool-proof, but good enough. */
852
    for (n = 4+size; n <= 4+size+total-(sizeof(probe_data)-1); n++)
853
        if (!memcmp(p->buf+n, probe_data, sizeof(probe_data)-1))
854
            return AVPROBE_SCORE_MAX;
855

    
856
    return 0;
857
}
858

    
859
static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
860
                                                 int num)
861
{
862
    MatroskaTrack *tracks = matroska->tracks.elem;
863
    int i;
864

    
865
    for (i=0; i < matroska->tracks.nb_elem; i++)
866
        if (tracks[i].num == num)
867
            return &tracks[i];
868

    
869
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
870
    return NULL;
871
}
872

    
873
static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
874
                                  MatroskaTrack *track)
875
{
876
    MatroskaTrackEncoding *encodings = track->encodings.elem;
877
    uint8_t* data = *buf;
878
    int isize = *buf_size;
879
    uint8_t* pkt_data = NULL;
880
    int pkt_size = isize;
881
    int result = 0;
882
    int olen;
883

    
884
    switch (encodings[0].compression.algo) {
885
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
886
        return encodings[0].compression.settings.size;
887
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
888
        do {
889
            olen = pkt_size *= 3;
890
            pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
891
            result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
892
        } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
893
        if (result)
894
            goto failed;
895
        pkt_size -= olen;
896
        break;
897
#if CONFIG_ZLIB
898
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
899
        z_stream zstream = {0};
900
        if (inflateInit(&zstream) != Z_OK)
901
            return -1;
902
        zstream.next_in = data;
903
        zstream.avail_in = isize;
904
        do {
905
            pkt_size *= 3;
906
            pkt_data = av_realloc(pkt_data, pkt_size);
907
            zstream.avail_out = pkt_size - zstream.total_out;
908
            zstream.next_out = pkt_data + zstream.total_out;
909
            result = inflate(&zstream, Z_NO_FLUSH);
910
        } while (result==Z_OK && pkt_size<10000000);
911
        pkt_size = zstream.total_out;
912
        inflateEnd(&zstream);
913
        if (result != Z_STREAM_END)
914
            goto failed;
915
        break;
916
    }
917
#endif
918
#if CONFIG_BZLIB
919
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
920
        bz_stream bzstream = {0};
921
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
922
            return -1;
923
        bzstream.next_in = data;
924
        bzstream.avail_in = isize;
925
        do {
926
            pkt_size *= 3;
927
            pkt_data = av_realloc(pkt_data, pkt_size);
928
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
929
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
930
            result = BZ2_bzDecompress(&bzstream);
931
        } while (result==BZ_OK && pkt_size<10000000);
932
        pkt_size = bzstream.total_out_lo32;
933
        BZ2_bzDecompressEnd(&bzstream);
934
        if (result != BZ_STREAM_END)
935
            goto failed;
936
        break;
937
    }
938
#endif
939
    default:
940
        return -1;
941
    }
942

    
943
    *buf = pkt_data;
944
    *buf_size = pkt_size;
945
    return 0;
946
 failed:
947
    av_free(pkt_data);
948
    return -1;
949
}
950

    
951
static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
952
                                    AVPacket *pkt, uint64_t display_duration)
953
{
954
    char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
955
    for (; *ptr!=',' && ptr<end-1; ptr++);
956
    if (*ptr == ',')
957
        layer = ++ptr;
958
    for (; *ptr!=',' && ptr<end-1; ptr++);
959
    if (*ptr == ',') {
960
        int64_t end_pts = pkt->pts + display_duration;
961
        int sc = matroska->time_scale * pkt->pts / 10000000;
962
        int ec = matroska->time_scale * end_pts  / 10000000;
963
        int sh, sm, ss, eh, em, es, len;
964
        sh = sc/360000;  sc -= 360000*sh;
965
        sm = sc/  6000;  sc -=   6000*sm;
966
        ss = sc/   100;  sc -=    100*ss;
967
        eh = ec/360000;  ec -= 360000*eh;
968
        em = ec/  6000;  ec -=   6000*em;
969
        es = ec/   100;  ec -=    100*es;
970
        *ptr++ = '\0';
971
        len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
972
        if (!(line = av_malloc(len)))
973
            return;
974
        snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
975
                 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
976
        av_free(pkt->data);
977
        pkt->data = line;
978
        pkt->size = strlen(line);
979
    }
980
}
981

    
982
static void matroska_merge_packets(AVPacket *out, AVPacket *in)
983
{
984
    out->data = av_realloc(out->data, out->size+in->size);
985
    memcpy(out->data+out->size, in->data, in->size);
986
    out->size += in->size;
987
    av_destruct_packet(in);
988
    av_free(in);
989
}
990

    
991
static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
992
                                 AVMetadata **metadata, char *prefix)
993
{
994
    MatroskaTag *tags = list->elem;
995
    char key[1024];
996
    int i;
997

    
998
    for (i=0; i < list->nb_elem; i++) {
999
        const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1000
        if (prefix)  snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1001
        else         av_strlcpy(key, tags[i].name, sizeof(key));
1002
        if (tags[i].def || !lang) {
1003
        av_metadata_set(metadata, key, tags[i].string);
1004
        if (tags[i].sub.nb_elem)
1005
            matroska_convert_tag(s, &tags[i].sub, metadata, key);
1006
        }
1007
        if (lang) {
1008
            av_strlcat(key, "-", sizeof(key));
1009
            av_strlcat(key, lang, sizeof(key));
1010
            av_metadata_set(metadata, key, tags[i].string);
1011
            if (tags[i].sub.nb_elem)
1012
                matroska_convert_tag(s, &tags[i].sub, metadata, key);
1013
        }
1014
    }
1015
}
1016

    
1017
static void matroska_convert_tags(AVFormatContext *s)
1018
{
1019
    MatroskaDemuxContext *matroska = s->priv_data;
1020
    MatroskaTags *tags = matroska->tags.elem;
1021
    int i, j;
1022

    
1023
    for (i=0; i < matroska->tags.nb_elem; i++) {
1024
        if (tags[i].target.attachuid) {
1025
            MatroskaAttachement *attachment = matroska->attachments.elem;
1026
            for (j=0; j<matroska->attachments.nb_elem; j++)
1027
                if (attachment[j].uid == tags[i].target.attachuid)
1028
                    matroska_convert_tag(s, &tags[i].tag,
1029
                                         &attachment[j].stream->metadata, NULL);
1030
        } else if (tags[i].target.chapteruid) {
1031
            MatroskaChapter *chapter = matroska->chapters.elem;
1032
            for (j=0; j<matroska->chapters.nb_elem; j++)
1033
                if (chapter[j].uid == tags[i].target.chapteruid)
1034
                    matroska_convert_tag(s, &tags[i].tag,
1035
                                         &chapter[j].chapter->metadata, NULL);
1036
        } else if (tags[i].target.trackuid) {
1037
            MatroskaTrack *track = matroska->tracks.elem;
1038
            for (j=0; j<matroska->tracks.nb_elem; j++)
1039
                if (track[j].uid == tags[i].target.trackuid)
1040
                    matroska_convert_tag(s, &tags[i].tag,
1041
                                         &track[j].stream->metadata, NULL);
1042
        } else {
1043
            matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1044
                                 tags[i].target.type);
1045
        }
1046
    }
1047
}
1048

    
1049
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1050
{
1051
    EbmlList *seekhead_list = &matroska->seekhead;
1052
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1053
    uint32_t level_up = matroska->level_up;
1054
    int64_t before_pos = url_ftell(matroska->ctx->pb);
1055
    MatroskaLevel level;
1056
    int i;
1057

    
1058
    for (i=0; i<seekhead_list->nb_elem; i++) {
1059
        int64_t offset = seekhead[i].pos + matroska->segment_start;
1060

    
1061
        if (seekhead[i].pos <= before_pos
1062
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1063
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1064
            continue;
1065

    
1066
        /* seek */
1067
        if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
1068
            continue;
1069

    
1070
        /* We don't want to lose our seekhead level, so we add
1071
         * a dummy. This is a crude hack. */
1072
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1073
            av_log(matroska->ctx, AV_LOG_INFO,
1074
                   "Max EBML element depth (%d) reached, "
1075
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1076
            break;
1077
        }
1078

    
1079
        level.start = 0;
1080
        level.length = (uint64_t)-1;
1081
        matroska->levels[matroska->num_levels] = level;
1082
        matroska->num_levels++;
1083

    
1084
        ebml_parse(matroska, matroska_segment, matroska);
1085

    
1086
        /* remove dummy level */
1087
        while (matroska->num_levels) {
1088
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1089
            if (length == (uint64_t)-1)
1090
                break;
1091
        }
1092
    }
1093

    
1094
    /* seek back */
1095
    url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
1096
    matroska->level_up = level_up;
1097
}
1098

    
1099
static int matroska_aac_profile(char *codec_id)
1100
{
1101
    static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1102
    int profile;
1103

    
1104
    for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1105
        if (strstr(codec_id, aac_profiles[profile]))
1106
            break;
1107
    return profile + 1;
1108
}
1109

    
1110
static int matroska_aac_sri(int samplerate)
1111
{
1112
    int sri;
1113

    
1114
    for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
1115
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1116
            break;
1117
    return sri;
1118
}
1119

    
1120
static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1121
{
1122
    MatroskaDemuxContext *matroska = s->priv_data;
1123
    EbmlList *attachements_list = &matroska->attachments;
1124
    MatroskaAttachement *attachements;
1125
    EbmlList *chapters_list = &matroska->chapters;
1126
    MatroskaChapter *chapters;
1127
    MatroskaTrack *tracks;
1128
    EbmlList *index_list;
1129
    MatroskaIndex *index;
1130
    int index_scale = 1;
1131
    uint64_t max_start = 0;
1132
    Ebml ebml = { 0 };
1133
    AVStream *st;
1134
    int i, j;
1135

    
1136
    matroska->ctx = s;
1137

    
1138
    /* First read the EBML header. */
1139
    if (ebml_parse(matroska, ebml_syntax, &ebml)
1140
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1141
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1142
        || ebml.doctype_version > 2) {
1143
        av_log(matroska->ctx, AV_LOG_ERROR,
1144
               "EBML header using unsupported features\n"
1145
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1146
               ebml.version, ebml.doctype, ebml.doctype_version);
1147
        return AVERROR_NOFMT;
1148
    }
1149
    ebml_free(ebml_syntax, &ebml);
1150

    
1151
    /* The next thing is a segment. */
1152
    if (ebml_parse(matroska, matroska_segments, matroska) < 0)
1153
        return -1;
1154
    matroska_execute_seekhead(matroska);
1155

    
1156
    if (matroska->duration)
1157
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1158
                                  * 1000 / AV_TIME_BASE;
1159
    av_metadata_set(&s->metadata, "title", matroska->title);
1160

    
1161
    tracks = matroska->tracks.elem;
1162
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1163
        MatroskaTrack *track = &tracks[i];
1164
        enum CodecID codec_id = CODEC_ID_NONE;
1165
        EbmlList *encodings_list = &tracks->encodings;
1166
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1167
        uint8_t *extradata = NULL;
1168
        int extradata_size = 0;
1169
        int extradata_offset = 0;
1170
        ByteIOContext b;
1171

    
1172
        /* Apply some sanity checks. */
1173
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1174
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1175
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1176
            av_log(matroska->ctx, AV_LOG_INFO,
1177
                   "Unknown or unsupported track type %"PRIu64"\n",
1178
                   track->type);
1179
            continue;
1180
        }
1181
        if (track->codec_id == NULL)
1182
            continue;
1183

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

    
1234
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1235
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1236
                        strlen(ff_mkv_codec_tags[j].str))){
1237
                codec_id= ff_mkv_codec_tags[j].id;
1238
                break;
1239
            }
1240
        }
1241

    
1242
        st = track->stream = av_new_stream(s, 0);
1243
        if (st == NULL)
1244
            return AVERROR(ENOMEM);
1245

    
1246
        if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1247
            && track->codec_priv.size >= 40
1248
            && track->codec_priv.data != NULL) {
1249
            track->ms_compat = 1;
1250
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1251
            codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1252
            extradata_offset = 40;
1253
        } else if (!strcmp(track->codec_id, "A_MS/ACM")
1254
                   && track->codec_priv.size >= 14
1255
                   && track->codec_priv.data != NULL) {
1256
            init_put_byte(&b, track->codec_priv.data, track->codec_priv.size,
1257
                          URL_RDONLY, NULL, NULL, NULL, NULL);
1258
            ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1259
            codec_id = st->codec->codec_id;
1260
            extradata_offset = FFMIN(track->codec_priv.size, 18);
1261
        } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1262
                   && (track->codec_priv.size >= 86)
1263
                   && (track->codec_priv.data != NULL)) {
1264
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1265
            codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
1266
        } else if (codec_id == CODEC_ID_PCM_S16BE) {
1267
            switch (track->audio.bitdepth) {
1268
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1269
            case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
1270
            case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
1271
            }
1272
        } else if (codec_id == CODEC_ID_PCM_S16LE) {
1273
            switch (track->audio.bitdepth) {
1274
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1275
            case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
1276
            case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
1277
            }
1278
        } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1279
            codec_id = CODEC_ID_PCM_F64LE;
1280
        } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1281
            int profile = matroska_aac_profile(track->codec_id);
1282
            int sri = matroska_aac_sri(track->audio.samplerate);
1283
            extradata = av_malloc(5);
1284
            if (extradata == NULL)
1285
                return AVERROR(ENOMEM);
1286
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1287
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1288
            if (strstr(track->codec_id, "SBR")) {
1289
                sri = matroska_aac_sri(track->audio.out_samplerate);
1290
                extradata[2] = 0x56;
1291
                extradata[3] = 0xE5;
1292
                extradata[4] = 0x80 | (sri<<3);
1293
                extradata_size = 5;
1294
            } else
1295
                extradata_size = 2;
1296
        } else if (codec_id == CODEC_ID_TTA) {
1297
            extradata_size = 30;
1298
            extradata = av_mallocz(extradata_size);
1299
            if (extradata == NULL)
1300
                return AVERROR(ENOMEM);
1301
            init_put_byte(&b, extradata, extradata_size, 1,
1302
                          NULL, NULL, NULL, NULL);
1303
            put_buffer(&b, "TTA1", 4);
1304
            put_le16(&b, 1);
1305
            put_le16(&b, track->audio.channels);
1306
            put_le16(&b, track->audio.bitdepth);
1307
            put_le32(&b, track->audio.out_samplerate);
1308
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1309
        } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1310
                   codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1311
            extradata_offset = 26;
1312
        } else if (codec_id == CODEC_ID_RA_144) {
1313
            track->audio.out_samplerate = 8000;
1314
            track->audio.channels = 1;
1315
        } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1316
                   codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1317
            int flavor;
1318
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1319
                          0, NULL, NULL, NULL, NULL);
1320
            url_fskip(&b, 22);
1321
            flavor                       = get_be16(&b);
1322
            track->audio.coded_framesize = get_be32(&b);
1323
            url_fskip(&b, 12);
1324
            track->audio.sub_packet_h    = get_be16(&b);
1325
            track->audio.frame_size      = get_be16(&b);
1326
            track->audio.sub_packet_size = get_be16(&b);
1327
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1328
            if (codec_id == CODEC_ID_RA_288) {
1329
                st->codec->block_align = track->audio.coded_framesize;
1330
                track->codec_priv.size = 0;
1331
            } else {
1332
                if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1333
                    const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1334
                    track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1335
                    st->codec->bit_rate = sipr_bit_rate[flavor];
1336
                }
1337
                st->codec->block_align = track->audio.sub_packet_size;
1338
                extradata_offset = 78;
1339
            }
1340
        }
1341
        track->codec_priv.size -= extradata_offset;
1342

    
1343
        if (codec_id == CODEC_ID_NONE)
1344
            av_log(matroska->ctx, AV_LOG_INFO,
1345
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1346

    
1347
        if (track->time_scale < 0.01)
1348
            track->time_scale = 1.0;
1349
        av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1350

    
1351
        st->codec->codec_id = codec_id;
1352
        st->start_time = 0;
1353
        if (strcmp(track->language, "und"))
1354
            av_metadata_set(&st->metadata, "language", track->language);
1355
        av_metadata_set(&st->metadata, "title", track->name);
1356

    
1357
        if (track->flag_default)
1358
            st->disposition |= AV_DISPOSITION_DEFAULT;
1359

    
1360
        if (track->default_duration)
1361
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1362
                      track->default_duration, 1000000000, 30000);
1363

    
1364
        if (!st->codec->extradata) {
1365
            if(extradata){
1366
                st->codec->extradata = extradata;
1367
                st->codec->extradata_size = extradata_size;
1368
            } else if(track->codec_priv.data && track->codec_priv.size > 0){
1369
                st->codec->extradata = av_mallocz(track->codec_priv.size +
1370
                                                  FF_INPUT_BUFFER_PADDING_SIZE);
1371
                if(st->codec->extradata == NULL)
1372
                    return AVERROR(ENOMEM);
1373
                st->codec->extradata_size = track->codec_priv.size;
1374
                memcpy(st->codec->extradata,
1375
                       track->codec_priv.data + extradata_offset,
1376
                       track->codec_priv.size);
1377
            }
1378
        }
1379

    
1380
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1381
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1382
            st->codec->codec_tag  = track->video.fourcc;
1383
            st->codec->width  = track->video.pixel_width;
1384
            st->codec->height = track->video.pixel_height;
1385
            av_reduce(&st->sample_aspect_ratio.num,
1386
                      &st->sample_aspect_ratio.den,
1387
                      st->codec->height * track->video.display_width,
1388
                      st->codec-> width * track->video.display_height,
1389
                      255);
1390
            if (st->codec->codec_id != CODEC_ID_H264)
1391
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1392
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1393
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1394
            st->codec->sample_rate = track->audio.out_samplerate;
1395
            st->codec->channels = track->audio.channels;
1396
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1397
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1398
        }
1399
    }
1400

    
1401
    attachements = attachements_list->elem;
1402
    for (j=0; j<attachements_list->nb_elem; j++) {
1403
        if (!(attachements[j].filename && attachements[j].mime &&
1404
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1405
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1406
        } else {
1407
            AVStream *st = av_new_stream(s, 0);
1408
            if (st == NULL)
1409
                break;
1410
            av_metadata_set(&st->metadata, "filename",attachements[j].filename);
1411
            st->codec->codec_id = CODEC_ID_NONE;
1412
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1413
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1414
            if(st->codec->extradata == NULL)
1415
                break;
1416
            st->codec->extradata_size = attachements[j].bin.size;
1417
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1418

    
1419
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1420
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1421
                             strlen(ff_mkv_mime_tags[i].str))) {
1422
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1423
                    break;
1424
                }
1425
            }
1426
            attachements[j].stream = st;
1427
        }
1428
    }
1429

    
1430
    chapters = chapters_list->elem;
1431
    for (i=0; i<chapters_list->nb_elem; i++)
1432
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1433
            && (max_start==0 || chapters[i].start > max_start)) {
1434
            chapters[i].chapter =
1435
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1436
                           chapters[i].start, chapters[i].end,
1437
                           chapters[i].title);
1438
            av_metadata_set(&chapters[i].chapter->metadata,
1439
                            "title", chapters[i].title);
1440
            max_start = chapters[i].start;
1441
        }
1442

    
1443
    index_list = &matroska->index;
1444
    index = index_list->elem;
1445
    if (index_list->nb_elem
1446
        && index[0].time > 100000000000000/matroska->time_scale) {
1447
        av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1448
        index_scale = matroska->time_scale;
1449
    }
1450
    for (i=0; i<index_list->nb_elem; i++) {
1451
        EbmlList *pos_list = &index[i].pos;
1452
        MatroskaIndexPos *pos = pos_list->elem;
1453
        for (j=0; j<pos_list->nb_elem; j++) {
1454
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1455
                                                              pos[j].track);
1456
            if (track && track->stream)
1457
                av_add_index_entry(track->stream,
1458
                                   pos[j].pos + matroska->segment_start,
1459
                                   index[i].time/index_scale, 0, 0,
1460
                                   AVINDEX_KEYFRAME);
1461
        }
1462
    }
1463

    
1464
    matroska_convert_tags(s);
1465

    
1466
    return 0;
1467
}
1468

    
1469
/*
1470
 * Put one packet in an application-supplied AVPacket struct.
1471
 * Returns 0 on success or -1 on failure.
1472
 */
1473
static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1474
                                   AVPacket *pkt)
1475
{
1476
    if (matroska->num_packets > 0) {
1477
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1478
        av_free(matroska->packets[0]);
1479
        if (matroska->num_packets > 1) {
1480
            memmove(&matroska->packets[0], &matroska->packets[1],
1481
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
1482
            matroska->packets =
1483
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
1484
                           sizeof(AVPacket *));
1485
        } else {
1486
            av_freep(&matroska->packets);
1487
        }
1488
        matroska->num_packets--;
1489
        return 0;
1490
    }
1491

    
1492
    return -1;
1493
}
1494

    
1495
/*
1496
 * Free all packets in our internal queue.
1497
 */
1498
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1499
{
1500
    if (matroska->packets) {
1501
        int n;
1502
        for (n = 0; n < matroska->num_packets; n++) {
1503
            av_free_packet(matroska->packets[n]);
1504
            av_free(matroska->packets[n]);
1505
        }
1506
        av_freep(&matroska->packets);
1507
        matroska->num_packets = 0;
1508
    }
1509
}
1510

    
1511
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1512
                                int size, int64_t pos, uint64_t cluster_time,
1513
                                uint64_t duration, int is_keyframe,
1514
                                int64_t cluster_pos)
1515
{
1516
    uint64_t timecode = AV_NOPTS_VALUE;
1517
    MatroskaTrack *track;
1518
    int res = 0;
1519
    AVStream *st;
1520
    AVPacket *pkt;
1521
    int16_t block_time;
1522
    uint32_t *lace_size = NULL;
1523
    int n, flags, laces = 0;
1524
    uint64_t num;
1525

    
1526
    if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1527
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1528
        return res;
1529
    }
1530
    data += n;
1531
    size -= n;
1532

    
1533
    track = matroska_find_track_by_num(matroska, num);
1534
    if (size <= 3 || !track || !track->stream) {
1535
        av_log(matroska->ctx, AV_LOG_INFO,
1536
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1537
        return res;
1538
    }
1539
    st = track->stream;
1540
    if (st->discard >= AVDISCARD_ALL)
1541
        return res;
1542
    if (duration == AV_NOPTS_VALUE)
1543
        duration = track->default_duration / matroska->time_scale;
1544

    
1545
    block_time = AV_RB16(data);
1546
    data += 2;
1547
    flags = *data++;
1548
    size -= 3;
1549
    if (is_keyframe == -1)
1550
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1551

    
1552
    if (cluster_time != (uint64_t)-1
1553
        && (block_time >= 0 || cluster_time >= -block_time)) {
1554
        timecode = cluster_time + block_time;
1555
        if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1556
            && timecode < track->end_timecode)
1557
            is_keyframe = 0;  /* overlapping subtitles are not key frame */
1558
        if (is_keyframe)
1559
            av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1560
        track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1561
    }
1562

    
1563
    if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1564
        if (!is_keyframe || timecode < matroska->skip_to_timecode)
1565
            return res;
1566
        matroska->skip_to_keyframe = 0;
1567
    }
1568

    
1569
    switch ((flags & 0x06) >> 1) {
1570
        case 0x0: /* no lacing */
1571
            laces = 1;
1572
            lace_size = av_mallocz(sizeof(int));
1573
            lace_size[0] = size;
1574
            break;
1575

    
1576
        case 0x1: /* Xiph lacing */
1577
        case 0x2: /* fixed-size lacing */
1578
        case 0x3: /* EBML lacing */
1579
            assert(size>0); // size <=3 is checked before size-=3 above
1580
            laces = (*data) + 1;
1581
            data += 1;
1582
            size -= 1;
1583
            lace_size = av_mallocz(laces * sizeof(int));
1584

    
1585
            switch ((flags & 0x06) >> 1) {
1586
                case 0x1: /* Xiph lacing */ {
1587
                    uint8_t temp;
1588
                    uint32_t total = 0;
1589
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1590
                        while (1) {
1591
                            if (size == 0) {
1592
                                res = -1;
1593
                                break;
1594
                            }
1595
                            temp = *data;
1596
                            lace_size[n] += temp;
1597
                            data += 1;
1598
                            size -= 1;
1599
                            if (temp != 0xff)
1600
                                break;
1601
                        }
1602
                        total += lace_size[n];
1603
                    }
1604
                    lace_size[n] = size - total;
1605
                    break;
1606
                }
1607

    
1608
                case 0x2: /* fixed-size lacing */
1609
                    for (n = 0; n < laces; n++)
1610
                        lace_size[n] = size / laces;
1611
                    break;
1612

    
1613
                case 0x3: /* EBML lacing */ {
1614
                    uint32_t total;
1615
                    n = matroska_ebmlnum_uint(matroska, data, size, &num);
1616
                    if (n < 0) {
1617
                        av_log(matroska->ctx, AV_LOG_INFO,
1618
                               "EBML block data error\n");
1619
                        break;
1620
                    }
1621
                    data += n;
1622
                    size -= n;
1623
                    total = lace_size[0] = num;
1624
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1625
                        int64_t snum;
1626
                        int r;
1627
                        r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1628
                        if (r < 0) {
1629
                            av_log(matroska->ctx, AV_LOG_INFO,
1630
                                   "EBML block data error\n");
1631
                            break;
1632
                        }
1633
                        data += r;
1634
                        size -= r;
1635
                        lace_size[n] = lace_size[n - 1] + snum;
1636
                        total += lace_size[n];
1637
                    }
1638
                    lace_size[n] = size - total;
1639
                    break;
1640
                }
1641
            }
1642
            break;
1643
    }
1644

    
1645
    if (res == 0) {
1646
        for (n = 0; n < laces; n++) {
1647
            if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1648
                 st->codec->codec_id == CODEC_ID_COOK ||
1649
                 st->codec->codec_id == CODEC_ID_SIPR ||
1650
                 st->codec->codec_id == CODEC_ID_ATRAC3) &&
1651
                 st->codec->block_align && track->audio.sub_packet_size) {
1652
                int a = st->codec->block_align;
1653
                int sps = track->audio.sub_packet_size;
1654
                int cfs = track->audio.coded_framesize;
1655
                int h = track->audio.sub_packet_h;
1656
                int y = track->audio.sub_packet_cnt;
1657
                int w = track->audio.frame_size;
1658
                int x;
1659

    
1660
                if (!track->audio.pkt_cnt) {
1661
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1662
                        for (x=0; x<h/2; x++)
1663
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1664
                                   data+x*cfs, cfs);
1665
                    else if (st->codec->codec_id == CODEC_ID_SIPR)
1666
                        memcpy(track->audio.buf + y*w, data, w);
1667
                    else
1668
                        for (x=0; x<w/sps; x++)
1669
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1670

    
1671
                    if (++track->audio.sub_packet_cnt >= h) {
1672
                        if (st->codec->codec_id == CODEC_ID_SIPR)
1673
                            ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1674
                        track->audio.sub_packet_cnt = 0;
1675
                        track->audio.pkt_cnt = h*w / a;
1676
                    }
1677
                }
1678
                while (track->audio.pkt_cnt) {
1679
                    pkt = av_mallocz(sizeof(AVPacket));
1680
                    av_new_packet(pkt, a);
1681
                    memcpy(pkt->data, track->audio.buf
1682
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1683
                    pkt->pos = pos;
1684
                    pkt->stream_index = st->index;
1685
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1686
                }
1687
            } else {
1688
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1689
                int offset = 0, pkt_size = lace_size[n];
1690
                uint8_t *pkt_data = data;
1691

    
1692
                if (lace_size[n] > size) {
1693
                    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1694
                    break;
1695
                }
1696

    
1697
                if (encodings && encodings->scope & 1) {
1698
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1699
                    if (offset < 0)
1700
                        continue;
1701
                }
1702

    
1703
                pkt = av_mallocz(sizeof(AVPacket));
1704
                /* XXX: prevent data copy... */
1705
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1706
                    av_free(pkt);
1707
                    res = AVERROR(ENOMEM);
1708
                    break;
1709
                }
1710
                if (offset)
1711
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1712
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1713

    
1714
                if (pkt_data != data)
1715
                    av_free(pkt_data);
1716

    
1717
                if (n == 0)
1718
                    pkt->flags = is_keyframe;
1719
                pkt->stream_index = st->index;
1720

    
1721
                if (track->ms_compat)
1722
                    pkt->dts = timecode;
1723
                else
1724
                    pkt->pts = timecode;
1725
                pkt->pos = pos;
1726
                if (st->codec->codec_id == CODEC_ID_TEXT)
1727
                    pkt->convergence_duration = duration;
1728
                else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1729
                    pkt->duration = duration;
1730

    
1731
                if (st->codec->codec_id == CODEC_ID_SSA)
1732
                    matroska_fix_ass_packet(matroska, pkt, duration);
1733

    
1734
                if (matroska->prev_pkt &&
1735
                    timecode != AV_NOPTS_VALUE &&
1736
                    matroska->prev_pkt->pts == timecode &&
1737
                    matroska->prev_pkt->stream_index == st->index)
1738
                    matroska_merge_packets(matroska->prev_pkt, pkt);
1739
                else {
1740
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1741
                    matroska->prev_pkt = pkt;
1742
                }
1743
            }
1744

    
1745
            if (timecode != AV_NOPTS_VALUE)
1746
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1747
            data += lace_size[n];
1748
            size -= lace_size[n];
1749
        }
1750
    }
1751

    
1752
    av_free(lace_size);
1753
    return res;
1754
}
1755

    
1756
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1757
{
1758
    MatroskaCluster cluster = { 0 };
1759
    EbmlList *blocks_list;
1760
    MatroskaBlock *blocks;
1761
    int i, res;
1762
    int64_t pos = url_ftell(matroska->ctx->pb);
1763
    matroska->prev_pkt = NULL;
1764
    if (matroska->has_cluster_id){
1765
        /* For the first cluster we parse, its ID was already read as
1766
           part of matroska_read_header(), so don't read it again */
1767
        res = ebml_parse_id(matroska, matroska_clusters,
1768
                            MATROSKA_ID_CLUSTER, &cluster);
1769
        pos -= 4;  /* sizeof the ID which was already read */
1770
        matroska->has_cluster_id = 0;
1771
    } else
1772
        res = ebml_parse(matroska, matroska_clusters, &cluster);
1773
    blocks_list = &cluster.blocks;
1774
    blocks = blocks_list->elem;
1775
    for (i=0; i<blocks_list->nb_elem; i++)
1776
        if (blocks[i].bin.size > 0) {
1777
            int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
1778
            res=matroska_parse_block(matroska,
1779
                                     blocks[i].bin.data, blocks[i].bin.size,
1780
                                     blocks[i].bin.pos,  cluster.timecode,
1781
                                     blocks[i].duration, is_keyframe,
1782
                                     pos);
1783
        }
1784
    ebml_free(matroska_cluster, &cluster);
1785
    if (res < 0)  matroska->done = 1;
1786
    return res;
1787
}
1788

    
1789
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1790
{
1791
    MatroskaDemuxContext *matroska = s->priv_data;
1792

    
1793
    while (matroska_deliver_packet(matroska, pkt)) {
1794
        if (matroska->done)
1795
            return AVERROR_EOF;
1796
        matroska_parse_cluster(matroska);
1797
    }
1798

    
1799
    return 0;
1800
}
1801

    
1802
static int matroska_read_seek(AVFormatContext *s, int stream_index,
1803
                              int64_t timestamp, int flags)
1804
{
1805
    MatroskaDemuxContext *matroska = s->priv_data;
1806
    MatroskaTrack *tracks = matroska->tracks.elem;
1807
    AVStream *st = s->streams[stream_index];
1808
    int i, index, index_sub, index_min;
1809

    
1810
    if (!st->nb_index_entries)
1811
        return 0;
1812
    timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1813

    
1814
    if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1815
        url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1816
        while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1817
            matroska_clear_queue(matroska);
1818
            if (matroska_parse_cluster(matroska) < 0)
1819
                break;
1820
        }
1821
    }
1822

    
1823
    matroska_clear_queue(matroska);
1824
    if (index < 0)
1825
        return 0;
1826

    
1827
    index_min = index;
1828
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1829
        tracks[i].end_timecode = 0;
1830
        if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1831
            && !tracks[i].stream->discard != AVDISCARD_ALL) {
1832
            index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1833
            if (index_sub >= 0
1834
                && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1835
                && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1836
                index_min = index_sub;
1837
        }
1838
    }
1839

    
1840
    url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
1841
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1842
    matroska->skip_to_timecode = st->index_entries[index].timestamp;
1843
    matroska->done = 0;
1844
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1845
    return 0;
1846
}
1847

    
1848
static int matroska_read_close(AVFormatContext *s)
1849
{
1850
    MatroskaDemuxContext *matroska = s->priv_data;
1851
    MatroskaTrack *tracks = matroska->tracks.elem;
1852
    int n;
1853

    
1854
    matroska_clear_queue(matroska);
1855

    
1856
    for (n=0; n < matroska->tracks.nb_elem; n++)
1857
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1858
            av_free(tracks[n].audio.buf);
1859
    ebml_free(matroska_segment, matroska);
1860

    
1861
    return 0;
1862
}
1863

    
1864
AVInputFormat matroska_demuxer = {
1865
    "matroska",
1866
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1867
    sizeof(MatroskaDemuxContext),
1868
    matroska_probe,
1869
    matroska_read_header,
1870
    matroska_read_packet,
1871
    matroska_read_close,
1872
    matroska_read_seek,
1873
    .metadata_conv = ff_mkv_metadata_conv,
1874
};