Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 6cb6e159

History | View | Annotate | Download (63.2 KB)

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

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

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

    
49
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
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
typedef struct {
94
    uint64_t algo;
95
    EbmlBin  settings;
96
} MatroskaTrackCompression;
97

    
98
typedef struct {
99
    uint64_t scope;
100
    uint64_t type;
101
    MatroskaTrackCompression compression;
102
} MatroskaTrackEncoding;
103

    
104
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

    
113
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

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

    
142
    AVStream *stream;
143
    int64_t end_timecode;
144
} MatroskaTrack;
145

    
146
typedef struct {
147
    char *filename;
148
    char *mime;
149
    EbmlBin bin;
150
} MatroskaAttachement;
151

    
152
typedef struct {
153
    uint64_t start;
154
    uint64_t end;
155
    uint64_t uid;
156
    char    *title;
157

    
158
    AVChapter *chapter;
159
} MatroskaChapter;
160

    
161
typedef struct {
162
    uint64_t track;
163
    uint64_t pos;
164
} MatroskaIndexPos;
165

    
166
typedef struct {
167
    uint64_t time;
168
    EbmlList pos;
169
} MatroskaIndex;
170

    
171
typedef struct {
172
    char *name;
173
    char *string;
174
    EbmlList sub;
175
} MatroskaTag;
176

    
177
typedef struct {
178
    uint64_t id;
179
    uint64_t pos;
180
} MatroskaSeekhead;
181

    
182
typedef struct {
183
    uint64_t start;
184
    uint64_t length;
185
} MatroskaLevel;
186

    
187
typedef struct {
188
    AVFormatContext *ctx;
189

    
190
    /* EBML stuff */
191
    int num_levels;
192
    MatroskaLevel levels[EBML_MAX_DEPTH];
193
    int level_up;
194

    
195
    uint64_t time_scale;
196
    double   duration;
197
    char    *title;
198
    EbmlList tracks;
199
    EbmlList attachments;
200
    EbmlList chapters;
201
    EbmlList index;
202
    EbmlList tags;
203
    EbmlList seekhead;
204

    
205
    /* byte position of the segment inside the stream */
206
    int64_t segment_start;
207

    
208
    /* the packet queue */
209
    AVPacket **packets;
210
    int num_packets;
211
    AVPacket *prev_pkt;
212

    
213
    int done;
214
    int has_cluster_id;
215

    
216
    /* What to skip before effectively reading a packet. */
217
    int skip_to_keyframe;
218
    uint64_t skip_to_timecode;
219
} MatroskaDemuxContext;
220

    
221
typedef struct {
222
    uint64_t duration;
223
    int64_t  reference;
224
    EbmlBin  bin;
225
} MatroskaBlock;
226

    
227
typedef struct {
228
    uint64_t timecode;
229
    EbmlList blocks;
230
} MatroskaCluster;
231

    
232
static EbmlSyntax ebml_header[] = {
233
    { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
234
    { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
235
    { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
236
    { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
237
    { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
238
    { EBML_ID_EBMLVERSION,            EBML_NONE },
239
    { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
240
    { 0 }
241
};
242

    
243
static EbmlSyntax ebml_syntax[] = {
244
    { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
245
    { 0 }
246
};
247

    
248
static EbmlSyntax matroska_info[] = {
249
    { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
250
    { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
251
    { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
252
    { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
253
    { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
254
    { MATROSKA_ID_DATEUTC,            EBML_NONE },
255
    { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
256
    { 0 }
257
};
258

    
259
static EbmlSyntax matroska_track_video[] = {
260
    { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
261
    { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
262
    { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
263
    { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
264
    { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
265
    { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
266
    { MATROSKA_ID_VIDEOPIXELCROPB,    EBML_NONE },
267
    { MATROSKA_ID_VIDEOPIXELCROPT,    EBML_NONE },
268
    { MATROSKA_ID_VIDEOPIXELCROPL,    EBML_NONE },
269
    { MATROSKA_ID_VIDEOPIXELCROPR,    EBML_NONE },
270
    { MATROSKA_ID_VIDEODISPLAYUNIT,   EBML_NONE },
271
    { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
272
    { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
273
    { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
274
    { 0 }
275
};
276

    
277
static EbmlSyntax matroska_track_audio[] = {
278
    { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
279
    { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
280
    { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
281
    { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
282
    { 0 }
283
};
284

    
285
static EbmlSyntax matroska_track_encoding_compression[] = {
286
    { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
287
    { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
288
    { 0 }
289
};
290

    
291
static EbmlSyntax matroska_track_encoding[] = {
292
    { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
293
    { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
294
    { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
295
    { MATROSKA_ID_ENCODINGORDER,      EBML_NONE },
296
    { 0 }
297
};
298

    
299
static EbmlSyntax matroska_track_encodings[] = {
300
    { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
301
    { 0 }
302
};
303

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

    
331
static EbmlSyntax matroska_tracks[] = {
332
    { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
333
    { 0 }
334
};
335

    
336
static EbmlSyntax matroska_attachment[] = {
337
    { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
338
    { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
339
    { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
340
    { MATROSKA_ID_FILEDESC,           EBML_NONE },
341
    { MATROSKA_ID_FILEUID,            EBML_NONE },
342
    { 0 }
343
};
344

    
345
static EbmlSyntax matroska_attachments[] = {
346
    { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
347
    { 0 }
348
};
349

    
350
static EbmlSyntax matroska_chapter_display[] = {
351
    { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
352
    { MATROSKA_ID_CHAPLANG,           EBML_NONE },
353
    { 0 }
354
};
355

    
356
static EbmlSyntax matroska_chapter_entry[] = {
357
    { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
358
    { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
359
    { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
360
    { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
361
    { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
362
    { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
363
    { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
364
    { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
365
    { 0 }
366
};
367

    
368
static EbmlSyntax matroska_chapter[] = {
369
    { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
370
    { MATROSKA_ID_EDITIONUID,         EBML_NONE },
371
    { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
372
    { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
373
    { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
374
    { 0 }
375
};
376

    
377
static EbmlSyntax matroska_chapters[] = {
378
    { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
379
    { 0 }
380
};
381

    
382
static EbmlSyntax matroska_index_pos[] = {
383
    { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
384
    { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
385
    { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
386
    { 0 }
387
};
388

    
389
static EbmlSyntax matroska_index_entry[] = {
390
    { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
391
    { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
392
    { 0 }
393
};
394

    
395
static EbmlSyntax matroska_index[] = {
396
    { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
397
    { 0 }
398
};
399

    
400
static EbmlSyntax matroska_simpletag[] = {
401
    { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
402
    { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
403
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
404
    { MATROSKA_ID_TAGLANG,            EBML_NONE },
405
    { MATROSKA_ID_TAGDEFAULT,         EBML_NONE },
406
    { 0 }
407
};
408

    
409
static EbmlSyntax matroska_tag[] = {
410
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), 0, {.n=matroska_simpletag} },
411
    { MATROSKA_ID_TAGTARGETS,         EBML_NONE },
412
    { 0 }
413
};
414

    
415
static EbmlSyntax matroska_tags[] = {
416
    { MATROSKA_ID_TAG,                EBML_NEST, 0, offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
417
    { 0 }
418
};
419

    
420
static EbmlSyntax matroska_seekhead_entry[] = {
421
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
422
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
423
    { 0 }
424
};
425

    
426
static EbmlSyntax matroska_seekhead[] = {
427
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
428
    { 0 }
429
};
430

    
431
static EbmlSyntax matroska_segment[] = {
432
    { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
433
    { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
434
    { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
435
    { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
436
    { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
437
    { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
438
    { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
439
    { MATROSKA_ID_CLUSTER,        EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
440
    { 0 }
441
};
442

    
443
static EbmlSyntax matroska_segments[] = {
444
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
445
    { 0 }
446
};
447

    
448
static EbmlSyntax matroska_blockgroup[] = {
449
    { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
450
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
451
    { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
452
    { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
453
    { 0 }
454
};
455

    
456
static EbmlSyntax matroska_cluster[] = {
457
    { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
458
    { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
459
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
460
    { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
461
    { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
462
    { 0 }
463
};
464

    
465
static EbmlSyntax matroska_clusters[] = {
466
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
467
    { MATROSKA_ID_INFO,           EBML_NONE },
468
    { MATROSKA_ID_CUES,           EBML_NONE },
469
    { MATROSKA_ID_TAGS,           EBML_NONE },
470
    { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
471
    { 0 }
472
};
473

    
474
#define SIZE_OFF(x) sizeof(((AVFormatContext*)0)->x),offsetof(AVFormatContext,x)
475
const struct {
476
    const char name[16];
477
    int   size;
478
    int   offset;
479
} metadata[] = {
480
    { "TITLE",           SIZE_OFF(title)      },
481
    { "ARTIST",          SIZE_OFF(author)     },
482
    { "WRITTEN_BY",      SIZE_OFF(author)     },
483
    { "LEAD_PERFORMER",  SIZE_OFF(author)     },
484
    { "COPYRIGHT",       SIZE_OFF(copyright)  },
485
    { "COMMENT",         SIZE_OFF(comment)    },
486
    { "ALBUM",           SIZE_OFF(album)      },
487
    { "DATE_WRITTEN",    SIZE_OFF(year)       },
488
    { "DATE_RELEASED",   SIZE_OFF(year)       },
489
    { "PART_NUMBER",     SIZE_OFF(track)      },
490
    { "GENRE",           SIZE_OFF(genre)      },
491
};
492

    
493
/*
494
 * Return: Whether we reached the end of a level in the hierarchy or not.
495
 */
496
static int ebml_level_end(MatroskaDemuxContext *matroska)
497
{
498
    ByteIOContext *pb = matroska->ctx->pb;
499
    int64_t pos = url_ftell(pb);
500

    
501
    if (matroska->num_levels > 0) {
502
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
503
        if (pos - level->start >= level->length) {
504
            matroska->num_levels--;
505
            return 1;
506
        }
507
    }
508
    return 0;
509
}
510

    
511
/*
512
 * Read: an "EBML number", which is defined as a variable-length
513
 * array of bytes. The first byte indicates the length by giving a
514
 * number of 0-bits followed by a one. The position of the first
515
 * "one" bit inside the first byte indicates the length of this
516
 * number.
517
 * Returns: number of bytes read, < 0 on error
518
 */
519
static int ebml_read_num(MatroskaDemuxContext *matroska, ByteIOContext *pb,
520
                         int max_size, uint64_t *number)
521
{
522
    int len_mask = 0x80, read = 1, n = 1;
523
    int64_t total = 0;
524

    
525
    /* The first byte tells us the length in bytes - get_byte() can normally
526
     * return 0, but since that's not a valid first ebmlID byte, we can
527
     * use it safely here to catch EOS. */
528
    if (!(total = get_byte(pb))) {
529
        /* we might encounter EOS here */
530
        if (!url_feof(pb)) {
531
            int64_t pos = url_ftell(pb);
532
            av_log(matroska->ctx, AV_LOG_ERROR,
533
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
534
                   pos, pos);
535
        }
536
        return AVERROR(EIO); /* EOS or actual I/O error */
537
    }
538

    
539
    /* get the length of the EBML number */
540
    while (read <= max_size && !(total & len_mask)) {
541
        read++;
542
        len_mask >>= 1;
543
    }
544
    if (read > max_size) {
545
        int64_t pos = url_ftell(pb) - 1;
546
        av_log(matroska->ctx, AV_LOG_ERROR,
547
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
548
               (uint8_t) total, pos, pos);
549
        return AVERROR_INVALIDDATA;
550
    }
551

    
552
    /* read out length */
553
    total &= ~len_mask;
554
    while (n++ < read)
555
        total = (total << 8) | get_byte(pb);
556

    
557
    *number = total;
558

    
559
    return read;
560
}
561

    
562
/*
563
 * Read the next element as an unsigned int.
564
 * 0 is success, < 0 is failure.
565
 */
566
static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
567
{
568
    int n = 0;
569

    
570
    if (size < 1 || size > 8)
571
        return AVERROR_INVALIDDATA;
572

    
573
    /* big-endian ordering; build up number */
574
    *num = 0;
575
    while (n++ < size)
576
        *num = (*num << 8) | get_byte(pb);
577

    
578
    return 0;
579
}
580

    
581
/*
582
 * Read the next element as a float.
583
 * 0 is success, < 0 is failure.
584
 */
585
static int ebml_read_float(ByteIOContext *pb, int size, double *num)
586
{
587
    if (size == 4) {
588
        *num= av_int2flt(get_be32(pb));
589
    } else if(size==8){
590
        *num= av_int2dbl(get_be64(pb));
591
    } else
592
        return AVERROR_INVALIDDATA;
593

    
594
    return 0;
595
}
596

    
597
/*
598
 * Read the next element as an ASCII string.
599
 * 0 is success, < 0 is failure.
600
 */
601
static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
602
{
603
    av_free(*str);
604
    /* EBML strings are usually not 0-terminated, so we allocate one
605
     * byte more, read the string and NULL-terminate it ourselves. */
606
    if (!(*str = av_malloc(size + 1)))
607
        return AVERROR(ENOMEM);
608
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
609
        av_free(*str);
610
        return AVERROR(EIO);
611
    }
612
    (*str)[size] = '\0';
613

    
614
    return 0;
615
}
616

    
617
/*
618
 * Read the next element as binary data.
619
 * 0 is success, < 0 is failure.
620
 */
621
static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
622
{
623
    av_free(bin->data);
624
    if (!(bin->data = av_malloc(length)))
625
        return AVERROR(ENOMEM);
626

    
627
    bin->size = length;
628
    bin->pos  = url_ftell(pb);
629
    if (get_buffer(pb, bin->data, length) != length)
630
        return AVERROR(EIO);
631

    
632
    return 0;
633
}
634

    
635
/*
636
 * Read the next element, but only the header. The contents
637
 * are supposed to be sub-elements which can be read separately.
638
 * 0 is success, < 0 is failure.
639
 */
640
static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
641
{
642
    ByteIOContext *pb = matroska->ctx->pb;
643
    MatroskaLevel *level;
644

    
645
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
646
        av_log(matroska->ctx, AV_LOG_ERROR,
647
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
648
        return AVERROR(ENOSYS);
649
    }
650

    
651
    level = &matroska->levels[matroska->num_levels++];
652
    level->start = url_ftell(pb);
653
    level->length = length;
654

    
655
    return 0;
656
}
657

    
658
/*
659
 * Read signed/unsigned "EBML" numbers.
660
 * Return: number of bytes processed, < 0 on error
661
 */
662
static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
663
                                 uint8_t *data, uint32_t size, uint64_t *num)
664
{
665
    ByteIOContext pb;
666
    init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
667
    return ebml_read_num(matroska, &pb, 8, num);
668
}
669

    
670
/*
671
 * Same as above, but signed.
672
 */
673
static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
674
                                 uint8_t *data, uint32_t size, int64_t *num)
675
{
676
    uint64_t unum;
677
    int res;
678

    
679
    /* read as unsigned number first */
680
    if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
681
        return res;
682

    
683
    /* make signed (weird way) */
684
    *num = unum - ((1LL << (7*res - 1)) - 1);
685

    
686
    return res;
687
}
688

    
689
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
690
                           EbmlSyntax *syntax, void *data);
691

    
692
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
693
                         uint32_t id, void *data)
694
{
695
    int i;
696
    for (i=0; syntax[i].id; i++)
697
        if (id == syntax[i].id)
698
            break;
699
    if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
700
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
701
    return ebml_parse_elem(matroska, &syntax[i], data);
702
}
703

    
704
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
705
                      void *data)
706
{
707
    uint64_t id;
708
    int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
709
    id |= 1 << 7*res;
710
    return res < 0 ? res : ebml_parse_id(matroska, syntax, id, data);
711
}
712

    
713
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
714
                           void *data)
715
{
716
    int i, res = 0;
717

    
718
    for (i=0; syntax[i].id; i++)
719
        switch (syntax[i].type) {
720
        case EBML_UINT:
721
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
722
            break;
723
        case EBML_FLOAT:
724
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
725
            break;
726
        case EBML_STR:
727
        case EBML_UTF8:
728
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
729
            break;
730
        }
731

    
732
    while (!res && !ebml_level_end(matroska))
733
        res = ebml_parse(matroska, syntax, data);
734

    
735
    return res;
736
}
737

    
738
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
739
                           EbmlSyntax *syntax, void *data)
740
{
741
    ByteIOContext *pb = matroska->ctx->pb;
742
    uint32_t id = syntax->id;
743
    uint64_t length;
744
    int res;
745

    
746
    data = (char *)data + syntax->data_offset;
747
    if (syntax->list_elem_size) {
748
        EbmlList *list = data;
749
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
750
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
751
        memset(data, 0, syntax->list_elem_size);
752
        list->nb_elem++;
753
    }
754

    
755
    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
756
        if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
757
            return res;
758

    
759
    switch (syntax->type) {
760
    case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
761
    case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
762
    case EBML_STR:
763
    case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
764
    case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
765
    case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
766
                         return res;
767
                     if (id == MATROSKA_ID_SEGMENT)
768
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
769
                     return ebml_parse_nest(matroska, syntax->def.n, data);
770
    case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
771
    case EBML_STOP:  *(int *)data = 1;      return 1;
772
    default:         return url_fseek(pb,length,SEEK_CUR)<0 ? AVERROR(EIO) : 0;
773
    }
774
    if (res == AVERROR_INVALIDDATA)
775
        av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
776
    else if (res == AVERROR(EIO))
777
        av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
778
    return res;
779
}
780

    
781
static void ebml_free(EbmlSyntax *syntax, void *data)
782
{
783
    int i, j;
784
    for (i=0; syntax[i].id; i++) {
785
        void *data_off = (char *)data + syntax[i].data_offset;
786
        switch (syntax[i].type) {
787
        case EBML_STR:
788
        case EBML_UTF8:  av_freep(data_off);                      break;
789
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
790
        case EBML_NEST:
791
            if (syntax[i].list_elem_size) {
792
                EbmlList *list = data_off;
793
                char *ptr = list->elem;
794
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
795
                    ebml_free(syntax[i].def.n, ptr);
796
                av_free(list->elem);
797
            } else
798
                ebml_free(syntax[i].def.n, data_off);
799
        default:  break;
800
        }
801
    }
802
}
803

    
804

    
805
/*
806
 * Autodetecting...
807
 */
808
static int matroska_probe(AVProbeData *p)
809
{
810
    uint64_t total = 0;
811
    int len_mask = 0x80, size = 1, n = 1;
812
    static const char probe_data[] = "matroska";
813

    
814
    /* EBML header? */
815
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
816
        return 0;
817

    
818
    /* length of header */
819
    total = p->buf[4];
820
    while (size <= 8 && !(total & len_mask)) {
821
        size++;
822
        len_mask >>= 1;
823
    }
824
    if (size > 8)
825
      return 0;
826
    total &= (len_mask - 1);
827
    while (n < size)
828
        total = (total << 8) | p->buf[4 + n++];
829

    
830
    /* Does the probe data contain the whole header? */
831
    if (p->buf_size < 4 + size + total)
832
      return 0;
833

    
834
    /* The header must contain the document type 'matroska'. For now,
835
     * we don't parse the whole header but simply check for the
836
     * availability of that array of characters inside the header.
837
     * Not fully fool-proof, but good enough. */
838
    for (n = 4+size; n <= 4+size+total-(sizeof(probe_data)-1); n++)
839
        if (!memcmp(p->buf+n, probe_data, sizeof(probe_data)-1))
840
            return AVPROBE_SCORE_MAX;
841

    
842
    return 0;
843
}
844

    
845
static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
846
                                                 int num)
847
{
848
    MatroskaTrack *tracks = matroska->tracks.elem;
849
    int i;
850

    
851
    for (i=0; i < matroska->tracks.nb_elem; i++)
852
        if (tracks[i].num == num)
853
            return &tracks[i];
854

    
855
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
856
    return NULL;
857
}
858

    
859
static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
860
                                  MatroskaTrack *track)
861
{
862
    MatroskaTrackEncoding *encodings = track->encodings.elem;
863
    uint8_t* data = *buf;
864
    int isize = *buf_size;
865
    uint8_t* pkt_data = NULL;
866
    int pkt_size = isize;
867
    int result = 0;
868
    int olen;
869

    
870
    switch (encodings[0].compression.algo) {
871
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
872
        return encodings[0].compression.settings.size;
873
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
874
        do {
875
            olen = pkt_size *= 3;
876
            pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
877
            result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
878
        } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
879
        if (result)
880
            goto failed;
881
        pkt_size -= olen;
882
        break;
883
#if CONFIG_ZLIB
884
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
885
        z_stream zstream = {0};
886
        if (inflateInit(&zstream) != Z_OK)
887
            return -1;
888
        zstream.next_in = data;
889
        zstream.avail_in = isize;
890
        do {
891
            pkt_size *= 3;
892
            pkt_data = av_realloc(pkt_data, pkt_size);
893
            zstream.avail_out = pkt_size - zstream.total_out;
894
            zstream.next_out = pkt_data + zstream.total_out;
895
            result = inflate(&zstream, Z_NO_FLUSH);
896
        } while (result==Z_OK && pkt_size<10000000);
897
        pkt_size = zstream.total_out;
898
        inflateEnd(&zstream);
899
        if (result != Z_STREAM_END)
900
            goto failed;
901
        break;
902
    }
903
#endif
904
#if CONFIG_BZLIB
905
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
906
        bz_stream bzstream = {0};
907
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
908
            return -1;
909
        bzstream.next_in = data;
910
        bzstream.avail_in = isize;
911
        do {
912
            pkt_size *= 3;
913
            pkt_data = av_realloc(pkt_data, pkt_size);
914
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
915
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
916
            result = BZ2_bzDecompress(&bzstream);
917
        } while (result==BZ_OK && pkt_size<10000000);
918
        pkt_size = bzstream.total_out_lo32;
919
        BZ2_bzDecompressEnd(&bzstream);
920
        if (result != BZ_STREAM_END)
921
            goto failed;
922
        break;
923
    }
924
#endif
925
    default:
926
        return -1;
927
    }
928

    
929
    *buf = pkt_data;
930
    *buf_size = pkt_size;
931
    return 0;
932
 failed:
933
    av_free(pkt_data);
934
    return -1;
935
}
936

    
937
static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
938
                                    AVPacket *pkt, uint64_t display_duration)
939
{
940
    char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
941
    for (; *ptr!=',' && ptr<end-1; ptr++);
942
    if (*ptr == ',')
943
        layer = ++ptr;
944
    for (; *ptr!=',' && ptr<end-1; ptr++);
945
    if (*ptr == ',') {
946
        int64_t end_pts = pkt->pts + display_duration;
947
        int sc = matroska->time_scale * pkt->pts / 10000000;
948
        int ec = matroska->time_scale * end_pts  / 10000000;
949
        int sh, sm, ss, eh, em, es, len;
950
        sh = sc/360000;  sc -= 360000*sh;
951
        sm = sc/  6000;  sc -=   6000*sm;
952
        ss = sc/   100;  sc -=    100*ss;
953
        eh = ec/360000;  ec -= 360000*eh;
954
        em = ec/  6000;  ec -=   6000*em;
955
        es = ec/   100;  ec -=    100*es;
956
        *ptr++ = '\0';
957
        len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
958
        if (!(line = av_malloc(len)))
959
            return;
960
        snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
961
                 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
962
        av_free(pkt->data);
963
        pkt->data = line;
964
        pkt->size = strlen(line);
965
    }
966
}
967

    
968
static void matroska_merge_packets(AVPacket *out, AVPacket *in)
969
{
970
    out->data = av_realloc(out->data, out->size+in->size);
971
    memcpy(out->data+out->size, in->data, in->size);
972
    out->size += in->size;
973
    av_destruct_packet(in);
974
    av_free(in);
975
}
976

    
977
static void matroska_convert_tags(AVFormatContext *s, EbmlList *list)
978
{
979
    MatroskaTag *tags = list->elem;
980
    int i, j;
981

    
982
    for (i=0; i < list->nb_elem; i++) {
983
        for (j=0; j < FF_ARRAY_ELEMS(metadata); j++){
984
            if (!strcmp(tags[i].name, metadata[j].name)) {
985
                int *ptr = (int *)((char *)s + metadata[j].offset);
986
                if (*ptr)  continue;
987
                if (metadata[j].size > sizeof(int))
988
                    av_strlcpy((char *)ptr, tags[i].string, metadata[j].size);
989
                else
990
                    *ptr = atoi(tags[i].string);
991
            }
992
        }
993
        if (tags[i].sub.nb_elem)
994
            matroska_convert_tags(s, &tags[i].sub);
995
    }
996
}
997

    
998
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
999
{
1000
    EbmlList *seekhead_list = &matroska->seekhead;
1001
    MatroskaSeekhead *seekhead = seekhead_list->elem;
1002
    uint32_t level_up = matroska->level_up;
1003
    int64_t before_pos = url_ftell(matroska->ctx->pb);
1004
    MatroskaLevel level;
1005
    int i;
1006

    
1007
    for (i=0; i<seekhead_list->nb_elem; i++) {
1008
        int64_t offset = seekhead[i].pos + matroska->segment_start;
1009

    
1010
        if (seekhead[i].pos <= before_pos
1011
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1012
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
1013
            continue;
1014

    
1015
        /* seek */
1016
        if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
1017
            continue;
1018

    
1019
        /* We don't want to lose our seekhead level, so we add
1020
         * a dummy. This is a crude hack. */
1021
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1022
            av_log(matroska->ctx, AV_LOG_INFO,
1023
                   "Max EBML element depth (%d) reached, "
1024
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1025
            break;
1026
        }
1027

    
1028
        level.start = 0;
1029
        level.length = (uint64_t)-1;
1030
        matroska->levels[matroska->num_levels] = level;
1031
        matroska->num_levels++;
1032

    
1033
        ebml_parse(matroska, matroska_segment, matroska);
1034

    
1035
        /* remove dummy level */
1036
        while (matroska->num_levels) {
1037
            uint64_t length = matroska->levels[--matroska->num_levels].length;
1038
            if (length == (uint64_t)-1)
1039
                break;
1040
        }
1041
    }
1042

    
1043
    /* seek back */
1044
    url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
1045
    matroska->level_up = level_up;
1046
}
1047

    
1048
static int matroska_aac_profile(char *codec_id)
1049
{
1050
    static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1051
    int profile;
1052

    
1053
    for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1054
        if (strstr(codec_id, aac_profiles[profile]))
1055
            break;
1056
    return profile + 1;
1057
}
1058

    
1059
static int matroska_aac_sri(int samplerate)
1060
{
1061
    int sri;
1062

    
1063
    for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
1064
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1065
            break;
1066
    return sri;
1067
}
1068

    
1069
static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1070
{
1071
    MatroskaDemuxContext *matroska = s->priv_data;
1072
    EbmlList *attachements_list = &matroska->attachments;
1073
    MatroskaAttachement *attachements;
1074
    EbmlList *chapters_list = &matroska->chapters;
1075
    MatroskaChapter *chapters;
1076
    MatroskaTrack *tracks;
1077
    EbmlList *index_list;
1078
    MatroskaIndex *index;
1079
    int index_scale = 1;
1080
    uint64_t max_start = 0;
1081
    Ebml ebml = { 0 };
1082
    AVStream *st;
1083
    int i, j;
1084

    
1085
    matroska->ctx = s;
1086

    
1087
    /* First read the EBML header. */
1088
    if (ebml_parse(matroska, ebml_syntax, &ebml)
1089
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
1090
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1091
        || ebml.doctype_version > 2) {
1092
        av_log(matroska->ctx, AV_LOG_ERROR,
1093
               "EBML header using unsupported features\n"
1094
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1095
               ebml.version, ebml.doctype, ebml.doctype_version);
1096
        return AVERROR_NOFMT;
1097
    }
1098
    ebml_free(ebml_syntax, &ebml);
1099

    
1100
    /* The next thing is a segment. */
1101
    if (ebml_parse(matroska, matroska_segments, matroska) < 0)
1102
        return -1;
1103
    matroska_execute_seekhead(matroska);
1104

    
1105
    if (matroska->duration)
1106
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1107
                                  * 1000 / AV_TIME_BASE;
1108
    av_metadata_set(&s->metadata, "title", matroska->title);
1109
    matroska_convert_tags(s, &matroska->tags);
1110

    
1111
    tracks = matroska->tracks.elem;
1112
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1113
        MatroskaTrack *track = &tracks[i];
1114
        enum CodecID codec_id = CODEC_ID_NONE;
1115
        EbmlList *encodings_list = &tracks->encodings;
1116
        MatroskaTrackEncoding *encodings = encodings_list->elem;
1117
        uint8_t *extradata = NULL;
1118
        int extradata_size = 0;
1119
        int extradata_offset = 0;
1120
        ByteIOContext b;
1121

    
1122
        /* Apply some sanity checks. */
1123
        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
        if (track->codec_id == NULL)
1132
            continue;
1133

    
1134
        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
#if CONFIG_ZLIB
1152
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1153
#endif
1154
#if CONFIG_BZLIB
1155
                 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
        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
            }
1190
        }
1191

    
1192
        st = track->stream = av_new_stream(s, 0);
1193
        if (st == NULL)
1194
            return AVERROR(ENOMEM);
1195

    
1196
        if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1197
            && track->codec_priv.size >= 40
1198
            && track->codec_priv.data != NULL) {
1199
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1200
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1201
        } else if (!strcmp(track->codec_id, "A_MS/ACM")
1202
                   && track->codec_priv.size >= 18
1203
                   && track->codec_priv.data != NULL) {
1204
            init_put_byte(&b, track->codec_priv.data, track->codec_priv.size,
1205
                          URL_RDONLY, NULL, NULL, NULL, NULL);
1206
            get_wav_header(&b, st->codec, track->codec_priv.size);
1207
            codec_id = st->codec->codec_id;
1208
            extradata_offset = 18;
1209
            track->codec_priv.size -= extradata_offset;
1210
        } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1211
                   && (track->codec_priv.size >= 86)
1212
                   && (track->codec_priv.data != NULL)) {
1213
            track->video.fourcc = AV_RL32(track->codec_priv.data);
1214
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1215
        } else if (codec_id == CODEC_ID_PCM_S16BE) {
1216
            switch (track->audio.bitdepth) {
1217
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1218
            case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
1219
            case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
1220
            }
1221
        } else if (codec_id == CODEC_ID_PCM_S16LE) {
1222
            switch (track->audio.bitdepth) {
1223
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
1224
            case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
1225
            case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
1226
            }
1227
        } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1228
            codec_id = CODEC_ID_PCM_F64LE;
1229
        } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1230
            int profile = matroska_aac_profile(track->codec_id);
1231
            int sri = matroska_aac_sri(track->audio.samplerate);
1232
            extradata = av_malloc(5);
1233
            if (extradata == NULL)
1234
                return AVERROR(ENOMEM);
1235
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1236
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1237
            if (strstr(track->codec_id, "SBR")) {
1238
                sri = matroska_aac_sri(track->audio.out_samplerate);
1239
                extradata[2] = 0x56;
1240
                extradata[3] = 0xE5;
1241
                extradata[4] = 0x80 | (sri<<3);
1242
                extradata_size = 5;
1243
            } else
1244
                extradata_size = 2;
1245
        } else if (codec_id == CODEC_ID_TTA) {
1246
            extradata_size = 30;
1247
            extradata = av_mallocz(extradata_size);
1248
            if (extradata == NULL)
1249
                return AVERROR(ENOMEM);
1250
            init_put_byte(&b, extradata, extradata_size, 1,
1251
                          NULL, NULL, NULL, NULL);
1252
            put_buffer(&b, "TTA1", 4);
1253
            put_le16(&b, 1);
1254
            put_le16(&b, track->audio.channels);
1255
            put_le16(&b, track->audio.bitdepth);
1256
            put_le32(&b, track->audio.out_samplerate);
1257
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1258
        } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1259
                   codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1260
            extradata_offset = 26;
1261
            track->codec_priv.size -= extradata_offset;
1262
        } else if (codec_id == CODEC_ID_RA_144) {
1263
            track->audio.out_samplerate = 8000;
1264
            track->audio.channels = 1;
1265
        } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1266
                   codec_id == CODEC_ID_ATRAC3) {
1267
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1268
                          0, NULL, NULL, NULL, NULL);
1269
            url_fskip(&b, 24);
1270
            track->audio.coded_framesize = get_be32(&b);
1271
            url_fskip(&b, 12);
1272
            track->audio.sub_packet_h    = get_be16(&b);
1273
            track->audio.frame_size      = get_be16(&b);
1274
            track->audio.sub_packet_size = get_be16(&b);
1275
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1276
            if (codec_id == CODEC_ID_RA_288) {
1277
                st->codec->block_align = track->audio.coded_framesize;
1278
                track->codec_priv.size = 0;
1279
            } else {
1280
                st->codec->block_align = track->audio.sub_packet_size;
1281
                extradata_offset = 78;
1282
                track->codec_priv.size -= extradata_offset;
1283
            }
1284
        }
1285

    
1286
        if (codec_id == CODEC_ID_NONE)
1287
            av_log(matroska->ctx, AV_LOG_INFO,
1288
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
1289

    
1290
        if (track->time_scale < 0.01)
1291
            track->time_scale = 1.0;
1292
        av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1293

    
1294
        st->codec->codec_id = codec_id;
1295
        st->start_time = 0;
1296
        if (strcmp(track->language, "und"))
1297
            av_metadata_set(&st->metadata, "language", track->language);
1298

    
1299
        if (track->flag_default)
1300
            st->disposition |= AV_DISPOSITION_DEFAULT;
1301

    
1302
        if (track->default_duration)
1303
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1304
                      track->default_duration, 1000000000, 30000);
1305

    
1306
        if(extradata){
1307
            st->codec->extradata = extradata;
1308
            st->codec->extradata_size = extradata_size;
1309
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
1310
            st->codec->extradata = av_mallocz(track->codec_priv.size +
1311
                                              FF_INPUT_BUFFER_PADDING_SIZE);
1312
            if(st->codec->extradata == NULL)
1313
                return AVERROR(ENOMEM);
1314
            st->codec->extradata_size = track->codec_priv.size;
1315
            memcpy(st->codec->extradata,
1316
                   track->codec_priv.data + extradata_offset,
1317
                   track->codec_priv.size);
1318
        }
1319

    
1320
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1321
            st->codec->codec_type = CODEC_TYPE_VIDEO;
1322
            st->codec->codec_tag  = track->video.fourcc;
1323
            st->codec->width  = track->video.pixel_width;
1324
            st->codec->height = track->video.pixel_height;
1325
            av_reduce(&st->sample_aspect_ratio.num,
1326
                      &st->sample_aspect_ratio.den,
1327
                      st->codec->height * track->video.display_width,
1328
                      st->codec-> width * track->video.display_height,
1329
                      255);
1330
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
1331
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1332
            st->codec->codec_type = CODEC_TYPE_AUDIO;
1333
            st->codec->sample_rate = track->audio.out_samplerate;
1334
            st->codec->channels = track->audio.channels;
1335
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1336
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1337
        }
1338
    }
1339

    
1340
    attachements = attachements_list->elem;
1341
    for (j=0; j<attachements_list->nb_elem; j++) {
1342
        if (!(attachements[j].filename && attachements[j].mime &&
1343
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
1344
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1345
        } else {
1346
            AVStream *st = av_new_stream(s, 0);
1347
            if (st == NULL)
1348
                break;
1349
            av_metadata_set(&st->metadata, "filename",attachements[j].filename);
1350
            st->codec->codec_id = CODEC_ID_NONE;
1351
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1352
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
1353
            if(st->codec->extradata == NULL)
1354
                break;
1355
            st->codec->extradata_size = attachements[j].bin.size;
1356
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1357

    
1358
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1359
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1360
                             strlen(ff_mkv_mime_tags[i].str))) {
1361
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1362
                    break;
1363
                }
1364
            }
1365
        }
1366
    }
1367

    
1368
    chapters = chapters_list->elem;
1369
    for (i=0; i<chapters_list->nb_elem; i++)
1370
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1371
            && (max_start==0 || chapters[i].start > max_start)) {
1372
            chapters[i].chapter =
1373
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1374
                           chapters[i].start, chapters[i].end,
1375
                           chapters[i].title);
1376
            av_metadata_set(&chapters[i].chapter->metadata,
1377
                            "title", chapters[i].title);
1378
            max_start = chapters[i].start;
1379
        }
1380

    
1381
    index_list = &matroska->index;
1382
    index = index_list->elem;
1383
    if (index_list->nb_elem
1384
        && index[0].time > 100000000000000/matroska->time_scale) {
1385
        av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1386
        index_scale = matroska->time_scale;
1387
    }
1388
    for (i=0; i<index_list->nb_elem; i++) {
1389
        EbmlList *pos_list = &index[i].pos;
1390
        MatroskaIndexPos *pos = pos_list->elem;
1391
        for (j=0; j<pos_list->nb_elem; j++) {
1392
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1393
                                                              pos[j].track);
1394
            if (track && track->stream)
1395
                av_add_index_entry(track->stream,
1396
                                   pos[j].pos + matroska->segment_start,
1397
                                   index[i].time/index_scale, 0, 0,
1398
                                   AVINDEX_KEYFRAME);
1399
        }
1400
    }
1401

    
1402
    return 0;
1403
}
1404

    
1405
/*
1406
 * Put one packet in an application-supplied AVPacket struct.
1407
 * Returns 0 on success or -1 on failure.
1408
 */
1409
static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1410
                                   AVPacket *pkt)
1411
{
1412
    if (matroska->num_packets > 0) {
1413
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1414
        av_free(matroska->packets[0]);
1415
        if (matroska->num_packets > 1) {
1416
            memmove(&matroska->packets[0], &matroska->packets[1],
1417
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
1418
            matroska->packets =
1419
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
1420
                           sizeof(AVPacket *));
1421
        } else {
1422
            av_freep(&matroska->packets);
1423
        }
1424
        matroska->num_packets--;
1425
        return 0;
1426
    }
1427

    
1428
    return -1;
1429
}
1430

    
1431
/*
1432
 * Free all packets in our internal queue.
1433
 */
1434
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1435
{
1436
    if (matroska->packets) {
1437
        int n;
1438
        for (n = 0; n < matroska->num_packets; n++) {
1439
            av_free_packet(matroska->packets[n]);
1440
            av_free(matroska->packets[n]);
1441
        }
1442
        av_freep(&matroska->packets);
1443
        matroska->num_packets = 0;
1444
    }
1445
}
1446

    
1447
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1448
                                int size, int64_t pos, uint64_t cluster_time,
1449
                                uint64_t duration, int is_keyframe,
1450
                                int64_t cluster_pos)
1451
{
1452
    uint64_t timecode = AV_NOPTS_VALUE;
1453
    MatroskaTrack *track;
1454
    int res = 0;
1455
    AVStream *st;
1456
    AVPacket *pkt;
1457
    int16_t block_time;
1458
    uint32_t *lace_size = NULL;
1459
    int n, flags, laces = 0;
1460
    uint64_t num;
1461

    
1462
    if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1463
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1464
        return res;
1465
    }
1466
    data += n;
1467
    size -= n;
1468

    
1469
    track = matroska_find_track_by_num(matroska, num);
1470
    if (size <= 3 || !track || !track->stream) {
1471
        av_log(matroska->ctx, AV_LOG_INFO,
1472
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1473
        return res;
1474
    }
1475
    st = track->stream;
1476
    if (st->discard >= AVDISCARD_ALL)
1477
        return res;
1478
    if (duration == AV_NOPTS_VALUE)
1479
        duration = track->default_duration / matroska->time_scale;
1480

    
1481
    block_time = AV_RB16(data);
1482
    data += 2;
1483
    flags = *data++;
1484
    size -= 3;
1485
    if (is_keyframe == -1)
1486
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1487

    
1488
    if (cluster_time != (uint64_t)-1
1489
        && (block_time >= 0 || cluster_time >= -block_time)) {
1490
        timecode = cluster_time + block_time;
1491
        if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1492
            && timecode < track->end_timecode)
1493
            is_keyframe = 0;  /* overlapping subtitles are not key frame */
1494
        if (is_keyframe)
1495
            av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1496
        track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1497
    }
1498

    
1499
    if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1500
        if (!is_keyframe || timecode < matroska->skip_to_timecode)
1501
            return res;
1502
        matroska->skip_to_keyframe = 0;
1503
    }
1504

    
1505
    switch ((flags & 0x06) >> 1) {
1506
        case 0x0: /* no lacing */
1507
            laces = 1;
1508
            lace_size = av_mallocz(sizeof(int));
1509
            lace_size[0] = size;
1510
            break;
1511

    
1512
        case 0x1: /* Xiph lacing */
1513
        case 0x2: /* fixed-size lacing */
1514
        case 0x3: /* EBML lacing */
1515
            assert(size>0); // size <=3 is checked before size-=3 above
1516
            laces = (*data) + 1;
1517
            data += 1;
1518
            size -= 1;
1519
            lace_size = av_mallocz(laces * sizeof(int));
1520

    
1521
            switch ((flags & 0x06) >> 1) {
1522
                case 0x1: /* Xiph lacing */ {
1523
                    uint8_t temp;
1524
                    uint32_t total = 0;
1525
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1526
                        while (1) {
1527
                            if (size == 0) {
1528
                                res = -1;
1529
                                break;
1530
                            }
1531
                            temp = *data;
1532
                            lace_size[n] += temp;
1533
                            data += 1;
1534
                            size -= 1;
1535
                            if (temp != 0xff)
1536
                                break;
1537
                        }
1538
                        total += lace_size[n];
1539
                    }
1540
                    lace_size[n] = size - total;
1541
                    break;
1542
                }
1543

    
1544
                case 0x2: /* fixed-size lacing */
1545
                    for (n = 0; n < laces; n++)
1546
                        lace_size[n] = size / laces;
1547
                    break;
1548

    
1549
                case 0x3: /* EBML lacing */ {
1550
                    uint32_t total;
1551
                    n = matroska_ebmlnum_uint(matroska, data, size, &num);
1552
                    if (n < 0) {
1553
                        av_log(matroska->ctx, AV_LOG_INFO,
1554
                               "EBML block data error\n");
1555
                        break;
1556
                    }
1557
                    data += n;
1558
                    size -= n;
1559
                    total = lace_size[0] = num;
1560
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1561
                        int64_t snum;
1562
                        int r;
1563
                        r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1564
                        if (r < 0) {
1565
                            av_log(matroska->ctx, AV_LOG_INFO,
1566
                                   "EBML block data error\n");
1567
                            break;
1568
                        }
1569
                        data += r;
1570
                        size -= r;
1571
                        lace_size[n] = lace_size[n - 1] + snum;
1572
                        total += lace_size[n];
1573
                    }
1574
                    lace_size[n] = size - total;
1575
                    break;
1576
                }
1577
            }
1578
            break;
1579
    }
1580

    
1581
    if (res == 0) {
1582
        for (n = 0; n < laces; n++) {
1583
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1584
                st->codec->codec_id == CODEC_ID_COOK ||
1585
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1586
                int a = st->codec->block_align;
1587
                int sps = track->audio.sub_packet_size;
1588
                int cfs = track->audio.coded_framesize;
1589
                int h = track->audio.sub_packet_h;
1590
                int y = track->audio.sub_packet_cnt;
1591
                int w = track->audio.frame_size;
1592
                int x;
1593

    
1594
                if (!track->audio.pkt_cnt) {
1595
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1596
                        for (x=0; x<h/2; x++)
1597
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1598
                                   data+x*cfs, cfs);
1599
                    else
1600
                        for (x=0; x<w/sps; x++)
1601
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1602

    
1603
                    if (++track->audio.sub_packet_cnt >= h) {
1604
                        track->audio.sub_packet_cnt = 0;
1605
                        track->audio.pkt_cnt = h*w / a;
1606
                    }
1607
                }
1608
                while (track->audio.pkt_cnt) {
1609
                    pkt = av_mallocz(sizeof(AVPacket));
1610
                    av_new_packet(pkt, a);
1611
                    memcpy(pkt->data, track->audio.buf
1612
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1613
                    pkt->pos = pos;
1614
                    pkt->stream_index = st->index;
1615
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1616
                }
1617
            } else {
1618
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1619
                int offset = 0, pkt_size = lace_size[n];
1620
                uint8_t *pkt_data = data;
1621

    
1622
                if (encodings && encodings->scope & 1) {
1623
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1624
                    if (offset < 0)
1625
                        continue;
1626
                }
1627

    
1628
                pkt = av_mallocz(sizeof(AVPacket));
1629
                /* XXX: prevent data copy... */
1630
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1631
                    av_free(pkt);
1632
                    res = AVERROR(ENOMEM);
1633
                    n = laces-1;
1634
                    break;
1635
                }
1636
                if (offset)
1637
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1638
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1639

    
1640
                if (pkt_data != data)
1641
                    av_free(pkt_data);
1642

    
1643
                if (n == 0)
1644
                    pkt->flags = is_keyframe;
1645
                pkt->stream_index = st->index;
1646

    
1647
                pkt->pts = timecode;
1648
                pkt->pos = pos;
1649
                if (st->codec->codec_id == CODEC_ID_TEXT)
1650
                    pkt->convergence_duration = duration;
1651
                else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1652
                    pkt->duration = duration;
1653

    
1654
                if (st->codec->codec_id == CODEC_ID_SSA)
1655
                    matroska_fix_ass_packet(matroska, pkt, duration);
1656

    
1657
                if (matroska->prev_pkt &&
1658
                    timecode != AV_NOPTS_VALUE &&
1659
                    matroska->prev_pkt->pts == timecode &&
1660
                    matroska->prev_pkt->stream_index == st->index)
1661
                    matroska_merge_packets(matroska->prev_pkt, pkt);
1662
                else {
1663
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1664
                    matroska->prev_pkt = pkt;
1665
                }
1666
            }
1667

    
1668
            if (timecode != AV_NOPTS_VALUE)
1669
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1670
            data += lace_size[n];
1671
        }
1672
    }
1673

    
1674
    av_free(lace_size);
1675
    return res;
1676
}
1677

    
1678
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1679
{
1680
    MatroskaCluster cluster = { 0 };
1681
    EbmlList *blocks_list;
1682
    MatroskaBlock *blocks;
1683
    int i, res;
1684
    int64_t pos = url_ftell(matroska->ctx->pb);
1685
    matroska->prev_pkt = NULL;
1686
    if (matroska->has_cluster_id){
1687
        /* For the first cluster we parse, its ID was already read as
1688
           part of matroska_read_header(), so don't read it again */
1689
        res = ebml_parse_id(matroska, matroska_clusters,
1690
                            MATROSKA_ID_CLUSTER, &cluster);
1691
        pos -= 4;  /* sizeof the ID which was already read */
1692
        matroska->has_cluster_id = 0;
1693
    } else
1694
        res = ebml_parse(matroska, matroska_clusters, &cluster);
1695
    blocks_list = &cluster.blocks;
1696
    blocks = blocks_list->elem;
1697
    for (i=0; i<blocks_list->nb_elem; i++)
1698
        if (blocks[i].bin.size > 0)
1699
            res=matroska_parse_block(matroska,
1700
                                     blocks[i].bin.data, blocks[i].bin.size,
1701
                                     blocks[i].bin.pos,  cluster.timecode,
1702
                                     blocks[i].duration, !blocks[i].reference,
1703
                                     pos);
1704
    ebml_free(matroska_cluster, &cluster);
1705
    if (res < 0)  matroska->done = 1;
1706
    return res;
1707
}
1708

    
1709
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1710
{
1711
    MatroskaDemuxContext *matroska = s->priv_data;
1712

    
1713
    while (matroska_deliver_packet(matroska, pkt)) {
1714
        if (matroska->done)
1715
            return AVERROR(EIO);
1716
        matroska_parse_cluster(matroska);
1717
    }
1718

    
1719
    return 0;
1720
}
1721

    
1722
static int matroska_read_seek(AVFormatContext *s, int stream_index,
1723
                              int64_t timestamp, int flags)
1724
{
1725
    MatroskaDemuxContext *matroska = s->priv_data;
1726
    MatroskaTrack *tracks = matroska->tracks.elem;
1727
    AVStream *st = s->streams[stream_index];
1728
    int i, index, index_sub, index_min;
1729

    
1730
    if (!st->nb_index_entries)
1731
        return 0;
1732
    timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1733

    
1734
    if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1735
        url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1736
        while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1737
            matroska_clear_queue(matroska);
1738
            if (matroska_parse_cluster(matroska) < 0)
1739
                break;
1740
        }
1741
    }
1742

    
1743
    matroska_clear_queue(matroska);
1744
    if (index < 0)
1745
        return 0;
1746

    
1747
    index_min = index;
1748
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1749
        tracks[i].end_timecode = 0;
1750
        if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1751
            && !tracks[i].stream->discard != AVDISCARD_ALL) {
1752
            index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1753
            if (index_sub >= 0
1754
                && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1755
                && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1756
                index_min = index_sub;
1757
        }
1758
    }
1759

    
1760
    url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
1761
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1762
    matroska->skip_to_timecode = st->index_entries[index].timestamp;
1763
    matroska->done = 0;
1764
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1765
    return 0;
1766
}
1767

    
1768
static int matroska_read_close(AVFormatContext *s)
1769
{
1770
    MatroskaDemuxContext *matroska = s->priv_data;
1771
    MatroskaTrack *tracks = matroska->tracks.elem;
1772
    int n;
1773

    
1774
    matroska_clear_queue(matroska);
1775

    
1776
    for (n=0; n < matroska->tracks.nb_elem; n++)
1777
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1778
            av_free(tracks[n].audio.buf);
1779
    ebml_free(matroska_segment, matroska);
1780

    
1781
    return 0;
1782
}
1783

    
1784
AVInputFormat matroska_demuxer = {
1785
    "matroska",
1786
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1787
    sizeof(MatroskaDemuxContext),
1788
    matroska_probe,
1789
    matroska_read_header,
1790
    matroska_read_packet,
1791
    matroska_read_close,
1792
    matroska_read_seek,
1793
};