~ubuntu-branches/debian/sid/gstreamer0.10-ffmpeg/sid

« back to all changes in this revision

Viewing changes to gst-libs/ext/ffmpeg/libavformat/matroskadec.c

  • Committer: Bazaar Package Importer
  • Author(s): Sebastian Dröge
  • Date: 2009-02-22 12:24:07 UTC
  • mfrom: (1.1.24 jaunty)
  • Revision ID: james.westby@ubuntu.com-20090222122407-nubojphrd84klmee
Tags: 0.10.6-3
Upload to unstable.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/*
2
 
 * Matroska file demuxer (no muxer yet)
3
 
 * Copyright (c) 2003-2004 The ffmpeg Project
 
2
 * Matroska file demuxer
 
3
 * Copyright (c) 2003-2008 The FFmpeg Project
4
4
 *
5
5
 * This file is part of FFmpeg.
6
6
 *
24
24
 * Matroska file demuxer
25
25
 * by Ronald Bultje <rbultje@ronald.bitfreak.net>
26
26
 * with a little help from Moritz Bunkus <moritz@bunkus.org>
27
 
 * Specs available on the matroska project page:
28
 
 * http://www.matroska.org/.
 
27
 * totally reworked by Aurelien Jacobs <aurel@gnuage.org>
 
28
 * Specs available on the Matroska project page: http://www.matroska.org/.
29
29
 */
30
30
 
 
31
#include <stdio.h>
31
32
#include "avformat.h"
32
33
/* For codec_get_id(). */
33
34
#include "riff.h"
34
 
#include "intfloat_readwrite.h"
 
35
#include "isom.h"
35
36
#include "matroska.h"
36
37
#include "libavcodec/mpeg4audio.h"
37
 
 
38
 
typedef struct Track {
39
 
    MatroskaTrackType type;
40
 
 
41
 
    /* Unique track number and track ID. stream_index is the index that
42
 
     * the calling app uses for this track. */
43
 
    uint32_t num;
44
 
    uint32_t uid;
45
 
    int stream_index;
46
 
 
47
 
    char *name;
48
 
    char language[4];
49
 
 
50
 
    char *codec_id;
51
 
    char *codec_name;
52
 
 
53
 
    unsigned char *codec_priv;
54
 
    int codec_priv_size;
55
 
 
 
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;
56
135
    uint64_t default_duration;
57
 
    MatroskaTrackFlags flags;
 
136
    uint64_t flag_default;
 
137
    MatroskaTrackVideo video;
 
138
    MatroskaTrackAudio audio;
 
139
    EbmlList encodings;
 
140
 
 
141
    AVStream *stream;
 
142
    int64_t end_timecode;
58
143
} MatroskaTrack;
59
144
 
60
 
typedef struct MatroskaVideoTrack {
61
 
    MatroskaTrack track;
62
 
 
63
 
    int pixel_width;
64
 
    int pixel_height;
65
 
    int display_width;
66
 
    int display_height;
67
 
 
68
 
    uint32_t fourcc;
69
 
 
70
 
    MatroskaAspectRatioMode ar_mode;
71
 
    MatroskaEyeMode eye_mode;
72
 
 
73
 
    //..
74
 
} MatroskaVideoTrack;
75
 
 
76
 
typedef struct MatroskaAudioTrack {
77
 
    MatroskaTrack track;
78
 
 
79
 
    int channels;
80
 
    int bitdepth;
81
 
    int internal_samplerate;
82
 
    int samplerate;
83
 
    int block_align;
84
 
 
85
 
    /* real audio header */
86
 
    int coded_framesize;
87
 
    int sub_packet_h;
88
 
    int frame_size;
89
 
    int sub_packet_size;
90
 
    int sub_packet_cnt;
91
 
    int pkt_cnt;
92
 
    uint8_t *buf;
93
 
    //..
94
 
} MatroskaAudioTrack;
95
 
 
96
 
typedef struct MatroskaSubtitleTrack {
97
 
    MatroskaTrack track;
98
 
    //..
99
 
} MatroskaSubtitleTrack;
100
 
 
101
 
#define MAX_TRACK_SIZE (FFMAX3(sizeof(MatroskaVideoTrack), \
102
 
                                    sizeof(MatroskaAudioTrack), \
103
 
                                    sizeof(MatroskaSubtitleTrack)))
104
 
 
105
 
