Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 33ac07ea

History | View | Annotate | Download (56.5 KB)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
140
    AVStream *stream;
141
} MatroskaTrack;
142

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

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

    
156
typedef struct {
157
    uint64_t track;
158
    uint64_t pos;
159
} MatroskaIndexPos;
160

    
161
typedef struct {
162
    uint64_t time;
163
    EbmlList pos;
164
} MatroskaIndex;
165

    
166
typedef struct {
167
    uint64_t id;
168
    uint64_t pos;
169
} MatroskaSeekhead;
170

    
171
typedef struct {
172
    uint64_t start;
173
    uint64_t length;
174
} MatroskaLevel;
175

    
176
typedef struct {
177
    AVFormatContext *ctx;
178

    
179
    /* ebml stuff */
180
    int num_levels;
181
    MatroskaLevel levels[EBML_MAX_DEPTH];
182
    int level_up;
183

    
184
    uint64_t time_scale;
185
    double   duration;
186
    char    *title;
187
    EbmlList tracks;
188
    EbmlList attachments;
189
    EbmlList chapters;
190
    EbmlList index;
191
    EbmlList seekhead;
192

    
193
    /* num_streams is the number of streams that av_new_stream() was called
194
     * for ( = that are available to the calling program). */
195
    int num_streams;
196

    
197
    /* byte position of the segment inside the stream */
198
    offset_t segment_start;
199

    
200
    /* The packet queue. */
201
    AVPacket **packets;
202
    int num_packets;
203

    
204
    int done;
205
    int has_cluster_id;
206

    
207
    /* What to skip before effectively reading a packet. */
208
    int skip_to_keyframe;
209
    AVStream *skip_to_stream;
210
} MatroskaDemuxContext;
211

    
212
typedef struct {
213
    uint64_t duration;
214
    int64_t  reference;
215
    EbmlBin  bin;
216
} MatroskaBlock;
217

    
218
typedef struct {
219
    uint64_t timecode;
220
    EbmlList blocks;
221
} MatroskaCluster;
222

    
223
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
224

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

    
237
static EbmlSyntax ebml_syntax[] = {
238
    { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
239
    { 0 }
240
};
241

    
242
static EbmlSyntax matroska_info[] = {
243
    { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
244
    { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
245
    { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
246
    { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
247
    { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
248
    { MATROSKA_ID_DATEUTC,            EBML_NONE },
249
    { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
250
    { EBML_ID_VOID,                   EBML_NONE },
251
    { 0 }
252
};
253

    
254
static EbmlSyntax matroska_track_video[] = {
255
    { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
256
    { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
257
    { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
258
    { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
259
    { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
260
    { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
261
    { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
262
    { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
263
    { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
264
    { EBML_ID_VOID,                   EBML_NONE },
265
    { 0 }
266
};
267

    
268
static EbmlSyntax matroska_track_audio[] = {
269
    { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
270
    { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
271
    { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
272
    { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
273
    { EBML_ID_VOID,                   EBML_NONE },
274
    { 0 }
275
};
276

    
277
static EbmlSyntax matroska_track_encoding_compression[] = {
278
    { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
279
    { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
280
    { EBML_ID_VOID,                   EBML_NONE },
281
    { 0 }
282
};
283

    
284
static EbmlSyntax matroska_track_encoding[] = {
285
    { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
286
    { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
287
    { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
288
    { EBML_ID_VOID,                   EBML_NONE },
289
    { 0 }
290
};
291

    
292
static EbmlSyntax matroska_track_encodings[] = {
293
    { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
294
    { EBML_ID_VOID,                   EBML_NONE },
295
    { 0 }
296
};
297

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

    
325
static EbmlSyntax matroska_tracks[] = {
326
    { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
327
    { EBML_ID_VOID,                   EBML_NONE },
328
    { 0 }
329
};
330

    
331
static EbmlSyntax matroska_attachment[] = {
332
    { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
333
    { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
334
    { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
335
    { MATROSKA_ID_FILEUID,            EBML_NONE },
336
    { EBML_ID_VOID,                   EBML_NONE },
337
    { 0 }
338
};
339

    
340
static EbmlSyntax matroska_attachments[] = {
341
    { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
342
    { EBML_ID_VOID,                   EBML_NONE },
343
    { 0 }
344
};
345

    
346
static EbmlSyntax matroska_chapter_display[] = {
347
    { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
348
    { EBML_ID_VOID,                   EBML_NONE },
349
    { 0 }
350
};
351

    
352
static EbmlSyntax matroska_chapter_entry[] = {
353
    { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
354
    { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
355
    { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
356
    { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
357
    { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
358
    { EBML_ID_VOID,                   EBML_NONE },
359
    { 0 }
360
};
361

    
362
static EbmlSyntax matroska_chapter[] = {
363
    { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
364
    { MATROSKA_ID_EDITIONUID,         EBML_NONE },
365
    { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
366
    { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
367
    { EBML_ID_VOID,                   EBML_NONE },
368
    { 0 }
369
};
370

    
371
static EbmlSyntax matroska_chapters[] = {
372
    { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
373
    { EBML_ID_VOID,                   EBML_NONE },
374
    { 0 }
375
};
376

    
377
static EbmlSyntax matroska_index_pos[] = {
378
    { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
379
    { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
380
    { EBML_ID_VOID,                   EBML_NONE },
381
    { 0 }
382
};
383

    
384
static EbmlSyntax matroska_index_entry[] = {
385
    { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
386
    { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
387
    { EBML_ID_VOID,                   EBML_NONE },
388
    { 0 }
389
};
390

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

    
397
static EbmlSyntax matroska_tags[] = {
398
    { EBML_ID_VOID,                   EBML_NONE },
399
    { 0 }
400
};
401

    
402
static EbmlSyntax matroska_seekhead_entry[] = {
403
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
404
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
405
    { EBML_ID_VOID,                   EBML_NONE },
406
    { 0 }
407
};
408

    
409
static EbmlSyntax matroska_seekhead[] = {
410
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
411
    { EBML_ID_VOID,                   EBML_NONE },
412
    { 0 }
413
};
414

    
415
static EbmlSyntax matroska_segment[] = {
416
    { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
417
    { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
418
    { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
419
    { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
420
    { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
421
    { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
422
    { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
423
    { MATROSKA_ID_CLUSTER,        EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
424
    { EBML_ID_VOID,               EBML_NONE },
425
    { 0 }
426
};
427

    
428
static EbmlSyntax matroska_segments[] = {
429
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
430
    { 0 }
431
};
432

    
433
static EbmlSyntax matroska_blockgroup[] = {
434
    { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
435
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
436
    { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
437
    { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
438
    { EBML_ID_VOID,               EBML_NONE },
439
    { 0 }
440
};
441

    
442
static EbmlSyntax matroska_cluster[] = {
443
    { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
444
    { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
445
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
446
    { EBML_ID_VOID,               EBML_NONE },
447
    { 0 }
448
};
449

    
450
static EbmlSyntax matroska_clusters[] = {
451
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
452
    { 0 }
453
};
454

    
455
/*
456
 * Return: whether we reached the end of a level in the hierarchy or not
457
 */
458
static int ebml_level_end(MatroskaDemuxContext *matroska)
459
{
460
    ByteIOContext *pb = matroska->ctx->pb;
461
    offset_t pos = url_ftell(pb);
462

    
463
    if (matroska->num_levels > 0) {
464
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
465
        if (pos - level->start >= level->length) {
466
            matroska->num_levels--;
467
            return 1;
468
        }
469
    }
470
    return 0;
471
}
472

    
473
/*
474
 * Read: an "EBML number", which is defined as a variable-length
475
 * array of bytes. The first byte indicates the length by giving a
476
 * number of 0-bits followed by a one. The position of the first
477
 * "one" bit inside the first byte indicates the length of this
478
 * number.
479
 * Returns: num. of bytes read. < 0 on error.
480
 */
481
static int ebml_read_num(MatroskaDemuxContext *matroska, ByteIOContext *pb,
482
                         int max_size, uint64_t *number)
483
{
484
    int len_mask = 0x80, read = 1, n = 1;
485
    int64_t total = 0;
486

    
487
    /* the first byte tells us the length in bytes - get_byte() can normally
488
     * return 0, but since that's not a valid first ebmlID byte, we can
489
     * use it safely here to catch EOS. */
490
    if (!(total = get_byte(pb))) {
491
        /* we might encounter EOS here */
492
        if (!url_feof(pb)) {
493
            offset_t pos = url_ftell(pb);
494
            av_log(matroska->ctx, AV_LOG_ERROR,
495
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
496
                   pos, pos);
497
        }
498
        return AVERROR(EIO); /* EOS or actual I/O error */
499
    }
500

    
501
    /* get the length of the EBML number */
502
    while (read <= max_size && !(total & len_mask)) {
503
        read++;
504
        len_mask >>= 1;
505
    }
506
    if (read > max_size) {
507
        offset_t pos = url_ftell(pb) - 1;
508
        av_log(matroska->ctx, AV_LOG_ERROR,
509
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
510
               (uint8_t) total, pos, pos);
511
        return AVERROR_INVALIDDATA;
512
    }
513

    
514
    /* read out length */
515
    total &= ~len_mask;
516
    while (n++ < read)
517
        total = (total << 8) | get_byte(pb);
518

    
519
    *number = total;
520

    
521
    return read;
522
}
523

    
524
/*
525
 * Read: the element content data ID.
526
 * 0 is success, < 0 is failure.
527
 */
528
static int ebml_read_element_id(MatroskaDemuxContext *matroska, uint32_t *id)
529
{
530
    int read;
531
    uint64_t total;
532

    
533
    /* read out the "EBML number", include tag in ID */
534
    if ((read = ebml_read_num(matroska, matroska->ctx->pb, 4, &total)) < 0)
535
        return read;
536
    *id = total | (1 << (read * 7));
537

    
538
    return 0;
539
}
540

    
541
/*
542
 * Read the next element as an unsigned int.
543
 * 0 is success, < 0 is failure.
544
 */
545
static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
546
{
547
    int n = 0;
548

    
549
    if (size < 1 || size > 8)
550
        return AVERROR_INVALIDDATA;
551

    
552
    /* big-endian ordening; build up number */
553
    *num = 0;
554
    while (n++ < size)
555
        *num = (*num << 8) | get_byte(pb);
556

    
557
    return 0;
558
}
559

    
560
/*
561
 * Read the next element as a float.
562
 * 0 is success, < 0 is failure.
563
 */
564
static int ebml_read_float(ByteIOContext *pb, int size, double *num)
565
{
566
    if (size == 4) {
567
        *num= av_int2flt(get_be32(pb));
568
    } else if(size==8){
569
        *num= av_int2dbl(get_be64(pb));
570
    } else
571
        return AVERROR_INVALIDDATA;
572

    
573
    return 0;
574
}
575

    
576
/*
577
 * Read the next element as an ASCII string.
578
 * 0 is success, < 0 is failure.
579
 */
580
static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
581
{
582
    av_free(*str);
583
    /* ebml strings are usually not 0-terminated, so we allocate one
584
     * byte more, read the string and NULL-terminate it ourselves. */
585
    if (!(*str = av_malloc(size + 1)))
586
        return AVERROR(ENOMEM);
587
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
588
        av_free(*str);
589
        return AVERROR(EIO);
590
    }
591
    (*str)[size] = '\0';
592

    
593
    return 0;
594
}
595

    
596
/*
597
 * Read the next element as binary data.
598
 * 0 is success, < 0 is failure.
599
 */
600
static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
601
{
602
    av_free(bin->data);
603
    if (!(bin->data = av_malloc(length)))
604
        return AVERROR(ENOMEM);
605

    
606
    bin->size = length;
607
    bin->pos  = url_ftell(pb);
608
    if (get_buffer(pb, bin->data, length) != length)
609
        return AVERROR(EIO);
610

    
611
    return 0;
612
}
613

    
614
/*
615
 * Read the next element, but only the header. The contents
616
 * are supposed to be sub-elements which can be read separately.
617
 * 0 is success, < 0 is failure.
618
 */
619
static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
620
{
621
    ByteIOContext *pb = matroska->ctx->pb;
622
    MatroskaLevel *level;
623

    
624
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
625
        av_log(matroska->ctx, AV_LOG_ERROR,
626
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
627
        return AVERROR(ENOSYS);
628
    }
629

    
630
    level = &matroska->levels[matroska->num_levels++];
631
    level->start = url_ftell(pb);
632
    level->length = length;
633

    
634
    return 0;
635
}
636

    
637
/*
638
 * Read signed/unsigned "EBML" numbers.
639
 * Return: number of bytes processed, < 0 on error.
640
 */
641
static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
642
                                 uint8_t *data, uint32_t size, uint64_t *num)
643
{
644
    ByteIOContext pb;
645
    init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
646
    return ebml_read_num(matroska, &pb, 8, num);
647
}
648

    
649
/*
650
 * Same as above, but signed.
651
 */
652
static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
653
                                 uint8_t *data, uint32_t size, int64_t *num)
654
{
655
    uint64_t unum;
656
    int res;
657

    
658
    /* read as unsigned number first */
659
    if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
660
        return res;
661

    
662
    /* make signed (weird way) */
663
    *num = unum - ((1LL << (7*res - 1)) - 1);
664

    
665
    return res;
666
}
667

    
668
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
669
                           EbmlSyntax *syntax, void *data);
670

    
671
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
672
                         uint32_t id, void *data)
673
{
674
    int i;
675
    for (i=0; syntax[i].id; i++)
676
        if (id == syntax[i].id)
677
            break;
678
    if (!syntax[i].id)
679
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
680
    return ebml_parse_elem(matroska, &syntax[i], data);
681
}
682

    
683
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
684
                      void *data)
685
{
686
    uint32_t id;
687
    int res = ebml_read_element_id(matroska, &id);
688
    return res < 0 ? res : ebml_parse_id(matroska, syntax, id, data);
689
}
690

    
691
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
692
                           void *data)
693
{
694
    int i, res = 0;
695

    
696
    for (i=0; syntax[i].id; i++)
697
        switch (syntax[i].type) {
698
        case EBML_UINT:
699
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
700
            break;
701
        case EBML_FLOAT:
702
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
703
            break;
704
        case EBML_STR:
705
        case EBML_UTF8:
706
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
707
            break;
708
        }
709

    
710
    while (!res && !ebml_level_end(matroska))
711
        res = ebml_parse(matroska, syntax, data);
712

    
713
    return res;
714
}
715

    
716
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
717
                           EbmlSyntax *syntax, void *data)
718
{
719
    ByteIOContext *pb = matroska->ctx->pb;
720
    uint32_t id = syntax->id;
721
    uint64_t length;
722
    int res;
723

    
724
    data = (char *)data + syntax->data_offset;
725
    if (syntax->list_elem_size) {
726
        EbmlList *list = data;
727
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
728
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
729
        memset(data, 0, syntax->list_elem_size);
730
        list->nb_elem++;
731
    }
732

    
733
    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
734
        if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
735
            return res;
736

    
737
    switch (syntax->type) {
738
    case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
739
    case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
740
    case EBML_STR:
741
    case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
742
    case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
743
    case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
744
                         return res;
745
                     if (id == MATROSKA_ID_SEGMENT)
746
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
747
                     return ebml_parse_nest(matroska, syntax->def.n, data);
748
    case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
749
    case EBML_STOP:  *(int *)data = 1;      return 1;
750
    default:         url_fskip(pb, length); return 0;
751
    }
752
    if (res == AVERROR_INVALIDDATA)
753
        av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
754
    else if (res == AVERROR(EIO))
755
        av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
756
    return res;
757
}
758

    
759
static void ebml_free(EbmlSyntax *syntax, void *data)
760
{
761
    int i, j;
762
    for (i=0; syntax[i].id; i++) {
763
        void *data_off = (char *)data + syntax[i].data_offset;
764
        switch (syntax[i].type) {
765
        case EBML_STR:
766
        case EBML_UTF8:  av_freep(data_off);                      break;
767
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
768
        case EBML_NEST:
769
            if (syntax[i].list_elem_size) {
770
                EbmlList *list = data_off;
771
                char *ptr = list->elem;
772
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
773
                    ebml_free(syntax[i].def.n, ptr);
774
                av_free(list->elem);
775
            } else
776
                ebml_free(syntax[i].def.n, data_off);
777
        default:  break;
778
        }
779
    }
780
}
781

    
782

    
783
/*
784
 * Autodetecting...
785
 */
786
static int matroska_probe(AVProbeData *p)
787
{
788
    uint64_t total = 0;
789
    int len_mask = 0x80, size = 1, n = 1;
790
    char probe_data[] = "matroska";
791

    
792
    /* ebml header? */
793
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
794
        return 0;
795

    
796
    /* length of header */
797
    total = p->buf[4];
798
    while (size <= 8 && !(total & len_mask)) {
799
        size++;
800
        len_mask >>= 1;
801
    }
802
    if (size > 8)
803
      return 0;
804
    total &= (len_mask - 1);
805
    while (n < size)
806
        total = (total << 8) | p->buf[4 + n++];
807

    
808
    /* does the probe data contain the whole header? */
809
    if (p->buf_size < 4 + size + total)
810
      return 0;
811

    
812
    /* the header must contain the document type 'matroska'. For now,
813
     * we don't parse the whole header but simply check for the
814
     * availability of that array of characters inside the header.
815
     * Not fully fool-proof, but good enough. */
816
    for (n = 4+size; n <= 4+size+total-(sizeof(probe_data)-1); n++)
817
        if (!memcmp(p->buf+n, probe_data, sizeof(probe_data)-1))
818
            return AVPROBE_SCORE_MAX;
819

    
820
    return 0;
821
}
822

    
823
static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
824
                                                 int num)
825
{
826
    MatroskaTrack *tracks = matroska->tracks.elem;
827
    int i;
828

    
829
    for (i=0; i < matroska->tracks.nb_elem; i++)
830
        if (tracks[i].num == num)
831
            return &tracks[i];
832

    
833
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
834
    return NULL;
835
}
836

    
837
static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
838
                                  MatroskaTrack *track)
839
{
840
    MatroskaTrackEncoding *encodings = track->encodings.elem;
841
    uint8_t* data = *buf;
842
    int isize = *buf_size;
843
    uint8_t* pkt_data = NULL;
844
    int pkt_size = isize;
845
    int result = 0;
846
    int olen;
847

    
848
    switch (encodings[0].compression.algo) {
849
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
850
        return encodings[0].compression.settings.size;
851
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
852
        do {
853
            olen = pkt_size *= 3;
854
            pkt_data = av_realloc(pkt_data,
855
                                  pkt_size+LZO_OUTPUT_PADDING);
856
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
857
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
858
        if (result)
859
            goto failed;
860
        pkt_size -= olen;
861
        break;
862
#ifdef CONFIG_ZLIB
863
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
864
        z_stream zstream = {0};
865
        if (inflateInit(&zstream) != Z_OK)
866
            return -1;
867
        zstream.next_in = data;
868
        zstream.avail_in = isize;
869
        do {
870
            pkt_size *= 3;
871
            pkt_data = av_realloc(pkt_data, pkt_size);
872
            zstream.avail_out = pkt_size - zstream.total_out;
873
            zstream.next_out = pkt_data + zstream.total_out;
874
            result = inflate(&zstream, Z_NO_FLUSH);
875
        } while (result==Z_OK && pkt_size<10000000);
876
        pkt_size = zstream.total_out;
877
        inflateEnd(&zstream);
878
        if (result != Z_STREAM_END)
879
            goto failed;
880
        break;
881
    }
882
#endif
883
#ifdef CONFIG_BZLIB
884
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
885
        bz_stream bzstream = {0};
886
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
887
            return -1;
888
        bzstream.next_in = data;
889
        bzstream.avail_in = isize;
890
        do {
891
            pkt_size *= 3;
892
            pkt_data = av_realloc(pkt_data, pkt_size);
893
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
894
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
895
            result = BZ2_bzDecompress(&bzstream);
896
        } while (result==BZ_OK && pkt_size<10000000);
897
        pkt_size = bzstream.total_out_lo32;
898
        BZ2_bzDecompressEnd(&bzstream);
899
        if (result != BZ_STREAM_END)
900
            goto failed;
901
        break;
902
    }
903
#endif
904
    }
905

    
906
    *buf = pkt_data;
907
    *buf_size = pkt_size;
908
    return 0;
909
 failed:
910
    av_free(pkt_data);
911
    return -1;
912
}
913

    
914
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
915
{
916
    EbmlList *seekhead_list = &matroska->seekhead;
917
    MatroskaSeekhead *seekhead = seekhead_list->elem;
918
    uint32_t level_up = matroska->level_up;
919
    offset_t before_pos = url_ftell(matroska->ctx->pb);
920
    MatroskaLevel level;
921
    int i;
922

    
923
    for (i=0; i<seekhead_list->nb_elem; i++) {
924
        offset_t offset = seekhead[i].pos + matroska->segment_start;
925

    
926
        if (seekhead[i].pos <= before_pos
927
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
928
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
929
            continue;
930

    
931
        /* seek */
932
        if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
933
            continue;
934

    
935
        /* we don't want to lose our seekhead level, so we add
936
         * a dummy. This is a crude hack. */
937
        if (matroska->num_levels == EBML_MAX_DEPTH) {
938
            av_log(matroska->ctx, AV_LOG_INFO,
939
                   "Max EBML element depth (%d) reached, "
940
                   "cannot parse further.\n", EBML_MAX_DEPTH);
941
            break;
942
        }
943

    
944
        level.start = 0;
945
        level.length = (uint64_t)-1;
946
        matroska->levels[matroska->num_levels] = level;
947
        matroska->num_levels++;
948

    
949
        ebml_parse(matroska, matroska_segment, matroska);
950

    
951
        /* remove dummy level */
952
        while (matroska->num_levels) {
953
            uint64_t length = matroska->levels[--matroska->num_levels].length;
954
            if (length == (uint64_t)-1)
955
                break;
956
        }
957
    }
958

    
959
    /* seek back */
960
    url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
961
    matroska->level_up = level_up;
962
}
963

    
964
static int matroska_aac_profile(char *codec_id)
965
{
966
    static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
967
    int profile;
968

    
969
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
970
        if (strstr(codec_id, aac_profiles[profile]))
971
            break;
972
    return profile + 1;
973
}
974

    
975
static int matroska_aac_sri(int samplerate)
976
{
977
    int sri;
978

    
979
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
980
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
981
            break;
982
    return sri;
983
}
984

    
985
static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
986
{
987
    MatroskaDemuxContext *matroska = s->priv_data;
988
    EbmlList *attachements_list = &matroska->attachments;
989
    MatroskaAttachement *attachements;
990
    EbmlList *chapters_list = &matroska->chapters;
991
    MatroskaChapter *chapters;
992
    MatroskaTrack *tracks;
993
    EbmlList *index_list;
994
    MatroskaIndex *index;
995
    Ebml ebml = { 0 };
996
    AVStream *st;
997
    int i, j;
998

    
999
    matroska->ctx = s;
1000

    
1001
    /* First read the EBML header. */
1002
    if (ebml_parse(matroska, ebml_syntax, &ebml)
1003
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1004
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1005
        || ebml.doctype_version > 2) {
1006
        av_log(matroska->ctx, AV_LOG_ERROR,
1007
               "EBML header using unsupported features\n"
1008
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1009
               ebml.version, ebml.doctype, ebml.doctype_version);
1010
        return AVERROR_NOFMT;
1011
    }
1012
    ebml_free(ebml_syntax, &ebml);
1013

    
1014
    /* The next thing is a segment. */
1015
    if (ebml_parse(matroska, matroska_segments, matroska) < 0)
1016
        return -1;
1017
    matroska_execute_seekhead(matroska);
1018

    
1019
    if (matroska->duration)
1020
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1021
                                  * 1000 / AV_TIME_BASE;
1022
    if (matroska->title)
1023
        strncpy(matroska->ctx->title, matroska->title,
1024
                sizeof(matroska->ctx->title)-1);
1025

    
1026
    tracks = matroska->tracks.elem;
1027
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1028
        MatroskaTrack *track = &tracks[i];
1029
        enum CodecID codec_id = CODEC_ID_NONE;
1030
        EbmlList *encodings_list = &tracks->encodings;
1031
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1032
        uint8_t *extradata = NULL;
1033
        int extradata_size = 0;
1034
        int extradata_offset = 0;
1035

    
1036
        /* Apply some sanity checks. */
1037
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1038
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1039
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1040
            av_log(matroska->ctx, AV_LOG_INFO,
1041
                   "Unknown or unsupported track type %"PRIu64"\n",
1042
                   track->type);
1043
            continue;
1044
        }
1045
        if (track->codec_id == NULL)
1046
            continue;
1047

    
1048
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1049
            if (!track->default_duration)
1050
                track->default_duration = 1000000000/track->video.frame_rate;
1051
            if (!track->video.display_width)
1052
                track->video.display_width = track->video.pixel_width;
1053
            if (!track->video.display_height)
1054
                track->video.display_height = track->video.pixel_height;
1055
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1056
            if (!track->audio.out_samplerate)
1057
                track->audio.out_samplerate = track->audio.samplerate;
1058
        }
1059
        if (encodings_list->nb_elem > 1) {
1060
            av_log(matroska->ctx, AV_LOG_ERROR,
1061
                   "Multiple combined encodings no supported");
1062
        } else if (encodings_list->nb_elem == 1) {
1063
            if (encodings[0].type ||
1064
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1065
#ifdef CONFIG_ZLIB
1066
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1067
#endif
1068
#ifdef CONFIG_BZLIB
1069
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1070
#endif
1071
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1072
                encodings[0].scope = 0;
1073
                av_log(matroska->ctx, AV_LOG_ERROR,
1074
                       "Unsupported encoding type");
1075
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1076
                uint8_t *codec_priv = track->codec_priv.data;
1077
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1078
                                                    &track->codec_priv.size,
1079
                                                    track);
1080
                if (offset < 0) {
1081
                    track->codec_priv.data = NULL;
1082
                    track->codec_priv.size = 0;
1083
                    av_log(matroska->ctx, AV_LOG_ERROR,
1084
                           "Failed to decode codec private data\n");
1085
                } else if (offset > 0) {
1086
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1087
                    memcpy(track->codec_priv.data,
1088
                           encodings[0].compression.settings.data, offset);
1089
                    memcpy(track->codec_priv.data+offset, codec_priv,
1090
                           track->codec_priv.size);
1091
                    track->codec_priv.size += offset;
1092
                }
1093
                if (codec_priv != track->codec_priv.data)
1094
                    av_free(codec_priv);
1095
            }
1096
        }
1097

    
1098
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1099
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1100
                        strlen(ff_mkv_codec_tags[j].str))){
1101
                codec_id= ff_mkv_codec_tags[j].id;
1102
                break;
1103
            }
1104
        }
1105

    
1106
        st = track->stream = av_new_stream(s, matroska->num_streams++);
1107
        if (st == NULL)
1108
            return AVERROR(ENOMEM);
1109

    
1110
        if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1111
            && track->codec_priv.size >= 40
1112
            && track->codec_priv.data != NULL) {
1113
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1114
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1115
        } else if (!strcmp(track->codec_id, "A_MS/ACM")
1116
                   && track->codec_priv.size >= 18
1117
                   && track->codec_priv.data != NULL) {
1118
            uint16_t tag = AV_RL16(track->codec_priv.data);
1119
            codec_id = codec_get_id(codec_wav_tags, tag);
1120
        } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1121
                   && (track->codec_priv.size >= 86)
1122
                   && (track->codec_priv.data != NULL)) {
1123
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1124
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1125
        } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1126
            int profile = matroska_aac_profile(track->codec_id);
1127
            int sri = matroska_aac_sri(track->audio.samplerate);
1128
            extradata = av_malloc(5);
1129
            if (extradata == NULL)
1130
                return AVERROR(ENOMEM);
1131
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1132
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1133
            if (strstr(track->codec_id, "SBR")) {
1134
                sri = matroska_aac_sri(track->audio.out_samplerate);
1135
                extradata[2] = 0x56;
1136
                extradata[3] = 0xE5;
1137
                extradata[4] = 0x80 | (sri<<3);
1138
                extradata_size = 5;
1139
            } else
1140
                extradata_size = 2;
1141
        } else if (codec_id == CODEC_ID_TTA) {
1142
            ByteIOContext b;
1143
            extradata_size = 30;
1144
            extradata = av_mallocz(extradata_size);
1145
            if (extradata == NULL)
1146
                return AVERROR(ENOMEM);
1147
            init_put_byte(&b, extradata, extradata_size, 1,
1148
                          NULL, NULL, NULL, NULL);
1149
            put_buffer(&b, "TTA1", 4);
1150
            put_le16(&b, 1);
1151
            put_le16(&b, track->audio.channels);
1152
            put_le16(&b, track->audio.bitdepth);
1153
            put_le32(&b, track->audio.out_samplerate);
1154
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1155
        } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1156
                   codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1157
            extradata_offset = 26;
1158
            track->codec_priv.size -= extradata_offset;
1159
        } else if (codec_id == CODEC_ID_RA_144) {
1160
            track->audio.out_samplerate = 8000;
1161
            track->audio.channels = 1;
1162
        } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1163
                   codec_id == CODEC_ID_ATRAC3) {
1164
            ByteIOContext b;
1165

    
1166
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1167
                          0, NULL, NULL, NULL, NULL);
1168
            url_fskip(&b, 24);
1169
            track->audio.coded_framesize = get_be32(&b);
1170
            url_fskip(&b, 12);
1171
            track->audio.sub_packet_h    = get_be16(&b);
1172
            track->audio.frame_size      = get_be16(&b);
1173
            track->audio.sub_packet_size = get_be16(&b);
1174
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1175
            if (codec_id == CODEC_ID_RA_288) {
1176
                st->codec->block_align = track->audio.coded_framesize;
1177
                track->codec_priv.size = 0;
1178
            } else {
1179
                st->codec->block_align = track->audio.sub_packet_size;
1180
                extradata_offset = 78;
1181
                track->codec_priv.size -= extradata_offset;
1182
            }
1183
        }
1184

    
1185
        if (codec_id == CODEC_ID_NONE)
1186
            av_log(matroska->ctx, AV_LOG_INFO,
1187
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1188

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

    
1191
        st->codec->codec_id = codec_id;
1192
        st->start_time = 0;
1193
        if (strcmp(track->language, "und"))
1194
            av_strlcpy(st->language, track->language, 4);
1195

    
1196
        if (track->flag_default)
1197
            st->disposition |= AV_DISPOSITION_DEFAULT;
1198

    
1199
        if (track->default_duration)
1200
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1201
                      track->default_duration, 1000000000, 30000);
1202

    
1203
        if(extradata){
1204
            st->codec->extradata = extradata;
1205
            st->codec->extradata_size = extradata_size;
1206
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1207
            st->codec->extradata = av_malloc(track->codec_priv.size);
1208
            if(st->codec->extradata == NULL)
1209
                return AVERROR(ENOMEM);
1210
            st->codec->extradata_size = track->codec_priv.size;
1211
            memcpy(st->codec->extradata,
1212
                   track->codec_priv.data + extradata_offset,
1213
                   track->codec_priv.size);
1214
        }
1215

    
1216
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1217
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1218
            st->codec->codec_tag  = track->video.fourcc;
1219
            st->codec->width  = track->video.pixel_width;
1220
            st->codec->height = track->video.pixel_height;
1221
            av_reduce(&st->codec->sample_aspect_ratio.num,
1222
                      &st->codec->sample_aspect_ratio.den,
1223
                      st->codec->height * track->video.display_width,
1224
                      st->codec-> width * track->video.display_height,
1225
                      255);
1226
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1227
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1228
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1229
            st->codec->sample_rate = track->audio.out_samplerate;
1230
            st->codec->channels = track->audio.channels;
1231
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1232
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1233
        }
1234
    }
1235

    
1236
    attachements = attachements_list->elem;
1237
    for (j=0; j<attachements_list->nb_elem; j++) {
1238
        if (!(attachements[j].filename && attachements[j].mime &&
1239
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1240
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1241
        } else {
1242
            AVStream *st = av_new_stream(s, matroska->num_streams++);
1243
            if (st == NULL)
1244
                break;
1245
            st->filename          = av_strdup(attachements[j].filename);
1246
            st->codec->codec_id = CODEC_ID_NONE;
1247
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1248
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1249
            if(st->codec->extradata == NULL)
1250
                break;
1251
            st->codec->extradata_size = attachements[j].bin.size;
1252
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1253

    
1254
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1255
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1256
                             strlen(ff_mkv_mime_tags[i].str))) {
1257
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1258
                    break;
1259
                }
1260
            }
1261
        }
1262
    }
1263

    
1264
    chapters = chapters_list->elem;
1265
    for (i=0; i<chapters_list->nb_elem; i++)
1266
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1267
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1268
                           chapters[i].start, chapters[i].end,
1269
                           chapters[i].title);
1270

    
1271
    index_list = &matroska->index;
1272
    index = index_list->elem;
1273
    for (i=0; i<index_list->nb_elem; i++) {
1274
        EbmlList *pos_list = &index[i].pos;
1275
        MatroskaIndexPos *pos = pos_list->elem;
1276
        for (j=0; j<pos_list->nb_elem; j++) {
1277
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1278
                                                              pos[j].track);
1279
            if (track && track->stream)
1280
                av_add_index_entry(track->stream,
1281
                                   pos[j].pos + matroska->segment_start,
1282
                                   index[i].time*matroska->time_scale/AV_TIME_BASE,
1283
                                   0, 0, AVINDEX_KEYFRAME);
1284
        }
1285
    }
1286

    
1287
    return 0;
1288
}
1289

    
1290
/*
1291
 * Put a packet into our internal queue. Will be delivered to the
1292
 * user/application during the next get_packet() call.
1293
 */
1294
static void matroska_queue_packet(MatroskaDemuxContext *matroska, AVPacket *pkt)
1295
{
1296
    matroska->packets =
1297
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
1298
                   sizeof(AVPacket *));
1299
    matroska->packets[matroska->num_packets] = pkt;
1300
    matroska->num_packets++;
1301
}
1302

    
1303
/*
1304
 * Put one packet in an application-supplied AVPacket struct.
1305
 * Returns 0 on success or -1 on failure.
1306
 */
1307
static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1308
                                   AVPacket *pkt)
1309
{
1310
    if (matroska->num_packets > 0) {
1311
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1312
        av_free(matroska->packets[0]);
1313
        if (matroska->num_packets > 1) {
1314
            memmove(&matroska->packets[0], &matroska->packets[1],
1315
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
1316
            matroska->packets =
1317
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
1318
                           sizeof(AVPacket *));
1319
        } else {
1320
            av_freep(&matroska->packets);
1321
        }
1322
        matroska->num_packets--;
1323
        return 0;
1324
    }
1325

    
1326
    return -1;
1327
}
1328

    
1329
/*
1330
 * Free all packets in our internal queue.
1331
 */
1332
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1333
{
1334
    if (matroska->packets) {
1335
        int n;
1336
        for (n = 0; n < matroska->num_packets; n++) {
1337
            av_free_packet(matroska->packets[n]);
1338
            av_free(matroska->packets[n]);
1339
        }
1340
        av_free(matroska->packets);
1341
        matroska->packets = NULL;
1342
        matroska->num_packets = 0;
1343
    }
1344
}
1345

    
1346
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1347
                                int size, int64_t pos, uint64_t cluster_time,
1348
                                uint64_t duration, int is_keyframe)
1349
{
1350
    MatroskaTrack *track;
1351
    int res = 0;
1352
    AVStream *st;
1353
    AVPacket *pkt;
1354
    int16_t block_time;
1355
    uint32_t *lace_size = NULL;
1356
    int n, flags, laces = 0;
1357
    uint64_t num;
1358

    
1359
    if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1360
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1361
        return res;
1362
    }
1363
    data += n;
1364
    size -= n;
1365

    
1366
    track = matroska_find_track_by_num(matroska, num);
1367
    if (size <= 3 || !track || !track->stream) {
1368
        av_log(matroska->ctx, AV_LOG_INFO,
1369
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1370
        return res;
1371
    }
1372
    st = track->stream;
1373
    if (st->discard >= AVDISCARD_ALL)
1374
        return res;
1375
    if (duration == AV_NOPTS_VALUE)
1376
        duration = track->default_duration / matroska->time_scale;
1377

    
1378
    block_time = AV_RB16(data);
1379
    data += 2;
1380
    flags = *data++;
1381
    size -= 3;
1382
    if (is_keyframe == -1)
1383
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1384

    
1385
    if (matroska->skip_to_keyframe) {
1386
        if (!is_keyframe || st != matroska->skip_to_stream)
1387
            return res;
1388
        matroska->skip_to_keyframe = 0;
1389
    }
1390

    
1391
    switch ((flags & 0x06) >> 1) {
1392
        case 0x0: /* no lacing */
1393
            laces = 1;
1394
            lace_size = av_mallocz(sizeof(int));
1395
            lace_size[0] = size;
1396
            break;
1397

    
1398
        case 0x1: /* xiph lacing */
1399
        case 0x2: /* fixed-size lacing */
1400
        case 0x3: /* EBML lacing */
1401
            assert(size>0); // size <=3 is checked before size-=3 above
1402
            laces = (*data) + 1;
1403
            data += 1;
1404
            size -= 1;
1405
            lace_size = av_mallocz(laces * sizeof(int));
1406

    
1407
            switch ((flags & 0x06) >> 1) {
1408
                case 0x1: /* xiph lacing */ {
1409
                    uint8_t temp;
1410
                    uint32_t total = 0;
1411
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1412
                        while (1) {
1413
                            if (size == 0) {
1414
                                res = -1;
1415
                                break;
1416
                            }
1417
                            temp = *data;
1418
                            lace_size[n] += temp;
1419
                            data += 1;
1420
                            size -= 1;
1421
                            if (temp != 0xff)
1422
                                break;
1423
                        }
1424
                        total += lace_size[n];
1425
                    }
1426
                    lace_size[n] = size - total;
1427
                    break;
1428
                }
1429

    
1430
                case 0x2: /* fixed-size lacing */
1431
                    for (n = 0; n < laces; n++)
1432
                        lace_size[n] = size / laces;
1433
                    break;
1434

    
1435
                case 0x3: /* EBML lacing */ {
1436
                    uint32_t total;
1437
                    n = matroska_ebmlnum_uint(matroska, data, size, &num);
1438
                    if (n < 0) {
1439
                        av_log(matroska->ctx, AV_LOG_INFO,
1440
                               "EBML block data error\n");
1441
                        break;
1442
                    }
1443
                    data += n;
1444
                    size -= n;
1445
                    total = lace_size[0] = num;
1446
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1447
                        int64_t snum;
1448
                        int r;
1449
                        r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1450
                        if (r < 0) {
1451
                            av_log(matroska->ctx, AV_LOG_INFO,
1452
                                   "EBML block data error\n");
1453
                            break;
1454
                        }
1455
                        data += r;
1456
                        size -= r;
1457
                        lace_size[n] = lace_size[n - 1] + snum;
1458
                        total += lace_size[n];
1459
                    }
1460
                    lace_size[n] = size - total;
1461
                    break;
1462
                }
1463
            }
1464
            break;
1465
    }
1466

    
1467
    if (res == 0) {
1468
        uint64_t timecode = AV_NOPTS_VALUE;
1469

    
1470
        if (cluster_time != (uint64_t)-1
1471
            && (block_time >= 0 || cluster_time >= -block_time))
1472
            timecode = cluster_time + block_time;
1473

    
1474
        for (n = 0; n < laces; n++) {
1475
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1476
                st->codec->codec_id == CODEC_ID_COOK ||
1477
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1478
                int a = st->codec->block_align;
1479
                int sps = track->audio.sub_packet_size;
1480
                int cfs = track->audio.coded_framesize;
1481
                int h = track->audio.sub_packet_h;
1482
                int y = track->audio.sub_packet_cnt;
1483
                int w = track->audio.frame_size;
1484
                int x;
1485

    
1486
                if (!track->audio.pkt_cnt) {
1487
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1488
                        for (x=0; x<h/2; x++)
1489
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1490
                                   data+x*cfs, cfs);
1491
                    else
1492
                        for (x=0; x<w/sps; x++)
1493
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1494

    
1495
                    if (++track->audio.sub_packet_cnt >= h) {
1496
                        track->audio.sub_packet_cnt = 0;
1497
                        track->audio.pkt_cnt = h*w / a;
1498
                    }
1499
                }
1500
                while (track->audio.pkt_cnt) {
1501
                    pkt = av_mallocz(sizeof(AVPacket));
1502
                    av_new_packet(pkt, a);
1503
                    memcpy(pkt->data, track->audio.buf
1504
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1505
                    pkt->pos = pos;
1506
                    pkt->stream_index = st->index;
1507
                    matroska_queue_packet(matroska, pkt);
1508
                }
1509
            } else {
1510
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1511
                int offset = 0, pkt_size = lace_size[n];
1512
                uint8_t *pkt_data = data;
1513

    
1514
                if (encodings && encodings->scope & 1) {
1515
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1516
                    if (offset < 0)
1517
                        continue;
1518
                }
1519

    
1520
                pkt = av_mallocz(sizeof(AVPacket));
1521
                /* XXX: prevent data copy... */
1522
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1523
                    av_free(pkt);
1524
                    res = AVERROR(ENOMEM);
1525
                    n = laces-1;
1526
                    break;
1527
                }
1528
                if (offset)
1529
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1530
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1531

    
1532
                if (pkt_data != data)
1533
                    av_free(pkt_data);
1534

    
1535
                if (n == 0)
1536
                    pkt->flags = is_keyframe;
1537
                pkt->stream_index = st->index;
1538

    
1539
                pkt->pts = timecode;
1540
                pkt->pos = pos;
1541
                pkt->duration = duration;
1542

    
1543
                matroska_queue_packet(matroska, pkt);
1544
            }
1545

    
1546
            if (timecode != AV_NOPTS_VALUE)
1547
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1548
            data += lace_size[n];
1549
        }
1550
    }
1551

    
1552
    av_free(lace_size);
1553
    return res;
1554
}
1555

    
1556
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1557
{
1558
    MatroskaCluster cluster = { 0 };
1559
    EbmlList *blocks_list;
1560
    MatroskaBlock *blocks;
1561
    int i, res;
1562
    if (matroska->has_cluster_id){
1563
        /* For the first cluster we parse, it's ID was already read as
1564
           part of matroska_read_header(), so don't read it again */
1565
        res = ebml_parse_id(matroska, matroska_clusters,
1566
                            MATROSKA_ID_CLUSTER, &cluster);
1567
        matroska->has_cluster_id = 0;
1568
    } else
1569
        res = ebml_parse(matroska, matroska_clusters, &cluster);
1570
    blocks_list = &cluster.blocks;
1571
    blocks = blocks_list->elem;
1572
    for (i=0; !res && i<blocks_list->nb_elem; i++)
1573
        if (blocks[i].bin.size > 0)
1574
            res=matroska_parse_block(matroska,
1575
                                     blocks[i].bin.data, blocks[i].bin.size,
1576
                                     blocks[i].bin.pos,  cluster.timecode,
1577
                                     blocks[i].duration, !blocks[i].reference);
1578
    ebml_free(matroska_cluster, &cluster);
1579
    return res;
1580
}
1581

    
1582
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1583
{
1584
    MatroskaDemuxContext *matroska = s->priv_data;
1585

    
1586
    while (matroska_deliver_packet(matroska, pkt)) {
1587
        if (matroska->done)
1588
            return AVERROR(EIO);
1589
        if (matroska_parse_cluster(matroska) < 0)
1590
            matroska->done = 1;
1591
    }
1592

    
1593
    return 0;
1594
}
1595

    
1596
static int matroska_read_seek(AVFormatContext *s, int stream_index,
1597
                              int64_t timestamp, int flags)
1598
{
1599
    MatroskaDemuxContext *matroska = s->priv_data;
1600
    AVStream *st = s->streams[stream_index];
1601
    int index;
1602

    
1603
    index = av_index_search_timestamp(st, timestamp, flags);
1604
    if (index < 0)
1605
        return 0;
1606

    
1607
    matroska_clear_queue(matroska);
1608

    
1609
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1610
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1611
    matroska->skip_to_stream = st;
1612
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1613
    return 0;
1614
}
1615

    
1616
static int matroska_read_close(AVFormatContext *s)
1617
{
1618
    MatroskaDemuxContext *matroska = s->priv_data;
1619
    MatroskaTrack *tracks = matroska->tracks.elem;
1620
    int n;
1621

    
1622
    matroska_clear_queue(matroska);
1623

    
1624
    for (n=0; n < matroska->tracks.nb_elem; n++)
1625
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1626
            av_free(tracks[n].audio.buf);
1627
    ebml_free(matroska_segment, matroska);
1628

    
1629
    return 0;
1630
}
1631

    
1632
AVInputFormat matroska_demuxer = {
1633
    "matroska",
1634
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1635
    sizeof(MatroskaDemuxContext),
1636
    matroska_probe,
1637
    matroska_read_header,
1638
    matroska_read_packet,
1639
    matroska_read_close,
1640
    matroska_read_seek,
1641
};