Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 7c4a25c8

History | View | Annotate | Download (70.3 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/PDF/QTFileFormat.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_NONE, 0 },
119
};
120

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

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

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

    
151
typedef struct MOV_sample_to_chunk_tbl {
152
    long first;
153
    long count;
154
    long id;
155
} MOV_sample_to_chunk_tbl;
156

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

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

    
170
typedef struct {
171
    uint8_t  version;
172
    uint32_t flags; // 24bit
173

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

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

    
209
    /* 0x05 DecSpecificDescrTag */
210
    uint8_t  decoder_cfg_len;
211
    uint8_t *decoder_cfg;
212

    
213
    /* 0x06 SLConfigDescrTag */
214
    uint8_t  sl_config_len;
215
    uint8_t *sl_config;
216
} MOV_esds_t;
217

    
218
struct MOVParseTableEntry;
219

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

    
246
typedef struct MOVContext {
247
    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) */
248
    AVFormatContext *fc;
249
    int time_scale;
250
    int duration; /* duration of the longest track */
251
    int found_moov; /* when both 'moov' and 'mdat' sections has been found */
252
    int found_mdat; /* we suppose we have enough data to read the file */
253
    int64_t mdat_size;
254
    int64_t mdat_offset;
255
    int total_streams;
256
    /* some streams listed here aren't presented to the ffmpeg API, since they aren't either video nor audio
257
     * but we need the info to be able to skip data from those streams in the 'mdat' section
258
     */
259
    MOVStreamContext *streams[MAX_STREAMS];
260

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

    
268
    AVPaletteControl palette_control;
269
} MOVContext;
270

    
271

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

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

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

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

    
316

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

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

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

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

    
339
    a.offset = atom.offset;
340

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

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

    
383
        a.offset += a.size;
384
        total_size += a.size;
385
    }
386

    
387
    if (!err && total_size < atom.size && atom.size < 0x7ffff) {
388
        //av_log(NULL, AV_LOG_DEBUG, "RESET  %Ld  %Ld  err:%d\n", atom.size, total_size, err);
389
        url_fskip(pb, atom.size - total_size);
390
    }
391

    
392
#ifdef DEBUG
393
    debug_indent--;
394
#endif
395
    return err;
396
}
397

    
398
static int mov_read_ctab(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
399
{
400
    unsigned int len;
401
    MOV_ctab_t *t;
402
    //url_fskip(pb, atom.size); // for now
403
    c->ctab = av_realloc(c->ctab, ++c->ctab_size);
404
    t = c->ctab[c->ctab_size];
405
    t->seed = get_be32(pb);
406
    t->flags = get_be16(pb);
407
    t->size = get_be16(pb) + 1;
408
    len = 2 * t->size * 4;
409
    if (len > 0) {
410
        t->clrs = av_malloc(len); // 16bit A R G B
411
        if (t->clrs)
412
            get_buffer(pb, t->clrs, len);
413
    }
414

    
415
    return 0;
416
}
417

    
418
static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
419
{
420
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
421
    int len = 0;
422
    uint32_t type;
423
    uint32_t ctype;
424

    
425
    print_atom("hdlr", atom);
426

    
427
    get_byte(pb); /* version */
428
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
429

    
430
    /* component type */
431
    ctype = get_le32(pb);
432
    type = get_le32(pb); /* component subtype */
433

    
434
#ifdef DEBUG
435
    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);
436
    av_log(NULL, AV_LOG_DEBUG, "stype= %c%c%c%c\n", *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
437
#endif
438
#ifdef DEBUG
439
/* XXX: yeah this is ugly... */
440
    if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
441
        if(type == MKTAG('v', 'i', 'd', 'e'))
442
            puts("hdlr: vide");
443
        else if(type == MKTAG('s', 'o', 'u', 'n'))
444
            puts("hdlr: soun");
445
    } else if(ctype == 0) { /* MP4 */
446
        if(type == MKTAG('v', 'i', 'd', 'e'))
447
            puts("hdlr: vide");
448
        else if(type == MKTAG('s', 'o', 'u', 'n'))
449
            puts("hdlr: soun");
450
        else if(type == MKTAG('o', 'd', 's', 'm'))
451
            puts("hdlr: odsm");
452
        else if(type == MKTAG('s', 'd', 's', 'm'))
453
            puts("hdlr: sdsm");
454
    } else puts("hdlr: meta");
455
#endif
456

    
457
    if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
458
        /* helps parsing the string hereafter... */
459
        c->mp4 = 0;
460
        if(type == MKTAG('v', 'i', 'd', 'e'))
461
            st->codec.codec_type = CODEC_TYPE_VIDEO;
462
        else if(type == MKTAG('s', 'o', 'u', 'n'))
463
            st->codec.codec_type = CODEC_TYPE_AUDIO;
464
    } else if(ctype == 0) { /* MP4 */
465
        /* helps parsing the string hereafter... */
466
        c->mp4 = 1;
467
        if(type == MKTAG('v', 'i', 'd', 'e'))
468
            st->codec.codec_type = CODEC_TYPE_VIDEO;
469
        else if(type == MKTAG('s', 'o', 'u', 'n'))
470
            st->codec.codec_type = CODEC_TYPE_AUDIO;
471
    }
472
    get_be32(pb); /* component  manufacture */
473
    get_be32(pb); /* component flags */
474
    get_be32(pb); /* component flags mask */
475

    
476
    if(atom.size <= 24)
477
        return 0; /* nothing left to read */
478
    /* XXX: MP4 uses a C string, not a pascal one */
479
    /* component name */
480

    
481
    if(c->mp4) {
482
        /* .mp4: C string */
483
        while(get_byte(pb) && (++len < (atom.size - 24)));
484
    } else {
485
        /* .mov: PASCAL string */
486
#ifdef DEBUG
487
        char* buf;
488
#endif
489
        len = get_byte(pb);
490
#ifdef DEBUG
491
        buf = (uint8_t*) av_malloc(len+1);
492
        if (buf) {
493
            get_buffer(pb, buf, len);
494
            buf[len] = '\0';
495
            av_log(NULL, AV_LOG_DEBUG, "**buf='%s'\n", buf);
496
            av_free(buf);
497
        } else
498
#endif
499
            url_fskip(pb, len);
500
    }
501

    
502
    url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
503
    return 0;
