Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskadec.c @ 21a115d1

History | View | Annotate | Download (62.4 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 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/avstring.h"
40
#include "libavutil/lzo.h"
41
#ifdef CONFIG_ZLIB
42
#include <zlib.h>
43
#endif
44
#ifdef CONFIG_BZLIB
45
#include <bzlib.h>
46
#endif
47

    
48
typedef enum {
49
    EBML_NONE,
50
    EBML_UINT,
51
    EBML_FLOAT,
52
    EBML_STR,
53
    EBML_UTF8,
54
    EBML_BIN,
55
    EBML_NEST,
56
    EBML_PASS,
57
    EBML_STOP,
58
} EbmlType;
59

    
60
typedef const struct EbmlSyntax {
61
    uint32_t id;
62
    EbmlType type;
63
    int list_elem_size;
64
    int data_offset;
65
    union {
66
        uint64_t    u;
67
        double      f;
68
        const char *s;
69
        const struct EbmlSyntax *n;
70
    } def;
71
} EbmlSyntax;
72

    
73
typedef struct {
74
    int nb_elem;
75
    void *elem;
76
} EbmlList;
77

    
78
typedef struct {
79
    int      size;
80
    uint8_t *data;
81
    int64_t  pos;
82
} EbmlBin;
83

    
84
typedef struct {
85
    uint64_t version;
86
    uint64_t max_size;
87
    uint64_t id_length;
88
    char    *doctype;
89
    uint64_t doctype_version;
90
} Ebml;
91

    
92
typedef struct {
93
    uint64_t algo;
94
    EbmlBin  settings;
95
} MatroskaTrackCompression;
96

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

    
103
typedef struct {
104
    double   frame_rate;
105
    uint64_t display_width;
106
    uint64_t display_height;
107
    uint64_t pixel_width;
108
    uint64_t pixel_height;
109
    uint64_t fourcc;
110
} MatroskaTrackVideo;
111

    
112
typedef struct {
113
    double   samplerate;
114
    double   out_samplerate;
115
    uint64_t bitdepth;
116
    uint64_t channels;
117

    
118
    /* real audio header (extracted from extradata) */
119
    int      coded_framesize;
120
    int      sub_packet_h;
121
    int      frame_size;
122
    int      sub_packet_size;
123
    int      sub_packet_cnt;
124
    int      pkt_cnt;
125
    uint8_t *buf;
126
} MatroskaTrackAudio;
127

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

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

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

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

    
158
typedef struct {
159
    uint64_t track;
160
    uint64_t pos;
161
} MatroskaIndexPos;
162

    
163
typedef struct {
164
    uint64_t time;
165
    EbmlList pos;
166
} MatroskaIndex;
167

    
168
typedef struct {
169
    char *name;
170
    char *string;
171
    EbmlList sub;
172
} MatroskaTag;
173

    
174
typedef struct {
175
    uint64_t id;
176
    uint64_t pos;
177
} MatroskaSeekhead;
178

    
179
typedef struct {
180
    uint64_t start;
181
    uint64_t length;
182
} MatroskaLevel;
183

    
184
typedef struct {
185
    AVFormatContext *ctx;
186

    
187
    /* EBML stuff */
188
    int num_levels;
189
    MatroskaLevel levels[EBML_MAX_DEPTH];
190
    int level_up;
191

    
192
    uint64_t time_scale;
193
    double   duration;
194
    char    *title;
195
    EbmlList tracks;
196
    EbmlList attachments;
197
    EbmlList chapters;
198
    EbmlList index;
199
    EbmlList tags;
200
    EbmlList seekhead;
201

    
202
    /* byte position of the segment inside the stream */
203
    offset_t segment_start;
204

    
205
    /* the packet queue */
206
    AVPacket **packets;
207
    int num_packets;
208
    AVPacket *prev_pkt;
209

    
210
    int done;
211
    int has_cluster_id;
212

    
213
    /* What to skip before effectively reading a packet. */
214
    int skip_to_keyframe;
215
    uint64_t skip_to_timecode;
216
} MatroskaDemuxContext;
217

    
218
typedef struct {
219
    uint64_t duration;
220
    int64_t  reference;
221
    EbmlBin  bin;
222
} MatroskaBlock;
223

    
224
typedef struct {
225
    uint64_t timecode;
226
    EbmlList blocks;
227
} MatroskaCluster;
228

    
229
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
230

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
556
    *number = total;
557

    
558
    return read;
559
}
560

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

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

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

    
577
    return 0;
