Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ e356fc57

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