Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 263a93ec

History | View | Annotate | Download (54.1 KB)

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

    
22
#include <limits.h>
23

    
24
//#define DEBUG
25

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

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

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

    
63
#include "qtpalette.h"
64

    
65

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

    
69
/* the QuickTime file format is quite convoluted...
70
 * it has lots of index tables, each indexing something in another one...
71
 * Here we just use what is needed to read the chunks
72
 */
73

    
74
typedef struct MOV_sample_to_chunk_tbl {
75
    int first;
76
    int count;
77
    int id;
78
} MOV_sample_to_chunk_tbl;
79

    
80
typedef struct {
81
    uint32_t type;
82
    int64_t offset;
83
    int64_t size; /* total size (excluding the size and type fields) */
84
} MOV_atom_t;
85

    
86
typedef struct MOV_mdat_atom_s {
87
    offset_t offset;
88
    int64_t size;
89
} MOV_mdat_atom_t;
90

    
91
struct MOVParseTableEntry;
92

    
93
typedef struct MOVStreamContext {
94
    int ffindex; /* the ffmpeg stream id */
95
    int next_chunk;
96
    unsigned int chunk_count;
97
    int64_t *chunk_offsets;
98
    unsigned int stts_count;
99
    Time2Sample *stts_data;
100
    unsigned int ctts_count;
101
    Time2Sample *ctts_data;
102
    unsigned int edit_count; /* number of 'edit' (elst atom) */
103
    unsigned int sample_to_chunk_sz;
104
    MOV_sample_to_chunk_tbl *sample_to_chunk;
105
    int sample_to_ctime_index;
106
    int sample_to_ctime_sample;
107
    unsigned int sample_size;
108
    unsigned int sample_count;
109
    int *sample_sizes;
110
    unsigned int keyframe_count;
111
    int *keyframes;
112
    int time_scale;
113
    int time_rate;
114
    int current_sample;
115
    unsigned int bytes_per_frame;
116
    unsigned int samples_per_frame;
117
    int dv_audio_container;
118
} MOVStreamContext;
119

    
120
typedef struct MOVContext {
121
    AVFormatContext *fc;
122
    int time_scale;
123
    int64_t duration; /* duration of the longest track */
124
    int found_moov; /* when both 'moov' and 'mdat' sections has been found */
125
    int found_mdat; /* we suppose we have enough data to read the file */
126
    int64_t mdat_offset;
127
    int total_streams;
128
    MOVStreamContext *streams[MAX_STREAMS];
129

    
130
    const struct MOVParseTableEntry *parse_table; /* could be eventually used to change the table */
131
    /* NOTE: for recursion save to/ restore from local variable! */
132

    
133
    AVPaletteControl palette_control;
134
    MOV_mdat_atom_t *mdat_list;
135
    int mdat_count;
136
    DVDemuxContext *dv_demux;
137
    AVFormatContext *dv_fctx;
138
    int isom; /* 1 if file is ISO Media (mp4/3gp) */
139
} MOVContext;
140

    
141

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

    
144
/* those functions parse an atom */
145
/* return code:
146
 1: found what I wanted, exit
147
 0: continue to parse next atom
148
 -1: error occured, exit
149
 */
150
typedef int (*mov_parse_function)(MOVContext *ctx, ByteIOContext *pb, MOV_atom_t atom);
151

    
152
/* links atom IDs to parse functions */
153
typedef struct MOVParseTableEntry {
154
    uint32_t type;
155
    mov_parse_function func;
156
} MOVParseTableEntry;
157

    
158
static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
159
{
160
    int64_t total_size = 0;
161
    MOV_atom_t a;
162
    int i;
163
    int err = 0;
164

    
165
    a.offset = atom.offset;
166

    
167
    if (atom.size < 0)
168
        atom.size = INT64_MAX;
169
    while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
170
        a.size = atom.size;
171
        a.type=0L;
172
        if(atom.size >= 8) {
173
            a.size = get_be32(pb);
174
            a.type = get_le32(pb);
175
        }
176
        total_size += 8;
177
        a.offset += 8;
178
        dprintf(c->fc, "type: %08x  %.4s  sz: %"PRIx64"  %"PRIx64"   %"PRIx64"\n", a.type, (char*)&a.type, a.size, atom.size, total_size);
179
        if (a.size == 1) { /* 64 bit extended size */
180
            a.size = get_be64(pb) - 8;
181
            a.offset += 8;
182
            total_size += 8;
183
        }
184
        if (a.size == 0) {
185
            a.size = atom.size - total_size;
186
            if (a.size <= 8)
187
                break;
188
        }
189
        a.size -= 8;
190
        if(a.size < 0 || a.size > atom.size - total_size)
191
            break;
192

    
193
        for (i = 0; c->parse_table[i].type != 0L
194
             && c->parse_table[i].type != a.type; i++)
195
            /* empty */;
196

    
197
        if (c->parse_table[i].type == 0) { /* skip leaf atoms data */
198
            url_fskip(pb, a.size);
199
        } else {
200
            offset_t start_pos = url_ftell(pb);
201
            int64_t left;
202
            err = (c->parse_table[i].func)(c, pb, a);
203
            left = a.size - url_ftell(pb) + start_pos;
204
            if (left > 0) /* skip garbage at atom end */
205
                url_fskip(pb, left);
206
        }
207

    
208
        a.offset += a.size;
209
        total_size += a.size;
210
    }
211

    
212
    if (!err && total_size < atom.size && atom.size < 0x7ffff) {
213
        url_fskip(pb, atom.size - total_size);
214
    }
215

    
216
    return err;
