Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ b9866ebc

History | View | Annotate | Download (71.8 KB)

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

    
20
#include <limits.h>
21
 
22
#include "avformat.h"
23
#include "avi.h"
24

    
25
#ifdef CONFIG_ZLIB
26
#include <zlib.h>
27
#endif
28

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

    
57
//#define DEBUG
58
#ifdef DEBUG
59
#include <stdio.h>
60
#include <fcntl.h>
61
#endif
62

    
63
#include "qtpalette.h"
64

    
65

    
66
/* Allows seeking (MOV_SPLIT_CHUNKS should also be defined) */
67
#define MOV_SEEK
68

    
69
/* allows chunk splitting - should work now... */
70
/* in case you can't read a file, try commenting */
71
#define MOV_SPLIT_CHUNKS
72

    
73
/* Special handling for movies created with Minolta Dimaxe Xi*/
74
/* this fix should not interfere with other .mov files, but just in case*/
75
#define MOV_MINOLTA_FIX
76

    
77
/* some streams in QT (and in MP4 mostly) aren't either video nor audio */
78
/* so we first list them as this, then clean up the list of streams we give back, */
79
/* getting rid of these */
80
#define CODEC_TYPE_MOV_OTHER        (enum CodecType) 2
81

    
82
static const CodecTag mov_video_tags[] = {
83
/*  { CODEC_ID_, MKTAG('c', 'v', 'i', 'd') }, *//* Cinepak */
84
/*  { CODEC_ID_H263, MKTAG('r', 'a', 'w', ' ') }, *//* Uncompressed RGB */
85
/*  { CODEC_ID_H263, MKTAG('Y', 'u', 'v', '2') }, *//* Uncompressed YUV422 */
86
/*    { CODEC_ID_RAWVIDEO, MKTAG('A', 'V', 'U', 'I') }, *//* YUV with alpha-channel (AVID Uncompressed) */
87
/* Graphics */
88
/* Animation */
89
/* Apple video */
90
/* Kodak Photo CD */
91
    { CODEC_ID_MJPEG, MKTAG('j', 'p', 'e', 'g') }, /* PhotoJPEG */
92
    { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'e', 'g') }, /* MPEG */
93
    { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'a') }, /* Motion-JPEG (format A) */
94
    { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'b') }, /* Motion-JPEG (format B) */
95
    { CODEC_ID_MJPEG, MKTAG('A', 'V', 'D', 'J') }, /* MJPEG with alpha-channel (AVID JFIF meridien compressed) */
