Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ e0e4be59

History | View | Annotate | Download (62.9 KB)

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