217
}
218

    
219
static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
220
{
221
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
222
    uint32_t type;
223
    uint32_t ctype;
224

    
225
    get_byte(pb); /* version */
226
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
227

    
228
    /* component type */
229
    ctype = get_le32(pb);
230
    type = get_le32(pb); /* component subtype */
231

    
232
    dprintf(c->fc, "ctype= %c%c%c%c (0x%08x)\n", *((char *)&ctype), ((char *)&ctype)[1], ((char *)&ctype)[2], ((char *)&ctype)[3], (int) ctype);
233
    dprintf(c->fc, "stype= %c%c%c%c\n", *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
234
    if(!ctype)
235
        c->isom = 1;
236
    if(type == MKTAG('v', 'i', 'd', 'e'))
237
        st->codec->codec_type = CODEC_TYPE_VIDEO;
238
    else if(type == MKTAG('s', 'o', 'u', 'n'))
239
        st->codec->codec_type = CODEC_TYPE_AUDIO;
240
    else if(type == MKTAG('m', '1', 'a', ' '))
241
        st->codec->codec_id = CODEC_ID_MP2;
242
    else if(type == MKTAG('s', 'u', 'b', 'p')) {
243
        st->codec->codec_type = CODEC_TYPE_SUBTITLE;
244
        st->codec->codec_id = CODEC_ID_DVD_SUBTITLE;
245
    }
246
    get_be32(pb); /* component  manufacture */
247
    get_be32(pb); /* component flags */
248
    get_be32(pb); /* component flags mask */
249

    
250
    if(atom.size <= 24)
251
        return 0; /* nothing left to read */
252

    
253
    url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
254
    return 0;
255
}
256

    
257
static int mp4_read_descr_len(ByteIOContext *pb)
258
{
259
    int len = 0;
260
    int count = 4;
261
    while (count--) {
262
        int c = get_byte(pb);
263
        len = (len << 7) | (c & 0x7f);
264
        if (!(c & 0x80))
265
            break;
266
    }
267
    return len;
268
}
269

    
270
static int mp4_read_descr(MOVContext *c, ByteIOContext *pb, int *tag)
271
{
272
    int len;
273
    *tag = get_byte(pb);
274
    len = mp4_read_descr_len(pb);
275
    dprintf(c->fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
276
    return len;
277
}
278

    
279
#define MP4ESDescrTag                   0x03
280
#define MP4DecConfigDescrTag            0x04
281
#define MP4DecSpecificDescrTag          0x05
282

    
283
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
284
{
285
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
286
    int tag, len;
287

    
288
    /* Well, broken but suffisant for some MP4 streams */
289
    get_be32(pb); /* version + flags */
290
    len = mp4_read_descr(c, pb, &tag);
291
    if (tag == MP4ESDescrTag) {
292
        get_be16(pb); /* ID */
293
        get_byte(pb); /* priority */
294
    } else
295
        get_be16(pb); /* ID */
296

    
297
    len = mp4_read_descr(c, pb, &tag);
298
    if (tag == MP4DecConfigDescrTag) {
299
        int object_type_id = get_byte(pb);
300
        get_byte(pb); /* stream type */
301
        get_be24(pb); /* buffer size db */
302
        get_be32(pb); /* max bitrate */
303
        get_be32(pb); /* avg bitrate */
304

    
305
        st->codec->codec_id= codec_get_id(ff_mp4_obj_type, object_type_id);
306
        dprintf(c->fc, "esds object type id %d\n", object_type_id);
307
        len = mp4_read_descr(c, pb, &tag);
308
        if (tag == MP4DecSpecificDescrTag) {
309
            dprintf(c->fc, "Specific MPEG4 header len=%d\n", len);
310
            st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
311
            if (st->codec->extradata) {
312
                get_buffer(pb, st->codec->extradata, len);
313
                st->codec->extradata_size = len;
314
                /* from mplayer */
315
                if ((*st->codec->extradata >> 3) == 29) {
316
                    st->codec->codec_id = CODEC_ID_MP3ON4;
317
                }
318
            }
319
        }
320
    }
321
    return 0;
322
}
323

    
324
/* this atom contains actual media data */
325
static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
326
{
327
    if(atom.size == 0) /* wrong one (MP4) */
328
        return 0;
329
    c->mdat_list = av_realloc(c->mdat_list, (c->mdat_count + 1) * sizeof(*c->mdat_list));
330
    c->mdat_list[c->mdat_count].offset = atom.offset;
331
    c->mdat_list[c->mdat_count].size = atom.size;
332
    c->mdat_count++;
333
    c->found_mdat=1;
334
    c->mdat_offset = atom.offset;
335
    if(c->found_moov)
336
        return 1; /* found both, just go */
337
    url_fskip(pb, atom.size);
338
    return 0; /* now go for moov */
339
}
340

    
341
static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
342
{
343
    uint32_t type = get_le32(pb);
344

    
345
    if (type != MKTAG('q','t',' ',' '))
346
        c->isom = 1;
347
    av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
348
    get_be32(pb); /* minor version */
349
    url_fskip(pb, atom.size - 8);
350
    return 0;
351
}
352

    
353
/* this atom should contain all header atoms */
354
static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
355
{
356
    int err;
357

    
358
    err = mov_read_default(c, pb, atom);
359
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
360
    /* so we don't parse the whole file if over a network */
361
    c->found_moov=1;
362
    if(c->found_mdat)
363
        return 1; /* found both, just go */
364
    return 0; /* now go for mdat */
365
}
366

    
367

    
368
static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
369
{
370
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
371
    MOVStreamContext *sc = st->priv_data;
372
    int version = get_byte(pb);
373
    int lang;
374

    
375
    if (version > 1)
376
        return 1; /* unsupported */
377

    
378
    get_byte(pb); get_byte(pb);
379
    get_byte(pb); /* flags */
380

    
381
    if (version == 1) {
382
        get_be64(pb);
383
        get_be64(pb);
384
    } else {
385
        get_be32(pb); /* creation time */
386
        get_be32(pb); /* modification time */
387
    }
388

    
389
    sc->time_scale = get_be32(pb);
390
    st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
391

    
392
    lang = get_be16(pb); /* language */
393
    ff_mov_lang_to_iso639(lang, st->language);
394
    get_be16(pb); /* quality */
395

    
396
    return 0;
397
}
398

    
399
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
400
{
401
    int version = get_byte(pb); /* version */
402
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
403

    
404
    if (version == 1) {
405
        get_be64(pb);
406
        get_be64(pb);
407
    } else {
408
        get_be32(pb); /* creation time */
409
        get_be32(pb); /* modification time */
410
    }
411
    c->time_scale = get_be32(pb); /* time scale */
412
#ifdef DEBUG
413
    av_log(NULL, AV_LOG_DEBUG, "time scale = %i\n", c->time_scale);
414
#endif
415
    c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
416
    get_be32(pb); /* preferred scale */
417

    
418
    get_be16(pb); /* preferred volume */
419

    
420
    url_fskip(pb, 10); /* reserved */
421

    
422
    url_fskip(pb, 36); /* display matrix */
423

    
424
    get_be32(pb); /* preview time */
425
    get_be32(pb); /* preview duration */
426
    get_be32(pb); /* poster time */
427
    get_be32(pb); /* selection time */
428
    get_be32(pb); /* selection duration */
429
    get_be32(pb); /* current time */
430
    get_be32(pb); /* next track ID */
431

    
432
    return 0;
433
}
434

    
435
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
436
{
437
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
438

    
439
    if((uint64_t)atom.size > (1<<30))
440
        return -1;
441

    
442
    // currently SVQ3 decoder expect full STSD header - so let's fake it
443
    // this should be fixed and just SMI header should be passed
444
    av_free(st->codec->extradata);
445
    st->codec->extradata_size = 0x5a + atom.size;
446
    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
447

    
448
    if (st->codec->extradata) {
449
        memcpy(st->codec->extradata, "SVQ3", 4); // fake
450
        get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
451
        dprintf(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
452
    } else
453
        url_fskip(pb, atom.size);
454

    
455
    return 0;
456
}
457

    
458
static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
459
{
460
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
461
    int little_endian = get_be16(pb);
462

    
463
    if (little_endian) {
464
        switch (st->codec->codec_id) {
465
        case CODEC_ID_PCM_S24BE:
466
            st->codec->codec_id = CODEC_ID_PCM_S24LE;
467
            break;
468
        case CODEC_ID_PCM_S32BE:
469
            st->codec->codec_id = CODEC_ID_PCM_S32LE;
470
            break;
471
        default:
472
            break;
473
        }
474
    }
475
    return 0;
476
}
477

    
478
/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
479
static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
480
{
481
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
482
    if((uint64_t)atom.size > (1<<30))
483
        return -1;
484
    av_free(st->codec->extradata);
485
    st->codec->extradata_size = atom.size + 8;
486
    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
487
    if (st->codec->extradata) {
488
        AV_WL32(st->codec->extradata + 4, atom.type);
489
        get_buffer(pb, st->codec->extradata + 8, atom.size);
490
    } else
491
        url_fskip(pb, atom.size);
492
    return 0;
493
}
494

    
495
static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
496
{
497
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
498

    
499
    if((uint64_t)atom.size > (1<<30))
500
        return -1;
501

    
502
    if (st->codec->codec_id == CODEC_ID_QDM2) {
503
        // pass all frma atom to codec, needed at least for QDM2
504
        av_free(st->codec->extradata);
505
        st->codec->extradata_size = atom.size;
506
        st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
507

    
508
        if (st->codec->extradata) {
509
            get_buffer(pb, st->codec->extradata, atom.size);
510
        } else
511
            url_fskip(pb, atom.size);
512
    } else if (atom.size > 8) { /* to read frma, esds atoms */
513
        mov_read_default(c, pb, atom);
514
    } else
515
        url_fskip(pb, atom.size);
516
    return 0;
517
}
518

    
519
static int mov_read_avcC(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
520
{
521
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
522

    
523
    if((uint64_t)atom.size > (1<<30))
524
        return -1;
525

    
526
    av_free(st->codec->extradata);
527

    
528
    st->codec->extradata_size = atom.size;
529
    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
530

    
531
    if (st->codec->extradata) {
532
        get_buffer(pb, st->codec->extradata, atom.size);
533
    } else
534
        url_fskip(pb, atom.size);
535

    
536
    return 0;
537
}
538

    
539
static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
540
{
541
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
542
    MOVStreamContext *sc = st->priv_data;
543
    unsigned int i, entries;
544

    
545
    get_byte(pb); /* version */
546
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
547

    
548
    entries = get_be32(pb);
549

    
550
    if(entries >= UINT_MAX/sizeof(int64_t))
551
        return -1;
552

    
553
    sc->chunk_count = entries;
554
    sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
555
    if (!sc->chunk_offsets)
556
        return -1;
557
    if (atom.type == MKTAG('s', 't', 'c', 'o')) {
558
        for(i=0; i<entries; i++) {
559
            sc->chunk_offsets[i] = get_be32(pb);
560
        }
561
    } else if (atom.type == MKTAG('c', 'o', '6', '4')) {
562
        for(i=0; i<entries; i++) {
563
            sc->chunk_offsets[i] = get_be64(pb);
564
        }
565
    } else
566
        return -1;
567

    
568
    return 0;
569
}
570

    
571
static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
572
{
573
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
574
    MOVStreamContext *sc = st->priv_data;
575
    int entries, frames_per_sample;
576
    uint32_t format;
577
    uint8_t codec_name[32];
578

    
579
    /* for palette traversal */
580
    int color_depth;
581
    int color_start;
582
    int color_count;
583
    int color_end;
584
    int color_index;
585
    int color_dec;
586
    int color_greyscale;
587
    unsigned char *color_table;
588
    int j;
589
    unsigned char r, g, b;
590

    
591
    get_byte(pb); /* version */
592
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
593

    
594
    entries = get_be32(pb);
595

    
596
    while(entries--) { //Parsing Sample description table
597
        enum CodecID id;
598
        MOV_atom_t a = { 0, 0, 0 };
599
        offset_t start_pos = url_ftell(pb);
600
        int size = get_be32(pb); /* size */
601
        format = get_le32(pb); /* data format */
602

    
603
        get_be32(pb); /* reserved */
604
        get_be16(pb); /* reserved */
605
        get_be16(pb); /* index */
606

    
607
        if (st->codec->codec_tag) {
608
            /* multiple fourcc, just skip for now */
609
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
610
            continue;
611
        }
612

    
613
        st->codec->codec_tag = format;
614
        id = codec_get_id(codec_movaudio_tags, format);
615
        if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
616
            st->codec->codec_type = CODEC_TYPE_AUDIO;
617
        } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
618
                   format && format != MKTAG('m', 'p', '4', 's')) { /* skip old asf mpeg4 tag */
619
            id = codec_get_id(codec_movvideo_tags, format);
620
            if (id <= 0)
621
                id = codec_get_id(codec_bmp_tags, format);
622
            if (id > 0)
623
                st->codec->codec_type = CODEC_TYPE_VIDEO;
624
        }
625

    
626
        dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n",
627
                size,
628
                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff, (format >> 24) & 0xff,
629
                st->codec->codec_type);
630

    
631
        if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
632
            st->codec->codec_id = id;
633
            get_be16(pb); /* version */
634
            get_be16(pb); /* revision level */
635
            get_be32(pb); /* vendor */
636
            get_be32(pb); /* temporal quality */
637
            get_be32(pb); /* spacial quality */
638

    
639
            st->codec->width = get_be16(pb); /* width */
640
            st->codec->height = get_be16(pb); /* height */
641

    
642
            get_be32(pb); /* horiz resolution */
643
            get_be32(pb); /* vert resolution */
644
            get_be32(pb); /* data size, always 0 */
645
            frames_per_sample = get_be16(pb); /* frames per samples */
646
#ifdef DEBUG
647
            av_log(NULL, AV_LOG_DEBUG, "frames/samples = %d\n", frames_per_sample);
648
#endif
649
            get_buffer(pb, codec_name, 32); /* codec name, pascal string (FIXME: true for mp4?) */
650
            if (codec_name[0] <= 31) {
651
                memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
652
                st->codec->codec_name[codec_name[0]] = 0;
653
            }
654

    
655
            st->codec->bits_per_sample = get_be16(pb); /* depth */
656
            st->codec->color_table_id = get_be16(pb); /* colortable id */
657

    
658
            /* figure out the palette situation */
659
            color_depth = st->codec->bits_per_sample & 0x1F;
660
            color_greyscale = st->codec->bits_per_sample & 0x20;
661

    
662
            /* if the depth is 2, 4, or 8 bpp, file is palettized */
663
            if ((color_depth == 2) || (color_depth == 4) ||
664
                (color_depth == 8)) {
665

    
666
                if (color_greyscale) {
667

    
668
                    /* compute the greyscale palette */
669
                    color_count = 1 << color_depth;
670
                    color_index = 255;
671
                    color_dec = 256 / (color_count - 1);
672
                    for (j = 0; j < color_count; j++) {
673
                        r = g = b = color_index;
674
                        c->palette_control.palette[j] =
675
                            (r << 16) | (g << 8) | (b);
676
                        color_index -= color_dec;
677
                        if (color_index < 0)
678
                            color_index = 0;
679
                    }
680

    
681
                } else if (st->codec->color_table_id & 0x08) {
682

    
683
                    /* if flag bit 3 is set, use the default palette */
684
                    color_count = 1 << color_depth;
685
                    if (color_depth == 2)
686
                        color_table = ff_qt_default_palette_4;
687
                    else if (color_depth == 4)
688
                        color_table = ff_qt_default_palette_16;
689
                    else
690
                        color_table = ff_qt_default_palette_256;
691

    
692
                    for (j = 0; j < color_count; j++) {
693
                        r = color_table[j * 4 + 0];
694
                        g = color_table[j * 4 + 1];
695
                        b = color_table[j * 4 + 2];
696
                        c->palette_control.palette[j] =
697
                            (r << 16) | (g << 8) | (b);
698
                    }
699

    
700
                } else {
701

    
702
                    /* load the palette from the file */
703
                    color_start = get_be32(pb);
704
                    color_count = get_be16(pb);
705
                    color_end = get_be16(pb);
706
                    for (j = color_start; j <= color_end; j++) {
707
                        /* each R, G, or B component is 16 bits;
708
                         * only use the top 8 bits; skip alpha bytes
709
                         * up front */
710
                        get_byte(pb);
711
                        get_byte(pb);
712
                        r = get_byte(pb);
713
                        get_byte(pb);
714
                        g = get_byte(pb);
715
                        get_byte(pb);
716
                        b = get_byte(pb);
717
                        get_byte(pb);
718
                        c->palette_control.palette[j] =
719
                            (r << 16) | (g << 8) | (b);
720
                    }
721
                }
722

    
723
                st->codec->palctrl = &c->palette_control;
724
                st->codec->palctrl->palette_changed = 1;
725
            } else
726
                st->codec->palctrl = NULL;
727
        } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
728
            int bits_per_sample;
729
            uint16_t version = get_be16(pb);
730

    
731
            st->codec->codec_id = id;
732
            get_be16(pb); /* revision level */
733
            get_be32(pb); /* vendor */
734

    
735
            st->codec->channels = get_be16(pb);             /* channel count */
736
            dprintf(c->fc, "audio channels %d\n", st->codec->channels);
737
            st->codec->bits_per_sample = get_be16(pb);      /* sample size */
738
            /* do we need to force to 16 for AMR ? */
739

    
740
            /* handle specific s8 codec */
741
            get_be16(pb); /* compression id = 0*/
742
            get_be16(pb); /* packet size = 0 */
743

    
744
            st->codec->sample_rate = ((get_be32(pb) >> 16));
745

    
746
            switch (st->codec->codec_id) {
747
            case CODEC_ID_PCM_S8:
748
            case CODEC_ID_PCM_U8:
749
                if (st->codec->bits_per_sample == 16)
750
                    st->codec->codec_id = CODEC_ID_PCM_S16BE;
751
                break;
752
            case CODEC_ID_PCM_S16LE:
753
            case CODEC_ID_PCM_S16BE:
754
                if (st->codec->bits_per_sample == 8)
755
                    st->codec->codec_id = CODEC_ID_PCM_S8;
756
                else if (st->codec->bits_per_sample == 24)
757
                    st->codec->codec_id = CODEC_ID_PCM_S24BE;
758
                break;
759
            default:
760
                break;
761
            }
762

    
763
            //Read QT version 1 fields. In version 0 theese dont exist
764
            dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
765
            if(!c->isom) {
766
                if(version==1) {
767
                    sc->samples_per_frame = get_be32(pb);
768
                    get_be32(pb); /* bytes per packet */
769
                    sc->bytes_per_frame = get_be32(pb);
770
                    get_be32(pb); /* bytes per sample */
771
                } else if(version==2) {
772
                    get_be32(pb); /* sizeof struct only */
773
                    st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
774
                    st->codec->channels = get_be32(pb);
775
                    get_be32(pb); /* always 0x7F000000 */
776
                    get_be32(pb); /* bits per channel if sound is uncompressed */
777
                    get_be32(pb); /* lcpm format specific flag */
778
                    get_be32(pb); /* bytes per audio packet if constant */
779
                    get_be32(pb); /* lpcm frames per audio packet if constant */
780
                }
781
            }
782

    
783
            bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
784
            if (bits_per_sample) {
785
                st->codec->bits_per_sample = bits_per_sample;
786
                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
787
            }
788
        } else {
789
            /* other codec type, just skip (rtp, mp4s, tmcd ...) */
790
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
791
        }
792
        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
793
        a.size = size - (url_ftell(pb) - start_pos);
794
        if (a.size > 8)
795
            mov_read_default(c, pb, a);
796
        else if (a.size > 0)
797
            url_fskip(pb, a.size);
798
    }
