Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 7caf0cc6

History | View | Annotate | Download (62.8 KB)

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

    
22
#include <limits.h>
23

    
24
//#define DEBUG
25

    
26
#include "avformat.h"
27
#include "riff.h"
28
#include "isom.h"
29
#include "dv.h"
30

    
31
#ifdef CONFIG_ZLIB
32
#include <zlib.h>
33
#endif
34

    
35
/*
36
 * First version by Francois Revol revol@free.fr
37
 * Seek function by Gael Chardon gael.dev@4now.net
38
 *
39
 * Features and limitations:
40
 * - reads most of the QT files I have (at least the structure),
41
 *   the exceptions are .mov with zlib compressed headers ('cmov' section). It shouldn't be hard to implement.
42
 *   FIXED, Francois Revol, 07/17/2002
43
 * - ffmpeg has nearly none of the usual QuickTime codecs,
44
 *   although I succesfully dumped raw and mp3 audio tracks off .mov files.
45
 *   Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
46
 * - .mp4 parsing is still hazardous, although the format really is QuickTime with some minor changes
47
 *   (to make .mov parser crash maybe ?), despite what they say in the MPEG FAQ at
48
 *   http://mpeg.telecomitalialab.com/faq.htm
49
 * - the code is quite ugly... maybe I won't do it recursive next time :-)
50
 * - seek is not supported with files that contain edit list
51
 *
52
 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
53
 * when coding this :) (it's a writer anyway)
54
 *
55
 * Reference documents:
56
 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
57
 * Apple:
58
 *  http://developer.apple.com/documentation/QuickTime/QTFF/
59
 *  http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
60
 * QuickTime is a trademark of Apple (AFAIK :))
61
 */
62

    
63
#include "qtpalette.h"
64

    
65

    
66
#undef NDEBUG
67
#include <assert.h>
68

    
69
static const AVCodecTag mov_video_tags[] = {
70
/*  { CODEC_ID_, MKTAG('c', 'v', 'i', 'd') }, *//* Cinepak */
71
/*  { CODEC_ID_H263, MKTAG('r', 'a', 'w', ' ') }, *//* Uncompressed RGB */
72
/*  { CODEC_ID_H263, MKTAG('Y', 'u', 'v', '2') }, *//* Uncompressed YUV422 */
73
/*    { CODEC_ID_RAWVIDEO, MKTAG('A', 'V', 'U', 'I') }, *//* YUV with alpha-channel (AVID Uncompressed) */
74
/* Graphics */
75
/* Animation */
76
/* Apple video */
77
/* Kodak Photo CD */
78
    { CODEC_ID_MJPEG, MKTAG('j', 'p', 'e', 'g') }, /* PhotoJPEG */
79
    { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'e', 'g') }, /* MPEG */
80
    { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'a') }, /* Motion-JPEG (format A) */
81
    { CODEC_ID_MJPEGB, MKTAG('m', 'j', 'p', 'b') }, /* Motion-JPEG (format B) */
82
    { CODEC_ID_MJPEG, MKTAG('A', 'V', 'D', 'J') }, /* MJPEG with alpha-channel (AVID JFIF meridien compressed) */
83
/*    { CODEC_ID_MJPEG, MKTAG('A', 'V', 'R', 'n') }, *//* MJPEG with alpha-channel (AVID ABVB/Truevision NuVista) */
84
    { CODEC_ID_GIF, MKTAG('g', 'i', 'f', ' ') }, /* embedded gif files as frames (usually one "click to play movie" frame) */
85
/* Sorenson video */
86
    { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') }, /* Sorenson Video v1 */
87
    { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', '1') }, /* Sorenson Video v1 */
88
    { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', 'i') }, /* Sorenson Video v1 (from QT specs)*/
89
    { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') }, /* Sorenson Video v3 */
90
    { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
91
    { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', 'X') }, /* OpenDiVX *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
92
    { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') },
93
    { CODEC_ID_MPEG4, MKTAG('3', 'I', 'V', '2') }, /* experimental: 3IVX files before ivx D4 4.5.1 */
94
/*    { CODEC_ID_, MKTAG('I', 'V', '5', '0') }, *//* Indeo 5.0 */
95
    { CODEC_ID_H263, MKTAG('h', '2', '6', '3') }, /* H263 */
96
    { CODEC_ID_H263, MKTAG('s', '2', '6', '3') }, /* H263 ?? works */
97
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
98
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
99
    { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') }, /* On2 VP3 */
100
    { CODEC_ID_RPZA, MKTAG('r', 'p', 'z', 'a') }, /* Apple Video (RPZA) */
101
    { CODEC_ID_CINEPAK, MKTAG('c', 'v', 'i', 'd') }, /* Cinepak */
102
    { CODEC_ID_8BPS, MKTAG('8', 'B', 'P', 'S') }, /* Planar RGB (8BPS) */
103
    { CODEC_ID_SMC, MKTAG('s', 'm', 'c', ' ') }, /* Apple Graphics (SMC) */
104
    { CODEC_ID_QTRLE, MKTAG('r', 'l', 'e', ' ') }, /* Apple Animation (RLE) */
105
    { CODEC_ID_MSRLE, MKTAG('W', 'R', 'L', 'E') },
106
    { CODEC_ID_QDRAW, MKTAG('q', 'd', 'r', 'w') }, /* QuickDraw */
107
    { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') }, /* AVC-1/H.264 */
108
    { CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '2') }, /* MPEG2 produced by Sony HD camera */
109
    { CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '3') }, /* HDV produced by FCP */
110
    { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '5', 'n') }, /* MPEG2 IMX NTSC 525/60 50mb/s produced by FCP */
111
    { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '5', 'p') }, /* MPEG2 IMX PAL 625/50 50mb/s produced by FCP */
112
    { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '3', 'n') }, /* MPEG2 IMX NTSC 525/60 30mb/s produced by FCP */
113
    { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '3', 'p') }, /* MPEG2 IMX PAL 625/50 30mb/s produced by FCP */
114
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'p', 'p') }, /* DVCPRO PAL produced by FCP */
115
    //{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '5') }, /* DVCPRO HD 50i produced by FCP */
116
    //{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '6') }, /* DVCPRO HD 60i produced by FCP */
117
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'p') }, /* DVCPRO50 PAL produced by FCP */
118
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'n') }, /* DVCPRO50 NTSC produced by FCP */
119
    { CODEC_ID_DVVIDEO, MKTAG('A', 'V', 'd', 'v') }, /* AVID DV */
120
    //{ CODEC_ID_JPEG2000, MKTAG('m', 'j', 'p', '2') }, /* JPEG 2000 produced by FCP */
121
    { CODEC_ID_TARGA, MKTAG('t', 'g', 'a', ' ') }, /* Truevision Targa */
122
    { CODEC_ID_TIFF, MKTAG('t', 'i', 'f', 'f') }, /* TIFF embedded in MOV */
123
    { CODEC_ID_RAWVIDEO, MKTAG('2', 'v', 'u', 'y') }, /* UNCOMPRESSED 8BIT 4:2:2 */
124
    { CODEC_ID_VC1,  MKTAG('v', 'c', '-', '1') }, /* SMPTE RP 2025 */
125
    { CODEC_ID_WMV3, MKTAG('v', 'c', '-', '1') }, /* SMPTE RP 2025 */
126
    { CODEC_ID_PNG,  MKTAG('p', 'n', 'g', ' ') },
127
    { CODEC_ID_NONE, 0 },