typedef struct MatroskaLevel {
 
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 {
106
180
    uint64_t start;
107
181
    uint64_t length;
108
182
} MatroskaLevel;
109
183
 
110
 
typedef struct MatroskaDemuxIndex {
111
 
  uint64_t        pos;   /* of the corresponding *cluster*! */
112
 
  uint16_t        track; /* reference to 'num' */
113
 
  uint64_t        time;  /* in nanoseconds */
114
 
} MatroskaDemuxIndex;
115
 
 
116
 
typedef struct MatroskaDemuxContext {
 
184
typedef struct {
117
185
    AVFormatContext *ctx;
118
186
 
119
 
    /* ebml stuff */
 
187
    /* EBML stuff */
120
188
    int num_levels;
121
189
    MatroskaLevel levels[EBML_MAX_DEPTH];
122
190
    int level_up;
123
191
 
124
 
    /* matroska stuff */
125
 
    char *writing_app;
126
 
    char *muxing_app;
127
 
    int64_t created;
128
 
 
129
 
    /* timescale in the file */
130
 
    int64_t time_scale;
131
 
 
132
 
    /* num_streams is the number of streams that av_new_stream() was called
133
 
     * for ( = that are available to the calling program). */
134
 
    int num_tracks;
135
 
    int num_streams;
136
 
    MatroskaTrack *tracks[MAX_STREAMS];
137
 
 
138
 
    /* cache for ID peeking */
139
 
    uint32_t peek_id;
 
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;
140
201
 
141
202
    /* byte position of the segment inside the stream */
142
 
    offset_t segment_start;
 
203
    int64_t segment_start;
143
204
 
144
 
    /* The packet queue. */
 
205
    /* the packet queue */
145
206
    AVPacket **packets;
146
207
    int num_packets;
 
208
    AVPacket *prev_pkt;
147
209
 
148
 
    /* have we already parse metadata/cues/clusters? */
149
 
    int metadata_parsed;
150
 
    int index_parsed;
151
210
    int done;
152
 
 
153
 
    /* The index for seeking. */
154
 
    int num_indexes;
155
 
    MatroskaDemuxIndex *index;
 
211
    int has_cluster_id;
156
212
 
157
213
    /* What to skip before effectively reading a packet. */
158
214
    int skip_to_keyframe;
159
 
    AVStream *skip_to_stream;
 
215
    uint64_t skip_to_timecode;
160
216
} MatroskaDemuxContext;
161
217
 
162
 
/*
163
 
 * The first few functions handle EBML file parsing. The rest
164
 
 * is the document interpretation. Matroska really just is a
165
 
 * EBML file.
166
 
 */
167
 
 
168
 
/*
169
 
 * Return: the amount of levels in the hierarchy that the
170
 
 * current element lies higher than the previous one.
171
 
 * The opposite isn't done - that's auto-done using master
172
 
 * element reading.
173
 
 */
174
 
 
175
 
static int
176
 
ebml_read_element_level_up (MatroskaDemuxContext *matroska)
 
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
static EbmlSyntax ebml_header[] = {
 
230
    { EBML_ID_EBMLREADVERSION,        EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
 
231
    { EBML_ID_EBMLMAXSIZELENGTH,      EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
 
232
    { EBML_ID_EBMLMAXIDLENGTH,        EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
 
233
    { EBML_ID_DOCTYPE,                EBML_STR,  0, offsetof(Ebml,doctype), {.s="(none)"} },
 
234
    { EBML_ID_DOCTYPEREADVERSION,     EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
 
235
    { EBML_ID_EBMLVERSION,            EBML_NONE },
 
236
    { EBML_ID_DOCTYPEVERSION,         EBML_NONE },
 
237
    { 0 }
 
238
};
 
239
 
 
240
static EbmlSyntax ebml_syntax[] = {
 
241
    { EBML_ID_HEADER,                 EBML_NEST, 0, 0, {.n=ebml_header} },
 
242
    { 0 }
 
243
};
 
244
 
 
245
static EbmlSyntax matroska_info[] = {
 
246
    { MATROSKA_ID_TIMECODESCALE,      EBML_UINT,  0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
 
247
    { MATROSKA_ID_DURATION,           EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
 
248
    { MATROSKA_ID_TITLE,              EBML_UTF8,  0, offsetof(MatroskaDemuxContext,title) },
 
249
    { MATROSKA_ID_WRITINGAPP,         EBML_NONE },
 
250
    { MATROSKA_ID_MUXINGAPP,          EBML_NONE },
 
251
    { MATROSKA_ID_DATEUTC,            EBML_NONE },
 
252
    { MATROSKA_ID_SEGMENTUID,         EBML_NONE },
 
253
    { 0 }
 
254
};
 
255
 
 
256
static EbmlSyntax matroska_track_video[] = {
 
257
    { MATROSKA_ID_VIDEOFRAMERATE,     EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
 
258
    { MATROSKA_ID_VIDEODISPLAYWIDTH,  EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
 
259
    { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
 
260
    { MATROSKA_ID_VIDEOPIXELWIDTH,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
 
261
    { MATROSKA_ID_VIDEOPIXELHEIGHT,   EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
 
262
    { MATROSKA_ID_VIDEOCOLORSPACE,    EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
 
263
    { MATROSKA_ID_VIDEOPIXELCROPB,    EBML_NONE },
 
264
    { MATROSKA_ID_VIDEOPIXELCROPT,    EBML_NONE },
 
265
    { MATROSKA_ID_VIDEOPIXELCROPL,    EBML_NONE },
 
266
    { MATROSKA_ID_VIDEOPIXELCROPR,    EBML_NONE },
 
267
    { MATROSKA_ID_VIDEODISPLAYUNIT,   EBML_NONE },
 
268
    { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
 
269
    { MATROSKA_ID_VIDEOSTEREOMODE,    EBML_NONE },
 
270
    { MATROSKA_ID_VIDEOASPECTRATIO,   EBML_NONE },
 
271
    { 0 }
 
272
};
 
273
 
 
274
static EbmlSyntax matroska_track_audio[] = {
 
275
    { MATROSKA_ID_AUDIOSAMPLINGFREQ,  EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
 
276
    { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
 
277
    { MATROSKA_ID_AUDIOBITDEPTH,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
 
278
    { MATROSKA_ID_AUDIOCHANNELS,      EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
 
279
    { 0 }
 
280
};
 
281
 
 
282
static EbmlSyntax matroska_track_encoding_compression[] = {
 
283
    { MATROSKA_ID_ENCODINGCOMPALGO,   EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
 
284
    { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
 
285
    { 0 }
 
286
};
 
287
 
 
288
static EbmlSyntax matroska_track_encoding[] = {
 
289
    { MATROSKA_ID_ENCODINGSCOPE,      EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
 
290
    { MATROSKA_ID_ENCODINGTYPE,       EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
 
291
    { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
 
292
    { MATROSKA_ID_ENCODINGORDER,      EBML_NONE },
 
293
    { 0 }
 
294
};
 
295
 
 
296
static EbmlSyntax matroska_track_encodings[] = {
 
297
    { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
 
298
    { 0 }
 
299
};
 
300
 
 
301
static EbmlSyntax matroska_track[] = {
 
302
    { MATROSKA_ID_TRACKNUMBER,          EBML_UINT, 0, offsetof(MatroskaTrack,num) },
 
303
    { MATROSKA_ID_TRACKTYPE,            EBML_UINT, 0, offsetof(MatroskaTrack,type) },
 
304
    { MATROSKA_ID_CODECID,              EBML_STR,  0, offsetof(MatroskaTrack,codec_id) },
 
305
    { MATROSKA_ID_CODECPRIVATE,         EBML_BIN,  0, offsetof(MatroskaTrack,codec_priv) },
 
306
    { MATROSKA_ID_TRACKLANGUAGE,        EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
 
307
    { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
 
308
    { MATROSKA_ID_TRACKTIMECODESCALE,   EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
 
309
    { MATROSKA_ID_TRACKFLAGDEFAULT,     EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
 
310
    { MATROSKA_ID_TRACKVIDEO,           EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
 
311
    { MATROSKA_ID_TRACKAUDIO,           EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
 
312
    { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
 
313
    { MATROSKA_ID_TRACKUID,             EBML_NONE },
 
314
    { MATROSKA_ID_TRACKNAME,            EBML_NONE },
 
315
    { MATROSKA_ID_TRACKFLAGENABLED,     EBML_NONE },
 
316
    { MATROSKA_ID_TRACKFLAGFORCED,      EBML_NONE },
 
317
    { MATROSKA_ID_TRACKFLAGLACING,      EBML_NONE },
 
318
    { MATROSKA_ID_CODECNAME,            EBML_NONE },
 
319
    { MATROSKA_ID_CODECDECODEALL,       EBML_NONE },
 
320
    { MATROSKA_ID_CODECINFOURL,         EBML_NONE },
 
321
    { MATROSKA_ID_CODECDOWNLOADURL,     EBML_NONE },
 
322
    { MATROSKA_ID_TRACKMINCACHE,        EBML_NONE },
 
323
    { MATROSKA_ID_TRACKMAXCACHE,        EBML_NONE },
 
324
    { MATROSKA_ID_TRACKMAXBLKADDID,     EBML_NONE },
 
325
    { 0 }
 
326
};
 
327
 
 
328
static EbmlSyntax matroska_tracks[] = {
 
329
    { MATROSKA_ID_TRACKENTRY,         EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
 
330
    { 0 }
 
331
};
 
332
 
 
333
static EbmlSyntax matroska_attachment[] = {
 
334
    { MATROSKA_ID_FILENAME,           EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
 
335
    { MATROSKA_ID_FILEMIMETYPE,       EBML_STR,  0, offsetof(MatroskaAttachement,mime) },
 
336
    { MATROSKA_ID_FILEDATA,           EBML_BIN,  0, offsetof(MatroskaAttachement,bin) },
 
337
    { MATROSKA_ID_FILEDESC,           EBML_NONE },
 
338
    { MATROSKA_ID_FILEUID,            EBML_NONE },
 
339
    { 0 }
 
340
};
 
341
 
 
342
static EbmlSyntax matroska_attachments[] = {
 
343
    { MATROSKA_ID_ATTACHEDFILE,       EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
 
344
    { 0 }
 
345
};
 
346
 
 
347
static EbmlSyntax matroska_chapter_display[] = {
 
348
    { MATROSKA_ID_CHAPSTRING,         EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
 
349
    { MATROSKA_ID_CHAPLANG,           EBML_NONE },
 
350
    { 0 }
 
351
};
 
352
 
 
353
static EbmlSyntax matroska_chapter_entry[] = {
 
354
    { MATROSKA_ID_CHAPTERTIMESTART,   EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
 
355
    { MATROSKA_ID_CHAPTERTIMEEND,     EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
 
356
    { MATROSKA_ID_CHAPTERUID,         EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
 
357
    { MATROSKA_ID_CHAPTERDISPLAY,     EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
 
358
    { MATROSKA_ID_CHAPTERFLAGHIDDEN,  EBML_NONE },
 
359
    { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
 
360
    { MATROSKA_ID_CHAPTERPHYSEQUIV,   EBML_NONE },
 
361
    { MATROSKA_ID_CHAPTERATOM,        EBML_NONE },
 
362
    { 0 }
 
363
};
 
364
 
 
365
static EbmlSyntax matroska_chapter[] = {
 
366
    { MATROSKA_ID_CHAPTERATOM,        EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
 
367
    { MATROSKA_ID_EDITIONUID,         EBML_NONE },
 
368
    { MATROSKA_ID_EDITIONFLAGHIDDEN,  EBML_NONE },
 
369
    { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
 
370
    { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
 
371
    { 0 }
 
372
};
 
373
 
 
374
static EbmlSyntax matroska_chapters[] = {
 
375
    { MATROSKA_ID_EDITIONENTRY,       EBML_NEST, 0, 0, {.n=matroska_chapter} },
 
376
    { 0 }
 
377
};
 
378
 
 
379
static EbmlSyntax matroska_index_pos[] = {
 
380
    { MATROSKA_ID_CUETRACK,           EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
 
381
    { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos)   },
 
382
    { MATROSKA_ID_CUEBLOCKNUMBER,     EBML_NONE },
 
383
    { 0 }
 
384
};
 
385
 
 
386
static EbmlSyntax matroska_index_entry[] = {
 
387
    { MATROSKA_ID_CUETIME,            EBML_UINT, 0, offsetof(MatroskaIndex,time) },
 
388
    { MATROSKA_ID_CUETRACKPOSITION,   EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
 
389
    { 0 }
 
390
};
 
391
 
 
392
static EbmlSyntax matroska_index[] = {
 
393
    { MATROSKA_ID_POINTENTRY,         EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
 
394
    { 0 }
 
395
};
 
396
 
 
397
static EbmlSyntax matroska_simpletag[] = {
 
398
    { MATROSKA_ID_TAGNAME,            EBML_UTF8, 0, offsetof(MatroskaTag,name) },
 
399
    { MATROSKA_ID_TAGSTRING,          EBML_UTF8, 0, offsetof(MatroskaTag,string) },
 
400
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
 
401
    { MATROSKA_ID_TAGLANG,            EBML_NONE },
 
402
    { MATROSKA_ID_TAGDEFAULT,         EBML_NONE },
 
403
    { 0 }
 
404
};
 
405
 
 
406
static EbmlSyntax matroska_tag[] = {
 
407
    { MATROSKA_ID_SIMPLETAG,          EBML_NEST, sizeof(MatroskaTag), 0, {.n=matroska_simpletag} },
 
408
    { MATROSKA_ID_TAGTARGETS,         EBML_NONE },
 
409
    { 0 }
 
410
};
 
411
 
 
412
static EbmlSyntax matroska_tags[] = {
 
413
    { MATROSKA_ID_TAG,                EBML_NEST, 0, offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
 
414
    { 0 }
 
415
};
 
416
 
 
417
static EbmlSyntax matroska_seekhead_entry[] = {
 
418
    { MATROSKA_ID_SEEKID,             EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
 
419
    { MATROSKA_ID_SEEKPOSITION,       EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
 
420
    { 0 }
 
421
};
 
422
 
 
423
static EbmlSyntax matroska_seekhead[] = {
 
424
    { MATROSKA_ID_SEEKENTRY,          EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
 
425
    { 0 }
 
426
};
 
427
 
 
428
static EbmlSyntax matroska_segment[] = {
 
429
    { MATROSKA_ID_INFO,           EBML_NEST, 0, 0, {.n=matroska_info       } },
 
430
    { MATROSKA_ID_TRACKS,         EBML_NEST, 0, 0, {.n=matroska_tracks     } },
 
431
    { MATROSKA_ID_ATTACHMENTS,    EBML_NEST, 0, 0, {.n=matroska_attachments} },
 
432
    { MATROSKA_ID_CHAPTERS,       EBML_NEST, 0, 0, {.n=matroska_chapters   } },
 
433
    { MATROSKA_ID_CUES,           EBML_NEST, 0, 0, {.n=matroska_index      } },
 
434
    { MATROSKA_ID_TAGS,           EBML_NEST, 0, 0, {.n=matroska_tags       } },
 
435
    { MATROSKA_ID_SEEKHEAD,       EBML_NEST, 0, 0, {.n=matroska_seekhead   } },
 
436
    { MATROSKA_ID_CLUSTER,        EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
 
437
    { 0 }
 
438
};
 
439
 
 
440
static EbmlSyntax matroska_segments[] = {
 
441
    { MATROSKA_ID_SEGMENT,        EBML_NEST, 0, 0, {.n=matroska_segment    } },
 
442
    { 0 }
 
443
};
 
444
 
 
445
static EbmlSyntax matroska_blockgroup[] = {
 
446
    { MATROSKA_ID_BLOCK,          EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
 
447
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_BIN,  0, offsetof(MatroskaBlock,bin) },
 
448
    { MATROSKA_ID_BLOCKDURATION,  EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
 
449
    { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
 
450
    { 0 }
 
451
};
 
452
 
 
453
static EbmlSyntax matroska_cluster[] = {
 
454
    { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
 
455
    { MATROSKA_ID_BLOCKGROUP,     EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
 
456
    { MATROSKA_ID_SIMPLEBLOCK,    EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
 
457
    { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
 
458
    { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
 
459
    { 0 }
 
460
};
 
461
 
 
462
static EbmlSyntax matroska_clusters[] = {
 
463
    { MATROSKA_ID_CLUSTER,        EBML_NEST, 0, 0, {.n=matroska_cluster} },
 
464
    { MATROSKA_ID_INFO,           EBML_NONE },
 
465
    { MATROSKA_ID_CUES,           EBML_NONE },
 
466
    { MATROSKA_ID_TAGS,           EBML_NONE },
 
467
    { MATROSKA_ID_SEEKHEAD,       EBML_NONE },
 
468
    { 0 }
 
469
};
 
470
 
 
471
#define SIZE_OFF(x) sizeof(((AVFormatContext*)0)->x),offsetof(AVFormatContext,x)
 
472
const struct {
 
473
    const char name[16];
 
474
    int   size;
 
475
    int   offset;
 
476
} metadata[] = {
 
477
    { "TITLE",           SIZE_OFF(title)      },
 
478
    { "ARTIST",          SIZE_OFF(author)     },
 
479
    { "WRITTEN_BY",      SIZE_OFF(author)     },
 
480
    { "LEAD_PERFORMER",  SIZE_OFF(author)     },
 
481
    { "COPYRIGHT",       SIZE_OFF(copyright)  },
 
482
    { "COMMENT",         SIZE_OFF(comment)    },
 
483
    { "ALBUM",           SIZE_OFF(album)      },
 
484
    { "DATE_WRITTEN",    SIZE_OFF(year)       },
 
485
    { "DATE_RELEASED",   SIZE_OFF(year)       },
 
486
    { "PART_NUMBER",     SIZE_OFF(track)      },
 
487
    { "GENRE",           SIZE_OFF(genre)      },
 
488
};
 
489
 
 
490
/*
 
491
 * Return: Whether we reached the end of a level in the hierarchy or not.
 
492
 */
 
493
static int ebml_level_end(MatroskaDemuxContext *matroska)
177
494
{
178
495
    ByteIOContext *pb = matroska->ctx->pb;
179
 
    offset_t pos = url_ftell(pb);
180
 
    int num = 0;
 
496
    int64_t pos = url_ftell(pb);
181
497
 
182
 
    while (matroska->num_levels > 0) {
 
498
    if (matroska->num_levels > 0) {
183
499
        MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
184
 
 
185
 
        if (pos >= level->start + level->length) {
 
500
        if (pos - level->start >= level->length) {
186
501
            matroska->num_levels--;
187
 
            num++;
188
 
        } else {
189
 
            break;
 
502
            return 1;
190
503
        }
191
504
    }
192
 
 
193
 
    return num;
 
505
    return 0;
194
506
}
195
507
 
196
508
/*
199
511
 * number of 0-bits followed by a one. The position of the first
200
512
 * "one" bit inside the first byte indicates the length of this
201
513
 * number.
202
 
 * Returns: num. of bytes read. < 0 on error.
 
514
 * Returns: number of bytes read, < 0 on error
203
515
 */
204
 
 
205
 
static int
206
 
ebml_read_num (MatroskaDemuxContext *matroska,
207
 
               int                   max_size,
208
 
               uint64_t             *number)
 
516
static int ebml_read_num(MatroskaDemuxContext *matroska, ByteIOContext *pb,
 
517
                         int max_size, uint64_t *number)
209
518
{
210
 
    ByteIOContext *pb = matroska->ctx->pb;
211
519
    int len_mask = 0x80, read = 1, n = 1;
212
520
    int64_t total = 0;
213
521
 
214
 
    /* the first byte tells us the length in bytes - get_byte() can normally
 
522
    /* The first byte tells us the length in bytes - get_byte() can normally
215
523
     * return 0, but since that's not a valid first ebmlID byte, we can
216
524
     * use it safely here to catch EOS. */
217
525
    if (!(total = get_byte(pb))) {
218
526
        /* we might encounter EOS here */
219
527
        if (!url_feof(pb)) {
220
 
            offset_t pos = url_ftell(pb);
 
528
            int64_t pos = url_ftell(pb);
221
529
            av_log(matroska->ctx, AV_LOG_ERROR,
222
530
                   "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
223
531
                   pos, pos);
231
539
        len_mask >>= 1;
232
540
    }
233
541
    if (read > max_size) {
234
 
        offset_t pos = url_ftell(pb) - 1;
 
542
        int64_t pos = url_ftell(pb) - 1;
235
543
        av_log(matroska->ctx, AV_LOG_ERROR,
236
544
               "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
237
545
               (uint8_t) total, pos, pos);
249
557
}
250
558
 
251
559
/*
252
 
 * Read: the element content data ID.
253
 
 * Return: the number of bytes read or < 0 on error.
254
 
 */
255
 
 
256
 
static int
257
 
ebml_read_element_id (MatroskaDemuxContext *matroska,
258
 
                      uint32_t             *id,
259
 
                      int                  *level_up)
260
 
{
261
 
    int read;
262
 
    uint64_t total;
263
 
 
264
 
    /* if we re-call this, use our cached ID */
265
 
    if (matroska->peek_id != 0) {
266
 
        if (level_up)
267
 
            *level_up = 0;
268
 
        *id = matroska->peek_id;
269
 
        return 0;
270
 
    }
271
 
 
272
 
    /* read out the "EBML number", include tag in ID */
273
 
    if ((read = ebml_read_num(matroska, 4, &total)) < 0)
274
 
        return read;
275
 
    *id = matroska->peek_id  = total | (1 << (read * 7));
276
 
 
277
 
    /* level tracking */
278
 
    if (level_up)
279
 
        *level_up = ebml_read_element_level_up(matroska);
280
 
 
281
 
    return read;
282
 
}
283
 
 
284
 
/*
285
 
 * Read: element content length.
286
 
 * Return: the number of bytes read or < 0 on error.
287
 
 */
288
 
 
289
 
static int
290
 
ebml_read_element_length (MatroskaDemuxContext *matroska,
291
 
                          uint64_t             *length)
292
 
{
293
 
    /* clear cache since we're now beyond that data point */
294
 
    matroska->peek_id = 0;
295
 
 
296
 
    /* read out the "EBML number", include tag in ID */
297
 
    return ebml_read_num(matroska, 8, length);
298
 
}
299
 
 
300
 
/*
301
 
 * Return: the ID of the next element, or 0 on error.
302
 
 * Level_up contains the amount of levels that this
303
 
 * next element lies higher than the previous one.
304
 
 */
305
 
 
306
 
static uint32_t
307
 
ebml_peek_id (MatroskaDemuxContext *matroska,
308
 
              int                  *level_up)
309
 
{
310
 
    uint32_t id;
311
 
 
312
 
    if (ebml_read_element_id(matroska, &id, level_up) < 0)
313
 
        return 0;
314
 
 
315
 
    return id;
316
 
}
317
 
 
318
 
/*
319
 
 * Seek to a given offset.
320
 
 * 0 is success, -1 is failure.
321
 
 */
322
 
 
323
 
static int
324
 
ebml_read_seek (MatroskaDemuxContext *matroska,
325
 
                offset_t              offset)
326
 
{
327
 
    ByteIOContext *pb = matroska->ctx->pb;
328
 
 
329
 
    /* clear ID cache, if any */
330
 
    matroska->peek_id = 0;
331
 
 
332
 
    return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
333
 
}
334
 
 
335
 
/*
336
 
 * Skip the next element.
337
 
 * 0 is success, -1 is failure.
338
 
 */
339
 
 
340
 
static int
341
 
ebml_read_skip (MatroskaDemuxContext *matroska)
342
 
{
343
 
    ByteIOContext *pb = matroska->ctx->pb;
344
 
    uint32_t id;
345
 
    uint64_t length;
346
 
    int res;
347
 
 
348
 
    if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
349
 
        (res = ebml_read_element_length(matroska, &length)) < 0)
350
 
        return res;
351
 
 
352
 
    url_fskip(pb, length);
353
 
 
354
 
    return 0;
355
 
}
356
 
 
357
 
/*
358
560
 * Read the next element as an unsigned int.
359
561
 * 0 is success, < 0 is failure.
360
562
 */
361
 
 
362
 
static int
363
 
ebml_read_uint (MatroskaDemuxContext *matroska,
364
 
                uint32_t             *id,
365
 
                uint64_t             *num)
 
563
static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
366
564
{
367
 
    ByteIOContext *pb = matroska->ctx->pb;
368
 
    int n = 0, size, res;
369
 
    uint64_t rlength;
 
565
    int n = 0;
370
566
 
371
 
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
372
 
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
373
 
        return res;
374
 
    size = rlength;
375
 
    if (size < 1 || size > 8) {
376
 
        offset_t pos = url_ftell(pb);
377
 
        av_log(matroska->ctx, AV_LOG_ERROR,
378
 
               "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
379
 
                size, pos, pos);
 
567
    if (size < 1 || size > 8)
380
568
        return AVERROR_INVALIDDATA;
381
 
    }
382
569
 
383
 
    /* big-endian ordening; build up number */
 
570
    /* big-endian ordering; build up number */
384
571
    *num = 0;
385
572
    while (n++ < size)
386
573
        *num = (*num << 8) | get_byte(pb);
389
576
}
390
577
 
391
578
/*
392
 
 * Read the next element as a signed int.
393
 
 * 0 is success, < 0 is failure.
394
 
 */
395
 
 
396
 
static int
397
 
ebml_read_sint (MatroskaDemuxContext *matroska,
398
 
                uint32_t             *id,
399
 
                int64_t              *num)
400
 
{
401
 
    ByteIOContext *pb = matroska->ctx->pb;
402
 
    int size, n = 1, negative = 0, res;
403
 
    uint64_t rlength;
404
 
 
405
 
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
406
 
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
407
 
        return res;
408
 
    size = rlength;
409
 
    if (size < 1 || size > 8) {
410
 
        offset_t pos = url_ftell(pb);
411
 
        av_log(matroska->ctx, AV_LOG_ERROR,
412
 
               "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
413
 
                size, pos, pos);
414
 
        return AVERROR_INVALIDDATA;
415
 
    }
416
 
    if ((*num = get_byte(pb)) & 0x80) {
417
 
        negative = 1;
418
 
        *num &= ~0x80;
419
 
    }
420
 
    while (n++ < size)
421
 
        *num = (*num << 8) | get_byte(pb);
422
 
 
423
 
    /* make signed */
424
 
    if (negative)
425
 
        *num = *num - (1LL << ((8 * size) - 1));
426
 
 
427
 
    return 0;
428
 
}
429
 
 
430
 
/*
431
579
 * Read the next element as a float.
432
580
 * 0 is success, < 0 is failure.
433
581
 */
434
 
 
435
 
static int
436
 
ebml_read_float (MatroskaDemuxContext *matroska,
437
 
                 uint32_t             *id,
438
 
                 double               *num)
 
582
static int ebml_read_float(ByteIOContext *pb, int size, double *num)
439
583
{
440
 
    ByteIOContext *pb = matroska->ctx->pb;
441
 
    int size, res;
442
 
    uint64_t rlength;
443
 
 
444
 
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
445
 
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
446
 
        return res;
447
 
    size = rlength;
448
 
 
449
584
    if (size == 4) {
450
585
        *num= av_int2flt(get_be32(pb));
451
586
    } else if(size==8){
452
587
        *num= av_int2dbl(get_be64(pb));
453
 
    } else{
454
 
        offset_t pos = url_ftell(pb);
455
 
        av_log(matroska->ctx, AV_LOG_ERROR,
456
 
               "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
457
 
               size, pos, pos);
 
588
    } else
458
589
        return AVERROR_INVALIDDATA;
459
 
    }
460
590
 
461
591
    return 0;
462
592
}
465
595
 * Read the next element as an ASCII string.
466
596
 * 0 is success, < 0 is failure.
467
597
 */
468
 
 
469
 
static int
470
 
ebml_read_ascii (MatroskaDemuxContext *matroska,
471
 
                 uint32_t             *id,
472
 
                 char                **str)
 
598
static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
473
599
{
474
 
    ByteIOContext *pb = matroska->ctx->pb;
475
 
    int size, res;
476
 
    uint64_t rlength;
477
 
 
478
 
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
479
 
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
480
 
        return res;
481
 
    size = rlength;
482
 
 
483
 
    /* ebml strings are usually not 0-terminated, so we allocate one
 
600
    av_free(*str);
 
601
    /* EBML strings are usually not 0-terminated, so we allocate one
484
602
     * byte more, read the string and NULL-terminate it ourselves. */
485
 
    if (size < 0 || !(*str = av_malloc(size + 1))) {
486
 
        av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
 
603
    if (!(*str = av_malloc(size + 1)))
487
604
        return AVERROR(ENOMEM);
488
 
    }
489
605
    if (get_buffer(pb, (uint8_t *) *str, size) != size) {
490
 
        offset_t pos = url_ftell(pb);
491
 
        av_log(matroska->ctx, AV_LOG_ERROR,
492
 
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
 
606
        av_free(*str);
493
607
        return AVERROR(EIO);
494
608
    }
495
609
    (*str)[size] = '\0';
498
612
}
499
613
 
500
614
/*
501
 
 * Read the next element as a UTF-8 string.
502
 
 * 0 is success, < 0 is failure.
503
 
 */
504
 
 
505
 
static int
506
 
ebml_read_utf8 (MatroskaDemuxContext *matroska,
507
 
                uint32_t             *id,
508
 
                char                **str)
509
 
{
510
 
  return ebml_read_ascii(matroska, id, str);
511
 
}
512
 
 
513
 
/*
514
 
 * Read the next element as a date (nanoseconds since 1/1/2000).
515
 
 * 0 is success, < 0 is failure.
516
 
 */
517
 
 
518
 
static int
519
 
ebml_read_date (MatroskaDemuxContext *matroska,
520
 
                uint32_t             *id,
521
 
                int64_t              *date)
522
 
{
523
 
  return ebml_read_sint(matroska, id, date);
 
615
 * Read the next element as binary data.
 
616
 * 0 is success, < 0 is failure.
 
617
 */
 
618
static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
 
619
{
 
620
    av_free(bin->data);
 
621
    if (!(bin->data = av_malloc(length)))
 
622
        return AVERROR(ENOMEM);
 
623
 
 
624
    bin->size = length;
 
625
    bin->pos  = url_ftell(pb);
 
626
    if (get_buffer(pb, bin->data, length) != length)
 
627
        return AVERROR(EIO);
 
628
 
 
629
    return 0;
524
630
}
525
631
 
526
632
/*
528
634
 * are supposed to be sub-elements which can be read separately.
529
635
 * 0 is success, < 0 is failure.
530
636
 */
531
 
 
532
 
static int
533
 
ebml_read_master (MatroskaDemuxContext *matroska,
534
 
                  uint32_t             *id)
 
637
static int ebml_read_master(MatroskaDemuxContext *matroska, int length)
535
638
{
536
639
    ByteIOContext *pb = matroska->ctx->pb;
537
 
    uint64_t length;
538
640
    MatroskaLevel *level;
539
 
    int res;
540
 
 
541
 
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
542
 
        (res = ebml_read_element_length(matroska, &length)) < 0)
543
 
        return res;
544
 
 
545
 
    /* protect... (Heaven forbids that the '>' is true) */
 
641
 
546
642
    if (matroska->num_levels >= EBML_MAX_DEPTH) {
547
643
        av_log(matroska->ctx, AV_LOG_ERROR,
548
644
               "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
549
645
        return AVERROR(ENOSYS);
550
646
    }
551
647
 
552
 
    /* remember level */
553
648
    level = &matroska->levels[matroska->num_levels++];
554
649
    level->start = url_ftell(pb);
555
650
    level->length = length;
558
653
}
559
654
 
560
655
/*
561
 
 * Read the next element as binary data.
562
 
 * 0 is success, < 0 is failure.
563
 
 */
564
 
 
565
 
static int
566
 
ebml_read_binary (MatroskaDemuxContext *matroska,
567
 
                  uint32_t             *id,
568
 
                  uint8_t             **binary,
569
 
                  int                  *size)
570
 
{
571
 
    ByteIOContext *pb = matroska->ctx->pb;
572
 
    uint64_t rlength;
573
 
    int res;
574
 
 
575
 
    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
576
 
        (res = ebml_read_element_length(matroska, &rlength)) < 0)
577
 
        return res;
578
 
    *size = rlength;
579
 
 
580
 
    if (!(*binary = av_malloc(*size))) {
581
 
        av_log(matroska->ctx, AV_LOG_ERROR,
582
 
               "Memory allocation error\n");
583
 
        return AVERROR(ENOMEM);
584
 
    }
585
 
 
586
 
    if (get_buffer(pb, *binary, *size) != *size) {
587
 
        offset_t pos = url_ftell(pb);
588
 
        av_log(matroska->ctx, AV_LOG_ERROR,
589
 
               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
590
 
        return AVERROR(EIO);
591
 
    }
592
 
 
593
 
    return 0;
594
 
}
595
 
 
596
 
/*
597
656
 * Read signed/unsigned "EBML" numbers.
598
 
 * Return: number of bytes processed, < 0 on error.
599
 
 * XXX: use ebml_read_num().
 
657
 * Return: number of bytes processed, < 0 on error
600
658
 */
601
 
 
602
 
static int
603
 
matroska_ebmlnum_uint (uint8_t  *data,
604
 
                       uint32_t  size,
605
 
                       uint64_t *num)
 
659
static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
 
660
                                 uint8_t *data, uint32_t size, uint64_t *num)
606
661
{
607
 
    int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
608
 
    uint64_t total;
609
 
 
610
 
    if (size <= 0)
611
 
        return AVERROR_INVALIDDATA;
612
 
 
613
 
    total = data[0];
614
 
    while (read <= 8 && !(total & len_mask)) {
615
 
        read++;
616
 
        len_mask >>= 1;
617
 
    }
618
 
    if (read > 8)
619
 
        return AVERROR_INVALIDDATA;
620
 
 
621
 
    if ((total &= (len_mask - 1)) == len_mask - 1)
622
 
        num_ffs++;
623
 
    if (size < read)
624
 
        return AVERROR_INVALIDDATA;
625
 
    while (n < read) {
626
 
        if (data[n] == 0xff)
627
 
            num_ffs++;
628
 
        total = (total << 8) | data[n];
629
 
        n++;
630
 
    }
631
 
 
632
 
    if (read == num_ffs)
633
 
        *num = (uint64_t)-1;
634
 
    else
635
 
        *num = total;
636
 
 
637
 
    return read;
 
662
    ByteIOContext pb;
 
663
    init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
 
664
    return ebml_read_num(matroska, &pb, 8, num);
638
665
}
639
666
 
640
667
/*
641
668
 * Same as above, but signed.
642
669
 */
643
 
 
644
 
static int
645
 
matroska_ebmlnum_sint (uint8_t  *data,
646
 
                       uint32_t  size,
647
 
                       int64_t  *num)
 
670
static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
 
671
                                 uint8_t *data, uint32_t size, int64_t *num)
648
672
{
649
673
    uint64_t unum;
650
674
    int res;
651
675
 
652
676
    /* read as unsigned number first */
653
 
    if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
 
677
    if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
654
678
        return res;
655
679
 
656
680
    /* make signed (weird way) */
657
 
    if (unum == (uint64_t)-1)
658
 
        *num = INT64_MAX;
659
 
    else
660
 
        *num = unum - ((1LL << ((7 * res) - 1)) - 1);
 
681
    *num = unum - ((1LL << (7*res - 1)) - 1);
661
682
 
662
683
    return res;
663
684
}
664
685
 
665
 
/*
666
 
 * Read an EBML header.
667
 
 * 0 is success, < 0 is failure.
668
 
 */
669
 
 
670
 
static int
671
 
ebml_read_header (MatroskaDemuxContext *matroska,
672
 
                  char                **doctype,
673
 
                  int                  *version)
674
 
{
675
 
    uint32_t id;
676
 
    int level_up, res = 0;
677
 
 
678
 
    /* default init */
679
 
    if (doctype)
680
 
        *doctype = NULL;
681
 
    if (version)
682
 
        *version = 1;
683
 
 
684
 
    if (!(id = ebml_peek_id(matroska, &level_up)) ||
685
 
        level_up != 0 || id != EBML_ID_HEADER) {
686
 
        av_log(matroska->ctx, AV_LOG_ERROR,
687
 
               "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
688
 
        return AVERROR_INVALIDDATA;
689
 
    }
690
 
    if ((res = ebml_read_master(matroska, &id)) < 0)
691
 
        return res;
692
 
 
693
 
    while (res == 0) {
694
 
        if (!(id = ebml_peek_id(matroska, &level_up)))
695
 
            return AVERROR(EIO);
696
 
 
697
 
        /* end-of-header */
698
 
        if (level_up)
699
 
            break;
700
 
 
701
 
        switch (id) {
702
 
            /* is our read version uptodate? */
703
 
            case EBML_ID_EBMLREADVERSION: {
704
 
                uint64_t num;
705
 
 
706
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
707
 
                    return res;
708
 
                if (num > EBML_VERSION) {
709
 
                    av_log(matroska->ctx, AV_LOG_ERROR,
710
 
                           "EBML version %"PRIu64" (> %d) is not supported\n",
711
 
                           num, EBML_VERSION);
712
 
                    return AVERROR_INVALIDDATA;
713
 
                }
714
 
                break;
715
 
            }
716
 
 
717
 
            /* we only handle 8 byte lengths at max */
718
 
            case EBML_ID_EBMLMAXSIZELENGTH: {
719
 
                uint64_t num;
720
 
 
721
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
722
 
                    return res;
723
 
                if (num > sizeof(uint64_t)) {
724
 
                    av_log(matroska->ctx, AV_LOG_ERROR,
725
 
                           "Integers of size %"PRIu64" (> %zd) not supported\n",
726
 
                           num, sizeof(uint64_t));
727
 
                    return AVERROR_INVALIDDATA;
728
 
                }
729
 
                break;
730
 
            }
731
 
 
732
 
            /* we handle 4 byte IDs at max */
733
 
            case EBML_ID_EBMLMAXIDLENGTH: {
734
 
                uint64_t num;
735
 
 
736
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
737
 
                    return res;
738
 
                if (num > sizeof(uint32_t)) {
739
 
                    av_log(matroska->ctx, AV_LOG_ERROR,
740
 
                           "IDs of size %"PRIu64" (> %zu) not supported\n",
741
 
                            num, sizeof(uint32_t));
742
 
                    return AVERROR_INVALIDDATA;
743
 
                }
744
 
                break;
745
 
            }
746
 
 
747
 
            case EBML_ID_DOCTYPE: {
748
 
                char *text;
749
 
 
750
 
                if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
751
 
                    return res;
752
 
                if (doctype) {
753
 
                    if (*doctype)
754
 
                        av_free(*doctype);
755
 
                    *doctype = text;
756
 
                } else
757
 
                    av_free(text);
758
 
                break;
759
 
            }
760
 
 
761
 
            case EBML_ID_DOCTYPEREADVERSION: {
762
 
                uint64_t num;
763
 
 
764
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
765
 
                    return res;
766
 
                if (version)
767
 
                    *version = num;
768
 
                break;
769
 
            }
770
 
 
771
 
            default:
772
 
                av_log(matroska->ctx, AV_LOG_INFO,
773
 
                       "Unknown data type 0x%x in EBML header", id);
774
 
                /* pass-through */
775
 
 
776
 
            case EBML_ID_VOID:
777
 
            /* we ignore these two, as they don't tell us anything we
778
 
             * care about */
779
 
            case EBML_ID_EBMLVERSION:
780
 
            case EBML_ID_DOCTYPEVERSION:
781
 
                res = ebml_read_skip (matroska);
782
 
                break;
783
 
        }
784
 
    }
785
 
 
786
 
    return 0;
787
 
}
788
 
 
789
 
 
790
 
static int
791
 
matroska_find_track_by_num (MatroskaDemuxContext *matroska,
792
 
                            int                   num)
 
686
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
 
687
                           EbmlSyntax *syntax, void *data);
 
688
 
 
689
static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
 
690
                         uint32_t id, void *data)
793
691
{
794
692
    int i;
795
 
 
796
 
    for (i = 0; i < matroska->num_tracks; i++)
797
 
        if (matroska->tracks[i]->num == num)
798
 
            return i;
799
 
 
800
 
    return -1;
801
 
}
802
 
 
803
 
 
804
 
/*
805
 
 * Put one packet in an application-supplied AVPacket struct.
806
 
 * Returns 0 on success or -1 on failure.
807
 
 */
808
 
 
809
 
static int
810
 
matroska_deliver_packet (MatroskaDemuxContext *matroska,
811
 
                         AVPacket             *pkt)
812
 
{
813
 
    if (matroska->num_packets > 0) {
814
 
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
815
 
        av_free(matroska->packets[0]);
816
 
        if (matroska->num_packets > 1) {
817
 
            memmove(&matroska->packets[0], &matroska->packets[1],
818
 
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
819
 
            matroska->packets =
820
 
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
821
 
                           sizeof(AVPacket *));
822
 
        } else {
823
 
            av_freep(&matroska->packets);
824
 
        }
825
 
        matroska->num_packets--;
826
 
        return 0;
827
 
    }
828
 
 
829
 
    return -1;
830
 
}
831
 
 
832
 
/*
833
 
 * Put a packet into our internal queue. Will be delivered to the
834
 
 * user/application during the next get_packet() call.
835
 
 */
836
 
 
837
 
static void
838
 
matroska_queue_packet (MatroskaDemuxContext *matroska,
839
 
                       AVPacket             *pkt)
840
 
{
841
 
    matroska->packets =
842
 
        av_realloc(matroska->packets, (matroska->num_packets + 1) *
843
 
                   sizeof(AVPacket *));
844
 
    matroska->packets[matroska->num_packets] = pkt;
845
 
    matroska->num_packets++;
846
 
}
847
 
 
848
 
/*
849
 
 * Free all packets in our internal queue.
850
 
 */
851
 
static void
852
 
matroska_clear_queue (MatroskaDemuxContext *matroska)
853
 
{
854
 
    if (matroska->packets) {
855
 
        int n;
856
 
        for (n = 0; n < matroska->num_packets; n++) {
857
 
            av_free_packet(matroska->packets[n]);
858
 
            av_free(matroska->packets[n]);
859
 
        }
860
 
        av_free(matroska->packets);
861
 
        matroska->packets = NULL;
862
 
        matroska->num_packets = 0;
 
693
    for (i=0; syntax[i].id; i++)
 
694
        if (id == syntax[i].id)
 
695
            break;
 
696
    if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
 
697
        av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
 
698
    return ebml_parse_elem(matroska, &syntax[i], data);
 
699
}
 
700
 
 
701
static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
 
702
                      void *data)
 
703
{
 
704
    uint64_t id;
 
705
    int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
 
706
    id |= 1 << 7*res;
 
707
    return res < 0 ? res : ebml_parse_id(matroska, syntax, id, data);
 
708
}
 
709
 
 
710
static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
 
711
                           void *data)
 
712
{
 
713
    int i, res = 0;
 
714
 
 
715
    for (i=0; syntax[i].id; i++)
 
716
        switch (syntax[i].type) {
 
717
        case EBML_UINT:
 
718
            *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
 
719
            break;
 
720
        case EBML_FLOAT:
 
721
            *(double   *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
 
722
            break;
 
723
        case EBML_STR:
 
724
        case EBML_UTF8:
 
725
            *(char    **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
 
726
            break;
 
727
        }
 
728
 
 
729
    while (!res && !ebml_level_end(matroska))
 
730
        res = ebml_parse(matroska, syntax, data);
 
731
 
 
732
    return res;
 
733
}
 
734
 
 
735
static int ebml_parse_elem(MatroskaDemuxContext *matroska,
 
736
                           EbmlSyntax *syntax, void *data)
 
737
{
 
738
    ByteIOContext *pb = matroska->ctx->pb;
 
739
    uint32_t id = syntax->id;
 
740
    uint64_t length;
 
741
    int res;
 
742
 
 
743
    data = (char *)data + syntax->data_offset;
 
744
    if (syntax->list_elem_size) {
 
745
        EbmlList *list = data;
 
746
        list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
 
747
        data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
 
748
        memset(data, 0, syntax->list_elem_size);
 
749
        list->nb_elem++;
 
750
    }
 
751
 
 
752
    if (syntax->type != EBML_PASS && syntax->type != EBML_STOP)
 
753
        if ((res = ebml_read_num(matroska, pb, 8, &length)) < 0)
 
754
            return res;
 
755
 
 
756
    switch (syntax->type) {
 
757
    case EBML_UINT:  res = ebml_read_uint  (pb, length, data);  break;
 
758
    case EBML_FLOAT: res = ebml_read_float (pb, length, data);  break;
 
759
    case EBML_STR:
 
760
    case EBML_UTF8:  res = ebml_read_ascii (pb, length, data);  break;
 
761
    case EBML_BIN:   res = ebml_read_binary(pb, length, data);  break;
 
762
    case EBML_NEST:  if ((res=ebml_read_master(matroska, length)) < 0)
 
763
                         return res;
 
764
                     if (id == MATROSKA_ID_SEGMENT)
 
765
                         matroska->segment_start = url_ftell(matroska->ctx->pb);
 
766
                     return ebml_parse_nest(matroska, syntax->def.n, data);
 
767
    case EBML_PASS:  return ebml_parse_id(matroska, syntax->def.n, id, data);
 
768
    case EBML_STOP:  *(int *)data = 1;      return 1;
 
769
    default:         return url_fseek(pb,length,SEEK_CUR)<0 ? AVERROR(EIO) : 0;
 
770
    }
 
771
    if (res == AVERROR_INVALIDDATA)
 
772
        av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
 
773
    else if (res == AVERROR(EIO))
 
774
        av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
 
775
    return res;
 
776
}
 
777
 
 
778
static void ebml_free(EbmlSyntax *syntax, void *data)
 
779
{
 
780
    int i, j;
 
781
    for (i=0; syntax[i].id; i++) {
 
782
        void *data_off = (char *)data + syntax[i].data_offset;
 
783
        switch (syntax[i].type) {
 
784
        case EBML_STR:
 
785
        case EBML_UTF8:  av_freep(data_off);                      break;
 
786
        case EBML_BIN:   av_freep(&((EbmlBin *)data_off)->data);  break;
 
787
        case EBML_NEST:
 
788
            if (syntax[i].list_elem_size) {
 
789
                EbmlList *list = data_off;
 
790
                char *ptr = list->elem;
 
791
                for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
 
792
                    ebml_free(syntax[i].def.n, ptr);
 
793
                av_free(list->elem);
 
794
            } else
 
795
                ebml_free(syntax[i].def.n, data_off);
 
796
        default:  break;
 
797
        }
863
798
    }
864
799
}
865
800
 
867
802
/*
868
803
 * Autodetecting...
869
804
 */
870
 
 
871
 
static int
872
 
matroska_probe (AVProbeData *p)
 
805
static int matroska_probe(AVProbeData *p)
873
806
{
874
807
    uint64_t total = 0;
875
808
    int len_mask = 0x80, size = 1, n = 1;
876
 
    uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
 
809
    static const char probe_data[] = "matroska";
877
810
 
878
 
    /* ebml header? */
 
811
    /* EBML header? */
879
812
    if (AV_RB32(p->buf) != EBML_ID_HEADER)
880
813
        return 0;
881
814
 
891
824
    while (n < size)
892
825
        total = (total << 8) | p->buf[4 + n++];
893
826
 
894
 
    /* does the probe data contain the whole header? */
 
827
    /* Does the probe data contain the whole header? */
895
828
    if (p->buf_size < 4 + size + total)
896
829
      return 0;
897
830
 
898
 
    /* the header must contain the document type 'matroska'. For now,
 
831
    /* The header must contain the document type 'matroska'. For now,
899
832
     * we don't parse the whole header but simply check for the
900
833
     * availability of that array of characters inside the header.
901
834
     * Not fully fool-proof, but good enough. */
902
 
    for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
903
 
        if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
 
835
    for (n = 4+size; n <= 4+size+total-(sizeof(probe_data)-1); n++)
 
836
        if (!memcmp(p->buf+n, probe_data, sizeof(probe_data)-1))
904
837
            return AVPROBE_SCORE_MAX;
905
838
 
906
839
    return 0;
907
840
}
908
841
 
909
 
/*
910
 
 * From here on, it's all XML-style DTD stuff... Needs no comments.
911
 
 */
912
 
 
913
 
static int
914
 
matroska_parse_info (MatroskaDemuxContext *matroska)
915
 
{
916
 
    int res = 0;
917
 
    uint32_t id;
918
 
 
919
 
    av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
920
 
 
921
 
    while (res == 0) {
922
 
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
923
 
            res = AVERROR(EIO);
924
 
            break;
925
 
        } else if (matroska->level_up) {
926
 
            matroska->level_up--;
927
 
            break;
928
 
        }
929
 
 
930
 
        switch (id) {
931
 
            /* cluster timecode */
932
 
            case MATROSKA_ID_TIMECODESCALE: {
933
 
                uint64_t num;
934
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
935
 
                    break;
936
 
                matroska->time_scale = num;
937
 
                break;
938
 
            }
939
 
 
940
 
            case MATROSKA_ID_DURATION: {
941
 
                double num;
942
 
                if ((res = ebml_read_float(matroska, &id, &num)) < 0)
943
 
                    break;
944
 
                matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
945
 
                break;
946
 
            }
947
 
 
948
 
            case MATROSKA_ID_TITLE: {
949
 
                char *text;
950
 
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
951
 
                    break;
952
 
                strncpy(matroska->ctx->title, text,
953
 
                        sizeof(matroska->ctx->title)-1);
954
 
                av_free(text);
955
 
                break;
956
 
            }
957
 
 
958
 
            case MATROSKA_ID_WRITINGAPP: {
959
 
                char *text;
960
 
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
961
 
                    break;
962
 
                matroska->writing_app = text;
963
 
                break;
964
 
            }
965
 
 
966
 
            case MATROSKA_ID_MUXINGAPP: {
967
 
                char *text;
968
 
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
969
 
                    break;
970
 
                matroska->muxing_app = text;
971
 
                break;
972
 
            }
973
 
 
974
 
            case MATROSKA_ID_DATEUTC: {
975
 
                int64_t time;
976
 
                if ((res = ebml_read_date(matroska, &id, &time)) < 0)
977
 
                    break;
978
 
                matroska->created = time;
979
 
                break;
980
 
            }
981
 
 
982
 
            default:
983
 
                av_log(matroska->ctx, AV_LOG_INFO,
984
 
                       "Unknown entry 0x%x in info header\n", id);
985
 
                /* fall-through */
986
 
 
987
 
            case EBML_ID_VOID:
988
 
                res = ebml_read_skip(matroska);
989
 
                break;
990
 
        }
991
 
 
992
 
        if (matroska->level_up) {
993
 
            matroska->level_up--;
994
 
            break;
995
 
        }
996
 
    }
997
 
 
998
 
    return res;
999
 
}
1000
 
 
1001
 
static int
1002
 
matroska_add_stream (MatroskaDemuxContext *matroska)
1003
 
{
1004
 
    int res = 0;
1005
 
    uint32_t id;
1006
 
    MatroskaTrack *track;
1007
 
 
1008
 
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1009
 
 
1010
 
    /* Allocate a generic track. As soon as we know its type we'll realloc. */
1011
 
    track = av_mallocz(MAX_TRACK_SIZE);
1012
 
    matroska->num_tracks++;
1013
 
    strcpy(track->language, "eng");
1014
 
 
1015
 
    /* start with the master */
1016
 
    if ((res = ebml_read_master(matroska, &id)) < 0)
1017
 
        return res;
1018
 
 
1019
 
    /* try reading the trackentry headers */
1020
 
    while (res == 0) {
1021
 
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1022
 
            res = AVERROR(EIO);
1023
 
            break;
1024
 
        } else if (matroska->level_up > 0) {
1025
 
            matroska->level_up--;
1026
 
            break;
1027
 
        }
1028
 
 
1029
 
        switch (id) {
1030
 
            /* track number (unique stream ID) */
1031
 
            case MATROSKA_ID_TRACKNUMBER: {
1032
 
                uint64_t num;
1033
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1034
 
                    break;
1035
 
                track->num = num;
1036
 
                break;
1037
 
            }
1038
 
 
1039
 
            /* track UID (unique identifier) */
1040
 
            case MATROSKA_ID_TRACKUID: {
1041
 
                uint64_t num;
1042
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1043
 
                    break;
1044
 
                track->uid = num;
1045
 
                break;
1046
 
            }
1047
 
 
1048
 
            /* track type (video, audio, combined, subtitle, etc.) */
1049
 
            case MATROSKA_ID_TRACKTYPE: {
1050
 
                uint64_t num;
1051
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1052
 
                    break;
1053
 
                if (track->type && track->type != num) {
1054
 
                    av_log(matroska->ctx, AV_LOG_INFO,
1055
 
                           "More than one tracktype in an entry - skip\n");
1056
 
                    break;
1057
 
                }
1058
 
                track->type = num;
1059
 
 
1060
 
                switch (track->type) {
1061
 
                    case MATROSKA_TRACK_TYPE_VIDEO:
1062
 
                    case MATROSKA_TRACK_TYPE_AUDIO:
1063
 
                    case MATROSKA_TRACK_TYPE_SUBTITLE:
1064
 
                        break;
1065
 
                    case MATROSKA_TRACK_TYPE_COMPLEX:
1066
 
                    case MATROSKA_TRACK_TYPE_LOGO:
1067
 
                    case MATROSKA_TRACK_TYPE_CONTROL:
1068
 
                    default:
1069
 
                        av_log(matroska->ctx, AV_LOG_INFO,
1070
 
                               "Unknown or unsupported track type 0x%x\n",
1071
 
                               track->type);
1072
 
                        track->type = 0;
1073
 
                        break;
1074
 
                }
1075
 
                matroska->tracks[matroska->num_tracks - 1] = track;
1076
 
                break;
1077
 
            }
1078
 
 
1079
 
            /* tracktype specific stuff for video */
1080
 
            case MATROSKA_ID_TRACKVIDEO: {
1081
 
                MatroskaVideoTrack *videotrack;
1082
 
                if (!track->type)
1083
 
                    track->type = MATROSKA_TRACK_TYPE_VIDEO;
1084
 
                if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1085
 
                    av_log(matroska->ctx, AV_LOG_INFO,
1086
 
                           "video data in non-video track - ignoring\n");
1087
 
                    res = AVERROR_INVALIDDATA;
1088
 
                    break;
1089
 
                } else if ((res = ebml_read_master(matroska, &id)) < 0)
1090
 
                    break;
1091
 
                videotrack = (MatroskaVideoTrack *)track;
1092
 
 
1093
 
                while (res == 0) {
1094
 
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1095
 
                        res = AVERROR(EIO);
1096
 
                        break;
1097
 
                    } else if (matroska->level_up > 0) {
1098
 
                        matroska->level_up--;
1099
 
                        break;
1100
 
                    }
1101
 
 
1102
 
                    switch (id) {
1103
 
                        /* fixme, this should be one-up, but I get it here */
1104
 
                        case MATROSKA_ID_TRACKDEFAULTDURATION: {
1105
 
                            uint64_t num;
1106
 
                            if ((res = ebml_read_uint (matroska, &id,
1107
 
                                                       &num)) < 0)
1108
 
                                break;
1109
 
                            track->default_duration = num;
1110
 
                            break;
1111
 
                        }
1112
 
 
1113
 
                        /* video framerate */
1114
 
                        case MATROSKA_ID_VIDEOFRAMERATE: {
1115
 
                            double num;
1116
 
                            if ((res = ebml_read_float(matroska, &id,
1117
 
                                                       &num)) < 0)
1118
 
                                break;
1119
 
                            if (!track->default_duration)
1120
 
                                track->default_duration = 1000000000/num;
1121
 
                            break;
1122
 
                        }
1123
 
 
1124
 
                        /* width of the size to display the video at */
1125
 
                        case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1126
 
                            uint64_t num;
1127
 
                            if ((res = ebml_read_uint(matroska, &id,
1128
 
                                                      &num)) < 0)
1129
 
                                break;
1130
 
                            videotrack->display_width = num;
1131
 
                            break;
1132
 
                        }
1133
 
 
1134
 
                        /* height of the size to display the video at */
1135
 
                        case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1136
 
                            uint64_t num;
1137
 
                            if ((res = ebml_read_uint(matroska, &id,
1138
 
                                                      &num)) < 0)
1139
 
                                break;
1140
 
                            videotrack->display_height = num;
1141
 
                            break;
1142
 
                        }
1143
 
 
1144
 
                        /* width of the video in the file */
1145
 
                        case MATROSKA_ID_VIDEOPIXELWIDTH: {
1146
 
                            uint64_t num;
1147
 
                            if ((res = ebml_read_uint(matroska, &id,
1148
 
                                                      &num)) < 0)
1149
 
                                break;
1150
 
                            videotrack->pixel_width = num;
1151
 
                            break;
1152
 
                        }
1153
 
 
1154
 
                        /* height of the video in the file */
1155
 
                        case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1156
 
                            uint64_t num;
1157
 
                            if ((res = ebml_read_uint(matroska, &id,
1158
 
                                                      &num)) < 0)
1159
 
                                break;
1160
 
                            videotrack->pixel_height = num;
1161
 
                            break;
1162
 
                        }
1163
 
 
1164
 
                        /* whether the video is interlaced */
1165
 
                        case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1166
 
                            uint64_t num;
1167
 
                            if ((res = ebml_read_uint(matroska, &id,
1168
 
                                                      &num)) < 0)
1169
 
                                break;
1170
 
                            if (num)
1171
 
                                track->flags |=
1172
 
                                    MATROSKA_VIDEOTRACK_INTERLACED;
1173
 
                            else
1174
 
                                track->flags &=
1175
 
                                    ~MATROSKA_VIDEOTRACK_INTERLACED;
1176
 
                            break;
1177
 
                        }
1178
 
 
1179
 
                        /* stereo mode (whether the video has two streams,
1180
 
                         * where one is for the left eye and the other for
1181
 
                         * the right eye, which creates a 3D-like
1182
 
                         * effect) */
1183
 
                        case MATROSKA_ID_VIDEOSTEREOMODE: {
1184
 
                            uint64_t num;
1185
 
                            if ((res = ebml_read_uint(matroska, &id,
1186
 
                                                      &num)) < 0)
1187
 
                                break;
1188
 
                            if (num != MATROSKA_EYE_MODE_MONO &&
1189
 
                                num != MATROSKA_EYE_MODE_LEFT &&
1190
 
                                num != MATROSKA_EYE_MODE_RIGHT &&
1191
 
                                num != MATROSKA_EYE_MODE_BOTH) {
1192
 
                                av_log(matroska->ctx, AV_LOG_INFO,
1193
 
                                       "Ignoring unknown eye mode 0x%x\n",
1194
 
                                       (uint32_t) num);
1195
 
                                break;
1196
 
                            }
1197
 
                            videotrack->eye_mode = num;
1198
 
                            break;
1199
 
                        }
1200
 
 
1201
 
                        /* aspect ratio behaviour */
1202
 
                        case MATROSKA_ID_VIDEOASPECTRATIO: {
1203
 
                            uint64_t num;
1204
 
                            if ((res = ebml_read_uint(matroska, &id,
1205
 
                                                      &num)) < 0)
1206
 
                                break;
1207
 
                            if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1208
 
                                num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1209
 
                                num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1210
 
                                av_log(matroska->ctx, AV_LOG_INFO,
1211
 
                                       "Ignoring unknown aspect ratio 0x%x\n",
1212
 
                                       (uint32_t) num);
1213
 
                                break;
1214
 
                            }
1215
 
                            videotrack->ar_mode = num;
1216
 
                            break;
1217
 
                        }
1218
 
 
1219
 
                        /* colorspace (only matters for raw video)
1220
 
                         * fourcc */
1221
 
                        case MATROSKA_ID_VIDEOCOLORSPACE: {
1222
 
                            uint64_t num;
1223
 
                            if ((res = ebml_read_uint(matroska, &id,
1224
 
                                                      &num)) < 0)
1225
 
                                break;
1226
 
                            videotrack->fourcc = num;
1227
 
                            break;
1228
 
                        }
1229
 
 
1230
 
                        default:
1231
 
                            av_log(matroska->ctx, AV_LOG_INFO,
1232
 
                                   "Unknown video track header entry "
1233
 
                                   "0x%x - ignoring\n", id);
1234
 
                            /* pass-through */
1235
 
 
1236
 
                        case EBML_ID_VOID:
1237
 
                            res = ebml_read_skip(matroska);
1238
 
                            break;
1239
 
                    }
1240
 
 
1241
 
                    if (matroska->level_up) {
1242
 
                        matroska->level_up--;
1243
 
                        break;
1244
 
                    }
1245
 
                }
1246
 
                break;
1247
 
            }
1248
 
 
1249
 
            /* tracktype specific stuff for audio */
1250
 
            case MATROSKA_ID_TRACKAUDIO: {
1251
 
                MatroskaAudioTrack *audiotrack;
1252
 
                if (!track->type)
1253
 
                    track->type = MATROSKA_TRACK_TYPE_AUDIO;
1254
 
                if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1255
 
                    av_log(matroska->ctx, AV_LOG_INFO,
1256
 
                           "audio data in non-audio track - ignoring\n");
1257
 
                    res = AVERROR_INVALIDDATA;
1258
 
                    break;
1259
 
                } else if ((res = ebml_read_master(matroska, &id)) < 0)
1260
 
                    break;
1261
 
                audiotrack = (MatroskaAudioTrack *)track;
1262
 
                audiotrack->channels = 1;
1263
 
                audiotrack->samplerate = 8000;
1264
 
 
1265
 
                while (res == 0) {
1266
 
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1267
 
                        res = AVERROR(EIO);
1268
 
                        break;
1269
 
                    } else if (matroska->level_up > 0) {
1270
 
                        matroska->level_up--;
1271
 
                        break;
1272
 
                    }
1273
 
 
1274
 
                    switch (id) {
1275
 
                        /* samplerate */
1276
 
                        case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1277
 
                            double num;
1278
 
                            if ((res = ebml_read_float(matroska, &id,
1279
 
                                                       &num)) < 0)
1280
 
                                break;
1281
 
                            audiotrack->internal_samplerate =
1282
 
                            audiotrack->samplerate = num;
1283
 
                            break;
1284
 
                        }
1285
 
 
1286
 
                        case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1287
 
                            double num;
1288
 
                            if ((res = ebml_read_float(matroska, &id,
1289
 
                                                       &num)) < 0)
1290
 
                                break;
1291
 
                            audiotrack->samplerate = num;
1292
 
                            break;
1293
 
                        }
1294
 
 
1295
 
                            /* bitdepth */
1296
 
                        case MATROSKA_ID_AUDIOBITDEPTH: {
1297
 
                            uint64_t num;
1298
 
                            if ((res = ebml_read_uint(matroska, &id,
1299
 
                                                      &num)) < 0)
1300
 
                                break;
1301
 
                            audiotrack->bitdepth = num;
1302
 
                            break;
1303
 
                        }
1304
 
 
1305
 
                            /* channels */
1306
 
                        case MATROSKA_ID_AUDIOCHANNELS: {
1307
 
                            uint64_t num;
1308
 
                            if ((res = ebml_read_uint(matroska, &id,
1309
 
                                                      &num)) < 0)
1310
 
                                break;
1311
 
                            audiotrack->channels = num;
1312
 
                            break;
1313
 
                        }
1314
 
 
1315
 
                        default:
1316
 
                            av_log(matroska->ctx, AV_LOG_INFO,
1317
 
                                   "Unknown audio track header entry "
1318
 
                                   "0x%x - ignoring\n", id);
1319
 
                            /* pass-through */
1320
 
 
1321
 
                        case EBML_ID_VOID:
1322
 
                            res = ebml_read_skip(matroska);
1323
 
                            break;
1324
 
                    }
1325
 
 
1326
 
                    if (matroska->level_up) {
1327
 
                        matroska->level_up--;
1328
 
                        break;
1329
 
                    }
1330
 
                }
1331
 
                break;
1332
 
            }
1333
 
 
1334
 
                /* codec identifier */
1335
 
            case MATROSKA_ID_CODECID: {
1336
 
                char *text;
1337
 
                if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1338
 
                    break;
1339
 
                track->codec_id = text;
1340
 
                break;
1341
 
            }
1342
 
 
1343
 
                /* codec private data */
1344
 
            case MATROSKA_ID_CODECPRIVATE: {
1345
 
                uint8_t *data;
1346
 
                int size;
1347
 
                if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1348
 
                    break;
1349
 
                track->codec_priv = data;
1350
 
                track->codec_priv_size = size;
1351
 
                break;
1352
 
            }
1353
 
 
1354
 
                /* name of the codec */
1355
 
            case MATROSKA_ID_CODECNAME: {
1356
 
                char *text;
1357
 
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1358
 
                    break;
1359
 
                track->codec_name = text;
1360
 
                break;
1361
 
            }
1362
 
 
1363
 
                /* name of this track */
1364
 
            case MATROSKA_ID_TRACKNAME: {
1365
 
                char *text;
1366
 
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1367
 
                    break;
1368
 
                track->name = text;
1369
 
                break;
1370
 
            }
1371
 
 
1372
 
                /* language (matters for audio/subtitles, mostly) */
1373
 
            case MATROSKA_ID_TRACKLANGUAGE: {
1374
 
                char *text, *end;
1375
 
                if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1376
 
                    break;
1377
 
                if ((end = strchr(text, '-')))
1378
 
                    *end = '\0';
1379
 
                if (strlen(text) == 3)
1380
 
                    strcpy(track->language, text);
1381
 
                av_free(text);
1382
 
                break;
1383
 
            }
1384
 
 
1385
 
                /* whether this is actually used */
1386
 
            case MATROSKA_ID_TRACKFLAGENABLED: {
1387
 
                uint64_t num;
1388
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1389
 
                    break;
1390
 
                if (num)
1391
 
                    track->flags |= MATROSKA_TRACK_ENABLED;
1392
 
                else
1393
 
                    track->flags &= ~MATROSKA_TRACK_ENABLED;
1394
 
                break;
1395
 
            }
1396
 
 
1397
 
                /* whether it's the default for this track type */
1398
 
            case MATROSKA_ID_TRACKFLAGDEFAULT: {
1399
 
                uint64_t num;
1400
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1401
 
                    break;
1402
 
                if (num)
1403
 
                    track->flags |= MATROSKA_TRACK_DEFAULT;
1404
 
                else
1405
 
                    track->flags &= ~MATROSKA_TRACK_DEFAULT;
1406
 
                break;
1407
 
            }
1408
 
 
1409
 
                /* lacing (like MPEG, where blocks don't end/start on frame
1410
 
                 * boundaries) */
1411
 
            case MATROSKA_ID_TRACKFLAGLACING: {
1412
 
                uint64_t num;
1413
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1414
 
                    break;
1415
 
                if (num)
1416
 
                    track->flags |= MATROSKA_TRACK_LACING;
1417
 
                else
1418
 
                    track->flags &= ~MATROSKA_TRACK_LACING;
1419
 
                break;
1420
 
            }
1421
 
 
1422
 
                /* default length (in time) of one data block in this track */
1423
 
            case MATROSKA_ID_TRACKDEFAULTDURATION: {
1424
 
                uint64_t num;
1425
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1426
 
                    break;
1427
 
                track->default_duration = num;
1428
 
                break;
1429
 
            }
1430
 
 
1431
 
            default:
1432
 
                av_log(matroska->ctx, AV_LOG_INFO,
1433
 
                       "Unknown track header entry 0x%x - ignoring\n", id);
1434
 
                /* pass-through */
1435
 
 
1436
 
            case EBML_ID_VOID:
1437
 
            /* we ignore these because they're nothing useful. */
1438
 
            case MATROSKA_ID_CODECINFOURL:
1439
 
            case MATROSKA_ID_CODECDOWNLOADURL:
1440
 
            case MATROSKA_ID_TRACKMINCACHE:
1441
 
            case MATROSKA_ID_TRACKMAXCACHE:
1442
 
                res = ebml_read_skip(matroska);
1443
 
                break;
1444
 
        }
1445
 
 
1446
 
        if (matroska->level_up) {
1447
 
            matroska->level_up--;
1448
 
            break;
1449
 
        }
1450
 
    }
1451
 
 
1452
 
    return res;
1453
 
}
1454
 
 
1455
 
static int
1456
 
matroska_parse_tracks (MatroskaDemuxContext *matroska)
1457
 
{
1458
 
    int res = 0;
1459
 
    uint32_t id;
1460
 
 
1461
 
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1462
 
 
1463
 
    while (res == 0) {
1464
 
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1465
 
            res = AVERROR(EIO);
1466
 
            break;
1467
 
        } else if (matroska->level_up) {
1468
 
            matroska->level_up--;
1469
 
            break;
1470
 
        }
1471
 
 
1472
 
        switch (id) {
1473
 
            /* one track within the "all-tracks" header */
1474
 
            case MATROSKA_ID_TRACKENTRY:
1475
 
                res = matroska_add_stream(matroska);
1476
 
                break;
1477
 
 
1478
 
            default:
1479
 
                av_log(matroska->ctx, AV_LOG_INFO,
1480
 
                       "Unknown entry 0x%x in track header\n", id);
1481
 
                /* fall-through */
1482
 
 
1483
 
            case EBML_ID_VOID:
1484
 
                res = ebml_read_skip(matroska);
1485
 
                break;
1486
 
        }
1487
 
 
1488
 
        if (matroska->level_up) {
1489
 
            matroska->level_up--;
1490
 
            break;
1491
 
        }
1492
 
    }
1493
 
 
1494
 
    return res;
1495
 
}
1496
 
 
1497
 
static int
1498
 
matroska_parse_index (MatroskaDemuxContext *matroska)
1499
 
{
1500
 
    int res = 0;
1501
 
    uint32_t id;
1502
 
    MatroskaDemuxIndex idx;
1503
 
 
1504
 
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1505
 
 
1506
 
    while (res == 0) {
1507
 
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1508
 
            res = AVERROR(EIO);
1509
 
            break;
1510
 
        } else if (matroska->level_up) {
1511
 
            matroska->level_up--;
1512
 
            break;
1513
 
        }
1514
 
 
1515
 
        switch (id) {
1516
 
            /* one single index entry ('point') */
1517
 
            case MATROSKA_ID_POINTENTRY:
1518
 
                if ((res = ebml_read_master(matroska, &id)) < 0)
1519
 
                    break;
1520
 
 
1521
 
                /* in the end, we hope to fill one entry with a
1522
 
                 * timestamp, a file position and a tracknum */
1523
 
                idx.pos   = (uint64_t) -1;
1524
 
                idx.time  = (uint64_t) -1;
1525
 
                idx.track = (uint16_t) -1;
1526
 
 
1527
 
                while (res == 0) {
1528
 
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1529
 
                        res = AVERROR(EIO);
1530
 
                        break;
1531
 
                    } else if (matroska->level_up) {
1532
 
                        matroska->level_up--;
1533
 
                        break;
1534
 
                    }
1535
 
 
1536
 
                    switch (id) {
1537
 
                        /* one single index entry ('point') */
1538
 
                        case MATROSKA_ID_CUETIME: {
1539
 
                            uint64_t time;
1540
 
                            if ((res = ebml_read_uint(matroska, &id,
1541
 
                                                      &time)) < 0)
1542
 
                                break;
1543
 
                            idx.time = time * matroska->time_scale;
1544
 
                            break;
1545
 
                        }
1546
 
 
1547
 
                        /* position in the file + track to which it
1548
 
                         * belongs */
1549
 
                        case MATROSKA_ID_CUETRACKPOSITION:
1550
 
                            if ((res = ebml_read_master(matroska, &id)) < 0)
1551
 
                                break;
1552
 
 
1553
 
                            while (res == 0) {
1554
 
                                if (!(id = ebml_peek_id (matroska,
1555
 
                                                    &matroska->level_up))) {
1556
 
                                    res = AVERROR(EIO);
1557
 
                                    break;
1558
 
                                } else if (matroska->level_up) {
1559
 
                                    matroska->level_up--;
1560
 
                                    break;
1561
 
                                }
1562
 
 
1563
 
                                switch (id) {
1564
 
                                    /* track number */
1565
 
                                    case MATROSKA_ID_CUETRACK: {
1566
 
                                        uint64_t num;
1567
 
                                        if ((res = ebml_read_uint(matroska,
1568
 
                                                          &id, &num)) < 0)
1569
 
                                            break;
1570
 
                                        idx.track = num;
1571
 
                                        break;
1572
 
                                    }
1573
 
 
1574
 
                                        /* position in file */
1575
 
                                    case MATROSKA_ID_CUECLUSTERPOSITION: {
1576
 
                                        uint64_t num;
1577
 
                                        if ((res = ebml_read_uint(matroska,
1578
 
                                                          &id, &num)) < 0)
1579
 
                                            break;
1580
 
                                        idx.pos = num+matroska->segment_start;
1581
 
                                        break;
1582
 
                                    }
1583
 
 
1584
 
                                    default:
1585
 
                                        av_log(matroska->ctx, AV_LOG_INFO,
1586
 
                                               "Unknown entry 0x%x in "
1587
 
                                               "CuesTrackPositions\n", id);
1588
 
                                        /* fall-through */
1589
 
 
1590
 
                                    case EBML_ID_VOID:
1591
 
                                        res = ebml_read_skip(matroska);
1592
 
                                        break;
1593
 
                                }
1594
 
 
1595
 
                                if (matroska->level_up) {
1596
 
                                    matroska->level_up--;
1597
 
                                    break;
1598
 
                                }
1599
 
                            }
1600
 
 
1601
 
                            break;
1602
 
 
1603
 
                        default:
1604
 
                            av_log(matroska->ctx, AV_LOG_INFO,
1605
 
                                   "Unknown entry 0x%x in cuespoint "
1606
 
                                   "index\n", id);
1607
 
                            /* fall-through */
1608
 
 
1609
 
                        case EBML_ID_VOID:
1610
 
                            res = ebml_read_skip(matroska);
1611
 
                            break;
1612
 
                    }
1613
 
 
1614
 
                    if (matroska->level_up) {
1615
 
                        matroska->level_up--;
1616
 
                        break;
1617
 
                    }
1618
 
                }
1619
 
 
1620
 
                /* so let's see if we got what we wanted */
1621
 
                if (idx.pos   != (uint64_t) -1 &&
1622
 
                    idx.time  != (uint64_t) -1 &&
1623
 
                    idx.track != (uint16_t) -1) {
1624
 
                    if (matroska->num_indexes % 32 == 0) {
1625
 
                        /* re-allocate bigger index */
1626
 
                        matroska->index =
1627
 
                            av_realloc(matroska->index,
1628
 
                                       (matroska->num_indexes + 32) *
1629
 
                                       sizeof(MatroskaDemuxIndex));
1630
 
                    }
1631
 
                    matroska->index[matroska->num_indexes] = idx;
1632
 
                    matroska->num_indexes++;
1633
 
                }
1634
 
                break;
1635
 
 
1636
 
            default:
1637
 
                av_log(matroska->ctx, AV_LOG_INFO,
1638
 
                       "Unknown entry 0x%x in cues header\n", id);
1639
 
                /* fall-through */
1640
 
 
1641
 
            case EBML_ID_VOID:
1642
 
                res = ebml_read_skip(matroska);
1643
 
                break;
1644
 
        }
1645
 
 
1646
 
        if (matroska->level_up) {
1647
 
            matroska->level_up--;
1648
 
            break;
1649
 
        }
1650
 
    }
1651
 
 
1652
 
    return res;
1653
 
}
1654
 
 
1655
 
static int
1656
 
matroska_parse_metadata (MatroskaDemuxContext *matroska)
1657
 
{
1658
 
    int res = 0;
1659
 
    uint32_t id;
1660
 
 
1661
 
    while (res == 0) {
1662
 
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1663
 
            res = AVERROR(EIO);
1664
 
            break;
1665
 
        } else if (matroska->level_up) {
1666
 
            matroska->level_up--;
1667
 
            break;
1668
 
        }
1669
 
 
1670
 
        switch (id) {
1671
 
            /* Hm, this is unsupported... */
1672
 
            default:
1673
 
                av_log(matroska->ctx, AV_LOG_INFO,
1674
 
                       "Unknown entry 0x%x in metadata header\n", id);
1675
 
                /* fall-through */
1676
 
 
1677
 
            case EBML_ID_VOID:
1678
 
                res = ebml_read_skip(matroska);
1679
 
                break;
1680
 
        }
1681
 
 
1682
 
        if (matroska->level_up) {
1683
 
            matroska->level_up--;
1684
 
            break;
1685
 
        }
1686
 
    }
1687
 
 
1688
 
    return res;
1689
 
}
1690
 
 
1691
 
static int
1692
 
matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1693
 
{
1694
 
    int res = 0;
1695
 
    uint32_t id;
1696
 
 
1697
 
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1698
 
 
1699
 
    while (res == 0) {
1700
 
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1701
 
            res = AVERROR(EIO);
1702
 
            break;
1703
 
        } else if (matroska->level_up) {
1704
 
            matroska->level_up--;
1705
 
            break;
1706
 
        }
1707
 
 
1708
 
        switch (id) {
1709
 
            case MATROSKA_ID_SEEKENTRY: {
1710
 
                uint32_t seek_id = 0, peek_id_cache = 0;
1711
 
                uint64_t seek_pos = (uint64_t) -1, t;
1712
 
 
1713
 
                if ((res = ebml_read_master(matroska, &id)) < 0)
1714
 
                    break;
1715
 
 
1716
 
                while (res == 0) {
1717
 
                    if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1718
 
                        res = AVERROR(EIO);
1719
 
                        break;
1720
 
                    } else if (matroska->level_up) {
1721
 
                        matroska->level_up--;
1722
 
                        break;
1723
 
                    }
1724
 
 
1725
 
                    switch (id) {
1726
 
                        case MATROSKA_ID_SEEKID:
1727
 
                            res = ebml_read_uint(matroska, &id, &t);
1728
 
                            seek_id = t;
1729
 
                            break;
1730
 
 
1731
 
                        case MATROSKA_ID_SEEKPOSITION:
1732
 
                            res = ebml_read_uint(matroska, &id, &seek_pos);
1733
 
                            break;
1734
 
 
1735
 
                        default:
1736
 
                            av_log(matroska->ctx, AV_LOG_INFO,
1737
 
                                   "Unknown seekhead ID 0x%x\n", id);
1738
 
                            /* fall-through */
1739
 
 
1740
 
                        case EBML_ID_VOID:
1741
 
                            res = ebml_read_skip(matroska);
1742
 
                            break;
1743
 
                    }
1744
 
 
1745
 
                    if (matroska->level_up) {
1746
 
                        matroska->level_up--;
1747
 
                        break;
1748
 
                    }
1749
 
                }
1750
 
 
1751
 
                if (!seek_id || seek_pos == (uint64_t) -1) {
1752
 
                    av_log(matroska->ctx, AV_LOG_INFO,
1753
 
                           "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1754
 
                           seek_id, seek_pos);
1755
 
                    break;
1756
 
                }
1757
 
 
1758
 
                switch (seek_id) {
1759
 
                    case MATROSKA_ID_CUES:
1760
 
                    case MATROSKA_ID_TAGS: {
1761
 
                        uint32_t level_up = matroska->level_up;
1762
 
                        offset_t before_pos;
1763
 
                        uint64_t length;
1764
 
                        MatroskaLevel level;
1765
 
 
1766
 
                        /* remember the peeked ID and the current position */
1767
 
                        peek_id_cache = matroska->peek_id;
1768
 
                        before_pos = url_ftell(matroska->ctx->pb);
1769
 
 
1770
 
                        /* seek */
1771
 
                        if ((res = ebml_read_seek(matroska, seek_pos +
1772
 
                                               matroska->segment_start)) < 0)
1773
 
                            return res;
1774
 
 
1775
 
                        /* we don't want to lose our seekhead level, so we add
1776
 
                         * a dummy. This is a crude hack. */
1777
 
                        if (matroska->num_levels == EBML_MAX_DEPTH) {
1778
 
                            av_log(matroska->ctx, AV_LOG_INFO,
1779
 
                                   "Max EBML element depth (%d) reached, "
1780
 
                                   "cannot parse further.\n", EBML_MAX_DEPTH);
1781
 
                            return AVERROR_UNKNOWN;
1782
 
                        }
1783
 
 
1784
 
                        level.start = 0;
1785
 
                        level.length = (uint64_t)-1;
1786
 
                        matroska->levels[matroska->num_levels] = level;
1787
 
                        matroska->num_levels++;
1788
 
 
1789
 
                        /* check ID */
1790
 
                        if (!(id = ebml_peek_id (matroska,
1791
 
                                                 &matroska->level_up)))
1792
 
                            goto finish;
1793
 
                        if (id != seek_id) {
1794
 
                            av_log(matroska->ctx, AV_LOG_INFO,
1795
 
                                   "We looked for ID=0x%x but got "
1796
 
                                   "ID=0x%x (pos=%"PRIu64")",
1797
 
                                   seek_id, id, seek_pos +
1798
 
                                   matroska->segment_start);
1799
 
                            goto finish;
1800
 
                        }
1801
 
 
1802
 
                        /* read master + parse */
1803
 
                        if ((res = ebml_read_master(matroska, &id)) < 0)
1804
 
                            goto finish;
1805
 
                        switch (id) {
1806
 
                            case MATROSKA_ID_CUES:
1807
 
                                if (!(res = matroska_parse_index(matroska)) ||
1808
 
                                    url_feof(matroska->ctx->pb)) {
1809
 
                                    matroska->index_parsed = 1;
1810
 
                                    res = 0;
1811
 
                                }
1812
 
                                break;
1813
 
                            case MATROSKA_ID_TAGS:
1814
 
                                if (!(res = matroska_parse_metadata(matroska)) ||
1815
 
                                   url_feof(matroska->ctx->pb)) {
1816
 
                                    matroska->metadata_parsed = 1;
1817
 
                                    res = 0;
1818
 
                                }
1819
 
                                break;
1820
 
                        }
1821
 
 
1822
 
                    finish:
1823
 
                        /* remove dummy level */
1824
 
                        while (matroska->num_levels) {
1825
 
                            matroska->num_levels--;
1826
 
                            length =
1827
 
                                matroska->levels[matroska->num_levels].length;
1828
 
                            if (length == (uint64_t)-1)
1829
 
                                break;
1830
 
                        }
1831
 
 
1832
 
                        /* seek back */
1833
 
                        if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1834
 
                            return res;
1835
 
                        matroska->peek_id = peek_id_cache;
1836
 
                        matroska->level_up = level_up;
1837
 
                        break;
1838
 
                    }
1839
 
 
1840
 
                    default:
1841
 
                        av_log(matroska->ctx, AV_LOG_INFO,
1842
 
                               "Ignoring seekhead entry for ID=0x%x\n",
1843
 
                               seek_id);
1844
 
                        break;
1845
 
                }
1846
 
 
1847
 
                break;
1848
 
            }
1849
 
 
1850
 
            default:
1851
 
                av_log(matroska->ctx, AV_LOG_INFO,
1852
 
                       "Unknown seekhead ID 0x%x\n", id);
1853
 
                /* fall-through */
1854
 
 
1855
 
            case EBML_ID_VOID:
1856
 
                res = ebml_read_skip(matroska);
1857
 
                break;
1858
 
        }
1859
 
 
1860
 
        if (matroska->level_up) {
1861
 
            matroska->level_up--;
1862
 
            break;
1863
 
        }
1864
 
    }
1865
 
 
1866
 
    return res;
1867
 
}
1868
 
 
1869
 
static int
1870
 
matroska_parse_attachments(AVFormatContext *s)
1871
 
{
1872
 
    MatroskaDemuxContext *matroska = s->priv_data;
1873
 
    int res = 0;
1874
 
    uint32_t id;
1875
 
 
1876
 
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing attachments...\n");
1877
 
 
1878
 
    while (res == 0) {
1879
 
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1880
 
            res = AVERROR(EIO);
1881
 
            break;
1882
 
        } else if (matroska->level_up) {
1883
 
            matroska->level_up--;
1884
 
            break;
1885
 
        }
1886
 
 
1887
 
        switch (id) {
1888
 
        case MATROSKA_ID_ATTACHEDFILE: {
1889
 
            char* name = NULL;
1890
 
            char* mime = NULL;
1891
 
            uint8_t* data = NULL;
1892
 
            int i, data_size = 0;
1893
 
            AVStream *st;
1894
 
 
1895
 
            if ((res = ebml_read_master(matroska, &id)) < 0)
1896
 
                break;
1897
 
 
1898
 
            while (res == 0) {
1899
 
                if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1900
 
                    res = AVERROR(EIO);
1901
 
                    break;
1902
 
                } else if (matroska->level_up) {
1903
 
                    matroska->level_up--;
1904
 
                    break;
1905
 
                }
1906
 
 
1907
 
                switch (id) {
1908
 
                case MATROSKA_ID_FILENAME:
1909
 
                    res = ebml_read_utf8 (matroska, &id, &name);
1910
 
                    break;
1911
 
 
1912
 
                case MATROSKA_ID_FILEMIMETYPE:
1913
 
                    res = ebml_read_ascii (matroska, &id, &mime);
1914
 
                    break;
1915
 
 
1916
 
                case MATROSKA_ID_FILEDATA:
1917
 
                    res = ebml_read_binary(matroska, &id, &data, &data_size);
1918
 
                    break;
1919
 
 
1920
 
                default:
1921
 
                    av_log(matroska->ctx, AV_LOG_INFO,
1922
 
                           "Unknown attachedfile ID 0x%x\n", id);
1923
 
                case EBML_ID_VOID:
1924
 
                    res = ebml_read_skip(matroska);
1925
 
                    break;
1926
 
                }
1927
 
 
1928
 
                if (matroska->level_up) {
1929
 
                    matroska->level_up--;
1930
 
                    break;
1931
 
                }
1932
 
            }
1933
 
 
1934
 
            if (!(name && mime && data && data_size > 0)) {
1935
 
                av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1936
 
                break;
1937
 
            }
1938
 
 
1939
 
            st = av_new_stream(s, matroska->num_streams++);
1940
 
            if (st == NULL)
1941
 
                return AVERROR(ENOMEM);
1942
 
            st->filename = av_strdup(name);
1943
 
            st->codec->codec_id = CODEC_ID_NONE;
1944
 
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1945
 
            st->codec->extradata = av_malloc(data_size);
1946
 
            if(st->codec->extradata == NULL)
1947
 
                return AVERROR(ENOMEM);
1948
 
            st->codec->extradata_size = data_size;
1949
 
            memcpy(st->codec->extradata, data, data_size);
1950
 
 
1951
 
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1952
 
                if (!strncmp(ff_mkv_mime_tags[i].str, mime,
1953
 
                             strlen(ff_mkv_mime_tags[i].str))) {
1954
 
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
1955
 
                    break;
1956
 
                }
1957
 
            }
1958
 
 
1959
 
            av_log(matroska->ctx, AV_LOG_DEBUG, "new attachment: %s, %s, size %d \n", name, mime, data_size);
1960
 
            break;
1961
 
        }
1962
 
 
1963
 
        default:
 
842
static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
 
843
                                                 int num)
 
844
{
 
845
    MatroskaTrack *tracks = matroska->tracks.elem;
 
846
    int i;
 
847
 
 
848
    for (i=0; i < matroska->tracks.nb_elem; i++)
 
849
        if (tracks[i].num == num)
 
850
            return &tracks[i];
 
851
 
 
852
    av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
 
853
    return NULL;
 
854
}
 
855
 
 
856
static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
 
857
                                  MatroskaTrack *track)
 
858
{
 
859
    MatroskaTrackEncoding *encodings = track->encodings.elem;
 
860
    uint8_t* data = *buf;
 
861
    int isize = *buf_size;
 
862
    uint8_t* pkt_data = NULL;
 
863
    int pkt_size = isize;
 
864
    int result = 0;
 
865
    int olen;
 
866
 
 
867
    switch (encodings[0].compression.algo) {
 
868
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
 
869
        return encodings[0].compression.settings.size;
 
870
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
 
871
        do {
 
872
            olen = pkt_size *= 3;
 
873
            pkt_data = av_realloc(pkt_data,
 
874
                                  pkt_size+LZO_OUTPUT_PADDING);
 
875
            result = lzo1x_decode(pkt_data, &olen, data, &isize);
 
876
        } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
 
877
        if (result)
 
878
            goto failed;
 
879
        pkt_size -= olen;
 
880
        break;
 
881
#ifdef CONFIG_ZLIB
 
882
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
 
883
        z_stream zstream = {0};
 
884
        if (inflateInit(&zstream) != Z_OK)
 
885
            return -1;
 
886
        zstream.next_in = data;
 
887
        zstream.avail_in = isize;
 
888
        do {
 
889
            pkt_size *= 3;
 
890
            pkt_data = av_realloc(pkt_data, pkt_size);
 
891
            zstream.avail_out = pkt_size - zstream.total_out;
 
892
            zstream.next_out = pkt_data + zstream.total_out;
 
893
            result = inflate(&zstream, Z_NO_FLUSH);
 
894
        } while (result==Z_OK && pkt_size<10000000);
 
895
        pkt_size = zstream.total_out;
 
896
        inflateEnd(&zstream);
 
897
        if (result != Z_STREAM_END)
 
898
            goto failed;
 
899
        break;
 
900
    }
 
901
#endif
 
902
#ifdef CONFIG_BZLIB
 
903
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
 
904
        bz_stream bzstream = {0};
 
905
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
 
906
            return -1;
 
907
        bzstream.next_in = data;
 
908
        bzstream.avail_in = isize;
 
909
        do {
 
910
            pkt_size *= 3;
 
911
            pkt_data = av_realloc(pkt_data, pkt_size);
 
912
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
 
913
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
 
914
            result = BZ2_bzDecompress(&bzstream);
 
915
        } while (result==BZ_OK && pkt_size<10000000);
 
916
        pkt_size = bzstream.total_out_lo32;
 
917
        BZ2_bzDecompressEnd(&bzstream);
 
918
        if (result != BZ_STREAM_END)
 
919
            goto failed;
 
920
        break;
 
921
    }
 
922
#endif
 
923
    default:
 
924
        return -1;
 
925
    }
 
926
 
 
927
    *buf = pkt_data;
 
928
    *buf_size = pkt_size;
 
929
    return 0;
 
930
 failed:
 
931
    av_free(pkt_data);
 
932
    return -1;
 
933
}
 
934
 
 
935
static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
 
936
                                    AVPacket *pkt, uint64_t display_duration)
 
937
{
 
938
    char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
 
939
    for (; *ptr!=',' && ptr<end-1; ptr++);
 
940
    if (*ptr == ',')
 
941
        layer = ++ptr;
 
942
    for (; *ptr!=',' && ptr<end-1; ptr++);
 
943
    if (*ptr == ',') {
 
944
        int64_t end_pts = pkt->pts + display_duration;
 
945
        int sc = matroska->time_scale * pkt->pts / 10000000;
 
946
        int ec = matroska->time_scale * end_pts  / 10000000;
 
947
        int sh, sm, ss, eh, em, es, len;
 
948
        sh = sc/360000;  sc -= 360000*sh;
 
949
        sm = sc/  6000;  sc -=   6000*sm;
 
950
        ss = sc/   100;  sc -=    100*ss;
 
951
        eh = ec/360000;  ec -= 360000*eh;
 
952
        em = ec/  6000;  ec -=   6000*em;
 
953
        es = ec/   100;  ec -=    100*es;
 
954
        *ptr++ = '\0';
 
955
        len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
 
956
        if (!(line = av_malloc(len)))
 
957
            return;
 
958
        snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
 
959
                 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
 
960
        av_free(pkt->data);
 
961
        pkt->data = line;
 
962
        pkt->size = strlen(line);
 
963
    }
 
964
}
 
965
 
 
966
static void matroska_merge_packets(AVPacket *out, AVPacket *in)
 
967
{
 
968
    out->data = av_realloc(out->data, out->size+in->size);
 
969
    memcpy(out->data+out->size, in->data, in->size);
 
970
    out->size += in->size;
 
971
    av_destruct_packet(in);
 
972
    av_free(in);
 
973
}
 
974
 
 
975
static void matroska_convert_tags(AVFormatContext *s, EbmlList *list)
 
976
{
 
977
    MatroskaTag *tags = list->elem;
 
978
    int i, j;
 
979
 
 
980
    for (i=0; i < list->nb_elem; i++) {
 
981
        for (j=0; j < FF_ARRAY_ELEMS(metadata); j++){
 
982
            if (!strcmp(tags[i].name, metadata[j].name)) {
 
983
                int *ptr = (int *)((char *)s + metadata[j].offset);
 
984
                if (*ptr)  continue;
 
985
                if (metadata[j].size > sizeof(int))
 
986
                    av_strlcpy((char *)ptr, tags[i].string, metadata[j].size);
 
987
                else
 
988
                    *ptr = atoi(tags[i].string);
 
989
            }
 
990
        }
 
991
        if (tags[i].sub.nb_elem)
 
992
            matroska_convert_tags(s, &tags[i].sub);
 
993
    }
 
994
}
 
995
 
 
996
static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
 
997
{
 
998
    EbmlList *seekhead_list = &matroska->seekhead;
 
999
    MatroskaSeekhead *seekhead = seekhead_list->elem;
 
1000
    uint32_t level_up = matroska->level_up;
 
1001
    int64_t before_pos = url_ftell(matroska->ctx->pb);
 
1002
    MatroskaLevel level;
 
1003
    int i;
 
1004
 
 
1005
    for (i=0; i<seekhead_list->nb_elem; i++) {
 
1006
        int64_t offset = seekhead[i].pos + matroska->segment_start;
 
1007
 
 
1008
        if (seekhead[i].pos <= before_pos
 
1009
            || seekhead[i].id == MATROSKA_ID_SEEKHEAD
 
1010
            || seekhead[i].id == MATROSKA_ID_CLUSTER)
 
1011
            continue;
 
1012
 
 
1013
        /* seek */
 
1014
        if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
 
1015
            continue;
 
1016
 
 
1017
        /* We don't want to lose our seekhead level, so we add
 
1018
         * a dummy. This is a crude hack. */
 
1019
        if (matroska->num_levels == EBML_MAX_DEPTH) {
1964
1020
            av_log(matroska->ctx, AV_LOG_INFO,
1965
 
                   "Unknown attachments ID 0x%x\n", id);
1966
 
            /* fall-through */
1967
 
 
1968
 
        case EBML_ID_VOID:
1969
 
            res = ebml_read_skip(matroska);
 
1021
                   "Max EBML element depth (%d) reached, "
 
1022
                   "cannot parse further.\n", EBML_MAX_DEPTH);
1970
1023
            break;
1971
1024
        }
1972
1025
 
1973
 
        if (matroska->level_up) {
1974
 
            matroska->level_up--;
1975
 
            break;
 
1026
        level.start = 0;
 
1027
        level.length = (uint64_t)-1;
 
1028
        matroska->levels[matroska->num_levels] = level;
 
1029
        matroska->num_levels++;
 
1030
 
 
1031
        ebml_parse(matroska, matroska_segment, matroska);
 
1032
 
 
1033
        /* remove dummy level */
 
1034
        while (matroska->num_levels) {
 
1035
            uint64_t length = matroska->levels[--matroska->num_levels].length;
 
1036
            if (length == (uint64_t)-1)
 
1037
                break;
1976
1038
        }
1977
1039
    }
1978
1040
 
1979
 
    return res;
 
1041
    /* seek back */
 
1042
    url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
 
1043
    matroska->level_up = level_up;
1980
1044
}
1981
1045
 
1982
 
#define ARRAY_SIZE(x)  (sizeof(x)/sizeof(*x))
1983
 
 
1984
 
static int
1985
 
matroska_aac_profile (char *codec_id)
 
1046
static int matroska_aac_profile(char *codec_id)
1986
1047
{
1987
 
    static const char *aac_profiles[] = {
1988
 
        "MAIN", "LC", "SSR"
1989
 
    };
 
1048
    static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1990
1049
    int profile;
1991
1050
 
1992
 
    for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
 
1051
    for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1993
1052
        if (strstr(codec_id, aac_profiles[profile]))
1994
1053
            break;
1995
1054
    return profile + 1;
1996
1055
}
1997
1056
 
1998
 
static int
1999
 
matroska_aac_sri (int samplerate)
 
1057
static int matroska_aac_sri(int samplerate)
2000
1058
{
2001
1059
    int sri;
2002
1060
 
2003
 
    for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
 
1061
    for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
2004
1062
        if (ff_mpeg4audio_sample_rates[sri] == samplerate)
2005
1063
            break;
2006
1064
    return sri;
2007
1065
}
2008
1066
 
2009
 
static int
2010
 
matroska_read_header (AVFormatContext    *s,
2011
 
                      AVFormatParameters *ap)
 
1067
static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
2012
1068
{
2013
1069
    MatroskaDemuxContext *matroska = s->priv_data;
2014
 
    char *doctype;
2015
 
    int version, last_level, res = 0;
2016
 
    uint32_t id;
 
1070
    EbmlList *attachements_list = &matroska->attachments;
 
1071
    MatroskaAttachement *attachements;
 
1072
    EbmlList *chapters_list = &matroska->chapters;
 
1073
    MatroskaChapter *chapters;
 
1074
    MatroskaTrack *tracks;
 
1075
    EbmlList *index_list;
 
1076
    MatroskaIndex *index;
 
1077
    Ebml ebml = { 0 };
 
1078
    AVStream *st;
 
1079
    int i, j;
2017
1080
 
2018
1081
    matroska->ctx = s;
2019
1082
 
2020
1083
    /* First read the EBML header. */
2021
 
    doctype = NULL;
2022
 
    if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2023
 
        return res;
2024
 
    if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2025
 
        av_log(matroska->ctx, AV_LOG_ERROR,
2026
 
               "Wrong EBML doctype ('%s' != 'matroska').\n",
2027
 
               doctype ? doctype : "(none)");
2028
 
        if (doctype)
2029
 
            av_free(doctype);
2030
 
        return AVERROR_NOFMT;
2031
 
    }
2032
 
    av_free(doctype);
2033
 
    if (version > 2) {
2034
 
        av_log(matroska->ctx, AV_LOG_ERROR,
2035
 
               "Matroska demuxer version 2 too old for file version %d\n",
2036
 
               version);
2037
 
        return AVERROR_NOFMT;
2038
 
    }
 
1084
    if (ebml_parse(matroska, ebml_syntax, &ebml)
 
1085
        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)
 
1086
        || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
 
1087
        || ebml.doctype_version > 2) {
 
1088
        av_log(matroska->ctx, AV_LOG_ERROR,
 
1089
               "EBML header using unsupported features\n"
 
1090
               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
 
1091
               ebml.version, ebml.doctype, ebml.doctype_version);
 
1092
        return AVERROR_NOFMT;
 
1093
    }
 
1094
    ebml_free(ebml_syntax, &ebml);
2039
1095
 
2040
1096
    /* The next thing is a segment. */
2041
 
    while (1) {
2042
 
        if (!(id = ebml_peek_id(matroska, &last_level)))
2043
 
            return AVERROR(EIO);
2044
 
        if (id == MATROSKA_ID_SEGMENT)
2045
 
            break;
2046
 
 
2047
 
        /* oi! */
2048
 
        av_log(matroska->ctx, AV_LOG_INFO,
2049
 
               "Expected a Segment ID (0x%x), but received 0x%x!\n",
2050
 
               MATROSKA_ID_SEGMENT, id);
2051
 
        if ((res = ebml_read_skip(matroska)) < 0)
2052
 
            return res;
2053
 
    }
2054
 
 
2055
 
    /* We now have a Matroska segment.
2056
 
     * Seeks are from the beginning of the segment,
2057
 
     * after the segment ID/length. */
2058
 
    if ((res = ebml_read_master(matroska, &id)) < 0)
2059
 
        return res;
2060
 
    matroska->segment_start = url_ftell(s->pb);
2061
 
 
2062
 
    matroska->time_scale = 1000000;
2063
 
    /* we've found our segment, start reading the different contents in here */
2064
 
    while (res == 0) {
2065
 
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2066
 
            res = AVERROR(EIO);
2067
 
            break;
2068
 
        } else if (matroska->level_up) {
2069
 
            matroska->level_up--;
2070
 
            break;
2071
 
        }
2072
 
 
2073
 
        switch (id) {
2074
 
            /* stream info */
2075
 
            case MATROSKA_ID_INFO: {
2076
 
                if ((res = ebml_read_master(matroska, &id)) < 0)
2077
 
                    break;
2078
 
                res = matroska_parse_info(matroska);
2079
 
                break;
2080
 
            }
2081
 
 
2082
 
            /* track info headers */
2083
 
            case MATROSKA_ID_TRACKS: {
2084
 
                if ((res = ebml_read_master(matroska, &id)) < 0)
2085
 
                    break;
2086
 
                res = matroska_parse_tracks(matroska);
2087
 
                break;
2088
 
            }
2089
 
 
2090
 
            /* stream index */
2091
 
            case MATROSKA_ID_CUES: {
2092
 
                if (!matroska->index_parsed) {
2093
 
                    if ((res = ebml_read_master(matroska, &id)) < 0)
2094
 
                        break;
2095
 
                    res = matroska_parse_index(matroska);
2096
 
                } else
2097
 
                    res = ebml_read_skip(matroska);
2098
 
                break;
2099
 
            }
2100
 
 
2101
 
            /* metadata */
2102
 
            case MATROSKA_ID_TAGS: {
2103
 
                if (!matroska->metadata_parsed) {
2104
 
                    if ((res = ebml_read_master(matroska, &id)) < 0)
2105
 
                        break;
2106
 
                    res = matroska_parse_metadata(matroska);
2107
 
                } else
2108
 
                    res = ebml_read_skip(matroska);
2109
 
                break;
2110
 
            }
2111
 
 
2112
 
            /* file index (if seekable, seek to Cues/Tags to parse it) */
2113
 
            case MATROSKA_ID_SEEKHEAD: {
2114
 
                if ((res = ebml_read_master(matroska, &id)) < 0)
2115
 
                    break;
2116
 
                res = matroska_parse_seekhead(matroska);
2117
 
                break;
2118
 
            }
2119
 
 
2120
 
            case MATROSKA_ID_ATTACHMENTS: {
2121
 
                if ((res = ebml_read_master(matroska, &id)) < 0)
2122
 
                    break;
2123
 
                res = matroska_parse_attachments(s);
2124
 
                break;
2125
 
            }
2126
 
 
2127
 
            case MATROSKA_ID_CLUSTER: {
2128
 
                /* Do not read the master - this will be done in the next
2129
 
                 * call to matroska_read_packet. */
2130
 
                res = 1;
2131
 
                break;
2132
 
            }
2133
 
 
2134
 
            default:
2135
 
                av_log(matroska->ctx, AV_LOG_INFO,
2136
 
                       "Unknown matroska file header ID 0x%x\n", id);
2137
 
            /* fall-through */
2138
 
 
2139
 
            case EBML_ID_VOID:
2140
 
                res = ebml_read_skip(matroska);
2141
 
                break;
2142
 
        }
2143
 
 
2144
 
        if (matroska->level_up) {
2145
 
            matroska->level_up--;
2146
 
            break;
2147
 
        }
2148
 
    }
2149
 
 
2150
 
    /* Have we found a cluster? */
2151
 
    if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2152
 
        int i, j;
2153
 
        MatroskaTrack *track;
2154
 
        AVStream *st;
2155
 
 
2156
 
        for (i = 0; i < matroska->num_tracks; i++) {
2157
 
            enum CodecID codec_id = CODEC_ID_NONE;
2158
 
            uint8_t *extradata = NULL;
2159
 
            int extradata_size = 0;
2160
 
            int extradata_offset = 0;
2161
 
            track = matroska->tracks[i];
2162
 
            track->stream_index = -1;
2163
 
 
2164
 
            /* Apply some sanity checks. */
2165
 
            if (track->codec_id == NULL)
2166
 
                continue;
2167
 
 
2168
 
            for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
2169
 
                if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2170
 
                            strlen(ff_mkv_codec_tags[j].str))){
2171
 
                    codec_id= ff_mkv_codec_tags[j].id;
2172
 
                    break;
2173
 
                }
2174
 
            }
2175
 
 
2176
 
            /* Set the FourCC from the CodecID. */
2177
 
            /* This is the MS compatibility mode which stores a
2178
 
             * BITMAPINFOHEADER in the CodecPrivate. */
2179
 
            if (!strcmp(track->codec_id,
2180
 
                        MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2181
 
                (track->codec_priv_size >= 40) &&
2182
 
                (track->codec_priv != NULL)) {
2183
 
                MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2184
 
 
2185
 
                /* Offset of biCompression. Stored in LE. */
2186
 
                vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2187
 
                codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2188
 
 
2189
 
            }
2190
 
 
2191
 
            /* This is the MS compatibility mode which stores a
2192
 
             * WAVEFORMATEX in the CodecPrivate. */
2193
 
            else if (!strcmp(track->codec_id,
2194
 
                             MATROSKA_CODEC_ID_AUDIO_ACM) &&
2195
 
                (track->codec_priv_size >= 18) &&
2196
 
                (track->codec_priv != NULL)) {
2197
 
                uint16_t tag;
2198
 
 
2199
 
                /* Offset of wFormatTag. Stored in LE. */
2200
 
                tag = AV_RL16(track->codec_priv);
2201
 
                codec_id = codec_get_id(codec_wav_tags, tag);
2202
 
 
2203
 
            }
2204
 
 
2205
 
            else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2206
 
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2207
 
                int profile = matroska_aac_profile(track->codec_id);
2208
 
                int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2209
 
                extradata = av_malloc(5);
2210
 
                if (extradata == NULL)
2211
 
                    return AVERROR(ENOMEM);
2212
 
                extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2213
 
                extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2214
 
                if (strstr(track->codec_id, "SBR")) {
2215
 
                    sri = matroska_aac_sri(audiotrack->samplerate);
2216
 
                    extradata[2] = 0x56;
2217
 
                    extradata[3] = 0xE5;
2218
 
                    extradata[4] = 0x80 | (sri<<3);
2219
 
                    extradata_size = 5;
2220
 
                } else {
2221
 
                    extradata_size = 2;
2222
 
                }
2223
 
            }
2224
 
 
2225
 
            else if (codec_id == CODEC_ID_TTA) {
2226
 
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2227
 
                ByteIOContext b;
2228
 
                extradata_size = 30;
2229
 
                extradata = av_mallocz(extradata_size);
2230
 
                if (extradata == NULL)
2231
 
                    return AVERROR(ENOMEM);
2232
 
                init_put_byte(&b, extradata, extradata_size, 1,
2233
 
                              NULL, NULL, NULL, NULL);
2234
 
                put_buffer(&b, "TTA1", 4);
2235
 
                put_le16(&b, 1);
2236
 
                put_le16(&b, audiotrack->channels);
2237
 
                put_le16(&b, audiotrack->bitdepth);
2238
 
                put_le32(&b, audiotrack->samplerate);
2239
 
                put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2240
 
            }
2241
 
 
2242
 
            else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2243
 
                     codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2244
 
                extradata_offset = 26;
2245
 
                track->codec_priv_size -= extradata_offset;
2246
 
            }
2247
 
 
2248
 
            else if (codec_id == CODEC_ID_RA_144) {
2249
 
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2250
 
                audiotrack->samplerate = 8000;
2251
 
                audiotrack->channels = 1;
2252
 
            }
2253
 
 
2254
 
            else if (codec_id == CODEC_ID_RA_288 ||
2255
 
                     codec_id == CODEC_ID_COOK ||
2256
 
                     codec_id == CODEC_ID_ATRAC3) {
2257
 
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2258
 
                ByteIOContext b;
2259
 
 
2260
 
                init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2261
 
                              NULL, NULL, NULL, NULL);
2262
 
                url_fskip(&b, 24);
2263
 
                audiotrack->coded_framesize = get_be32(&b);
2264
 
                url_fskip(&b, 12);
2265
 
                audiotrack->sub_packet_h    = get_be16(&b);
2266
 
                audiotrack->frame_size      = get_be16(&b);
2267
 
                audiotrack->sub_packet_size = get_be16(&b);
2268
 
                audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2269
 
                if (codec_id == CODEC_ID_RA_288) {
2270
 
                    audiotrack->block_align = audiotrack->coded_framesize;
2271
 
                    track->codec_priv_size = 0;
2272
 
                } else {
2273
 
                    audiotrack->block_align = audiotrack->sub_packet_size;
2274
 
                    extradata_offset = 78;
2275
 
                    track->codec_priv_size -= extradata_offset;
2276
 
                }
2277
 
            }
2278
 
 
2279
 
            if (codec_id == CODEC_ID_NONE) {
2280
 
                av_log(matroska->ctx, AV_LOG_INFO,
2281
 
                       "Unknown/unsupported CodecID %s.\n",
2282
 
                       track->codec_id);
2283
 
            }
2284
 
 
2285
 
            track->stream_index = matroska->num_streams;
2286
 
 
2287
 
            matroska->num_streams++;
2288
 
            st = av_new_stream(s, track->stream_index);
 
1097
    if (ebml_parse(matroska, matroska_segments, matroska) < 0)
 
1098
        return -1;
 
1099
    matroska_execute_seekhead(matroska);
 
1100
 
 
1101
    if (matroska->duration)
 
1102
        matroska->ctx->duration = matroska->duration * matroska->time_scale
 
1103
                                  * 1000 / AV_TIME_BASE;
 
1104
    if (matroska->title)
 
1105
        strncpy(matroska->ctx->title, matroska->title,
 
1106
                sizeof(matroska->ctx->title)-1);
 
1107
    matroska_convert_tags(s, &matroska->tags);
 
1108
 
 
1109
    tracks = matroska->tracks.elem;
 
1110
    for (i=0; i < matroska->tracks.nb_elem; i++) {
 
1111
        MatroskaTrack *track = &tracks[i];
 
1112
        enum CodecID codec_id = CODEC_ID_NONE;
 
1113
        EbmlList *encodings_list = &tracks->encodings;
 
1114
        MatroskaTrackEncoding *encodings = encodings_list->elem;
 
1115
        uint8_t *extradata = NULL;
 
1116
        int extradata_size = 0;
 
1117
        int extradata_offset = 0;
 
1118
 
 
1119
        /* Apply some sanity checks. */
 
1120
        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
 
1121
            track->type != MATROSKA_TRACK_TYPE_AUDIO &&
 
1122
            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
 
1123
            av_log(matroska->ctx, AV_LOG_INFO,
 
1124
                   "Unknown or unsupported track type %"PRIu64"\n",
 
1125
                   track->type);
 
1126
            continue;
 
1127
        }
 
1128
        if (track->codec_id == NULL)
 
1129
            continue;
 
1130
 
 
1131
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
 
1132
            if (!track->default_duration)
 
1133
                track->default_duration = 1000000000/track->video.frame_rate;
 
1134
            if (!track->video.display_width)
 
1135
                track->video.display_width = track->video.pixel_width;
 
1136
            if (!track->video.display_height)
 
1137
                track->video.display_height = track->video.pixel_height;
 
1138
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
 
1139
            if (!track->audio.out_samplerate)
 
1140
                track->audio.out_samplerate = track->audio.samplerate;
 
1141
        }
 
1142
        if (encodings_list->nb_elem > 1) {
 
1143
            av_log(matroska->ctx, AV_LOG_ERROR,
 
1144
                   "Multiple combined encodings no supported");
 
1145
        } else if (encodings_list->nb_elem == 1) {
 
1146
            if (encodings[0].type ||
 
1147
                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
 
1148
#ifdef CONFIG_ZLIB
 
1149
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
 
1150
#endif
 
1151
#ifdef CONFIG_BZLIB
 
1152
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
 
1153
#endif
 
1154
                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
 
1155
                encodings[0].scope = 0;
 
1156
                av_log(matroska->ctx, AV_LOG_ERROR,
 
1157
                       "Unsupported encoding type");
 
1158
            } else if (track->codec_priv.size && encodings[0].scope&2) {
 
1159
                uint8_t *codec_priv = track->codec_priv.data;
 
1160
                int offset = matroska_decode_buffer(&track->codec_priv.data,
 
1161
                                                    &track->codec_priv.size,
 
1162
                                                    track);
 
1163
                if (offset < 0) {
 
1164
                    track->codec_priv.data = NULL;
 
1165
                    track->codec_priv.size = 0;
 
1166
                    av_log(matroska->ctx, AV_LOG_ERROR,
 
1167
                           "Failed to decode codec private data\n");
 
1168
                } else if (offset > 0) {
 
1169
                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
 
1170
                    memcpy(track->codec_priv.data,
 
1171
                           encodings[0].compression.settings.data, offset);
 
1172
                    memcpy(track->codec_priv.data+offset, codec_priv,
 
1173
                           track->codec_priv.size);
 
1174
                    track->codec_priv.size += offset;
 
1175
                }
 
1176
                if (codec_priv != track->codec_priv.data)
 
1177
                    av_free(codec_priv);
 
1178
            }
 
1179
        }
 
1180
 
 
1181
        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
 
1182
            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
 
1183
                        strlen(ff_mkv_codec_tags[j].str))){
 
1184
                codec_id= ff_mkv_codec_tags[j].id;
 
1185
                break;
 
1186
            }
 
1187
        }
 
1188
 
 
1189
        st = track->stream = av_new_stream(s, 0);
 
1190
        if (st == NULL)
 
1191
            return AVERROR(ENOMEM);
 
1192
 
 
1193
        if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
 
1194
            && track->codec_priv.size >= 40
 
1195
            && track->codec_priv.data != NULL) {
 
1196
            track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
 
1197
            codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
 
1198
        } else if (!strcmp(track->codec_id, "A_MS/ACM")
 
1199
                   && track->codec_priv.size >= 18
 
1200
                   && track->codec_priv.data != NULL) {
 
1201
            uint16_t tag = AV_RL16(track->codec_priv.data);
 
1202
            codec_id = codec_get_id(codec_wav_tags, tag);
 
1203
        } else if (!strcmp(track->codec_id, "V_QUICKTIME")
 
1204
                   && (track->codec_priv.size >= 86)
 
1205
                   && (track->codec_priv.data != NULL)) {
 
1206
            track->video.fourcc = AV_RL32(track->codec_priv.data);
 
1207
            codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
 
1208
        } else if (codec_id == CODEC_ID_PCM_S16BE) {
 
1209
            switch (track->audio.bitdepth) {
 
1210
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
 
1211
            case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;
 
1212
            case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;
 
1213
            }
 
1214
        } else if (codec_id == CODEC_ID_PCM_S16LE) {
 
1215
            switch (track->audio.bitdepth) {
 
1216
            case  8:  codec_id = CODEC_ID_PCM_U8;     break;
 
1217
            case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;
 
1218
            case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;
 
1219
            }
 
1220
        } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
 
1221
            codec_id = CODEC_ID_PCM_F64LE;
 
1222
        } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
 
1223
            int profile = matroska_aac_profile(track->codec_id);
 
1224
            int sri = matroska_aac_sri(track->audio.samplerate);
 
1225
            extradata = av_malloc(5);
 
1226
            if (extradata == NULL)
 
1227
                return AVERROR(ENOMEM);
 
1228
            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
 
1229
            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
 
1230
            if (strstr(track->codec_id, "SBR")) {
 
1231
                sri = matroska_aac_sri(track->audio.out_samplerate);
 
1232
                extradata[2] = 0x56;
 
1233
                extradata[3] = 0xE5;
 
1234
                extradata[4] = 0x80 | (sri<<3);
 
1235
                extradata_size = 5;
 
1236
            } else
 
1237
                extradata_size = 2;
 
1238
        } else if (codec_id == CODEC_ID_TTA) {
 
1239
            ByteIOContext b;
 
1240
            extradata_size = 30;
 
1241
            extradata = av_mallocz(extradata_size);
 
1242
            if (extradata == NULL)
 
1243
                return AVERROR(ENOMEM);
 
1244
            init_put_byte(&b, extradata, extradata_size, 1,
 
1245
                          NULL, NULL, NULL, NULL);
 
1246
            put_buffer(&b, "TTA1", 4);
 
1247
            put_le16(&b, 1);
 
1248
            put_le16(&b, track->audio.channels);
 
1249
            put_le16(&b, track->audio.bitdepth);
 
1250
            put_le32(&b, track->audio.out_samplerate);
 
1251
            put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
 
1252
        } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
 
1253
                   codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
 
1254
            extradata_offset = 26;
 
1255
            track->codec_priv.size -= extradata_offset;
 
1256
        } else if (codec_id == CODEC_ID_RA_144) {
 
1257
            track->audio.out_samplerate = 8000;
 
1258
            track->audio.channels = 1;
 
1259
        } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
 
1260
                   codec_id == CODEC_ID_ATRAC3) {
 
1261
            ByteIOContext b;
 
1262
 
 
1263
            init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
 
1264
                          0, NULL, NULL, NULL, NULL);
 
1265
            url_fskip(&b, 24);
 
1266
            track->audio.coded_framesize = get_be32(&b);
 
1267
            url_fskip(&b, 12);
 
1268
            track->audio.sub_packet_h    = get_be16(&b);
 
1269
            track->audio.frame_size      = get_be16(&b);
 
1270
            track->audio.sub_packet_size = get_be16(&b);
 
1271
            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
 
1272
            if (codec_id == CODEC_ID_RA_288) {
 
1273
                st->codec->block_align = track->audio.coded_framesize;
 
1274
                track->codec_priv.size = 0;
 
1275
            } else {
 
1276
                st->codec->block_align = track->audio.sub_packet_size;
 
1277
                extradata_offset = 78;
 
1278
                track->codec_priv.size -= extradata_offset;
 
1279
            }
 
1280
        }
 
1281
 
 
1282
        if (codec_id == CODEC_ID_NONE)
 
1283
            av_log(matroska->ctx, AV_LOG_INFO,
 
1284
                   "Unknown/unsupported CodecID %s.\n", track->codec_id);
 
1285
 
 
1286
        if (track->time_scale < 0.01)
 
1287
            track->time_scale = 1.0;
 
1288
        av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
 
1289
 
 
1290
        st->codec->codec_id = codec_id;
 
1291
        st->start_time = 0;
 
1292
        if (strcmp(track->language, "und"))
 
1293
            av_strlcpy(st->language, track->language, 4);
 
1294
 
 
1295
        if (track->flag_default)
 
1296
            st->disposition |= AV_DISPOSITION_DEFAULT;
 
1297
 
 
1298
        if (track->default_duration)
 
1299
            av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
 
1300
                      track->default_duration, 1000000000, 30000);
 
1301
 
 
1302
        if(extradata){
 
1303
            st->codec->extradata = extradata;
 
1304
            st->codec->extradata_size = extradata_size;
 
1305
        } else if(track->codec_priv.data && track->codec_priv.size > 0){
 
1306
            st->codec->extradata = av_malloc(track->codec_priv.size);
 
1307
            if(st->codec->extradata == NULL)
 
1308
                return AVERROR(ENOMEM);
 
1309
            st->codec->extradata_size = track->codec_priv.size;
 
1310
            memcpy(st->codec->extradata,
 
1311
                   track->codec_priv.data + extradata_offset,
 
1312
                   track->codec_priv.size);
 
1313
        }
 
1314
 
 
1315
        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
 
1316
            st->codec->codec_type = CODEC_TYPE_VIDEO;
 
1317
            st->codec->codec_tag  = track->video.fourcc;
 
1318
            st->codec->width  = track->video.pixel_width;
 
1319
            st->codec->height = track->video.pixel_height;
 
1320
            av_reduce(&st->sample_aspect_ratio.num,
 
1321
                      &st->sample_aspect_ratio.den,
 
1322
                      st->codec->height * track->video.display_width,
 
1323
                      st->codec-> width * track->video.display_height,
 
1324
                      255);
 
1325
            st->need_parsing = AVSTREAM_PARSE_HEADERS;
 
1326
        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
 
1327
            st->codec->codec_type = CODEC_TYPE_AUDIO;
 
1328
            st->codec->sample_rate = track->audio.out_samplerate;
 
1329
            st->codec->channels = track->audio.channels;
 
1330
        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
 
1331
            st->codec->codec_type = CODEC_TYPE_SUBTITLE;
 
1332
        }
 
1333
    }
 
1334
 
 
1335
    attachements = attachements_list->elem;
 
1336
    for (j=0; j<attachements_list->nb_elem; j++) {
 
1337
        if (!(attachements[j].filename && attachements[j].mime &&
 
1338
              attachements[j].bin.data && attachements[j].bin.size > 0)) {
 
1339
            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
 
1340
        } else {
 
1341
            AVStream *st = av_new_stream(s, 0);
2289
1342
            if (st == NULL)
2290
 
                return AVERROR(ENOMEM);
2291
 
            av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2292
 
 
2293
 
            st->codec->codec_id = codec_id;
2294
 
            st->start_time = 0;
2295
 
            if (strcmp(track->language, "und"))
2296
 
                strcpy(st->language, track->language);
2297
 
 
2298
 
            if (track->flags & MATROSKA_TRACK_DEFAULT)
2299
 
                st->disposition |= AV_DISPOSITION_DEFAULT;
2300
 
 
2301
 
            if (track->default_duration)
2302
 
                av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2303
 
                          track->default_duration, 1000000000, 30000);
2304
 
 
2305
 
            if(extradata){
2306
 
                st->codec->extradata = extradata;
2307
 
                st->codec->extradata_size = extradata_size;
2308
 
            } else if(track->codec_priv && track->codec_priv_size > 0){
2309
 
                st->codec->extradata = av_malloc(track->codec_priv_size);
2310
 
                if(st->codec->extradata == NULL)
2311
 
                    return AVERROR(ENOMEM);
2312
 
                st->codec->extradata_size = track->codec_priv_size;
2313
 
                memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2314
 
                       track->codec_priv_size);
2315
 
            }
2316
 
 
2317
 
            if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2318
 
                MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2319
 
 
2320
 
                st->codec->codec_type = CODEC_TYPE_VIDEO;
2321
 
                st->codec->codec_tag = videotrack->fourcc;
2322
 
                st->codec->width = videotrack->pixel_width;
2323
 
                st->codec->height = videotrack->pixel_height;
2324
 
                if (videotrack->display_width == 0)
2325
 
                    videotrack->display_width= videotrack->pixel_width;
2326
 
                if (videotrack->display_height == 0)
2327
 
                    videotrack->display_height= videotrack->pixel_height;
2328
 
                av_reduce(&st->codec->sample_aspect_ratio.num,
2329
 
                          &st->codec->sample_aspect_ratio.den,
2330
 
                          st->codec->height * videotrack->display_width,
2331
 
                          st->codec-> width * videotrack->display_height,
2332
 
                          255);
2333
 
                st->need_parsing = AVSTREAM_PARSE_HEADERS;
2334
 
            } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2335
 
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2336
 
 
2337
 
                st->codec->codec_type = CODEC_TYPE_AUDIO;
2338
 
                st->codec->sample_rate = audiotrack->samplerate;
2339
 
                st->codec->channels = audiotrack->channels;
2340
 
                st->codec->block_align = audiotrack->block_align;
2341
 
            } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2342
 
                st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2343
 
            }
2344
 
 
2345
 
            /* What do we do with private data? E.g. for Vorbis. */
2346
 
        }
2347
 
        res = 0;
2348
 
    }
2349
 
 
2350
 
    if (matroska->index_parsed) {
2351
 
        int i, track, stream;
2352
 
        for (i=0; i<matroska->num_indexes; i++) {
2353
 
            MatroskaDemuxIndex *idx = &matroska->index[i];
2354
 
            track = matroska_find_track_by_num(matroska, idx->track);
2355
 
            if (track < 0)  continue;
2356
 
            stream = matroska->tracks[track]->stream_index;
2357
 
            if (stream >= 0 && stream < matroska->ctx->nb_streams)
2358
 
                av_add_index_entry(matroska->ctx->streams[stream],
2359
 
                                   idx->pos, idx->time/matroska->time_scale,
2360
 
                                   0, 0, AVINDEX_KEYFRAME);
2361
 
        }
2362
 
    }
2363
 
 
2364
 
    return res;
2365
 
}
2366
 
 
2367
 
static int
2368
 
matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2369
 
                     int64_t pos, uint64_t cluster_time, uint64_t duration,
2370
 
                     int is_keyframe, int is_bframe)
2371
 
{
 
1343
                break;
 
1344
            st->filename          = av_strdup(attachements[j].filename);
 
1345
            st->codec->codec_id = CODEC_ID_NONE;
 
1346
            st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
 
1347
            st->codec->extradata  = av_malloc(attachements[j].bin.size);
 
1348
            if(st->codec->extradata == NULL)
 
1349
                break;
 
1350
            st->codec->extradata_size = attachements[j].bin.size;
 
1351
            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
 
1352
 
 
1353
            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
 
1354
                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
 
1355
                             strlen(ff_mkv_mime_tags[i].str))) {
 
1356
                    st->codec->codec_id = ff_mkv_mime_tags[i].id;
 
1357
                    break;
 
1358
                }
 
1359
            }
 
1360
        }
 
1361
    }
 
1362
 
 
1363
    chapters = chapters_list->elem;
 
1364
    for (i=0; i<chapters_list->nb_elem; i++)
 
1365
        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
 
1366
            ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
 
1367
                           chapters[i].start, chapters[i].end,
 
1368
                           chapters[i].title);
 
1369
 
 
1370
    index_list = &matroska->index;
 
1371
    index = index_list->elem;
 
1372
    for (i=0; i<index_list->nb_elem; i++) {
 
1373
        EbmlList *pos_list = &index[i].pos;
 
1374
        MatroskaIndexPos *pos = pos_list->elem;
 
1375
        for (j=0; j<pos_list->nb_elem; j++) {
 
1376
            MatroskaTrack *track = matroska_find_track_by_num(matroska,
 
1377
                                                              pos[j].track);
 
1378
            if (track && track->stream)
 
1379
                av_add_index_entry(track->stream,
 
1380
                                   pos[j].pos + matroska->segment_start,
 
1381
                                   index[i].time, 0, 0, AVINDEX_KEYFRAME);
 
1382
        }
 
1383
    }
 
1384
 
 
1385
    return 0;
 
1386
}
 
1387
 
 
1388
/*
 
1389
 * Put one packet in an application-supplied AVPacket struct.
 
1390
 * Returns 0 on success or -1 on failure.
 
1391
 */
 
1392
static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
 
1393
                                   AVPacket *pkt)
 
1394
{
 
1395
    if (matroska->num_packets > 0) {
 
1396
        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
 
1397
        av_free(matroska->packets[0]);
 
1398
        if (matroska->num_packets > 1) {
 
1399
            memmove(&matroska->packets[0], &matroska->packets[1],
 
1400
                    (matroska->num_packets - 1) * sizeof(AVPacket *));
 
1401
            matroska->packets =
 
1402
                av_realloc(matroska->packets, (matroska->num_packets - 1) *
 
1403
                           sizeof(AVPacket *));
 
1404
        } else {
 
1405
            av_freep(&matroska->packets);
 
1406
        }
 
1407
        matroska->num_packets--;
 
1408
        return 0;
 
1409
    }
 
1410
 
 
1411
    return -1;
 
1412
}
 
1413
 
 
1414
/*
 
1415
 * Free all packets in our internal queue.
 
1416
 */
 
1417
static void matroska_clear_queue(MatroskaDemuxContext *matroska)
 
1418
{
 
1419
    if (matroska->packets) {
 
1420
        int n;
 
1421
        for (n = 0; n < matroska->num_packets; n++) {
 
1422
            av_free_packet(matroska->packets[n]);
 
1423
            av_free(matroska->packets[n]);
 
1424
        }
 
1425
        av_freep(&matroska->packets);
 
1426
        matroska->num_packets = 0;
 
1427
    }
 
1428
}
 
1429
 
 
1430
static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
 
1431
                                int size, int64_t pos, uint64_t cluster_time,
 
1432
                                uint64_t duration, int is_keyframe,
 
1433
                                int64_t cluster_pos)
 
1434
{
 
1435
    uint64_t timecode = AV_NOPTS_VALUE;
 
1436
    MatroskaTrack *track;
2372
1437
    int res = 0;
2373
 
    int track;
2374
1438
    AVStream *st;
2375
1439
    AVPacket *pkt;
2376
 
    uint8_t *origdata = data;
2377
1440
    int16_t block_time;
2378
1441
    uint32_t *lace_size = NULL;
2379
1442
    int n, flags, laces = 0;
2380
1443
    uint64_t num;
2381
 
    int stream_index;
2382
1444
 
2383
 
    /* first byte(s): tracknum */
2384
 
    if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
 
1445
    if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
2385
1446
        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2386
 
        av_free(origdata);
2387
1447
        return res;
2388
1448
    }
2389
1449
    data += n;
2390
1450
    size -= n;
2391
1451
 
2392
 
    /* fetch track from num */
2393
1452
    track = matroska_find_track_by_num(matroska, num);
2394
 
    if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
 
1453
    if (size <= 3 || !track || !track->stream) {
2395
1454
        av_log(matroska->ctx, AV_LOG_INFO,
2396
 
               "Invalid stream %d or size %u\n", track, size);
2397
 
        av_free(origdata);
2398
 
        return res;
2399
 
    }
2400
 
    stream_index = matroska->tracks[track]->stream_index;
2401
 
    if (stream_index < 0 || stream_index >= matroska->ctx->nb_streams) {
2402
 
        av_free(origdata);
2403
 
        return res;
2404
 
    }
2405
 
    st = matroska->ctx->streams[stream_index];
2406
 
    if (st->discard >= AVDISCARD_ALL) {
2407
 
        av_free(origdata);
2408
 
        return res;
2409
 
    }
 
1455
               "Invalid stream %"PRIu64" or size %u\n", num, size);
 
1456
        return res;
 
1457
    }
 