799

    
800
    if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1) {
801
        st->codec->sample_rate= sc->time_scale;
802
    }
803

    
804
    /* special codec parameters handling */
805
    switch (st->codec->codec_id) {
806
#ifdef CONFIG_H261_DECODER
807
    case CODEC_ID_H261:
808
#endif
809
#ifdef CONFIG_H263_DECODER
810
    case CODEC_ID_H263:
811
#endif
812
#ifdef CONFIG_MPEG4_DECODER
813
    case CODEC_ID_MPEG4:
814
#endif
815
        st->codec->width= 0; /* let decoder init width/height */
816
        st->codec->height= 0;
817
        break;
818
#ifdef CONFIG_LIBFAAD
819
    case CODEC_ID_AAC:
820
#endif
821
#ifdef CONFIG_VORBIS_DECODER
822
    case CODEC_ID_VORBIS:
823
#endif
824
    case CODEC_ID_MP3ON4:
825
        st->codec->sample_rate= 0; /* let decoder init parameters properly */
826
        break;
827
#ifdef CONFIG_DV_DEMUXER
828
    case CODEC_ID_DVAUDIO:
829
        c->dv_fctx = av_alloc_format_context();
830
        c->dv_demux = dv_init_demux(c->dv_fctx);
831
        if (!c->dv_demux) {
832
            av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
833
            return -1;
834
        }
835
        sc->dv_audio_container = 1;
836
        st->codec->codec_id = CODEC_ID_PCM_S16LE;
837
        break;
838
#endif
839
    /* no ifdef since parameters are always those */
840
    case CODEC_ID_AMR_WB:
841
        st->codec->sample_rate= 16000;
842
        st->codec->channels= 1; /* really needed */
843
        break;
844
    case CODEC_ID_AMR_NB:
845
        st->codec->sample_rate= 8000;
846
        st->codec->channels= 1; /* really needed */
847
        break;
848
    case CODEC_ID_MP2:
849
    case CODEC_ID_MP3:
850
        st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
851
        st->need_parsing = AVSTREAM_PARSE_FULL;
852
        break;
853
    default:
854
        break;
855
    }