504
}
505

    
506
static int mov_mp4_read_descr_len(ByteIOContext *pb)
507
{
508
    int len = 0;
509
    int count = 4;
510
    while (count--) {
511
        int c = get_byte(pb);
512
        len = (len << 7) | (c & 0x7f);
513
        if (!(c & 0x80))
514
            break;
515
    }
516
    return len;
517
}
518

    
519
static int mov_mp4_read_descr(ByteIOContext *pb, int *tag)
520
{
521
    int len;
522
    *tag = get_byte(pb);
523
    len = mov_mp4_read_descr_len(pb);
524
#ifdef DEBUG
525
    av_log(NULL, AV_LOG_DEBUG, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
526
#endif
527
    return len;
528
}
529

    
530
static inline unsigned int get_be24(ByteIOContext *s)
531
{
532
    unsigned int val;
533
    val = get_byte(s) << 16;
534
    val |= get_byte(s) << 8;
535
    val |= get_byte(s);
536
    return val;
537
}
538

    
539
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
540
{
541
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
542
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
543
    int64_t start_pos = url_ftell(pb);
544
    int tag, len;
545

    
546
    print_atom("esds", atom);
547

    
548
    /* Well, broken but suffisant for some MP4 streams */
549
    get_be32(pb); /* version + flags */
550
    len = mov_mp4_read_descr(pb, &tag);
551
    if (tag == MP4ESDescrTag) {
552
        get_be16(pb); /* ID */
553
        get_byte(pb); /* priority */
554
    } else
555
        get_be16(pb); /* ID */
556

    
557
    len = mov_mp4_read_descr(pb, &tag);
558
    if (tag == MP4DecConfigDescrTag) {
559
        sc->esds.object_type_id = get_byte(pb);
560
        sc->esds.stream_type = get_byte(pb);
561
        sc->esds.buffer_size_db = get_be24(pb);
562
        sc->esds.max_bitrate = get_be32(pb);
563
        sc->esds.avg_bitrate = get_be32(pb);
564

    
565
        len = mov_mp4_read_descr(pb, &tag);
566
        //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);
567
        if (tag == MP4DecSpecificDescrTag) {
568
#ifdef DEBUG
569
            av_log(NULL, AV_LOG_DEBUG, "Specific MPEG4 header len=%d\n", len);
570
#endif
571
            st->codec.extradata = (uint8_t*) av_mallocz(len);
572
            if (st->codec.extradata) {
573
                get_buffer(pb, st->codec.extradata, len);
574
                st->codec.extradata_size = len;
575
            }
576
        }
577
    }
578
    /* in any case, skip garbage */
579
    url_fskip(pb, atom.size - ((url_ftell(pb) - start_pos)));
580
    return 0;
581
}
582

    
583
/* this atom contains actual media data */
584
static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
585
{
586
    print_atom("mdat", atom);
587

    
588
    if(atom.size == 0) /* wrong one (MP4) */
589
        return 0;
590
    c->found_mdat=1;
591
    c->mdat_offset = atom.offset;
592
    c->mdat_size = atom.size;
593
    if(c->found_moov)
594
        return 1; /* found both, just go */
595
    url_fskip(pb, atom.size);
596
    return 0; /* now go for moov */
597
}
598

    
599
/* this atom should contain all header atoms */
600
static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
601
{
602
    int err;
603

    
604
    print_atom("moov", atom);
605

    
606
    err = mov_read_default(c, pb, atom);
607
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
608
    /* so we don't parse the whole file if over a network */
609
    c->found_moov=1;
610
    if(c->found_mdat)
611
        return 1; /* found both, just go */
612
    return 0; /* now go for mdat */
613
}
614

    
615

    
616
static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
617
{
618
    print_atom("mdhd", atom);
619

    
620
    get_byte(pb); /* version */
621

    
622
    get_byte(pb); get_byte(pb);
623
    get_byte(pb); /* flags */
624

    
625
    get_be32(pb); /* creation time */
626
    get_be32(pb); /* modification time */
627

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

    
630
#ifdef DEBUG
631
    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 */
632
#endif
633
    get_be32(pb); /* duration */
634

    
635
    get_be16(pb); /* language */
636
    get_be16(pb); /* quality */
637

    
638
    return 0;
639
}
640

    
641
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
642
{
643
    print_atom("mvhd", atom);
644

    
645
    get_byte(pb); /* version */
646
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
647

    
648
    get_be32(pb); /* creation time */
649
    get_be32(pb); /* modification time */
650
    c->time_scale = get_be32(pb); /* time scale */
651
#ifdef DEBUG
652
    av_log(NULL, AV_LOG_DEBUG, "time scale = %i\n", c->time_scale);
653
#endif
654
    c->duration = get_be32(pb); /* duration */
655
    get_be32(pb); /* preferred scale */
656

    
657
    get_be16(pb); /* preferred volume */
658

    
659
    url_fskip(pb, 10); /* reserved */
660

    
661
    url_fskip(pb, 36); /* display matrix */
662

    
663
    get_be32(pb); /* preview time */
664
    get_be32(pb); /* preview duration */
665
    get_be32(pb); /* poster time */
666
    get_be32(pb); /* selection time */
667
    get_be32(pb); /* selection duration */
668
    get_be32(pb); /* current time */
669
    get_be32(pb); /* next track ID */
670

    
671
    return 0;
672
}
673

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

    
678
    // currently SVQ3 decoder expect full STSD header - so let's fake it
679
    // this should be fixed and just SMI header should be passed
680
    av_free(st->codec.extradata);
681
    st->codec.extradata_size = 0x5a + atom.size;
682
    st->codec.extradata = (uint8_t*) av_mallocz(st->codec.extradata_size);
683

    
684
    if (st->codec.extradata) {
685
        strcpy(st->codec.extradata, "SVQ3"); // fake
686
        get_buffer(pb, st->codec.extradata + 0x5a, atom.size);
687
        //av_log(NULL, AV_LOG_DEBUG, "Reading SMI %Ld  %s\n", atom.size, (char*)st->codec.extradata + 0x5a);
688
    } else
689
        url_fskip(pb, atom.size);
690

    
691
    return 0;
692
}
693

    
694
static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
695
{
696
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
697
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
698
    int entries, i;
699

    
700
    print_atom("stco", atom);
701

    
702
    get_byte(pb); /* version */
703
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
704

    
705
    entries = get_be32(pb);
706
    sc->chunk_count = entries;
707
    sc->chunk_offsets = (int64_t*) av_malloc(entries * sizeof(int64_t));
708
    if (!sc->chunk_offsets)
709
        return -1;
710
    if (atom.type == MKTAG('s', 't', 'c', 'o')) {
711
        for(i=0; i<entries; i++) {
712
            sc->chunk_offsets[i] = get_be32(pb);
713
        }
714
    } else if (atom.type == MKTAG('c', 'o', '6', '4')) {
715
        for(i=0; i<entries; i++) {
716
            sc->chunk_offsets[i] = get_be64(pb);
717
        }
718
    } else
719
        return -1;
720
#ifdef DEBUG
721
/*
722
    for(i=0; i<entries; i++) {
723
        av_log(NULL, AV_LOG_DEBUG, "chunk offset=0x%Lx\n", sc->chunk_offsets[i]);
724
    }
725
*/
726
#endif
727
    return 0;
728
}
729

    
730
static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
731
{
732
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
733
    //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
734
    int entries, frames_per_sample;
735
    uint32_t format;
736

    
737
    /* for palette traversal */
738
    int color_depth;
739
    int color_start;
740
    int color_count;
741
    int color_end;
742
    int color_index;
743
    int color_dec;
744
    int color_greyscale;
745
    unsigned char *color_table;
746
    int j;
747
    unsigned char r, g, b;
748

    
749
    print_atom("stsd", atom);
750

    
751
    get_byte(pb); /* version */
752
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
753

    
754
    entries = get_be32(pb);
755

    
756
    while(entries--) { //Parsing Sample description table
757
        enum CodecID id;
758
        int size = get_be32(pb); /* size */
759
        format = get_le32(pb); /* data format */
760

    
761
        get_be32(pb); /* reserved */
762
        get_be16(pb); /* reserved */
763
        get_be16(pb); /* index */
764

    
765
        /* for MPEG4: set codec type by looking for it */
766
        id = codec_get_id(mov_video_tags, format);
767
        if (id >= 0) {
768
            AVCodec *codec;
769
            codec = avcodec_find_decoder(id);
770
            if (codec)
771
                st->codec.codec_type = codec->type;
772
        }
773
#ifdef DEBUG
774
        av_log(NULL, AV_LOG_DEBUG, "size=%d 4CC= %c%c%c%c codec_type=%d\n",
775
               size,
776
               (format >> 0) & 0xff,
777
               (format >> 8) & 0xff,
778
               (format >> 16) & 0xff,
779
               (format >> 24) & 0xff,
780
               st->codec.codec_type);
781
#endif
782
        st->codec.codec_tag = format;
783
        if(st->codec.codec_type==CODEC_TYPE_VIDEO) {
784
            MOV_atom_t a = { 0, 0, 0 };
785
            st->codec.codec_id = id;
786
            get_be16(pb); /* version */
787
            get_be16(pb); /* revision level */
788
            get_be32(pb); /* vendor */
789
            get_be32(pb); /* temporal quality */
790
            get_be32(pb); /* spacial quality */
791
            st->codec.width = get_be16(pb); /* width */
792
            st->codec.height = get_be16(pb); /* height */
793
#if 1
794
            if (st->codec.codec_id == CODEC_ID_MPEG4) {
795
                /* in some MPEG4 the width/height are not correct, so
796
                   we ignore this info */
797
                st->codec.width = 0;
798
                st->codec.height = 0;
799
            }
800
#endif
801
            get_be32(pb); /* horiz resolution */
802
            get_be32(pb); /* vert resolution */
803
            get_be32(pb); /* data size, always 0 */
804
            frames_per_sample = get_be16(pb); /* frames per samples */
805
#ifdef DEBUG
806
            av_log(NULL, AV_LOG_DEBUG, "frames/samples = %d\n", frames_per_sample);
807
#endif
808
            get_buffer(pb, (uint8_t *)st->codec.codec_name, 32); /* codec name */
809

    
810
            st->codec.bits_per_sample = get_be16(pb); /* depth */
811
            st->codec.color_table_id = get_be16(pb); /* colortable id */
812

    
813
/*          These are set in mov_read_stts and might already be set!
814
            st->codec.frame_rate      = 25;
815
            st->codec.frame_rate_base = 1;
816
*/
817
            size -= (16+8*4+2+32+2*2);
818
#if 0
819
            while (size >= 8) {
820
                MOV_atom_t a;
821
                int64_t start_pos;
822

823
                a.size = get_be32(pb);
824
                a.type = get_le32(pb);
825
                size -= 8;
826
#ifdef DEBUG
827
                av_log(NULL, AV_LOG_DEBUG, "VIDEO: atom_type=%c%c%c%c atom.size=%Ld size_left=%d\n",
828
                       (a.type >> 0) & 0xff,
829
                       (a.type >> 8) & 0xff,
830
                       (a.type >> 16) & 0xff,
831
                       (a.type >> 24) & 0xff,
832
                       a.size, size);
833
#endif
834
                start_pos = url_ftell(pb);
835

    
836
                switch(a.type) {
837
                case MKTAG('e', 's', 'd', 's'):
838
                    {
839
                        int tag, len;
840
                        /* Well, broken but suffisant for some MP4 streams */
841
                        get_be32(pb); /* version + flags */
842
                        len = mov_mp4_read_descr(pb, &tag);
843
                        if (tag == 0x03) {
844
                            /* MP4ESDescrTag */
845
                            get_be16(pb); /* ID */
846
                            get_byte(pb); /* priority */
847
                            len = mov_mp4_read_descr(pb, &tag);
848
                            if (tag != 0x04)
849
                                goto fail;
850
                            /* MP4DecConfigDescrTag */
851
                            get_byte(pb); /* objectTypeId */
852
                            get_be32(pb); /* streamType + buffer size */
853
                            get_be32(pb); /* max bit rate */
854
                            get_be32(pb); /* avg bit rate */
855
                            len = mov_mp4_read_descr(pb, &tag);
856
                            if (tag != 0x05)
857
                                goto fail;
858
                            /* MP4DecSpecificDescrTag */
859
#ifdef DEBUG
860
                            av_log(NULL, AV_LOG_DEBUG, "Specific MPEG4 header len=%d\n", len);
861
#endif
862
                            sc->header_data = av_mallocz(len);
863
                            if (sc->header_data) {
864
                                get_buffer(pb, sc->header_data, len);
865
                                sc->header_len = len;
866
                            }
867
                        }
868
                        /* in any case, skip garbage */
869
                    }
870
                    break;
871
                default:
872
                    break;
873
                }
874
            fail:
875
                av_log(NULL, AV_LOG_DEBUG, "ATOMENEWSIZE %Ld   %d\n", atom.size, url_ftell(pb) - start_pos);
876
                if (atom.size > 8) {
877
                    url_fskip(pb, (atom.size - 8) -
878
                              ((url_ftell(pb) - start_pos)));
879
                    size -= atom.size - 8;
880
                }
881
            }
882
            if (size > 0) {
883
                /* unknown extension */
884
                url_fskip(pb, size);
885
            }
886
#else
887

    
888
            /* figure out the palette situation */
889
            color_depth = st->codec.bits_per_sample & 0x1F;
890
            color_greyscale = st->codec.bits_per_sample & 0x20;
891

    
892
            /* if the depth is 2, 4, or 8 bpp, file is palettized */
893
            if ((color_depth == 2) || (color_depth == 4) || 
894
                (color_depth == 8)) {
895

    
896
                if (color_greyscale) {
897

    
898
                    /* compute the greyscale palette */
899
                    color_count = 1 << color_depth;
900
                    color_index = 255;
901
                    color_dec = 256 / (color_count - 1);
902
                    for (j = 0; j < color_count; j++) {
903
                        r = g = b = color_index;
904
                        c->palette_control.palette[j] =
905
                            (r << 16) | (g << 8) | (b);
906
                        color_index -= color_dec;
907
                        if (color_index < 0)
908
                            color_index = 0;
909
                    }
910

    
911
                } else if (st->codec.color_table_id & 0x08) {
912

    
913
                    /* if flag bit 3 is set, use the default palette */
914
                    color_count = 1 << color_depth;
915
                    if (color_depth == 2)
916
                        color_table = ff_qt_default_palette_4;
917
                    else if (color_depth == 4)
918
                        color_table = ff_qt_default_palette_16;
919
                    else
920
                        color_table = ff_qt_default_palette_256;
921

    
922
                    for (j = 0; j < color_count; j++) {
923
                        r = color_table[j * 4 + 0];
924
                        g = color_table[j * 4 + 1];
925
                        b = color_table[j * 4 + 2];
926
                        c->palette_control.palette[j] =
927
                            (r << 16) | (g << 8) | (b);
928
                    }
929

    
930
                } else {
931

    
932
                    /* load the palette from the file */
933
                    color_start = get_be32(pb);
934
                    color_count = get_be16(pb);
935
                    color_end = get_be16(pb);
936
                    for (j = color_start; j <= color_end; j++) {
937
                        /* each R, G, or B component is 16 bits;
938
                         * only use the top 8 bits; skip alpha bytes
939
                         * up front */
940
                        get_byte(pb);
941
                        get_byte(pb);
942
                        r = get_byte(pb);
943
                        get_byte(pb);
944
                        g = get_byte(pb);
945
                        get_byte(pb);
946
                        b = get_byte(pb);
947
                        get_byte(pb);
948
                        c->palette_control.palette[j] =
949
                            (r << 16) | (g << 8) | (b);
950
                    }
951
                }
952

    
953
                st->codec.palctrl = &c->palette_control;
954
                st->codec.palctrl->palette_changed = 1;
955
            } else
956
                st->codec.palctrl = NULL;
957

    
958
            a.size = size;
959
            mov_read_default(c, pb, a);
960
#endif
961
        } else {
962
            st->codec.codec_id = codec_get_id(mov_audio_tags, format);
963
            if(st->codec.codec_id==CODEC_ID_AMR_NB || st->codec.codec_id==CODEC_ID_AMR_WB) //from TS26.244
964
            {
965
#ifdef DEBUG
966
               av_log(NULL, AV_LOG_DEBUG, "AMR-NB or AMR-WB audio identified!!\n");
967
#endif
968
               get_be32(pb);get_be32(pb); //Reserved_8
969
               get_be16(pb);//Reserved_2
970
               get_be16(pb);//Reserved_2
971
               get_be32(pb);//Reserved_4
972
               get_be16(pb);//TimeScale
973
               get_be16(pb);//Reserved_2
974

    
975
                //AMRSpecificBox.(10 bytes)
976
               
977
               get_be32(pb); //size
978
               get_be32(pb); //type=='damr'
979
               get_be32(pb); //vendor
980
               get_byte(pb); //decoder version
981
               get_be16(pb); //mode_set
982
               get_byte(pb); //mode_change_period
983
               get_byte(pb); //frames_per_sample
984

    
985
               st->duration = AV_NOPTS_VALUE;//Not possible to get from this info, must count number of AMR frames
986
               if(st->codec.codec_id==CODEC_ID_AMR_NB)
987
               {
988
                   st->codec.sample_rate=8000;
989
                   st->codec.channels=1;
990
               }
991
               else //AMR-WB
992
               {
993
                   st->codec.sample_rate=16000;
994
                   st->codec.channels=1;
995
               }
996
               st->codec.bits_per_sample=16;
997
               st->codec.bit_rate=0; /*It is not possible to tell this before we have 
998
                                       an audio frame and even then every frame can be different*/
999
            }
1000
            else if( st->codec.codec_tag == MKTAG( 'm', 'p', '4', 's' ))
1001
            {
1002
                //This is some stuff for the hint track, lets ignore it!
1003
                //Do some mp4 auto detect.
1004
                c->mp4=1;
1005
                size-=(16);
1006
                url_fskip(pb, size); /* The mp4s atom also contians a esds atom that we can skip*/
1007
            }
1008
            else if( st->codec.codec_tag == MKTAG( 'm', 'p', '4', 'a' ))
1009
            {
1010
                /* Handle mp4 audio tag */
1011
                get_be32(pb); /* version */
1012
                get_be32(pb);
1013
                st->codec.channels = get_be16(pb); /* channels */
1014
                st->codec.bits_per_sample = get_be16(pb); /* bits per sample */
1015
                get_be32(pb);
1016
                st->codec.sample_rate = get_be16(pb); /* sample rate, not always correct */
1017
                get_be16(pb);
1018
                c->mp4=1;
1019
                {
1020
                MOV_atom_t a = { format, url_ftell(pb), size - (20 + 20 + 8) };
1021
                mov_read_default(c, pb, a);
1022
                }
1023
                /* Get correct sample rate from extradata */
1024
                if(st->codec.extradata_size) {
1025
                   const int samplerate_table[] = {
1026
                     96000, 88200, 64000, 48000, 44100, 32000, 
1027
                     24000, 22050, 16000, 12000, 11025, 8000,
1028
                     7350, 0, 0, 0
1029
                   };
1030
                   unsigned char *px = st->codec.extradata;
1031
                   // 5 bits objectTypeIndex, 4 bits sampleRateIndex, 4 bits channels
1032
                   int samplerate_index = ((px[0] & 7) << 1) + ((px[1] >> 7) & 1);
1033
                   st->codec.sample_rate = samplerate_table[samplerate_index];
1034
                }
1035
            }
1036
            else if(size>=(16+20))
1037
            {//16 bytes read, reading atleast 20 more
1038
#ifdef DEBUG
1039
                av_log(NULL, AV_LOG_DEBUG, "audio size=0x%X\n",size);
1040
#endif
1041
                uint16_t version = get_be16(pb); /* version */
1042
                get_be16(pb); /* revision level */
1043
                get_be32(pb); /* vendor */
1044

    
1045
                st->codec.channels = get_be16(pb);                /* channel count */
1046
                st->codec.bits_per_sample = get_be16(pb);        /* sample size */
1047

    
1048
                /* handle specific s8 codec */
1049
                get_be16(pb); /* compression id = 0*/
1050
                get_be16(pb); /* packet size = 0 */
1051

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

    
1055
                switch (st->codec.codec_id) {
1056
                case CODEC_ID_PCM_S16BE:
1057
                    if (st->codec.bits_per_sample == 8)
1058
                        st->codec.codec_id = CODEC_ID_PCM_S8;
1059
                    /* fall */
1060
                case CODEC_ID_PCM_U8:
1061
                    st->codec.bit_rate = st->codec.sample_rate * 8;
1062
                    break;
1063
                default:
1064
                    ;
1065
                }
1066

    
1067
                //Read QT version 1 fields. In version 0 theese dont exist
1068
#ifdef DEBUG
1069
                av_log(NULL, AV_LOG_DEBUG, "version =%d mp4=%d\n",version,c->mp4);
1070
                av_log(NULL, AV_LOG_DEBUG, "size-(16+20+16)=%d\n",size-(16+20+16));
1071
#endif
1072
                if((version==1) && size>=(16+20+16))
1073
                {
1074
                    get_be32(pb); /* samples per packet */
1075
                    get_be32(pb); /* bytes per packet */
1076
                    get_be32(pb); /* bytes per frame */
1077
                    get_be32(pb); /* bytes per sample */
1078
                    if(size>(16+20+16))
1079
                    {
1080
                        //Optional, additional atom-based fields
1081
#ifdef DEBUG
1082
                        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 ),
1083
                            (format >> 0) & 0xff,
1084
                            (format >> 8) & 0xff,
1085
                            (format >> 16) & 0xff,
1086
                            (format >> 24) & 0xff);
1087
#endif
1088
                        MOV_atom_t a = { format, url_ftell(pb), size - (16 + 20 + 16 + 8) };
1089
                        mov_read_default(c, pb, a);
1090
                    }
1091
                }
1092
                else
1093
                {
1094
                    //We should be down to 0 bytes here, but lets make sure.
1095
                    size-=(16+20);
1096
#ifdef DEBUG
1097
                    if(size>0)
1098
                        av_log(NULL, AV_LOG_DEBUG, "skipping 0x%X bytes\n",size-(16+20));
1099
#endif
1100
                    url_fskip(pb, size);
1101
                }
1102
            }
1103
            else
1104
            {
1105
                size-=16;
1106
                //Unknown size, but lets do our best and skip the rest.
1107
#ifdef DEBUG
1108
                av_log(NULL, AV_LOG_DEBUG, "Strange size, skipping 0x%X bytes\n",size);
1109
#endif
1110
                url_fskip(pb, size);
1111
            }
1112
        }
