Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 9ed83b0a

History | View | Annotate | Download (46.5 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
#include "avformat.h"
20
#include "avi.h"
21

    
22
#ifdef CONFIG_ZLIB
23
#include <zlib.h>
24
#endif
25

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

    
52
//#define DEBUG
53
#ifdef DEBUG
54
#include <stdio.h>
55
#include <fcntl.h>
56
#endif
57

    
58
/* allows chunk splitting - should work now... */
59
/* in case you can't read a file, try commenting */
60
#define MOV_SPLIT_CHUNKS
61

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

    
67
static const CodecTag mov_video_tags[] = {
68
/*  { CODEC_ID_, MKTAG('c', 'v', 'i', 'd') }, *//* Cinepak */
69
/*  { CODEC_ID_H263, MKTAG('r', 'a', 'w', ' ') }, *//* Uncompressed RGB */
70
/*  { CODEC_ID_H263, MKTAG('Y', 'u', 'v', '2') }, *//* Uncompressed YUV422 */
71
/*    { CODEC_ID_RAWVIDEO, MKTAG('A', 'V', 'U', 'I') }, *//* YUV with alpha-channel (AVID Uncompressed) */
72
/* Graphics */
73
/* Animation */
74
/* Apple video */
75
/* Kodak Photo CD */
76
    { CODEC_ID_MJPEG, MKTAG('j', 'p', 'e', 'g') }, /* PhotoJPEG */
77
    { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'e', 'g') }, /* MPEG */
78
    { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'a') }, /* Motion-JPEG (format A) */
79
    { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'b') }, /* Motion-JPEG (format B) */
80
    { CODEC_ID_MJPEG, MKTAG('A', 'V', 'D', 'J') }, /* MJPEG with alpha-channel (AVID JFIF meridien compressed) */
