~ubuntu-branches/ubuntu/raring/libav/raring-security

« back to all changes in this revision

Viewing changes to .pc/post-0.7.1/0070-Fix-memory-re-allocation-in-matroskadec.c-related-to.patch/libavformat/matroskadec.c

  • Committer: Package Import Robot
  • Author(s): Reinhard Tartler
  • Date: 2011-10-01 00:22:07 UTC
  • mfrom: (1.3.8 sid)
  • Revision ID: package-import@ubuntu.com-20111001002207-tnxz39i0rwr5ufy9
Tags: 4:0.7.2-1ubuntu1
* Merge from debian, remaining changes:
  - don't build against libfaad, libdirac, librtmp and libopenjpeg,
    lame, xvid, x264  (all in universe)
  - not installing into multiarch directories
* This new upstream release has basically merged in all 70 patches that
  are present in 4:0.7.1-7ubuntu2, plus some additional, similarily
  focused ones.

Show diffs side-by-side

added added

removed removed

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