1113
    }
1114

    
1115
    return 0;
1116
}
1117

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

    
1124
    print_atom("stsc", atom);
1125

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

    
1129
    entries = get_be32(pb);
1130
#ifdef DEBUG
1131
av_log(NULL, AV_LOG_DEBUG, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1132
#endif
1133
    sc->sample_to_chunk_sz = entries;
1134
    sc->sample_to_chunk = (MOV_sample_to_chunk_tbl*) av_malloc(entries * sizeof(MOV_sample_to_chunk_tbl));
1135
    if (!sc->sample_to_chunk)
1136
        return -1;
1137
    for(i=0; i<entries; i++) {
1138
        sc->sample_to_chunk[i].first = get_be32(pb);
1139
        sc->sample_to_chunk[i].count = get_be32(pb);
1140
        sc->sample_to_chunk[i].id = get_be32(pb);
1141
#ifdef DEBUG
1142
/*        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); */
1143
#endif
1144
    }
1145
    return 0;
1146
}
1147

    
1148
static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1149
{
1150
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1151
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1152
    int entries, i;
1153

    
1154
    print_atom("stss", atom);
1155

    
1156
    get_byte(pb); /* version */
1157
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1158

    
1159
    entries = get_be32(pb);
1160
    sc->keyframe_count = entries;
1161
#ifdef DEBUG
1162
    av_log(NULL, AV_LOG_DEBUG, "keyframe_count = %ld\n", sc->keyframe_count);
1163
#endif
1164
    sc->keyframes = (long*) av_malloc(entries * sizeof(long));
1165
    if (!sc->keyframes)
1166
        return -1;
1167
    for(i=0; i<entries; i++) {
1168
        sc->keyframes[i] = get_be32(pb);
1169
#ifdef DEBUG
1170
/*        av_log(NULL, AV_LOG_DEBUG, "keyframes[]=%ld\n", sc->keyframes[i]); */
1171
#endif
1172
    }
1173
    return 0;
1174
}
1175

    
1176
static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1177
{
1178
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1179
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1180
    int entries, i;
1181

    
1182
    print_atom("stsz", atom);
1183

    
1184
    get_byte(pb); /* version */
1185
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1186

    
1187
    sc->sample_size = get_be32(pb);
1188
    entries = get_be32(pb);
1189
    sc->sample_count = entries;
1190
#ifdef DEBUG
1191
    av_log(NULL, AV_LOG_DEBUG, "sample_size = %ld sample_count = %ld\n", sc->sample_size, sc->sample_count);
1192
#endif
1193
    if(sc->sample_size)
1194
        return 0; /* there isn't any table following */
1195
    sc->sample_sizes = (long*) av_malloc(entries * sizeof(long));
1196
    if (!sc->sample_sizes)
1197
        return -1;
1198
    for(i=0; i<entries; i++) {
1199
        sc->sample_sizes[i] = get_be32(pb);
1200
#ifdef DEBUG
1201
/*        av_log(NULL, AV_LOG_DEBUG, "sample_sizes[]=%ld\n", sc->sample_sizes[i]); */
1202
#endif
1203
    }
1204
    return 0;
1205
}
1206

    
1207
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1208
{
1209
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1210
    //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1211
    int entries, i;
1212
    int64_t duration=0;
1213
    int64_t total_sample_count=0;
1214

    
1215
    print_atom("stts", atom);
1216

    
1217
    get_byte(pb); /* version */
1218
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1219
    entries = get_be32(pb);
1220

    
1221
    c->streams[c->fc->nb_streams-1]->stts_count = entries;
1222
    c->streams[c->fc->nb_streams-1]->stts_data = (uint64_t*) av_malloc(entries * sizeof(uint64_t));
1223

    
1224
#ifdef DEBUG
1225
av_log(NULL, AV_LOG_DEBUG, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1226
#endif
1227
    for(i=0; i<entries; i++) {
1228
        int32_t sample_duration;
1229
        int32_t sample_count;
1230

    
1231
        sample_count=get_be32(pb);
1232
        sample_duration = get_be32(pb);
1233
        c->streams[c->fc->nb_streams - 1]->stts_data[i] = (uint64_t)sample_count<<32 | (uint64_t)sample_duration;
1234
#ifdef DEBUG
1235
        av_log(NULL, AV_LOG_DEBUG, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1236
#endif
1237
        duration+=sample_duration*sample_count;
1238
        total_sample_count+=sample_count;
1239

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

1242
        if (!i && st->codec.codec_type==CODEC_TYPE_VIDEO) {
1243
            st->codec.frame_rate_base = sample_duration ? sample_duration : 1;
1244
            st->codec.frame_rate = c->streams[c->fc->nb_streams-1]->time_scale;
1245
#ifdef DEBUG
1246
            av_log(NULL, AV_LOG_DEBUG, "VIDEO FRAME RATE= %i (sd= %i)\n", st->codec.frame_rate, sample_duration);
1247
#endif
1248
        }
1249
#endif
1250
    }
1251

    
1252
    /*The stsd atom which contain codec type sometimes comes after the stts so we cannot check for codec_type*/
1253
    if(duration>0)
1254
    {
1255
        av_reduce(
1256
            &st->codec.frame_rate, 
1257
            &st->codec.frame_rate_base, 
1258
            c->streams[c->fc->nb_streams-1]->time_scale * total_sample_count,
1259
            duration,
1260
            INT_MAX
1261
        );
1262

    
1263
#ifdef DEBUG
1264
        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);
1265
#endif
1266
    }
1267
    else
1268
    {
1269
        st->codec.frame_rate_base = 1;
1270
        st->codec.frame_rate = c->streams[c->fc->nb_streams-1]->time_scale;
1271
    }
1272
    return 0;
1273
}
1274

    
1275
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1276
{
1277
    AVStream *st;
1278
    MOVStreamContext *sc;
1279

    
1280
    print_atom("trak", atom);
1281

    
1282
    st = av_new_stream(c->fc, c->fc->nb_streams);
1283
    if (!st) return -2;
1284
    sc = (MOVStreamContext*) av_mallocz(sizeof(MOVStreamContext));
1285
    if (!sc) {
1286
        av_free(st);
1287
        return -1;
1288
    }
1289

    
1290
    sc->sample_to_chunk_index = -1;
1291
    st->priv_data = sc;
1292
    st->codec.codec_type = CODEC_TYPE_MOV_OTHER;
1293
    st->start_time = 0; /* XXX: check */
1294
    st->duration = (c->duration * (int64_t)AV_TIME_BASE) / c->time_scale;
1295
    c->streams[c->fc->nb_streams-1] = sc;
1296

    
1297
    return mov_read_default(c, pb, atom);
1298
}
1299

    
1300
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1301
{
1302
    AVStream *st;
1303

    
1304
    print_atom("tkhd", atom);
1305

    
1306
    st = c->fc->streams[c->fc->nb_streams-1];
1307

    
1308
    get_byte(pb); /* version */
1309

    
1310
    get_byte(pb); get_byte(pb);
1311
    get_byte(pb); /* flags */
1312
    /*
1313
    MOV_TRACK_ENABLED 0x0001
1314
    MOV_TRACK_IN_MOVIE 0x0002
1315
    MOV_TRACK_IN_PREVIEW 0x0004
1316
    MOV_TRACK_IN_POSTER 0x0008
1317
    */
1318

    
1319
    get_be32(pb); /* creation time */
1320
    get_be32(pb); /* modification time */
1321
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1322
    get_be32(pb); /* reserved */
1323
    st->start_time = 0; /* check */
1324
    st->duration = (get_be32(pb) * (int64_t)AV_TIME_BASE) / c->time_scale; /* duration */
1325
    get_be32(pb); /* reserved */
1326
    get_be32(pb); /* reserved */
1327

    
1328
    get_be16(pb); /* layer */
1329
    get_be16(pb); /* alternate group */
1330
    get_be16(pb); /* volume */
1331
    get_be16(pb); /* reserved */
1332

    
1333
    url_fskip(pb, 36); /* display matrix */
1334

    
1335
    /* those are fixed-point */
1336
    st->codec.width = get_be32(pb) >> 16; /* track width */
1337
    st->codec.height = get_be32(pb) >> 16; /* track height */
1338

    
1339
    return 0;
1340
}
1341

    
1342
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1343
/* like the files created with Adobe Premiere 5.0, for samples see */
1344
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1345
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1346
{
1347
    int err;
1348

    
1349
#ifdef DEBUG
1350
    print_atom("wide", atom);
1351
    debug_indent++;
1352
#endif
1353
    if (atom.size < 8)
1354
        return 0; /* continue */
1355
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1356
        url_fskip(pb, atom.size - 4);
1357
        return 0;
1358
    }
1359
    atom.type = get_le32(pb);
1360
    atom.offset += 8;
1361
    atom.size -= 8;
1362
    if (atom.type != MKTAG('m', 'd', 'a', 't')) {
1363
        url_fskip(pb, atom.size);
1364
        return 0;
1365
    }
1366
    err = mov_read_mdat(c, pb, atom);
1367
#ifdef DEBUG
1368
    debug_indent--;
1369
#endif
1370
    return err;
1371
}
1372

    
1373

    
1374
#ifdef CONFIG_ZLIB
1375
static int null_read_packet(void *opaque, uint8_t *buf, int buf_size)
1376
{
1377
    return -1;
1378
}
1379

    
1380
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1381
{
1382
    ByteIOContext ctx;
1383
    uint8_t *cmov_data;
1384
    uint8_t *moov_data; /* uncompressed data */
1385
    long cmov_len, moov_len;
1386
    int ret;
1387

    
1388
    print_atom("cmov", atom);
1389

    
1390
    get_be32(pb); /* dcom atom */
1391
    if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
1392
        return -1;
1393
    if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
1394
        av_log(NULL, AV_LOG_DEBUG, "unknown compression for cmov atom !");
1395
        return -1;
1396
    }