578
}
579

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

    
593
    return 0;
594
}
595

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

    
613
    return 0;
614
}
615

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

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

    
631
    return 0;
632
}
633

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

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

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

    
654
    return 0;
655
}
656

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

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

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

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

    
685
    return res;
686
}
687

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

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

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

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

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

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

    
734
    return res;
735
}
736

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

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

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

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

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

    
803

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

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

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

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

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

    
841
    return 0;
842
}
843

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

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

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

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

    
869
    switch (encodings[0].compression.algo) {
870
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
871
        return encodings[0].compression.settings.size;
872
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
873
        do {
874
            olen = pkt_size *= 3;
875
            pkt_data = av_realloc(pkt_data,
876
                                  pkt_size+LZO_OUTPUT_PADDING);
877
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
878
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
879
        if (result)
880
            goto failed;
881
        pkt_size -= olen;
882
        break;
883
#ifdef 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
#ifdef 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 < ARRAY_SIZE(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
    offset_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
        offset_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<ARRAY_SIZE(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<ARRAY_SIZE(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
    Ebml ebml = { 0 };
1080
    AVStream *st;
1081
    int i, j;
1082

    
1083
    matroska->ctx = s;
1084

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

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

    
1103
    if (matroska->duration)
1104
        matroska->ctx->duration = matroska->duration * matroska->time_scale
1105
                                  * 1000 / AV_TIME_BASE;
1106
    if (matroska->title)
1107
        strncpy(matroska->ctx->title, matroska->title,
1108
                sizeof(matroska->ctx->title)-1);
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

    
1121
        /* Apply some sanity checks. */
1122
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1123
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1124
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1125
            av_log(matroska->ctx, AV_LOG_INFO,
1126
                   "Unknown or unsupported track type %"PRIu64"\n",
1127
                   track->type);
1128
            continue;
1129
        }
1130
        if (track->codec_id == NULL)
1131
            continue;
1132

    
1133
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1134
            if (!track->default_duration)
1135
                track->default_duration = 1000000000/track->video.frame_rate;
1136
            if (!track->video.display_width)
1137
                track->video.display_width = track->video.pixel_width;
1138
            if (!track->video.display_height)
1139
                track->video.display_height = track->video.pixel_height;
1140
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1141
            if (!track->audio.out_samplerate)
1142
                track->audio.out_samplerate = track->audio.samplerate;
1143
        }
1144
        if (encodings_list->nb_elem > 1) {
1145
            av_log(matroska->ctx, AV_LOG_ERROR,
1146
                   "Multiple combined encodings no supported");
1147
        } else if (encodings_list->nb_elem == 1) {
1148
            if (encodings[0].type ||
1149
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1150
#ifdef CONFIG_ZLIB
1151
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1152
#endif
1153
#ifdef CONFIG_BZLIB
1154
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1155
#endif
1156
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1157
                encodings[0].scope = 0;
1158
                av_log(matroska->ctx, AV_LOG_ERROR,
1159
                       "Unsupported encoding type");
1160
            } else if (track->codec_priv.size && encodings[0].scope&2) {
1161
                uint8_t *codec_priv = track->codec_priv.data;
1162
                int offset = matroska_decode_buffer(&track->codec_priv.data,
1163
                                                    &track->codec_priv.size,
1164
                                                    track);
1165
                if (offset < 0) {
1166
                    track->codec_priv.data = NULL;
1167
                    track->codec_priv.size = 0;
1168
                    av_log(matroska->ctx, AV_LOG_ERROR,
1169
                           "Failed to decode codec private data\n");
1170
                } else if (offset > 0) {
1171
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1172
                    memcpy(track->codec_priv.data,
1173
                           encodings[0].compression.settings.data, offset);
1174
                    memcpy(track->codec_priv.data+offset, codec_priv,
1175
                           track->codec_priv.size);
1176
                    track->codec_priv.size += offset;
1177
                }
1178
                if (codec_priv != track->codec_priv.data)
1179
                    av_free(codec_priv);
1180
            }
1181
        }
1182

    
1183
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1184
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1185
                        strlen(ff_mkv_codec_tags[j].str))){
1186
                codec_id= ff_mkv_codec_tags[j].id;
1187
                break;
1188
            }