1458
    st = track->stream;
 
1459
    if (st->discard >= AVDISCARD_ALL)
 
1460
        return res;
2410
1461
    if (duration == AV_NOPTS_VALUE)
2411
 
        duration = matroska->tracks[track]->default_duration / matroska->time_scale;
 
1462
        duration = track->default_duration / matroska->time_scale;
2412
1463
 
2413
 
    /* block_time (relative to cluster time) */
2414
1464
    block_time = AV_RB16(data);
2415
1465
    data += 2;
2416
1466
    flags = *data++;
2418
1468
    if (is_keyframe == -1)
2419
1469
        is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
2420
1470
 
2421
 
    if (matroska->skip_to_keyframe) {
2422
 
        if (!is_keyframe || st != matroska->skip_to_stream) {
2423
 
            av_free(origdata);
 
1471
    if (cluster_time != (uint64_t)-1
 
1472
        && (block_time >= 0 || cluster_time >= -block_time)) {
 
1473
        timecode = cluster_time + block_time;
 
1474
        if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
 
1475
            && timecode < track->end_timecode)
 
1476
            is_keyframe = 0;  /* overlapping subtitles are not key frame */
 
1477
        if (is_keyframe)
 
1478
            av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
 
1479
        track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
 
1480
    }
 
1481
 
 
1482
    if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
 
1483
        if (!is_keyframe || timecode < matroska->skip_to_timecode)
2424
1484
            return res;
2425
 
        }