1397
    get_be32(pb); /* cmvd atom */
1398
    if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
1399
        return -1;
1400
    moov_len = get_be32(pb); /* uncompressed size */
1401
    cmov_len = atom.size - 6 * 4;
1402

    
1403
    cmov_data = (uint8_t *) av_malloc(cmov_len);
1404
    if (!cmov_data)
1405
        return -1;
1406
    moov_data = (uint8_t *) av_malloc(moov_len);
1407
    if (!moov_data) {
1408
        av_free(cmov_data);
1409
        return -1;
1410
    }
1411
    get_buffer(pb, cmov_data, cmov_len);
1412
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1413
        return -1;
1414
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, null_read_packet, NULL, NULL) != 0)
1415
        return -1;
1416
    ctx.buf_end = ctx.buffer + moov_len;
1417
    atom.type = MKTAG( 'm', 'o', 'o', 'v' );
1418
    atom.offset = 0;
1419
    atom.size = moov_len;
1420
#ifdef DEBUG
1421
    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1422
#endif
1423
    ret = mov_read_default(c, &ctx, atom);
1424
    av_free(moov_data);
1425
    av_free(cmov_data);
1426

    
1427
    return ret;
1428
}
1429
#endif
1430

    
1431
/* edit list atom */
1432
static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1433
{
1434
  print_atom("elst", atom);
1435

    
1436
  get_byte(pb); /* version */
1437
  get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1438
  c->streams[c->fc->nb_streams-1]->edit_count = get_be32(pb);     /* entries */
1439
#ifdef DEBUG
1440
  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);