1189
        }
1190

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

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

    
1265
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1266
                          0, NULL, NULL, NULL, NULL);
1267
            url_fskip(&b, 24);
1268
            track->audio.coded_framesize = get_be32(&b);
1269
            url_fskip(&b, 12);
1270
            track->audio.sub_packet_h    = get_be16(&b);
1271
            track->audio.frame_size      = get_be16(&b);
1272
            track->audio.sub_packet_size = get_be16(&b);
1273
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1274
            if (codec_id == CODEC_ID_RA_288) {
1275
                st->codec->block_align = track->audio.coded_framesize;
1276
                track->codec_priv.size = 0;
1277
            } else {
1278
                st->codec->block_align = track->audio.sub_packet_size;
1279
                extradata_offset = 78;
1280
                track->codec_priv.size -= extradata_offset;
1281
            }
1282
        }
1283

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

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

    
1292
        st->codec->codec_id = codec_id;
1293
        st->start_time = 0;
1294
        if (strcmp(track->language, "und"))
1295
            av_strlcpy(st->language, track->language, 4);
1296

    
1297
        if (track->flag_default)
1298
            st->disposition |= AV_DISPOSITION_DEFAULT;
1299

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

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

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

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

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

    
1365
    chapters = chapters_list->elem;
1366
    for (i=0; i<chapters_list->nb_elem; i++)
1367
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1368
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1369
                           chapters[i].start, chapters[i].end,
1370
                           chapters[i].title);
1371

    
1372
    index_list = &matroska->index;
1373
    index = index_list->elem;
1374
    for (i=0; i<index_list->nb_elem; i++) {
1375
        EbmlList *pos_list = &index[i].pos;
1376
        MatroskaIndexPos *pos = pos_list->elem;
1377
        for (j=0; j<pos_list->nb_elem; j++) {
1378
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
1379
                                                              pos[j].track);
1380
            if (track && track->stream)
1381
                av_add_index_entry(track->stream,
1382
                                   pos[j].pos + matroska->segment_start,
1383
                                   index[i].time, 0, 0, AVINDEX_KEYFRAME);
1384
        }
1385
    }
1386

    
1387
    return 0;
1388
}
1389

    
1390
/*
1391
 * Put one packet in an application-supplied AVPacket struct.
1392
 * Returns 0 on success or -1 on failure.
1393
 */
1394
static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1395
                                   AVPacket *pkt)
1396
{
1397
    if (matroska->num_packets > 0) {
1398
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1399
        av_free(matroska->packets[0]);
1400
        if (matroska->num_packets > 1) {
1401
            memmove(&matroska->packets[0], &matroska->packets[1],
1402
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
1403
            matroska->packets =
1404
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
1405
                           sizeof(AVPacket *));
1406
        } else {
1407
            av_freep(&matroska->packets);
1408
        }
1409
        matroska->num_packets--;
1410
        return 0;
1411
    }
1412

    
1413
    return -1;
1414
}
1415

    
1416
/*
1417
 * Free all packets in our internal queue.
1418
 */
1419
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1420
{
1421
    if (matroska->packets) {
1422
        int n;
1423
        for (n = 0; n < matroska->num_packets; n++) {
1424
            av_free_packet(matroska->packets[n]);
1425
            av_free(matroska->packets[n]);
1426
        }
1427
        av_freep(&matroska->packets);
1428
        matroska->num_packets = 0;
1429
    }
1430
}
1431

    
1432
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1433
                                int size, int64_t pos, uint64_t cluster_time,
1434
                                uint64_t duration, int is_keyframe,
1435
                                int64_t cluster_pos)