96
/*    { CODEC_ID_MJPEG, MKTAG('A', 'V', 'R', 'n') }, *//* MJPEG with alpha-channel (AVID ABVB/Truevision NuVista) */
97
/*    { CODEC_ID_GIF, MKTAG('g', 'i', 'f', ' ') }, *//* embedded gif files as frames (usually one "click to play movie" frame) */
98
/* Sorenson video */
99
    { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') }, /* Sorenson Video v1 */
100
    { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', '1') }, /* Sorenson Video v1 */
101
    { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', 'i') }, /* Sorenson Video v1 (from QT specs)*/
102
    { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') }, /* Sorenson Video v3 */
103
    { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
104
    { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', 'X') }, /* OpenDiVX *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
105
    { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') },
106
/*    { CODEC_ID_, MKTAG('I', 'V', '5', '0') }, *//* Indeo 5.0 */
107
    { CODEC_ID_H263, MKTAG('h', '2', '6', '3') }, /* H263 */
108
    { CODEC_ID_H263, MKTAG('s', '2', '6', '3') }, /* H263 ?? works */
109
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
110
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
111
/*    { CODEC_ID_DVVIDEO, MKTAG('A', 'V', 'd', 'v') }, *//* AVID dv */
112
    { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') }, /* On2 VP3 */
113
    { CODEC_ID_RPZA, MKTAG('r', 'p', 'z', 'a') }, /* Apple Video (RPZA) */
114
    { CODEC_ID_CINEPAK, MKTAG('c', 'v', 'i', 'd') }, /* Cinepak */
115
    { CODEC_ID_8BPS, MKTAG('8', 'B', 'P', 'S') }, /* Planar RGB (8BPS) */
116
    { CODEC_ID_SMC, MKTAG('s', 'm', 'c', ' ') }, /* Apple Graphics (SMC) */
117
    { CODEC_ID_QTRLE, MKTAG('r', 'l', 'e', ' ') }, /* Apple Animation (RLE) */
118
    { CODEC_ID_QDRAW, MKTAG('q', 'd', 'r', 'w') }, /* QuickDraw */
119
    { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') }, /* AVC-1/H.264 */
120
    { CODEC_ID_NONE, 0 },
121
};
122

    
123
static const CodecTag mov_audio_tags[] = {
124
/*    { CODEC_ID_PCM_S16BE, MKTAG('N', 'O', 'N', 'E') }, *//* uncompressed */
125
    { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') }, /* 16 bits */
126
    /* { CODEC_ID_PCM_S8, MKTAG('t', 'w', 'o', 's') },*/ /* 8 bits */
127
    { CODEC_ID_PCM_U8, MKTAG('r', 'a', 'w', ' ') }, /* 8 bits unsigned */
128
    { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') }, /*  */
129
    { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') }, /*  */
130
    { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') }, /*  */
131
    { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') }, /* IMA-4 ADPCM */
132
    { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') }, /* Macintosh Audio Compression and Expansion 3:1 */
133
    { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') }, /* Macintosh Audio Compression and Expansion 6:1 */
134

    
135
    { CODEC_ID_MP2, MKTAG('.', 'm', 'p', '3') }, /* MPEG layer 3 */ /* sample files at http://www.3ivx.com/showcase.html use this tag */
136
    { CODEC_ID_MP2, 0x6D730055 }, /* MPEG layer 3 */
137
    { CODEC_ID_MP2, 0x5500736D }, /* MPEG layer 3 *//* XXX: check endianness */
138
/*    { CODEC_ID_OGG_VORBIS, MKTAG('O', 'g', 'g', 'S') }, *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
139
/* MP4 tags */
140
    { CODEC_ID_MPEG4AAC, MKTAG('m', 'p', '4', 'a') }, /* MPEG-4 AAC */
141
    /* The standard for mpeg4 audio is still not normalised AFAIK anyway */
142
    { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') }, /* AMR-NB 3gp */
143
    { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') }, /* AMR-WB 3gp */
144
    { CODEC_ID_AC3, MKTAG('m', 's', 0x20, 0x00) }, /* Dolby AC-3 */
145
    { CODEC_ID_NONE, 0 },
146
};
147

    
148
/* the QuickTime file format is quite convoluted...
149
 * it has lots of index tables, each indexing something in another one...
150
 * Here we just use what is needed to read the chunks
151
 */
152

    
153
typedef struct MOV_sample_to_chunk_tbl {
154
    long first;
155
    long count;
156
    long id;
157
} MOV_sample_to_chunk_tbl;
158

    
159
typedef struct {
160
    uint32_t type;
161
    int64_t offset;
162
    int64_t size; /* total size (excluding the size and type fields) */
163
} MOV_atom_t;
164

    
165
typedef struct {
166
    int seed;
167
    int flags;
168
    int size;
169
    void* clrs;
170
} MOV_ctab_t;
171

    
172
typedef struct {
173
    uint8_t  version;
174
    uint32_t flags; // 24bit
175

    
176
    /* 0x03 ESDescrTag */
177
    uint16_t es_id;
178
#define MP4ODescrTag                        0x01
179
#define MP4IODescrTag                        0x02
180
#define MP4ESDescrTag                        0x03
181
#define MP4DecConfigDescrTag                0x04
182
#define MP4DecSpecificDescrTag                0x05
183
#define MP4SLConfigDescrTag                0x06
184
#define MP4ContentIdDescrTag                0x07
185
#define MP4SupplContentIdDescrTag        0x08
186
#define MP4IPIPtrDescrTag                0x09
187
#define MP4IPMPPtrDescrTag                0x0A
188
#define MP4IPMPDescrTag                        0x0B
189
#define MP4RegistrationDescrTag                0x0D
190
#define MP4ESIDIncDescrTag                0x0E
191
#define MP4ESIDRefDescrTag                0x0F
192
#define MP4FileIODescrTag                0x10
193
#define MP4FileODescrTag                0x11
194
#define MP4ExtProfileLevelDescrTag        0x13
195
#define MP4ExtDescrTagsStart                0x80
196
#define MP4ExtDescrTagsEnd                0xFE
197
    uint8_t  stream_priority;
198

    
199
    /* 0x04 DecConfigDescrTag */
200
    uint8_t  object_type_id;
201
    uint8_t  stream_type;
202
    /* XXX: really streamType is
203
     * only 6bit, followed by:
204
     * 1bit  upStream
205
     * 1bit  reserved
206
     */
207
    uint32_t buffer_size_db; // 24
208
    uint32_t max_bitrate;
209
    uint32_t avg_bitrate;
210

    
211
    /* 0x05 DecSpecificDescrTag */
212
    uint8_t  decoder_cfg_len;
213
    uint8_t *decoder_cfg;
214

    
215
    /* 0x06 SLConfigDescrTag */
216
    uint8_t  sl_config_len;
217
    uint8_t *sl_config;
218
} MOV_esds_t;
219

    
220
struct MOVParseTableEntry;
221

    
222
typedef struct MOVStreamContext {
223
    int ffindex; /* the ffmpeg stream id */
224
    int is_ff_stream; /* Is this stream presented to ffmpeg ? i.e. is this an audio or video stream ? */
225
    long next_chunk;
226
    long chunk_count;
227
    int64_t *chunk_offsets;
228
    int32_t stts_count;
229
    uint64_t *stts_data;            /* concatenated data from the time-to-sample atom (count|duration) */
230
    int32_t edit_count;             /* number of 'edit' (elst atom) */
231
    long sample_to_chunk_sz;
232
    MOV_sample_to_chunk_tbl *sample_to_chunk;
233
    long sample_to_chunk_index;
234
    long sample_size;
235
    long sample_count;
236
    long *sample_sizes;
237
    long keyframe_count;
238
    long *keyframes;
239
    int time_scale;
240
    long current_sample;
241
    long left_in_chunk; /* how many samples before next chunk */
242
    /* specific MPEG4 header which is added at the beginning of the stream */
243
    unsigned int header_len;
244
    uint8_t *header_data;
245
    MOV_esds_t esds;
246
} MOVStreamContext;
247

    
248
typedef struct MOVContext {
249
    int mp4; /* set to 1 as soon as we are sure that the file is an .mp4 file (even some header parsing depends on this) */
250
    AVFormatContext *fc;
251
    int time_scale;
252
    int duration; /* duration of the longest track */
253
    int found_moov; /* when both 'moov' and 'mdat' sections has been found */
254
    int found_mdat; /* we suppose we have enough data to read the file */
255
    int64_t mdat_size;
256
    int64_t mdat_offset;
257
    int total_streams;
258
    /* some streams listed here aren't presented to the ffmpeg API, since they aren't either video nor audio
259
     * but we need the info to be able to skip data from those streams in the 'mdat' section
260
     */
261
    MOVStreamContext *streams[MAX_STREAMS];
262

    
263
    int64_t next_chunk_offset;
264
    MOVStreamContext *partial; /* != 0 : there is still to read in the current chunk */
265
    int ctab_size;
266
    MOV_ctab_t **ctab;           /* color tables */
267
    const struct MOVParseTableEntry *parse_table; /* could be eventually used to change the table */
268
    /* NOTE: for recursion save to/ restore from local variable! */
269

    
270
    AVPaletteControl palette_control;
271
} MOVContext;
272

    
273

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

    
276
/* those functions parse an atom */
277
/* return code:
278
 1: found what I wanted, exit
279
 0: continue to parse next atom
280
 -1: error occured, exit
281
 */
282
typedef int (*mov_parse_function)(MOVContext *ctx, ByteIOContext *pb, MOV_atom_t atom);
283

    
284
/* links atom IDs to parse functions */
285
typedef struct MOVParseTableEntry {
286
    uint32_t type;
287
    mov_parse_function func;
288
} MOVParseTableEntry;
289

    
290
#ifdef DEBUG
291
/*
292
 * XXX: static sux, even more in a multithreaded environment...
293
 * Avoid them. This is here just to help debugging.
294
 */
295
static int debug_indent = 0;
296
void print_atom(const char *str, MOV_atom_t atom)
297
{
298
    unsigned int tag, i;
299
    tag = (unsigned int) atom.type;
300
    i=debug_indent;
301
    if(tag == 0) tag = MKTAG('N', 'U', 'L', 'L');
302
    while(i--)
303
        av_log(NULL, AV_LOG_DEBUG, "|");
304
    av_log(NULL, AV_LOG_DEBUG, "parse:");
305
    av_log(NULL, AV_LOG_DEBUG, " %s: tag=%c%c%c%c offset=0x%x size=0x%x\n",
306
           str, tag & 0xff,
307
           (tag >> 8) & 0xff,
308
           (tag >> 16) & 0xff,
309
           (tag >> 24) & 0xff,
310
           (unsigned int)atom.offset,
311
           (unsigned int)atom.size);
312
    assert((unsigned int)atom.size < 0x7fffffff);// catching errors
313
}
314
#else
315
#define print_atom(a,b)
316
#endif
317

    
318

    
319
static int mov_read_leaf(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
320
{
321
    print_atom("leaf", atom);
322

    
323
    if (atom.size>1)
324
        url_fskip(pb, atom.size);
325
/*        url_seek(pb, atom_offset+atom.size, SEEK_SET); */
326
    return 0;
327
}
328

    
329
static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
330
{
331
    int64_t total_size = 0;
332
    MOV_atom_t a;
333
    int i;
334
    int err = 0;
335

    
336
#ifdef DEBUG
337
    print_atom("default", atom);
338
    debug_indent++;
339
#endif
340

    
341
    a.offset = atom.offset;
342

    
343
    if (atom.size < 0)
344
        atom.size = 0x7fffffffffffffffLL;
345
    while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
346
        a.size = atom.size;
347
        a.type=0L;
348
        if(atom.size >= 8) {
349
            a.size = get_be32(pb);
350
            a.type = get_le32(pb);
351
        }
352
        total_size += 8;
353
        a.offset += 8;
354
        //av_log(NULL, AV_LOG_DEBUG, "type: %08x  %.4s  sz: %Lx  %Lx   %Lx\n", type, (char*)&type, size, atom.size, total_size);
355
        if (a.size == 1) { /* 64 bit extended size */
356
            a.size = get_be64(pb) - 8;
357
            a.offset += 8;
358
            total_size += 8;
359
        }
360
        if (a.size == 0) {
361
            a.size = atom.size - total_size;
362
            if (a.size <= 8)
363
                break;
364
        }
365
        for (i = 0; c->parse_table[i].type != 0L
366
             && c->parse_table[i].type != a.type; i++)
367
            /* empty */;
368

    
369
        a.size -= 8;
370
        
371
        if(a.size < 0)
372
            break;
373
        
374
//        av_log(NULL, AV_LOG_DEBUG, " i=%ld\n", i);
375
        if (c->parse_table[i].type == 0) { /* skip leaf atoms data */
376
//            url_seek(pb, atom.offset+atom.size, SEEK_SET);
377
#ifdef DEBUG
378
            print_atom("unknown", a);
379
#endif
380
            url_fskip(pb, a.size);
381
        } else {
382
#ifdef DEBUG
383
            //char b[5] = { type & 0xff, (type >> 8) & 0xff, (type >> 16) & 0xff, (type >> 24) & 0xff, 0 };
384
            //print_atom(b, type, offset, size);
385
#endif
386
            err = (c->parse_table[i].func)(c, pb, a);
387
        }
388

    
389
        a.offset += a.size;
390
        total_size += a.size;
391
    }
392

    
393
    if (!err && total_size < atom.size && atom.size < 0x7ffff) {
394
        //av_log(NULL, AV_LOG_DEBUG, "RESET  %Ld  %Ld  err:%d\n", atom.size, total_size, err);
395
        url_fskip(pb, atom.size - total_size);
396
    }
397

    
398
#ifdef DEBUG
399
    debug_indent--;
400
#endif
401
    return err;
402
}
403

    
404
static int mov_read_ctab(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
405
{
406
    unsigned int len;
407
    MOV_ctab_t *t;
408
#if 1
409
    url_fskip(pb, atom.size); // for now
410
#else
411
    VERY VERY BROKEN, NEVER execute this, needs rewrite
412
    c->ctab = av_realloc(c->ctab, ++c->ctab_size);
413
    t = c->ctab[c->ctab_size];
414
    t->seed = get_be32(pb);
415
    t->flags = get_be16(pb);
416
    t->size = get_be16(pb) + 1;
417
    len = 2 * t->size * 4;
418
    if (len > 0) {
419
        t->clrs = av_malloc(len); // 16bit A R G B
420
        if (t->clrs)
421
            get_buffer(pb, t->clrs, len);
422
    }
423
#endif
424

    
425
    return 0;
426
}
427

    
428
static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
429
{
430
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
431
    int len = 0;
432
    uint32_t type;
433
    uint32_t ctype;
434

    
435
    print_atom("hdlr", atom);
436

    
437
    get_byte(pb); /* version */
438
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
439

    
440
    /* component type */
441
    ctype = get_le32(pb);
442
    type = get_le32(pb); /* component subtype */
443

    
444
#ifdef DEBUG
445
    av_log(NULL, AV_LOG_DEBUG, "ctype= %c%c%c%c (0x%08lx)\n", *((char *)&ctype), ((char *)&ctype)[1], ((char *)&ctype)[2], ((char *)&ctype)[3], (long) ctype);
446
    av_log(NULL, AV_LOG_DEBUG, "stype= %c%c%c%c\n", *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
447
#endif
448
#ifdef DEBUG
449
/* XXX: yeah this is ugly... */
450
    if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
451
        if(type == MKTAG('v', 'i', 'd', 'e'))
452
            puts("hdlr: vide");
453
        else if(type == MKTAG('s', 'o', 'u', 'n'))
454
            puts("hdlr: soun");
455
    } else if(ctype == 0) { /* MP4 */
456
        if(type == MKTAG('v', 'i', 'd', 'e'))
457
            puts("hdlr: vide");
458
        else if(type == MKTAG('s', 'o', 'u', 'n'))
459
            puts("hdlr: soun");
460
        else if(type == MKTAG('o', 'd', 's', 'm'))
461
            puts("hdlr: odsm");
462
        else if(type == MKTAG('s', 'd', 's', 'm'))
463
            puts("hdlr: sdsm");
464
    } else puts("hdlr: meta");
465
#endif
466

    
467
    if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
468
        /* helps parsing the string hereafter... */
469
        c->mp4 = 0;
470
        if(type == MKTAG('v', 'i', 'd', 'e'))
471
            st->codec.codec_type = CODEC_TYPE_VIDEO;
472
        else if(type == MKTAG('s', 'o', 'u', 'n'))
473
            st->codec.codec_type = CODEC_TYPE_AUDIO;
474
    } else if(ctype == 0) { /* MP4 */
475
        /* helps parsing the string hereafter... */
476
        c->mp4 = 1;
477
        if(type == MKTAG('v', 'i', 'd', 'e'))
478
            st->codec.codec_type = CODEC_TYPE_VIDEO;
479
        else if(type == MKTAG('s', 'o', 'u', 'n'))
480
            st->codec.codec_type = CODEC_TYPE_AUDIO;
481
    }
482
    get_be32(pb); /* component  manufacture */
483
    get_be32(pb); /* component flags */
484
    get_be32(pb); /* component flags mask */
485

    
486
    if(atom.size <= 24)
487
        return 0; /* nothing left to read */
488
    /* XXX: MP4 uses a C string, not a pascal one */
489
    /* component name */
490

    
491
    if(c->mp4) {
492
        /* .mp4: C string */
493
        while(get_byte(pb) && (++len < (atom.size - 24)));
494
    } else {
495
        /* .mov: PASCAL string */
496
#ifdef DEBUG
497
        char* buf;
498
#endif
499
        len = get_byte(pb);
500
#ifdef DEBUG
501
        buf = (uint8_t*) av_malloc(len+1);
502
        if (buf) {
503
            get_buffer(pb, buf, len);
504
            buf[len] = '\0';
505
            av_log(NULL, AV_LOG_DEBUG, "**buf='%s'\n", buf);
506
            av_free(buf);
507
        } else
508
#endif
509
            url_fskip(pb, len);
510
    }
511

    
512
    url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
513
    return 0;
514
}
515

    
516
static int mov_mp4_read_descr_len(ByteIOContext *pb)
517
{
518
    int len = 0;
519
    int count = 4;
520
    while (count--) {
521
        int c = get_byte(pb);
522
        len = (len << 7) | (c & 0x7f);
523
        if (!(c & 0x80))
524
            break;
525
    }
526
    return len;
527
}
528

    
529
static int mov_mp4_read_descr(ByteIOContext *pb, int *tag)
530
{
531
    int len;
532
    *tag = get_byte(pb);
533
    len = mov_mp4_read_descr_len(pb);
534
#ifdef DEBUG
535
    av_log(NULL, AV_LOG_DEBUG, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
536
#endif
537
    return len;
538
}
539

    
540
static inline unsigned int get_be24(ByteIOContext *s)
541
{
542
    unsigned int val;
543
    val = get_byte(s) << 16;
544
    val |= get_byte(s) << 8;
545
    val |= get_byte(s);
546
    return val;
547
}
548

    
549
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
550
{
551
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
552
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
553
    int64_t start_pos = url_ftell(pb);
554
    int tag, len;
555

    
556
    print_atom("esds", atom);
557

    
558
    /* Well, broken but suffisant for some MP4 streams */
559
    get_be32(pb); /* version + flags */
560
    len = mov_mp4_read_descr(pb, &tag);
561
    if (tag == MP4ESDescrTag) {
562
        get_be16(pb); /* ID */
563
        get_byte(pb); /* priority */
564
    } else
565
        get_be16(pb); /* ID */
566

    
567
    len = mov_mp4_read_descr(pb, &tag);
568
    if (tag == MP4DecConfigDescrTag) {
569
        sc->esds.object_type_id = get_byte(pb);
570
        sc->esds.stream_type = get_byte(pb);
571
        sc->esds.buffer_size_db = get_be24(pb);
572
        sc->esds.max_bitrate = get_be32(pb);
573
        sc->esds.avg_bitrate = get_be32(pb);
574

    
575
        len = mov_mp4_read_descr(pb, &tag);
576
        //av_log(NULL, AV_LOG_DEBUG, "LEN %d  TAG %d  m:%d a:%d\n", len, tag, sc->esds.max_bitrate, sc->esds.avg_bitrate);
577
        if (tag == MP4DecSpecificDescrTag) {
578
#ifdef DEBUG
579
            av_log(NULL, AV_LOG_DEBUG, "Specific MPEG4 header len=%d\n", len);
580
#endif
581
            st->codec.extradata = (uint8_t*) av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
582
            if (st->codec.extradata) {
583
                get_buffer(pb, st->codec.extradata, len);
584
                st->codec.extradata_size = len;
585
            }
586
        }
587
    }
588
    /* in any case, skip garbage */
589
    url_fskip(pb, atom.size - ((url_ftell(pb) - start_pos)));
590
    return 0;
591
}
592

    
593
/* this atom contains actual media data */
594
static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
595
{
596
    print_atom("mdat", atom);
597

    
598
    if(atom.size == 0) /* wrong one (MP4) */
599
        return 0;
600
    c->found_mdat=1;
601
    c->mdat_offset = atom.offset;
602
    c->mdat_size = atom.size;
603
    if(c->found_moov)
604
        return 1; /* found both, just go */
605
    url_fskip(pb, atom.size);
606
    return 0; /* now go for moov */
607
}
608

    
609
/* this atom should contain all header atoms */
610
static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
611
{
612
    int err;
613

    
614
    print_atom("moov", atom);
615

    
616
    err = mov_read_default(c, pb, atom);
617
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
618
    /* so we don't parse the whole file if over a network */
619
    c->found_moov=1;
620
    if(c->found_mdat)
621
        return 1; /* found both, just go */
622
    return 0; /* now go for mdat */
623
}
624

    
625

    
626
static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
627
{
628
    print_atom("mdhd", atom);
629

    
630
    get_byte(pb); /* version */
631

    
632
    get_byte(pb); get_byte(pb);
633
    get_byte(pb); /* flags */
634

    
635
    get_be32(pb); /* creation time */
636
    get_be32(pb); /* modification time */
637

    
638
    c->streams[c->fc->nb_streams-1]->time_scale = get_be32(pb);
639

    
640
#ifdef DEBUG
641
    av_log(NULL, AV_LOG_DEBUG, "track[%i].time_scale = %i\n", c->fc->nb_streams-1, c->streams[c->fc->nb_streams-1]->time_scale); /* time scale */
642
#endif
643
    get_be32(pb); /* duration */
644

    
645
    get_be16(pb); /* language */
646
    get_be16(pb); /* quality */
647

    
648
    return 0;
649
}
650

    
651
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
652
{
653
    print_atom("mvhd", atom);
654

    
655
    get_byte(pb); /* version */
656
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
657

    
658
    get_be32(pb); /* creation time */
659
    get_be32(pb); /* modification time */
660
    c->time_scale = get_be32(pb); /* time scale */
661
#ifdef DEBUG
662
    av_log(NULL, AV_LOG_DEBUG, "time scale = %i\n", c->time_scale);
663
#endif
664
    c->duration = get_be32(pb); /* duration */
665
    get_be32(pb); /* preferred scale */
666

    
667
    get_be16(pb); /* preferred volume */
668

    
669
    url_fskip(pb, 10); /* reserved */
670

    
671
    url_fskip(pb, 36); /* display matrix */
672

    
673
    get_be32(pb); /* preview time */
674
    get_be32(pb); /* preview duration */
675
    get_be32(pb); /* poster time */
676
    get_be32(pb); /* selection time */
677
    get_be32(pb); /* selection duration */
678
    get_be32(pb); /* current time */
679
    get_be32(pb); /* next track ID */
680

    
681
    return 0;
682
}
683

    
684
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
685
{
686
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
687

    
688
    if((uint64_t)atom.size > (1<<30))
689
        return -1;
690
    
691
    // currently SVQ3 decoder expect full STSD header - so let's fake it
692
    // this should be fixed and just SMI header should be passed
693
    av_free(st->codec.extradata);
694
    st->codec.extradata_size = 0x5a + atom.size;
695
    st->codec.extradata = (uint8_t*) av_mallocz(st->codec.extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
696

    
697
    if (st->codec.extradata) {
698
        strcpy(st->codec.extradata, "SVQ3"); // fake
699
        get_buffer(pb, st->codec.extradata + 0x5a, atom.size);
700
        //av_log(NULL, AV_LOG_DEBUG, "Reading SMI %Ld  %s\n", atom.size, (char*)st->codec.extradata + 0x5a);
701
    } else
702
        url_fskip(pb, atom.size);
703

    
704
    return 0;
705
}
706

    
707
static int mov_read_avcC(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
708
{
709
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
710

    
711
    if((uint64_t)atom.size > (1<<30))
712
        return -1;
713

    
714
    av_free(st->codec.extradata);
715

    
716
    st->codec.extradata_size = atom.size;
717
    st->codec.extradata = (uint8_t*) av_mallocz(st->codec.extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
718

    
719
    if (st->codec.extradata) {
720
        get_buffer(pb, st->codec.extradata, atom.size);
721
    } else
722
        url_fskip(pb, atom.size);
723

    
724
    return 0;
725
}
726

    
727
static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
728
{
729
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
730
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
731
    unsigned int i, entries;
732

    
733
    print_atom("stco", atom);
734

    
735
    get_byte(pb); /* version */
736
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
737

    
738
    entries = get_be32(pb);
739
        
740
    if(entries >= UINT_MAX/sizeof(int64_t))
741
        return -1;
742
 
743
    sc->chunk_count = entries;
744
    sc->chunk_offsets = (int64_t*) av_malloc(entries * sizeof(int64_t));
745
    if (!sc->chunk_offsets)
746
        return -1;
747
    if (atom.type == MKTAG('s', 't', 'c', 'o')) {
748
        for(i=0; i<entries; i++) {
749
            sc->chunk_offsets[i] = get_be32(pb);
750
        }
751
    } else if (atom.type == MKTAG('c', 'o', '6', '4')) {
752
        for(i=0; i<entries; i++) {
753
            sc->chunk_offsets[i] = get_be64(pb);
754
        }
755
    } else
756
        return -1;
757
#ifdef DEBUG
758
/*
759
    for(i=0; i<entries; i++) {
760
        av_log(NULL, AV_LOG_DEBUG, "chunk offset=0x%Lx\n", sc->chunk_offsets[i]);
761
    }
762
*/
763
#endif
764
    return 0;
765
}
766

    
767
static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
768
{
769
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
770
    //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
771
    int entries, frames_per_sample;
772
    uint32_t format;
773

    
774
    /* for palette traversal */
775
    int color_depth;
776
    int color_start;
777
    int color_count;
778
    int color_end;
779
    int color_index;
780
    int color_dec;
781
    int color_greyscale;
782
    unsigned char *color_table;
783
    int j;
784
    unsigned char r, g, b;
785

    
786
    print_atom("stsd", atom);
787

    
788
    get_byte(pb); /* version */
789
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
790

    
791
    entries = get_be32(pb);
792

    
793
    while(entries--) { //Parsing Sample description table
794
        enum CodecID id;
795
        int size = get_be32(pb); /* size */
796
        format = get_le32(pb); /* data format */
797

    
798
        get_be32(pb); /* reserved */
799
        get_be16(pb); /* reserved */
800
        get_be16(pb); /* index */
801

    
802
        /* for MPEG4: set codec type by looking for it */
803
        id = codec_get_id(mov_video_tags, format);
804
        if (id >= 0) {
805
            AVCodec *codec;
806
            codec = avcodec_find_decoder(id);
807
            if (codec)
808
                st->codec.codec_type = codec->type;
809
        }
810
#ifdef DEBUG
811
        av_log(NULL, AV_LOG_DEBUG, "size=%d 4CC= %c%c%c%c codec_type=%d\n",
812
               size,
813
               (format >> 0) & 0xff,
814
               (format >> 8) & 0xff,
815
               (format >> 16) & 0xff,
816
               (format >> 24) & 0xff,
817
               st->codec.codec_type);
818
#endif
819
        st->codec.codec_tag = format;
820
        if(st->codec.codec_type==CODEC_TYPE_VIDEO) {
821
            MOV_atom_t a = { 0, 0, 0 };
822
            st->codec.codec_id = id;
823
            get_be16(pb); /* version */
824
            get_be16(pb); /* revision level */
825
            get_be32(pb); /* vendor */
826
            get_be32(pb); /* temporal quality */
827
            get_be32(pb); /* spacial quality */
828
            st->codec.width = get_be16(pb); /* width */
829
            st->codec.height = get_be16(pb); /* height */
830
#if 1
831
            if (st->codec.codec_id == CODEC_ID_MPEG4) {
832
                /* in some MPEG4 the width/height are not correct, so
833
                   we ignore this info */
834
                st->codec.width = 0;
835
                st->codec.height = 0;
836
            }
837
#endif
838
            get_be32(pb); /* horiz resolution */
839
            get_be32(pb); /* vert resolution */
840
            get_be32(pb); /* data size, always 0 */
841
            frames_per_sample = get_be16(pb); /* frames per samples */
842
#ifdef DEBUG
843
            av_log(NULL, AV_LOG_DEBUG, "frames/samples = %d\n", frames_per_sample);
844
#endif
845
            get_buffer(pb, (uint8_t *)st->codec.codec_name, 32); /* codec name */
846

    
847
            st->codec.bits_per_sample = get_be16(pb); /* depth */
848
            st->codec.color_table_id = get_be16(pb); /* colortable id */
849

    
850
/*          These are set in mov_read_stts and might already be set!
851
            st->codec.frame_rate      = 25;
852
            st->codec.frame_rate_base = 1;
853
*/
854
            size -= (16+8*4+2+32+2*2);
855
#if 0
856
            while (size >= 8) {
857
                MOV_atom_t a;
858
                int64_t start_pos;
859

860
                a.size = get_be32(pb);
861
                a.type = get_le32(pb);
862
                size -= 8;
863
#ifdef DEBUG
864
                av_log(NULL, AV_LOG_DEBUG, "VIDEO: atom_type=%c%c%c%c atom.size=%Ld size_left=%d\n",
865
                       (a.type >> 0) & 0xff,
866
                       (a.type >> 8) & 0xff,
867
                       (a.type >> 16) & 0xff,
868
                       (a.type >> 24) & 0xff,
869
                       a.size, size);
870
#endif
871
                start_pos = url_ftell(pb);
872

    
873
                switch(a.type) {
874
                case MKTAG('e', 's', 'd', 's'):
875
                    {
876
                        int tag, len;
877
                        /* Well, broken but suffisant for some MP4 streams */
878
                        get_be32(pb); /* version + flags */
879
                        len = mov_mp4_read_descr(pb, &tag);
880
                        if (tag == 0x03) {
881
                            /* MP4ESDescrTag */
882
                            get_be16(pb); /* ID */
883
                            get_byte(pb); /* priority */
884
                            len = mov_mp4_read_descr(pb, &tag);
885
                            if (tag != 0x04)
886
                                goto fail;
887
                            /* MP4DecConfigDescrTag */
888
                            get_byte(pb); /* objectTypeId */
889
                            get_be32(pb); /* streamType + buffer size */
890
                            get_be32(pb); /* max bit rate */
891
                            get_be32(pb); /* avg bit rate */
892
                            len = mov_mp4_read_descr(pb, &tag);
893
                            if (tag != 0x05)
894
                                goto fail;
895
                            /* MP4DecSpecificDescrTag */
896
#ifdef DEBUG
897
                            av_log(NULL, AV_LOG_DEBUG, "Specific MPEG4 header len=%d\n", len);
898
#endif
899
                            sc->header_data = av_mallocz(len);
900
                            if (sc->header_data) {
901
                                get_buffer(pb, sc->header_data, len);
902
                                sc->header_len = len;
903
                            }
904
                        }
905
                        /* in any case, skip garbage */
906
                    }
907
                    break;
908
                default:
909
                    break;
910
                }
911
            fail:
912
                av_log(NULL, AV_LOG_DEBUG, "ATOMENEWSIZE %Ld   %d\n", atom.size, url_ftell(pb) - start_pos);
913
                if (atom.size > 8) {
914
                    url_fskip(pb, (atom.size - 8) -
915
                              ((url_ftell(pb) - start_pos)));
916
                    size -= atom.size - 8;
917
                }
918
            }
919
            if (size > 0) {
920
                /* unknown extension */
921
                url_fskip(pb, size);
922
            }
923
#else
924

    
925
            /* figure out the palette situation */
926
            color_depth = st->codec.bits_per_sample & 0x1F;
927
            color_greyscale = st->codec.bits_per_sample & 0x20;
928

    
929
            /* if the depth is 2, 4, or 8 bpp, file is palettized */
930
            if ((color_depth == 2) || (color_depth == 4) || 
931
                (color_depth == 8)) {
932

    
933
                if (color_greyscale) {
934

    
935
                    /* compute the greyscale palette */
936
                    color_count = 1 << color_depth;
937
                    color_index = 255;
938
                    color_dec = 256 / (color_count - 1);
939
                    for (j = 0; j < color_count; j++) {
940
                        r = g = b = color_index;
941
                        c->palette_control.palette[j] =
942
                            (r << 16) | (g << 8) | (b);
943
                        color_index -= color_dec;
944
                        if (color_index < 0)
945
                            color_index = 0;
946
                    }
947

    
948
                } else if (st->codec.color_table_id & 0x08) {
949

    
950
                    /* if flag bit 3 is set, use the default palette */
951
                    color_count = 1 << color_depth;
952
                    if (color_depth == 2)
953
                        color_table = ff_qt_default_palette_4;
954
                    else if (color_depth == 4)
955
                        color_table = ff_qt_default_palette_16;
956
                    else
957
                        color_table = ff_qt_default_palette_256;
958

    
959
                    for (j = 0; j < color_count; j++) {
960
                        r = color_table[j * 4 + 0];
961
                        g = color_table[j * 4 + 1];
962
                        b = color_table[j * 4 + 2];
963
                        c->palette_control.palette[j] =
964
                            (r << 16) | (g << 8) | (b);
965
                    }
966

    
967
                } else {
968

    
969
                    /* load the palette from the file */
970
                    color_start = get_be32(pb);
971
                    color_count = get_be16(pb);
972
                    color_end = get_be16(pb);
973
                    for (j = color_start; j <= color_end; j++) {
974
                        /* each R, G, or B component is 16 bits;
975
                         * only use the top 8 bits; skip alpha bytes
976
                         * up front */
977
                        get_byte(pb);
978
                        get_byte(pb);
979
                        r = get_byte(pb);
980
                        get_byte(pb);
981
                        g = get_byte(pb);
982
                        get_byte(pb);
983
                        b = get_byte(pb);
984
                        get_byte(pb);
985
                        c->palette_control.palette[j] =
986
                            (r << 16) | (g << 8) | (b);
987
                    }
988
                }
989

    
990
                st->codec.palctrl = &c->palette_control;
991
                st->codec.palctrl->palette_changed = 1;
992
            } else
993
                st->codec.palctrl = NULL;
994

    
995
            a.size = size;
996
            mov_read_default(c, pb, a);
997
#endif
998
        } else {
999
            st->codec.codec_id = codec_get_id(mov_audio_tags, format);
1000
            if(st->codec.codec_id==CODEC_ID_AMR_NB || st->codec.codec_id==CODEC_ID_AMR_WB) //from TS26.244
1001
            {
1002
#ifdef DEBUG
1003
               av_log(NULL, AV_LOG_DEBUG, "AMR-NB or AMR-WB audio identified!!\n");
1004
#endif
1005
               get_be32(pb);get_be32(pb); //Reserved_8
1006
               get_be16(pb);//Reserved_2
1007
               get_be16(pb);//Reserved_2
1008
               get_be32(pb);//Reserved_4
1009
               get_be16(pb);//TimeScale
1010
               get_be16(pb);//Reserved_2
1011

    
1012
                //AMRSpecificBox.(10 bytes)
1013
               
1014
               get_be32(pb); //size
1015
               get_be32(pb); //type=='damr'
1016
               get_be32(pb); //vendor
1017
               get_byte(pb); //decoder version
1018
               get_be16(pb); //mode_set
1019
               get_byte(pb); //mode_change_period
1020
               get_byte(pb); //frames_per_sample
1021

    
1022
               st->duration = AV_NOPTS_VALUE;//Not possible to get from this info, must count number of AMR frames
1023
               if(st->codec.codec_id==CODEC_ID_AMR_NB)
1024
               {
1025
                   st->codec.sample_rate=8000;
1026
                   st->codec.channels=1;
1027
               }
1028
               else //AMR-WB
1029
               {
1030
                   st->codec.sample_rate=16000;
1031
                   st->codec.channels=1;
1032
               }
1033
               st->codec.bits_per_sample=16;
1034
               st->codec.bit_rate=0; /*It is not possible to tell this before we have 
1035
                                       an audio frame and even then every frame can be different*/
1036
            }
1037
            else if( st->codec.codec_tag == MKTAG( 'm', 'p', '4', 's' ))
1038
            {
1039
                //This is some stuff for the hint track, lets ignore it!
1040
                //Do some mp4 auto detect.
1041
                c->mp4=1;
1042
                size-=(16);
1043
                url_fskip(pb, size); /* The mp4s atom also contians a esds atom that we can skip*/
1044
            }
1045
            else if( st->codec.codec_tag == MKTAG( 'm', 'p', '4', 'a' ))
1046
            {
1047
                /* Handle mp4 audio tag */
1048
                get_be32(pb); /* version */
1049
                get_be32(pb);
1050
                st->codec.channels = get_be16(pb); /* channels */
1051
                st->codec.bits_per_sample = get_be16(pb); /* bits per sample */
1052
                get_be32(pb);
1053
                st->codec.sample_rate = get_be16(pb); /* sample rate, not always correct */
1054
                get_be16(pb);
1055
                c->mp4=1;
1056
                {
1057
                MOV_atom_t a = { format, url_ftell(pb), size - (20 + 20 + 8) };
1058
                mov_read_default(c, pb, a);
1059
                }
1060
                /* Get correct sample rate from extradata */
1061
                if(st->codec.extradata_size) {
1062
                   const int samplerate_table[] = {
1063
                     96000, 88200, 64000, 48000, 44100, 32000, 
1064
                     24000, 22050, 16000, 12000, 11025, 8000,
1065
                     7350, 0, 0, 0
1066
                   };
1067
                   unsigned char *px = st->codec.extradata;
1068
                   // 5 bits objectTypeIndex, 4 bits sampleRateIndex, 4 bits channels
1069
                   int samplerate_index = ((px[0] & 7) << 1) + ((px[1] >> 7) & 1);
1070
                   st->codec.sample_rate = samplerate_table[samplerate_index];
1071
                }
1072
            }
1073
            else if(size>=(16+20))
1074
            {//16 bytes read, reading atleast 20 more
1075
                uint16_t version;
1076
#ifdef DEBUG
1077
                av_log(NULL, AV_LOG_DEBUG, "audio size=0x%X\n",size);
1078
#endif
1079
                version = get_be16(pb); /* version */
1080
                get_be16(pb); /* revision level */
1081
                get_be32(pb); /* vendor */
1082

    
1083
                st->codec.channels = get_be16(pb);                /* channel count */
1084
                st->codec.bits_per_sample = get_be16(pb);        /* sample size */
1085

    
1086
                /* handle specific s8 codec */
1087
                get_be16(pb); /* compression id = 0*/
1088
                get_be16(pb); /* packet size = 0 */
1089

    
1090
                st->codec.sample_rate = ((get_be32(pb) >> 16));
1091
                //av_log(NULL, AV_LOG_DEBUG, "CODECID %d  %d  %.4s\n", st->codec.codec_id, CODEC_ID_PCM_S16BE, (char*)&format);
1092

    
1093
                switch (st->codec.codec_id) {
1094
                case CODEC_ID_PCM_S16BE:
1095
                    if (st->codec.bits_per_sample == 8)
1096
                        st->codec.codec_id = CODEC_ID_PCM_S8;
1097
                    /* fall */
1098
                case CODEC_ID_PCM_U8:
1099
                    st->codec.bit_rate = st->codec.sample_rate * 8;
1100
                    break;
1101
                default:
1102
                    ;
1103
                }
1104

    
1105
                //Read QT version 1 fields. In version 0 theese dont exist
1106
#ifdef DEBUG
1107
                av_log(NULL, AV_LOG_DEBUG, "version =%d mp4=%d\n",version,c->mp4);
1108
                av_log(NULL, AV_LOG_DEBUG, "size-(16+20+16)=%d\n",size-(16+20+16));
1109
#endif
1110
                if((version==1) && size>=(16+20+16))
1111
                {
1112
                    get_be32(pb); /* samples per packet */
1113
                    get_be32(pb); /* bytes per packet */
1114
                    get_be32(pb); /* bytes per frame */
1115
                    get_be32(pb); /* bytes per sample */
1116
                    if(size>(16+20+16))
1117
                    {
1118
                        //Optional, additional atom-based fields
1119
                        MOV_atom_t a = { format, url_ftell(pb), size - (16 + 20 + 16 + 8) };
1120
#ifdef DEBUG
1121
                        av_log(NULL, AV_LOG_DEBUG, "offest=0x%X, sizeleft=%d=0x%x,format=%c%c%c%c\n",(int)url_ftell(pb),size - (16 + 20 + 16 ),size - (16 + 20 + 16 ),
1122
                            (format >> 0) & 0xff,
1123
                            (format >> 8) & 0xff,
1124
                            (format >> 16) & 0xff,
1125
                            (format >> 24) & 0xff);
1126
#endif
1127
                        mov_read_default(c, pb, a);
1128
                    }
1129
                }
1130
                else
1131
                {
1132
                    //We should be down to 0 bytes here, but lets make sure.
1133
                    size-=(16+20);
1134
#ifdef DEBUG
1135
                    if(size>0)
1136
                        av_log(NULL, AV_LOG_DEBUG, "skipping 0x%X bytes\n",size-(16+20));
1137
#endif
1138
                    url_fskip(pb, size);
1139
                }
1140
            }
1141
            else
1142
            {
1143
                size-=16;
1144
                //Unknown size, but lets do our best and skip the rest.
1145
#ifdef DEBUG
1146
                av_log(NULL, AV_LOG_DEBUG, "Strange size, skipping 0x%X bytes\n",size);
1147
#endif
1148
                url_fskip(pb, size);
1149
            }
1150
        }
1151
    }
1152

    
1153
    return 0;
1154
}
1155

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

    
1162
    print_atom("stsc", atom);
1163

    
1164
    get_byte(pb); /* version */
1165
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1166

    
1167
    entries = get_be32(pb);
1168
    
1169
    if(entries >= UINT_MAX / sizeof(MOV_sample_to_chunk_tbl))
1170
        return -1;
1171
    
1172
#ifdef DEBUG
1173
av_log(NULL, AV_LOG_DEBUG, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1174
#endif
1175
    sc->sample_to_chunk_sz = entries;
1176
    sc->sample_to_chunk = (MOV_sample_to_chunk_tbl*) av_malloc(entries * sizeof(MOV_sample_to_chunk_tbl));
1177
    if (!sc->sample_to_chunk)
1178
        return -1;
1179
    for(i=0; i<entries; i++) {
1180
        sc->sample_to_chunk[i].first = get_be32(pb);
1181
        sc->sample_to_chunk[i].count = get_be32(pb);
1182
        sc->sample_to_chunk[i].id = get_be32(pb);
1183
#ifdef DEBUG
1184
/*        av_log(NULL, AV_LOG_DEBUG, "sample_to_chunk first=%ld count=%ld, id=%ld\n", sc->sample_to_chunk[i].first, sc->sample_to_chunk[i].count, sc->sample_to_chunk[i].id); */
1185
#endif
1186
    }
1187
    return 0;
1188
}
1189

    
1190
static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1191
{
1192
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1193
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1194
    unsigned int i, entries;
1195

    
1196
    print_atom("stss", atom);
1197

    
1198
    get_byte(pb); /* version */
1199
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1200

    
1201
    entries = get_be32(pb);
1202
    
1203
    if(entries >= UINT_MAX / sizeof(long))
1204
        return -1;
1205
    
1206
    sc->keyframe_count = entries;
1207
#ifdef DEBUG
1208
    av_log(NULL, AV_LOG_DEBUG, "keyframe_count = %ld\n", sc->keyframe_count);
1209
#endif
1210
    sc->keyframes = (long*) av_malloc(entries * sizeof(long));
1211
    if (!sc->keyframes)
1212
        return -1;
1213
    for(i=0; i<entries; i++) {
1214
        sc->keyframes[i] = get_be32(pb);
1215
#ifdef DEBUG
1216
/*        av_log(NULL, AV_LOG_DEBUG, "keyframes[]=%ld\n", sc->keyframes[i]); */
1217
#endif
1218
    }
1219
    return 0;
1220
}
1221

    
1222
static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1223
{
1224
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1225
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1226
    unsigned int i, entries;
1227

    
1228
    print_atom("stsz", atom);
1229

    
1230
    get_byte(pb); /* version */
1231
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1232

    
1233
    sc->sample_size = get_be32(pb);
1234
    entries = get_be32(pb);
1235
    if(entries >= UINT_MAX / sizeof(long))
1236
        return -1;
1237

    
1238
    sc->sample_count = entries;
1239
#ifdef DEBUG
1240
    av_log(NULL, AV_LOG_DEBUG, "sample_size = %ld sample_count = %ld\n", sc->sample_size, sc->sample_count);
1241
#endif
1242
    if(sc->sample_size)
1243
        return 0; /* there isn't any table following */
1244
    sc->sample_sizes = (long*) av_malloc(entries * sizeof(long));
1245
    if (!sc->sample_sizes)
1246
        return -1;
1247
    for(i=0; i<entries; i++) {
1248
        sc->sample_sizes[i] = get_be32(pb);
1249
#ifdef DEBUG
1250
/*        av_log(NULL, AV_LOG_DEBUG, "sample_sizes[]=%ld\n", sc->sample_sizes[i]); */
1251
#endif
1252
    }
1253
    return 0;
1254
}
1255

    
1256
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1257
{
1258
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1259
    //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1260
    unsigned int i, entries;
1261
    int64_t duration=0;
1262
    int64_t total_sample_count=0;
1263

    
1264
    print_atom("stts", atom);
1265

    
1266
    get_byte(pb); /* version */
1267
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1268
    entries = get_be32(pb);
1269
    if(entries >= UINT_MAX / sizeof(uint64_t))
1270
        return -1;
1271

    
1272
    c->streams[c->fc->nb_streams-1]->stts_count = entries;
1273
    c->streams[c->fc->nb_streams-1]->stts_data = (uint64_t*) av_malloc(entries * sizeof(uint64_t));
1274

    
1275
#ifdef DEBUG
1276
av_log(NULL, AV_LOG_DEBUG, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1277
#endif
1278
    for(i=0; i<entries; i++) {
1279
        int32_t sample_duration;
1280
        int32_t sample_count;
1281

    
1282
        sample_count=get_be32(pb);
1283
        sample_duration = get_be32(pb);
1284
        c->streams[c->fc->nb_streams - 1]->stts_data[i] = (uint64_t)sample_count<<32 | (uint64_t)sample_duration;
1285
#ifdef DEBUG
1286
        av_log(NULL, AV_LOG_DEBUG, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1287
#endif
1288
        duration+=sample_duration*sample_count;
1289
        total_sample_count+=sample_count;
1290

    
1291
#if 0 //We calculate an average instead, needed by .mp4-files created with nec e606 3g phone
1292

1293
        if (!i && st->codec.codec_type==CODEC_TYPE_VIDEO) {
1294
            st->codec.frame_rate_base = sample_duration ? sample_duration : 1;
1295
            st->codec.frame_rate = c->streams[c->fc->nb_streams-1]->time_scale;
1296
#ifdef DEBUG
1297
            av_log(NULL, AV_LOG_DEBUG, "VIDEO FRAME RATE= %i (sd= %i)\n", st->codec.frame_rate, sample_duration);
1298
#endif
1299
        }
1300
#endif
1301
    }
1302

    
1303
    /*The stsd atom which contain codec type sometimes comes after the stts so we cannot check for codec_type*/
1304
    if(duration>0)
1305
    {
1306
        av_reduce(
1307
            &st->codec.frame_rate, 
1308
            &st->codec.frame_rate_base, 
1309
            c->streams[c->fc->nb_streams-1]->time_scale * total_sample_count,
1310
            duration,
1311
            INT_MAX
1312
        );
1313

    
1314
#ifdef DEBUG
1315
        av_log(NULL, AV_LOG_DEBUG, "FRAME RATE average (video or audio)= %f (tot sample count= %i ,tot dur= %i timescale=%d)\n", (float)st->codec.frame_rate/st->codec.frame_rate_base,total_sample_count,duration,c->streams[c->fc->nb_streams-1]->time_scale);
1316
#endif
1317
    }
1318
    else
1319
    {
1320
        st->codec.frame_rate_base = 1;
1321
        st->codec.frame_rate = c->streams[c->fc->nb_streams-1]->time_scale;
1322
    }
1323
    return 0;
1324
}
1325

    
1326
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1327
{
1328
    AVStream *st;
1329
    MOVStreamContext *sc;
1330

    
1331
    print_atom("trak", atom);
1332

    
1333
    st = av_new_stream(c->fc, c->fc->nb_streams);
1334
    if (!st) return -2;
1335
    sc = (MOVStreamContext*) av_mallocz(sizeof(MOVStreamContext));
1336
    if (!sc) {
1337
        av_free(st);
1338
        return -1;
1339
    }
1340

    
1341
    sc->sample_to_chunk_index = -1;
1342
    st->priv_data = sc;
1343
    st->codec.codec_type = CODEC_TYPE_MOV_OTHER;
1344
    st->start_time = 0; /* XXX: check */
1345
    st->duration = (c->duration * (int64_t)AV_TIME_BASE) / c->time_scale;
1346
    c->streams[c->fc->nb_streams-1] = sc;
1347

    
1348
    return mov_read_default(c, pb, atom);
1349
}
1350

    
1351
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1352
{
1353
    AVStream *st;
1354

    
1355
    print_atom("tkhd", atom);
1356

    
1357
    st = c->fc->streams[c->fc->nb_streams-1];
1358

    
1359
    get_byte(pb); /* version */
1360

    
1361
    get_byte(pb); get_byte(pb);
1362
    get_byte(pb); /* flags */
1363
    /*
1364
    MOV_TRACK_ENABLED 0x0001
1365
    MOV_TRACK_IN_MOVIE 0x0002
1366
    MOV_TRACK_IN_PREVIEW 0x0004
1367
    MOV_TRACK_IN_POSTER 0x0008
1368
    */
1369

    
1370
    get_be32(pb); /* creation time */
1371
    get_be32(pb); /* modification time */
1372
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1373
    get_be32(pb); /* reserved */
1374
    st->start_time = 0; /* check */
1375
    st->duration = (get_be32(pb) * (int64_t)AV_TIME_BASE) / c->time_scale; /* duration */
1376
    get_be32(pb); /* reserved */
1377
    get_be32(pb); /* reserved */
1378

    
1379
    get_be16(pb); /* layer */
1380
    get_be16(pb); /* alternate group */
1381
    get_be16(pb); /* volume */
1382
    get_be16(pb); /* reserved */
1383

    
1384
    url_fskip(pb, 36); /* display matrix */
1385

    
1386
    /* those are fixed-point */
1387
    st->codec.width = get_be32(pb) >> 16; /* track width */
1388
    st->codec.height = get_be32(pb) >> 16; /* track height */
1389

    
1390
    return 0;
1391
}
1392

    
1393
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1394
/* like the files created with Adobe Premiere 5.0, for samples see */
1395
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1396
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1397
{
1398
    int err;
1399

    
1400
#ifdef DEBUG
1401
    print_atom("wide", atom);
1402
    debug_indent++;
1403
#endif
1404
    if (atom.size < 8)
1405
        return 0; /* continue */
1406
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1407
        url_fskip(pb, atom.size - 4);
1408
        return 0;
1409
    }
1410
    atom.type = get_le32(pb);
1411
    atom.offset += 8;
1412
    atom.size -= 8;
1413
    if (atom.type != MKTAG('m', 'd', 'a', 't')) {
1414
        url_fskip(pb, atom.size);
1415
        return 0;
1416
    }
1417
    err = mov_read_mdat(c, pb, atom);
1418
#ifdef DEBUG
1419
    debug_indent--;
1420
#endif
1421
    return err;
1422
}
1423

    
1424

    
1425
#ifdef CONFIG_ZLIB
1426
static int null_read_packet(void *opaque, uint8_t *buf, int buf_size)
1427
{
1428
    return -1;
1429
}
1430

    
1431
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1432
{
1433
    ByteIOContext ctx;
1434
    uint8_t *cmov_data;
1435
    uint8_t *moov_data; /* uncompressed data */
1436
    long cmov_len, moov_len;
1437
    int ret;
1438

    
1439
    print_atom("cmov", atom);
1440

    
1441
    get_be32(pb); /* dcom atom */
1442
    if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
1443
        return -1;
1444
    if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
1445
        av_log(NULL, AV_LOG_DEBUG, "unknown compression for cmov atom !");
1446
        return -1;
1447
    }
1448
    get_be32(pb); /* cmvd atom */
1449
    if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
1450
        return -1;
1451
    moov_len = get_be32(pb); /* uncompressed size */
1452
    cmov_len = atom.size - 6 * 4;
1453

    
1454
    cmov_data = (uint8_t *) av_malloc(cmov_len);
1455
    if (!cmov_data)
1456
        return -1;
1457
    moov_data = (uint8_t *) av_malloc(moov_len);
1458
    if (!moov_data) {
1459
        av_free(cmov_data);
1460
        return -1;
1461
    }
1462
    get_buffer(pb, cmov_data, cmov_len);
1463
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1464
        return -1;
1465
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, null_read_packet, NULL, NULL) != 0)
1466
        return -1;
1467
    ctx.buf_end = ctx.buffer + moov_len;
1468
    atom.type = MKTAG( 'm', 'o', 'o', 'v' );
1469
    atom.offset = 0;
1470
    atom.size = moov_len;
1471
#ifdef DEBUG
1472
    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1473
#endif
1474
    ret = mov_read_default(c, &ctx, atom);
1475
    av_free(moov_data);
1476
    av_free(cmov_data);
1477

    
1478
    return ret;
1479
}
1480
#endif
1481

    
1482
/* edit list atom */
1483
static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1484
{
1485
  int i, edit_count;
1486
  print_atom("elst", atom);
1487

    
1488
  get_byte(pb); /* version */
1489
  get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1490
  edit_count= c->streams[c->fc->nb_streams-1]->edit_count = get_be32(pb);     /* entries */
1491
  
1492
  for(i=0; i<edit_count; i++){
1493
    get_be32(pb); /* Track duration */
1494
    get_be32(pb); /* Media time */
1495
    get_be32(pb); /* Media rate */
1496
  }
1497
#ifdef DEBUG
1498
  av_log(NULL, AV_LOG_DEBUG, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, c->streams[c->fc->nb_streams-1]->edit_count);
1499
#endif
1500
  return 0;
1501
}
1502

    
1503
static const MOVParseTableEntry mov_default_parse_table[] = {
1504
/* mp4 atoms */
1505
{ MKTAG( 'c', 'o', '6', '4' ), mov_read_stco },
1506
{ MKTAG( 'c', 'p', 'r', 't' ), mov_read_default },
1507
{ MKTAG( 'c', 'r', 'h', 'd' ), mov_read_default },
1508
{ MKTAG( 'c', 't', 't', 's' ), mov_read_leaf }, /* composition time to sample */
1509
{ MKTAG( 'd', 'i', 'n', 'f' ), mov_read_default }, /* data information */
1510
{ MKTAG( 'd', 'p', 'n', 'd' ), mov_read_leaf },
1511
{ MKTAG( 'd', 'r', 'e', 'f' ), mov_read_leaf },
1512
{ MKTAG( 'e', 'd', 't', 's' ), mov_read_default },
1513
{ MKTAG( 'e', 'l', 's', 't' ), mov_read_elst },
1514
{ MKTAG( 'f', 'r', 'e', 'e' ), mov_read_leaf },
1515
{ MKTAG( 'h', 'd', 'l', 'r' ), mov_read_hdlr },
1516
{ MKTAG( 'h', 'i', 'n', 't' ), mov_read_leaf },
1517
{ MKTAG( 'h', 'm', 'h', 'd' ), mov_read_leaf },
1518
{ MKTAG( 'i', 'o', 'd', 's' ), mov_read_leaf },
1519
{ MKTAG( 'm', 'd', 'a', 't' ), mov_read_mdat },
1520
{ MKTAG( 'm', 'd', 'h', 'd' ), mov_read_mdhd },
1521
{ MKTAG( 'm', 'd', 'i', 'a' ), mov_read_default },
1522
{ MKTAG( 'm', 'i', 'n', 'f' ), mov_read_default },
1523
{ MKTAG( 'm', 'o', 'o', 'v' ), mov_read_moov },
1524
{ MKTAG( 'm', 'p', '4', 'a' ), mov_read_default },
1525
{ MKTAG( 'm', 'p', '4', 's' ), mov_read_default },
1526
{ MKTAG( 'm', 'p', '4', 'v' ), mov_read_default },
1527
{ MKTAG( 'm', 'p', 'o', 'd' ), mov_read_leaf },
1528
{ MKTAG( 'm', 'v', 'h', 'd' ), mov_read_mvhd },
1529
{ MKTAG( 'n', 'm', 'h', 'd' ), mov_read_leaf },
1530
{ MKTAG( 'o', 'd', 'h', 'd' ), mov_read_default },
1531
{ MKTAG( 's', 'd', 'h', 'd' ), mov_read_default },
1532
{ MKTAG( 's', 'k', 'i', 'p' ), mov_read_leaf },
1533
{ MKTAG( 's', 'm', 'h', 'd' ), mov_read_leaf }, /* sound media info header */
1534
{ MKTAG( 'S', 'M', 'I', ' ' ), mov_read_smi }, /* Sorenson extension ??? */
1535
{ MKTAG( 'a', 'v', 'c', 'C' ), mov_read_avcC }, 
1536
{ MKTAG( 's', 't', 'b', 'l' ), mov_read_default },
1537
{ MKTAG( 's', 't', 'c', 'o' ), mov_read_stco },
1538
{ MKTAG( 's', 't', 'd', 'p' ), mov_read_default },
1539
{ MKTAG( 's', 't', 's', 'c' ), mov_read_stsc },
1540
{ MKTAG( 's', 't', 's', 'd' ), mov_read_stsd }, /* sample description */
1541
{ MKTAG( 's', 't', 's', 'h' ), mov_read_default },
1542
{ MKTAG( 's', 't', 's', 's' ), mov_read_stss }, /* sync sample */
1543
{ MKTAG( 's', 't', 's', 'z' ), mov_read_stsz }, /* sample size */
1544
{ MKTAG( 's', 't', 't', 's' ), mov_read_stts },
1545
{ MKTAG( 't', 'k', 'h', 'd' ), mov_read_tkhd }, /* track header */
1546
{ MKTAG( 't', 'r', 'a', 'k' ), mov_read_trak },
1547
{ MKTAG( 't', 'r', 'e', 'f' ), mov_read_default }, /* not really */
1548
{ MKTAG( 'u', 'd', 't', 'a' ), mov_read_leaf },
1549
{ MKTAG( 'u', 'r', 'l', ' ' ), mov_read_leaf },
1550
{ MKTAG( 'u', 'r', 'n', ' ' ), mov_read_leaf },
1551
{ MKTAG( 'u', 'u', 'i', 'd' ), mov_read_default },
1552
{ MKTAG( 'v', 'm', 'h', 'd' ), mov_read_leaf }, /* video media info header */
1553
{ MKTAG( 'w', 'a', 'v', 'e' ), mov_read_default },
1554
/* extra mp4 */
1555
{ MKTAG( 'M', 'D', 'E', 'S' ), mov_read_leaf },
1556
/* QT atoms */
1557
{ MKTAG( 'c', 'h', 'a', 'p' ), mov_read_leaf },
1558
{ MKTAG( 'c', 'l', 'i', 'p' ), mov_read_default },
1559
{ MKTAG( 'c', 'r', 'g', 'n' ), mov_read_leaf },
1560
{ MKTAG( 'c', 't', 'a', 'b' ), mov_read_ctab },
1561
{ MKTAG( 'e', 's', 'd', 's' ), mov_read_esds },
1562
{ MKTAG( 'k', 'm', 'a', 't' ), mov_read_leaf },
1563
{ MKTAG( 'm', 'a', 't', 't' ), mov_read_default },
1564
{ MKTAG( 'r', 'd', 'r', 'f' ), mov_read_leaf },
1565
{ MKTAG( 'r', 'm', 'd', 'a' ), mov_read_default },
1566
{ MKTAG( 'r', 'm', 'd', 'r' ), mov_read_leaf },
1567
{ MKTAG( 'r', 'm', 'r', 'a' ), mov_read_default },
1568
{ MKTAG( 's', 'c', 'p', 't' ), mov_read_leaf },
1569
{ MKTAG( 's', 's', 'r', 'c' ), mov_read_leaf },
1570
{ MKTAG( 's', 'y', 'n', 'c' ), mov_read_leaf },
1571
{ MKTAG( 't', 'c', 'm', 'd' ), mov_read_leaf },
1572
{ MKTAG( 'w', 'i', 'd', 'e' ), mov_read_wide }, /* place holder */
1573
//{ MKTAG( 'r', 'm', 'q', 'u' ), mov_read_leaf },
1574
#ifdef CONFIG_ZLIB
1575
{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_cmov },
1576
#else
1577
{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_leaf },
1578
#endif
1579
{ 0L, mov_read_leaf }
1580
};
1581

    
1582
static void mov_free_stream_context(MOVStreamContext *sc)
1583
{
1584
    if(sc) {
1585
        av_free(sc->chunk_offsets);
1586
        av_free(sc->sample_to_chunk);
1587
        av_free(sc->sample_sizes);
1588
        av_free(sc->keyframes);
1589
        av_free(sc->header_data);
1590
        av_free(sc->stts_data);        
1591
        av_free(sc);
1592
    }
1593
}
1594

    
1595
static inline uint32_t mov_to_tag(uint8_t *buf)
1596
{
1597
    return MKTAG(buf[0], buf[1], buf[2], buf[3]);
1598
}
1599

    
1600
static inline uint32_t to_be32(uint8_t *buf)
1601
{
1602
    return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
1603
}
1604

    
1605
/* XXX: is it sufficient ? */
1606
static int mov_probe(AVProbeData *p)
1607
{
1608
    unsigned int offset;
1609
    uint32_t tag;
1610

    
1611
    /* check file header */
1612
    if (p->buf_size <= 12)
1613
        return 0;
1614
    offset = 0;
1615
    for(;;) {
1616
        /* ignore invalid offset */
1617
        if ((offset + 8) > (unsigned int)p->buf_size)
1618
            return 0;
1619
        tag = mov_to_tag(p->buf + offset + 4);
1620
        switch(tag) {
1621
        case MKTAG( 'm', 'o', 'o', 'v' ):
1622
        case MKTAG( 'w', 'i', 'd', 'e' ):
1623
        case MKTAG( 'f', 'r', 'e', 'e' ):
1624
        case MKTAG( 'm', 'd', 'a', 't' ):
1625
        case MKTAG( 'p', 'n', 'o', 't' ): /* detect movs with preview pics like ew.mov and april.mov */
1626
        case MKTAG( 'u', 'd', 't', 'a' ): /* Packet Video PVAuthor adds this and a lot of more junk */
1627
            return AVPROBE_SCORE_MAX;
1628
        case MKTAG( 'f', 't', 'y', 'p' ):
1629
        case MKTAG( 's', 'k', 'i', 'p' ):
1630
            offset = to_be32(p->buf+offset) + offset;
1631
            break;
1632
        default:
1633
            /* unrecognized tag */
1634
            return 0;
1635
        }
1636
    }
1637
    return 0;
1638
}
1639

    
1640
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1641
{
1642
    MOVContext *mov = (MOVContext *) s->priv_data;
1643
    ByteIOContext *pb = &s->pb;
1644
    int i, j, nb, err;
1645
    MOV_atom_t atom = { 0, 0, 0 };
1646

    
1647
    mov->fc = s;
1648
    mov->parse_table = mov_default_parse_table;
1649
#if 0
1650
    /* XXX: I think we should auto detect */
1651
    if(s->iformat->name[1] == 'p')
1652
        mov->mp4 = 1;
1653
#endif
1654
    if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1655
        atom.size = url_filesize(url_fileno(pb));
1656
    else
1657
        atom.size = 0x7FFFFFFFFFFFFFFFLL;
1658

    
1659
#ifdef DEBUG
1660
    av_log(NULL, AV_LOG_DEBUG, "filesz=%Ld\n", atom.size);
1661
#endif
1662

    
1663
    /* check MOV header */
1664
    err = mov_read_default(mov, pb, atom);
1665
    if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
1666
        av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%lld\n",
1667
                err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1668
        return -1;
1669
    }
1670
#ifdef DEBUG
1671
    av_log(NULL, AV_LOG_DEBUG, "on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1672
#endif
1673
    /* some cleanup : make sure we are on the mdat atom */
1674
    if(!url_is_streamed(pb) && (url_ftell(pb) != mov->mdat_offset))
1675
        url_fseek(pb, mov->mdat_offset, SEEK_SET);
1676

    
1677
    mov->next_chunk_offset = mov->mdat_offset; /* initialise reading */
1678

    
1679
#ifdef DEBUG
1680
    av_log(NULL, AV_LOG_DEBUG, "mdat_reset_offset=%d\n", (int) url_ftell(pb));
1681
#endif
1682

    
1683
#ifdef DEBUG
1684
    av_log(NULL, AV_LOG_DEBUG, "streams= %d\n", s->nb_streams);
1685
#endif
1686
    mov->total_streams = nb = s->nb_streams;
1687

    
1688
#if 1
1689
    for(i=0; i<s->nb_streams;) {
1690
        if(s->streams[i]->codec.codec_type == CODEC_TYPE_MOV_OTHER) {/* not audio, not video, delete */
1691
            av_free(s->streams[i]);
1692
            for(j=i+1; j<s->nb_streams; j++)
1693
                s->streams[j-1] = s->streams[j];
1694
            s->nb_streams--;
1695
        } else
1696
            i++;
1697
    }
1698
    for(i=0; i<s->nb_streams;i++) {
1699
        MOVStreamContext *sc;
1700
        sc = (MOVStreamContext *)s->streams[i]->priv_data;
1701
        sc->ffindex = i;
1702
        sc->is_ff_stream = 1;
1703
    }
1704
#endif
1705
#ifdef DEBUG
1706
    av_log(NULL, AV_LOG_DEBUG, "real streams= %d\n", s->nb_streams);
1707
#endif
1708
    return 0;
1709
}
1710

    
1711
/* Yes, this is ugly... I didn't write the specs of QT :p */
1712
/* XXX:remove useless commented code sometime */
1713
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1714
{
1715
    MOVContext *mov = (MOVContext *) s->priv_data;
1716
    MOVStreamContext *sc;
1717
    int64_t offset = 0x0FFFFFFFFFFFFFFFLL;
1718
    int i, a, b, m;
1719
    int size;
1720
    int idx;
1721
    size = 0x0FFFFFFF;
1722

    
1723
#ifdef MOV_SPLIT_CHUNKS
1724
    if (mov->partial) {
1725

    
1726
        int idx;
1727

    
1728
        sc = mov->partial;
1729
        idx = sc->sample_to_chunk_index;
1730

    
1731
        if (idx < 0) return 0;
1732
        size = (sc->sample_size)?sc->sample_size:sc->sample_sizes[sc->current_sample];
1733

    
1734
        sc->current_sample++;
1735
        sc->left_in_chunk--;
1736

    
1737
        if (sc->left_in_chunk <= 0)
1738
            mov->partial = 0;
1739
        offset = mov->next_chunk_offset;
1740
        /* extract the sample */
1741

    
1742
        goto readchunk;
1743
    }
1744
#endif
1745

    
1746
again:
1747
    sc = 0;
1748
    for(i=0; i<mov->total_streams; i++) {
1749
        MOVStreamContext *msc = mov->streams[i];
1750
        //av_log(NULL, AV_LOG_DEBUG, "MOCHUNK %ld  %d   %p  pos:%Ld\n", mov->streams[i]->next_chunk, mov->total_streams, mov->streams[i], url_ftell(&s->pb));
1751
        if ((msc->next_chunk < msc->chunk_count) && msc->next_chunk >= 0
1752
           && (msc->chunk_offsets[msc->next_chunk] < offset)) {
1753
            sc = msc;
1754
            offset = msc->chunk_offsets[msc->next_chunk];
1755
            //av_log(NULL, AV_LOG_DEBUG, "SELETED  %Ld  i:%d\n", offset, i);
1756
        }
1757
    }
1758
    if (!sc || offset==0x0FFFFFFFFFFFFFFFLL)
1759
        return -1;
1760

    
1761
    sc->next_chunk++;
1762

    
1763
    if(mov->next_chunk_offset < offset) { /* some meta data */
1764
        url_fskip(&s->pb, (offset - mov->next_chunk_offset));
1765
        mov->next_chunk_offset = offset;
1766
    }
1767

    
1768
//av_log(NULL, AV_LOG_DEBUG, "chunk: [%i] %lli -> %lli\n", st_id, mov->next_chunk_offset, offset);
1769
    if(!sc->is_ff_stream || s->streams[sc->ffindex]->discard) {
1770
        url_fskip(&s->pb, (offset - mov->next_chunk_offset));
1771
        mov->next_chunk_offset = offset;
1772
        offset = 0x0FFFFFFFFFFFFFFFLL;
1773
        goto again;
1774
    }
1775

    
1776
    /* now get the chunk size... */
1777

    
1778
    for(i=0; i<mov->total_streams; i++) {
1779
        MOVStreamContext *msc = mov->streams[i];
1780
        if ((msc->next_chunk < msc->chunk_count)
1781
            && ((msc->chunk_offsets[msc->next_chunk] - offset) < size))
1782
            size = msc->chunk_offsets[msc->next_chunk] - offset;
1783
    }
1784

    
1785
#ifdef MOV_MINOLTA_FIX
1786
    //Make sure that size is according to sample_size (Needed by .mov files 
1787
    //created on a Minolta Dimage Xi where audio chunks contains waste data in the end)
1788
    //Maybe we should really not only check sc->sample_size, but also sc->sample_sizes
1789
    //but I have no such movies
1790
    if (sc->sample_size > 0) { 
1791
        int foundsize=0;
1792
        for(i=0; i<(sc->sample_to_chunk_sz); i++) {
1793
            if( (sc->sample_to_chunk[i].first)<=(sc->next_chunk) && (sc->sample_size>0) )
1794
            {
1795
                // I can't figure out why for PCM audio sample_size is always 1
1796
                // (it should actually be channels*bits_per_second/8) but it is.
1797
                AVCodecContext* cod = &s->streams[sc->ffindex]->codec;
1798
                if (sc->sample_size == 1 && (cod->codec_id == CODEC_ID_PCM_S16BE || cod->codec_id == CODEC_ID_PCM_S16LE))
1799
                    foundsize=(sc->sample_to_chunk[i].count*cod->channels*cod->bits_per_sample)/8;
1800
                else
1801
                    foundsize=sc->sample_to_chunk[i].count*sc->sample_size;
1802
            }
1803
#ifdef DEBUG
1804
            av_log(NULL, AV_LOG_DEBUG, "sample_to_chunk first=%ld count=%ld, id=%ld\n", sc->sample_to_chunk[i].first, sc->sample_to_chunk[i].count, sc->sample_to_chunk[i].id);
1805
#endif
1806
        }
1807
        if( (foundsize>0) && (foundsize<size) )
1808
        {
1809
#ifdef DEBUG
1810
            /*av_log(NULL, AV_LOG_DEBUG, "this size should actually be %d\n",foundsize);*/
1811
#endif
1812
            size=foundsize;
1813
        }
1814
    }
1815
#endif //MOV_MINOLTA_FIX
1816

    
1817
#ifdef MOV_SPLIT_CHUNKS
1818
    /* split chunks into samples */
1819
    idx = sc->sample_to_chunk_index;
1820
    if ((idx + 1 < sc->sample_to_chunk_sz)
1821
            && (sc->next_chunk >= sc->sample_to_chunk[idx + 1].first))
1822
        idx++;
1823
    sc->sample_to_chunk_index = idx;
1824
    if (idx >= 0 && sc->sample_to_chunk[idx].count != 1) {
1825
        mov->partial = sc;
1826
        /* we'll have to get those samples before next chunk */
1827
        sc->left_in_chunk = sc->sample_to_chunk[idx].count - 1;
1828
        size = (sc->sample_size)?sc->sample_size:sc->sample_sizes[sc->current_sample];
1829
    }
1830

    
1831
    sc->current_sample++;
1832
#endif
1833

    
1834
readchunk:
1835
#ifdef DEBUG
1836
    av_log(NULL, AV_LOG_DEBUG, "chunk: %lli -> %lli (%i)\n", offset, offset + size, size);
1837
#endif
1838
    if(size == 0x0FFFFFFF)
1839
        size = mov->mdat_size + mov->mdat_offset - offset;
1840
    if(size < 0)
1841
        return -1;
1842
    if(size == 0)
1843
        return -1;
1844
    url_fseek(&s->pb, offset, SEEK_SET);
1845

    
1846
    //av_log(NULL, AV_LOG_DEBUG, "READCHUNK hlen: %d  %d off: %Ld   pos:%Ld\n", size, sc->header_len, offset, url_ftell(&s->pb));
1847
    if (sc->header_len > 0) {
1848
        av_new_packet(pkt, size + sc->header_len);
1849
        memcpy(pkt->data, sc->header_data, sc->header_len);
1850
        get_buffer(&s->pb, pkt->data + sc->header_len, size);
1851
        /* free header */
1852
        av_freep(&sc->header_data);
1853
        sc->header_len = 0;
1854
    } else {
1855
        av_new_packet(pkt, size);
1856
        get_buffer(&s->pb, pkt->data, pkt->size);
1857
    }
1858
    pkt->stream_index = sc->ffindex;
1859
    
1860
    // If the keyframes table exists, mark any samples that are in the table as key frames.
1861
    // If no table exists, treat very sample as a key frame.
1862
    if (sc->keyframes) {        
1863
        a = 0;
1864
        b = sc->keyframe_count - 1;
1865
        
1866
        while (a < b) {
1867
            m = (a + b + 1) >> 1;
1868
            if (sc->keyframes[m] > sc->current_sample) {
1869
                b = m - 1;
1870
            } else {
1871
                a = m;
1872
            }    
1873
        }
1874
        
1875
        if (sc->keyframes[a] == sc->current_sample)
1876
            pkt->flags |= PKT_FLAG_KEY;
1877
    }
1878
    else
1879
        pkt->flags |= PKT_FLAG_KEY;
1880

    
1881
#ifdef DEBUG
1882

    
1883
    av_log(NULL, AV_LOG_DEBUG, "Packet (%d, %ld) ", pkt->stream_index, pkt->size);
1884
    for(i=0; i<8; i++)
1885
        av_log(NULL, AV_LOG_DEBUG, "%02x ", pkt->data[i]);
1886
    for(i=0; i<8; i++)
1887
        av_log(NULL, AV_LOG_DEBUG, "%c ", (pkt->data[i]) & 0x7F);
1888
    av_log(NULL, AV_LOG_DEBUG, "\n");
1889

    
1890
#endif
1891

    
1892
    mov->next_chunk_offset = offset + size;
1893

    
1894
    return 0;
1895
}
1896

    
1897
#if defined(MOV_SPLIT_CHUNKS) && defined(MOV_SEEK)
1898
/**
1899
 * Seek method based on the one described in the Appendix C of QTFileFormat.pdf
1900
 */
1901
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1902
{
1903
    MOVContext* mov = (MOVContext *) s->priv_data;
1904
    MOVStreamContext* sc;
1905
    int32_t i, a, b, m;
1906
    int64_t sample_time;
1907
    int64_t start_time;
1908
    int32_t seek_sample, sample;
1909
    int32_t duration;
1910
    int32_t count;
1911
    int32_t chunk;
1912
    int32_t left_in_chunk;
1913
    int64_t chunk_file_offset;
1914
    int64_t sample_file_offset;
1915
    int32_t first_chunk_sample;
1916
    int32_t sample_to_chunk_idx;
1917
    int mov_idx;
1918

    
1919
    // Find the corresponding mov stream
1920
    for (mov_idx = 0; mov_idx < mov->total_streams; mov_idx++)
1921
        if (mov->streams[mov_idx]->ffindex == stream_index)
1922
            break;
1923
    if (mov_idx == mov->total_streams) {
1924
        av_log(s, AV_LOG_ERROR, "mov: requested stream was not found in mov streams (idx=%i)\n", stream_index);
1925
        return -1;
1926
    }
1927
    sc = mov->streams[mov_idx];
1928

    
1929
    // Step 1. Find the edit that contains the requested time (elst)
1930
    if (sc->edit_count) {
1931
        // FIXME should handle edit list
1932
        av_log(s, AV_LOG_ERROR, "mov: does not handle seeking in files that contain edit list (c:%d)\n", sc->edit_count);
1933
        return -1;
1934
    }
1935

    
1936
    // Step 2. Find the corresponding sample using the Time-to-sample atom (stts) */
1937
#ifdef DEBUG
1938
  av_log(s, AV_LOG_DEBUG, "Searching for time %li in stream #%i (time_scale=%i)\n", (long)timestamp, mov_idx, sc->time_scale);
1939
#endif
1940
    // convert timestamp from time_base unit to timescale unit
1941
    sample_time = av_rescale( timestamp,
1942
                            (int64_t)sc->time_scale * s->streams[stream_index]->time_base.num,
1943
                            (int64_t)s->streams[stream_index]->time_base.den);
1944
    start_time = 0; // FIXME use elst atom
1945
    sample = 1; // sample are 0 based in table
1946
#ifdef DEBUG
1947
    av_log(s, AV_LOG_DEBUG, "Searching for sample_time %li \n", (long)sample_time);
1948
#endif
1949
    for (i = 0; i < sc->stts_count; i++) {
1950
        count = (uint32_t)(sc->stts_data[i]>>32);
1951
        duration = (uint32_t)(sc->stts_data[i]&0xffff);
1952
//av_log(s, AV_LOG_DEBUG, "> sample_time %lli \n", (long)sample_time);                
1953
//av_log(s, AV_LOG_DEBUG, "> count=%i duration=%i\n", count, duration);        
1954
        if ((start_time + count*duration) > sample_time) {
1955
            sample += (sample_time - start_time) / duration;
1956
            break;
1957
        }
1958
        sample += count;
1959
        start_time += count * duration;
1960
    }   
1961
    /* NOTE: despite what qt doc say, the dt value (Display Time in qt vocabulary) computed with the stts atom
1962
       is a decoding time stamp (dts) not a presentation time stamp. And as usual dts != pts for stream with b frames */
1963

    
1964
#ifdef DEBUG
1965
    av_log(s, AV_LOG_DEBUG, "Found time %li at sample #%u\n", (long)sample_time, sample);
1966
#endif
1967
    if (sample > sc->sample_count) {
1968
        av_log(s, AV_LOG_ERROR, "mov: sample pos is too high, unable to seek (req. sample=%i, sample count=%ld)\n", sample, sc->sample_count);
1969
        return -1;
1970
    }
1971

    
1972
    // Step 3. Find the prior sync. sample using the Sync sample atom (stss)
1973
    if (sc->keyframes) {
1974
        a = 0;
1975
        b = sc->keyframe_count - 1;
1976
        while (a < b) {
1977
            m = (a + b + 1) >> 1;
1978
            if (sc->keyframes[m] > sample) {
1979
                b = m - 1;
1980
            } else {
1981
                a = m;
1982
            }
1983
#ifdef DEBUG
1984
         // av_log(s, AV_LOG_DEBUG, "a=%i (%i) b=%i (%i) m=%i (%i) stream #%i\n", a, sc->keyframes[a], b, sc->keyframes[b], m, sc->keyframes[m], mov_idx);
1985
#endif
1986
        }
1987
        seek_sample = sc->keyframes[a];
1988
    }
1989
    else
1990
        seek_sample = sample; // else all samples are key frames
1991
#ifdef DEBUG
1992
    av_log(s, AV_LOG_DEBUG, "Found nearest keyframe at sample #%i \n", seek_sample);
1993
#endif
1994

    
1995
    // Step 4. Find the chunk of the sample using the Sample-to-chunk-atom (stsc)
1996
    for (first_chunk_sample = 1, i = 0; i < (sc->sample_to_chunk_sz - 1); i++) {
1997
        b = (sc->sample_to_chunk[i + 1].first - sc->sample_to_chunk[i].first) * sc->sample_to_chunk[i].count;
1998
        if (seek_sample >= first_chunk_sample && seek_sample < (first_chunk_sample + b))
1999
            break;
2000
        first_chunk_sample += b;
2001
    }
2002
    chunk = sc->sample_to_chunk[i].first + (seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count;
2003
    left_in_chunk = sc->sample_to_chunk[i].count - (seek_sample - first_chunk_sample) % sc->sample_to_chunk[i].count;
2004
    first_chunk_sample += ((seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count) * sc->sample_to_chunk[i].count;
2005
    sample_to_chunk_idx = i;
2006
#ifdef DEBUG
2007
    av_log(s, AV_LOG_DEBUG, "Sample was found in chunk #%i at sample offset %i (idx %i)\n", chunk, seek_sample - first_chunk_sample, sample_to_chunk_idx);
2008
#endif
2009

    
2010
    // Step 5. Find the offset of the chunk using the chunk offset atom
2011
    if (!sc->chunk_offsets) {
2012
        av_log(s, AV_LOG_ERROR, "mov: no chunk offset atom, unable to seek\n");
2013
        return -1;
2014
    }
2015
    if (chunk > sc->chunk_count) {
2016
        av_log(s, AV_LOG_ERROR, "mov: chunk offset atom too short, unable to seek (req. chunk=%i, chunk count=%li)\n", chunk, sc->chunk_count);
2017
        return -1;
2018
    }
2019
    chunk_file_offset = sc->chunk_offsets[chunk - 1];
2020
#ifdef DEBUG
2021
    av_log(s, AV_LOG_DEBUG, "Chunk file offset is #%llu \n", chunk_file_offset);
2022
#endif
2023

    
2024
    // Step 6. Find the byte offset within the chunk using the sample size atom
2025
    sample_file_offset = chunk_file_offset;
2026
    if (sc->sample_size)
2027
        sample_file_offset += (seek_sample - first_chunk_sample) * sc->sample_size;
2028
    else {
2029
        for (i = 0; i < (seek_sample - first_chunk_sample); i++) {
2030
        sample_file_offset += sc->sample_sizes[first_chunk_sample + i - 1];
2031
        }
2032
    }
2033
#ifdef DEBUG
2034
    av_log(s, AV_LOG_DEBUG, "Sample file offset is #%llu \n", sample_file_offset);
2035
#endif
2036

    
2037
    // Step 6. Update the parser
2038
    mov->partial = sc;
2039
    mov->next_chunk_offset = sample_file_offset;
2040
    // Update current stream state
2041
    sc->current_sample = seek_sample - 1;  // zero based
2042
    sc->left_in_chunk = left_in_chunk;
2043
    sc->next_chunk = chunk; // +1 -1 (zero based)
2044
    sc->sample_to_chunk_index = sample_to_chunk_idx;
2045

    
2046
    // Update other streams    
2047
    for (i = 0; i<mov->total_streams; i++) {
2048
        MOVStreamContext *msc;
2049
        if (i == mov_idx) continue;
2050
        // Find the nearest 'next' chunk
2051
        msc = mov->streams[i];
2052
        a = 0;
2053
        b = msc->chunk_count - 1;
2054
        while (a < b) {
2055
            m = (a + b + 1) >> 1;
2056
            if (msc->chunk_offsets[m] > chunk_file_offset) {
2057
                b = m - 1;
2058
            } else {
2059
                a = m;
2060
            }
2061
#ifdef DEBUG            
2062
/*            av_log(s, AV_LOG_DEBUG, "a=%i (%li) b=%i (%li) m=%i (%li) stream #%i\n"
2063
            , a, (long)msc->chunk_offsets[a], b, (long)msc->chunk_offsets[b], m, (long)msc->chunk_offsets[m],  i); */
2064
#endif                  
2065
        }
2066
        msc->next_chunk = a;
2067
        if (msc->chunk_offsets[a] < chunk_file_offset && a < (msc->chunk_count-1))
2068
            msc->next_chunk ++;
2069
#ifdef DEBUG        
2070
        av_log(s, AV_LOG_DEBUG, "Nearest next chunk for stream #%i is #%i @%lli\n", i, msc->next_chunk+1, msc->chunk_offsets[msc->next_chunk]);
2071
#endif        
2072
        // Compute sample count and index in the sample_to_chunk table (what a pity)
2073
        msc->sample_to_chunk_index = 0;
2074
        msc->current_sample = 0;
2075
        for(;  msc->sample_to_chunk_index < (msc->sample_to_chunk_sz - 1)
2076
            && msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first <= (1 + msc->next_chunk); msc->sample_to_chunk_index++) {
2077
            msc->current_sample += (msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first - msc->sample_to_chunk[msc->sample_to_chunk_index].first) \
2078
            * msc->sample_to_chunk[msc->sample_to_chunk_index].count;
2079
        }
2080
        msc->current_sample += (msc->next_chunk - (msc->sample_to_chunk[msc->sample_to_chunk_index].first - 1)) * sc->sample_to_chunk[msc->sample_to_chunk_index].count;
2081
        msc->left_in_chunk = msc->sample_to_chunk[msc->sample_to_chunk_index].count - 1;
2082
#ifdef DEBUG        
2083
        av_log(s, AV_LOG_DEBUG, "Next Sample for stream #%i is #%i @%i\n", i, msc->current_sample + 1, msc->sample_to_chunk_index + 1);
2084
#endif        
2085
    }                
2086
    return 0;
2087
}
2088
#endif
2089

    
2090
static int mov_read_close(AVFormatContext *s)
2091
{
2092
    int i;
2093
    MOVContext *mov = (MOVContext *) s->priv_data;
2094
    for(i=0; i<mov->total_streams; i++)
2095
        mov_free_stream_context(mov->streams[i]);
2096
    /* free color tabs */
2097
    for(i=0; i<mov->ctab_size; i++)
2098
        av_freep(&mov->ctab[i]);
2099
    av_freep(&mov->ctab);
2100
    return 0;
2101
}
2102

    
2103
static AVInputFormat mov_iformat = {
2104
    "mov,mp4,m4a,3gp",
2105
    "QuickTime/MPEG4 format",
2106
    sizeof(MOVContext),
2107
    mov_probe,
2108
    mov_read_header,
2109
    mov_read_packet,
2110
    mov_read_close,
2111
#if defined(MOV_SPLIT_CHUNKS) && defined(MOV_SEEK)
2112
    mov_read_seek,
2113
#endif    
2114
};
2115

    
2116
int mov_init(void)
2117
{
2118
    av_register_input_format(&mov_iformat);
2119
    return 0;
2120
}