1441
#endif
1442
  return 0;
1443
}
1444

    
1445
static const MOVParseTableEntry mov_default_parse_table[] = {
1446
/* mp4 atoms */
1447
{ MKTAG( 'c', 'o', '6', '4' ), mov_read_stco },
1448
{ MKTAG( 'c', 'p', 'r', 't' ), mov_read_default },
1449
{ MKTAG( 'c', 'r', 'h', 'd' ), mov_read_default },
1450
{ MKTAG( 'c', 't', 't', 's' ), mov_read_leaf }, /* composition time to sample */
1451
{ MKTAG( 'd', 'i', 'n', 'f' ), mov_read_default }, /* data information */
1452
{ MKTAG( 'd', 'p', 'n', 'd' ), mov_read_leaf },
1453
{ MKTAG( 'd', 'r', 'e', 'f' ), mov_read_leaf },
1454
{ MKTAG( 'e', 'd', 't', 's' ), mov_read_default },
1455
//{ MKTAG( 'e', 'l', 's', 't' ), mov_read_elst }, //broken, try some movs from http://videos.av7.net/
1456
{ MKTAG( 'f', 'r', 'e', 'e' ), mov_read_leaf },
1457
{ MKTAG( 'h', 'd', 'l', 'r' ), mov_read_hdlr },
1458
{ MKTAG( 'h', 'i', 'n', 't' ), mov_read_leaf },
1459
{ MKTAG( 'h', 'm', 'h', 'd' ), mov_read_leaf },
1460
{ MKTAG( 'i', 'o', 'd', 's' ), mov_read_leaf },
1461
{ MKTAG( 'm', 'd', 'a', 't' ), mov_read_mdat },
1462
{ MKTAG( 'm', 'd', 'h', 'd' ), mov_read_mdhd },
1463
{ MKTAG( 'm', 'd', 'i', 'a' ), mov_read_default },
1464
{ MKTAG( 'm', 'i', 'n', 'f' ), mov_read_default },
1465
{ MKTAG( 'm', 'o', 'o', 'v' ), mov_read_moov },
1466
{ MKTAG( 'm', 'p', '4', 'a' ), mov_read_default },
1467
{ MKTAG( 'm', 'p', '4', 's' ), mov_read_default },
1468
{ MKTAG( 'm', 'p', '4', 'v' ), mov_read_default },
1469
{ MKTAG( 'm', 'p', 'o', 'd' ), mov_read_leaf },
1470
{ MKTAG( 'm', 'v', 'h', 'd' ), mov_read_mvhd },
1471
{ MKTAG( 'n', 'm', 'h', 'd' ), mov_read_leaf },
1472
{ MKTAG( 'o', 'd', 'h', 'd' ), mov_read_default },
1473
{ MKTAG( 's', 'd', 'h', 'd' ), mov_read_default },
1474
{ MKTAG( 's', 'k', 'i', 'p' ), mov_read_leaf },
1475
{ MKTAG( 's', 'm', 'h', 'd' ), mov_read_leaf }, /* sound media info header */
1476
{ MKTAG( 'S', 'M', 'I', ' ' ), mov_read_smi }, /* Sorrenson extension ??? */
1477
{ MKTAG( 's', 't', 'b', 'l' ), mov_read_default },
1478
{ MKTAG( 's', 't', 'c', 'o' ), mov_read_stco },
1479
{ MKTAG( 's', 't', 'd', 'p' ), mov_read_default },
1480
{ MKTAG( 's', 't', 's', 'c' ), mov_read_stsc },
1481
{ MKTAG( 's', 't', 's', 'd' ), mov_read_stsd }, /* sample description */
1482
{ MKTAG( 's', 't', 's', 'h' ), mov_read_default },
1483
{ MKTAG( 's', 't', 's', 's' ), mov_read_stss }, /* sync sample */
1484
{ MKTAG( 's', 't', 's', 'z' ), mov_read_stsz }, /* sample size */
1485
{ MKTAG( 's', 't', 't', 's' ), mov_read_stts },
1486
{ MKTAG( 't', 'k', 'h', 'd' ), mov_read_tkhd }, /* track header */
1487
{ MKTAG( 't', 'r', 'a', 'k' ), mov_read_trak },
1488
{ MKTAG( 't', 'r', 'e', 'f' ), mov_read_default }, /* not really */
1489
{ MKTAG( 'u', 'd', 't', 'a' ), mov_read_leaf },
1490
{ MKTAG( 'u', 'r', 'l', ' ' ), mov_read_leaf },
1491
{ MKTAG( 'u', 'r', 'n', ' ' ), mov_read_leaf },
1492
{ MKTAG( 'u', 'u', 'i', 'd' ), mov_read_default },
1493
{ MKTAG( 'v', 'm', 'h', 'd' ), mov_read_leaf }, /* video media info header */
1494
{ MKTAG( 'w', 'a', 'v', 'e' ), mov_read_default },
1495
/* extra mp4 */
1496
{ MKTAG( 'M', 'D', 'E', 'S' ), mov_read_leaf },
1497
/* QT atoms */
1498
{ MKTAG( 'c', 'h', 'a', 'p' ), mov_read_leaf },
1499
{ MKTAG( 'c', 'l', 'i', 'p' ), mov_read_default },
1500
{ MKTAG( 'c', 'r', 'g', 'n' ), mov_read_leaf },
1501
{ MKTAG( 'c', 't', 'a', 'b' ), mov_read_ctab },
1502
{ MKTAG( 'e', 's', 'd', 's' ), mov_read_esds },
1503
{ MKTAG( 'k', 'm', 'a', 't' ), mov_read_leaf },
1504
{ MKTAG( 'm', 'a', 't', 't' ), mov_read_default },
1505
{ MKTAG( 'r', 'd', 'r', 'f' ), mov_read_leaf },
1506
{ MKTAG( 'r', 'm', 'd', 'a' ), mov_read_default },
1507
{ MKTAG( 'r', 'm', 'd', 'r' ), mov_read_leaf },
1508
{ MKTAG( 'r', 'm', 'r', 'a' ), mov_read_default },
1509
{ MKTAG( 's', 'c', 'p', 't' ), mov_read_leaf },
1510
{ MKTAG( 's', 's', 'r', 'c' ), mov_read_leaf },
1511
{ MKTAG( 's', 'y', 'n', 'c' ), mov_read_leaf },
1512
{ MKTAG( 't', 'c', 'm', 'd' ), mov_read_leaf },
1513
{ MKTAG( 'w', 'i', 'd', 'e' ), mov_read_wide }, /* place holder */
1514
//{ MKTAG( 'r', 'm', 'q', 'u' ), mov_read_leaf },
1515
#ifdef CONFIG_ZLIB
1516
{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_cmov },
1517
#else
1518
{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_leaf },
1519
#endif
1520
{ 0L, mov_read_leaf }
1521
};
1522

    
1523
static void mov_free_stream_context(MOVStreamContext *sc)
1524
{
1525
    if(sc) {
1526
        av_free(sc->chunk_offsets);
1527
        av_free(sc->sample_to_chunk);
1528
        av_free(sc->sample_sizes);
1529
        av_free(sc->keyframes);
1530
        av_free(sc->header_data);
1531
        av_free(sc->stts_data);        
1532
        av_free(sc);
1533
    }
1534
}
1535

    
1536
static inline uint32_t mov_to_tag(uint8_t *buf)
1537
{
1538
    return MKTAG(buf[0], buf[1], buf[2], buf[3]);
1539
}
1540

    
1541
static inline uint32_t to_be32(uint8_t *buf)
1542
{
1543
    return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
1544
}
1545

    
1546
/* XXX: is it sufficient ? */
1547
static int mov_probe(AVProbeData *p)
1548
{
1549
    unsigned int offset;
1550
    uint32_t tag;
1551

    
1552
    /* check file header */
1553
    if (p->buf_size <= 12)
1554
        return 0;
1555
    offset = 0;
1556
    for(;;) {
1557
        /* ignore invalid offset */
1558
        if ((offset + 8) > (unsigned int)p->buf_size)
1559
            return 0;
1560
        tag = mov_to_tag(p->buf + offset + 4);
1561
        switch(tag) {
1562
        case MKTAG( 'm', 'o', 'o', 'v' ):
1563
        case MKTAG( 'w', 'i', 'd', 'e' ):
1564
        case MKTAG( 'f', 'r', 'e', 'e' ):
1565
        case MKTAG( 'm', 'd', 'a', 't' ):
1566
        case MKTAG( 'p', 'n', 'o', 't' ): /* detect movs with preview pics like ew.mov and april.mov */
1567
        case MKTAG( 'u', 'd', 't', 'a' ): /* Packet Video PVAuthor adds this and a lot of more junk */
1568
            return AVPROBE_SCORE_MAX;
1569
        case MKTAG( 'f', 't', 'y', 'p' ):
1570
        case MKTAG( 's', 'k', 'i', 'p' ):
1571
            offset = to_be32(p->buf+offset) + offset;
1572
            break;
1573
        default:
1574
            /* unrecognized tag */
1575
            return 0;
1576
        }
1577
    }
1578
    return 0;
1579
}
1580

    
1581
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1582
{
1583
    MOVContext *mov = (MOVContext *) s->priv_data;
1584
    ByteIOContext *pb = &s->pb;
1585
    int i, j, nb, err;
1586
    MOV_atom_t atom = { 0, 0, 0 };
1587

    
1588
    mov->fc = s;
1589
    mov->parse_table = mov_default_parse_table;
1590
#if 0
1591
    /* XXX: I think we should auto detect */
1592
    if(s->iformat->name[1] == 'p')
1593
        mov->mp4 = 1;
1594
#endif
1595
    if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1596
        atom.size = url_filesize(url_fileno(pb));
1597
    else
1598
        atom.size = 0x7FFFFFFFFFFFFFFFLL;
1599

    
1600
#ifdef DEBUG
1601
    av_log(NULL, AV_LOG_DEBUG, "filesz=%Ld\n", atom.size);
1602
#endif
1603

    
1604
    /* check MOV header */
1605
    err = mov_read_default(mov, pb, atom);
1606
    if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
1607
        av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%lld\n",
1608
                err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1609
        return -1;
1610
    }