856

    
857
    return 0;
858
}
859

    
860
static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
861
{
862
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
863
    MOVStreamContext *sc = st->priv_data;
864
    unsigned int i, entries;
865

    
866
    get_byte(pb); /* version */
867
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
868

    
869
    entries = get_be32(pb);
870

    
871
    if(entries >= UINT_MAX / sizeof(MOV_sample_to_chunk_tbl))
872
        return -1;
873

    
874
#ifdef DEBUG
875
av_log(NULL, AV_LOG_DEBUG, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
876
#endif
877
    sc->sample_to_chunk_sz = entries;
878
    sc->sample_to_chunk = av_malloc(entries * sizeof(MOV_sample_to_chunk_tbl));
879
    if (!sc->sample_to_chunk)
880
        return -1;
881
    for(i=0; i<entries; i++) {
882
        sc->sample_to_chunk[i].first = get_be32(pb);
883
        sc->sample_to_chunk[i].count = get_be32(pb);
884
        sc->sample_to_chunk[i].id = get_be32(pb);
885
    }
886
    return 0;
887
}
888

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

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

    
898
    entries = get_be32(pb);
899

    
900
    if(entries >= UINT_MAX / sizeof(int))
901
        return -1;
902

    
903
    sc->keyframe_count = entries;
904
#ifdef DEBUG
905
    av_log(NULL, AV_LOG_DEBUG, "keyframe_count = %d\n", sc->keyframe_count);
906
#endif
907
    sc->keyframes = av_malloc(entries * sizeof(int));
908
    if (!sc->keyframes)
909
        return -1;
910
    for(i=0; i<entries; i++) {
911
        sc->keyframes[i] = get_be32(pb);
912
#ifdef DEBUG
913
/*        av_log(NULL, AV_LOG_DEBUG, "keyframes[]=%d\n", sc->keyframes[i]); */
914
#endif
915
    }
916
    return 0;
917
}
918

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

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

    
928
    sample_size = get_be32(pb);