128
};
129

    
130
static const AVCodecTag mov_audio_tags[] = {
131
    { CODEC_ID_PCM_S32BE, MKTAG('i', 'n', '3', '2') },
132
    { CODEC_ID_PCM_S24BE, MKTAG('i', 'n', '2', '4') },
133
    { CODEC_ID_PCM_S16BE, MKTAG('N', 'O', 'N', 'E') }, /* uncompressed */
134
    { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') }, /* 16 bits */
135
    { CODEC_ID_PCM_U8, MKTAG('r', 'a', 'w', ' ') }, /* 8 bits unsigned */
136
    { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') }, /*  */
137
    { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') }, /*  */
138
    { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') }, /*  */
139
    { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') }, /* IMA-4 ADPCM */
140
    { CODEC_ID_ADPCM_MS, MKTAG('m', 's', 0x00, 0x02) }, /* MS ADPCM */
141
    { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') }, /* Macintosh Audio Compression and Expansion 3:1 */
142
    { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') }, /* Macintosh Audio Compression and Expansion 6:1 */
143

    
144
    { CODEC_ID_MP3, MKTAG('.', 'm', 'p', '3') }, /* MPEG layer 3 */ /* sample files at http://www.3ivx.com/showcase.html use this tag */
145
    { CODEC_ID_MP2, 0x6D730055 }, /* MPEG layer 3 */
146
    { CODEC_ID_MP2, 0x5500736D }, /* MPEG layer 3 *//* XXX: check endianness */
147
/*    { CODEC_ID_OGG_VORBIS, MKTAG('O', 'g', 'g', 'S') }, *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
148
/* MP4 tags */
149
    { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') }, /* MPEG-4 AAC */
150
    /* The standard for mpeg4 audio is still not normalised AFAIK anyway */
151
    { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') }, /* AMR-NB 3gp */
152
    { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') }, /* AMR-WB 3gp */
153
    { CODEC_ID_AC3, MKTAG('m', 's', 0x20, 0x00) }, /* Dolby AC-3 */
154
    { CODEC_ID_ALAC,MKTAG('a', 'l', 'a', 'c') }, /* Apple Lossless */
155
    { CODEC_ID_QDM2,MKTAG('Q', 'D', 'M', '2') }, /* QDM2 */
156
    { CODEC_ID_DVAUDIO, MKTAG('v', 'd', 'v', 'a') },
157
    { CODEC_ID_DVAUDIO, MKTAG('d', 'v', 'c', 'a') },
158
    { CODEC_ID_PCM_S16LE, MKTAG('l', 'p', 'c', 'm') },
159
    { CODEC_ID_NONE, 0 },
160
};
161

    
162
/* the QuickTime file format is quite convoluted...
163
 * it has lots of index tables, each indexing something in another one...
164
 * Here we just use what is needed to read the chunks
165
 */
166

    
167
typedef struct MOV_sample_to_chunk_tbl {
168
    long first;
169
    long count;
170
    long id;
171
} MOV_sample_to_chunk_tbl;
172

    
173
typedef struct {
174
    uint32_t type;
175
    int64_t offset;
176
    int64_t size; /* total size (excluding the size and type fields) */
177
} MOV_atom_t;
178

    
179
typedef struct {
180
    int seed;
181
    int flags;
182
    int size;
183
    void* clrs;
184
} MOV_ctab_t;
185

    
186
typedef struct MOV_mdat_atom_s {
187
    offset_t offset;
188
    int64_t size;
189
} MOV_mdat_atom_t;
190

    
191
typedef struct {
192
    uint8_t  version;
193
    uint32_t flags; // 24bit
194

    
195
    /* 0x03 ESDescrTag */
196
    uint16_t es_id;
197
#define MP4ODescrTag                    0x01
198
#define MP4IODescrTag                   0x02
199
#define MP4ESDescrTag                   0x03
200
#define MP4DecConfigDescrTag            0x04
201
#define MP4DecSpecificDescrTag          0x05
202
#define MP4SLConfigDescrTag             0x06
203
#define MP4ContentIdDescrTag            0x07
204
#define MP4SupplContentIdDescrTag       0x08
205
#define MP4IPIPtrDescrTag               0x09
206
#define MP4IPMPPtrDescrTag              0x0A
207
#define MP4IPMPDescrTag                 0x0B
208
#define MP4RegistrationDescrTag         0x0D
209
#define MP4ESIDIncDescrTag              0x0E
210
#define MP4ESIDRefDescrTag              0x0F
211
#define MP4FileIODescrTag               0x10
212
#define MP4FileODescrTag                0x11
213
#define MP4ExtProfileLevelDescrTag      0x13
214
#define MP4ExtDescrTagsStart            0x80
215
#define MP4ExtDescrTagsEnd              0xFE
216
    uint8_t  stream_priority;
217

    
218
    /* 0x04 DecConfigDescrTag */
219
    uint8_t  object_type_id;
220
    uint8_t  stream_type;
221
    /* XXX: really streamType is
222
     * only 6bit, followed by:
223
     * 1bit  upStream
224
     * 1bit  reserved
225
     */
226
    uint32_t buffer_size_db; // 24
227
    uint32_t max_bitrate;
228
    uint32_t avg_bitrate;
229

    
230
    /* 0x05 DecSpecificDescrTag */
231
    uint8_t  decoder_cfg_len;
232
    uint8_t *decoder_cfg;
233

    
234
    /* 0x06 SLConfigDescrTag */
235
    uint8_t  sl_config_len;
236
    uint8_t *sl_config;
237
} MOV_esds_t;
238

    
239
struct MOVParseTableEntry;
240

    
241
typedef struct MOVStreamContext {
242
    int ffindex; /* the ffmpeg stream id */
243
    long next_chunk;
244
    long chunk_count;
245
    int64_t *chunk_offsets;
246
    int stts_count;
247
    Time2Sample *stts_data;
248
    int ctts_count;
249
    Time2Sample *ctts_data;
250
    int edit_count;             /* number of 'edit' (elst atom) */
251
    long sample_to_chunk_sz;
252
    MOV_sample_to_chunk_tbl *sample_to_chunk;
253
    int sample_to_ctime_index;
254
    int sample_to_ctime_sample;
255
    long sample_size;
256
    long sample_count;
257
    long *sample_sizes;
258
    long keyframe_count;
259
    long *keyframes;
260
    int time_scale;
261
    int time_rate;
262
    long current_sample;
263
    MOV_esds_t esds;
264
    AVRational sample_size_v1;
265
    int dv_audio_container;
266
} MOVStreamContext;
267

    
268
typedef struct MOVContext {
269
    AVFormatContext *fc;
270
    int time_scale;
271
    int64_t duration; /* duration of the longest track */
272
    int found_moov; /* when both 'moov' and 'mdat' sections has been found */
273
    int found_mdat; /* we suppose we have enough data to read the file */
274
    int64_t mdat_size;
275
    int64_t mdat_offset;
276
    int total_streams;
277
    /* some streams listed here aren't presented to the ffmpeg API, since they aren't either video nor audio
278
     * but we need the info to be able to skip data from those streams in the 'mdat' section
279
     */
280
    MOVStreamContext *streams[MAX_STREAMS];
281

    
282
    int ctab_size;
283
    MOV_ctab_t **ctab;           /* color tables */
284
    const struct MOVParseTableEntry *parse_table; /* could be eventually used to change the table */
285
    /* NOTE: for recursion save to/ restore from local variable! */
286

    
287
    AVPaletteControl palette_control;
288
    MOV_mdat_atom_t *mdat_list;
289
    int mdat_count;
290
    DVDemuxContext *dv_demux;
291
    AVFormatContext *dv_fctx;
292
    int isom; /* 1 if file is ISO Media (mp4/3gp) */
293
} MOVContext;
294

    
295

    
296
/* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
297

    
298
/* those functions parse an atom */
299
/* return code:
300
 1: found what I wanted, exit
301
 0: continue to parse next atom
302
 -1: error occured, exit
303
 */
304
typedef int (*mov_parse_function)(MOVContext *ctx, ByteIOContext *pb, MOV_atom_t atom);
305

    
306
/* links atom IDs to parse functions */
307
typedef struct MOVParseTableEntry {
308
    uint32_t type;
309
    mov_parse_function func;
310
} MOVParseTableEntry;
311

    
312
static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
313
{
314
    int64_t total_size = 0;
315
    MOV_atom_t a;
316
    int i;
317
    int err = 0;
318

    
319
    a.offset = atom.offset;
320

    
321
    if (atom.size < 0)
322
        atom.size = 0x7fffffffffffffffLL;
323
    while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
324
        a.size = atom.size;
325
        a.type=0L;
326
        if(atom.size >= 8) {
327
            a.size = get_be32(pb);
328
            a.type = get_le32(pb);
329
        }
330
        total_size += 8;
331
        a.offset += 8;
332
        dprintf("type: %08x  %.4s  sz: %"PRIx64"  %"PRIx64"   %"PRIx64"\n", a.type, (char*)&a.type, a.size, atom.size, total_size);
333
        if (a.size == 1) { /* 64 bit extended size */
334
            a.size = get_be64(pb) - 8;
335
            a.offset += 8;
336
            total_size += 8;
337
        }
338
        if (a.size == 0) {
339
            a.size = atom.size - total_size;
340
            if (a.size <= 8)
341
                break;
342
        }
343
        for (i = 0; c->parse_table[i].type != 0L
344
             && c->parse_table[i].type != a.type; i++)
345
            /* empty */;
346

    
347
        a.size -= 8;
348

    
349
        if(a.size < 0)
350
            break;
351

    
352
        if (c->parse_table[i].type == 0) { /* skip leaf atoms data */
353
            url_fskip(pb, a.size);
354
        } else {
355
            offset_t start_pos = url_ftell(pb);
356
            int64_t left;
357
            err = (c->parse_table[i].func)(c, pb, a);
358
            left = a.size - url_ftell(pb) + start_pos;
359
            if (left > 0) /* skip garbage at atom end */
360
                url_fskip(pb, left);
361
        }
362

    
363
        a.offset += a.size;
364
        total_size += a.size;
365
    }
366

    
367
    if (!err && total_size < atom.size && atom.size < 0x7ffff) {
368
        url_fskip(pb, atom.size - total_size);
369
    }
370

    
371
    return err;
372
}
373

    
374
static int mov_read_ctab(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
375
{
376
#if 1
377
    url_fskip(pb, atom.size); // for now
378
#else
379
    VERY VERY BROKEN, NEVER execute this, needs rewrite
380
    unsigned int len;
381
    MOV_ctab_t *t;
382
    c->ctab = av_realloc(c->ctab, ++c->ctab_size);
383
    t = c->ctab[c->ctab_size];
384
    t->seed = get_be32(pb);
385
    t->flags = get_be16(pb);
386
    t->size = get_be16(pb) + 1;
387
    len = 2 * t->size * 4;
388
    if (len > 0) {
389
        t->clrs = av_malloc(len); // 16bit A R G B
390
        if (t->clrs)
391
            get_buffer(pb, t->clrs, len);
392
    }
393
#endif
394

    
395
    return 0;
396
}
397

    
398
static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
399
{
400
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
401
    uint32_t type;
402
    uint32_t ctype;
403

    
404
    get_byte(pb); /* version */
405
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
406

    
407
    /* component type */
408
    ctype = get_le32(pb);
409
    type = get_le32(pb); /* component subtype */
410

    
411
    dprintf("ctype= %c%c%c%c (0x%08lx)\n", *((char *)&ctype), ((char *)&ctype)[1], ((char *)&ctype)[2], ((char *)&ctype)[3], (long) ctype);
412
    dprintf("stype= %c%c%c%c\n", *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
413
    if(!ctype)
414
        c->isom = 1;
415
    if(type == MKTAG('v', 'i', 'd', 'e'))
416
        st->codec->codec_type = CODEC_TYPE_VIDEO;
417
    else if(type == MKTAG('s', 'o', 'u', 'n'))
418
        st->codec->codec_type = CODEC_TYPE_AUDIO;
419
    else if(type == MKTAG('m', '1', 'a', ' '))
420
        st->codec->codec_id = CODEC_ID_MP2;
421
    else if(type == MKTAG('s', 'u', 'b', 'p')) {
422
        st->codec->codec_type = CODEC_TYPE_SUBTITLE;
423
        st->codec->codec_id = CODEC_ID_DVD_SUBTITLE;
424
    }
425
    get_be32(pb); /* component  manufacture */
426
    get_be32(pb); /* component flags */
427
    get_be32(pb); /* component flags mask */
428

    
429
    if(atom.size <= 24)
430
        return 0; /* nothing left to read */
431

    
432
    url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
433
    return 0;
434
}
435

    
436
static int mov_mp4_read_descr_len(ByteIOContext *pb)
437
{
438
    int len = 0;
439
    int count = 4;
440
    while (count--) {
441
        int c = get_byte(pb);
442
        len = (len << 7) | (c & 0x7f);
443
        if (!(c & 0x80))
444
            break;
445
    }
446
    return len;
447
}
448

    
449
static int mov_mp4_read_descr(ByteIOContext *pb, int *tag)
450
{
451
    int len;
452
    *tag = get_byte(pb);
453
    len = mov_mp4_read_descr_len(pb);
454
    dprintf("MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
455
    return len;
456
}
457

    
458
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
459
{
460
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
461
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
462
    int tag, len;
463

    
464
    /* Well, broken but suffisant for some MP4 streams */
465
    get_be32(pb); /* version + flags */
466
    len = mov_mp4_read_descr(pb, &tag);
467
    if (tag == MP4ESDescrTag) {
468
        get_be16(pb); /* ID */
469
        get_byte(pb); /* priority */
470
    } else
471
        get_be16(pb); /* ID */
472

    
473
    len = mov_mp4_read_descr(pb, &tag);
474
    if (tag == MP4DecConfigDescrTag) {
475
        sc->esds.object_type_id = get_byte(pb);
476
        sc->esds.stream_type = get_byte(pb);
477
        sc->esds.buffer_size_db = get_be24(pb);
478
        sc->esds.max_bitrate = get_be32(pb);
479
        sc->esds.avg_bitrate = get_be32(pb);
480

    
481
        st->codec->codec_id= codec_get_id(ff_mov_obj_type, sc->esds.object_type_id);
482
        dprintf("esds object type id %d\n", sc->esds.object_type_id);
483
        len = mov_mp4_read_descr(pb, &tag);
484
        if (tag == MP4DecSpecificDescrTag) {
485
            dprintf("Specific MPEG4 header len=%d\n", len);
486
            st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
487
            if (st->codec->extradata) {
488
                get_buffer(pb, st->codec->extradata, len);
489
                st->codec->extradata_size = len;
490
                /* from mplayer */
491
                if ((*st->codec->extradata >> 3) == 29) {
492
                    st->codec->codec_id = CODEC_ID_MP3ON4;
493
                }
494
            }
495
        }
496
    }
497
    return 0;
498
}
499

    
500
/* this atom contains actual media data */
501
static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
502
{
503
    if(atom.size == 0) /* wrong one (MP4) */
504
        return 0;
505
    c->mdat_list = av_realloc(c->mdat_list, (c->mdat_count + 1) * sizeof(*c->mdat_list));
506
    c->mdat_list[c->mdat_count].offset = atom.offset;
507
    c->mdat_list[c->mdat_count].size = atom.size;
508
    c->mdat_count++;
509
    c->found_mdat=1;
510
    c->mdat_offset = atom.offset;
511
    c->mdat_size = atom.size;
512
    if(c->found_moov)
513
        return 1; /* found both, just go */
514
    url_fskip(pb, atom.size);
515
    return 0; /* now go for moov */
516
}
517

    
518
static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
519
{
520
    uint32_t type = get_le32(pb);
521

    
522
    if (type != MKTAG('q','t',' ',' '))
523
        c->isom = 1;
524
    av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
525
    get_be32(pb); /* minor version */
526
    url_fskip(pb, atom.size - 8);
527
    return 0;
528
}
529

    
530
/* this atom should contain all header atoms */
531
static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
532
{
533
    int err;
534

    
535
    err = mov_read_default(c, pb, atom);
536
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
537
    /* so we don't parse the whole file if over a network */
538
    c->found_moov=1;
539
    if(c->found_mdat)
540
        return 1; /* found both, just go */
541
    return 0; /* now go for mdat */
542
}
543

    
544

    
545
static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
546
{
547
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
548
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
549
    int version = get_byte(pb);
550
    int lang;
551

    
552
    if (version > 1)
553
        return 1; /* unsupported */
554

    
555
    get_byte(pb); get_byte(pb);
556
    get_byte(pb); /* flags */
557

    
558
    if (version == 1) {
559
        get_be64(pb);
560
        get_be64(pb);
561
    } else {
562
        get_be32(pb); /* creation time */
563
        get_be32(pb); /* modification time */
564
    }
565

    
566
    sc->time_scale = get_be32(pb);
567
    st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
568

    
569
    lang = get_be16(pb); /* language */
570
    ff_mov_lang_to_iso639(lang, st->language);
571
    get_be16(pb); /* quality */
572

    
573
    return 0;
574
}
575

    
576
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
577
{
578
    int version = get_byte(pb); /* version */
579
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
580

    
581
    if (version == 1) {
582
        get_be64(pb);
583
        get_be64(pb);
584
    } else {
585
        get_be32(pb); /* creation time */
586
        get_be32(pb); /* modification time */
587
    }
588
    c->time_scale = get_be32(pb); /* time scale */
589
#ifdef DEBUG
590
    av_log(NULL, AV_LOG_DEBUG, "time scale = %i\n", c->time_scale);
591
#endif
592
    c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
593
    get_be32(pb); /* preferred scale */
594

    
595
    get_be16(pb); /* preferred volume */
596

    
597
    url_fskip(pb, 10); /* reserved */
598

    
599
    url_fskip(pb, 36); /* display matrix */
600

    
601
    get_be32(pb); /* preview time */
602
    get_be32(pb); /* preview duration */
603
    get_be32(pb); /* poster time */
604
    get_be32(pb); /* selection time */
605
    get_be32(pb); /* selection duration */
606
    get_be32(pb); /* current time */
607
    get_be32(pb); /* next track ID */
608

    
609
    return 0;
610
}
611

    
612
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
613
{
614
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
615

    
616
    if((uint64_t)atom.size > (1<<30))
617
        return -1;
618

    
619
    // currently SVQ3 decoder expect full STSD header - so let's fake it
620
    // this should be fixed and just SMI header should be passed
621
    av_free(st->codec->extradata);
622
    st->codec->extradata_size = 0x5a + atom.size;
623
    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
624

    
625
    if (st->codec->extradata) {
626
        strcpy(st->codec->extradata, "SVQ3"); // fake
627
        get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
628
        dprintf("Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
629
    } else
630
        url_fskip(pb, atom.size);
631

    
632
    return 0;
633
}
634

    
635
static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
636
{
637
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
638
    int little_endian = get_be16(pb);
639

    
640
    if (little_endian) {
641
        switch (st->codec->codec_id) {
642
        case CODEC_ID_PCM_S24BE:
643
            st->codec->codec_id = CODEC_ID_PCM_S24LE;
644
            break;
645
        case CODEC_ID_PCM_S32BE:
646
            st->codec->codec_id = CODEC_ID_PCM_S32LE;
647
            break;
648
        default:
649
            break;
650
        }
651
    }
652
    return 0;
653
}
654

    
655
static int mov_read_alac(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
656
{
657
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
658

    
659
    // currently ALAC decoder expect full atom header - so let's fake it
660
    // this should be fixed and just ALAC header should be passed
661

    
662
    av_free(st->codec->extradata);
663
    st->codec->extradata_size = 36;
664
    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
665

    
666
    if (st->codec->extradata) {
667
        strcpy(st->codec->extradata + 4, "alac"); // fake
668
        get_buffer(pb, st->codec->extradata + 8, 36 - 8);
669
        dprintf("Reading alac %d  %s\n", st->codec->extradata_size, st->codec->extradata);
670
    } else
671
        url_fskip(pb, atom.size);
672
    return 0;
673
}
674

    
675
static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
676
{
677
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
678

    
679
    if((uint64_t)atom.size > (1<<30))
680
        return -1;
681

    
682
    if (st->codec->codec_id == CODEC_ID_QDM2) {
683
        // pass all frma atom to codec, needed at least for QDM2
684
        av_free(st->codec->extradata);
685
        st->codec->extradata_size = atom.size;
686
        st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
687

    
688
        if (st->codec->extradata) {
689
            get_buffer(pb, st->codec->extradata, atom.size);
690
        } else
691
            url_fskip(pb, atom.size);
692
    } else if (atom.size > 8) { /* to read frma, esds atoms */
693
        mov_read_default(c, pb, atom);
694
    } else
695
        url_fskip(pb, atom.size);
696
    return 0;
697
}
698

    
699
static int mov_read_jp2h(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
700
{
701
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
702

    
703
    if((uint64_t)atom.size > (1<<30))
704
        return -1;
705

    
706
    av_free(st->codec->extradata);
707

    
708
    st->codec->extradata_size = atom.size + 8;
709
    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
710

    
711
    /* pass all jp2h atom to codec */
712
    if (st->codec->extradata) {
713
        strcpy(st->codec->extradata + 4, "jp2h");
714
        get_buffer(pb, st->codec->extradata + 8, atom.size);
715
    } else
716
        url_fskip(pb, atom.size);
717
    return 0;
718
}
719

    
720
static int mov_read_avcC(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
721
{
722
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
723

    
724
    if((uint64_t)atom.size > (1<<30))
725
        return -1;
726

    
727
    av_free(st->codec->extradata);
728

    
729
    st->codec->extradata_size = atom.size;
730
    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
731

    
732
    if (st->codec->extradata) {
733
        get_buffer(pb, st->codec->extradata, atom.size);
734
    } else
735
        url_fskip(pb, atom.size);
736

    
737
    return 0;
738
}
739

    
740
static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
741
{
742
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
743
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
744
    unsigned int i, entries;
745

    
746
    get_byte(pb); /* version */
747
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
748

    
749
    entries = get_be32(pb);
750

    
751
    if(entries >= UINT_MAX/sizeof(int64_t))
752
        return -1;
753

    
754
    sc->chunk_count = entries;
755
    sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
756
    if (!sc->chunk_offsets)
757
        return -1;
758
    if (atom.type == MKTAG('s', 't', 'c', 'o')) {
759
        for(i=0; i<entries; i++) {
760
            sc->chunk_offsets[i] = get_be32(pb);
761
        }
762
    } else if (atom.type == MKTAG('c', 'o', '6', '4')) {
763
        for(i=0; i<entries; i++) {
764
            sc->chunk_offsets[i] = get_be64(pb);
765
        }
766
    } else
767
        return -1;
768

    
769
    return 0;
770
}
771

    
772
static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
773
{
774
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
775
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
776
    int entries, frames_per_sample;
777
    uint32_t format;
778
    uint8_t codec_name[32];
779

    
780
    /* for palette traversal */
781
    int color_depth;
782
    int color_start;
783
    int color_count;
784
    int color_end;
785
    int color_index;
786
    int color_dec;
787
    int color_greyscale;
788
    unsigned char *color_table;
789
    int j;
790
    unsigned char r, g, b;
791

    
792
    get_byte(pb); /* version */
793
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
794

    
795
    entries = get_be32(pb);
796

    
797
    while(entries--) { //Parsing Sample description table
798
        enum CodecID id;
799
        MOV_atom_t a = { 0, 0, 0 };
800
        offset_t start_pos = url_ftell(pb);
801
        int size = get_be32(pb); /* size */
802
        format = get_le32(pb); /* data format */
803

    
804
        get_be32(pb); /* reserved */
805
        get_be16(pb); /* reserved */
806
        get_be16(pb); /* index */
807

    
808
        if (st->codec->codec_tag) {
809
            /* multiple fourcc, just skip for now */
810
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
811
            continue;
812
        }
813

    
814
        st->codec->codec_tag = format;
815
        id = codec_get_id(mov_audio_tags, format);
816
        if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
817
            st->codec->codec_type = CODEC_TYPE_AUDIO;
818
        } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
819
                   format && format != MKTAG('m', 'p', '4', 's')) { /* skip old asf mpeg4 tag */
820
            id = codec_get_id(mov_video_tags, format);
821
            if (id <= 0)
822
                id = codec_get_id(codec_bmp_tags, format);
823
            if (id > 0)
824
                st->codec->codec_type = CODEC_TYPE_VIDEO;
825
        }
826

    
827
        dprintf("size=%d 4CC= %c%c%c%c codec_type=%d\n",
828
                size,
829
                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff, (format >> 24) & 0xff,
830
                st->codec->codec_type);
831

    
832
        if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
833
            st->codec->codec_id = id;
834
            get_be16(pb); /* version */
835
            get_be16(pb); /* revision level */
836
            get_be32(pb); /* vendor */
837
            get_be32(pb); /* temporal quality */
838
            get_be32(pb); /* spacial quality */
839

    
840
            st->codec->width = get_be16(pb); /* width */
841
            st->codec->height = get_be16(pb); /* height */
842

    
843
            get_be32(pb); /* horiz resolution */
844
            get_be32(pb); /* vert resolution */
845
            get_be32(pb); /* data size, always 0 */
846
            frames_per_sample = get_be16(pb); /* frames per samples */
847
#ifdef DEBUG
848
            av_log(NULL, AV_LOG_DEBUG, "frames/samples = %d\n", frames_per_sample);
849
#endif
850
            get_buffer(pb, codec_name, 32); /* codec name, pascal string (FIXME: true for mp4?) */
851
            if (codec_name[0] <= 31) {
852
                memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
853
                st->codec->codec_name[codec_name[0]] = 0;
854
            }
855

    
856
            st->codec->bits_per_sample = get_be16(pb); /* depth */
857
            st->codec->color_table_id = get_be16(pb); /* colortable id */
858

    
859
            /* figure out the palette situation */
860
            color_depth = st->codec->bits_per_sample & 0x1F;
861
            color_greyscale = st->codec->bits_per_sample & 0x20;
862

    
863
            /* if the depth is 2, 4, or 8 bpp, file is palettized */
864
            if ((color_depth == 2) || (color_depth == 4) ||
865
                (color_depth == 8)) {
866

    
867
                if (color_greyscale) {
868

    
869
                    /* compute the greyscale palette */
870
                    color_count = 1 << color_depth;
871
                    color_index = 255;
872
                    color_dec = 256 / (color_count - 1);
873
                    for (j = 0; j < color_count; j++) {
874
                        r = g = b = color_index;
875
                        c->palette_control.palette[j] =
876
                            (r << 16) | (g << 8) | (b);
877
                        color_index -= color_dec;
878
                        if (color_index < 0)
879
                            color_index = 0;
880
                    }
881

    
882
                } else if (st->codec->color_table_id & 0x08) {
883

    
884
                    /* if flag bit 3 is set, use the default palette */
885
                    color_count = 1 << color_depth;
886
                    if (color_depth == 2)
887
                        color_table = ff_qt_default_palette_4;
888
                    else if (color_depth == 4)
889
                        color_table = ff_qt_default_palette_16;
890
                    else
891
                        color_table = ff_qt_default_palette_256;
892

    
893
                    for (j = 0; j < color_count; j++) {
894
                        r = color_table[j * 4 + 0];
895
                        g = color_table[j * 4 + 1];
896
                        b = color_table[j * 4 + 2];
897
                        c->palette_control.palette[j] =
898
                            (r << 16) | (g << 8) | (b);
899
                    }
900

    
901
                } else {
902

    
903
                    /* load the palette from the file */
904
                    color_start = get_be32(pb);
905
                    color_count = get_be16(pb);
906
                    color_end = get_be16(pb);
907
                    for (j = color_start; j <= color_end; j++) {
908
                        /* each R, G, or B component is 16 bits;
909
                         * only use the top 8 bits; skip alpha bytes
910
                         * up front */
911
                        get_byte(pb);
912
                        get_byte(pb);
913
                        r = get_byte(pb);
914
                        get_byte(pb);
915
                        g = get_byte(pb);
916
                        get_byte(pb);
917
                        b = get_byte(pb);
918
                        get_byte(pb);
919
                        c->palette_control.palette[j] =
920
                            (r << 16) | (g << 8) | (b);
921
                    }
922
                }
923

    
924
                st->codec->palctrl = &c->palette_control;
925
                st->codec->palctrl->palette_changed = 1;
926
            } else
927
                st->codec->palctrl = NULL;
928
        } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
929
            int bits_per_sample;
930
            uint16_t version = get_be16(pb);
931

    
932
            st->codec->codec_id = id;
933
            get_be16(pb); /* revision level */
934
            get_be32(pb); /* vendor */
935

    
936
            st->codec->channels = get_be16(pb);             /* channel count */
937
            dprintf("audio channels %d\n", st->codec->channels);
938
            st->codec->bits_per_sample = get_be16(pb);      /* sample size */
939
            /* do we need to force to 16 for AMR ? */
940

    
941
            /* handle specific s8 codec */
942
            get_be16(pb); /* compression id = 0*/
943
            get_be16(pb); /* packet size = 0 */
944

    
945
            st->codec->sample_rate = ((get_be32(pb) >> 16));
946

    
947
            switch (st->codec->codec_id) {
948
            case CODEC_ID_PCM_S8:
949
            case CODEC_ID_PCM_U8:
950
                if (st->codec->bits_per_sample == 16)
951
                    st->codec->codec_id = CODEC_ID_PCM_S16BE;
952
                break;
953
            case CODEC_ID_PCM_S16LE:
954
            case CODEC_ID_PCM_S16BE:
955
                if (st->codec->bits_per_sample == 8)
956
                    st->codec->codec_id = CODEC_ID_PCM_S8;
957
                else if (st->codec->bits_per_sample == 24)
958
                    st->codec->codec_id = CODEC_ID_PCM_S24BE;
959
                break;
960
            default:
961
                break;
962
            }
963

    
964
            //Read QT version 1 fields. In version 0 theese dont exist
965
            dprintf("version =%d, isom =%d\n",version,c->isom);
966
            if(!c->isom) {
967
                if(version==1) {
968
                    sc->sample_size_v1.den = get_be32(pb); /* samples per packet */
969
                    get_be32(pb); /* bytes per packet */
970
                    sc->sample_size_v1.num = get_be32(pb); /* bytes per frame */
971
                    get_be32(pb); /* bytes per sample */
972
                } else if(version==2) {
973
                    get_be32(pb); /* sizeof struct only */
974
                    st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
975
                    st->codec->channels = get_be32(pb);
976
                    get_be32(pb); /* always 0x7F000000 */
977
                    get_be32(pb); /* bits per channel if sound is uncompressed */
978
                    get_be32(pb); /* lcpm format specific flag */
979
                    get_be32(pb); /* bytes per audio packet if constant */
980
                    get_be32(pb); /* lpcm frames per audio packet if constant */
981
                }
982
            }
983

    
984
            bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
985
            if (bits_per_sample) {
986
                st->codec->bits_per_sample = bits_per_sample;
987
                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
988
            }
989
        } else {
990
            /* other codec type, just skip (rtp, mp4s, tmcd ...) */
991
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
992
        }
993
        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
994
        a.size = size - (url_ftell(pb) - start_pos);
995
        if (a.size > 8)
996
            mov_read_default(c, pb, a);
997
        else if (a.size > 0)
998
            url_fskip(pb, a.size);
999
    }
1000

    
1001
    if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1) {
1002
        st->codec->sample_rate= sc->time_scale;
1003
    }
1004

    
1005
    /* special codec parameters handling */
1006
    switch (st->codec->codec_id) {
1007
#ifdef CONFIG_H261_DECODER
1008
    case CODEC_ID_H261:
1009
#endif
1010
#ifdef CONFIG_H263_DECODER
1011
    case CODEC_ID_H263:
1012
#endif
1013
#ifdef CONFIG_MPEG4_DECODER
1014
    case CODEC_ID_MPEG4:
1015
#endif
1016
        st->codec->width= 0; /* let decoder init width/height */
1017
        st->codec->height= 0;
1018
        break;
1019
#ifdef CONFIG_LIBFAAD
1020
    case CODEC_ID_AAC:
1021
#endif
1022
#ifdef CONFIG_VORBIS_DECODER
1023
    case CODEC_ID_VORBIS:
1024
#endif
1025
    case CODEC_ID_MP3ON4:
1026
        st->codec->sample_rate= 0; /* let decoder init parameters properly */
1027
        break;
1028
#ifdef CONFIG_DV_DEMUXER
1029
    case CODEC_ID_DVAUDIO:
1030
        c->dv_fctx = av_alloc_format_context();
1031
        c->dv_demux = dv_init_demux(c->dv_fctx);
1032
        if (!c->dv_demux) {
1033
            av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1034
            return -1;
1035
        }
1036
        sc->dv_audio_container = 1;
1037
        st->codec->codec_id = CODEC_ID_PCM_S16LE;
1038
        break;
1039
#endif
1040
    /* no ifdef since parameters are always those */
1041
    case CODEC_ID_AMR_WB:
1042
        st->codec->sample_rate= 16000;
1043
        st->codec->channels= 1; /* really needed */
1044
        break;
1045
    case CODEC_ID_AMR_NB:
1046
        st->codec->sample_rate= 8000;
1047
        st->codec->channels= 1; /* really needed */
1048
        break;
1049
    case CODEC_ID_MP2:
1050
        st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1051
        st->need_parsing = 1;
1052
        break;
1053
    default:
1054
        break;
1055
    }
1056

    
1057
    return 0;
1058
}
1059

    
1060
static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1061
{
1062
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1063
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1064
    unsigned int i, entries;
1065

    
1066
    get_byte(pb); /* version */
1067
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1068

    
1069
    entries = get_be32(pb);
1070

    
1071
    if(entries >= UINT_MAX / sizeof(MOV_sample_to_chunk_tbl))
1072
        return -1;
1073

    
1074
#ifdef DEBUG
1075
av_log(NULL, AV_LOG_DEBUG, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1076
#endif
1077
    sc->sample_to_chunk_sz = entries;
1078
    sc->sample_to_chunk = av_malloc(entries * sizeof(MOV_sample_to_chunk_tbl));
1079
    if (!sc->sample_to_chunk)
1080
        return -1;
1081
    for(i=0; i<entries; i++) {
1082
        sc->sample_to_chunk[i].first = get_be32(pb);
1083
        sc->sample_to_chunk[i].count = get_be32(pb);
1084
        sc->sample_to_chunk[i].id = get_be32(pb);
1085
    }
1086
    return 0;
1087
}
1088

    
1089
static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1090
{
1091
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1092
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1093
    unsigned int i, entries;
1094

    
1095
    get_byte(pb); /* version */
1096
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1097

    
1098
    entries = get_be32(pb);
1099

    
1100
    if(entries >= UINT_MAX / sizeof(long))
1101
        return -1;
1102

    
1103
    sc->keyframe_count = entries;
1104
#ifdef DEBUG
1105
    av_log(NULL, AV_LOG_DEBUG, "keyframe_count = %ld\n", sc->keyframe_count);
1106
#endif
1107
    sc->keyframes = av_malloc(entries * sizeof(long));
1108
    if (!sc->keyframes)
1109
        return -1;
1110
    for(i=0; i<entries; i++) {
1111
        sc->keyframes[i] = get_be32(pb);
1112
#ifdef DEBUG
1113
/*        av_log(NULL, AV_LOG_DEBUG, "keyframes[]=%ld\n", sc->keyframes[i]); */
1114
#endif
1115
    }
1116
    return 0;
1117
}
1118

    
1119
static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1120
{
1121
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1122
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1123
    unsigned int i, entries, sample_size;
1124

    
1125
    get_byte(pb); /* version */
1126
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1127

    
1128
    sample_size = get_be32(pb);
1129
    if (!sc->sample_size) /* do not overwrite value computed in stsd */
1130
        sc->sample_size = sample_size;
1131
    entries = get_be32(pb);
1132
    if(entries >= UINT_MAX / sizeof(long))
1133
        return -1;
1134

    
1135
    sc->sample_count = entries;
1136
    if (sample_size)
1137
        return 0;
1138

    
1139
#ifdef DEBUG
1140
    av_log(NULL, AV_LOG_DEBUG, "sample_size = %ld sample_count = %ld\n", sc->sample_size, sc->sample_count);
1141
#endif
1142
    sc->sample_sizes = av_malloc(entries * sizeof(long));
1143
    if (!sc->sample_sizes)
1144
        return -1;
1145
    for(i=0; i<entries; i++) {
1146
        sc->sample_sizes[i] = get_be32(pb);
1147
#ifdef DEBUG
1148
        av_log(NULL, AV_LOG_DEBUG, "sample_sizes[]=%ld\n", sc->sample_sizes[i]);
1149
#endif
1150
    }
1151
    return 0;
1152
}
1153

    
1154
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1155
{
1156
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1157
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1158
    unsigned int i, entries;
1159
    int64_t duration=0;
1160
    int64_t total_sample_count=0;
1161

    
1162
    get_byte(pb); /* version */
1163
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1164
    entries = get_be32(pb);
1165
    if(entries >= UINT_MAX / sizeof(Time2Sample))
1166
        return -1;
1167

    
1168
    sc->stts_count = entries;
1169
    sc->stts_data = av_malloc(entries * sizeof(Time2Sample));
1170

    
1171
#ifdef DEBUG
1172
av_log(NULL, AV_LOG_DEBUG, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1173
#endif
1174

    
1175
    sc->time_rate=0;
1176

    
1177
    for(i=0; i<entries; i++) {
1178
        int sample_duration;
1179
        int sample_count;
1180

    
1181
        sample_count=get_be32(pb);
1182
        sample_duration = get_be32(pb);
1183
        sc->stts_data[i].count= sample_count;
1184
        sc->stts_data[i].duration= sample_duration;
1185

    
1186
        sc->time_rate= ff_gcd(sc->time_rate, sample_duration);
1187

    
1188
        dprintf("sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1189

    
1190
        duration+=(int64_t)sample_duration*sample_count;
1191
        total_sample_count+=sample_count;
1192
    }
1193

    
1194
    st->nb_frames= total_sample_count;
1195
    if(duration)
1196
        st->duration= duration;
1197
    return 0;
1198
}
1199

    
1200
static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1201
{
1202
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1203
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1204
    unsigned int i, entries;
1205

    
1206
    get_byte(pb); /* version */
1207
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1208
    entries = get_be32(pb);
1209
    if(entries >= UINT_MAX / sizeof(Time2Sample))
1210
        return -1;
1211

    
1212
    sc->ctts_count = entries;
1213
    sc->ctts_data = av_malloc(entries * sizeof(Time2Sample));
1214

    
1215
    dprintf("track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1216

    
1217
    for(i=0; i<entries; i++) {
1218
        int count    =get_be32(pb);
1219
        int duration =get_be32(pb);
1220

    
1221
        if (duration < 0) {
1222
            av_log(c->fc, AV_LOG_ERROR, "negative ctts, ignoring\n");
1223
            sc->ctts_count = 0;
1224
            url_fskip(pb, 8 * (entries - i - 1));
1225
            break;
1226
        }
1227
        sc->ctts_data[i].count   = count;
1228
        sc->ctts_data[i].duration= duration;
1229

    
1230
        sc->time_rate= ff_gcd(sc->time_rate, duration);
1231
    }
1232
    return 0;
1233
}
1234

    
1235
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1236
{
1237
    AVStream *st;
1238
    MOVStreamContext *sc;
1239

    
1240
    st = av_new_stream(c->fc, c->fc->nb_streams);
1241
    if (!st) return -2;
1242
    sc = av_mallocz(sizeof(MOVStreamContext));
1243
    if (!sc) {
1244
        av_free(st);
1245
        return -1;
1246
    }
1247

    
1248
    st->priv_data = sc;
1249
    st->codec->codec_type = CODEC_TYPE_DATA;
1250
    st->start_time = 0; /* XXX: check */
1251
    c->streams[c->fc->nb_streams-1] = sc;
1252

    
1253
    return mov_read_default(c, pb, atom);
1254
}
1255

    
1256
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1257
{
1258
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1259
    int version = get_byte(pb);
1260

    
1261
    get_byte(pb); get_byte(pb);
1262
    get_byte(pb); /* flags */
1263
    /*
1264
    MOV_TRACK_ENABLED 0x0001
1265
    MOV_TRACK_IN_MOVIE 0x0002
1266
    MOV_TRACK_IN_PREVIEW 0x0004
1267
    MOV_TRACK_IN_POSTER 0x0008
1268
    */
1269

    
1270
    if (version == 1) {
1271
        get_be64(pb);
1272
        get_be64(pb);
1273
    } else {
1274
        get_be32(pb); /* creation time */
1275
        get_be32(pb); /* modification time */
1276
    }
1277
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1278
    get_be32(pb); /* reserved */
1279
    st->start_time = 0; /* check */
1280
    (version == 1) ? get_be64(pb) : get_be32(pb); /* highlevel (considering edits) duration in movie timebase */
1281
    get_be32(pb); /* reserved */
1282
    get_be32(pb); /* reserved */
1283

    
1284
    get_be16(pb); /* layer */
1285
    get_be16(pb); /* alternate group */
1286
    get_be16(pb); /* volume */
1287
    get_be16(pb); /* reserved */
1288

    
1289
    url_fskip(pb, 36); /* display matrix */
1290

    
1291
    /* those are fixed-point */
1292
    get_be32(pb); /* track width */
1293
    get_be32(pb); /* track height */
1294

    
1295
    return 0;
1296
}
1297

    
1298
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1299
/* like the files created with Adobe Premiere 5.0, for samples see */
1300
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1301
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1302
{
1303
    int err;
1304

    
1305
    if (atom.size < 8)
1306
        return 0; /* continue */
1307
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1308
        url_fskip(pb, atom.size - 4);
1309
        return 0;
1310
    }
1311
    atom.type = get_le32(pb);
1312
    atom.offset += 8;
1313
    atom.size -= 8;
1314
    if (atom.type != MKTAG('m', 'd', 'a', 't')) {
1315
        url_fskip(pb, atom.size);
1316
        return 0;
1317
    }
1318
    err = mov_read_mdat(c, pb, atom);
1319
    return err;
1320
}
1321

    
1322
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1323
{
1324
#ifdef CONFIG_ZLIB
1325
    ByteIOContext ctx;
1326
    uint8_t *cmov_data;
1327
    uint8_t *moov_data; /* uncompressed data */
1328
    long cmov_len, moov_len;
1329
    int ret;
1330

    
1331
    get_be32(pb); /* dcom atom */
1332
    if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
1333
        return -1;
1334
    if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
1335
        av_log(NULL, AV_LOG_ERROR, "unknown compression for cmov atom !");
1336
        return -1;
1337
    }
1338
    get_be32(pb); /* cmvd atom */
1339
    if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
1340
        return -1;
1341
    moov_len = get_be32(pb); /* uncompressed size */
1342
    cmov_len = atom.size - 6 * 4;
1343

    
1344
    cmov_data = av_malloc(cmov_len);
1345
    if (!cmov_data)
1346
        return -1;
1347
    moov_data = av_malloc(moov_len);
1348
    if (!moov_data) {
1349
        av_free(cmov_data);
1350
        return -1;
1351
    }
1352
    get_buffer(pb, cmov_data, cmov_len);
1353
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1354
        return -1;
1355
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
1356
        return -1;
1357
    atom.type = MKTAG( 'm', 'o', 'o', 'v' );
1358
    atom.offset = 0;
1359
    atom.size = moov_len;
1360
#ifdef DEBUG
1361
//    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1362
#endif
1363
    ret = mov_read_default(c, &ctx, atom);
1364
    av_free(moov_data);
1365
    av_free(cmov_data);
1366
    return ret;
1367
#else
1368
    av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
1369
    return -1;
1370
#endif
1371
}
1372

    
1373
/* edit list atom */
1374
static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1375
{
1376
    int i, edit_count;
1377

    
1378
    get_byte(pb); /* version */
1379
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1380
    edit_count= c->streams[c->fc->nb_streams-1]->edit_count = get_be32(pb);     /* entries */
1381

    
1382
    for(i=0; i<edit_count; i++){
1383
        get_be32(pb); /* Track duration */
1384
        get_be32(pb); /* Media time */
1385
        get_be32(pb); /* Media rate */
1386
    }
1387
    dprintf("track[%i].edit_count = %i\n", c->fc->nb_streams-1, c->streams[c->fc->nb_streams-1]->edit_count);
1388
    return 0;
1389
}
1390

    
1391
static const MOVParseTableEntry mov_default_parse_table[] = {
1392
/* mp4 atoms */
1393
{ MKTAG( 'c', 'o', '6', '4' ), mov_read_stco },
1394
{ MKTAG( 'c', 't', 't', 's' ), mov_read_ctts }, /* composition time to sample */
1395
{ MKTAG( 'e', 'd', 't', 's' ), mov_read_default },
1396
{ MKTAG( 'e', 'l', 's', 't' ), mov_read_elst },
1397
{ MKTAG( 'e', 'n', 'd', 'a' ), mov_read_enda },
1398
{ MKTAG( 'f', 't', 'y', 'p' ), mov_read_ftyp },
1399
{ MKTAG( 'h', 'd', 'l', 'r' ), mov_read_hdlr },
1400
{ MKTAG( 'j', 'p', '2', 'h' ), mov_read_jp2h },
1401
{ MKTAG( 'm', 'd', 'a', 't' ), mov_read_mdat },
1402
{ MKTAG( 'm', 'd', 'h', 'd' ), mov_read_mdhd },
1403
{ MKTAG( 'm', 'd', 'i', 'a' ), mov_read_default },
1404
{ MKTAG( 'm', 'i', 'n', 'f' ), mov_read_default },
1405
{ MKTAG( 'm', 'o', 'o', 'v' ), mov_read_moov },
1406
{ MKTAG( 'm', 'v', 'h', 'd' ), mov_read_mvhd },
1407
{ MKTAG( 'S', 'M', 'I', ' ' ), mov_read_smi }, /* Sorenson extension ??? */
1408
{ MKTAG( 'a', 'l', 'a', 'c' ), mov_read_alac }, /* alac specific atom */
1409
{ MKTAG( 'a', 'v', 'c', 'C' ), mov_read_avcC },
1410
{ MKTAG( 's', 't', 'b', 'l' ), mov_read_default },
1411
{ MKTAG( 's', 't', 'c', 'o' ), mov_read_stco },
1412
{ MKTAG( 's', 't', 's', 'c' ), mov_read_stsc },
1413
{ MKTAG( 's', 't', 's', 'd' ), mov_read_stsd }, /* sample description */
1414
{ MKTAG( 's', 't', 's', 's' ), mov_read_stss }, /* sync sample */
1415
{ MKTAG( 's', 't', 's', 'z' ), mov_read_stsz }, /* sample size */
1416
{ MKTAG( 's', 't', 't', 's' ), mov_read_stts },
1417
{ MKTAG( 't', 'k', 'h', 'd' ), mov_read_tkhd }, /* track header */
1418
{ MKTAG( 't', 'r', 'a', 'k' ), mov_read_trak },
1419
{ MKTAG( 'w', 'a', 'v', 'e' ), mov_read_wave },
1420
{ MKTAG( 'c', 't', 'a', 'b' ), mov_read_ctab },
1421
{ MKTAG( 'e', 's', 'd', 's' ), mov_read_esds },
1422
{ MKTAG( 'w', 'i', 'd', 'e' ), mov_read_wide }, /* place holder */
1423
{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_cmov },
1424
{ 0L, NULL }
1425
};
1426

    
1427
static void mov_free_stream_context(MOVStreamContext *sc)
1428
{
1429
    if(sc) {
1430
        av_freep(&sc->ctts_data);
1431
        av_freep(&sc);
1432
    }
1433
}
1434

    
1435
/* XXX: is it sufficient ? */
1436
static int mov_probe(AVProbeData *p)
1437
{
1438
    unsigned int offset;
1439
    uint32_t tag;
1440
    int score = 0;
1441

    
1442
    /* check file header */
1443
    if (p->buf_size <= 12)
1444
        return 0;
1445
    offset = 0;
1446
    for(;;) {
1447
        /* ignore invalid offset */
1448
        if ((offset + 8) > (unsigned int)p->buf_size)
1449
            return score;
1450
        tag = AV_RL32(p->buf + offset + 4);
1451
        switch(tag) {
1452
        /* check for obvious tags */
1453
        case MKTAG( 'j', 'P', ' ', ' ' ): /* jpeg 2000 signature */
1454
        case MKTAG( 'm', 'o', 'o', 'v' ):
1455
        case MKTAG( 'm', 'd', 'a', 't' ):
1456
        case MKTAG( 'p', 'n', 'o', 't' ): /* detect movs with preview pics like ew.mov and april.mov */
1457
        case MKTAG( 'u', 'd', 't', 'a' ): /* Packet Video PVAuthor adds this and a lot of more junk */
1458
            return AVPROBE_SCORE_MAX;
1459
        /* those are more common words, so rate then a bit less */
1460
        case MKTAG( 'w', 'i', 'd', 'e' ):
1461
        case MKTAG( 'f', 'r', 'e', 'e' ):
1462
        case MKTAG( 'j', 'u', 'n', 'k' ):
1463
        case MKTAG( 'p', 'i', 'c', 't' ):
1464
            return AVPROBE_SCORE_MAX - 5;
1465
        case MKTAG( 'f', 't', 'y', 'p' ):
1466
        case MKTAG( 's', 'k', 'i', 'p' ):
1467
        case MKTAG( 'u', 'u', 'i', 'd' ):
1468
            offset = AV_RB32(p->buf+offset) + offset;
1469
            /* if we only find those cause probedata is too small at least rate them */
1470
            score = AVPROBE_SCORE_MAX - 50;
1471
            break;
1472
        default:
1473
            /* unrecognized tag */
1474
            return score;
1475
        }
1476
    }
1477
    return score;
1478
}
1479

    
1480
static void mov_build_index(MOVContext *mov, AVStream *st)
1481
{
1482
    MOVStreamContext *sc = st->priv_data;
1483
    offset_t current_offset;
1484
    int64_t current_dts = 0;
1485
    int stts_index = 0;
1486
    int stsc_index = 0;
1487
    int stss_index = 0;
1488
    int i, j, k;
1489

    
1490
    if (sc->sample_sizes || st->codec->codec_type == CODEC_TYPE_VIDEO || sc->dv_audio_container) {
1491
        int keyframe, sample_size;
1492
        int current_sample = 0;
1493
        int stts_sample = 0;
1494
        int distance = 0;
1495

    
1496
        st->nb_frames = sc->sample_count;
1497
        for (i = 0; i < sc->chunk_count; i++) {
1498
            current_offset = sc->chunk_offsets[i];
1499
            if (stsc_index + 1 < sc->sample_to_chunk_sz && i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1500
                stsc_index++;
1501
            for (j = 0; j < sc->sample_to_chunk[stsc_index].count; j++) {
1502
                keyframe = !sc->keyframe_count || current_sample + 1 == sc->keyframes[stss_index];
1503
                if (keyframe) {
1504
                    distance = 0;
1505
                    if (stss_index + 1 < sc->keyframe_count)
1506
                        stss_index++;
1507
                }
1508
                sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1509
                dprintf("AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", size %d, distance %d, keyframe %d\n",
1510
                        st->index, current_sample, current_offset, current_dts, sample_size, distance, keyframe);
1511
                av_add_index_entry(st, current_offset, current_dts, sample_size, distance, keyframe ? AVINDEX_KEYFRAME : 0);
1512
                current_offset += sample_size;
1513
                assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
1514
                current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
1515
                distance++;
1516
                stts_sample++;
1517
                if (current_sample + 1 < sc->sample_count)
1518
                    current_sample++;
1519
                if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1520
                    stts_sample = 0;
1521
                    stts_index++;
1522
                }
1523
            }
1524
        }
1525
    } else { /* read whole chunk */
1526
        int chunk_samples, chunk_size, chunk_duration;
1527

    
1528
        for (i = 0; i < sc->chunk_count; i++) {
1529
            current_offset = sc->chunk_offsets[i];
1530
            if (stsc_index + 1 < sc->sample_to_chunk_sz && i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1531
                stsc_index++;
1532
            chunk_samples = sc->sample_to_chunk[stsc_index].count;
1533
            /* get chunk size */
1534
            if (sc->sample_size > 1 || st->codec->codec_id == CODEC_ID_PCM_U8 || st->codec->codec_id == CODEC_ID_PCM_S8)
1535
                chunk_size = chunk_samples * sc->sample_size;
1536
            else if (sc->sample_size_v1.den > 0 && (chunk_samples * sc->sample_size_v1.num % sc->sample_size_v1.den == 0))
1537
                chunk_size = chunk_samples * sc->sample_size_v1.num / sc->sample_size_v1.den;
1538
            else { /* workaround to find nearest next chunk offset */
1539
                chunk_size = INT_MAX;
1540
                for (j = 0; j < mov->total_streams; j++) {
1541
                    MOVStreamContext *msc = mov->streams[j];
1542

    
1543
                    for (k = msc->next_chunk; k < msc->chunk_count; k++) {
1544
                        if (msc->chunk_offsets[k] > current_offset && msc->chunk_offsets[k] - current_offset < chunk_size) {
1545
                            chunk_size = msc->chunk_offsets[k] - current_offset;
1546
                            msc->next_chunk = k;
1547
                            break;
1548
                        }
1549
                    }
1550
                }
1551
                /* check for last chunk */
1552
                if (chunk_size == INT_MAX)
1553
                    for (j = 0; j < mov->mdat_count; j++) {
1554
                        dprintf("mdat %d, offset %"PRIx64", size %"PRId64", current offset %"PRIx64"\n",
1555
                                j, mov->mdat_list[j].offset, mov->mdat_list[j].size, current_offset);
1556
                        if (mov->mdat_list[j].offset <= current_offset && mov->mdat_list[j].offset + mov->mdat_list[j].size > current_offset)
1557
                            chunk_size = mov->mdat_list[j].offset + mov->mdat_list[j].size - current_offset;
1558
                    }
1559
                assert(chunk_size != INT_MAX);
1560
                for (j = 0; j < mov->total_streams; j++) {
1561
                    mov->streams[j]->next_chunk = 0;
1562
                }
1563
            }
1564
            av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
1565
            /* get chunk duration */
1566
            chunk_duration = 0;
1567
            while (chunk_samples > 0) {
1568
                if (chunk_samples < sc->stts_data[stts_index].count) {
1569
                    chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1570
                    sc->stts_data[stts_index].count -= chunk_samples;
1571
                    break;
1572
                } else {
1573
                    chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1574
                    chunk_samples -= sc->stts_data[stts_index].count;
1575
                    if (stts_index + 1 < sc->stts_count) {
1576
                        stts_index++;
1577
                    }
1578
                }
1579
            }
1580
            dprintf("AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", size %d, duration %d\n",
1581
                    st->index, i, current_offset, current_dts, chunk_size, chunk_duration);
1582
            assert(chunk_duration % sc->time_rate == 0);
1583
            current_dts += chunk_duration / sc->time_rate;
1584
        }
1585
    }
1586
    /* adjust sample count to avindex entries */
1587
    sc->sample_count = st->nb_index_entries;
1588
}
1589

    
1590
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1591
{
1592
    MOVContext *mov = (MOVContext *) s->priv_data;
1593
    ByteIOContext *pb = &s->pb;
1594
    int i, err;
1595
    MOV_atom_t atom = { 0, 0, 0 };
1596

    
1597
    mov->fc = s;
1598
    mov->parse_table = mov_default_parse_table;
1599

    
1600
    if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1601
        atom.size = url_fsize(pb);
1602
    else
1603
        atom.size = 0x7FFFFFFFFFFFFFFFLL;
1604

    
1605
    /* check MOV header */
1606
    err = mov_read_default(mov, pb, atom);
1607
    if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
1608
        av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%"PRId64"\n",
1609
                err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1610
        return -1;
1611
    }
1612
    dprintf("on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1613

    
1614
    /* some cleanup : make sure we are on the mdat atom */
1615
    if(!url_is_streamed(pb) && (url_ftell(pb) != mov->mdat_offset))
1616
        url_fseek(pb, mov->mdat_offset, SEEK_SET);
1617

    
1618
    mov->total_streams = s->nb_streams;
1619

    
1620
    for(i=0; i<mov->total_streams; i++) {
1621
        MOVStreamContext *sc = mov->streams[i];
1622

    
1623
        if(!sc->time_rate)
1624
            sc->time_rate=1;
1625
        if(!sc->time_scale)
1626
            sc->time_scale= mov->time_scale;
1627
        av_set_pts_info(s->streams[i], 64, sc->time_rate, sc->time_scale);
1628

    
1629
        if(s->streams[i]->duration != AV_NOPTS_VALUE){
1630
            assert(s->streams[i]->duration % sc->time_rate == 0);
1631
            s->streams[i]->duration /= sc->time_rate;
1632
        }
1633
        sc->ffindex = i;
1634
        mov_build_index(mov, s->streams[i]);
1635
    }
1636

    
1637
    for(i=0; i<mov->total_streams; i++) {
1638
        /* dont need those anymore */
1639
        av_freep(&mov->streams[i]->chunk_offsets);
1640
        av_freep(&mov->streams[i]->sample_to_chunk);
1641
        av_freep(&mov->streams[i]->sample_sizes);
1642
        av_freep(&mov->streams[i]->keyframes);
1643
        av_freep(&mov->streams[i]->stts_data);
1644
    }
1645
    av_freep(&mov->mdat_list);
1646
    return 0;
1647
}
1648

    
1649
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1650
{
1651
    MOVContext *mov = s->priv_data;
1652
    MOVStreamContext *sc = 0;
1653
    AVIndexEntry *sample = 0;
1654
    int64_t best_dts = INT64_MAX;
1655
    int i;
1656

    
1657
    for (i = 0; i < mov->total_streams; i++) {
1658
        MOVStreamContext *msc = mov->streams[i];
1659

    
1660
        if (s->streams[i]->discard != AVDISCARD_ALL && msc->current_sample < msc->sample_count) {
1661
            AVIndexEntry *current_sample = &s->streams[i]->index_entries[msc->current_sample];
1662
            int64_t dts = av_rescale(current_sample->timestamp * (int64_t)msc->time_rate, AV_TIME_BASE, msc->time_scale);
1663

    
1664
            dprintf("stream %d, sample %ld, dts %"PRId64"\n", i, msc->current_sample, dts);
1665
            if (dts < best_dts) {
1666
                sample = current_sample;
1667
                best_dts = dts;
1668
                sc = msc;
1669
            }
1670
        }
1671
    }
1672
    if (!sample)
1673
        return -1;
1674
    /* must be done just before reading, to avoid infinite loop on sample */
1675
    sc->current_sample++;
1676
    if (sample->pos >= url_fsize(&s->pb)) {
1677
        av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n", sc->ffindex, sample->pos);
1678
        return -1;
1679
    }
1680
#ifdef CONFIG_DV_DEMUXER
1681
    if (sc->dv_audio_container) {
1682
        dv_get_packet(mov->dv_demux, pkt);
1683
        dprintf("dv audio pkt size %d\n", pkt->size);
1684
    } else {
1685
#endif
1686
        url_fseek(&s->pb, sample->pos, SEEK_SET);
1687
        av_get_packet(&s->pb, pkt, sample->size);
1688
#ifdef CONFIG_DV_DEMUXER
1689
        if (mov->dv_demux) {
1690
            void *pkt_destruct_func = pkt->destruct;
1691
            dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
1692
            pkt->destruct = pkt_destruct_func;
1693
        }
1694
    }
1695
#endif
1696
    pkt->stream_index = sc->ffindex;
1697
    pkt->dts = sample->timestamp;
1698
    if (sc->ctts_data) {
1699
        assert(sc->ctts_data[sc->sample_to_ctime_index].duration % sc->time_rate == 0);
1700
        pkt->pts = pkt->dts + sc->ctts_data[sc->sample_to_ctime_index].duration / sc->time_rate;
1701
        /* update ctts context */
1702
        sc->sample_to_ctime_sample++;
1703
        if (sc->sample_to_ctime_index < sc->ctts_count && sc->ctts_data[sc->sample_to_ctime_index].count == sc->sample_to_ctime_sample) {
1704
            sc->sample_to_ctime_index++;
1705
            sc->sample_to_ctime_sample = 0;
1706
        }
1707
    } else {
1708
        pkt->pts = pkt->dts;
1709
    }
1710
    pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
1711
    pkt->pos = sample->pos;
1712
    dprintf("stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n", pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
1713
    return 0;
1714
}
1715

    
1716
static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
1717
{
1718
    MOVStreamContext *sc = st->priv_data;
1719
    int sample, time_sample;
1720
    int i;
1721

    
1722
    sample = av_index_search_timestamp(st, timestamp, flags);
1723
    dprintf("stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
1724
    if (sample < 0) /* not sure what to do */
1725
        return -1;
1726
    sc->current_sample = sample;
1727
    dprintf("stream %d, found sample %ld\n", st->index, sc->current_sample);
1728
    /* adjust ctts index */
1729
    if (sc->ctts_data) {
1730
        time_sample = 0;
1731
        for (i = 0; i < sc->ctts_count; i++) {
1732
            time_sample += sc->ctts_data[i].count;
1733
            if (time_sample >= sc->current_sample) {
1734
                sc->sample_to_ctime_index = i;
1735
                sc->sample_to_ctime_sample = time_sample - sc->current_sample;
1736
                break;
1737
            }
1738
        }
1739
    }
1740
    return sample;
1741
}
1742

    
1743
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1744
{
1745
    AVStream *st;
1746
    int64_t seek_timestamp, timestamp;
1747
    int sample;
1748
    int i;
1749

    
1750
    if (stream_index >= s->nb_streams)
1751
        return -1;
1752

    
1753
    st = s->streams[stream_index];
1754
    sample = mov_seek_stream(st, sample_time, flags);
1755
    if (sample < 0)
1756
        return -1;
1757

    
1758
    /* adjust seek timestamp to found sample timestamp */
1759
    seek_timestamp = st->index_entries[sample].timestamp;
1760

    
1761
    for (i = 0; i < s->nb_streams; i++) {
1762
        st = s->streams[i];
1763
        if (stream_index == i || st->discard == AVDISCARD_ALL)
1764
            continue;
1765

    
1766
        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
1767
        mov_seek_stream(st, timestamp, flags);
1768
    }
1769
    return 0;
1770
}
1771

    
1772
static int mov_read_close(AVFormatContext *s)
1773
{
1774
    int i;
1775
    MOVContext *mov = (MOVContext *) s->priv_data;
1776
    for(i=0; i<mov->total_streams; i++)
1777
        mov_free_stream_context(mov->streams[i]);
1778
    /* free color tabs */
1779
    for(i=0; i<mov->ctab_size; i++)
1780
        av_freep(&mov->ctab[i]);
1781
    if(mov->dv_demux){
1782
        for(i=0; i<mov->dv_fctx->nb_streams; i++){
1783
            av_freep(&mov->dv_fctx->streams[i]->codec);
1784
            av_freep(&mov->dv_fctx->streams[i]);
1785
        }
1786
        av_freep(&mov->dv_fctx);
1787
        av_freep(&mov->dv_demux);
1788
    }
1789
    av_freep(&mov->ctab);
1790
    return 0;
1791
}
1792

    
1793
AVInputFormat mov_demuxer = {
1794
    "mov,mp4,m4a,3gp,3g2,mj2",
1795
    "QuickTime/MPEG4/Motion JPEG 2000 format",
1796
    sizeof(MOVContext),
1797
    mov_probe,
1798
    mov_read_header,
1799
    mov_read_packet,
1800
    mov_read_close,
1801
    mov_read_seek,
1802
};