1611
#ifdef DEBUG
1612
    av_log(NULL, AV_LOG_DEBUG, "on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1613
#endif
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->next_chunk_offset = mov->mdat_offset; /* initialise reading */
1619

    
1620
#ifdef DEBUG
1621
    av_log(NULL, AV_LOG_DEBUG, "mdat_reset_offset=%d\n", (int) url_ftell(pb));
1622
#endif
1623

    
1624
#ifdef DEBUG
1625
    av_log(NULL, AV_LOG_DEBUG, "streams= %d\n", s->nb_streams);
1626
#endif
1627
    mov->total_streams = nb = s->nb_streams;
1628

    
1629
#if 1
1630
    for(i=0; i<s->nb_streams;) {
1631
        if(s->streams[i]->codec.codec_type == CODEC_TYPE_MOV_OTHER) {/* not audio, not video, delete */
1632
            av_free(s->streams[i]);
1633
            for(j=i+1; j<s->nb_streams; j++)
1634
                s->streams[j-1] = s->streams[j];
1635
            s->nb_streams--;
1636
        } else
1637
            i++;
1638
    }
1639
    for(i=0; i<s->nb_streams;i++) {
1640
        MOVStreamContext *sc;
1641
        sc = (MOVStreamContext *)s->streams[i]->priv_data;
1642
        sc->ffindex = i;
1643
        sc->is_ff_stream = 1;
1644
    }
1645
#endif
1646
#ifdef DEBUG
1647
    av_log(NULL, AV_LOG_DEBUG, "real streams= %d\n", s->nb_streams);
1648
#endif
1649
    return 0;
1650
}
1651

    
1652
/* Yes, this is ugly... I didn't write the specs of QT :p */
1653
/* XXX:remove useless commented code sometime */
1654
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1655
{
1656
    MOVContext *mov = (MOVContext *) s->priv_data;
1657
    MOVStreamContext *sc;
1658
    int64_t offset = 0x0FFFFFFFFFFFFFFFLL;
1659
    int i, a, b, m;
1660
    int size;
1661
    size = 0x0FFFFFFF;
1662

    
1663
#ifdef MOV_SPLIT_CHUNKS
1664
    if (mov->partial) {
1665

    
1666
        int idx;
1667

    
1668
        sc = mov->partial;
1669
        idx = sc->sample_to_chunk_index;
1670

    
1671
        if (idx < 0) return 0;
1672
        size = sc->sample_sizes[sc->current_sample];
1673

    
1674
        sc->current_sample++;
1675
        sc->left_in_chunk--;
1676

    
1677
        if (sc->left_in_chunk <= 0)
1678
            mov->partial = 0;
1679
        offset = mov->next_chunk_offset;
1680
        /* extract the sample */
1681

    
1682
        goto readchunk;
1683
    }
1684
#endif
1685

    
1686
again:
1687
    sc = 0;
1688
    for(i=0; i<mov->total_streams; i++) {
1689
        MOVStreamContext *msc = mov->streams[i];
1690
        //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));
1691
        if ((msc->next_chunk < msc->chunk_count) && msc->next_chunk >= 0
1692
           && (msc->chunk_offsets[msc->next_chunk] < offset)) {
1693
            sc = msc;
1694
            offset = msc->chunk_offsets[msc->next_chunk];
1695
            //av_log(NULL, AV_LOG_DEBUG, "SELETED  %Ld  i:%d\n", offset, i);
1696
        }
1697
    }
1698
    if (!sc || offset==0x0FFFFFFFFFFFFFFFLL)
1699
        return -1;
1700

    
1701
    sc->next_chunk++;
1702

    
1703
    if(mov->next_chunk_offset < offset) { /* some meta data */
1704
        url_fskip(&s->pb, (offset - mov->next_chunk_offset));
1705
        mov->next_chunk_offset = offset;
1706
    }
1707

    
1708
//av_log(NULL, AV_LOG_DEBUG, "chunk: [%i] %lli -> %lli\n", st_id, mov->next_chunk_offset, offset);
1709
    if(!sc->is_ff_stream) {
1710
        url_fskip(&s->pb, (offset - mov->next_chunk_offset));
1711
        mov->next_chunk_offset = offset;
1712
        offset = 0x0FFFFFFFFFFFFFFFLL;
1713
        goto again;
1714
    }
1715

    
1716
    /* now get the chunk size... */
1717

    
1718
    for(i=0; i<mov->total_streams; i++) {
1719
        MOVStreamContext *msc = mov->streams[i];
1720
        if ((msc->next_chunk < msc->chunk_count)
1721
            && ((msc->chunk_offsets[msc->next_chunk] - offset) < size))
1722
            size = msc->chunk_offsets[msc->next_chunk] - offset;
1723
    }
1724

    
1725
#ifdef MOV_MINOLTA_FIX
1726
    //Make sure that size is according to sample_size (Needed by .mov files 
1727
    //created on a Minolta Dimage Xi where audio chunks contains waste data in the end)
1728
    //Maybe we should really not only check sc->sample_size, but also sc->sample_sizes
1729
    //but I have no such movies
1730
    if (sc->sample_size > 0) { 
1731
        int foundsize=0;
1732
        for(i=0; i<(sc->sample_to_chunk_sz); i++) {
1733
            if( (sc->sample_to_chunk[i].first)<=(sc->next_chunk) && (sc->sample_size>0) )
1734
            {
1735
                // I can't figure out why for PCM audio sample_size is always 1
1736
                // (it should actually be channels*bits_per_second/8) but it is.
1737
                AVCodecContext* cod = &s->streams[sc->ffindex]->codec;
1738
                if (sc->sample_size == 1 && (cod->codec_id == CODEC_ID_PCM_S16BE || cod->codec_id == CODEC_ID_PCM_S16LE))
1739
                    foundsize=(sc->sample_to_chunk[i].count*cod->channels*cod->bits_per_sample)/8;
1740
                else
1741
                    foundsize=sc->sample_to_chunk[i].count*sc->sample_size;
1742
            }
1743
#ifdef DEBUG
1744
            /*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);*/
1745
#endif
1746
        }
1747
        if( (foundsize>0) && (foundsize<size) )
1748
        {
1749
#ifdef DEBUG
1750
            /*av_log(NULL, AV_LOG_DEBUG, "this size should actually be %d\n",foundsize);*/
1751
#endif
1752
            size=foundsize;
1753
        }
1754
    }
1755
#endif //MOV_MINOLTA_FIX
1756

    
1757
#ifdef MOV_SPLIT_CHUNKS
1758
    /* split chunks into samples */
1759
    if (sc->sample_size == 0) {
1760
        int idx = sc->sample_to_chunk_index;
1761
        if ((idx + 1 < sc->sample_to_chunk_sz)
1762
            && (sc->next_chunk >= sc->sample_to_chunk[idx + 1].first))
1763
           idx++;
1764
        sc->sample_to_chunk_index = idx;
1765
        if (idx >= 0 && sc->sample_to_chunk[idx].count != 1) {
1766
            mov->partial = sc;
1767
            /* we'll have to get those samples before next chunk */
1768
            sc->left_in_chunk = sc->sample_to_chunk[idx].count - 1;
1769
            size = sc->sample_sizes[sc->current_sample];
1770
        }
1771

    
1772
        sc->current_sample++;
1773
    }
1774
#endif
1775

    
1776
readchunk:
1777
//av_log(NULL, AV_LOG_DEBUG, "chunk: [%i] %lli -> %lli (%i)\n", st_id, offset, offset + size, size);
1778
    if(size == 0x0FFFFFFF)
1779
        size = mov->mdat_size + mov->mdat_offset - offset;
1780
    if(size < 0)
1781
        return -1;
1782
    if(size == 0)
1783
        return -1;
1784
    url_fseek(&s->pb, offset, SEEK_SET);
1785

    
1786
    //av_log(NULL, AV_LOG_DEBUG, "READCHUNK hlen: %d  %d off: %Ld   pos:%Ld\n", size, sc->header_len, offset, url_ftell(&s->pb));
1787
    if (sc->header_len > 0) {
1788
        av_new_packet(pkt, size + sc->header_len);
1789
        memcpy(pkt->data, sc->header_data, sc->header_len);
1790
        get_buffer(&s->pb, pkt->data + sc->header_len, size);
1791
        /* free header */
1792
        av_freep(&sc->header_data);
1793
        sc->header_len = 0;
1794
    } else {
1795
        av_new_packet(pkt, size);
1796
        get_buffer(&s->pb, pkt->data, pkt->size);
1797
    }
1798
    pkt->stream_index = sc->ffindex;
1799
    
1800
    // If the keyframes table exists, mark any samples that are in the table as key frames.
1801
    // If no table exists, treat very sample as a key frame.
1802
    if (sc->keyframes) {        
1803
        a = 0;
1804
        b = sc->keyframe_count - 1;
1805
        
1806
        while (a < b) {
1807
            m = (a + b + 1) >> 1;
1808
            if (sc->keyframes[m] > sc->current_sample) {
1809
                b = m - 1;
1810
            } else {
1811
                a = m;
1812
            }    
1813
        }
1814
        
1815
        if (sc->keyframes[a] == sc->current_sample)
1816
            pkt->flags |= PKT_FLAG_KEY;
1817
    }
1818
    else
1819
        pkt->flags |= PKT_FLAG_KEY;
1820

    
1821
#ifdef DEBUG
1822
/*
1823
    av_log(NULL, AV_LOG_DEBUG, "Packet (%d, %d, %ld) ", pkt->stream_index, st_id, pkt->size);
1824
    for(i=0; i<8; i++)
1825
        av_log(NULL, AV_LOG_DEBUG, "%02x ", pkt->data[i]);
1826
    for(i=0; i<8; i++)
1827
        av_log(NULL, AV_LOG_DEBUG, "%c ", (pkt->data[i]) & 0x7F);
1828
    puts("");
1829
*/
1830
#endif
1831

    
1832
    mov->next_chunk_offset = offset + size;
1833

    
1834
    return 0;
1835
}
1836

    
1837
#if defined(MOV_SPLIT_CHUNKS) && defined(MOV_SEEK)
1838
/**
1839
 * Seek method based on the one described in the Appendix C of QTFileFormat.pdf
1840
 */