929
    if (!sc->sample_size) /* do not overwrite value computed in stsd */
930
        sc->sample_size = sample_size;
931
    entries = get_be32(pb);
932
    if(entries >= UINT_MAX / sizeof(int))
933
        return -1;
934

    
935
    sc->sample_count = entries;
936
    if (sample_size)
937
        return 0;
938

    
939
#ifdef DEBUG
940
    av_log(NULL, AV_LOG_DEBUG, "sample_size = %d sample_count = %d\n", sc->sample_size, sc->sample_count);
941
#endif
942
    sc->sample_sizes = av_malloc(entries * sizeof(int));
943
    if (!sc->sample_sizes)
944
        return -1;
945
    for(i=0; i<entries; i++) {
946
        sc->sample_sizes[i] = get_be32(pb);
947
#ifdef DEBUG
948
        av_log(NULL, AV_LOG_DEBUG, "sample_sizes[]=%d\n", sc->sample_sizes[i]);
949
#endif
950
    }
951
    return 0;
952
}
953

    
954
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
955
{
956
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
957
    MOVStreamContext *sc = st->priv_data;
958
    unsigned int i, entries;
959
    int64_t duration=0;
960
    int64_t total_sample_count=0;
961

    
962
    get_byte(pb); /* version */
963
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
964
    entries = get_be32(pb);
965
    if(entries >= UINT_MAX / sizeof(Time2Sample))
966
        return -1;
967

    
968
    sc->stts_count = entries;
969
    sc->stts_data = av_malloc(entries * sizeof(Time2Sample));
970

    
971
#ifdef DEBUG
972
av_log(NULL, AV_LOG_DEBUG, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
973
#endif
974

    
975
    sc->time_rate=0;
976

    
977
    for(i=0; i<entries; i++) {
978
        int sample_duration;
979
        int sample_count;
980

    
981
        sample_count=get_be32(pb);
982
        sample_duration = get_be32(pb);
983
        sc->stts_data[i].count= sample_count;
984
        sc->stts_data[i].duration= sample_duration;
985

    
986
        sc->time_rate= ff_gcd(sc->time_rate, sample_duration);
987

    
988
        dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
989

    
990
        duration+=(int64_t)sample_duration*sample_count;
991
        total_sample_count+=sample_count;
992
    }
993

    
994
    st->nb_frames= total_sample_count;
995
    if(duration)
996
        st->duration= duration;
997
    return 0;
998
}
999

    
1000
static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1001
{
1002
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1003
    MOVStreamContext *sc = st->priv_data;
1004
    unsigned int i, entries;
1005

    
1006
    get_byte(pb); /* version */
1007
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1008
    entries = get_be32(pb);
1009
    if(entries >= UINT_MAX / sizeof(Time2Sample))
1010
        return -1;
1011

    
1012
    sc->ctts_count = entries;
1013
    sc->ctts_data = av_malloc(entries * sizeof(Time2Sample));
1014

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

    
1017
    for(i=0; i<entries; i++) {
1018
        int count    =get_be32(pb);
1019
        int duration =get_be32(pb);
1020

    
1021
        if (duration < 0) {
1022
            av_log(c->fc, AV_LOG_ERROR, "negative ctts, ignoring\n");
1023
            sc->ctts_count = 0;
1024
            url_fskip(pb, 8 * (entries - i - 1));
1025
            break;
1026
        }
1027
        sc->ctts_data[i].count   = count;
1028
        sc->ctts_data[i].duration= duration;
1029

    
1030
        sc->time_rate= ff_gcd(sc->time_rate, duration);
1031
    }
1032
    return 0;
1033
}
1034

    
1035
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1036
{
1037
    AVStream *st;
1038
    MOVStreamContext *sc;
1039

    
1040
    st = av_new_stream(c->fc, c->fc->nb_streams);
1041
    if (!st) return -2;
1042
    sc = av_mallocz(sizeof(MOVStreamContext));
1043
    if (!sc) {
1044
        av_free(st);
1045
        return -1;
1046
    }
1047

    
1048
    st->priv_data = sc;
1049
    st->codec->codec_type = CODEC_TYPE_DATA;
1050
    st->start_time = 0; /* XXX: check */
1051
    c->streams[c->fc->nb_streams-1] = sc;
1052

    
1053
    return mov_read_default(c, pb, atom);
1054
}
1055

    
1056
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1057
{
1058
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1059
    int version = get_byte(pb);
1060

    
1061
    get_byte(pb); get_byte(pb);
1062
    get_byte(pb); /* flags */
1063
    /*
1064
    MOV_TRACK_ENABLED 0x0001
1065
    MOV_TRACK_IN_MOVIE 0x0002
1066
    MOV_TRACK_IN_PREVIEW 0x0004
1067
    MOV_TRACK_IN_POSTER 0x0008
1068
    */
1069

    
1070
    if (version == 1) {
1071
        get_be64(pb);
1072
        get_be64(pb);
1073
    } else {
1074
        get_be32(pb); /* creation time */
1075
        get_be32(pb); /* modification time */
1076
    }
1077
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1078
    get_be32(pb); /* reserved */
1079
    st->start_time = 0; /* check */
1080
    (version == 1) ? get_be64(pb) : get_be32(pb); /* highlevel (considering edits) duration in movie timebase */
1081
    get_be32(pb); /* reserved */
1082
    get_be32(pb); /* reserved */
1083

    
1084
    get_be16(pb); /* layer */
1085
    get_be16(pb); /* alternate group */
1086
    get_be16(pb); /* volume */
1087
    get_be16(pb); /* reserved */
1088

    
1089
    url_fskip(pb, 36); /* display matrix */
1090

    
1091
    /* those are fixed-point */
1092
    get_be32(pb); /* track width */
1093
    get_be32(pb); /* track height */
1094

    
1095
    return 0;
1096
}
1097

    
1098
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1099
/* like the files created with Adobe Premiere 5.0, for samples see */
1100
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1101
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1102
{
1103
    int err;
1104

    
1105
    if (atom.size < 8)
1106
        return 0; /* continue */
1107
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1108
        url_fskip(pb, atom.size - 4);
1109
        return 0;
1110
    }
1111
    atom.type = get_le32(pb);
1112
    atom.offset += 8;
1113
    atom.size -= 8;
1114
    if (atom.type != MKTAG('m', 'd', 'a', 't')) {
1115
        url_fskip(pb, atom.size);
1116
        return 0;
1117
    }
1118
    err = mov_read_mdat(c, pb, atom);
1119
    return err;
1120
}
1121

    
1122
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1123
{
1124
#ifdef CONFIG_ZLIB
1125
    ByteIOContext ctx;
1126
    uint8_t *cmov_data;
1127
    uint8_t *moov_data; /* uncompressed data */
1128
    long cmov_len, moov_len;
1129
    int ret;
1130

    
1131
    get_be32(pb); /* dcom atom */
1132
    if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
1133
        return -1;
1134
    if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
1135
        av_log(NULL, AV_LOG_ERROR, "unknown compression for cmov atom !");
1136
        return -1;
1137
    }
