Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ f14a201b

History | View | Annotate | Download (60.5 KB)

1 b061d892 David Conrad
/*
2 ff33c5c5 Aurelien Jacobs
 * Matroska file demuxer
3 5968d2dd Diego Biurrun
 * Copyright (c) 2003-2008 The FFmpeg Project
4 b061d892 David Conrad
 *
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 6de4aece Reimar Döffinger
 * @file matroskadec.c
24 b061d892 David Conrad
 * Matroska file demuxer
25
 * by Ronald Bultje <rbultje@ronald.bitfreak.net>
26
 * with a little help from Moritz Bunkus <moritz@bunkus.org>
27 ff33c5c5 Aurelien Jacobs
 * totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28 5968d2dd Diego Biurrun
 * Specs available on the Matroska project page: http://www.matroska.org/.
29 b061d892 David Conrad
 */
30
31 3eb9bfbb Aurelien Jacobs
#include <stdio.h>
32 b061d892 David Conrad
#include "avformat.h"
33
/* For codec_get_id(). */
34
#include "riff.h"
35 f009e36f Aurelien Jacobs
#include "isom.h"
36 b061d892 David Conrad
#include "matroska.h"
37 7bfacd4e Aurelien Jacobs
#include "libavcodec/mpeg4audio.h"
38 245976da Diego Biurrun
#include "libavutil/intfloat_readwrite.h"
39 5f8e0227 Aurelien Jacobs
#include "libavutil/avstring.h"
40 de3230fb Aurelien Jacobs
#include "libavutil/lzo.h"
41 fbb878ce Aurelien Jacobs
#ifdef CONFIG_ZLIB
42
#include <zlib.h>
43
#endif
44 54dddf09 Aurelien Jacobs
#ifdef CONFIG_BZLIB
45
#include <bzlib.h>
46
#endif
47 b061d892 David Conrad
48 789ed100 Aurelien Jacobs
typedef enum {
49
    EBML_NONE,
50
    EBML_UINT,
51
    EBML_FLOAT,
52
    EBML_STR,
53
    EBML_UTF8,
54
    EBML_BIN,
55
    EBML_NEST,
56
    EBML_PASS,
57
    EBML_STOP,
58
} EbmlType;
59
60
typedef const struct EbmlSyntax {
61
    uint32_t id;
62
    EbmlType type;
63
    int list_elem_size;
64
    int data_offset;
65
    union {
66
        uint64_t    u;
67
        double      f;
68
        const char *s;
69
        const struct EbmlSyntax *n;
70
    } def;
71
} EbmlSyntax;
72
73
typedef struct {
74
    int nb_elem;
75
    void *elem;
76
} EbmlList;
77
78
typedef struct {
79
    int      size;
80
    uint8_t *data;
81
    int64_t  pos;
82
} EbmlBin;
83
84 63511324 Aurelien Jacobs
typedef struct {
85
    uint64_t version;
86
    uint64_t max_size;
87
    uint64_t id_length;
88
    char    *doctype;
89
    uint64_t doctype_version;
90
} Ebml;
91
92 2cbc8811 Aurelien Jacobs
typedef struct {
93
    uint64_t algo;
94
    EbmlBin  settings;
95
} MatroskaTrackCompression;
96 b061d892 David Conrad
97 2cbc8811 Aurelien Jacobs
typedef struct {
98
    uint64_t scope;
99
    uint64_t type;
100
    MatroskaTrackCompression compression;
101
} MatroskaTrackEncoding;
102 b061d892 David Conrad
103 2cbc8811 Aurelien Jacobs
typedef struct {
104
    double   frame_rate;
105
    uint64_t display_width;
106
    uint64_t display_height;
107
    uint64_t pixel_width;
108
    uint64_t pixel_height;
109
    uint64_t fourcc;
110
} MatroskaTrackVideo;
111 b061d892 David Conrad
112 2cbc8811 Aurelien Jacobs
typedef struct {
113
    double   samplerate;
114
    double   out_samplerate;
115
    uint64_t bitdepth;
116
    uint64_t channels;
117
118
    /* real audio header (extracted from extradata) */
119
    int      coded_framesize;
120
    int      sub_packet_h;
121
    int      frame_size;
122
    int      sub_packet_size;
123
    int      sub_packet_cnt;
124
    int      pkt_cnt;
125
    uint8_t *buf;
126
} MatroskaTrackAudio;
127 b061d892 David Conrad
128 2cbc8811 Aurelien Jacobs
typedef struct {
129
    uint64_t num;
130
    uint64_t type;
131
    char    *codec_id;
132
    EbmlBin  codec_priv;
133
    char    *language;
134 7ff97085 Anton Khirnov
    double time_scale;
135 b061d892 David Conrad
    uint64_t default_duration;
136 4eff9743 Aurelien Jacobs
    uint64_t flag_default;
137 2cbc8811 Aurelien Jacobs
    MatroskaTrackVideo video;
138
    MatroskaTrackAudio audio;
139
    EbmlList encodings;
140 fc4d335f Aurelien Jacobs
141
    AVStream *stream;
142 b061d892 David Conrad
} MatroskaTrack;
143
144 e5929fdf Aurelien Jacobs
typedef struct {
145 b414cb89 Aurelien Jacobs
    char *filename;
146
    char *mime;
147
    EbmlBin bin;
148
} MatroskaAttachement;
149
150
typedef struct {
151 6bbd7c7b Aurelien Jacobs
    uint64_t start;
152
    uint64_t end;
153
    uint64_t uid;
154
    char    *title;
155
} MatroskaChapter;
156
157
typedef struct {
158 e5929fdf Aurelien Jacobs
    uint64_t track;
159
    uint64_t pos;
160
} MatroskaIndexPos;
161
162
typedef struct {
163
    uint64_t time;
164
    EbmlList pos;
165
} MatroskaIndex;
166
167 13b350a3 Aurelien Jacobs
typedef struct {
168 44015c56 Aurelien Jacobs
    char *name;
169
    char *string;
170
    EbmlList sub;
171
} MatroskaTag;
172
173
typedef struct {
174 13b350a3 Aurelien Jacobs
    uint64_t id;
175
    uint64_t pos;
176
} MatroskaSeekhead;
177
178 c171af9b Aurelien Jacobs
typedef struct {
179 8d75b5a2 Aurelien Jacobs
    uint64_t start;
180
    uint64_t length;
181 b061d892 David Conrad
} MatroskaLevel;
182
183 c171af9b Aurelien Jacobs
typedef struct {
184 b061d892 David Conrad
    AVFormatContext *ctx;
185
186 5968d2dd Diego Biurrun
    /* EBML stuff */
187 b061d892 David Conrad
    int num_levels;
188
    MatroskaLevel levels[EBML_MAX_DEPTH];
189
    int level_up;
190
191 29708581 Aurelien Jacobs
    uint64_t time_scale;
192
    double   duration;
193
    char    *title;
194 2cbc8811 Aurelien Jacobs
    EbmlList tracks;
195 b414cb89 Aurelien Jacobs
    EbmlList attachments;
196 6bbd7c7b Aurelien Jacobs
    EbmlList chapters;
197 e5929fdf Aurelien Jacobs
    EbmlList index;
198 44015c56 Aurelien Jacobs
    EbmlList tags;
199 13b350a3 Aurelien Jacobs
    EbmlList seekhead;
200 b061d892 David Conrad
201
    /* byte position of the segment inside the stream */
202
    offset_t segment_start;
203
204 5968d2dd Diego Biurrun
    /* the packet queue */
205 b061d892 David Conrad
    AVPacket **packets;
206
    int num_packets;
207
208 8d75b5a2 Aurelien Jacobs
    int done;
209 ce6f28bd Aurelien Jacobs
    int has_cluster_id;
210 b061d892 David Conrad
211
    /* What to skip before effectively reading a packet. */
212
    int skip_to_keyframe;
213
    AVStream *skip_to_stream;
214
} MatroskaDemuxContext;
215
216 209472b4 Aurelien Jacobs
typedef struct {
217
    uint64_t duration;
218
    int64_t  reference;
219
    EbmlBin  bin;
220
} MatroskaBlock;
221
222
typedef struct {
223
    uint64_t timecode;
224
    EbmlList blocks;
225
} MatroskaCluster;
226
227 4b3dc529 Aurelien Jacobs
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
228
229 63511324 Aurelien Jacobs
static EbmlSyntax ebml_header[] = {
230
    { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
231
    { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
232
    { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
233
    { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
234
    { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
235
    { EBML_ID_EBMLVERSION,            EBML_NONE },
236
    { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
237
    { 0 }
238
};
239
240
static EbmlSyntax ebml_syntax[] = {
241
    { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
242
    { 0 }
243
};
244
245 29708581 Aurelien Jacobs
static EbmlSyntax matroska_info[] = {
246
    { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
247
    { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
248
    { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
249
    { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
250
    { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
251
    { MATROSKA_ID_DATEUTC,            EBML_NONE },
252
    { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
253
    { 0 }
254
};
255
256 2cbc8811 Aurelien Jacobs
static EbmlSyntax matroska_track_video[] = {
257
    { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
258
    { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
259
    { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
260
    { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
261
    { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
262
    { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
263 5df3cc6f Aurelien Jacobs
    { MATROSKA_ID_VIDEOPIXELCROPB,    EBML_NONE },
264
    { MATROSKA_ID_VIDEOPIXELCROPT,    EBML_NONE },
265
    { MATROSKA_ID_VIDEOPIXELCROPL,    EBML_NONE },
266
    { MATROSKA_ID_VIDEOPIXELCROPR,    EBML_NONE },
267
    { MATROSKA_ID_VIDEODISPLAYUNIT,   EBML_NONE },
268 2cbc8811 Aurelien Jacobs
    { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
269
    { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
270
    { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
271
    { 0 }
272
};
273
274
static EbmlSyntax matroska_track_audio[] = {
275
    { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
276
    { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
277
    { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
278
    { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
279
    { 0 }
280
};
281
282
static EbmlSyntax matroska_track_encoding_compression[] = {
283
    { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
284
    { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
285
    { 0 }
286
};
287
288
static EbmlSyntax matroska_track_encoding[] = {
289
    { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
290
    { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
291
    { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
292 5df3cc6f Aurelien Jacobs
    { MATROSKA_ID_ENCODINGORDER,      EBML_NONE },
293 2cbc8811 Aurelien Jacobs
    { 0 }
294
};
295
296
static EbmlSyntax matroska_track_encodings[] = {
297
    { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
298
    { 0 }
299
};
300
301
static EbmlSyntax matroska_track[] = {
302
    { MATROSKA_ID_TRACKNUMBER,          EBML_UINT, 0, offsetof(MatroskaTrack,num) },
303
    { MATROSKA_ID_TRACKTYPE,            EBML_UINT, 0, offsetof(MatroskaTrack,type) },
304
    { MATROSKA_ID_CODECID,              EBML_STR,  0, offsetof(MatroskaTrack,codec_id) },
305
    { MATROSKA_ID_CODECPRIVATE,         EBML_BIN,  0, offsetof(MatroskaTrack,codec_priv) },
306
    { MATROSKA_ID_TRACKLANGUAGE,        EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
307
    { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
308
    { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
309
    { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
310
    { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
311
    { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
312
    { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
313
    { MATROSKA_ID_TRACKUID,             EBML_NONE },
314
    { MATROSKA_ID_TRACKNAME,            EBML_NONE },
315
    { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
316
    { MATROSKA_ID_TRACKFLAGFORCED,      EBML_NONE },
317
    { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
318
    { MATROSKA_ID_CODECNAME,            EBML_NONE },
319
    { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
320
    { MATROSKA_ID_CODECINFOURL,         EBML_NONE },
321
    { MATROSKA_ID_CODECDOWNLOADURL,     EBML_NONE },
322
    { MATROSKA_ID_TRACKMINCACHE,        EBML_NONE },
323
    { MATROSKA_ID_TRACKMAXCACHE,        EBML_NONE },
324 5df3cc6f Aurelien Jacobs
    { MATROSKA_ID_TRACKMAXBLKADDID,     EBML_NONE },
325 2cbc8811 Aurelien Jacobs
    { 0 }
326
};
327
328
static EbmlSyntax matroska_tracks[] = {
329
    { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
330
    { 0 }
331
};
332
333 b414cb89 Aurelien Jacobs
static EbmlSyntax matroska_attachment[] = {
334
    { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
335
    { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
336
    { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
337 5df3cc6f Aurelien Jacobs
    { MATROSKA_ID_FILEDESC,           EBML_NONE },
338 b414cb89 Aurelien Jacobs
    { MATROSKA_ID_FILEUID,            EBML_NONE },
339
    { 0 }
340
};
341
342
static EbmlSyntax matroska_attachments[] = {
343
    { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
344
    { 0 }
345
};
346
347 6bbd7c7b Aurelien Jacobs
static EbmlSyntax matroska_chapter_display[] = {
348
    { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
349 5df3cc6f Aurelien Jacobs
    { MATROSKA_ID_CHAPLANG,           EBML_NONE },
350 6bbd7c7b Aurelien Jacobs
    { 0 }
351
};
352
353
static EbmlSyntax matroska_chapter_entry[] = {
354
    { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
355
    { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
356
    { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
357
    { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
358
    { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
359 5df3cc6f Aurelien Jacobs
    { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
360
    { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
361
    { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
362 6bbd7c7b Aurelien Jacobs
    { 0 }
363
};
364
365
static EbmlSyntax matroska_chapter[] = {
366
    { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
367
    { MATROSKA_ID_EDITIONUID,         EBML_NONE },
368
    { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
369
    { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
370 5df3cc6f Aurelien Jacobs
    { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
371 6bbd7c7b Aurelien Jacobs
    { 0 }
372
};
373
374
static EbmlSyntax matroska_chapters[] = {
375
    { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
376
    { 0 }
377
};
378
379 e5929fdf Aurelien Jacobs
static EbmlSyntax matroska_index_pos[] = {
380
    { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
381
    { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
382 5df3cc6f Aurelien Jacobs
    { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
383 e5929fdf Aurelien Jacobs
    { 0 }
384
};
385
386
static EbmlSyntax matroska_index_entry[] = {
387
    { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
388
    { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
389
    { 0 }
390
};
391
392
static EbmlSyntax matroska_index[] = {
393
    { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
394
    { 0 }
395
};
396
397 44015c56 Aurelien Jacobs
static EbmlSyntax matroska_simpletag[] = {
398
    { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
399
    { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
400
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
401
    { MATROSKA_ID_TAGLANG,            EBML_NONE },
402
    { MATROSKA_ID_TAGDEFAULT,         EBML_NONE },
403
    { 0 }
404
};
405
406
static EbmlSyntax matroska_tag[] = {
407
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), 0, {.n=matroska_simpletag} },
408
    { MATROSKA_ID_TAGTARGETS,         EBML_NONE },
409
    { 0 }
410
};
411
412 434d496a Aurelien Jacobs
static EbmlSyntax matroska_tags[] = {
413 44015c56 Aurelien Jacobs
    { MATROSKA_ID_TAG,                EBML_NEST, 0, offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
414 434d496a Aurelien Jacobs
    { 0 }
415
};
416
417 13b350a3 Aurelien Jacobs
static EbmlSyntax matroska_seekhead_entry[] = {
418
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
419
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
420
    { 0 }
421
};
422
423
static EbmlSyntax matroska_seekhead[] = {
424
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
425
    { 0 }
426
};
427
428 ce6f28bd Aurelien Jacobs
static EbmlSyntax matroska_segment[] = {
429
    { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
430
    { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
431
    { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
432
    { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
433
    { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
434
    { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
435
    { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
436
    { MATROSKA_ID_CLUSTER,        EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
437
    { 0 }
438
};
439
440
static EbmlSyntax matroska_segments[] = {
441
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
442
    { 0 }
443
};
444
445 209472b4 Aurelien Jacobs
static EbmlSyntax matroska_blockgroup[] = {
446
    { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
447
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
448
    { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
449
    { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
450
    { 0 }
451
};
452
453
static EbmlSyntax matroska_cluster[] = {
454
    { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
455
    { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
456
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
457 5df3cc6f Aurelien Jacobs
    { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
458
    { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
459 209472b4 Aurelien Jacobs
    { 0 }
460
};
461
462
static EbmlSyntax matroska_clusters[] = {
463
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
464 5df3cc6f Aurelien Jacobs
    { MATROSKA_ID_INFO,           EBML_NONE },
465
    { MATROSKA_ID_CUES,           EBML_NONE },
466
    { MATROSKA_ID_TAGS,           EBML_NONE },
467
    { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
468 209472b4 Aurelien Jacobs
    { 0 }
469
};
470
471 44015c56 Aurelien Jacobs
#define SIZE_OFF(x) sizeof(((AVFormatContext*)0)->x),offsetof(AVFormatContext,x)
472
const struct {
473
    const char name[16];
474
    int   size;
475
    int   offset;
476
} metadata[] = {
477
    { "TITLE",           SIZE_OFF(title)      },
478
    { "ARTIST",          SIZE_OFF(author)     },
479
    { "WRITTEN_BY",      SIZE_OFF(author)     },
480
    { "LEAD_PERFORMER",  SIZE_OFF(author)     },
481
    { "COPYRIGHT",       SIZE_OFF(copyright)  },
482
    { "COMMENT",         SIZE_OFF(comment)    },
483
    { "ALBUM",           SIZE_OFF(album)      },
484
    { "DATE_WRITTEN",    SIZE_OFF(year)       },
485
    { "DATE_RELEASED",   SIZE_OFF(year)       },
486
    { "PART_NUMBER",     SIZE_OFF(track)      },
487
    { "GENRE",           SIZE_OFF(genre)      },
488
};
489
490 b061d892 David Conrad
/*
491 5968d2dd Diego Biurrun
 * Return: Whether we reached the end of a level in the hierarchy or not.
492 b061d892 David Conrad
 */
493 592110c2 Aurelien Jacobs
static int ebml_level_end(MatroskaDemuxContext *matroska)
494 b061d892 David Conrad
{
495 899681cd Björn Axelsson
    ByteIOContext *pb = matroska->ctx->pb;
496 b061d892 David Conrad
    offset_t pos = url_ftell(pb);
497
498 592110c2 Aurelien Jacobs
    if (matroska->num_levels > 0) {
499 b061d892 David Conrad
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
500 592110c2 Aurelien Jacobs
        if (pos - level->start >= level->length) {
501 b061d892 David Conrad
            matroska->num_levels--;
502 592110c2 Aurelien Jacobs
            return 1;
503 b061d892 David Conrad
        }
504
    }
505 592110c2 Aurelien Jacobs
    return 0;
506 b061d892 David Conrad
}
507
508
/*
509
 * Read: an "EBML number", which is defined as a variable-length
510
 * array of bytes. The first byte indicates the length by giving a
511
 * number of 0-bits followed by a one. The position of the first
512
 * "one" bit inside the first byte indicates the length of this
513
 * number.
514 5968d2dd Diego Biurrun
 * Returns: number of bytes read, < 0 on error
515 b061d892 David Conrad
 */
516 c1e01133 Aurelien Jacobs
static int ebml_read_num(MatroskaDemuxContext *matroska, ByteIOContext *pb,
517 f7b9687c Aurelien Jacobs
                         int max_size, uint64_t *number)
518 b061d892 David Conrad
{
519
    int len_mask = 0x80, read = 1, n = 1;
520
    int64_t total = 0;
521
522 5968d2dd Diego Biurrun
    /* The first byte tells us the length in bytes - get_byte() can normally
523 b061d892 David Conrad
     * return 0, but since that's not a valid first ebmlID byte, we can
524
     * use it safely here to catch EOS. */
525
    if (!(total = get_byte(pb))) {
526
        /* we might encounter EOS here */
527
        if (!url_feof(pb)) {
528
            offset_t pos = url_ftell(pb);
529
            av_log(matroska->ctx, AV_LOG_ERROR,
530
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
531
                   pos, pos);
532
        }
533 6f3e0b21 Panagiotis Issaris
        return AVERROR(EIO); /* EOS or actual I/O error */
534 b061d892 David Conrad
    }
535
536
    /* get the length of the EBML number */
537
    while (read <= max_size && !(total & len_mask)) {
538
        read++;
539
        len_mask >>= 1;
540
    }
541
    if (read > max_size) {
542
        offset_t pos = url_ftell(pb) - 1;
543
        av_log(matroska->ctx, AV_LOG_ERROR,
544
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
545
               (uint8_t) total, pos, pos);
546
        return AVERROR_INVALIDDATA;
547
    }
548
549
    /* read out length */
550
    total &= ~len_mask;
551
    while (n++ < read)
552
        total = (total << 8) | get_byte(pb);
553
554
    *number = total;
555
556
    return read;
557
}
558
559
/*
560
 * Read the next element as an unsigned int.
561
 * 0 is success, < 0 is failure.
562
 */
563 f7b9687c Aurelien Jacobs
static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
564 b061d892 David Conrad
{
565 c6cd2b3d Aurelien Jacobs
    int n = 0;
566 b061d892 David Conrad
567 ba5a1f99 Aurelien Jacobs
    if (size < 1 || size > 8)
568 b061d892 David Conrad
        return AVERROR_INVALIDDATA;
569
570 5968d2dd Diego Biurrun
    /* big-endian ordering; build up number */
571 b061d892 David Conrad
    *num = 0;
572
    while (n++ < size)
573
        *num = (*num << 8) | get_byte(pb);
574
575
    return 0;
576
}
577
578
/*
579
 * Read the next element as a float.
580
 * 0 is success, < 0 is failure.
581
 */
582 f7b9687c Aurelien Jacobs
static int ebml_read_float(ByteIOContext *pb, int size, double *num)
583 b061d892 David Conrad
{
584
    if (size == 4) {
585
        *num= av_int2flt(get_be32(pb));
586
    } else if(size==8){
587
        *num= av_int2dbl(get_be64(pb));
588 ba5a1f99 Aurelien Jacobs
    } else
589 b061d892 David Conrad
        return AVERROR_INVALIDDATA;
590
591
    return 0;
592
}
593
594
/*
595
 * Read the next element as an ASCII string.
596
 * 0 is success, < 0 is failure.
597
 */
598 f7b9687c Aurelien Jacobs
static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
599 b061d892 David Conrad
{
600 c6cd2b3d Aurelien Jacobs
    av_free(*str);
601 5968d2dd Diego Biurrun
    /* EBML strings are usually not 0-terminated, so we allocate one
602 b061d892 David Conrad
     * byte more, read the string and NULL-terminate it ourselves. */
603 c6cd2b3d Aurelien Jacobs
    if (!(*str = av_malloc(size + 1)))
604 769e10f0 Panagiotis Issaris
        return AVERROR(ENOMEM);
605 b061d892 David Conrad
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
606 ff2c222c Aurelien Jacobs
        av_free(*str);
607 6f3e0b21 Panagiotis Issaris
        return AVERROR(EIO);
608 b061d892 David Conrad
    }
609
    (*str)[size] = '\0';
610
611
    return 0;
612
}
613
614
/*
615 737c40da Aurelien Jacobs
 * Read the next element as binary data.
616
 * 0 is success, < 0 is failure.
617
 */
618
static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
619
{
620
    av_free(bin->data);
621
    if (!(bin->data = av_malloc(length)))
622
        return AVERROR(ENOMEM);
623
624
    bin->size = length;
625
    bin->pos  = url_ftell(pb);
626
    if (get_buffer(pb, bin->data, length) != length)
627
        return AVERROR(EIO);
628
629
    return 0;
630
}
631
632
/*
633 b061d892 David Conrad
 * Read the next element, but only the header. The contents
634
 * are supposed to be sub-elements which can be read separately.
635
 * 0 is success, < 0 is failure.
636
 */
637 f7b9687c Aurelien Jacobs
static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
638 b061d892 David Conrad
{
639 899681cd Björn Axelsson
    ByteIOContext *pb = matroska->ctx->pb;
640 b061d892 David Conrad
    MatroskaLevel *level;
641
642
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
643
        av_log(matroska->ctx, AV_LOG_ERROR,
644
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
645 85565db0 Panagiotis Issaris
        return AVERROR(ENOSYS);
646 b061d892 David Conrad
    }
647
648
    level = &matroska->levels[matroska->num_levels++];
649
    level->start = url_ftell(pb);
650
    level->length = length;
651
652
    return 0;
653
}
654
655
/*
656
 * Read signed/unsigned "EBML" numbers.
657 5968d2dd Diego Biurrun
 * Return: number of bytes processed, < 0 on error
658 b061d892 David Conrad
 */
659 c1e01133 Aurelien Jacobs
static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
660
                                 uint8_t *data, uint32_t size, uint64_t *num)
661 b061d892 David Conrad
{
662 c1e01133 Aurelien Jacobs
    ByteIOContext pb;
663
    init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
664
    return ebml_read_num(matroska, &pb, 8, num);
665 b061d892 David Conrad
}
666
667
/*
668
 * Same as above, but signed.
669
 */
670 c1e01133 Aurelien Jacobs
static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
671
                                 uint8_t *data, uint32_t size, int64_t *num)
672 b061d892 David Conrad
{
673
    uint64_t unum;
674
    int res;
675
676
    /* read as unsigned number first */
677 c1e01133 Aurelien Jacobs
    if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
678 b061d892 David Conrad
        return res;
679
680
    /* make signed (weird way) */
681 33ac07ea Aurelien Jacobs
    *num = unum - ((1LL << (7*res - 1)) - 1);
682 b061d892 David Conrad
683
    return res;
684
}
685
686 737c40da Aurelien Jacobs
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
687
                           EbmlSyntax *syntax, void *data);
688 b061d892 David Conrad
689 737c40da Aurelien Jacobs
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
690
                         uint32_t id, void *data)
691 b061d892 David Conrad
{
692
    int i;
693 737c40da Aurelien Jacobs
    for (i=0; syntax[i].id; i++)
694
        if (id == syntax[i].id)
695
            break;
696 b49d17b7 Aurelien Jacobs
    if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
697 737c40da Aurelien Jacobs
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
698
    return ebml_parse_elem(matroska, &syntax[i], data);
699 b061d892 David Conrad
}
700
701 737c40da Aurelien Jacobs
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
702
                      void *data)
703 b061d892 David Conrad
{
704 88cca989 Aurelien Jacobs
    uint64_t id;
705
    int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
706
    id |= 1 << 7*res;
707 737c40da Aurelien Jacobs
    return res < 0 ? res : ebml_parse_id(matroska, syntax, id, data);
708 b061d892 David Conrad
}
709
710 737c40da Aurelien Jacobs
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
711
                           void *data)
712 b061d892 David Conrad
{
713 737c40da Aurelien Jacobs
    int i, res = 0;
714 b061d892 David Conrad
715 737c40da Aurelien Jacobs
    for (i=0; syntax[i].id; i++)
716
        switch (syntax[i].type) {
717
        case EBML_UINT:
718
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
719
            break;
720
        case EBML_FLOAT:
721
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
722
            break;
723
        case EBML_STR:
724
        case EBML_UTF8:
725
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
726
            break;
727 34c9c1ba Aurelien Jacobs
        }
728 b061d892 David Conrad
729 737c40da Aurelien Jacobs
    while (!res && !ebml_level_end(matroska))
730
        res = ebml_parse(matroska, syntax, data);
731 b061d892 David Conrad
732 737c40da Aurelien Jacobs
    return res;
733 b061d892 David Conrad
}
734
735 789ed100 Aurelien Jacobs
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
736
                           EbmlSyntax *syntax, void *data)
737
{
738 c6cd2b3d Aurelien Jacobs
    ByteIOContext *pb = matroska->ctx->pb;
739 789ed100 Aurelien Jacobs
    uint32_t id = syntax->id;
740 c6cd2b3d Aurelien Jacobs
    uint64_t length;
741 789ed100 Aurelien Jacobs
    int res;
742
743
    data = (char *)data + syntax->data_offset;
744
    if (syntax->list_elem_size) {
745
        EbmlList *list = data;
746
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
747
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
748
        memset(data, 0, syntax->list_elem_size);
749
        list->nb_elem++;
750
    }
751
752 c6cd2b3d Aurelien Jacobs
    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
753 c1e01133 Aurelien Jacobs
        if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
754 c6cd2b3d Aurelien Jacobs
            return res;
755
756 789ed100 Aurelien Jacobs
    switch (syntax->type) {
757 c6cd2b3d Aurelien Jacobs
    case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
758
    case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
759 789ed100 Aurelien Jacobs
    case EBML_STR:
760 c6cd2b3d Aurelien Jacobs
    case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
761 eb05cacc Aurelien Jacobs
    case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
762 c6cd2b3d Aurelien Jacobs
    case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
763 789ed100 Aurelien Jacobs
                         return res;
764
                     if (id == MATROSKA_ID_SEGMENT)
765
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
766 6314cca0 Aurelien Jacobs
                     return ebml_parse_nest(matroska, syntax->def.n, data);
767 c4d3d9ba Aurelien Jacobs
    case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
768 789ed100 Aurelien Jacobs
    case EBML_STOP:  *(int *)data = 1;      return 1;
769 dc3e0211 Aurelien Jacobs
    default:         return url_fseek(pb,length,SEEK_CUR)<0 ? AVERROR(EIO) : 0;
770 789ed100 Aurelien Jacobs
    }
771 ba5a1f99 Aurelien Jacobs
    if (res == AVERROR_INVALIDDATA)
772
        av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
773
    else if (res == AVERROR(EIO))
774
        av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
775
    return res;
776 789ed100 Aurelien Jacobs
}
777
778
static void ebml_free(EbmlSyntax *syntax, void *data)
779
{
780
    int i, j;
781
    for (i=0; syntax[i].id; i++) {
782
        void *data_off = (char *)data + syntax[i].data_offset;
783
        switch (syntax[i].type) {
784
        case EBML_STR:
785
        case EBML_UTF8:  av_freep(data_off);                      break;
786
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
787
        case EBML_NEST:
788
            if (syntax[i].list_elem_size) {
789
                EbmlList *list = data_off;
790
                char *ptr = list->elem;
791
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
792
                    ebml_free(syntax[i].def.n, ptr);
793
                av_free(list->elem);
794
            } else
795
                ebml_free(syntax[i].def.n, data_off);
796
        default:  break;
797
        }
798
    }
799
}
800
801 737c40da Aurelien Jacobs
802
/*
803
 * Autodetecting...
804
 */
805
static int matroska_probe(AVProbeData *p)
806
{
807
    uint64_t total = 0;
808
    int len_mask = 0x80, size = 1, n = 1;
809 7b571fd7 Reimar Döffinger
    static const char probe_data[] = "matroska";
810 737c40da Aurelien Jacobs
811 5968d2dd Diego Biurrun
    /* EBML header? */
812 737c40da Aurelien Jacobs
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
813
        return 0;
814
815
    /* length of header */
816
    total = p->buf[4];
817
    while (size <= 8 && !(total & len_mask)) {
818
        size++;
819
        len_mask >>= 1;
820
    }
821
    if (size > 8)
822
      return 0;
823
    total &= (len_mask - 1);
824
    while (n < size)
825
        total = (total << 8) | p->buf[4 + n++];
826
827 5968d2dd Diego Biurrun
    /* Does the probe data contain the whole header? */
828 737c40da Aurelien Jacobs
    if (p->buf_size < 4 + size + total)
829
      return 0;
830
831 5968d2dd Diego Biurrun
    /* The header must contain the document type 'matroska'. For now,
832 737c40da Aurelien Jacobs
     * we don't parse the whole header but simply check for the
833
     * availability of that array of characters inside the header.
834
     * Not fully fool-proof, but good enough. */
835
    for (n = 4+size; n <= 4+size+total-(sizeof(probe_data)-1); n++)
836
        if (!memcmp(p->buf+n, probe_data, sizeof(probe_data)-1))
837
            return AVPROBE_SCORE_MAX;
838
839
    return 0;
840
}
841
842
static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
843
                                                 int num)
844
{
845
    MatroskaTrack *tracks = matroska->tracks.elem;
846
    int i;
847
848
    for (i=0; i < matroska->tracks.nb_elem; i++)
849
        if (tracks[i].num == num)
850
            return &tracks[i];
851
852
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
853
    return NULL;
854
}
855
856 f7b9687c Aurelien Jacobs
static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
857
                                  MatroskaTrack *track)
858 935ec5a1 Evgeniy Stepanov
{
859 2cbc8811 Aurelien Jacobs
    MatroskaTrackEncoding *encodings = track->encodings.elem;
860 935ec5a1 Evgeniy Stepanov
    uint8_t* data = *buf;
861
    int isize = *buf_size;
862
    uint8_t* pkt_data = NULL;
863
    int pkt_size = isize;
864
    int result = 0;
865
    int olen;
866
867 2cbc8811 Aurelien Jacobs
    switch (encodings[0].compression.algo) {
868 935ec5a1 Evgeniy Stepanov
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
869 2cbc8811 Aurelien Jacobs
        return encodings[0].compression.settings.size;
870 935ec5a1 Evgeniy Stepanov
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
871
        do {
872
            olen = pkt_size *= 3;
873
            pkt_data = av_realloc(pkt_data,
874
                                  pkt_size+LZO_OUTPUT_PADDING);
875
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
876
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
877
        if (result)
878
            goto failed;
879
        pkt_size -= olen;
880
        break;
881
#ifdef CONFIG_ZLIB
882
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
883
        z_stream zstream = {0};
884
        if (inflateInit(&zstream) != Z_OK)
885
            return -1;
886
        zstream.next_in = data;
887
        zstream.avail_in = isize;
888
        do {
889
            pkt_size *= 3;
890
            pkt_data = av_realloc(pkt_data, pkt_size);
891
            zstream.avail_out = pkt_size - zstream.total_out;
892
            zstream.next_out = pkt_data + zstream.total_out;
893
            result = inflate(&zstream, Z_NO_FLUSH);
894
        } while (result==Z_OK && pkt_size<10000000);
895
        pkt_size = zstream.total_out;
896
        inflateEnd(&zstream);
897
        if (result != Z_STREAM_END)
898
            goto failed;
899
        break;
900
    }
901
#endif
902
#ifdef CONFIG_BZLIB
903
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
904
        bz_stream bzstream = {0};
905
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
906
            return -1;
907
        bzstream.next_in = data;
908
        bzstream.avail_in = isize;
909
        do {
910
            pkt_size *= 3;
911
            pkt_data = av_realloc(pkt_data, pkt_size);
912
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
913
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
914
            result = BZ2_bzDecompress(&bzstream);
915
        } while (result==BZ_OK && pkt_size<10000000);
916
        pkt_size = bzstream.total_out_lo32;
917
        BZ2_bzDecompressEnd(&bzstream);
918
        if (result != BZ_STREAM_END)
919
            goto failed;
920
        break;
921
    }
922
#endif
923 28f27e0c Aurelien Jacobs
    default:
924
        return -1;
925 935ec5a1 Evgeniy Stepanov
    }
926
927
    *buf = pkt_data;
928
    *buf_size = pkt_size;
929
    return 0;
930
 failed:
931
    av_free(pkt_data);
932
    return -1;
933
}
934
935 3eb9bfbb Aurelien Jacobs
static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
936
                                    AVPacket *pkt)
937
{
938
    char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
939
    for (; *ptr!=',' && ptr<end-1; ptr++);
940
    if (*ptr == ',')
941
        layer = ++ptr;
942
    for (; *ptr!=',' && ptr<end-1; ptr++);
943
    if (*ptr == ',') {
944
        int64_t end_pts = pkt->pts + pkt->convergence_duration;
945
        int sc = matroska->time_scale * pkt->pts / 10000000;
946
        int ec = matroska->time_scale * end_pts  / 10000000;
947
        int sh, sm, ss, eh, em, es, len;
948
        sh = sc/360000;  sc -= 360000*sh;
949
        sm = sc/  6000;  sc -=   6000*sm;
950
        ss = sc/   100;  sc -=    100*ss;
951
        eh = ec/360000;  ec -= 360000*eh;
952
        em = ec/  6000;  ec -=   6000*em;
953
        es = ec/   100;  ec -=    100*es;
954
        *ptr++ = '\0';
955
        len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
956
        if (!(line = av_malloc(len)))
957
            return;
958
        snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s",
959
                 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
960
        av_free(pkt->data);
961
        pkt->data = line;
962
        pkt->size = strlen(line);
963
    }
964
}
965
966 44015c56 Aurelien Jacobs
static void matroska_convert_tags(AVFormatContext *s, EbmlList *list)
967
{
968
    MatroskaTag *tags = list->elem;
969
    int i, j;
970
971
    for (i=0; i < list->nb_elem; i++) {
972
        for (j=0; j < ARRAY_SIZE(metadata); j++){
973
            if (!strcmp(tags[i].name, metadata[j].name)) {
974
                int *ptr = (int *)((char *)s + metadata[j].offset);
975
                if (*ptr)  continue;
976
                if (metadata[j].size > sizeof(int))
977
                    av_strlcpy((char *)ptr, tags[i].string, metadata[j].size);
978
                else
979
                    *ptr = atoi(tags[i].string);
980
            }
981
        }
982
        if (tags[i].sub.nb_elem)
983
            matroska_convert_tags(s, &tags[i].sub);
984
    }
985
}
986
987 f7b9687c Aurelien Jacobs
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
988 13b350a3 Aurelien Jacobs
{
989
    EbmlList *seekhead_list = &matroska->seekhead;
990
    MatroskaSeekhead *seekhead = seekhead_list->elem;
991
    uint32_t level_up = matroska->level_up;
992
    offset_t before_pos = url_ftell(matroska->ctx->pb);
993
    MatroskaLevel level;
994 f06a4886 Aurelien Jacobs
    int i;
995 b061d892 David Conrad
996 13b350a3 Aurelien Jacobs
    for (i=0; i<seekhead_list->nb_elem; i++) {
997 66cfc385 Aurelien Jacobs
        offset_t offset = seekhead[i].pos + matroska->segment_start;
998
999 13b350a3 Aurelien Jacobs
        if (seekhead[i].pos <= before_pos
1000
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1001
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1002
            continue;
1003 b061d892 David Conrad
1004 4348571b Aurelien Jacobs
        /* seek */
1005 66cfc385 Aurelien Jacobs
        if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
1006 4348571b Aurelien Jacobs
            continue;
1007
1008 5968d2dd Diego Biurrun
        /* We don't want to lose our seekhead level, so we add
1009 4348571b Aurelien Jacobs
         * a dummy. This is a crude hack. */
1010
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1011
            av_log(matroska->ctx, AV_LOG_INFO,
1012
                   "Max EBML element depth (%d) reached, "
1013
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1014
            break;
1015
        }
1016
1017
        level.start = 0;
1018
        level.length = (uint64_t)-1;
1019
        matroska->levels[matroska->num_levels] = level;
1020
        matroska->num_levels++;
1021
1022 66a37e06 Aurelien Jacobs
        ebml_parse(matroska, matroska_segment, matroska);
1023 4348571b Aurelien Jacobs
1024
        /* remove dummy level */
1025
        while (matroska->num_levels) {
1026
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1027
            if (length == (uint64_t)-1)
1028
                break;
1029
        }
1030 13b350a3 Aurelien Jacobs
    }
1031 b061d892 David Conrad
1032 4348571b Aurelien Jacobs
    /* seek back */
1033 66cfc385 Aurelien Jacobs
    url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
1034 4348571b Aurelien Jacobs
    matroska->level_up = level_up;
1035 b061d892 David Conrad
}
1036
1037 f7b9687c Aurelien Jacobs
static int matroska_aac_profile(char *codec_id)
1038 b061d892 David Conrad
{
1039 ba18b99f Aurelien Jacobs
    static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1040 b061d892 David Conrad
    int profile;
1041
1042
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1043
        if (strstr(codec_id, aac_profiles[profile]))
1044
            break;
1045
    return profile + 1;
1046
}
1047
1048 f7b9687c Aurelien Jacobs
static int matroska_aac_sri(int samplerate)
1049 b061d892 David Conrad
{
1050
    int sri;
1051
1052 7bfacd4e Aurelien Jacobs
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1053
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1054 b061d892 David Conrad
            break;
1055
    return sri;
1056
}
1057
1058 f7b9687c Aurelien Jacobs
static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1059 b061d892 David Conrad
{
1060
    MatroskaDemuxContext *matroska = s->priv_data;
1061 9c25bafa Aurelien Jacobs
    EbmlList *attachements_list = &matroska->attachments;
1062
    MatroskaAttachement *attachements;
1063
    EbmlList *chapters_list = &matroska->chapters;
1064
    MatroskaChapter *chapters;
1065 9a9a3b03 Aurelien Jacobs
    MatroskaTrack *tracks;
1066 e5929fdf Aurelien Jacobs
    EbmlList *index_list;
1067
    MatroskaIndex *index;
1068 63511324 Aurelien Jacobs
    Ebml ebml = { 0 };
1069 9a9a3b03 Aurelien Jacobs
    AVStream *st;
1070 ce6f28bd Aurelien Jacobs
    int i, j;
1071 b061d892 David Conrad
1072
    matroska->ctx = s;
1073
1074
    /* First read the EBML header. */
1075 c4d3d9ba Aurelien Jacobs
    if (ebml_parse(matroska, ebml_syntax, &ebml)
1076 63511324 Aurelien Jacobs
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1077
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1078
        || ebml.doctype_version > 2) {
1079 b061d892 David Conrad
        av_log(matroska->ctx, AV_LOG_ERROR,
1080 63511324 Aurelien Jacobs
               "EBML header using unsupported features\n"
1081
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1082
               ebml.version, ebml.doctype, ebml.doctype_version);
1083 b061d892 David Conrad
        return AVERROR_NOFMT;
1084
    }
1085 63511324 Aurelien Jacobs
    ebml_free(ebml_syntax, &ebml);
1086 b061d892 David Conrad
1087
    /* The next thing is a segment. */
1088 c4d3d9ba Aurelien Jacobs
    if (ebml_parse(matroska, matroska_segments, matroska) < 0)
1089 ce6f28bd Aurelien Jacobs
        return -1;
1090 13b350a3 Aurelien Jacobs
    matroska_execute_seekhead(matroska);
1091 b061d892 David Conrad
1092 9c25bafa Aurelien Jacobs
    if (matroska->duration)
1093
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1094
                                  * 1000 / AV_TIME_BASE;
1095
    if (matroska->title)
1096
        strncpy(matroska->ctx->title, matroska->title,
1097
                sizeof(matroska->ctx->title)-1);
1098 44015c56 Aurelien Jacobs
    matroska_convert_tags(s, &matroska->tags);
1099 9c25bafa Aurelien Jacobs
1100 d88d806b Aurelien Jacobs
    tracks = matroska->tracks.elem;
1101
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1102
        MatroskaTrack *track = &tracks[i];
1103
        enum CodecID codec_id = CODEC_ID_NONE;
1104 9c25bafa Aurelien Jacobs
        EbmlList *encodings_list = &tracks->encodings;
1105
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1106 d88d806b Aurelien Jacobs
        uint8_t *extradata = NULL;
1107
        int extradata_size = 0;
1108
        int extradata_offset = 0;
1109
1110
        /* Apply some sanity checks. */
1111 9c25bafa Aurelien Jacobs
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1112
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1113
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1114
            av_log(matroska->ctx, AV_LOG_INFO,
1115
                   "Unknown or unsupported track type %"PRIu64"\n",
1116
                   track->type);
1117
            continue;
1118
        }
1119 d88d806b Aurelien Jacobs
        if (track->codec_id == NULL)
1120
            continue;
1121
1122 9c25bafa Aurelien Jacobs
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1123
            if (!track->default_duration)
1124
                track->default_duration = 1000000000/track->video.frame_rate;
1125
            if (!track->video.display_width)
1126
                track->video.display_width = track->video.pixel_width;
1127
            if (!track->video.display_height)
1128
                track->video.display_height = track->video.pixel_height;
1129
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1130
            if (!track->audio.out_samplerate)
1131
                track->audio.out_samplerate = track->audio.samplerate;
1132
        }
1133
        if (encodings_list->nb_elem > 1) {
1134
            av_log(matroska->ctx, AV_LOG_ERROR,
1135
                   "Multiple combined encodings no supported");
1136
        } else if (encodings_list->nb_elem == 1) {
1137
            if (encodings[0].type ||
1138
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1139
#ifdef CONFIG_ZLIB
1140
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1141
#endif
1142
#ifdef CONFIG_BZLIB
1143
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1144
#endif
1145
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1146
                encodings[0].scope = 0;
1147
                av_log(matroska->ctx, AV_LOG_ERROR,
1148
                       "Unsupported encoding type");
1149
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1150
                uint8_t *codec_priv = track->codec_priv.data;
1151
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1152
                                                    &track->codec_priv.size,
1153
                                                    track);
1154
                if (offset < 0) {
1155
                    track->codec_priv.data = NULL;
1156
                    track->codec_priv.size = 0;
1157
                    av_log(matroska->ctx, AV_LOG_ERROR,
1158
                           "Failed to decode codec private data\n");
1159
                } else if (offset > 0) {
1160
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1161
                    memcpy(track->codec_priv.data,
1162
                           encodings[0].compression.settings.data, offset);
1163
                    memcpy(track->codec_priv.data+offset, codec_priv,
1164
                           track->codec_priv.size);
1165
                    track->codec_priv.size += offset;
1166
                }
1167
                if (codec_priv != track->codec_priv.data)
1168
                    av_free(codec_priv);
1169
            }
1170
        }
1171
1172 d88d806b Aurelien Jacobs
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1173
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1174
                        strlen(ff_mkv_codec_tags[j].str))){
1175
                codec_id= ff_mkv_codec_tags[j].id;
1176
                break;
1177 b061d892 David Conrad
            }
1178 d88d806b Aurelien Jacobs
        }
1179 b061d892 David Conrad
1180 cc70d14b Aurelien Jacobs
        st = track->stream = av_new_stream(s, 0);
1181 d88d806b Aurelien Jacobs
        if (st == NULL)
1182
            return AVERROR(ENOMEM);
1183
1184 cc8be506 Aurelien Jacobs
        if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1185 28ba69e0 Aurelien Jacobs
            && track->codec_priv.size >= 40
1186
            && track->codec_priv.data != NULL) {
1187 d88d806b Aurelien Jacobs
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1188
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1189 cc8be506 Aurelien Jacobs
        } else if (!strcmp(track->codec_id, "A_MS/ACM")
1190 28ba69e0 Aurelien Jacobs
                   && track->codec_priv.size >= 18
1191
                   && track->codec_priv.data != NULL) {
1192 d88d806b Aurelien Jacobs
            uint16_t tag = AV_RL16(track->codec_priv.data);
1193
            codec_id = codec_get_id(codec_wav_tags, tag);
1194 28ba69e0 Aurelien Jacobs
        } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1195
                   && (track->codec_priv.size >= 86)
1196
                   && (track->codec_priv.data != NULL)) {
1197 d88d806b Aurelien Jacobs
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1198
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1199 eb9cf50a Aurelien Jacobs
        } else if (codec_id == CODEC_ID_PCM_S16BE) {
1200
            switch (track->audio.bitdepth) {
1201
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1202
            case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
1203
            case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
1204
            }
1205
        } else if (codec_id == CODEC_ID_PCM_S16LE) {
1206
            switch (track->audio.bitdepth) {
1207
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1208
            case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
1209
            case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
1210
            }
1211
        } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1212
            codec_id = CODEC_ID_PCM_F64LE;
1213 28ba69e0 Aurelien Jacobs
        } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1214 d88d806b Aurelien Jacobs
            int profile = matroska_aac_profile(track->codec_id);
1215
            int sri = matroska_aac_sri(track->audio.samplerate);
1216
            extradata = av_malloc(5);
1217
            if (extradata == NULL)
1218
                return AVERROR(ENOMEM);
1219
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1220
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1221
            if (strstr(track->codec_id, "SBR")) {
1222
                sri = matroska_aac_sri(track->audio.out_samplerate);
1223
                extradata[2] = 0x56;
1224
                extradata[3] = 0xE5;
1225
                extradata[4] = 0x80 | (sri<<3);
1226
                extradata_size = 5;
1227 16f97ab0 Aurelien Jacobs
            } else
1228 d88d806b Aurelien Jacobs
                extradata_size = 2;
1229 28ba69e0 Aurelien Jacobs
        } else if (codec_id == CODEC_ID_TTA) {
1230 d88d806b Aurelien Jacobs
            ByteIOContext b;
1231
            extradata_size = 30;
1232
            extradata = av_mallocz(extradata_size);
1233
            if (extradata == NULL)
1234
                return AVERROR(ENOMEM);
1235
            init_put_byte(&b, extradata, extradata_size, 1,
1236
                          NULL, NULL, NULL, NULL);
1237
            put_buffer(&b, "TTA1", 4);
1238
            put_le16(&b, 1);
1239
            put_le16(&b, track->audio.channels);
1240
            put_le16(&b, track->audio.bitdepth);
1241
            put_le32(&b, track->audio.out_samplerate);
1242
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1243 28ba69e0 Aurelien Jacobs
        } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1244
                   codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1245 d88d806b Aurelien Jacobs
            extradata_offset = 26;
1246
            track->codec_priv.size -= extradata_offset;
1247 28ba69e0 Aurelien Jacobs
        } else if (codec_id == CODEC_ID_RA_144) {
1248 d88d806b Aurelien Jacobs
            track->audio.out_samplerate = 8000;
1249
            track->audio.channels = 1;
1250 28ba69e0 Aurelien Jacobs
        } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1251
                   codec_id == CODEC_ID_ATRAC3) {
1252 d88d806b Aurelien Jacobs
            ByteIOContext b;
1253
1254
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1255
                          0, NULL, NULL, NULL, NULL);
1256
            url_fskip(&b, 24);
1257
            track->audio.coded_framesize = get_be32(&b);
1258
            url_fskip(&b, 12);
1259
            track->audio.sub_packet_h    = get_be16(&b);
1260
            track->audio.frame_size      = get_be16(&b);
1261
            track->audio.sub_packet_size = get_be16(&b);
1262
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1263
            if (codec_id == CODEC_ID_RA_288) {
1264
                st->codec->block_align = track->audio.coded_framesize;
1265
                track->codec_priv.size = 0;
1266
            } else {
1267
                st->codec->block_align = track->audio.sub_packet_size;
1268
                extradata_offset = 78;
1269 2cbc8811 Aurelien Jacobs
                track->codec_priv.size -= extradata_offset;
1270 b061d892 David Conrad
            }
1271 d88d806b Aurelien Jacobs
        }
1272 b061d892 David Conrad
1273 16f97ab0 Aurelien Jacobs
        if (codec_id == CODEC_ID_NONE)
1274 d88d806b Aurelien Jacobs
            av_log(matroska->ctx, AV_LOG_INFO,
1275 8f35a2c0 Aurelien Jacobs
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1276 eabb8ba4 Aurelien Jacobs
1277 3fc9d7ce Aurelien Jacobs
        if (track->time_scale < 0.01)
1278
            track->time_scale = 1.0;
1279 d88d806b Aurelien Jacobs
        av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1280 eabb8ba4 Aurelien Jacobs
1281 d88d806b Aurelien Jacobs
        st->codec->codec_id = codec_id;
1282
        st->start_time = 0;
1283
        if (strcmp(track->language, "und"))
1284
            av_strlcpy(st->language, track->language, 4);
1285 b061d892 David Conrad
1286 d88d806b Aurelien Jacobs
        if (track->flag_default)
1287
            st->disposition |= AV_DISPOSITION_DEFAULT;
1288 b061d892 David Conrad
1289 d88d806b Aurelien Jacobs
        if (track->default_duration)
1290
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1291
                      track->default_duration, 1000000000, 30000);
1292 b061d892 David Conrad
1293 d88d806b Aurelien Jacobs
        if(extradata){
1294
            st->codec->extradata = extradata;
1295
            st->codec->extradata_size = extradata_size;
1296
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1297
            st->codec->extradata = av_malloc(track->codec_priv.size);
1298
            if(st->codec->extradata == NULL)
1299
                return AVERROR(ENOMEM);
1300
            st->codec->extradata_size = track->codec_priv.size;
1301
            memcpy(st->codec->extradata,
1302
                   track->codec_priv.data + extradata_offset,
1303
                   track->codec_priv.size);
1304 b061d892 David Conrad
        }
1305 d88d806b Aurelien Jacobs
1306
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1307
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1308
            st->codec->codec_tag  = track->video.fourcc;
1309
            st->codec->width  = track->video.pixel_width;
1310
            st->codec->height = track->video.pixel_height;
1311 59729451 Aurelien Jacobs
            av_reduce(&st->sample_aspect_ratio.num,
1312
                      &st->sample_aspect_ratio.den,
1313 d88d806b Aurelien Jacobs
                      st->codec->height * track->video.display_width,
1314
                      st->codec-> width * track->video.display_height,
1315
                      255);
1316
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1317
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1318
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1319
            st->codec->sample_rate = track->audio.out_samplerate;
1320
            st->codec->channels = track->audio.channels;
1321
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1322
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1323
        }
1324 b061d892 David Conrad
    }
1325
1326 9c25bafa Aurelien Jacobs
    attachements = attachements_list->elem;
1327
    for (j=0; j<attachements_list->nb_elem; j++) {
1328
        if (!(attachements[j].filename && attachements[j].mime &&
1329
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1330
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1331
        } else {
1332 cc70d14b Aurelien Jacobs
            AVStream *st = av_new_stream(s, 0);
1333 9c25bafa Aurelien Jacobs
            if (st == NULL)
1334
                break;
1335
            st->filename          = av_strdup(attachements[j].filename);
1336
            st->codec->codec_id = CODEC_ID_NONE;
1337
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1338
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1339
            if(st->codec->extradata == NULL)
1340
                break;
1341
            st->codec->extradata_size = attachements[j].bin.size;
1342
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1343
1344
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1345
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1346
                             strlen(ff_mkv_mime_tags[i].str))) {
1347
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1348
                    break;
1349
                }
1350
            }
1351
        }
1352
    }
1353
1354
    chapters = chapters_list->elem;
1355
    for (i=0; i<chapters_list->nb_elem; i++)
1356
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1357
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1358
                           chapters[i].start, chapters[i].end,
1359
                           chapters[i].title);
1360
1361 e5929fdf Aurelien Jacobs
    index_list = &matroska->index;
1362
    index = index_list->elem;
1363
    for (i=0; i<index_list->nb_elem; i++) {
1364
        EbmlList *pos_list = &index[i].pos;
1365
        MatroskaIndexPos *pos = pos_list->elem;
1366
        for (j=0; j<pos_list->nb_elem; j++) {
1367 009ecd50 Aurelien Jacobs
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1368 e5929fdf Aurelien Jacobs
                                                              pos[j].track);
1369 009ecd50 Aurelien Jacobs
            if (track && track->stream)
1370
                av_add_index_entry(track->stream,
1371 e5929fdf Aurelien Jacobs
                                   pos[j].pos + matroska->segment_start,
1372 8e44312d Aurelien Jacobs
                                   index[i].time, 0, 0, AVINDEX_KEYFRAME);
1373 b061d892 David Conrad
        }
1374
    }
1375
1376 ce6f28bd Aurelien Jacobs
    return 0;
1377 b061d892 David Conrad
}
1378
1379 737c40da Aurelien Jacobs
/*
1380
 * Put one packet in an application-supplied AVPacket struct.
1381
 * Returns 0 on success or -1 on failure.
1382
 */
1383
static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1384
                                   AVPacket *pkt)
1385
{
1386
    if (matroska->num_packets > 0) {
1387
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1388
        av_free(matroska->packets[0]);
1389
        if (matroska->num_packets > 1) {
1390
            memmove(&matroska->packets[0], &matroska->packets[1],
1391
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
1392
            matroska->packets =
1393
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
1394
                           sizeof(AVPacket *));
1395
        } else {
1396
            av_freep(&matroska->packets);
1397
        }
1398
        matroska->num_packets--;
1399
        return 0;
1400
    }
1401
1402
    return -1;
1403
}
1404
1405
/*
1406
 * Free all packets in our internal queue.
1407
 */
1408
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1409
{
1410
    if (matroska->packets) {
1411
        int n;
1412
        for (n = 0; n < matroska->num_packets; n++) {
1413
            av_free_packet(matroska->packets[n]);
1414
            av_free(matroska->packets[n]);
1415
        }
1416 00a3431c Aurelien Jacobs
        av_freep(&matroska->packets);
1417 737c40da Aurelien Jacobs
        matroska->num_packets = 0;
1418
    }
1419
}
1420
1421 f7b9687c Aurelien Jacobs
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1422
                                int size, int64_t pos, uint64_t cluster_time,
1423 24c3da16 Aurelien Jacobs
                                uint64_t duration, int is_keyframe,
1424
                                int64_t cluster_pos)
1425 b061d892 David Conrad
{
1426 f14a201b Aurelien Jacobs
    uint64_t timecode = AV_NOPTS_VALUE;
1427 009ecd50 Aurelien Jacobs
    MatroskaTrack *track;
1428 a3467f86 Aurelien Jacobs
    int res = 0;
1429 b061d892 David Conrad
    AVStream *st;
1430
    AVPacket *pkt;
1431
    int16_t block_time;
1432
    uint32_t *lace_size = NULL;
1433
    int n, flags, laces = 0;
1434
    uint64_t num;
1435
1436 c1e01133 Aurelien Jacobs
    if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1437 b061d892 David Conrad
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1438
        return res;
1439
    }
1440
    data += n;
1441
    size -= n;
1442
1443
    track = matroska_find_track_by_num(matroska, num);
1444 009ecd50 Aurelien Jacobs
    if (size <= 3 || !track || !track->stream) {
1445 b061d892 David Conrad
        av_log(matroska->ctx, AV_LOG_INFO,
1446 009ecd50 Aurelien Jacobs
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1447 b061d892 David Conrad
        return res;
1448
    }
1449 009ecd50 Aurelien Jacobs
    st = track->stream;
1450 16f97ab0 Aurelien Jacobs
    if (st->discard >= AVDISCARD_ALL)
1451 b061d892 David Conrad
        return res;
1452
    if (duration == AV_NOPTS_VALUE)
1453 009ecd50 Aurelien Jacobs
        duration = track->default_duration / matroska->time_scale;
1454 b061d892 David Conrad
1455 2ce746c6 Aurelien Jacobs
    block_time = AV_RB16(data);
1456 b061d892 David Conrad
    data += 2;
1457 1607c534 Aurelien Jacobs
    flags = *data++;
1458
    size -= 3;
1459 b061d892 David Conrad
    if (is_keyframe == -1)
1460 84fa6e23 David Conrad
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1461 b061d892 David Conrad
1462 f14a201b Aurelien Jacobs
    if (cluster_time != (uint64_t)-1
1463
        && (block_time >= 0 || cluster_time >= -block_time)) {
1464
        timecode = cluster_time + block_time;
1465
        if (is_keyframe)
1466
            av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1467
    }
1468
1469 b061d892 David Conrad
    if (matroska->skip_to_keyframe) {
1470 16f97ab0 Aurelien Jacobs
        if (!is_keyframe || st != matroska->skip_to_stream)
1471 b061d892 David Conrad
            return res;
1472
        matroska->skip_to_keyframe = 0;
1473
    }
1474
1475
    switch ((flags & 0x06) >> 1) {
1476
        case 0x0: /* no lacing */
1477
            laces = 1;
1478
            lace_size = av_mallocz(sizeof(int));
1479
            lace_size[0] = size;
1480
            break;
1481
1482 5968d2dd Diego Biurrun
        case 0x1: /* Xiph lacing */
1483 b061d892 David Conrad
        case 0x2: /* fixed-size lacing */
1484
        case 0x3: /* EBML lacing */
1485 9bf8b562 Michael Niedermayer
            assert(size>0); // size <=3 is checked before size-=3 above
1486 b061d892 David Conrad
            laces = (*data) + 1;
1487
            data += 1;
1488
            size -= 1;
1489
            lace_size = av_mallocz(laces * sizeof(int));
1490
1491
            switch ((flags & 0x06) >> 1) {
1492 5968d2dd Diego Biurrun
                case 0x1: /* Xiph lacing */ {
1493 b061d892 David Conrad
                    uint8_t temp;
1494
                    uint32_t total = 0;
1495
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1496
                        while (1) {
1497
                            if (size == 0) {
1498
                                res = -1;
1499
                                break;
1500
                            }
1501
                            temp = *data;
1502
                            lace_size[n] += temp;
1503
                            data += 1;
1504
                            size -= 1;
1505
                            if (temp != 0xff)
1506
                                break;
1507
                        }
1508
                        total += lace_size[n];
1509
                    }
1510
                    lace_size[n] = size - total;
1511
                    break;
1512
                }
1513
1514
                case 0x2: /* fixed-size lacing */
1515
                    for (n = 0; n < laces; n++)
1516
                        lace_size[n] = size / laces;
1517
                    break;
1518
1519
                case 0x3: /* EBML lacing */ {
1520
                    uint32_t total;
1521 c1e01133 Aurelien Jacobs
                    n = matroska_ebmlnum_uint(matroska, data, size, &num);
1522 b061d892 David Conrad
                    if (n < 0) {
1523
                        av_log(matroska->ctx, AV_LOG_INFO,
1524
                               "EBML block data error\n");
1525
                        break;
1526
                    }
1527
                    data += n;
1528
                    size -= n;
1529
                    total = lace_size[0] = num;
1530
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1531
                        int64_t snum;
1532
                        int r;
1533 c1e01133 Aurelien Jacobs
                        r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1534 b061d892 David Conrad
                        if (r < 0) {
1535
                            av_log(matroska->ctx, AV_LOG_INFO,
1536
                                   "EBML block data error\n");
1537
                            break;
1538
                        }
1539
                        data += r;
1540
                        size -= r;
1541
                        lace_size[n] = lace_size[n - 1] + snum;
1542
                        total += lace_size[n];
1543
                    }
1544
                    lace_size[n] = size - total;
1545
                    break;
1546
                }
1547
            }
1548
            break;
1549
    }
1550
1551
    if (res == 0) {
1552
        for (n = 0; n < laces; n++) {
1553 ba8a76b8 Aurelien Jacobs
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1554
                st->codec->codec_id == CODEC_ID_COOK ||
1555
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1556
                int a = st->codec->block_align;
1557 2cbc8811 Aurelien Jacobs
                int sps = track->audio.sub_packet_size;
1558
                int cfs = track->audio.coded_framesize;
1559
                int h = track->audio.sub_packet_h;
1560
                int y = track->audio.sub_packet_cnt;
1561
                int w = track->audio.frame_size;
1562 ba8a76b8 Aurelien Jacobs
                int x;
1563
1564 2cbc8811 Aurelien Jacobs
                if (!track->audio.pkt_cnt) {
1565 ba8a76b8 Aurelien Jacobs
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1566
                        for (x=0; x<h/2; x++)
1567 2cbc8811 Aurelien Jacobs
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1568 ba8a76b8 Aurelien Jacobs
                                   data+x*cfs, cfs);
1569
                    else
1570
                        for (x=0; x<w/sps; x++)
1571 2cbc8811 Aurelien Jacobs
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1572 ba8a76b8 Aurelien Jacobs
1573 2cbc8811 Aurelien Jacobs
                    if (++track->audio.sub_packet_cnt >= h) {
1574
                        track->audio.sub_packet_cnt = 0;
1575
                        track->audio.pkt_cnt = h*w / a;
1576 979c0910 Aurelien Jacobs
                    }
1577 ba8a76b8 Aurelien Jacobs
                }
1578 2cbc8811 Aurelien Jacobs
                while (track->audio.pkt_cnt) {
1579 77abe5e8 Aurelien Jacobs
                    pkt = av_mallocz(sizeof(AVPacket));
1580 ba8a76b8 Aurelien Jacobs
                    av_new_packet(pkt, a);
1581 2cbc8811 Aurelien Jacobs
                    memcpy(pkt->data, track->audio.buf
1582
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1583 77abe5e8 Aurelien Jacobs
                    pkt->pos = pos;
1584 fc4d335f Aurelien Jacobs
                    pkt->stream_index = st->index;
1585 b8702539 Anton Khirnov
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1586 eabb8ba4 Aurelien Jacobs
                }
1587 ba8a76b8 Aurelien Jacobs
            } else {
1588 2cbc8811 Aurelien Jacobs
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1589 935ec5a1 Evgeniy Stepanov
                int offset = 0, pkt_size = lace_size[n];
1590 de3230fb Aurelien Jacobs
                uint8_t *pkt_data = data;
1591 ba8a76b8 Aurelien Jacobs
1592 2cbc8811 Aurelien Jacobs
                if (encodings && encodings->scope & 1) {
1593 8f35a2c0 Aurelien Jacobs
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1594 935ec5a1 Evgeniy Stepanov
                    if (offset < 0)
1595
                        continue;
1596 53a1e82b Aurelien Jacobs
                }
1597
1598 ba8a76b8 Aurelien Jacobs
                pkt = av_mallocz(sizeof(AVPacket));
1599
                /* XXX: prevent data copy... */
1600 de3230fb Aurelien Jacobs
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1601 34ae4097 Aurelien Jacobs
                    av_free(pkt);
1602 ba8a76b8 Aurelien Jacobs
                    res = AVERROR(ENOMEM);
1603
                    n = laces-1;
1604
                    break;
1605
                }
1606 53a1e82b Aurelien Jacobs
                if (offset)
1607 2cbc8811 Aurelien Jacobs
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1608 de3230fb Aurelien Jacobs
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1609 ba8a76b8 Aurelien Jacobs
1610 51e1cc16 Aurelien Jacobs
                if (pkt_data != data)
1611
                    av_free(pkt_data);
1612
1613 ba8a76b8 Aurelien Jacobs
                if (n == 0)
1614
                    pkt->flags = is_keyframe;
1615 fc4d335f Aurelien Jacobs
                pkt->stream_index = st->index;
1616 ba8a76b8 Aurelien Jacobs
1617
                pkt->pts = timecode;
1618
                pkt->pos = pos;
1619 62c24705 Aurelien Jacobs
                if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE)
1620
                    pkt->convergence_duration = duration;
1621
                else
1622
                    pkt->duration = duration;
1623 ba8a76b8 Aurelien Jacobs
1624 3eb9bfbb Aurelien Jacobs
                if (st->codec->codec_id == CODEC_ID_SSA)
1625
                    matroska_fix_ass_packet(matroska, pkt);
1626
1627 b8702539 Anton Khirnov
                dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
1628 ba8a76b8 Aurelien Jacobs
            }
1629 b061d892 David Conrad
1630 ba8a76b8 Aurelien Jacobs
            if (timecode != AV_NOPTS_VALUE)
1631
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1632 b061d892 David Conrad
            data += lace_size[n];
1633
        }
1634
    }
1635
1636
    av_free(lace_size);
1637 a3467f86 Aurelien Jacobs
    return res;
1638 b061d892 David Conrad
}
1639
1640 f7b9687c Aurelien Jacobs
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1641 b061d892 David Conrad
{
1642 209472b4 Aurelien Jacobs
    MatroskaCluster cluster = { 0 };
1643
    EbmlList *blocks_list;
1644
    MatroskaBlock *blocks;
1645 24c3da16 Aurelien Jacobs
    int i, res;
1646 8bc98ba9 Aurelien Jacobs
    offset_t pos = url_ftell(matroska->ctx->pb);
1647 38797638 Aurelien Jacobs
    if (matroska->has_cluster_id){
1648 5968d2dd Diego Biurrun
        /* For the first cluster we parse, its ID was already read as
1649 38797638 Aurelien Jacobs
           part of matroska_read_header(), so don't read it again */
1650
        res = ebml_parse_id(matroska, matroska_clusters,
1651
                            MATROSKA_ID_CLUSTER, &cluster);
1652 8bc98ba9 Aurelien Jacobs
        pos -= 4;  /* sizeof the ID which was already read */
1653 38797638 Aurelien Jacobs
        matroska->has_cluster_id = 0;
1654
    } else
1655
        res = ebml_parse(matroska, matroska_clusters, &cluster);
1656 209472b4 Aurelien Jacobs
    blocks_list = &cluster.blocks;
1657
    blocks = blocks_list->elem;
1658 131f1cb2 Aurelien Jacobs
    for (i=0; i<blocks_list->nb_elem; i++)
1659 dbfb0e5f Aurelien Jacobs
        if (blocks[i].bin.size > 0)
1660 209472b4 Aurelien Jacobs
            res=matroska_parse_block(matroska,
1661
                                     blocks[i].bin.data, blocks[i].bin.size,
1662
                                     blocks[i].bin.pos,  cluster.timecode,
1663 24c3da16 Aurelien Jacobs
                                     blocks[i].duration, !blocks[i].reference,
1664
                                     pos);
1665 209472b4 Aurelien Jacobs
    ebml_free(matroska_cluster, &cluster);
1666 653fb2f8 Aurelien Jacobs
    if (res < 0)  matroska->done = 1;
1667 b061d892 David Conrad
    return res;
1668
}
1669
1670 f7b9687c Aurelien Jacobs
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1671 b061d892 David Conrad
{
1672
    MatroskaDemuxContext *matroska = s->priv_data;
1673
1674
    while (matroska_deliver_packet(matroska, pkt)) {
1675
        if (matroska->done)
1676 6f3e0b21 Panagiotis Issaris
            return AVERROR(EIO);
1677 653fb2f8 Aurelien Jacobs
        matroska_parse_cluster(matroska);
1678 b061d892 David Conrad
    }
1679
1680
    return 0;
1681
}
1682
1683 f7b9687c Aurelien Jacobs
static int matroska_read_seek(AVFormatContext *s, int stream_index,
1684
                              int64_t timestamp, int flags)
1685 b061d892 David Conrad
{
1686
    MatroskaDemuxContext *matroska = s->priv_data;
1687
    AVStream *st = s->streams[stream_index];
1688
    int index;
1689
1690 dfbbbdc0 Aurelien Jacobs
    if (timestamp < 0)
1691
        timestamp = 0;
1692
1693 6bef5f9b Aurelien Jacobs
    if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1694
        if (st->nb_index_entries)
1695
            url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1696 0dbddda3 Aurelien Jacobs
        while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1697
            matroska_clear_queue(matroska);
1698
            if (matroska_parse_cluster(matroska) < 0)
1699
                break;
1700
        }
1701 6bef5f9b Aurelien Jacobs
    }
1702 b061d892 David Conrad
1703 243cc4c3 Aurelien Jacobs
    matroska_clear_queue(matroska);
1704 0f646a22 Aurelien Jacobs
    if (index < 0)
1705
        return 0;
1706 243cc4c3 Aurelien Jacobs
1707 899681cd Björn Axelsson
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1708 b061d892 David Conrad
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1709
    matroska->skip_to_stream = st;
1710 244ee48a Aurelien Jacobs
    matroska->done = 0;
1711 de6a9a26 Joakim Plate
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1712 b061d892 David Conrad
    return 0;
1713
}
1714
1715 f7b9687c Aurelien Jacobs
static int matroska_read_close(AVFormatContext *s)
1716 b061d892 David Conrad
{
1717
    MatroskaDemuxContext *matroska = s->priv_data;
1718 2cbc8811 Aurelien Jacobs
    MatroskaTrack *tracks = matroska->tracks.elem;
1719 70109c0d Aurelien Jacobs
    int n;
1720 b061d892 David Conrad
1721 34c9c1ba Aurelien Jacobs
    matroska_clear_queue(matroska);
1722 b061d892 David Conrad
1723 2cbc8811 Aurelien Jacobs
    for (n=0; n < matroska->tracks.nb_elem; n++)
1724
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1725
            av_free(tracks[n].audio.buf);
1726 ce6f28bd Aurelien Jacobs
    ebml_free(matroska_segment, matroska);
1727 b061d892 David Conrad
1728
    return 0;
1729
}
1730
1731
AVInputFormat matroska_demuxer = {
1732
    "matroska",
1733 bde15e74 Stefano Sabatini
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1734 b061d892 David Conrad
    sizeof(MatroskaDemuxContext),
1735
    matroska_probe,
1736
    matroska_read_header,
1737
    matroska_read_packet,
1738
    matroska_read_close,
1739
    matroska_read_seek,
1740
};