1841
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp)
1842
{
1843
    MOVContext* mov = (MOVContext *) s->priv_data;
1844
    MOVStreamContext* sc;
1845
    int32_t i, a, b, m;
1846
    int64_t sample_time;
1847
    int64_t start_time;
1848
    int32_t seek_sample, sample;
1849
    int32_t duration;
1850
    int32_t count;
1851
    int32_t chunk;
1852
    int32_t left_in_chunk;
1853
    int64_t chunk_file_offset;
1854
    int64_t sample_file_offset;
1855
    int32_t first_chunk_sample;
1856
    int32_t sample_to_chunk_idx;
1857
    int mov_idx;
1858

    
1859
    // Find the corresponding mov stream
1860
    for (mov_idx = 0; mov_idx < mov->total_streams; mov_idx++)
1861
        if (mov->streams[mov_idx]->ffindex == stream_index)
1862
            break;
1863
    if (mov_idx == mov->total_streams) {
1864
        av_log(s, AV_LOG_ERROR, "mov: requested stream was not found in mov streams (idx=%i)\n", stream_index);
1865
        return -1;
1866
    }
1867
    sc = mov->streams[mov_idx];
1868

    
1869
    // Step 1. Find the edit that contains the requested time (elst)
1870
    if (sc->edit_count) {
1871
        // FIXME should handle edit list
1872
        av_log(s, AV_LOG_ERROR, "mov: does not handle seeking in files that contain edit list (c:%d)\n", sc->edit_count);
1873
        return -1;
1874
    }
1875

    
1876
    // Step 2. Find the corresponding sample using the Time-to-sample atom (stts) */
1877
#ifdef DEBUG
1878
  av_log(s, AV_LOG_DEBUG, "Searching for time %li in stream #%i (time_scale=%i)\n", (long)timestamp, mov_idx, sc->time_scale);
1879
#endif
1880
    // convert timestamp from time_base unit to timescale unit
1881
    sample_time = av_rescale( timestamp,
1882
                            (int64_t)sc->time_scale * s->streams[stream_index]->time_base.num,
1883
                            (int64_t)s->streams[stream_index]->time_base.den);
1884
    start_time = 0; // FIXME use elst atom
1885
    sample = 1; // sample are 0 based in table
1886
#ifdef DEBUG
1887
    av_log(s, AV_LOG_DEBUG, "Searching for sample_time %li \n", (long)sample_time);
1888
#endif
1889
    for (i = 0; i < sc->stts_count; i++) {
1890
        count = (uint32_t)(sc->stts_data[i]>>32);
1891
        duration = (uint32_t)(sc->stts_data[i]&0xffff);
1892
//av_log(s, AV_LOG_DEBUG, "> sample_time %lli \n", (long)sample_time);                
1893
//av_log(s, AV_LOG_DEBUG, "> count=%i duration=%i\n", count, duration);        
1894
        if ((start_time + count*duration) > sample_time) {
1895
            sample += (sample_time - start_time) / duration;
1896
            break;
1897
        }
1898
        sample += count;
1899
        start_time += count * duration;
1900
    }   
1901
    /* NOTE: despite what qt doc say, the dt value (Display Time in qt vocabulary) computed with the stts atom
1902
       is a decoding time stamp (dts) not a presentation time stamp. And as usual dts != pts for stream with b frames */
1903

    
1904
#ifdef DEBUG
1905
    av_log(s, AV_LOG_DEBUG, "Found time %li at sample #%u\n", (long)sample_time, sample);
1906
#endif
1907
    if (sample > sc->sample_count) {
1908
        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);
1909
        return -1;
1910
    }