1138
    get_be32(pb); /* cmvd atom */
1139
    if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
1140
        return -1;
1141
    moov_len = get_be32(pb); /* uncompressed size */
1142
    cmov_len = atom.size - 6 * 4;
1143

    
1144
    cmov_data = av_malloc(cmov_len);
1145
    if (!cmov_data)
1146
        return -1;
1147
    moov_data = av_malloc(moov_len);
1148
    if (!moov_data) {
1149
        av_free(cmov_data);
1150
        return -1;
1151
    }
1152
    get_buffer(pb, cmov_data, cmov_len);
1153
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1154
        return -1;
1155
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
1156
        return -1;
1157
    atom.type = MKTAG( 'm', 'o', 'o', 'v' );
1158
    atom.offset = 0;
1159
    atom.size = moov_len;
1160
#ifdef DEBUG
1161
//    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1162
#endif
1163
    ret = mov_read_default(c, &ctx, atom);
1164
    av_free(moov_data);
1165
    av_free(cmov_data);
1166
    return ret;
1167
#else
1168
    av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
1169
    return -1;
1170
#endif
1171
}
1172

    
1173
/* edit list atom */
1174
static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1175
{
1176
    int i, edit_count;
1177

    
1178
    get_byte(pb); /* version */
1179
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1180
    edit_count= c->streams[c->fc->nb_streams-1]->edit_count = get_be32(pb);     /* entries */
1181

    
1182
    for(i=0; i<edit_count; i++){
1183
        get_be32(pb); /* Track duration */
1184
        get_be32(pb); /* Media time */
1185
        get_be32(pb); /* Media rate */
1186
    }
1187
    dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, c->streams[c->fc->nb_streams-1]->edit_count);
1188
    return 0;