1436
{
1437
    uint64_t timecode = AV_NOPTS_VALUE;
1438
    MatroskaTrack *track;
1439
    int res = 0;
1440
    AVStream *st;
1441
    AVPacket *pkt;
1442
    int16_t block_time;
1443
    uint32_t *lace_size = NULL;
1444
    int n, flags, laces = 0;
1445
    uint64_t num;
1446

    
1447
    if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1448
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1449
        return res;
1450
    }
1451
    data += n;
1452
    size -= n;
1453

    
1454
    track = matroska_find_track_by_num(matroska, num);
1455
    if (size <= 3 || !track || !track->stream) {
1456
        av_log(matroska->ctx, AV_LOG_INFO,
1457
               "Invalid stream %"PRIu64" or size %u\n", num, size);
1458
        return res;
1459
    }
1460
    st = track->stream;
1461
    if (st->discard >= AVDISCARD_ALL)
1462
        return res;
1463
    if (duration == AV_NOPTS_VALUE)
1464
        duration = track->default_duration / matroska->time_scale;
1465

    
1466
    block_time = AV_RB16(data);
1467
    data += 2;
1468
    flags = *data++;
1469
    size -= 3;
1470
    if (is_keyframe == -1)
1471
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1472

    
1473
    if (cluster_time != (uint64_t)-1
1474
        && (block_time >= 0 || cluster_time >= -block_time)) {
1475
        timecode = cluster_time + block_time;
1476
        if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1477
            && timecode < track->end_timecode)
1478
            is_keyframe = 0;  /* overlapping subtitles are not key frame */
1479
        if (is_keyframe)
1480
            av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1481
        track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1482
    }
1483

    
1484
    if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1485
        if (!is_keyframe || timecode < matroska->skip_to_timecode)
1486
            return res;
1487
        matroska->skip_to_keyframe = 0;
1488
    }
1489

    
1490
    switch ((flags & 0x06) >> 1) {
1491
        case 0x0: /* no lacing */
1492
            laces = 1;
1493
            lace_size = av_mallocz(sizeof(int));
1494
            lace_size[0] = size;
1495
            break;
1496

    
1497
        case 0x1: /* Xiph lacing */
1498
        case 0x2: /* fixed-size lacing */
1499
        case 0x3: /* EBML lacing */
1500
            assert(size>0); // size <=3 is checked before size-=3 above
1501
            laces = (*data) + 1;
1502
            data += 1;
1503
            size -= 1;
1504
            lace_size = av_mallocz(laces * sizeof(int));
1505

    
1506
            switch ((flags & 0x06) >> 1) {
1507
                case 0x1: /* Xiph lacing */ {
1508
                    uint8_t temp;
1509
                    uint32_t total = 0;
1510
                    for (n = 0; res == 0 && n < laces - 1; n++) {
1511
                        while (1) {
1512
                            if (size == 0) {
1513
                                res = -1;
1514
                                break;
1515
                            }
1516
                            temp = *data;
1517
                            lace_size[n] += temp;
1518
                            data += 1;
1519
                            size -= 1;
1520
                            if (temp != 0xff)
1521
                                break;
1522
                        }
1523
                        total += lace_size[n];
1524
                    }
1525
                    lace_size[n] = size - total;
1526
                    break;
1527
                }
1528

    
1529
                case 0x2: /* fixed-size lacing */
1530
                    for (n = 0; n < laces; n++)
1531
                        lace_size[n] = size / laces;
1532
                    break;
1533

    
1534
                case 0x3: /* EBML lacing */ {
1535
                    uint32_t total;
1536
                    n = matroska_ebmlnum_uint(matroska, data, size, &num);
1537
                    if (n < 0) {
1538
                        av_log(matroska->ctx, AV_LOG_INFO,
1539
                               "EBML block data error\n");
1540
                        break;
1541
                    }
1542
                    data += n;
1543
                    size -= n;
1544
                    total = lace_size[0] = num;
1545
                    for (n = 1; res == 0 && n < laces - 1; n++) {
1546
                        int64_t snum;
1547
                        int r;
1548
                        r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1549
                        if (r < 0) {
1550
                            av_log(matroska->ctx, AV_LOG_INFO,
1551
                                   "EBML block data error\n");
1552
                            break;
1553
                        }
1554
                        data += r;
1555
                        size -= r;
1556
                        lace_size[n] = lace_size[n - 1] + snum;
1557
                        total += lace_size[n];
1558
                    }
1559
                    lace_size[n] = size - total;
1560
                    break;
1561
                }
1562
            }
1563
            break;
1564
    }