1911

    
1912
    // Step 3. Find the prior sync. sample using the Sync sample atom (stss)
1913
    if (sc->keyframes) {
1914
        a = 0;
1915
        b = sc->keyframe_count - 1;
1916
        while (a < b) {
1917
            m = (a + b + 1) >> 1;
1918
            if (sc->keyframes[m] > sample) {
1919
                b = m - 1;
1920
            } else {
1921
                a = m;
1922
            }
1923
#ifdef DEBUG
1924
         // 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);
1925
#endif
1926
        }
1927
        seek_sample = sc->keyframes[a];
1928
    }
1929
    else
1930
        seek_sample = sample; // else all samples are key frames
1931
#ifdef DEBUG
1932
    av_log(s, AV_LOG_DEBUG, "Found nearest keyframe at sample #%i \n", seek_sample);
1933
#endif
1934

    
1935
    // Step 4. Find the chunk of the sample using the Sample-to-chunk-atom (stsc)
1936
    for (first_chunk_sample = 1, i = 0; i < (sc->sample_to_chunk_sz - 1); i++) {
1937
        b = (sc->sample_to_chunk[i + 1].first - sc->sample_to_chunk[i].first) * sc->sample_to_chunk[i].count;
1938
        if (seek_sample >= first_chunk_sample && seek_sample < (first_chunk_sample + b))
1939
            break;
1940
        first_chunk_sample += b;
1941
    }
1942
    chunk = sc->sample_to_chunk[i].first + (seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count;
1943
    left_in_chunk = sc->sample_to_chunk[i].count - (seek_sample - first_chunk_sample) % sc->sample_to_chunk[i].count;
1944
    first_chunk_sample += ((seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count) * sc->sample_to_chunk[i].count;
1945
    sample_to_chunk_idx = i;
1946
#ifdef DEBUG
1947
    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);
1948
#endif
1949

    
1950
    // Step 5. Find the offset of the chunk using the chunk offset atom
1951
    if (!sc->chunk_offsets) {
1952
        av_log(s, AV_LOG_ERROR, "mov: no chunk offset atom, unable to seek\n");
1953
        return -1;
1954
    }
1955
    if (chunk > sc->chunk_count) {
1956
        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);
1957
        return -1;
1958
    }
1959
    chunk_file_offset = sc->chunk_offsets[chunk - 1];
1960
#ifdef DEBUG
1961
    av_log(s, AV_LOG_DEBUG, "Chunk file offset is #%llu \n", chunk_file_offset);
1962
#endif
1963

    
1964
    // Step 6. Find the byte offset within the chunk using the sample size atom
1965
    sample_file_offset = chunk_file_offset;
1966
    if (sc->sample_size)
1967
        sample_file_offset += (seek_sample - first_chunk_sample) * sc->sample_size;
1968
    else {
1969
        for (i = 0; i < (seek_sample - first_chunk_sample); i++) {
1970
        sample_file_offset += sc->sample_sizes[first_chunk_sample + i - 1];
1971
        }
1972
    }
1973
#ifdef DEBUG
1974
    av_log(s, AV_LOG_DEBUG, "Sample file offset is #%llu \n", sample_file_offset);
1975
#endif
1976

    
1977
    // Step 6. Update the parser
1978
    mov->partial = sc;
1979
    mov->next_chunk_offset = sample_file_offset;
1980
    // Update current stream state
1981
    sc->current_sample = seek_sample - 1;  // zero based
1982
    sc->left_in_chunk = left_in_chunk;
1983
    sc->next_chunk = chunk; // +1 -1 (zero based)
1984
    sc->sample_to_chunk_index = sample_to_chunk_idx;
1985

    
1986
    // Update other streams    
1987
    for (i = 0; i<mov->total_streams; i++) {
1988
        MOVStreamContext *msc;
1989
        if (i == mov_idx) continue;
1990
        // Find the nearest 'next' chunk
1991
        msc = mov->streams[i];
1992
        a = 0;
1993
        b = msc->chunk_count - 1;
1994
        while (a < b) {
1995
            m = (a + b + 1) >> 1;
1996
            if (msc->chunk_offsets[m] > chunk_file_offset) {
1997
                b = m - 1;
1998
            } else {
1999
                a = m;
2000
            }
2001
#ifdef DEBUG            
2002
/*            av_log(s, AV_LOG_DEBUG, "a=%i (%li) b=%i (%li) m=%i (%li) stream #%i\n"
2003
            , a, (long)msc->chunk_offsets[a], b, (long)msc->chunk_offsets[b], m, (long)msc->chunk_offsets[m],  i); */
2004
#endif                  
2005
        }
2006
        msc->next_chunk = a;
2007
        if (msc->chunk_offsets[a] < chunk_file_offset && a < (msc->chunk_count-1))
2008
            msc->next_chunk ++;
2009
#ifdef DEBUG        
2010
        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]);
2011
#endif        
2012
        // Compute sample count and index in the sample_to_chunk table (what a pity)
2013
        msc->sample_to_chunk_index = 0;
2014
        msc->current_sample = 0;
2015
        for(;  msc->sample_to_chunk_index < (msc->sample_to_chunk_sz - 1)
2016
            && msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first <= (1 + msc->next_chunk); msc->sample_to_chunk_index++) {
2017
            msc->current_sample += (msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first - msc->sample_to_chunk[msc->sample_to_chunk_index].first) \
2018
            * msc->sample_to_chunk[msc->sample_to_chunk_index].count;
2019
        }
2020
        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;
2021
        msc->left_in_chunk = msc->sample_to_chunk[msc->sample_to_chunk_index].count - 1;
2022
#ifdef DEBUG        
2023
        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);
2024
#endif        
2025
    }                
2026
    return 0;
2027
}
2028
#endif
2029

    
2030
static int mov_read_close(AVFormatContext *s)
2031
{
2032
    int i;
2033
    MOVContext *mov = (MOVContext *) s->priv_data;
2034
    for(i=0; i<mov->total_streams; i++)
2035
        mov_free_stream_context(mov->streams[i]);
2036
    /* free color tabs */
2037
    for(i=0; i<mov->ctab_size; i++)
2038
        av_freep(&mov->ctab[i]);
2039
    av_freep(&mov->ctab);
2040
    return 0;
2041
}
2042

    
2043
static AVInputFormat mov_iformat = {
2044
    "mov,mp4,m4a,3gp",
2045
    "QuickTime/MPEG4 format",
2046
    sizeof(MOVContext),
2047
    mov_probe,
2048
    mov_read_header,
2049
    mov_read_packet,
2050
    mov_read_close,
2051
#if defined(MOV_SPLIT_CHUNKS) && defined(MOV_SEEK)
2052
    mov_read_seek,
2053
#endif    
2054
};
2055

    
2056
int mov_init(void)
2057
{
2058
    av_register_input_format(&mov_iformat);
2059
    return 0;
2060
}