1189
}
1190

    
1191
static const MOVParseTableEntry mov_default_parse_table[] = {
1192
/* mp4 atoms */
1193
{ MKTAG( 'c', 'o', '6', '4' ), mov_read_stco },
1194
{ MKTAG( 'c', 't', 't', 's' ), mov_read_ctts }, /* composition time to sample */
1195
{ MKTAG( 'e', 'd', 't', 's' ), mov_read_default },
1196
{ MKTAG( 'e', 'l', 's', 't' ), mov_read_elst },
1197
{ MKTAG( 'e', 'n', 'd', 'a' ), mov_read_enda },
1198
{ MKTAG( 'f', 'i', 'e', 'l' ), mov_read_extradata },
1199
{ MKTAG( 'f', 't', 'y', 'p' ), mov_read_ftyp },
1200
{ MKTAG( 'h', 'd', 'l', 'r' ), mov_read_hdlr },
1201
{ MKTAG( 'j', 'p', '2', 'h' ), mov_read_extradata },
1202
{ MKTAG( 'm', 'd', 'a', 't' ), mov_read_mdat },
1203
{ MKTAG( 'm', 'd', 'h', 'd' ), mov_read_mdhd },
1204
{ MKTAG( 'm', 'd', 'i', 'a' ), mov_read_default },
1205
{ MKTAG( 'm', 'i', 'n', 'f' ), mov_read_default },
1206
{ MKTAG( 'm', 'o', 'o', 'v' ), mov_read_moov },
1207
{ MKTAG( 'm', 'v', 'h', 'd' ), mov_read_mvhd },
1208
{ MKTAG( 'S', 'M', 'I', ' ' ), mov_read_smi }, /* Sorenson extension ??? */
1209
{ MKTAG( 'a', 'l', 'a', 'c' ), mov_read_extradata }, /* alac specific atom */
1210
{ MKTAG( 'a', 'v', 'c', 'C' ), mov_read_avcC },
1211
{ MKTAG( 's', 't', 'b', 'l' ), mov_read_default },
1212
{ MKTAG( 's', 't', 'c', 'o' ), mov_read_stco },
1213
{ MKTAG( 's', 't', 's', 'c' ), mov_read_stsc },
1214
{ MKTAG( 's', 't', 's', 'd' ), mov_read_stsd }, /* sample description */
1215
{ MKTAG( 's', 't', 's', 's' ), mov_read_stss }, /* sync sample */
1216
{ MKTAG( 's', 't', 's', 'z' ), mov_read_stsz }, /* sample size */
1217
{ MKTAG( 's', 't', 't', 's' ), mov_read_stts },
1218
{ MKTAG( 't', 'k', 'h', 'd' ), mov_read_tkhd }, /* track header */
1219
{ MKTAG( 't', 'r', 'a', 'k' ), mov_read_trak },
1220
{ MKTAG( 'w', 'a', 'v', 'e' ), mov_read_wave },
1221
{ MKTAG( 'e', 's', 'd', 's' ), mov_read_esds },
1222
{ MKTAG( 'w', 'i', 'd', 'e' ), mov_read_wide }, /* place holder */
1223
{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_cmov },
1224
{ 0L, NULL }
1225
};
1226

    
1227
static void mov_free_stream_context(MOVStreamContext *sc)
1228
{
1229
    if(sc) {
1230
        av_freep(&sc->ctts_data);
1231
        av_freep(&sc);
1232
    }
1233
}
1234

    
1235
/* XXX: is it sufficient ? */
1236
static int mov_probe(AVProbeData *p)
1237
{
1238
    unsigned int offset;
1239
    uint32_t tag;
1240
    int score = 0;
1241

    
1242
    /* check file header */
1243
    offset = 0;
1244
    for(;;) {
1245
        /* ignore invalid offset */
1246
        if ((offset + 8) > (unsigned int)p->buf_size)
1247
            return score;
1248
        tag = AV_RL32(p->buf + offset + 4);
1249
        switch(tag) {
1250
        /* check for obvious tags */
1251
        case MKTAG( 'j', 'P', ' ', ' ' ): /* jpeg 2000 signature */
1252
        case MKTAG( 'm', 'o', 'o', 'v' ):
1253
        case MKTAG( 'm', 'd', 'a', 't' ):
1254
        case MKTAG( 'p', 'n', 'o', 't' ): /* detect movs with preview pics like ew.mov and april.mov */
1255
        case MKTAG( 'u', 'd', 't', 'a' ): /* Packet Video PVAuthor adds this and a lot of more junk */
1256
            return AVPROBE_SCORE_MAX;
1257
        /* those are more common words, so rate then a bit less */
1258
        case MKTAG( 'e', 'd', 'i', 'w' ): /* xdcam files have reverted first tags */
1259
        case MKTAG( 'w', 'i', 'd', 'e' ):
1260
        case MKTAG( 'f', 'r', 'e', 'e' ):
1261
        case MKTAG( 'j', 'u', 'n', 'k' ):
1262
        case MKTAG( 'p', 'i', 'c', 't' ):
1263
            return AVPROBE_SCORE_MAX - 5;
1264
        case MKTAG( 'f', 't', 'y', 'p' ):
1265
        case MKTAG( 's', 'k', 'i', 'p' ):
1266
        case MKTAG( 'u', 'u', 'i', 'd' ):
1267
            offset = AV_RB32(p->buf+offset) + offset;
1268
            /* if we only find those cause probedata is too small at least rate them */
1269
            score = AVPROBE_SCORE_MAX - 50;
1270
            break;
1271
        default:
1272
            /* unrecognized tag */
1273
            return score;
1274
        }
1275
    }
1276
    return score;
1277
}
1278

    
1279
static void mov_build_index(MOVContext *mov, AVStream *st)
1280
{
1281
    MOVStreamContext *sc = st->priv_data;
1282
    offset_t current_offset;
1283
    int64_t current_dts = 0;
1284
    unsigned int stts_index = 0;
1285
    unsigned int stsc_index = 0;
1286
    unsigned int stss_index = 0;
1287
    unsigned int i, j, k;
1288

    
1289
    if (sc->sample_sizes || st->codec->codec_type == CODEC_TYPE_VIDEO || sc->dv_audio_container) {
1290
        unsigned int current_sample = 0;
1291
        unsigned int stts_sample = 0;
1292
        unsigned int keyframe, sample_size;
1293
        unsigned int distance = 0;
1294

    
1295
        st->nb_frames = sc->sample_count;
1296
        for (i = 0; i < sc->chunk_count; i++) {
1297
            current_offset = sc->chunk_offsets[i];
1298
            if (stsc_index + 1 < sc->sample_to_chunk_sz && i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1299
                stsc_index++;
1300
            for (j = 0; j < sc->sample_to_chunk[stsc_index].count; j++) {
1301
                if (current_sample >= sc->sample_count) {
1302
                    av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1303
                    goto out;
1304
                }
1305
                keyframe = !sc->keyframe_count || current_sample + 1 == sc->keyframes[stss_index];
1306
                if (keyframe) {
1307
                    distance = 0;
1308
                    if (stss_index + 1 < sc->keyframe_count)
1309
                        stss_index++;
1310
                }
1311
                sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1312
                dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", size %d, distance %d, keyframe %d\n",
1313
                        st->index, current_sample, current_offset, current_dts, sample_size, distance, keyframe);
1314
                av_add_index_entry(st, current_offset, current_dts, sample_size, distance, keyframe ? AVINDEX_KEYFRAME : 0);
1315
                current_offset += sample_size;
1316
                assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
1317
                current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
1318
                distance++;
1319
                stts_sample++;
1320
                current_sample++;
1321
                if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1322
                    stts_sample = 0;
1323
                    stts_index++;
1324
                }
1325
            }
1326
        }
1327
    } else { /* read whole chunk */
1328
        unsigned int chunk_samples, chunk_size, chunk_duration;
1329

    
1330
        for (i = 0; i < sc->chunk_count; i++) {
1331
            current_offset = sc->chunk_offsets[i];
1332
            if (stsc_index + 1 < sc->sample_to_chunk_sz && i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1333
                stsc_index++;
1334
            chunk_samples = sc->sample_to_chunk[stsc_index].count;
1335
            /* get chunk size */
1336
            if (sc->sample_size > 1 || st->codec->codec_id == CODEC_ID_PCM_U8 || st->codec->codec_id == CODEC_ID_PCM_S8)
1337
                chunk_size = chunk_samples * sc->sample_size;
1338
            else if (sc->samples_per_frame > 0 && (chunk_samples * sc->bytes_per_frame % sc->samples_per_frame == 0))
1339
                chunk_size = chunk_samples * sc->bytes_per_frame / sc->samples_per_frame;
1340
            else { /* workaround to find nearest next chunk offset */
1341
                chunk_size = INT_MAX;
1342
                for (j = 0; j < mov->total_streams; j++) {
1343
                    MOVStreamContext *msc = mov->streams[j];
1344

    
1345
                    for (k = msc->next_chunk; k < msc->chunk_count; k++) {
1346
                        if (msc->chunk_offsets[k] > current_offset && msc->chunk_offsets[k] - current_offset < chunk_size) {
1347
                            chunk_size = msc->chunk_offsets[k] - current_offset;
1348
                            msc->next_chunk = k;
1349
                            break;
1350
                        }
1351
                    }
1352
                }
1353
                /* check for last chunk */
1354
                if (chunk_size == INT_MAX)
1355
                    for (j = 0; j < mov->mdat_count; j++) {
1356
                        dprintf(mov->fc, "mdat %d, offset %"PRIx64", size %"PRId64", current offset %"PRIx64"\n",
1357
                                j, mov->mdat_list[j].offset, mov->mdat_list[j].size, current_offset);
1358
                        if (mov->mdat_list[j].offset <= current_offset && mov->mdat_list[j].offset + mov->mdat_list[j].size > current_offset)
1359
                            chunk_size = mov->mdat_list[j].offset + mov->mdat_list[j].size - current_offset;
1360
                    }
1361
                assert(chunk_size != INT_MAX);
1362
                for (j = 0; j < mov->total_streams; j++) {
1363
                    mov->streams[j]->next_chunk = 0;
1364
                }
1365
            }
1366
            av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
1367
            /* get chunk duration */
1368
            chunk_duration = 0;
1369
            while (chunk_samples > 0) {
1370
                if (chunk_samples < sc->stts_data[stts_index].count) {
1371
                    chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1372
                    sc->stts_data[stts_index].count -= chunk_samples;
1373
                    break;
1374
                } else {
1375
                    chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1376
                    chunk_samples -= sc->stts_data[stts_index].count;
1377
                    if (stts_index + 1 < sc->stts_count) {
1378
                        stts_index++;
1379
                    }
1380
                }
1381
            }
1382
            dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", size %d, duration %d\n",
1383
                    st->index, i, current_offset, current_dts, chunk_size, chunk_duration);
1384
            assert(chunk_duration % sc->time_rate == 0);
1385
            current_dts += chunk_duration / sc->time_rate;
1386
        }
1387
    }
1388
 out:
1389
    /* adjust sample count to avindex entries */
1390
    sc->sample_count = st->nb_index_entries;
1391
}
1392

    
1393
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1394
{
1395
    MOVContext *mov = s->priv_data;
1396
    ByteIOContext *pb = &s->pb;
1397
    int i, err;
1398
    MOV_atom_t atom = { 0, 0, 0 };
1399

    
1400
    mov->fc = s;
1401
    mov->parse_table = mov_default_parse_table;
1402

    
1403
    if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1404
        atom.size = url_fsize(pb);
1405
    else
1406
        atom.size = INT64_MAX;
1407

    
1408
    /* check MOV header */
1409
    err = mov_read_default(mov, pb, atom);
1410
    if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
1411
        av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%"PRId64"\n",
1412
                err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1413
        return -1;
1414
    }