1565

    
1566
    if (res == 0) {
1567
        for (n = 0; n < laces; n++) {
1568
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
1569
                st->codec->codec_id == CODEC_ID_COOK ||
1570
                st->codec->codec_id == CODEC_ID_ATRAC3) {
1571
                int a = st->codec->block_align;
1572
                int sps = track->audio.sub_packet_size;
1573
                int cfs = track->audio.coded_framesize;
1574
                int h = track->audio.sub_packet_h;
1575
                int y = track->audio.sub_packet_cnt;
1576
                int w = track->audio.frame_size;
1577
                int x;
1578

    
1579
                if (!track->audio.pkt_cnt) {
1580
                    if (st->codec->codec_id == CODEC_ID_RA_288)
1581
                        for (x=0; x<h/2; x++)
1582
                            memcpy(track->audio.buf+x*2*w+y*cfs,
1583
                                   data+x*cfs, cfs);
1584
                    else
1585
                        for (x=0; x<w/sps; x++)
1586
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1587

    
1588
                    if (++track->audio.sub_packet_cnt >= h) {
1589
                        track->audio.sub_packet_cnt = 0;
1590
                        track->audio.pkt_cnt = h*w / a;
1591
                    }
1592
                }
1593
                while (track->audio.pkt_cnt) {
1594
                    pkt = av_mallocz(sizeof(AVPacket));
1595
                    av_new_packet(pkt, a);
1596
                    memcpy(pkt->data, track->audio.buf
1597
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
1598
                    pkt->pos = pos;
1599
                    pkt->stream_index = st->index;
1600
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1601
                }
1602
            } else {
1603
                MatroskaTrackEncoding *encodings = track->encodings.elem;
1604
                int offset = 0, pkt_size = lace_size[n];
1605
                uint8_t *pkt_data = data;
1606

    
1607
                if (encodings && encodings->scope & 1) {
1608
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1609
                    if (offset < 0)
1610
                        continue;
1611
                }
1612

    
1613
                pkt = av_mallocz(sizeof(AVPacket));
1614
                /* XXX: prevent data copy... */
1615
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
1616
                    av_free(pkt);
1617
                    res = AVERROR(ENOMEM);
1618
                    n = laces-1;
1619
                    break;
1620
                }
1621
                if (offset)
1622
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
1623
                memcpy (pkt->data+offset, pkt_data, pkt_size);
1624

    
1625
                if (pkt_data != data)
1626
                    av_free(pkt_data);
1627

    
1628
                if (n == 0)
1629
                    pkt->flags = is_keyframe;
1630
                pkt->stream_index = st->index;
1631

    
1632
                pkt->pts = timecode;
1633
                pkt->pos = pos;
1634
                if (st->codec->codec_id == CODEC_ID_TEXT)
1635
                    pkt->convergence_duration = duration;
1636
                else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1637
                    pkt->duration = duration;
1638

    
1639
                if (st->codec->codec_id == CODEC_ID_SSA)
1640
                    matroska_fix_ass_packet(matroska, pkt, duration);
1641

    
1642
                if (matroska->prev_pkt &&
1643
                    timecode != AV_NOPTS_VALUE &&
1644
                    matroska->prev_pkt->pts == timecode &&
1645
                    matroska->prev_pkt->stream_index == st->index)
1646
                    matroska_merge_packets(matroska->prev_pkt, pkt);
1647
                else {
1648
                dynarray_add(&matroska->packets, &matroska->num_packets, pkt);
1649
                    matroska->prev_pkt = pkt;
1650
                }
1651
            }
1652

    
1653
            if (timecode != AV_NOPTS_VALUE)
1654
                timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1655
            data += lace_size[n];
1656
        }
1657
    }
1658

    
1659
    av_free(lace_size);
1660
    return res;