2426
1485
        matroska->skip_to_keyframe = 0;
2427
1486
    }
2428
1487
 
2433
1492
            lace_size[0] = size;
2434
1493
            break;
2435
1494
 
2436
 
        case 0x1: /* xiph lacing */
 
1495
        case 0x1: /* Xiph lacing */
2437
1496
        case 0x2: /* fixed-size lacing */
2438
1497
        case 0x3: /* EBML lacing */
2439
 
            if (size == 0) {
2440
 
                res = -1;
2441
 
                break;
2442
 
            }
 
1498
            assert(size>0); // size <=3 is checked before size-=3 above
2443
1499
            laces = (*data) + 1;
2444
1500
            data += 1;
2445
1501
            size -= 1;
2446
1502
            lace_size = av_mallocz(laces * sizeof(int));
2447
1503
 
2448
1504
            switch ((flags & 0x06) >> 1) {
2449
 
                case 0x1: /* xiph lacing */ {
 
1505
                case 0x1: /* Xiph lacing */ {
2450
1506
                    uint8_t temp;
2451
1507
                    uint32_t total = 0;
2452
1508
                    for (n = 0; res == 0 && n < laces - 1; n++) {
2475
1531
 
2476
1532
                case 0x3: /* EBML lacing */ {
2477
1533
                    uint32_t total;
2478
 
                    n = matroska_ebmlnum_uint(data, size, &num);
 
1534
                    n = matroska_ebmlnum_uint(matroska, data, size, &num);
2479
1535
                    if (n < 0) {
2480
1536
                        av_log(matroska->ctx, AV_LOG_INFO,
2481
1537
                               "EBML block data error\n");
2487
1543
                    for (n = 1; res == 0 && n < laces - 1; n++) {
2488
1544
                        int64_t snum;
2489
1545
                        int r;
2490
 
                        r = matroska_ebmlnum_sint (data, size, &snum);
 
1546
                        r = matroska_ebmlnum_sint(matroska, data, size, &snum);
2491
1547
                        if (r < 0) {
2492
1548
                            av_log(matroska->ctx, AV_LOG_INFO,
2493
1549
                                   "EBML block data error\n");
2506
1562
    }
2507
1563
 
2508
1564
    if (res == 0) {
2509
 
        uint64_t timecode = AV_NOPTS_VALUE;
2510
 
 
2511
 
        if (cluster_time != (uint64_t)-1
2512
 
            && (block_time >= 0 || cluster_time >= -block_time))
2513
 
            timecode = cluster_time + block_time;
2514
 
 
2515
1565
        for (n = 0; n < laces; n++) {
2516
1566
            if (st->codec->codec_id == CODEC_ID_RA_288 ||
2517
1567
                st->codec->codec_id == CODEC_ID_COOK ||
2518
1568
                st->codec->codec_id == CODEC_ID_ATRAC3) {
2519
 
                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2520
1569
                int a = st->codec->block_align;
2521
 
                int sps = audiotrack->sub_packet_size;
2522
 
                int cfs = audiotrack->coded_framesize;
2523
 
                int h = audiotrack->sub_packet_h;
2524
 
                int y = audiotrack->sub_packet_cnt;
2525
 
                int w = audiotrack->frame_size;
 
1570
                int sps = track->audio.sub_packet_size;
 
1571
                int cfs = track->audio.coded_framesize;
 
1572
                int h = track->audio.sub_packet_h;
 
1573
                int y = track->audio.sub_packet_cnt;
 
1574
                int w = track->audio.frame_size;
2526
1575
                int x;
2527
1576
 
2528
 
                if (!audiotrack->pkt_cnt) {
 
1577
                if (!track->audio.pkt_cnt) {
2529
1578
                    if (st->codec->codec_id == CODEC_ID_RA_288)
2530
1579
                        for (x=0; x<h/2; x++)
2531
 
                            memcpy(audiotrack->buf+x*2*w+y*cfs,
 
1580
                            memcpy(track->audio.buf+x*2*w+y*cfs,
2532
1581
                                   data+x*cfs, cfs);
2533
1582
                    else
2534
1583
                        for (x=0; x<w/sps; x++)
2535
 
                            memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
 
1584
                            memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2536
1585
 
2537
 
                    if (++audiotrack->sub_packet_cnt >= h) {
2538
 
                        audiotrack->sub_packet_cnt = 0;
2539
 
                        audiotrack->pkt_cnt = h*w / a;
 
1586
                    if (++track->audio.sub_packet_cnt >= h) {
 
1587
                        track->audio.sub_packet_cnt = 0;
 
1588
                        track->audio.pkt_cnt = h*w / a;
2540
1589
                    }
2541
1590
                }
2542
 
                while (audiotrack->pkt_cnt) {
 
1591
                while (track->audio.pkt_cnt) {
2543
1592
                    pkt = av_mallocz(sizeof(AVPacket));
2544
1593
                    av_new_packet(pkt, a);
2545
 
                    memcpy(pkt->data, audiotrack->buf
2546
 
                           + a * (h*w / a - audiotrack->pkt_cnt--), a);
 
1594
                    memcpy(pkt->data, track->audio.buf
 
1595
                           + a * (h*w / a - track->audio.pkt_cnt--), a);
2547
1596
                    pkt->pos = pos;
2548
 
                    pkt->stream_index = stream_index;
2549
 
                    matroska_queue_packet(matroska, pkt);
 
1597
                    pkt->stream_index = st->index;
 
1598
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2550
1599
                }
2551
1600
            } else {
2552
 
                int offset = 0;
 
1601
                MatroskaTrackEncoding *encodings = track->encodings.elem;
 
1602
                int offset = 0, pkt_size = lace_size[n];
 
1603
                uint8_t *pkt_data = data;
 
1604
 
 
1605
                if (encodings && encodings->scope & 1) {
 
1606
                    offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
 
1607
                    if (offset < 0)
 
1608
                        continue;
 
1609
                }
2553
1610
 
2554
1611
                pkt = av_mallocz(sizeof(AVPacket));
2555
1612
                /* XXX: prevent data copy... */
2556
 
                if (av_new_packet(pkt, lace_size[n]-offset) < 0) {
 
1613
                if (av_new_packet(pkt, pkt_size+offset) < 0) {
 
1614
                    av_free(pkt);
2557
1615
                    res = AVERROR(ENOMEM);
2558
1616
                    n = laces-1;
2559
1617
                    break;
2560
1618
                }
2561
 
                memcpy (pkt->data, data+offset, lace_size[n]-offset);
 
1619
                if (offset)
 
1620
                    memcpy (pkt->data, encodings->compression.settings.data, offset);
 
1621
                memcpy (pkt->data+offset, pkt_data, pkt_size);
 
1622
 
 
1623
                if (pkt_data != data)
 
1624
                    av_free(pkt_data);
2562
1625
 
2563
1626
                if (n == 0)
2564
1627
                    pkt->flags = is_keyframe;
2565
 
                pkt->stream_index = stream_index;
 
1628
                pkt->stream_index = st->index;
2566
1629
 
2567
1630
                pkt->pts = timecode;
2568
1631
                pkt->pos = pos;
2569
 
                pkt->duration = duration;
2570
 
 
2571
 
                matroska_queue_packet(matroska, pkt);
 
1632
                if (st->codec->codec_id == CODEC_ID_TEXT)
 
1633
                    pkt->convergence_duration = duration;
 
1634
                else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
 
1635
                    pkt->duration = duration;
 
1636
 
 
1637
                if (st->codec->codec_id == CODEC_ID_SSA)
 
1638
                    matroska_fix_ass_packet(matroska, pkt, duration);
 
1639
 
 
1640
                if (matroska->prev_pkt &&
 
1641
                    timecode != AV_NOPTS_VALUE &&
 
1642
                    matroska->prev_pkt->pts == timecode &&
 
1643
                    matroska->prev_pkt->stream_index == st->index)
 
1644
                    matroska_merge_packets(matroska->prev_pkt, pkt);
 
1645
                else {
 
1646
                    dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
 
1647
                    matroska->prev_pkt = pkt;
 
1648
                }
2572
1649
            }
2573
1650
 
2574
1651
            if (timecode != AV_NOPTS_VALUE)
2578
1655
    }
2579
1656
 
2580
1657
    av_free(lace_size);
2581
 
    av_free(origdata);
2582
 
    return res;
2583
 
}
2584
 
 
2585
 
static int
2586
 
matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2587
 
                           uint64_t              cluster_time)
2588
 
{
2589
 
    int res = 0;
2590
 
    uint32_t id;
2591
 
    int is_bframe = 0;
2592
 
    int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2593
 
    uint64_t duration = AV_NOPTS_VALUE;
2594
 
    uint8_t *data;
2595
 
    int size = 0;
2596
 
    int64_t pos = 0;
2597
 
 
2598
 
    av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2599
 
 
2600
 
    while (res == 0) {
2601
 
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2602
 
            res = AVERROR(EIO);
2603
 
            break;
2604
 
        } else if (matroska->level_up) {
2605
 
            matroska->level_up--;
2606
 
            break;
2607
 
        }
2608
 
 
2609
 
        switch (id) {
2610
 
            /* one block inside the group. Note, block parsing is one
2611
 
             * of the harder things, so this code is a bit complicated.
2612
 
             * See http://www.matroska.org/ for documentation. */
2613
 
            case MATROSKA_ID_BLOCK: {
2614
 
                pos = url_ftell(matroska->ctx->pb);
2615
 
                res = ebml_read_binary(matroska, &id, &data, &size);
2616
 
                break;
2617
 
            }
2618
 
 
2619
 
            case MATROSKA_ID_BLOCKDURATION: {
2620
 
                if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2621
 
                    break;
2622
 
                break;
2623
 
            }
2624
 
 
2625
 
            case MATROSKA_ID_BLOCKREFERENCE: {
2626
 
                int64_t num;
2627
 
                /* We've found a reference, so not even the first frame in
2628
 
                 * the lace is a key frame. */
2629
 
                is_keyframe = 0;
2630
 
                if (last_num_packets != matroska->num_packets)
2631
 
                    matroska->packets[last_num_packets]->flags = 0;
2632
 
                if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2633
 
                    break;
2634
 
                if (num > 0)
2635
 
                    is_bframe = 1;
2636
 
                break;
2637
 
            }
2638
 
 
2639
 
            default:
2640
 
                av_log(matroska->ctx, AV_LOG_INFO,
2641
 
                       "Unknown entry 0x%x in blockgroup data\n", id);
2642
 
                /* fall-through */
2643
 
 
2644
 
            case EBML_ID_VOID:
2645
 
                res = ebml_read_skip(matroska);
2646
 
                break;
2647
 
        }
2648
 
 
2649
 
        if (matroska->level_up) {
2650
 
            matroska->level_up--;
2651
 
            break;
2652
 
        }
2653
 
    }
2654
 
 
2655
 
    if (res)
2656
 
        return res;
2657
 
 
2658
 
    if (size > 0)
2659
 
        res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2660
 
                                   duration, is_keyframe, is_bframe);
2661
 
 
2662
 
    return res;
2663
 
}
2664
 
 
2665
 
static int
2666
 
matroska_parse_cluster (MatroskaDemuxContext *matroska)
2667
 
{
2668
 
    int res = 0;
2669
 
    uint32_t id;
2670
 
    uint64_t cluster_time = 0;
2671
 
    uint8_t *data;
2672
 
    int64_t pos;
2673
 
    int size;
2674
 
 
2675
 
    av_log(matroska->ctx, AV_LOG_DEBUG,
2676
 
           "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
2677
 
 
2678
 
    while (res == 0) {
2679
 
        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2680
 
            res = AVERROR(EIO);
2681
 
            break;
2682
 
        } else if (matroska->level_up) {
2683
 
            matroska->level_up--;
2684
 
            break;
2685
 
        }
2686
 
 
2687
 
        switch (id) {
2688
 
            /* cluster timecode */
2689
 
            case MATROSKA_ID_CLUSTERTIMECODE: {
2690
 
                uint64_t num;
2691
 
                if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2692
 
                    break;
2693
 
                cluster_time = num;
2694
 
                break;
2695
 
            }
2696
 
 
2697
 
                /* a group of blocks inside a cluster */
2698
 
            case MATROSKA_ID_BLOCKGROUP:
2699
 
                if ((res = ebml_read_master(matroska, &id)) < 0)
2700
 
                    break;
2701
 
                res = matroska_parse_blockgroup(matroska, cluster_time);
2702
 
                break;
2703
 
 
2704
 
            case MATROSKA_ID_SIMPLEBLOCK:
2705
 
                pos = url_ftell(matroska->ctx->pb);
2706
 
                res = ebml_read_binary(matroska, &id, &data, &size);
2707
 
                if (res == 0)
2708
 
                    res = matroska_parse_block(matroska, data, size, pos,
2709
 
                                               cluster_time, AV_NOPTS_VALUE,
2710
 
                                               -1, 0);
2711
 
                break;
2712
 
 
2713
 
            default:
2714
 
                av_log(matroska->ctx, AV_LOG_INFO,
2715
 
                       "Unknown entry 0x%x in cluster data\n", id);
2716
 
                /* fall-through */
2717
 
 
2718
 
            case EBML_ID_VOID:
2719
 
                res = ebml_read_skip(matroska);
2720
 
                break;
2721
 
        }
2722
 
 
2723
 
        if (matroska->level_up) {
2724
 
            matroska->level_up--;
2725
 
            break;
2726
 
        }
2727
 
    }
2728
 
 
2729
 
    return res;
2730
 
}
2731
 
 
2732
 
static int
2733
 
matroska_read_packet (AVFormatContext *s,
2734
 
                      AVPacket        *pkt)
 
1658
    return res;
 
1659
}
 
1660
 
 
1661
static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
 
1662
{
 
1663
    MatroskaCluster cluster = { 0 };
 
1664
    EbmlList *blocks_list;
 
1665
    MatroskaBlock *blocks;
 
1666
    int i, res;
 
1667
    int64_t pos = url_ftell(matroska->ctx->pb);
 
1668
    matroska->prev_pkt = NULL;
 
1669
    if (matroska->has_cluster_id){
 
1670
        /* For the first cluster we parse, its ID was already read as
 
1671
           part of matroska_read_header(), so don't read it again */
 
1672
        res = ebml_parse_id(matroska, matroska_clusters,
 
1673
                            MATROSKA_ID_CLUSTER, &cluster);
 
1674
        pos -= 4;  /* sizeof the ID which was already read */
 
1675
        matroska->has_cluster_id = 0;
 
1676
    } else
 
1677
        res = ebml_parse(matroska, matroska_clusters, &cluster);
 
1678
    blocks_list = &cluster.blocks;
 
1679
    blocks = blocks_list->elem;
 
1680
    for (i=0; i<blocks_list->nb_elem; i++)
 
1681
        if (blocks[i].bin.size > 0)
 
1682
            res=matroska_parse_block(matroska,
 
1683
                                     blocks[i].bin.data, blocks[i].bin.size,
 
1684
                                     blocks[i].bin.pos,  cluster.timecode,
 
1685
                                     blocks[i].duration, !blocks[i].reference,
 
1686
                                     pos);
 
1687
    ebml_free(matroska_cluster, &cluster);
 
1688
    if (res < 0)  matroska->done = 1;
 
1689
    return res;
 
1690
}
 
1691
 
 
1692
static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2735
1693
{
2736
1694
    MatroskaDemuxContext *matroska = s->priv_data;
2737
 
    int res;
2738
 
    uint32_t id;
2739
1695
 
2740
 
    /* Read stream until we have a packet queued. */
2741
1696
    while (matroska_deliver_packet(matroska, pkt)) {
2742
 
 
2743
 
        /* Have we already reached the end? */
2744
1697
        if (matroska->done)
2745
1698
            return AVERROR(EIO);
2746
 
 
2747
 
        res = 0;
2748
 
        while (res == 0) {
2749
 
            if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2750
 
                return AVERROR(EIO);
2751
 
            } else if (matroska->level_up) {
2752
 
                matroska->level_up--;
2753
 
                break;
2754
 
            }
2755
 
 
2756
 
            switch (id) {
2757
 
                case MATROSKA_ID_CLUSTER:
2758
 
                    if ((res = ebml_read_master(matroska, &id)) < 0)
2759
 
                        break;
2760
 
                    if ((res = matroska_parse_cluster(matroska)) == 0)
2761
 
                        res = 1; /* Parsed one cluster, let's get out. */
2762
 
                    break;
2763
 
 
2764
 
                default:
2765
 
                case EBML_ID_VOID:
2766
 
                    res = ebml_read_skip(matroska);
2767
 
                    break;
2768
 
            }
2769
 
 
2770
 
            if (matroska->level_up) {
2771
 
                matroska->level_up--;
2772
 
                break;
2773
 
            }
2774
 
        }
2775
 
 
2776
 
        if (res == -1)
2777
 
            matroska->done = 1;
 
1699
        matroska_parse_cluster(matroska);
2778
1700
    }
2779
1701
 
2780
1702
    return 0;
2781
1703
}
2782
1704
 
2783
 
static int
2784
 
matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2785
 
                    int flags)
 
1705
static int matroska_read_seek(AVFormatContext *s, int stream_index,
 
1706
                              int64_t timestamp, int flags)
2786
1707
{
2787
1708
    MatroskaDemuxContext *matroska = s->priv_data;
 
1709
    MatroskaTrack *tracks = matroska->tracks.elem;
2788
1710
    AVStream *st = s->streams[stream_index];
2789
 
    int index;
2790
 
 
2791
 
    /* find index entry */
2792
 
    index = av_index_search_timestamp(st, timestamp, flags);
 
1711
    int i, index, index_sub, index_min;
 
1712
 
 
1713
    if (!st->nb_index_entries)
 
1714
        return 0;
 
1715
    timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
 
1716
 
 
1717
    if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
 
1718
        url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
 
1719
        while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
 
1720
            matroska_clear_queue(matroska);
 
1721
            if (matroska_parse_cluster(matroska) < 0)
 
1722
                break;
 
1723
        }
 
1724
    }
 
1725
 
 
1726
    matroska_clear_queue(matroska);
2793
1727
    if (index < 0)
2794
1728
        return 0;
2795
1729
 
2796
 
    matroska_clear_queue(matroska);
 
1730
    index_min = index;
 
1731
    for (i=0; i < matroska->tracks.nb_elem; i++) {
 
1732
        tracks[i].end_timecode = 0;
 
1733
        if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
 
1734
            && !tracks[i].stream->discard != AVDISCARD_ALL) {
 
1735
            index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
 
1736
            if (index_sub >= 0
 
1737
                && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
 
1738
                && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
 
1739
                index_min = index_sub;
 
1740
        }
 
1741
    }
2797
1742
 
2798
 
    /* do the seek */
2799
 
    url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
 
1743
    url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2800
1744
    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2801
 
    matroska->skip_to_stream = st;
2802
 
    matroska->peek_id = 0;
 
1745
    matroska->skip_to_timecode = st->index_entries[index].timestamp;
 
1746
    matroska->done = 0;
 
1747
    av_update_cur_dts(s, st, st->index_entries[index].timestamp);
2803
1748
    return 0;
2804
1749
}
2805
1750
 
2806
 
static int
2807
 
matroska_read_close (AVFormatContext *s)
 
1751
static int matroska_read_close(AVFormatContext *s)
2808
1752
{
2809
1753
    MatroskaDemuxContext *matroska = s->priv_data;
2810
 
    int n = 0;
2811
 
 
2812
 
    av_free(matroska->writing_app);
2813
 
    av_free(matroska->muxing_app);
2814
 
    av_free(matroska->index);
 
1754
    MatroskaTrack *tracks = matroska->tracks.elem;
 
1755
    int n;
2815
1756
 
2816
1757
    matroska_clear_queue(matroska);
2817
1758
 
2818
 
    for (n = 0; n < matroska->num_tracks; n++) {
2819
 
        MatroskaTrack *track = matroska->tracks[n];
2820
 
        av_free(track->codec_id);
2821
 
        av_free(track->codec_name);
2822
 
        av_free(track->codec_priv);
2823
 
        av_free(track->name);
2824
 
 
2825
 
        if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2826
 
            MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2827
 
            av_free(audiotrack->buf);
2828
 
        }
2829
 
 
2830
 
        av_free(track);
2831
 
    }
 
1759
    for (n=0; n < matroska->tracks.nb_elem; n++)
 
1760
        if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
 
1761
            av_free(tracks[n].audio.buf);
 
1762
    ebml_free(matroska_segment, matroska);
2832
1763
 
2833
1764
    return 0;
2834
1765
}
2835
1766
 
2836
1767
AVInputFormat matroska_demuxer = {
2837
1768
    "matroska",
2838
 
    "Matroska file format",
 
1769
    NULL_IF_CONFIG_SMALL("Matroska file format"),
2839
1770
    sizeof(MatroskaDemuxContext),
2840
1771
    matroska_probe,
2841
1772
    matroska_read_header,