1415
    dprintf(mov->fc, "on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1416

    
1417
    /* some cleanup : make sure we are on the mdat atom */
1418
    if(!url_is_streamed(pb) && (url_ftell(pb) != mov->mdat_offset))
1419
        url_fseek(pb, mov->mdat_offset, SEEK_SET);
1420

    
1421
    mov->total_streams = s->nb_streams;
1422

    
1423
    for(i=0; i<mov->total_streams; i++) {
1424
        MOVStreamContext *sc = mov->streams[i];
1425
        AVStream *st = s->streams[i];
1426
        /* sanity checks */
1427
        if(!sc->stts_count || !sc->chunk_count || !sc->sample_to_chunk_sz ||
1428
           (!sc->sample_size && !sc->sample_count)){
1429
            av_log(s, AV_LOG_ERROR, "missing mandatory atoms, broken header\n");
1430
            sc->sample_count = 0; //ignore track
1431
            continue;
1432
        }
1433
        if(!sc->time_rate)
1434
            sc->time_rate=1;
1435
        if(!sc->time_scale)
1436
            sc->time_scale= mov->time_scale;
1437
        av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
1438

    
1439
        if (st->codec->codec_type == CODEC_TYPE_AUDIO && sc->stts_count == 1)
1440
            st->codec->frame_size = sc->stts_data[0].duration;
1441

    
1442
        if(st->duration != AV_NOPTS_VALUE){
1443
            assert(st->duration % sc->time_rate == 0);
1444
            st->duration /= sc->time_rate;
1445
        }
1446
        sc->ffindex = i;
1447
        mov_build_index(mov, st);
1448
    }
1449

    
1450
    for(i=0; i<mov->total_streams; i++) {
1451
        /* dont need those anymore */
1452
        av_freep(&mov->streams[i]->chunk_offsets);
1453
        av_freep(&mov->streams[i]->sample_to_chunk);
1454
        av_freep(&mov->streams[i]->sample_sizes);
1455
        av_freep(&mov->streams[i]->keyframes);
1456
        av_freep(&mov->streams[i]->stts_data);
1457
    }
1458
    av_freep(&mov->mdat_list);
1459
    return 0;
1460
}
1461

    
1462
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1463
{
1464
    MOVContext *mov = s->priv_data;
1465
    MOVStreamContext *sc = 0;
1466
    AVIndexEntry *sample = 0;
1467
    int64_t best_dts = INT64_MAX;
1468
    int i;
1469

    
1470
    for (i = 0; i < mov->total_streams; i++) {
1471
        MOVStreamContext *msc = mov->streams[i];
1472

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

    
1477
            dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
1478
            if (dts < best_dts) {
1479
                sample = current_sample;
1480
                best_dts = dts;
1481
                sc = msc;
1482
            }
1483
        }
1484
    }
1485
    if (!sample)
1486
        return -1;
1487
    /* must be done just before reading, to avoid infinite loop on sample */
1488
    sc->current_sample++;
1489
    if (sample->pos >= url_fsize(&s->pb)) {
1490
        av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n", sc->ffindex, sample->pos);
1491
        return -1;
1492
    }
1493
#ifdef CONFIG_DV_DEMUXER
1494
    if (sc->dv_audio_container) {
1495
        dv_get_packet(mov->dv_demux, pkt);
1496
        dprintf(s, "dv audio pkt size %d\n", pkt->size);
1497
    } else {
1498
#endif
1499
        url_fseek(&s->pb, sample->pos, SEEK_SET);
1500
        av_get_packet(&s->pb, pkt, sample->size);
1501
#ifdef CONFIG_DV_DEMUXER
1502
        if (mov->dv_demux) {
1503
            void *pkt_destruct_func = pkt->destruct;
1504
            dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
1505
            pkt->destruct = pkt_destruct_func;
1506
        }
1507
    }
1508
#endif
1509
    pkt->stream_index = sc->ffindex;
1510
    pkt->dts = sample->timestamp;
1511
    if (sc->ctts_data) {
1512
        assert(sc->ctts_data[sc->sample_to_ctime_index].duration % sc->time_rate == 0);
1513
        pkt->pts = pkt->dts + sc->ctts_data[sc->sample_to_ctime_index].duration / sc->time_rate;
1514
        /* update ctts context */
1515
        sc->sample_to_ctime_sample++;
1516
        if (sc->sample_to_ctime_index < sc->ctts_count && sc->ctts_data[sc->sample_to_ctime_index].count == sc->sample_to_ctime_sample) {
1517
            sc->sample_to_ctime_index++;
1518
            sc->sample_to_ctime_sample = 0;
1519
        }
1520
    } else {
1521
        pkt->pts = pkt->dts;
1522
    }
1523
    pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
1524
    pkt->pos = sample->pos;
1525
    dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n", pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
1526
    return 0;
1527
}
1528

    
1529
static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
1530
{
1531
    MOVStreamContext *sc = st->priv_data;
1532
    int sample, time_sample;
1533
    int i;
1534

    
1535
    sample = av_index_search_timestamp(st, timestamp, flags);
1536
    dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
1537
    if (sample < 0) /* not sure what to do */
1538
        return -1;
1539
    sc->current_sample = sample;
1540
    dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
1541
    /* adjust ctts index */
1542
    if (sc->ctts_data) {
1543
        time_sample = 0;
1544
        for (i = 0; i < sc->ctts_count; i++) {
1545
            time_sample += sc->ctts_data[i].count;
1546
            if (time_sample >= sc->current_sample) {
1547
                sc->sample_to_ctime_index = i;
1548
                sc->sample_to_ctime_sample = time_sample - sc->current_sample;
1549
                break;
1550
            }
1551
        }
1552
    }
1553
    return sample;
1554
}
1555

    
1556
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1557
{
1558
    AVStream *st;
1559
    int64_t seek_timestamp, timestamp;
1560
    int sample;
1561
    int i;
1562

    
1563
    if (stream_index >= s->nb_streams)
1564
        return -1;
1565

    
1566
    st = s->streams[stream_index];
1567
    sample = mov_seek_stream(st, sample_time, flags);
1568
    if (sample < 0)
1569
        return -1;
1570

    
1571
    /* adjust seek timestamp to found sample timestamp */
1572
    seek_timestamp = st->index_entries[sample].timestamp;
1573

    
1574
    for (i = 0; i < s->nb_streams; i++) {
1575
        st = s->streams[i];
1576
        if (stream_index == i || st->discard == AVDISCARD_ALL)
1577
            continue;
1578

    
1579
        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
1580
        mov_seek_stream(st, timestamp, flags);
1581
    }
1582
    return 0;
1583
}
1584

    
1585
static int mov_read_close(AVFormatContext *s)
1586
{
1587
    int i;
1588
    MOVContext *mov = s->priv_data;
1589
    for(i=0; i<mov->total_streams; i++)
1590
        mov_free_stream_context(mov->streams[i]);
1591
    if(mov->dv_demux){
1592
        for(i=0; i<mov->dv_fctx->nb_streams; i++){
1593
            av_freep(&mov->dv_fctx->streams[i]->codec);
1594
            av_freep(&mov->dv_fctx->streams[i]);
1595
        }
1596
        av_freep(&mov->dv_fctx);
1597
        av_freep(&mov->dv_demux);
1598
    }
1599
    return 0;
1600
}
1601

    
1602
AVInputFormat mov_demuxer = {
1603
    "mov,mp4,m4a,3gp,3g2,mj2",
1604
    "QuickTime/MPEG4/Motion JPEG 2000 format",
1605
    sizeof(MOVContext),
1606
    mov_probe,
1607
    mov_read_header,
1608
    mov_read_packet,
1609
    mov_read_close,
1610
    mov_read_seek,
1611
};