1661
}
1662

    
1663
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1664
{
1665
    MatroskaCluster cluster = { 0 };
1666
    EbmlList *blocks_list;
1667
    MatroskaBlock *blocks;
1668
    int i, res;
1669
    offset_t pos = url_ftell(matroska->ctx->pb);
1670
    matroska->prev_pkt = NULL;
1671
    if (matroska->has_cluster_id){
1672
        /* For the first cluster we parse, its ID was already read as
1673
           part of matroska_read_header(), so don't read it again */
1674
        res = ebml_parse_id(matroska, matroska_clusters,
1675
                            MATROSKA_ID_CLUSTER, &cluster);
1676
        pos -= 4;  /* sizeof the ID which was already read */
1677
        matroska->has_cluster_id = 0;
1678
    } else
1679
        res = ebml_parse(matroska, matroska_clusters, &cluster);
1680
    blocks_list = &cluster.blocks;
1681
    blocks = blocks_list->elem;
1682
    for (i=0; i<blocks_list->nb_elem; i++)
1683
        if (blocks[i].bin.size > 0)
1684
            res=matroska_parse_block(matroska,
1685
                                     blocks[i].bin.data, blocks[i].bin.size,
1686
                                     blocks[i].bin.pos,  cluster.timecode,
1687
                                     blocks[i].duration, !blocks[i].reference,
1688
                                     pos);
1689
    ebml_free(matroska_cluster, &cluster);
1690
    if (res < 0)  matroska->done = 1;
1691
    return res;
1692
}
1693

    
1694
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1695
{
1696
    MatroskaDemuxContext *matroska = s->priv_data;
1697

    
1698
    while (matroska_deliver_packet(matroska, pkt)) {
1699
        if (matroska->done)
1700
            return AVERROR(EIO);
1701
        matroska_parse_cluster(matroska);
1702
    }
1703

    
1704
    return 0;
1705
}
1706

    
1707
static int matroska_read_seek(AVFormatContext *s, int stream_index,
1708
                              int64_t timestamp, int flags)
1709
{
1710
    MatroskaDemuxContext *matroska = s->priv_data;
1711
    MatroskaTrack *tracks = matroska->tracks.elem;
1712
    AVStream *st = s->streams[stream_index];
1713
    int i, index, index_sub, index_min;
1714

    
1715
    if (!st->nb_index_entries)
1716
        return 0;
1717
    timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1718

    
1719
    if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1720
        url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1721
        while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1722
            matroska_clear_queue(matroska);
1723
            if (matroska_parse_cluster(matroska) < 0)
1724
                break;
1725
        }
1726
    }
1727

    
1728
    matroska_clear_queue(matroska);
1729
    if (index < 0)
1730
        return 0;
1731

    
1732
    index_min = index;
1733
    for (i=0; i < matroska->tracks.nb_elem; i++) {
1734
        tracks[i].end_timecode = 0;
1735
        if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1736
            && !tracks[i].stream->discard != AVDISCARD_ALL) {
1737
            index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1738
            if (index_sub >= 0
1739
                && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1740
                && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1741
                index_min = index_sub;
1742
        }
1743
    }
1744

    
1745
    url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
1746
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1747
    matroska->skip_to_timecode = st->index_entries[index].timestamp;
1748
    matroska->done = 0;
1749
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1750
    return 0;
1751
}
1752

    
1753
static int matroska_read_close(AVFormatContext *s)
1754
{
1755
    MatroskaDemuxContext *matroska = s->priv_data;
1756
    MatroskaTrack *tracks = matroska->tracks.elem;
1757
    int n;
1758

    
1759
    matroska_clear_queue(matroska);
1760

    
1761
    for (n=0; n < matroska->tracks.nb_elem; n++)
1762
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1763
            av_free(tracks[n].audio.buf);
1764
    ebml_free(matroska_segment, matroska);
1765

    
1766
    return 0;
1767
}
1768

    
1769
AVInputFormat matroska_demuxer = {
1770
    "matroska",
1771
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1772
    sizeof(MatroskaDemuxContext),
1773
    matroska_probe,
1774
    matroska_read_header,
1775
    matroska_read_packet,
1776
    matroska_read_close,
1777
    matroska_read_seek,
1778
};