81
/*    { CODEC_ID_MJPEG, MKTAG('A', 'V', 'R', 'n') }, *//* MJPEG with alpha-channel (AVID ABVB/Truevision NuVista) */
82
/*    { CODEC_ID_GIF, MKTAG('g', 'i', 'f', ' ') }, *//* embedded gif files as frames (usually one "click to play movie" frame) */
83
/* Sorenson video */
84
    { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') }, /* Sorenson Video v1 */
85
    { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', '1') }, /* Sorenson Video v1 */
86
    { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', 'i') }, /* Sorenson Video v1 (from QT specs)*/
87
    { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') }, /* Sorenson Video v3 */
88
    { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
89
    { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', 'X') }, /* OpenDiVX *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
90
/*    { CODEC_ID_, MKTAG('I', 'V', '5', '0') }, *//* Indeo 5.0 */
91
    { CODEC_ID_H263, MKTAG('h', '2', '6', '3') }, /* H263 */
92
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
93
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
94
/*    { CODEC_ID_DVVIDEO, MKTAG('A', 'V', 'd', 'v') }, *//* AVID dv */
95
    { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') }, /* On2 VP3 */
96
    { CODEC_ID_NONE, 0 },
97
};
98

    
99
static const CodecTag mov_audio_tags[] = {
100
/*    { CODEC_ID_PCM_S16BE, MKTAG('N', 'O', 'N', 'E') }, *//* uncompressed */
101
    { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') }, /* 16 bits */
102
    /* { CODEC_ID_PCM_S8, MKTAG('t', 'w', 'o', 's') },*/ /* 8 bits */
103
    { CODEC_ID_PCM_U8, MKTAG('r', 'a', 'w', ' ') }, /* 8 bits unsigned */
104
    { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') }, /*  */
105
    { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') }, /*  */
106
    { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') }, /*  */
107
    { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') }, /* IMA-4 ADPCM */
108
    { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') }, /* Macintosh Audio Compression and Expansion 3:1 */
109
    { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') }, /* Macintosh Audio Compression and Expansion 6:1 */
110

    
111
    { CODEC_ID_MP2, MKTAG('.', 'm', 'p', '3') }, /* MPEG layer 3 */ /* sample files at http://www.3ivx.com/showcase.html use this tag */
112
    { CODEC_ID_MP2, 0x6D730055 }, /* MPEG layer 3 */
113
    { CODEC_ID_MP2, 0x5500736D }, /* MPEG layer 3 *//* XXX: check endianness */
114
/*    { CODEC_ID_OGG_VORBIS, MKTAG('O', 'g', 'g', 'S') }, *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
115
/* MP4 tags */
116
    { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') }, /* MPEG 4 AAC or audio ? */
117
    /* The standard for mpeg4 audio is still not normalised AFAIK anyway */
118
    { CODEC_ID_NONE, 0 },
119
};
120

    
121
/* the QuickTime file format is quite convoluted...
122
 * it has lots of index tables, each indexing something in another one...
123
 * Here we just use what is needed to read the chunks
124
 */
125

    
126
typedef struct MOV_sample_to_chunk_tbl {
127
    long first;
128
    long count;
129
    long id;
130
} MOV_sample_to_chunk_tbl;
131

    
132
typedef struct {
133
    uint32_t type;
134
    int64_t offset;
135
    int64_t size; /* total size (excluding the size and type fields) */
136
} MOV_atom_t;
137

    
138
typedef struct {
139
    int seed;
140
    int flags;
141
    int size;
142
    void* clrs;
143
} MOV_ctab_t;
144

    
145
typedef struct {
146
    uint8_t  version;
147
    uint32_t flags; // 24bit
148

    
149
    /* 0x03 ESDescrTag */
150
    uint16_t es_id;
151
#define MP4ODescrTag                        0x01
152
#define MP4IODescrTag                        0x02
153
#define MP4ESDescrTag                        0x03
154
#define MP4DecConfigDescrTag                0x04
155
#define MP4DecSpecificDescrTag                0x05
156
#define MP4SLConfigDescrTag                0x06
157
#define MP4ContentIdDescrTag                0x07
158
#define MP4SupplContentIdDescrTag        0x08
159
#define MP4IPIPtrDescrTag                0x09
160
#define MP4IPMPPtrDescrTag                0x0A
161
#define MP4IPMPDescrTag                        0x0B
162
#define MP4RegistrationDescrTag                0x0D
163
#define MP4ESIDIncDescrTag                0x0E
164
#define MP4ESIDRefDescrTag                0x0F
165
#define MP4FileIODescrTag                0x10
166
#define MP4FileODescrTag                0x11
167
#define MP4ExtProfileLevelDescrTag        0x13
168
#define MP4ExtDescrTagsStart                0x80
169
#define MP4ExtDescrTagsEnd                0xFE
170
    uint8_t  stream_priority;
171

    
172
    /* 0x04 DecConfigDescrTag */
173
    uint8_t  object_type_id;
174
    uint8_t  stream_type;
175
    /* XXX: really streamType is
176
     * only 6bit, followed by:
177
     * 1bit  upStream
178
     * 1bit  reserved
179
     */
180
    uint32_t buffer_size_db; // 24
181
    uint32_t max_bitrate;
182
    uint32_t avg_bitrate;
183

    
184
    /* 0x05 DecSpecificDescrTag */
185
    uint8_t  decoder_cfg_len;
186
    uint8_t *decoder_cfg;
187

    
188
    /* 0x06 SLConfigDescrTag */
189
    uint8_t  sl_config_len;
190
    uint8_t *sl_config;
191
} MOV_esds_t;
192

    
193
struct MOVParseTableEntry;
194

    
195
typedef struct MOVStreamContext {
196
    int ffindex; /* the ffmpeg stream id */
197
    int is_ff_stream; /* Is this stream presented to ffmpeg ? i.e. is this an audio or video stream ? */
198
    long next_chunk;
199
    long chunk_count;
200
    int64_t *chunk_offsets;
201
    long sample_to_chunk_sz;
202
    MOV_sample_to_chunk_tbl *sample_to_chunk;
203
    long sample_to_chunk_index;
204
    long sample_size;
205
    long sample_count;
206
    long *sample_sizes;
207
    int time_scale;
208
    long current_sample;
209
    long left_in_chunk; /* how many samples before next chunk */
210
    /* specific MPEG4 header which is added at the beginning of the stream */
211
    int header_len;
212
    uint8_t *header_data;
213
    MOV_esds_t esds;
214
} MOVStreamContext;
215

    
216
typedef struct MOVContext {
217
    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) */
218
    AVFormatContext *fc;
219
    int time_scale;
220
    int duration; /* duration of the longest track */
221
    int found_moov; /* when both 'moov' and 'mdat' sections has been found */
222
    int found_mdat; /* we suppose we have enough data to read the file */
223
    int64_t mdat_size;
224
    int64_t mdat_offset;
225
    int total_streams;
226
    /* some streams listed here aren't presented to the ffmpeg API, since they aren't either video nor audio
227
     * but we need the info to be able to skip data from those streams in the 'mdat' section
228
     */
229
    MOVStreamContext *streams[MAX_STREAMS];
230

    
231
    int64_t next_chunk_offset;
232
    MOVStreamContext *partial; /* != 0 : there is still to read in the current chunk */
233
    int ctab_size;
234
    MOV_ctab_t **ctab;           /* color tables */
235
    const struct MOVParseTableEntry *parse_table; /* could be eventually used to change the table */
236
    /* NOTE: for recursion save to/ restore from local variable! */
237
} MOVContext;
238

    
239

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

    
242
/* those functions parse an atom */
243
/* return code:
244
 1: found what I wanted, exit
245
 0: continue to parse next atom
246
 -1: error occured, exit
247
 */
248
typedef int (*mov_parse_function)(MOVContext *ctx, ByteIOContext *pb, MOV_atom_t atom);
249

    
250
/* links atom IDs to parse functions */
251
typedef struct MOVParseTableEntry {
252
    uint32_t type;
253
    mov_parse_function func;
254
} MOVParseTableEntry;
255

    
256
#ifdef DEBUG
257
/*
258
 * XXX: static sux, even more in a multithreaded environment...
259
 * Avoid them. This is here just to help debugging.
260
 */
261
static int debug_indent = 0;
262
void print_atom(const char *str, MOV_atom_t atom)
263
{
264
    unsigned int tag, i;
265
    tag = (unsigned int) atom.type;
266
    i=debug_indent;
267
    if(tag == 0) tag = MKTAG('N', 'U', 'L', 'L');
268
    while(i--)
269
        printf("|");
270
    printf("parse:");
271
    printf(" %s: tag=%c%c%c%c offset=0x%x size=0x%x\n",
272
           str, tag & 0xff,
273
           (tag >> 8) & 0xff,
274
           (tag >> 16) & 0xff,
275
           (tag >> 24) & 0xff,
276
           (unsigned int)atom.offset,
277
           (unsigned int)atom.size);
278
    assert((unsigned int)atom.size < 0x7fffffff);// catching errors
279
}
280
#else
281
#define print_atom(a,b)
282
#endif
283

    
284

    
285
static int mov_read_leaf(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
286
{
287
    print_atom("leaf", atom);
288

    
289
    if (atom.size>1)
290
        url_fskip(pb, atom.size);
291
/*        url_seek(pb, atom_offset+atom.size, SEEK_SET); */
292
    return 0;
293
}
294

    
295
static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
296
{
297
    int64_t total_size = 0;
298
    MOV_atom_t a;
299
    int i;
300
    int err = 0;
301

    
302
#ifdef DEBUG
303
    print_atom("default", atom);
304
    debug_indent++;
305
#endif
306

    
307
    a.offset = atom.offset;
308

    
309
    if (atom.size < 0)
310
        atom.size = 0x7fffffffffffffffLL;
311
    while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
312
        a.size = atom.size;
313
        a.type=0L;
314
        if(atom.size >= 8) {
315
            a.size = get_be32(pb);
316
            a.type = get_le32(pb);
317
        }
318
        total_size += 8;
319
        a.offset += 8;
320
        //printf("type: %08x  %.4s  sz: %Lx  %Lx   %Lx\n", type, (char*)&type, size, atom.size, total_size);
321
        if (a.size == 1) { /* 64 bit extended size */
322
            a.size = get_be64(pb) - 8;
323
            a.offset += 8;
324
            total_size += 8;
325
        }
326
        if (a.size == 0) {
327
            a.size = atom.size - total_size;
328
            if (a.size <= 8)
329
                break;
330
        }
331
        for (i = 0; c->parse_table[i].type != 0L
332
             && c->parse_table[i].type != a.type; i++)
333
            /* empty */;
334

    
335
        a.size -= 8;
336
//        printf(" i=%ld\n", i);
337
        if (c->parse_table[i].type == 0) { /* skip leaf atoms data */
338
//            url_seek(pb, atom.offset+atom.size, SEEK_SET);
339
#ifdef DEBUG
340
            print_atom("unknown", a);
341
#endif
342
            url_fskip(pb, a.size);
343
        } else {
344
#ifdef DEBUG
345
            //char b[5] = { type & 0xff, (type >> 8) & 0xff, (type >> 16) & 0xff, (type >> 24) & 0xff, 0 };
346
            //print_atom(b, type, offset, size);
347
#endif
348
            err = (c->parse_table[i].func)(c, pb, a);
349
        }
350

    
351
        a.offset += a.size;
352
        total_size += a.size;
353
    }
354

    
355
    if (!err && total_size < atom.size && atom.size < 0x7ffff) {
356
        //printf("RESET  %Ld  %Ld  err:%d\n", atom.size, total_size, err);
357
        url_fskip(pb, atom.size - total_size);
358
    }
359

    
360
#ifdef DEBUG
361
    debug_indent--;
362
#endif
363
    return err;
364
}
365

    
366
static int mov_read_ctab(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
367
{
368
    unsigned int len;
369
    MOV_ctab_t *t;
370
    //url_fskip(pb, atom.size); // for now
371
    c->ctab = av_realloc(c->ctab, ++c->ctab_size);
372
    t = c->ctab[c->ctab_size];
373
    t->seed = get_be32(pb);
374
    t->flags = get_be16(pb);
375
    t->size = get_be16(pb) + 1;
376
    len = 2 * t->size * 4;
377
    if (len > 0) {
378
        t->clrs = av_malloc(len); // 16bit A R G B
379
        if (t->clrs)
380
            get_buffer(pb, t->clrs, len);
381
    }
382

    
383
    return 0;
384
}
385

    
386
static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
387
{
388
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
389
    int len = 0;
390
    uint32_t type;
391
    uint32_t ctype;
392

    
393
    print_atom("hdlr", atom);
394

    
395
    get_byte(pb); /* version */
396
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
397

    
398
    /* component type */
399
    ctype = get_le32(pb);
400
    type = get_le32(pb); /* component subtype */
401

    
402
#ifdef DEBUG
403
    printf("ctype= %c%c%c%c (0x%08lx)\n", *((char *)&ctype), ((char *)&ctype)[1], ((char *)&ctype)[2], ((char *)&ctype)[3], (long) ctype);
404
    printf("stype= %c%c%c%c\n", *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
405
#endif
406
#ifdef DEBUG
407
/* XXX: yeah this is ugly... */
408
    if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
409
        if(type == MKTAG('v', 'i', 'd', 'e'))
410
            puts("hdlr: vide");
411
        else if(type == MKTAG('s', 'o', 'u', 'n'))
412
            puts("hdlr: soun");
413
    } else if(ctype == 0) { /* MP4 */
414
        if(type == MKTAG('v', 'i', 'd', 'e'))
415
            puts("hdlr: vide");
416
        else if(type == MKTAG('s', 'o', 'u', 'n'))
417
            puts("hdlr: soun");
418
        else if(type == MKTAG('o', 'd', 's', 'm'))
419
            puts("hdlr: odsm");
420
        else if(type == MKTAG('s', 'd', 's', 'm'))
421
            puts("hdlr: sdsm");
422
    } else puts("hdlr: meta");
423
#endif
424

    
425
    if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
426
        /* helps parsing the string hereafter... */
427
        c->mp4 = 0;
428
        if(type == MKTAG('v', 'i', 'd', 'e'))
429
            st->codec.codec_type = CODEC_TYPE_VIDEO;
430
        else if(type == MKTAG('s', 'o', 'u', 'n'))
431
            st->codec.codec_type = CODEC_TYPE_AUDIO;
432
    } else if(ctype == 0) { /* MP4 */
433
        /* helps parsing the string hereafter... */
434
        c->mp4 = 1;
435
        if(type == MKTAG('v', 'i', 'd', 'e'))
436
            st->codec.codec_type = CODEC_TYPE_VIDEO;
437
        else if(type == MKTAG('s', 'o', 'u', 'n'))
438
            st->codec.codec_type = CODEC_TYPE_AUDIO;
439
    }
440
    get_be32(pb); /* component  manufacture */
441
    get_be32(pb); /* component flags */
442
    get_be32(pb); /* component flags mask */
443

    
444
    if(atom.size <= 24)
445
        return 0; /* nothing left to read */
446
    /* XXX: MP4 uses a C string, not a pascal one */
447
    /* component name */
448

    
449
    if(c->mp4) {
450
        /* .mp4: C string */
451
        while(get_byte(pb) && (++len < (atom.size - 24)));
452
    } else {
453
        /* .mov: PASCAL string */
454
#ifdef DEBUG
455
        char* buf;
456
#endif
457
        len = get_byte(pb);
458
#ifdef DEBUG
459
        buf = (uint8_t*) av_malloc(len+1);
460
        if (buf) {
461
            get_buffer(pb, buf, len);
462
            buf[len] = '\0';
463
            printf("**buf='%s'\n", buf);
464
            av_free(buf);
465
        } else
466
#endif
467
            url_fskip(pb, len);
468
    }
469

    
470
    return 0;
471
}
472

    
473
static int mov_mp4_read_descr_len(ByteIOContext *pb)
474
{
475
    int len = 0;
476
    int count = 4;
477
    while (count--) {
478
        int c = get_byte(pb);
479
        len = (len << 7) | (c & 0x7f);
480
        if (!(c & 0x80))
481
            break;
482
    }
483
    return len;
484
}
485

    
486
static int mov_mp4_read_descr(ByteIOContext *pb, int *tag)
487
{
488
    int len;
489
    *tag = get_byte(pb);
490
    len = mov_mp4_read_descr_len(pb);
491
#ifdef DEBUG
492
    printf("MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
493
#endif
494
    return len;
495
}
496

    
497
static inline unsigned int get_be24(ByteIOContext *s)
498
{
499
    unsigned int val;
500
    val = get_byte(s) << 16;
501
    val |= get_byte(s) << 8;
502
    val |= get_byte(s);
503
    return val;
504
}
505

    
506
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
507
{
508
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
509
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
510
    int64_t start_pos = url_ftell(pb);
511
    int tag, len;
512

    
513
    print_atom("esds", atom);
514

    
515
    /* Well, broken but suffisant for some MP4 streams */
516
    get_be32(pb); /* version + flags */
517
    len = mov_mp4_read_descr(pb, &tag);
518
    if (tag == MP4ESDescrTag) {
519
        get_be16(pb); /* ID */
520
        get_byte(pb); /* priority */
521
    } else
522
        get_be16(pb); /* ID */
523

    
524
    len = mov_mp4_read_descr(pb, &tag);
525
    if (tag == MP4DecConfigDescrTag) {
526
        sc->esds.object_type_id = get_byte(pb);
527
        sc->esds.stream_type = get_byte(pb);
528
        sc->esds.buffer_size_db = get_be24(pb);
529
        sc->esds.max_bitrate = get_be32(pb);
530
        sc->esds.avg_bitrate = get_be32(pb);
531

    
532
        len = mov_mp4_read_descr(pb, &tag);
533
        //printf("LEN %d  TAG %d  m:%d a:%d\n", len, tag, sc->esds.max_bitrate, sc->esds.avg_bitrate);
534
        if (tag == MP4DecSpecificDescrTag) {
535
#ifdef DEBUG
536
            printf("Specific MPEG4 header len=%d\n", len);
537
#endif
538
            st->codec.extradata = (uint8_t*) av_mallocz(len);
539
            if (st->codec.extradata) {
540
                get_buffer(pb, st->codec.extradata, len);
541
                st->codec.extradata_size = len;
542
            }
543
        }
544
    }
545
    /* in any case, skip garbage */
546
    url_fskip(pb, atom.size - ((url_ftell(pb) - start_pos)));
547
    return 0;
548
}
549

    
550
/* this atom contains actual media data */
551
static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
552
{
553
    print_atom("mdat", atom);
554

    
555
    if(atom.size == 0) /* wrong one (MP4) */
556
        return 0;
557
    c->found_mdat=1;
558
    c->mdat_offset = atom.offset;
559
    c->mdat_size = atom.size;
560
    if(c->found_moov)
561
        return 1; /* found both, just go */
562
    url_fskip(pb, atom.size);
563
    return 0; /* now go for moov */
564
}
565

    
566
/* this atom should contain all header atoms */
567
static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
568
{
569
    int err;
570

    
571
    print_atom("moov", atom);
572

    
573
    err = mov_read_default(c, pb, atom);
574
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
575
    /* so we don't parse the whole file if over a network */
576
    c->found_moov=1;
577
    if(c->found_mdat)
578
        return 1; /* found both, just go */
579
    return 0; /* now go for mdat */
580
}
581

    
582

    
583
static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
584
{
585
    print_atom("mdhd", atom);
586

    
587
    get_byte(pb); /* version */
588

    
589
    get_byte(pb); get_byte(pb);
590
    get_byte(pb); /* flags */
591

    
592
    get_be32(pb); /* creation time */
593
    get_be32(pb); /* modification time */
594

    
595
    c->streams[c->total_streams]->time_scale = get_be32(pb);
596

    
597
#ifdef DEBUG
598
    printf("track[%i].time_scale = %i\n", c->fc->nb_streams-1, c->streams[c->total_streams]->time_scale); /* time scale */
599
#endif
600
    get_be32(pb); /* duration */
601

    
602
    get_be16(pb); /* language */
603
    get_be16(pb); /* quality */
604

    
605
    return 0;
606
}
607

    
608
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
609
{
610
    print_atom("mvhd", atom);
611

    
612
    get_byte(pb); /* version */
613
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
614

    
615
    get_be32(pb); /* creation time */
616
    get_be32(pb); /* modification time */
617
    c->time_scale = get_be32(pb); /* time scale */
618
#ifdef DEBUG
619
    printf("time scale = %i\n", c->time_scale);
620
#endif
621
    c->duration = get_be32(pb); /* duration */
622
    get_be32(pb); /* preferred scale */
623

    
624
    get_be16(pb); /* preferred volume */
625

    
626
    url_fskip(pb, 10); /* reserved */
627

    
628
    url_fskip(pb, 36); /* display matrix */
629

    
630
    get_be32(pb); /* preview time */
631
    get_be32(pb); /* preview duration */
632
    get_be32(pb); /* poster time */
633
    get_be32(pb); /* selection time */
634
    get_be32(pb); /* selection duration */
635
    get_be32(pb); /* current time */
636
    get_be32(pb); /* next track ID */
637

    
638
    return 0;
639
}
640

    
641
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
642
{
643
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
644

    
645
    // currently SVQ3 decoder expect full STSD header - so let's fake it
646
    // this should be fixed and just SMI header should be passed
647
    av_free(st->codec.extradata);
648
    st->codec.extradata_size = 0x5a + atom.size;
649
    st->codec.extradata = (uint8_t*) av_mallocz(st->codec.extradata_size);
650

    
651
    if (st->codec.extradata) {
652
        int i;
653
        strcpy(st->codec.extradata, "SVQ3"); // fake
654
        get_buffer(pb, st->codec.extradata + 0x5a, atom.size);
655
        //printf("Reading SMI %Ld  %s\n", atom.size, (char*)st->codec.extradata + 0x5a);
656
    } else
657
        url_fskip(pb, atom.size);
658

    
659
    return 0;
660
}
661

    
662
static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
663
{
664
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
665
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
666
    int entries, i;
667

    
668
    print_atom("stco", atom);
669

    
670
    get_byte(pb); /* version */
671
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
672

    
673
    entries = get_be32(pb);
674
    sc->chunk_count = entries;
675
    sc->chunk_offsets = (int64_t*) av_malloc(entries * sizeof(int64_t));
676
    if (!sc->chunk_offsets)
677
        return -1;
678
    if (atom.type == MKTAG('s', 't', 'c', 'o')) {
679
        for(i=0; i<entries; i++) {
680
            sc->chunk_offsets[i] = get_be32(pb);
681
        }
682
    } else if (atom.type == MKTAG('c', 'o', '6', '4')) {
683
        for(i=0; i<entries; i++) {
684
            sc->chunk_offsets[i] = get_be64(pb);
685
        }
686
    } else
687
        return -1;
688
#ifdef DEBUG
689
/*
690
    for(i=0; i<entries; i++) {
691
        printf("chunk offset=0x%Lx\n", sc->chunk_offsets[i]);
692
    }
693
*/
694
#endif
695
    return 0;
696
}
697

    
698
static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
699
{
700
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
701
    //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
702
    int entries, frames_per_sample;
703
    uint32_t format;
704

    
705
    print_atom("stsd", atom);
706

    
707
    get_byte(pb); /* version */
708
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
709

    
710
    entries = get_be32(pb);
711

    
712
    while(entries--) {
713
        enum CodecID id;
714
        int size = get_be32(pb); /* size */
715
        format = get_le32(pb); /* data format */
716

    
717
        get_be32(pb); /* reserved */
718
        get_be16(pb); /* reserved */
719
        get_be16(pb); /* index */
720

    
721
        /* for MPEG4: set codec type by looking for it */
722
        id = codec_get_id(mov_video_tags, format);
723
        if (id >= 0) {
724
            AVCodec *codec;
725
            codec = avcodec_find_decoder(id);
726
            if (codec)
727
                st->codec.codec_type = codec->type;
728
        }
729
#ifdef DEBUG
730
        printf("size=%d 4CC= %c%c%c%c codec_type=%d\n",
731
               size,
732
               (format >> 0) & 0xff,
733
               (format >> 8) & 0xff,
734
               (format >> 16) & 0xff,
735
               (format >> 24) & 0xff,
736
               st->codec.codec_type);
737
#endif
738
        st->codec.codec_tag = format;
739
        if(st->codec.codec_type==CODEC_TYPE_VIDEO) {
740
            MOV_atom_t a = { 0, 0, 0 };
741
            st->codec.codec_id = id;
742
            get_be16(pb); /* version */
743
            get_be16(pb); /* revision level */
744
            get_be32(pb); /* vendor */
745
            get_be32(pb); /* temporal quality */
746
            get_be32(pb); /* spacial quality */
747
            st->codec.width = get_be16(pb); /* width */
748
            st->codec.height = get_be16(pb); /* height */
749
#if 1
750
            if (st->codec.codec_id == CODEC_ID_MPEG4) {
751
                /* in some MPEG4 the width/height are not correct, so
752
                   we ignore this info */
753
                st->codec.width = 0;
754
                st->codec.height = 0;
755
            }
756
#endif
757
            get_be32(pb); /* horiz resolution */
758
            get_be32(pb); /* vert resolution */
759
            get_be32(pb); /* data size, always 0 */
760
            frames_per_sample = get_be16(pb); /* frames per samples */
761
#ifdef DEBUG
762
            printf("frames/samples = %d\n", frames_per_sample);
763
#endif
764
            get_buffer(pb, (uint8_t *)st->codec.codec_name, 32); /* codec name */
765

    
766
            st->codec.bits_per_sample = get_be16(pb); /* depth */
767
            st->codec.color_table_id = get_be16(pb); /* colortable id */
768

    
769
            st->codec.frame_rate      = 25;
770
            st->codec.frame_rate_base = 1;
771

    
772
            size -= (16+8*4+2+32+2*2);
773
#if 0
774
            while (size >= 8) {
775
                MOV_atom_t a;
776
                int64_t start_pos;
777

778
                a.size = get_be32(pb);
779
                a.type = get_le32(pb);
780
                size -= 8;
781
#ifdef DEBUG
782
                printf("VIDEO: atom_type=%c%c%c%c atom.size=%Ld size_left=%d\n",
783
                       (a.type >> 0) & 0xff,
784
                       (a.type >> 8) & 0xff,
785
                       (a.type >> 16) & 0xff,
786
                       (a.type >> 24) & 0xff,
787
                       a.size, size);
788
#endif
789
                start_pos = url_ftell(pb);
790

    
791
                switch(a.type) {
792
                case MKTAG('e', 's', 'd', 's'):
793
                    {
794
                        int tag, len;
795
                        /* Well, broken but suffisant for some MP4 streams */
796
                        get_be32(pb); /* version + flags */
797
                        len = mov_mp4_read_descr(pb, &tag);
798
                        if (tag == 0x03) {
799
                            /* MP4ESDescrTag */
800
                            get_be16(pb); /* ID */
801
                            get_byte(pb); /* priority */
802
                            len = mov_mp4_read_descr(pb, &tag);
803
                            if (tag != 0x04)
804
                                goto fail;
805
                            /* MP4DecConfigDescrTag */
806
                            get_byte(pb); /* objectTypeId */
807
                            get_be32(pb); /* streamType + buffer size */
808
                            get_be32(pb); /* max bit rate */
809
                            get_be32(pb); /* avg bit rate */
810
                            len = mp4_read_descr(pb, &tag);
811
                            if (tag != 0x05)
812
                                goto fail;
813
                            /* MP4DecSpecificDescrTag */
814
#ifdef DEBUG
815
                            printf("Specific MPEG4 header len=%d\n", len);
816
#endif
817
                            sc->header_data = av_mallocz(len);
818
                            if (sc->header_data) {
819
                                get_buffer(pb, sc->header_data, len);
820
                                sc->header_len = len;
821
                            }
822
                        }
823
                        /* in any case, skip garbage */
824
                    }
825
                    break;
826
                default:
827
                    break;
828
                }
829
            fail:
830
                printf("ATOMENEWSIZE %Ld   %d\n", atom.size, url_ftell(pb) - start_pos);
831
                if (atom.size > 8) {
832
                    url_fskip(pb, (atom.size - 8) -
833
                              ((url_ftell(pb) - start_pos)));
834
                    size -= atom.size - 8;
835
                }
836
            }
837
            if (size > 0) {
838
                /* unknown extension */
839
                url_fskip(pb, size);
840
            }
841
#else
842
            a.size = size;
843
            mov_read_default(c, pb, a);
844
#endif
845
        } else {
846
            get_be16(pb); /* version */
847
            get_be16(pb); /* revision level */
848
            get_be32(pb); /* vendor */
849

    
850
            st->codec.channels = get_be16(pb);                /* channel count */
851
            st->codec.bits_per_sample = get_be16(pb);        /* sample size */
852

    
853
            st->codec.codec_id = codec_get_id(mov_audio_tags, format);
854
            /* handle specific s8 codec */
855
            get_be16(pb); /* compression id = 0*/
856
            get_be16(pb); /* packet size = 0 */
857

    
858
            st->codec.sample_rate = ((get_be32(pb) >> 16));
859
            //printf("CODECID %d  %d  %.4s\n", st->codec.codec_id, CODEC_ID_PCM_S16BE, (char*)&format);
860

    
861
            switch (st->codec.codec_id) {
862
            case CODEC_ID_PCM_S16BE:
863
                if (st->codec.bits_per_sample == 8)
864
                    st->codec.codec_id = CODEC_ID_PCM_S8;
865
                /* fall */
866
            case CODEC_ID_PCM_U8:
867
                st->codec.bit_rate = st->codec.sample_rate * 8;
868
                break;
869
            default:
870
                ;
871
            }
872
            get_be32(pb); /* samples per packet */
873
            get_be32(pb); /* bytes per packet */
874
            get_be32(pb); /* bytes per frame */
875
            get_be32(pb); /* bytes per sample */
876

    
877
            {
878
                MOV_atom_t a = { format, url_ftell(pb), size - (16 + 20 + 16 + 8) };
879
                mov_read_default(c, pb, a);
880
            }
881
        }
882
    }
883

    
884
    return 0;
885
}
886

    
887
static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
888
{
889
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
890
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
891
    int entries, i;
892

    
893
    print_atom("stsc", atom);
894

    
895
    get_byte(pb); /* version */
896
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
897

    
898
    entries = get_be32(pb);
899
#ifdef DEBUG
900
printf("track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
901
#endif
902
    sc->sample_to_chunk_sz = entries;
903
    sc->sample_to_chunk = (MOV_sample_to_chunk_tbl*) av_malloc(entries * sizeof(MOV_sample_to_chunk_tbl));
904
    if (!sc->sample_to_chunk)
905
        return -1;
906
    for(i=0; i<entries; i++) {
907
        sc->sample_to_chunk[i].first = get_be32(pb);
908
        sc->sample_to_chunk[i].count = get_be32(pb);
909
        sc->sample_to_chunk[i].id = get_be32(pb);
910
#ifdef DEBUG
911
/*        printf("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); */
912
#endif
913
    }
914
    return 0;
915
}
916

    
917
static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
918
{
919
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
920
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
921
    int entries, i;
922

    
923
    print_atom("stsz", atom);
924

    
925
    get_byte(pb); /* version */
926
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
927

    
928
    sc->sample_size = get_be32(pb);
929
    entries = get_be32(pb);
930
    sc->sample_count = entries;
931
#ifdef DEBUG
932
    printf("sample_size = %ld sample_count = %ld\n", sc->sample_size, sc->sample_count);
933
#endif
934
    if(sc->sample_size)
935
        return 0; /* there isn't any table following */
936
    sc->sample_sizes = (long*) av_malloc(entries * sizeof(long));
937
    if (!sc->sample_sizes)
938
        return -1;
939
    for(i=0; i<entries; i++) {
940
        sc->sample_sizes[i] = get_be32(pb);
941
#ifdef DEBUG
942
/*        printf("sample_sizes[]=%ld\n", sc->sample_sizes[i]); */
943
#endif
944
    }
945
    return 0;
946
}
947

    
948
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
949
{
950
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
951
    //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
952
    int entries, i;
953

    
954
    print_atom("stts", atom);
955

    
956
    get_byte(pb); /* version */
957
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
958
    entries = get_be32(pb);
959
#ifdef DEBUG
960
printf("track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
961
#endif
962
    for(i=0; i<entries; i++) {
963
        int sample_duration;
964

    
965
        get_be32(pb);
966
        sample_duration = get_be32(pb);
967

    
968
        if (!i && st->codec.codec_type==CODEC_TYPE_VIDEO) {
969
            st->codec.frame_rate_base = sample_duration ? sample_duration : 1;
970
            st->codec.frame_rate = c->streams[c->total_streams]->time_scale;
971
#ifdef DEBUG
972
            printf("VIDEO FRAME RATE= %i (sd= %i)\n", st->codec.frame_rate, sample_duration);
973
#endif
974
        }
975
    }
976
    return 0;
977
}
978

    
979
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
980
{
981
    AVStream *st;
982
    MOVStreamContext *sc;
983

    
984
    print_atom("trak", atom);
985

    
986
    st = av_new_stream(c->fc, c->fc->nb_streams);
987
    if (!st) return -2;
988
    sc = (MOVStreamContext*) av_mallocz(sizeof(MOVStreamContext));
989
    if (!sc) {
990
        av_free(st);
991
        return -1;
992
    }
993

    
994
    sc->sample_to_chunk_index = -1;
995
    st->priv_data = sc;
996
    st->codec.codec_type = CODEC_TYPE_MOV_OTHER;
997
    st->time_length = (c->duration * 1000) / c->time_scale; // time in miliseconds
998
    c->streams[c->fc->nb_streams-1] = sc;
999

    
1000
    return mov_read_default(c, pb, atom);
1001
}
1002

    
1003
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1004
{
1005
    AVStream *st;
1006

    
1007
    print_atom("tkhd", atom);
1008

    
1009
    st = c->fc->streams[c->fc->nb_streams-1];
1010

    
1011
    get_byte(pb); /* version */
1012

    
1013
    get_byte(pb); get_byte(pb);
1014
    get_byte(pb); /* flags */
1015
    /*
1016
    MOV_TRACK_ENABLED 0x0001
1017
    MOV_TRACK_IN_MOVIE 0x0002
1018
    MOV_TRACK_IN_PREVIEW 0x0004
1019
    MOV_TRACK_IN_POSTER 0x0008
1020
    */
1021

    
1022
    get_be32(pb); /* creation time */
1023
    get_be32(pb); /* modification time */
1024
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1025
    get_be32(pb); /* reserved */
1026
    st->time_length = get_be32(pb) * 1000 / c->time_scale; /* duration */
1027
    get_be32(pb); /* reserved */
1028
    get_be32(pb); /* reserved */
1029

    
1030
    get_be16(pb); /* layer */
1031
    get_be16(pb); /* alternate group */
1032
    get_be16(pb); /* volume */
1033
    get_be16(pb); /* reserved */
1034

    
1035
    url_fskip(pb, 36); /* display matrix */
1036

    
1037
    /* those are fixed-point */
1038
    st->codec.width = get_be32(pb) >> 16; /* track width */
1039
    st->codec.height = get_be32(pb) >> 16; /* track height */
1040

    
1041
    return 0;
1042
}
1043

    
1044
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1045
/* like the files created with Adobe Premiere 5.0, for samples see */
1046
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1047
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1048
{
1049
    int err;
1050

    
1051
#ifdef DEBUG
1052
    print_atom("wide", atom);
1053
    debug_indent++;
1054
#endif
1055
    if (atom.size < 8)
1056
        return 0; /* continue */
1057
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1058
        url_fskip(pb, atom.size - 4);
1059
        return 0;
1060
    }
1061
    atom.type = get_le32(pb);
1062
    atom.offset += 8;
1063
    atom.size -= 8;
1064
    if (atom.type != MKTAG('m', 'd', 'a', 't')) {
1065
        url_fskip(pb, atom.size);
1066
        return 0;
1067
    }
1068
    err = mov_read_mdat(c, pb, atom);
1069
#ifdef DEBUG
1070
    debug_indent--;
1071
#endif
1072
    return err;
1073
}
1074

    
1075

    
1076
#ifdef CONFIG_ZLIB
1077
static int null_read_packet(void *opaque, uint8_t *buf, int buf_size)
1078
{
1079
    return -1;
1080
}
1081

    
1082
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1083
{
1084
    ByteIOContext ctx;
1085
    uint8_t *cmov_data;
1086
    uint8_t *moov_data; /* uncompressed data */
1087
    long cmov_len, moov_len;
1088
    int ret;
1089

    
1090
    print_atom("cmov", atom);
1091

    
1092
    get_be32(pb); /* dcom atom */
1093
    if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
1094
        return -1;
1095
    if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
1096
        dprintf("unknown compression for cmov atom !");
1097
        return -1;
1098
    }
1099
    get_be32(pb); /* cmvd atom */
1100
    if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
1101
        return -1;
1102
    moov_len = get_be32(pb); /* uncompressed size */
1103
    cmov_len = atom.size - 6 * 4;
1104

    
1105
    cmov_data = (uint8_t *) av_malloc(cmov_len);
1106
    if (!cmov_data)
1107
        return -1;
1108
    moov_data = (uint8_t *) av_malloc(moov_len);
1109
    if (!moov_data) {
1110
        av_free(cmov_data);
1111
        return -1;
1112
    }
1113
    get_buffer(pb, cmov_data, cmov_len);
1114
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1115
        return -1;
1116
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, null_read_packet, NULL, NULL) != 0)
1117
        return -1;
1118
    ctx.buf_end = ctx.buffer + moov_len;
1119
    atom.type = MKTAG( 'm', 'o', 'o', 'v' );
1120
    atom.offset = 0;
1121
    atom.size = moov_len;
1122
#ifdef DEBUG
1123
    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1124
#endif
1125
    ret = mov_read_default(c, &ctx, atom);
1126
    av_free(moov_data);
1127
    av_free(cmov_data);
1128

    
1129
    return ret;
1130
}
1131
#endif
1132

    
1133
static const MOVParseTableEntry mov_default_parse_table[] = {
1134
/* mp4 atoms */
1135
{ MKTAG( 'c', 'o', '6', '4' ), mov_read_stco },
1136
{ MKTAG( 'c', 'p', 'r', 't' ), mov_read_default },
1137
{ MKTAG( 'c', 'r', 'h', 'd' ), mov_read_default },
1138
{ MKTAG( 'c', 't', 't', 's' ), mov_read_leaf }, /* composition time to sample */
1139
{ MKTAG( 'd', 'i', 'n', 'f' ), mov_read_default }, /* data information */
1140
{ MKTAG( 'd', 'p', 'n', 'd' ), mov_read_leaf },
1141
{ MKTAG( 'd', 'r', 'e', 'f' ), mov_read_leaf },
1142
{ MKTAG( 'e', 'd', 't', 's' ), mov_read_default },
1143
{ MKTAG( 'e', 'l', 's', 't' ), mov_read_leaf },
1144
{ MKTAG( 'f', 'r', 'e', 'e' ), mov_read_leaf },
1145
{ MKTAG( 'h', 'd', 'l', 'r' ), mov_read_hdlr },
1146
{ MKTAG( 'h', 'i', 'n', 't' ), mov_read_leaf },
1147
{ MKTAG( 'h', 'm', 'h', 'd' ), mov_read_leaf },
1148
{ MKTAG( 'i', 'o', 'd', 's' ), mov_read_leaf },
1149
{ MKTAG( 'm', 'd', 'a', 't' ), mov_read_mdat },
1150
{ MKTAG( 'm', 'd', 'h', 'd' ), mov_read_mdhd },
1151
{ MKTAG( 'm', 'd', 'i', 'a' ), mov_read_default },
1152
{ MKTAG( 'm', 'i', 'n', 'f' ), mov_read_default },
1153
{ MKTAG( 'm', 'o', 'o', 'v' ), mov_read_moov },
1154
{ MKTAG( 'm', 'p', '4', 'a' ), mov_read_default },
1155
{ MKTAG( 'm', 'p', '4', 's' ), mov_read_default },
1156
{ MKTAG( 'm', 'p', '4', 'v' ), mov_read_default },
1157
{ MKTAG( 'm', 'p', 'o', 'd' ), mov_read_leaf },
1158
{ MKTAG( 'm', 'v', 'h', 'd' ), mov_read_mvhd },
1159
{ MKTAG( 'n', 'm', 'h', 'd' ), mov_read_leaf },
1160
{ MKTAG( 'o', 'd', 'h', 'd' ), mov_read_default },
1161
{ MKTAG( 's', 'd', 'h', 'd' ), mov_read_default },
1162
{ MKTAG( 's', 'k', 'i', 'p' ), mov_read_default },
1163
{ MKTAG( 's', 'm', 'h', 'd' ), mov_read_leaf }, /* sound media info header */
1164
{ MKTAG( 'S', 'M', 'I', ' ' ), mov_read_smi }, /* Sorrenson extension ??? */
1165
{ MKTAG( 's', 't', 'b', 'l' ), mov_read_default },
1166
{ MKTAG( 's', 't', 'c', 'o' ), mov_read_stco },
1167
{ MKTAG( 's', 't', 'd', 'p' ), mov_read_default },
1168
{ MKTAG( 's', 't', 's', 'c' ), mov_read_stsc },
1169
{ MKTAG( 's', 't', 's', 'd' ), mov_read_stsd }, /* sample description */
1170
{ MKTAG( 's', 't', 's', 'h' ), mov_read_default },
1171
{ MKTAG( 's', 't', 's', 's' ), mov_read_leaf }, /* sync sample */
1172
{ MKTAG( 's', 't', 's', 'z' ), mov_read_stsz }, /* sample size */
1173
{ MKTAG( 's', 't', 't', 's' ), mov_read_stts },
1174
{ MKTAG( 't', 'k', 'h', 'd' ), mov_read_tkhd }, /* track header */
1175
{ MKTAG( 't', 'r', 'a', 'k' ), mov_read_trak },
1176
{ MKTAG( 't', 'r', 'e', 'f' ), mov_read_default }, /* not really */
1177
{ MKTAG( 'u', 'd', 't', 'a' ), mov_read_leaf },
1178
{ MKTAG( 'u', 'r', 'l', ' ' ), mov_read_leaf },
1179
{ MKTAG( 'u', 'r', 'n', ' ' ), mov_read_leaf },
1180
{ MKTAG( 'u', 'u', 'i', 'd' ), mov_read_default },
1181
{ MKTAG( 'v', 'm', 'h', 'd' ), mov_read_leaf }, /* video media info header */
1182
{ MKTAG( 'w', 'a', 'v', 'e' ), mov_read_default },
1183
/* extra mp4 */
1184
{ MKTAG( 'M', 'D', 'E', 'S' ), mov_read_leaf },
1185
/* QT atoms */
1186
{ MKTAG( 'c', 'h', 'a', 'p' ), mov_read_leaf },
1187
{ MKTAG( 'c', 'l', 'i', 'p' ), mov_read_default },
1188
{ MKTAG( 'c', 'r', 'g', 'n' ), mov_read_leaf },
1189
{ MKTAG( 'c', 't', 'a', 'b' ), mov_read_ctab },
1190
{ MKTAG( 'e', 's', 'd', 's' ), mov_read_esds },
1191
{ MKTAG( 'k', 'm', 'a', 't' ), mov_read_leaf },
1192
{ MKTAG( 'm', 'a', 't', 't' ), mov_read_default },
1193
{ MKTAG( 'r', 'd', 'r', 'f' ), mov_read_leaf },
1194
{ MKTAG( 'r', 'm', 'd', 'a' ), mov_read_default },
1195
{ MKTAG( 'r', 'm', 'd', 'r' ), mov_read_leaf },
1196
{ MKTAG( 'r', 'm', 'r', 'a' ), mov_read_default },
1197
{ MKTAG( 's', 'c', 'p', 't' ), mov_read_leaf },
1198
{ MKTAG( 's', 's', 'r', 'c' ), mov_read_leaf },
1199
{ MKTAG( 's', 'y', 'n', 'c' ), mov_read_leaf },
1200
{ MKTAG( 't', 'c', 'm', 'd' ), mov_read_leaf },
1201
{ MKTAG( 'w', 'i', 'd', 'e' ), mov_read_wide }, /* place holder */
1202
//{ MKTAG( 'r', 'm', 'q', 'u' ), mov_read_leaf },
1203
#ifdef CONFIG_ZLIB
1204
{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_cmov },
1205
#else
1206
{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_leaf },
1207
#endif
1208
{ 0L, mov_read_leaf }
1209
};
1210

    
1211
static void mov_free_stream_context(MOVStreamContext *sc)
1212
{
1213
    if(sc) {
1214
        av_free(sc->chunk_offsets);
1215
        av_free(sc->sample_to_chunk);
1216
        av_free(sc->sample_sizes);
1217
        av_free(sc->header_data);
1218
        av_free(sc);
1219
    }
1220
}
1221

    
1222
static inline uint32_t mov_to_tag(uint8_t *buf)
1223
{
1224
    return MKTAG(buf[0], buf[1], buf[2], buf[3]);
1225
}
1226

    
1227
static inline uint32_t to_be32(uint8_t *buf)
1228
{
1229
    return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
1230
}
1231

    
1232
/* XXX: is it sufficient ? */
1233
static int mov_probe(AVProbeData *p)
1234
{
1235
    unsigned int offset;
1236
    uint32_t tag;
1237

    
1238
    /* check file header */
1239
    if (p->buf_size <= 12)
1240
        return 0;
1241
    offset = 0;
1242
    for(;;) {
1243
        /* ignore invalid offset */
1244
        if ((offset + 8) > (unsigned int)p->buf_size)
1245
            return 0;
1246
        tag = mov_to_tag(p->buf + offset + 4);
1247
        switch(tag) {
1248
        case MKTAG( 'm', 'o', 'o', 'v' ):
1249
        case MKTAG( 'w', 'i', 'd', 'e' ):
1250
        case MKTAG( 'f', 'r', 'e', 'e' ):
1251
        case MKTAG( 'm', 'd', 'a', 't' ):
1252
        case MKTAG( 'p', 'n', 'o', 't' ): /* detect movs with preview pics like ew.mov and april.mov */
1253
            return AVPROBE_SCORE_MAX;
1254
        case MKTAG( 'f', 't', 'y', 'p' ):
1255
        case MKTAG( 's', 'k', 'i', 'p' ):
1256
            offset = to_be32(p->buf) + offset;
1257
            break;
1258
        default:
1259
            /* unrecognized tag */
1260
            return 0;
1261
        }
1262
    }
1263
    return 0;
1264
}
1265

    
1266
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1267
{
1268
    MOVContext *mov = (MOVContext *) s->priv_data;
1269
    ByteIOContext *pb = &s->pb;
1270
    int i, j, nb, err;
1271
    MOV_atom_t atom = { 0, 0, 0 };
1272

    
1273
    mov->fc = s;
1274
    mov->parse_table = mov_default_parse_table;
1275
#if 0
1276
    /* XXX: I think we should auto detect */
1277
    if(s->iformat->name[1] == 'p')
1278
        mov->mp4 = 1;
1279
#endif
1280
    if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1281
        atom.size = url_filesize(url_fileno(pb));
1282
    else
1283
        atom.size = 0x7FFFFFFFFFFFFFFFLL;
1284

    
1285
#ifdef DEBUG
1286
    printf("filesz=%Ld\n", atom.size);
1287
#endif
1288

    
1289
    /* check MOV header */
1290
    err = mov_read_default(mov, pb, atom);
1291
    if(err<0 || (!mov->found_moov || !mov->found_mdat)) {
1292
        puts("header not found !!!");
1293
        exit(1);
1294
    }
1295
#ifdef DEBUG
1296
    printf("on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1297
#endif
1298
    /* some cleanup : make sure we are on the mdat atom */
1299
    if(!url_is_streamed(pb) && (url_ftell(pb) != mov->mdat_offset))
1300
        url_fseek(pb, mov->mdat_offset, SEEK_SET);
1301

    
1302
    mov->next_chunk_offset = mov->mdat_offset; /* initialise reading */
1303

    
1304
#ifdef DEBUG
1305
    printf("mdat_reset_offset=%d\n", (int) url_ftell(pb));
1306
#endif
1307

    
1308
#ifdef DEBUG
1309
    printf("streams= %d\n", s->nb_streams);
1310
#endif
1311
    mov->total_streams = nb = s->nb_streams;
1312

    
1313
#if 1
1314
    for(i=0; i<s->nb_streams;) {
1315
        if(s->streams[i]->codec.codec_type == CODEC_TYPE_MOV_OTHER) {/* not audio, not video, delete */
1316
            av_free(s->streams[i]);
1317
            for(j=i+1; j<s->nb_streams; j++)
1318
                s->streams[j-1] = s->streams[j];
1319
            s->nb_streams--;
1320
        } else
1321
            i++;
1322
    }
1323
    for(i=0; i<s->nb_streams;i++) {
1324
        MOVStreamContext *sc;
1325
        sc = (MOVStreamContext *)s->streams[i]->priv_data;
1326
        sc->ffindex = i;
1327
        sc->is_ff_stream = 1;
1328
    }
1329
#endif
1330
#ifdef DEBUG
1331
    printf("real streams= %d\n", s->nb_streams);
1332
#endif
1333
    return 0;
1334
}
1335

    
1336
/* Yes, this is ugly... I didn't write the specs of QT :p */
1337
/* XXX:remove useless commented code sometime */
1338
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1339
{
1340
    MOVContext *mov = (MOVContext *) s->priv_data;
1341
    MOVStreamContext *sc;
1342
    int64_t offset = 0x0FFFFFFFFFFFFFFFLL;
1343
    int i;
1344
    int size;
1345
    size = 0x0FFFFFFF;
1346

    
1347
#ifdef MOV_SPLIT_CHUNKS
1348
    if (mov->partial) {
1349

    
1350
        int idx;
1351

    
1352
        sc = mov->partial;
1353
        idx = sc->sample_to_chunk_index;
1354

    
1355
        if (idx < 0) return 0;
1356
        size = sc->sample_sizes[sc->current_sample];
1357

    
1358
        sc->current_sample++;
1359
        sc->left_in_chunk--;
1360

    
1361
        if (sc->left_in_chunk <= 0)
1362
            mov->partial = 0;
1363
        offset = mov->next_chunk_offset;
1364
        /* extract the sample */
1365

    
1366
        goto readchunk;
1367
    }
1368
#endif
1369

    
1370
again:
1371
    sc = 0;
1372
    for(i=0; i<mov->total_streams; i++) {
1373
        MOVStreamContext *msc = mov->streams[i];
1374
        //printf("MOCHUNK %ld  %d   %p  pos:%Ld\n", mov->streams[i]->next_chunk, mov->total_streams, mov->streams[i], url_ftell(&s->pb));
1375
        if ((msc->next_chunk < msc->chunk_count) && msc->next_chunk >= 0
1376
           && (msc->chunk_offsets[msc->next_chunk] < offset)) {
1377
            sc = msc;
1378
            offset = msc->chunk_offsets[msc->next_chunk];
1379
            //printf("SELETED  %Ld  i:%d\n", offset, i);
1380
        }
1381
    }
1382
    if (!sc || offset==0x0FFFFFFFFFFFFFFFLL)
1383
        return -1;
1384

    
1385
    sc->next_chunk++;
1386

    
1387
    if(mov->next_chunk_offset < offset) { /* some meta data */
1388
        url_fskip(&s->pb, (offset - mov->next_chunk_offset));
1389
        mov->next_chunk_offset = offset;
1390
    }
1391

    
1392
//printf("chunk: [%i] %lli -> %lli\n", st_id, mov->next_chunk_offset, offset);
1393
    if(!sc->is_ff_stream) {
1394
        url_fskip(&s->pb, (offset - mov->next_chunk_offset));
1395
        mov->next_chunk_offset = offset;
1396
        offset = 0x0FFFFFFFFFFFFFFFLL;
1397
        goto again;
1398
    }
1399

    
1400
    /* now get the chunk size... */
1401

    
1402
    for(i=0; i<mov->total_streams; i++) {
1403
        MOVStreamContext *msc = mov->streams[i];
1404
        if ((msc->next_chunk < msc->chunk_count)
1405
            && ((msc->chunk_offsets[msc->next_chunk] - offset) < size))
1406
            size = msc->chunk_offsets[msc->next_chunk] - offset;
1407
    }
1408
#ifdef MOV_SPLIT_CHUNKS
1409
    /* split chunks into samples */
1410
    if (sc->sample_size == 0) {
1411
        int idx = sc->sample_to_chunk_index;
1412
        if ((idx + 1 < sc->sample_to_chunk_sz)
1413
            && (sc->next_chunk >= sc->sample_to_chunk[idx + 1].first))
1414
           idx++;
1415
        sc->sample_to_chunk_index = idx;
1416
        if (idx >= 0 && sc->sample_to_chunk[idx].count != 1) {
1417
            mov->partial = sc;
1418
            /* we'll have to get those samples before next chunk */
1419
            sc->left_in_chunk = sc->sample_to_chunk[idx].count - 1;
1420
            size = sc->sample_sizes[sc->current_sample];
1421
        }
1422

    
1423
        sc->current_sample++;
1424
    }
1425
#endif
1426

    
1427
readchunk:
1428
//printf("chunk: [%i] %lli -> %lli (%i)\n", st_id, offset, offset + size, size);
1429
    if(size == 0x0FFFFFFF)
1430
        size = mov->mdat_size + mov->mdat_offset - offset;
1431
    if(size < 0)
1432
        return -1;
1433
    if(size == 0)
1434
        return -1;
1435
    url_fseek(&s->pb, offset, SEEK_SET);
1436

    
1437
    //printf("READCHUNK hlen: %d  %d off: %Ld   pos:%Ld\n", size, sc->header_len, offset, url_ftell(&s->pb));
1438
    if (sc->header_len > 0) {
1439
        av_new_packet(pkt, size + sc->header_len);
1440
        memcpy(pkt->data, sc->header_data, sc->header_len);
1441
        get_buffer(&s->pb, pkt->data + sc->header_len, size);
1442
        /* free header */
1443
        av_freep(&sc->header_data);
1444
        sc->header_len = 0;
1445
    } else {
1446
        av_new_packet(pkt, size);
1447
        get_buffer(&s->pb, pkt->data, pkt->size);
1448
    }
1449
    pkt->stream_index = sc->ffindex;
1450

    
1451
#ifdef DEBUG
1452
/*
1453
    printf("Packet (%d, %d, %ld) ", pkt->stream_index, st_id, pkt->size);
1454
    for(i=0; i<8; i++)
1455
        printf("%02x ", pkt->data[i]);
1456
    for(i=0; i<8; i++)
1457
        printf("%c ", (pkt->data[i]) & 0x7F);
1458
    puts("");
1459
*/
1460
#endif
1461

    
1462
    mov->next_chunk_offset = offset + size;
1463

    
1464
    return 0;
1465
}
1466

    
1467
static int mov_read_close(AVFormatContext *s)
1468
{
1469
    int i;
1470
    MOVContext *mov = (MOVContext *) s->priv_data;
1471
    for(i=0; i<mov->total_streams; i++)
1472
        mov_free_stream_context(mov->streams[i]);
1473
    for(i=0; i<s->nb_streams; i++)
1474
        av_freep(&s->streams[i]);
1475
    /* free color tabs */
1476
    for(i=0; i<mov->ctab_size; i++)
1477
        av_freep(&mov->ctab[i]);
1478
    av_freep(&mov->ctab);
1479
    return 0;
1480
}
1481

    
1482
static AVInputFormat mov_iformat = {
1483
    "mov",
1484
    "QuickTime/MPEG4 format",
1485
    sizeof(MOVContext),
1486
    mov_probe,
1487
    mov_read_header,
1488
    mov_read_packet,
1489
    mov_read_close,
1490
};
1491

    
1492
int mov_init(void)
1493
{
1494
    av_register_input_format(&mov_iformat);
1495
    return 0;
1496
}