Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 3abe5fbd

History | View | Annotate | Download (55.2 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
 *   Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
42
 * - the code is quite ugly... maybe I won't do it recursive next time :-)
43
 *
44
 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
45
 * when coding this :) (it's a writer anyway)
46
 *
47
 * Reference documents:
48
 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
49
 * Apple:
50
 *  http://developer.apple.com/documentation/QuickTime/QTFF/
51
 *  http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
52
 * QuickTime is a trademark of Apple (AFAIK :))
53
 */
54

    
55
#include "qtpalette.h"
56

    
57

    
58
#undef NDEBUG
59
#include <assert.h>
60

    
61
/* the QuickTime file format is quite convoluted...
62
 * it has lots of index tables, each indexing something in another one...
63
 * Here we just use what is needed to read the chunks
64
 */
65

    
66
typedef struct {
67
    int first;
68
    int count;
69
    int id;
70
} MOV_stsc_t;
71

    
72
typedef struct {
73
    uint32_t type;
74
    int64_t offset;
75
    int64_t size; /* total size (excluding the size and type fields) */
76
} MOV_atom_t;
77

    
78
typedef struct {
79
    offset_t offset;
80
    int64_t size;
81
} MOV_mdat_t;
82

    
83
struct MOVParseTableEntry;
84

    
85
typedef struct MOVStreamContext {
86
    int ffindex; /* the ffmpeg stream id */
87
    int next_chunk;
88
    unsigned int chunk_count;
89
    int64_t *chunk_offsets;
90
    unsigned int stts_count;
91
    MOV_stts_t *stts_data;
92
    unsigned int ctts_count;
93
    MOV_stts_t *ctts_data;
94
    unsigned int edit_count; /* number of 'edit' (elst atom) */
95
    unsigned int sample_to_chunk_sz;
96
    MOV_stsc_t *sample_to_chunk;
97
    int sample_to_ctime_index;
98
    int sample_to_ctime_sample;
99
    unsigned int sample_size;
100
    unsigned int sample_count;
101
    int *sample_sizes;
102
    unsigned int keyframe_count;
103
    int *keyframes;
104
    int time_scale;
105
    int time_rate;
106
    int current_sample;
107
    unsigned int bytes_per_frame;
108
    unsigned int samples_per_frame;
109
    int dv_audio_container;
110
} MOVStreamContext;
111

    
112
typedef struct MOVContext {
113
    AVFormatContext *fc;
114
    int time_scale;
115
    int64_t duration; /* duration of the longest track */
116
    int found_moov; /* when both 'moov' and 'mdat' sections has been found */
117
    int found_mdat; /* we suppose we have enough data to read the file */
118
    AVPaletteControl palette_control;
119
    MOV_mdat_t *mdat_list;
120
    int mdat_count;
121
    DVDemuxContext *dv_demux;
122
    AVFormatContext *dv_fctx;
123
    int isom; /* 1 if file is ISO Media (mp4/3gp) */
124
} MOVContext;
125

    
126

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

    
129
/* those functions parse an atom */
130
/* return code:
131
 1: found what I wanted, exit
132
 0: continue to parse next atom
133
 -1: error occured, exit
134
 */
135
/* links atom IDs to parse functions */
136
typedef struct MOVParseTableEntry {
137
    uint32_t type;
138
    int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOV_atom_t atom);
139
} MOVParseTableEntry;
140

    
141
static const MOVParseTableEntry mov_default_parse_table[];
142

    
143
static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
144
{
145
    int64_t total_size = 0;
146
    MOV_atom_t a;
147
    int i;
148
    int err = 0;
149

    
150
    a.offset = atom.offset;
151

    
152
    if (atom.size < 0)
153
        atom.size = INT64_MAX;
154
    while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
155
        a.size = atom.size;
156
        a.type=0;
157
        if(atom.size >= 8) {
158
            a.size = get_be32(pb);
159
            a.type = get_le32(pb);
160
        }
161
        total_size += 8;
162
        a.offset += 8;
163
        dprintf(c->fc, "type: %08x  %.4s  sz: %"PRIx64"  %"PRIx64"   %"PRIx64"\n", a.type, (char*)&a.type, a.size, atom.size, total_size);
164
        if (a.size == 1) { /* 64 bit extended size */
165
            a.size = get_be64(pb) - 8;
166
            a.offset += 8;
167
            total_size += 8;
168
        }
169
        if (a.size == 0) {
170
            a.size = atom.size - total_size;
171
            if (a.size <= 8)
172
                break;
173
        }
174
        a.size -= 8;
175
        if(a.size < 0)
176
            break;
177
        a.size = FFMIN(a.size, atom.size - total_size);
178

    
179
        for (i = 0; mov_default_parse_table[i].type != 0
180
             && mov_default_parse_table[i].type != a.type; i++)
181
            /* empty */;
182

    
183
        if (mov_default_parse_table[i].type == 0) { /* skip leaf atoms data */
184
            url_fskip(pb, a.size);
185
        } else {
186
            offset_t start_pos = url_ftell(pb);
187
            int64_t left;
188
            err = mov_default_parse_table[i].parse(c, pb, a);
189
            if (c->found_moov && c->found_mdat)
190
                break;
191
            left = a.size - url_ftell(pb) + start_pos;
192
            if (left > 0) /* skip garbage at atom end */
193
                url_fskip(pb, left);
194
        }
195

    
196
        a.offset += a.size;
197
        total_size += a.size;
198
    }
199

    
200
    if (!err && total_size < atom.size && atom.size < 0x7ffff) {
201
        url_fskip(pb, atom.size - total_size);
202
    }
203

    
204
    return err;
205
}
206

    
207
static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
208
{
209
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
210
    uint32_t type;
211
    uint32_t ctype;
212

    
213
    get_byte(pb); /* version */
214
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
215

    
216
    /* component type */
217
    ctype = get_le32(pb);
218
    type = get_le32(pb); /* component subtype */
219

    
220
    dprintf(c->fc, "ctype= %c%c%c%c (0x%08x)\n", *((char *)&ctype), ((char *)&ctype)[1], ((char *)&ctype)[2], ((char *)&ctype)[3], (int) ctype);
221
    dprintf(c->fc, "stype= %c%c%c%c\n", *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
222
    if(!ctype)
223
        c->isom = 1;
224
    if(type == MKTAG('v', 'i', 'd', 'e'))
225
        st->codec->codec_type = CODEC_TYPE_VIDEO;
226
    else if(type == MKTAG('s', 'o', 'u', 'n'))
227
        st->codec->codec_type = CODEC_TYPE_AUDIO;
228
    else if(type == MKTAG('m', '1', 'a', ' '))
229
        st->codec->codec_id = CODEC_ID_MP2;
230
    else if(type == MKTAG('s', 'u', 'b', 'p')) {
231
        st->codec->codec_type = CODEC_TYPE_SUBTITLE;
232
        st->codec->codec_id = CODEC_ID_DVD_SUBTITLE;
233
    }
234
    get_be32(pb); /* component  manufacture */
235
    get_be32(pb); /* component flags */
236
    get_be32(pb); /* component flags mask */
237

    
238
    if(atom.size <= 24)
239
        return 0; /* nothing left to read */
240

    
241
    url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
242
    return 0;
243
}
244

    
245
static int mp4_read_descr_len(ByteIOContext *pb)
246
{
247
    int len = 0;
248
    int count = 4;
249
    while (count--) {
250
        int c = get_byte(pb);
251
        len = (len << 7) | (c & 0x7f);
252
        if (!(c & 0x80))
253
            break;
254
    }
255
    return len;
256
}
257

    
258
static int mp4_read_descr(MOVContext *c, ByteIOContext *pb, int *tag)
259
{
260
    int len;
261
    *tag = get_byte(pb);
262
    len = mp4_read_descr_len(pb);
263
    dprintf(c->fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
264
    return len;
265
}
266

    
267
#define MP4ESDescrTag                   0x03
268
#define MP4DecConfigDescrTag            0x04
269
#define MP4DecSpecificDescrTag          0x05
270

    
271
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
272
{
273
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
274
    int tag, len;
275

    
276
    get_be32(pb); /* version + flags */
277
    len = mp4_read_descr(c, pb, &tag);
278
    if (tag == MP4ESDescrTag) {
279
        get_be16(pb); /* ID */
280
        get_byte(pb); /* priority */
281
    } else
282
        get_be16(pb); /* ID */
283

    
284
    len = mp4_read_descr(c, pb, &tag);
285
    if (tag == MP4DecConfigDescrTag) {
286
        int object_type_id = get_byte(pb);
287
        get_byte(pb); /* stream type */
288
        get_be24(pb); /* buffer size db */
289
        get_be32(pb); /* max bitrate */
290
        get_be32(pb); /* avg bitrate */
291

    
292
        st->codec->codec_id= codec_get_id(ff_mp4_obj_type, object_type_id);
293
        dprintf(c->fc, "esds object type id %d\n", object_type_id);
294
        len = mp4_read_descr(c, pb, &tag);
295
        if (tag == MP4DecSpecificDescrTag) {
296
            dprintf(c->fc, "Specific MPEG4 header len=%d\n", len);
297
            st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
298
            if (st->codec->extradata) {
299
                get_buffer(pb, st->codec->extradata, len);
300
                st->codec->extradata_size = len;
301
                /* from mplayer */
302
                if ((*st->codec->extradata >> 3) == 29) {
303
                    st->codec->codec_id = CODEC_ID_MP3ON4;
304
                }
305
            }
306
        }
307
    }
308
    return 0;
309
}
310

    
311
/* this atom contains actual media data */
312
static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
313
{
314
    if(atom.size == 0) /* wrong one (MP4) */
315
        return 0;
316
    c->mdat_list = av_realloc(c->mdat_list, (c->mdat_count + 1) * sizeof(*c->mdat_list));
317
    c->mdat_list[c->mdat_count].offset = atom.offset;
318
    c->mdat_list[c->mdat_count].size = atom.size;
319
    c->mdat_count++;
320
    c->found_mdat=1;
321
    if(c->found_moov)
322
        return 1; /* found both, just go */
323
    url_fskip(pb, atom.size);
324
    return 0; /* now go for moov */
325
}
326

    
327
static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
328
{
329
    uint32_t type = get_le32(pb);
330

    
331
    if (type != MKTAG('q','t',' ',' '))
332
        c->isom = 1;
333
    av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
334
    get_be32(pb); /* minor version */
335
    url_fskip(pb, atom.size - 8);
336
    return 0;
337
}
338

    
339
/* this atom should contain all header atoms */
340
static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
341
{
342
    if (mov_read_default(c, pb, atom) < 0)
343
        return -1;
344
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
345
    /* so we don't parse the whole file if over a network */
346
    c->found_moov=1;
347
    if(c->found_mdat)
348
        return 1; /* found both, just go */
349
    return 0; /* now go for mdat */
350
}
351

    
352

    
353
static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
354
{
355
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
356
    MOVStreamContext *sc = st->priv_data;
357
    int version = get_byte(pb);
358
    int lang;
359

    
360
    if (version > 1)
361
        return 1; /* unsupported */
362

    
363
    get_byte(pb); get_byte(pb);
364
    get_byte(pb); /* flags */
365

    
366
    if (version == 1) {
367
        get_be64(pb);
368
        get_be64(pb);
369
    } else {
370
        get_be32(pb); /* creation time */
371
        get_be32(pb); /* modification time */
372
    }
373

    
374
    sc->time_scale = get_be32(pb);
375
    st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
376

    
377
    lang = get_be16(pb); /* language */
378
    ff_mov_lang_to_iso639(lang, st->language);
379
    get_be16(pb); /* quality */
380

    
381
    return 0;
382
}
383

    
384
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
385
{
386
    int version = get_byte(pb); /* version */
387
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
388

    
389
    if (version == 1) {
390
        get_be64(pb);
391
        get_be64(pb);
392
    } else {
393
        get_be32(pb); /* creation time */
394
        get_be32(pb); /* modification time */
395
    }
396
    c->time_scale = get_be32(pb); /* time scale */
397

    
398
    dprintf(c->fc, "time scale = %i\n", c->time_scale);
399

    
400
    c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
401
    get_be32(pb); /* preferred scale */
402

    
403
    get_be16(pb); /* preferred volume */
404

    
405
    url_fskip(pb, 10); /* reserved */
406

    
407
    url_fskip(pb, 36); /* display matrix */
408

    
409
    get_be32(pb); /* preview time */
410
    get_be32(pb); /* preview duration */
411
    get_be32(pb); /* poster time */
412
    get_be32(pb); /* selection time */
413
    get_be32(pb); /* selection duration */
414
    get_be32(pb); /* current time */
415
    get_be32(pb); /* next track ID */
416

    
417
    return 0;
418
}
419

    
420
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
421
{
422
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
423

    
424
    if((uint64_t)atom.size > (1<<30))
425
        return -1;
426

    
427
    // currently SVQ3 decoder expect full STSD header - so let's fake it
428
    // this should be fixed and just SMI header should be passed
429
    av_free(st->codec->extradata);
430
    st->codec->extradata_size = 0x5a + atom.size;
431
    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
432

    
433
    if (st->codec->extradata) {
434
        memcpy(st->codec->extradata, "SVQ3", 4); // fake
435
        get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
436
        dprintf(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
437
    } else
438
        url_fskip(pb, atom.size);
439

    
440
    return 0;
441
}
442

    
443
static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
444
{
445
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
446
    int little_endian = get_be16(pb);
447

    
448
    if (little_endian) {
449
        switch (st->codec->codec_id) {
450
        case CODEC_ID_PCM_S24BE:
451
            st->codec->codec_id = CODEC_ID_PCM_S24LE;
452
            break;
453
        case CODEC_ID_PCM_S32BE:
454
            st->codec->codec_id = CODEC_ID_PCM_S32LE;
455
            break;
456
        default:
457
            break;
458
        }
459
    }
460
    return 0;
461
}
462

    
463
/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
464
static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
465
{
466
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
467
    uint64_t size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
468
    uint8_t *buf;
469
    if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
470
        return -1;
471
    buf= av_realloc(st->codec->extradata, size);
472
    if(!buf)
473
        return -1;
474
    st->codec->extradata= buf;
475
    buf+= st->codec->extradata_size;
476
    st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
477
    AV_WB32(       buf    , atom.size + 8);
478
    AV_WL32(       buf + 4, atom.type);
479
    get_buffer(pb, buf + 8, atom.size);
480
    return 0;
481
}
482

    
483
static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
484
{
485
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
486

    
487
    if((uint64_t)atom.size > (1<<30))
488
        return -1;
489

    
490
    if (st->codec->codec_id == CODEC_ID_QDM2) {
491
        // pass all frma atom to codec, needed at least for QDM2
492
        av_free(st->codec->extradata);
493
        st->codec->extradata_size = atom.size;
494
        st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
495

    
496
        if (st->codec->extradata) {
497
            get_buffer(pb, st->codec->extradata, atom.size);
498
        } else
499
            url_fskip(pb, atom.size);
500
    } else if (atom.size > 8) { /* to read frma, esds atoms */
501
        if (mov_read_default(c, pb, atom) < 0)
502
            return -1;
503
    } else
504
        url_fskip(pb, atom.size);
505
    return 0;
506
}
507

    
508
/**
509
 * This function reads atom content and puts data in extradata without tag
510
 * nor size unlike mov_read_extradata.
511
 */
512
static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
513
{
514
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
515

    
516
    if((uint64_t)atom.size > (1<<30))
517
        return -1;
518

    
519
    av_free(st->codec->extradata);
520

    
521
    st->codec->extradata_size = atom.size;
522
    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
523

    
524
    if (st->codec->extradata) {
525
        get_buffer(pb, st->codec->extradata, atom.size);
526
    } else
527
        url_fskip(pb, atom.size);
528

    
529
    return 0;
530
}
531

    
532
static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
533
{
534
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
535
    MOVStreamContext *sc = st->priv_data;
536
    unsigned int i, entries;
537

    
538
    get_byte(pb); /* version */
539
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
540

    
541
    entries = get_be32(pb);
542

    
543
    if(entries >= UINT_MAX/sizeof(int64_t))
544
        return -1;
545

    
546
    sc->chunk_count = entries;
547
    sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
548
    if (!sc->chunk_offsets)
549
        return -1;
550
    if (atom.type == MKTAG('s', 't', 'c', 'o')) {
551
        for(i=0; i<entries; i++) {
552
            sc->chunk_offsets[i] = get_be32(pb);
553
        }
554
    } else if (atom.type == MKTAG('c', 'o', '6', '4')) {
555
        for(i=0; i<entries; i++) {
556
            sc->chunk_offsets[i] = get_be64(pb);
557
        }
558
    } else
559
        return -1;
560

    
561
    return 0;
562
}
563

    
564
static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
565
{
566
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
567
    MOVStreamContext *sc = st->priv_data;
568
    int entries, frames_per_sample;
569
    uint32_t format;
570
    uint8_t codec_name[32];
571

    
572
    /* for palette traversal */
573
    unsigned int color_depth;
574
    unsigned int color_start;
575
    unsigned int color_count;
576
    unsigned int color_end;
577
    int color_index;
578
    int color_dec;
579
    int color_greyscale;
580
    const uint8_t *color_table;
581
    int j;
582
    unsigned char r, g, b;
583

    
584
    get_byte(pb); /* version */
585
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
586

    
587
    entries = get_be32(pb);
588

    
589
    while(entries--) { //Parsing Sample description table
590
        enum CodecID id;
591
        MOV_atom_t a = { 0, 0, 0 };
592
        offset_t start_pos = url_ftell(pb);
593
        int size = get_be32(pb); /* size */
594
        format = get_le32(pb); /* data format */
595

    
596
        get_be32(pb); /* reserved */
597
        get_be16(pb); /* reserved */
598
        get_be16(pb); /* index */
599

    
600
        if (st->codec->codec_tag) {
601
            /* multiple fourcc, just skip for now */
602
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
603
            continue;
604
        }
605

    
606
        st->codec->codec_tag = format;
607
        id = codec_get_id(codec_movaudio_tags, format);
608
        if (id<=0 && (format&0xFFFF) == 'm' + ('s'<<8))
609
            id = codec_get_id(codec_wav_tags, bswap_32(format)&0xFFFF);
610

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

    
622
        dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n",
623
                size,
624
                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff, (format >> 24) & 0xff,
625
                st->codec->codec_type);
626

    
627
        if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
628
            st->codec->codec_id = id;
629
            get_be16(pb); /* version */
630
            get_be16(pb); /* revision level */
631
            get_be32(pb); /* vendor */
632
            get_be32(pb); /* temporal quality */
633
            get_be32(pb); /* spatial quality */
634

    
635
            st->codec->width = get_be16(pb); /* width */
636
            st->codec->height = get_be16(pb); /* height */
637

    
638
            get_be32(pb); /* horiz resolution */
639
            get_be32(pb); /* vert resolution */
640
            get_be32(pb); /* data size, always 0 */
641
            frames_per_sample = get_be16(pb); /* frames per samples */
642

    
643
            dprintf(c->fc, "frames/samples = %d\n", frames_per_sample);
644

    
645
            get_buffer(pb, codec_name, 32); /* codec name, pascal string (FIXME: true for mp4?) */
646
            if (codec_name[0] <= 31) {
647
                memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
648
                st->codec->codec_name[codec_name[0]] = 0;
649
            }
650

    
651
            st->codec->bits_per_sample = get_be16(pb); /* depth */
652
            st->codec->color_table_id = get_be16(pb); /* colortable id */
653

    
654
            /* figure out the palette situation */
655
            color_depth = st->codec->bits_per_sample & 0x1F;
656
            color_greyscale = st->codec->bits_per_sample & 0x20;
657

    
658
            /* if the depth is 2, 4, or 8 bpp, file is palettized */
659
            if ((color_depth == 2) || (color_depth == 4) ||
660
                (color_depth == 8)) {
661
                if (color_greyscale) {
662
                    /* compute the greyscale palette */
663
                    color_count = 1 << color_depth;
664
                    color_index = 255;
665
                    color_dec = 256 / (color_count - 1);
666
                    for (j = 0; j < color_count; j++) {
667
                        r = g = b = color_index;
668
                        c->palette_control.palette[j] =
669
                            (r << 16) | (g << 8) | (b);
670
                        color_index -= color_dec;
671
                        if (color_index < 0)
672
                            color_index = 0;
673
                    }
674
                } else if (st->codec->color_table_id & 0x08) {
675
                    /* if flag bit 3 is set, use the default palette */
676
                    color_count = 1 << color_depth;
677
                    if (color_depth == 2)
678
                        color_table = ff_qt_default_palette_4;
679
                    else if (color_depth == 4)
680
                        color_table = ff_qt_default_palette_16;
681
                    else
682
                        color_table = ff_qt_default_palette_256;
683

    
684
                    for (j = 0; j < color_count; j++) {
685
                        r = color_table[j * 4 + 0];
686
                        g = color_table[j * 4 + 1];
687
                        b = color_table[j * 4 + 2];
688
                        c->palette_control.palette[j] =
689
                            (r << 16) | (g << 8) | (b);
690
                    }
691
                } else {
692
                    /* load the palette from the file */
693
                    color_start = get_be32(pb);
694
                    color_count = get_be16(pb);
695
                    color_end = get_be16(pb);
696
                    if ((color_start <= 255) &&
697
                        (color_end <= 255)) {
698
                        for (j = color_start; j <= color_end; j++) {
699
                            /* each R, G, or B component is 16 bits;
700
                             * only use the top 8 bits; skip alpha bytes
701
                             * up front */
702
                            get_byte(pb);
703
                            get_byte(pb);
704
                            r = get_byte(pb);
705
                            get_byte(pb);
706
                            g = get_byte(pb);
707
                            get_byte(pb);
708
                            b = get_byte(pb);
709
                            get_byte(pb);
710
                            c->palette_control.palette[j] =
711
                                (r << 16) | (g << 8) | (b);
712
                        }
713
                    }
714
                }
715
                st->codec->palctrl = &c->palette_control;
716
                st->codec->palctrl->palette_changed = 1;
717
            } else
718
                st->codec->palctrl = NULL;
719
        } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
720
            int bits_per_sample;
721
            uint16_t version = get_be16(pb);
722

    
723
            st->codec->codec_id = id;
724
            get_be16(pb); /* revision level */
725
            get_be32(pb); /* vendor */
726

    
727
            st->codec->channels = get_be16(pb);             /* channel count */
728
            dprintf(c->fc, "audio channels %d\n", st->codec->channels);
729
            st->codec->bits_per_sample = get_be16(pb);      /* sample size */
730
            /* do we need to force to 16 for AMR ? */
731

    
732
            /* handle specific s8 codec */
733
            get_be16(pb); /* compression id = 0*/
734
            get_be16(pb); /* packet size = 0 */
735

    
736
            st->codec->sample_rate = ((get_be32(pb) >> 16));
737

    
738
            switch (st->codec->codec_id) {
739
            case CODEC_ID_PCM_S8:
740
            case CODEC_ID_PCM_U8:
741
                if (st->codec->bits_per_sample == 16)
742
                    st->codec->codec_id = CODEC_ID_PCM_S16BE;
743
                break;
744
            case CODEC_ID_PCM_S16LE:
745
            case CODEC_ID_PCM_S16BE:
746
                if (st->codec->bits_per_sample == 8)
747
                    st->codec->codec_id = CODEC_ID_PCM_S8;
748
                else if (st->codec->bits_per_sample == 24)
749
                    st->codec->codec_id = CODEC_ID_PCM_S24BE;
750
                break;
751
            default:
752
                break;
753
            }
754

    
755
            //Read QT version 1 fields. In version 0 these do not exist.
756
            dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
757
            if(!c->isom) {
758
                if(version==1) {
759
                    sc->samples_per_frame = get_be32(pb);
760
                    get_be32(pb); /* bytes per packet */
761
                    sc->bytes_per_frame = get_be32(pb);
762
                    get_be32(pb); /* bytes per sample */
763
                } else if(version==2) {
764
                    get_be32(pb); /* sizeof struct only */
765
                    st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
766
                    st->codec->channels = get_be32(pb);
767
                    get_be32(pb); /* always 0x7F000000 */
768
                    get_be32(pb); /* bits per channel if sound is uncompressed */
769
                    get_be32(pb); /* lcpm format specific flag */
770
                    get_be32(pb); /* bytes per audio packet if constant */
771
                    get_be32(pb); /* lpcm frames per audio packet if constant */
772
                }
773
            }
774

    
775
            bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
776
            if (bits_per_sample) {
777
                st->codec->bits_per_sample = bits_per_sample;
778
                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
779
            }
780
        } else {
781
            /* other codec type, just skip (rtp, mp4s, tmcd ...) */
782
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
783
        }
784
        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
785
        a.size = size - (url_ftell(pb) - start_pos);
786
        if (a.size > 8) {
787
            if (mov_read_default(c, pb, a) < 0)
788
                return -1;
789
        } else if (a.size > 0)
790
            url_fskip(pb, a.size);
791
    }
792

    
793
    if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1) {
794
        st->codec->sample_rate= sc->time_scale;
795
    }
796

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

    
854
    return 0;
855
}
856

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

    
863
    get_byte(pb); /* version */
864
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
865

    
866
    entries = get_be32(pb);
867

    
868
    if(entries >= UINT_MAX / sizeof(MOV_stsc_t))
869
        return -1;
870

    
871
    dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
872

    
873
    sc->sample_to_chunk_sz = entries;
874
    sc->sample_to_chunk = av_malloc(entries * sizeof(MOV_stsc_t));
875
    if (!sc->sample_to_chunk)
876
        return -1;
877
    for(i=0; i<entries; i++) {
878
        sc->sample_to_chunk[i].first = get_be32(pb);
879
        sc->sample_to_chunk[i].count = get_be32(pb);
880
        sc->sample_to_chunk[i].id = get_be32(pb);
881
    }
882
    return 0;
883
}
884

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

    
891
    get_byte(pb); /* version */
892
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
893

    
894
    entries = get_be32(pb);
895

    
896
    if(entries >= UINT_MAX / sizeof(int))
897
        return -1;
898

    
899
    sc->keyframe_count = entries;
900

    
901
    dprintf(c->fc, "keyframe_count = %d\n", sc->keyframe_count);
902

    
903
    sc->keyframes = av_malloc(entries * sizeof(int));
904
    if (!sc->keyframes)
905
        return -1;
906
    for(i=0; i<entries; i++) {
907
        sc->keyframes[i] = get_be32(pb);
908
        //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
909
    }
910
    return 0;
911
}
912

    
913
static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
914
{
915
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
916
    MOVStreamContext *sc = st->priv_data;
917
    unsigned int i, entries, sample_size;
918

    
919
    get_byte(pb); /* version */
920
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
921

    
922
    sample_size = get_be32(pb);
923
    if (!sc->sample_size) /* do not overwrite value computed in stsd */
924
        sc->sample_size = sample_size;
925
    entries = get_be32(pb);
926
    if(entries >= UINT_MAX / sizeof(int))
927
        return -1;
928

    
929
    sc->sample_count = entries;
930
    if (sample_size)
931
        return 0;
932

    
933
    dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, sc->sample_count);
934

    
935
    sc->sample_sizes = av_malloc(entries * sizeof(int));
936
    if (!sc->sample_sizes)
937
        return -1;
938
    for(i=0; i<entries; i++) {
939
        sc->sample_sizes[i] = get_be32(pb);
940
        dprintf(c->fc, "sample_sizes[]=%d\n", sc->sample_sizes[i]);
941
    }
942
    return 0;
943
}
944

    
945
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
946
{
947
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
948
    MOVStreamContext *sc = st->priv_data;
949
    unsigned int i, entries;
950
    int64_t duration=0;
951
    int64_t total_sample_count=0;
952

    
953
    get_byte(pb); /* version */
954
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
955
    entries = get_be32(pb);
956
    if(entries >= UINT_MAX / sizeof(MOV_stts_t))
957
        return -1;
958

    
959
    sc->stts_count = entries;
960
    sc->stts_data = av_malloc(entries * sizeof(MOV_stts_t));
961
    if (!sc->stts_data)
962
        return -1;
963
    dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
964

    
965
    sc->time_rate=0;
966

    
967
    for(i=0; i<entries; i++) {
968
        int sample_duration;
969
        int sample_count;
970

    
971
        sample_count=get_be32(pb);
972
        sample_duration = get_be32(pb);
973
        sc->stts_data[i].count= sample_count;
974
        sc->stts_data[i].duration= sample_duration;
975

    
976
        sc->time_rate= ff_gcd(sc->time_rate, sample_duration);
977

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

    
980
        duration+=(int64_t)sample_duration*sample_count;
981
        total_sample_count+=sample_count;
982
    }
983

    
984
    st->nb_frames= total_sample_count;
985
    if(duration)
986
        st->duration= duration;
987
    return 0;
988
}
989

    
990
static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
991
{
992
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
993
    MOVStreamContext *sc = st->priv_data;
994
    unsigned int i, entries;
995

    
996
    get_byte(pb); /* version */
997
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
998
    entries = get_be32(pb);
999
    if(entries >= UINT_MAX / sizeof(MOV_stts_t))
1000
        return -1;
1001

    
1002
    sc->ctts_count = entries;
1003
    sc->ctts_data = av_malloc(entries * sizeof(MOV_stts_t));
1004
    if (!sc->ctts_data)
1005
        return -1;
1006
    dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1007

    
1008
    for(i=0; i<entries; i++) {
1009
        int count    =get_be32(pb);
1010
        int duration =get_be32(pb);
1011

    
1012
        if (duration < 0) {
1013
            av_log(c->fc, AV_LOG_ERROR, "negative ctts, ignoring\n");
1014
            sc->ctts_count = 0;
1015
            url_fskip(pb, 8 * (entries - i - 1));
1016
            break;
1017
        }
1018
        sc->ctts_data[i].count   = count;
1019
        sc->ctts_data[i].duration= duration;
1020

    
1021
        sc->time_rate= ff_gcd(sc->time_rate, duration);
1022
    }
1023
    return 0;
1024
}
1025

    
1026
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1027
{
1028
    AVStream *st;
1029
    MOVStreamContext *sc;
1030

    
1031
    st = av_new_stream(c->fc, c->fc->nb_streams);
1032
    if (!st) return -2;
1033
    sc = av_mallocz(sizeof(MOVStreamContext));
1034
    if (!sc) {
1035
        av_free(st);
1036
        return -1;
1037
    }
1038

    
1039
    st->priv_data = sc;
1040
    st->codec->codec_type = CODEC_TYPE_DATA;
1041
    st->start_time = 0; /* XXX: check */
1042

    
1043
    return mov_read_default(c, pb, atom);
1044
}
1045

    
1046
static void mov_parse_udta_string(ByteIOContext *pb, char *str, int size)
1047
{
1048
    uint16_t str_size = get_be16(pb); /* string length */;
1049

    
1050
    get_be16(pb); /* skip language */
1051
    get_buffer(pb, str, FFMIN(size, str_size));
1052
}
1053

    
1054
static int mov_read_udta(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1055
{
1056
    uint64_t end = url_ftell(pb) + atom.size;
1057

    
1058
    while (url_ftell(pb) + 8 < end) {
1059
        uint32_t tag_size = get_be32(pb);
1060
        uint32_t tag      = get_le32(pb);
1061
        uint64_t next     = url_ftell(pb) + tag_size - 8;
1062

    
1063
        if (next > end) // stop if tag_size is wrong
1064
            break;
1065

    
1066
        switch (tag) {
1067
        case MKTAG(0xa9,'n','a','m'):
1068
            mov_parse_udta_string(pb, c->fc->title,     sizeof(c->fc->title));
1069
            break;
1070
        case MKTAG(0xa9,'w','r','t'):
1071
            mov_parse_udta_string(pb, c->fc->author,    sizeof(c->fc->author));
1072
            break;
1073
        case MKTAG(0xa9,'c','p','y'):
1074
            mov_parse_udta_string(pb, c->fc->copyright, sizeof(c->fc->copyright));
1075
            break;
1076
        case MKTAG(0xa9,'i','n','f'):
1077
            mov_parse_udta_string(pb, c->fc->comment,   sizeof(c->fc->comment));
1078
            break;
1079
        default:
1080
            break;
1081
        }
1082

    
1083
        url_fseek(pb, next, SEEK_SET);
1084
    }
1085

    
1086
    return 0;
1087
}
1088

    
1089
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1090
{
1091
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1092
    int version = get_byte(pb);
1093

    
1094
    get_byte(pb); get_byte(pb);
1095
    get_byte(pb); /* flags */
1096
    /*
1097
    MOV_TRACK_ENABLED 0x0001
1098
    MOV_TRACK_IN_MOVIE 0x0002
1099
    MOV_TRACK_IN_PREVIEW 0x0004
1100
    MOV_TRACK_IN_POSTER 0x0008
1101
    */
1102

    
1103
    if (version == 1) {
1104
        get_be64(pb);
1105
        get_be64(pb);
1106
    } else {
1107
        get_be32(pb); /* creation time */
1108
        get_be32(pb); /* modification time */
1109
    }
1110
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1111
    get_be32(pb); /* reserved */
1112
    st->start_time = 0; /* check */
1113
    (version == 1) ? get_be64(pb) : get_be32(pb); /* highlevel (considering edits) duration in movie timebase */
1114
    get_be32(pb); /* reserved */
1115
    get_be32(pb); /* reserved */
1116

    
1117
    get_be16(pb); /* layer */
1118
    get_be16(pb); /* alternate group */
1119
    get_be16(pb); /* volume */
1120
    get_be16(pb); /* reserved */
1121

    
1122
    url_fskip(pb, 36); /* display matrix */
1123

    
1124
    /* those are fixed-point */
1125
    get_be32(pb); /* track width */
1126
    get_be32(pb); /* track height */
1127

    
1128
    return 0;
1129
}
1130

    
1131
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1132
/* like the files created with Adobe Premiere 5.0, for samples see */
1133
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1134
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1135
{
1136
    int err;
1137

    
1138
    if (atom.size < 8)
1139
        return 0; /* continue */
1140
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1141
        url_fskip(pb, atom.size - 4);
1142
        return 0;
1143
    }
1144
    atom.type = get_le32(pb);
1145
    atom.offset += 8;
1146
    atom.size -= 8;
1147
    if (atom.type != MKTAG('m', 'd', 'a', 't')) {
1148
        url_fskip(pb, atom.size);
1149
        return 0;
1150
    }
1151
    err = mov_read_mdat(c, pb, atom);
1152
    return err;
1153
}
1154

    
1155
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1156
{
1157
#ifdef CONFIG_ZLIB
1158
    ByteIOContext ctx;
1159
    uint8_t *cmov_data;
1160
    uint8_t *moov_data; /* uncompressed data */
1161
    long cmov_len, moov_len;
1162
    int ret;
1163

    
1164
    get_be32(pb); /* dcom atom */
1165
    if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
1166
        return -1;
1167
    if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
1168
        av_log(NULL, AV_LOG_ERROR, "unknown compression for cmov atom !");
1169
        return -1;
1170
    }
1171
    get_be32(pb); /* cmvd atom */
1172
    if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
1173
        return -1;
1174
    moov_len = get_be32(pb); /* uncompressed size */
1175
    cmov_len = atom.size - 6 * 4;
1176

    
1177
    cmov_data = av_malloc(cmov_len);
1178
    if (!cmov_data)
1179
        return -1;
1180
    moov_data = av_malloc(moov_len);
1181
    if (!moov_data) {
1182
        av_free(cmov_data);
1183
        return -1;
1184
    }
1185
    get_buffer(pb, cmov_data, cmov_len);
1186
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1187
        return -1;
1188
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
1189
        return -1;
1190
    atom.type = MKTAG( 'm', 'o', 'o', 'v' );
1191
    atom.offset = 0;
1192
    atom.size = moov_len;
1193
#ifdef DEBUG
1194
//    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1195
#endif
1196
    ret = mov_read_default(c, &ctx, atom);
1197
    av_free(moov_data);
1198
    av_free(cmov_data);
1199
    return ret;
1200
#else
1201
    av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
1202
    return -1;
1203
#endif
1204
}
1205

    
1206
/* edit list atom */
1207
static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1208
{
1209
    MOVStreamContext *sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
1210
    int i, edit_count;
1211

    
1212
    get_byte(pb); /* version */
1213
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1214
    edit_count= sc->edit_count = get_be32(pb);     /* entries */
1215

    
1216
    for(i=0; i<edit_count; i++){
1217
        get_be32(pb); /* Track duration */
1218
        get_be32(pb); /* Media time */
1219
        get_be32(pb); /* Media rate */
1220
    }
1221
    dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, sc->edit_count);
1222
    return 0;
1223
}
1224

    
1225
static const MOVParseTableEntry mov_default_parse_table[] = {
1226
/* mp4 atoms */
1227
{ MKTAG( 'c', 'o', '6', '4' ), mov_read_stco },
1228
{ MKTAG( 'c', 't', 't', 's' ), mov_read_ctts }, /* composition time to sample */
1229
{ MKTAG( 'e', 'd', 't', 's' ), mov_read_default },
1230
{ MKTAG( 'e', 'l', 's', 't' ), mov_read_elst },
1231
{ MKTAG( 'e', 'n', 'd', 'a' ), mov_read_enda },
1232
{ MKTAG( 'f', 'i', 'e', 'l' ), mov_read_extradata },
1233
{ MKTAG( 'f', 't', 'y', 'p' ), mov_read_ftyp },
1234
{ MKTAG( 'g', 'l', 'b', 'l' ), mov_read_glbl },
1235
{ MKTAG( 'h', 'd', 'l', 'r' ), mov_read_hdlr },
1236
{ MKTAG( 'j', 'p', '2', 'h' ), mov_read_extradata },
1237
{ MKTAG( 'm', 'd', 'a', 't' ), mov_read_mdat },
1238
{ MKTAG( 'm', 'd', 'h', 'd' ), mov_read_mdhd },
1239
{ MKTAG( 'm', 'd', 'i', 'a' ), mov_read_default },
1240
{ MKTAG( 'm', 'i', 'n', 'f' ), mov_read_default },
1241
{ MKTAG( 'm', 'o', 'o', 'v' ), mov_read_moov },
1242
{ MKTAG( 'm', 'v', 'h', 'd' ), mov_read_mvhd },
1243
{ MKTAG( 'S', 'M', 'I', ' ' ), mov_read_smi }, /* Sorenson extension ??? */
1244
{ MKTAG( 'a', 'l', 'a', 'c' ), mov_read_extradata }, /* alac specific atom */
1245
{ MKTAG( 'a', 'v', 'c', 'C' ), mov_read_glbl },
1246
{ MKTAG( 's', 't', 'b', 'l' ), mov_read_default },
1247
{ MKTAG( 's', 't', 'c', 'o' ), mov_read_stco },
1248
{ MKTAG( 's', 't', 's', 'c' ), mov_read_stsc },
1249
{ MKTAG( 's', 't', 's', 'd' ), mov_read_stsd }, /* sample description */
1250
{ MKTAG( 's', 't', 's', 's' ), mov_read_stss }, /* sync sample */
1251
{ MKTAG( 's', 't', 's', 'z' ), mov_read_stsz }, /* sample size */
1252
{ MKTAG( 's', 't', 't', 's' ), mov_read_stts },
1253
{ MKTAG( 't', 'k', 'h', 'd' ), mov_read_tkhd }, /* track header */
1254
{ MKTAG( 't', 'r', 'a', 'k' ), mov_read_trak },
1255
{ MKTAG( 'u', 'd', 't', 'a' ), mov_read_udta },
1256
{ MKTAG( 'w', 'a', 'v', 'e' ), mov_read_wave },
1257
{ MKTAG( 'e', 's', 'd', 's' ), mov_read_esds },
1258
{ MKTAG( 'w', 'i', 'd', 'e' ), mov_read_wide }, /* place holder */
1259
{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_cmov },
1260
{ 0, NULL }
1261
};
1262

    
1263
/* XXX: is it sufficient ? */
1264
static int mov_probe(AVProbeData *p)
1265
{
1266
    unsigned int offset;
1267
    uint32_t tag;
1268
    int score = 0;
1269

    
1270
    /* check file header */
1271
    offset = 0;
1272
    for(;;) {
1273
        /* ignore invalid offset */
1274
        if ((offset + 8) > (unsigned int)p->buf_size)
1275
            return score;
1276
        tag = AV_RL32(p->buf + offset + 4);
1277
        switch(tag) {
1278
        /* check for obvious tags */
1279
        case MKTAG( 'j', 'P', ' ', ' ' ): /* jpeg 2000 signature */
1280
        case MKTAG( 'm', 'o', 'o', 'v' ):
1281
        case MKTAG( 'm', 'd', 'a', 't' ):
1282
        case MKTAG( 'p', 'n', 'o', 't' ): /* detect movs with preview pics like ew.mov and april.mov */
1283
        case MKTAG( 'u', 'd', 't', 'a' ): /* Packet Video PVAuthor adds this and a lot of more junk */
1284
            return AVPROBE_SCORE_MAX;
1285
        /* those are more common words, so rate then a bit less */
1286
        case MKTAG( 'e', 'd', 'i', 'w' ): /* xdcam files have reverted first tags */
1287
        case MKTAG( 'w', 'i', 'd', 'e' ):
1288
        case MKTAG( 'f', 'r', 'e', 'e' ):
1289
        case MKTAG( 'j', 'u', 'n', 'k' ):
1290
        case MKTAG( 'p', 'i', 'c', 't' ):
1291
            return AVPROBE_SCORE_MAX - 5;
1292
        case MKTAG( 'f', 't', 'y', 'p' ):
1293
        case MKTAG( 's', 'k', 'i', 'p' ):
1294
        case MKTAG( 'u', 'u', 'i', 'd' ):
1295
            offset = AV_RB32(p->buf+offset) + offset;
1296
            /* if we only find those cause probedata is too small at least rate them */
1297
            score = AVPROBE_SCORE_MAX - 50;
1298
            break;
1299
        default:
1300
            /* unrecognized tag */
1301
            return score;
1302
        }
1303
    }
1304
    return score;
1305
}
1306

    
1307
static void mov_build_index(MOVContext *mov, AVStream *st)
1308
{
1309
    MOVStreamContext *sc = st->priv_data;
1310
    offset_t current_offset;
1311
    int64_t current_dts = 0;
1312
    unsigned int stts_index = 0;
1313
    unsigned int stsc_index = 0;
1314
    unsigned int stss_index = 0;
1315
    unsigned int i, j, k;
1316

    
1317
    if (sc->sample_sizes || st->codec->codec_type == CODEC_TYPE_VIDEO || sc->dv_audio_container) {
1318
        unsigned int current_sample = 0;
1319
        unsigned int stts_sample = 0;
1320
        unsigned int keyframe, sample_size;
1321
        unsigned int distance = 0;
1322

    
1323
        st->nb_frames = sc->sample_count;
1324
        for (i = 0; i < sc->chunk_count; i++) {
1325
            current_offset = sc->chunk_offsets[i];
1326
            if (stsc_index + 1 < sc->sample_to_chunk_sz && i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1327
                stsc_index++;
1328
            for (j = 0; j < sc->sample_to_chunk[stsc_index].count; j++) {
1329
                if (current_sample >= sc->sample_count) {
1330
                    av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1331
                    goto out;
1332
                }
1333
                keyframe = !sc->keyframe_count || current_sample + 1 == sc->keyframes[stss_index];
1334
                if (keyframe) {
1335
                    distance = 0;
1336
                    if (stss_index + 1 < sc->keyframe_count)
1337
                        stss_index++;
1338
                }
1339
                sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1340
                dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", size %d, distance %d, keyframe %d\n",
1341
                        st->index, current_sample, current_offset, current_dts, sample_size, distance, keyframe);
1342
                av_add_index_entry(st, current_offset, current_dts, sample_size, distance, keyframe ? AVINDEX_KEYFRAME : 0);
1343
                current_offset += sample_size;
1344
                assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
1345
                current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
1346
                distance++;
1347
                stts_sample++;
1348
                current_sample++;
1349
                if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1350
                    stts_sample = 0;
1351
                    stts_index++;
1352
                }
1353
            }
1354
        }
1355
    } else { /* read whole chunk */
1356
        unsigned int chunk_samples, chunk_size, chunk_duration;
1357
        for (i = 0; i < sc->chunk_count; i++) {
1358
            current_offset = sc->chunk_offsets[i];
1359
            if (stsc_index + 1 < sc->sample_to_chunk_sz && i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1360
                stsc_index++;
1361
            chunk_samples = sc->sample_to_chunk[stsc_index].count;
1362
            /* get chunk size */
1363
            if (sc->sample_size > 1 || st->codec->codec_id == CODEC_ID_PCM_U8 || st->codec->codec_id == CODEC_ID_PCM_S8)
1364
                chunk_size = chunk_samples * sc->sample_size;
1365
            else if (sc->samples_per_frame > 0 && (chunk_samples * sc->bytes_per_frame % sc->samples_per_frame == 0))
1366
                chunk_size = chunk_samples * sc->bytes_per_frame / sc->samples_per_frame;
1367
            else { /* workaround to find nearest next chunk offset */
1368
                chunk_size = INT_MAX;
1369
                for (j = 0; j < mov->fc->nb_streams; j++) {
1370
                    MOVStreamContext *msc = mov->fc->streams[j]->priv_data;
1371
                    for (k = msc->next_chunk; k < msc->chunk_count; k++) {
1372
                        if (msc->chunk_offsets[k] > current_offset && msc->chunk_offsets[k] - current_offset < chunk_size) {
1373
                            chunk_size = msc->chunk_offsets[k] - current_offset;
1374
                            msc->next_chunk = k;
1375
                            break;
1376
                        }
1377
                    }
1378
                }
1379
                /* check for last chunk */
1380
                if (chunk_size == INT_MAX)
1381
                    for (j = 0; j < mov->mdat_count; j++) {
1382
                        dprintf(mov->fc, "mdat %d, offset %"PRIx64", size %"PRId64", current offset %"PRIx64"\n",
1383
                                j, mov->mdat_list[j].offset, mov->mdat_list[j].size, current_offset);
1384
                        if (mov->mdat_list[j].offset <= current_offset && mov->mdat_list[j].offset + mov->mdat_list[j].size > current_offset)
1385
                            chunk_size = mov->mdat_list[j].offset + mov->mdat_list[j].size - current_offset;
1386
                    }
1387
                assert(chunk_size != INT_MAX);
1388
                for (j = 0; j < mov->fc->nb_streams; j++) {
1389
                    MOVStreamContext *msc = mov->fc->streams[j]->priv_data;
1390
                    msc->next_chunk = 0;
1391
                }
1392
            }
1393
            av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
1394
            /* get chunk duration */
1395
            chunk_duration = 0;
1396
            while (chunk_samples > 0) {
1397
                if (chunk_samples < sc->stts_data[stts_index].count) {
1398
                    chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1399
                    sc->stts_data[stts_index].count -= chunk_samples;
1400
                    break;
1401
                } else {
1402
                    chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1403
                    chunk_samples -= sc->stts_data[stts_index].count;
1404
                    if (stts_index + 1 < sc->stts_count) {
1405
                        stts_index++;
1406
                    }
1407
                }
1408
            }
1409
            dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", size %d, duration %d\n",
1410
                    st->index, i, current_offset, current_dts, chunk_size, chunk_duration);
1411
            assert(chunk_duration % sc->time_rate == 0);
1412
            current_dts += chunk_duration / sc->time_rate;
1413
        }
1414
    }
1415
 out:
1416
    /* adjust sample count to avindex entries */
1417
    sc->sample_count = st->nb_index_entries;
1418
}
1419

    
1420
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1421
{
1422
    MOVContext *mov = s->priv_data;
1423
    ByteIOContext *pb = s->pb;
1424
    int i, err;
1425
    MOV_atom_t atom = { 0, 0, 0 };
1426

    
1427
    mov->fc = s;
1428

    
1429
    if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1430
        atom.size = url_fsize(pb);
1431
    else
1432
        atom.size = INT64_MAX;
1433

    
1434
    /* check MOV header */
1435
    err = mov_read_default(mov, pb, atom);
1436
    if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
1437
        av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%"PRId64"\n",
1438
                err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1439
        return -1;
1440
    }
1441
    dprintf(mov->fc, "on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1442

    
1443
    for(i=0; i<s->nb_streams; i++) {
1444
        AVStream *st = s->streams[i];
1445
        MOVStreamContext *sc = st->priv_data;
1446
        /* sanity checks */
1447
        if(!sc->stts_count || !sc->chunk_count || !sc->sample_to_chunk_sz ||
1448
           (!sc->sample_size && !sc->sample_count)){
1449
            av_log(s, AV_LOG_ERROR, "missing mandatory atoms, broken header\n");
1450
            sc->sample_count = 0; //ignore track
1451
            continue;
1452
        }
1453
        if(!sc->time_rate)
1454
            sc->time_rate=1;
1455
        if(!sc->time_scale)
1456
            sc->time_scale= mov->time_scale;
1457
        av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
1458

    
1459
        if (st->codec->codec_type == CODEC_TYPE_AUDIO && sc->stts_count == 1)
1460
            st->codec->frame_size = sc->stts_data[0].duration;
1461

    
1462
        if(st->duration != AV_NOPTS_VALUE){
1463
            assert(st->duration % sc->time_rate == 0);
1464
            st->duration /= sc->time_rate;
1465
        }
1466
        sc->ffindex = i;
1467
        mov_build_index(mov, st);
1468
    }
1469

    
1470
    for(i=0; i<s->nb_streams; i++) {
1471
        MOVStreamContext *sc = s->streams[i]->priv_data;
1472
        /* Do not need those anymore. */
1473
        av_freep(&sc->chunk_offsets);
1474
        av_freep(&sc->sample_to_chunk);
1475
        av_freep(&sc->sample_sizes);
1476
        av_freep(&sc->keyframes);
1477
        av_freep(&sc->stts_data);
1478
    }
1479
    av_freep(&mov->mdat_list);
1480
    return 0;
1481
}
1482

    
1483
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1484
{
1485
    MOVContext *mov = s->priv_data;
1486
    MOVStreamContext *sc = 0;
1487
    AVIndexEntry *sample = 0;
1488
    int64_t best_dts = INT64_MAX;
1489
    int i;
1490

    
1491
    for (i = 0; i < s->nb_streams; i++) {
1492
        AVStream *st = s->streams[i];
1493
        MOVStreamContext *msc = st->priv_data;
1494
        if (st->discard != AVDISCARD_ALL && msc->current_sample < msc->sample_count) {
1495
            AVIndexEntry *current_sample = &st->index_entries[msc->current_sample];
1496
            int64_t dts = av_rescale(current_sample->timestamp * (int64_t)msc->time_rate, AV_TIME_BASE, msc->time_scale);
1497
            dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
1498
            if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
1499
                (!url_is_streamed(s->pb) &&
1500
                 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
1501
                  (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))) {
1502
                sample = current_sample;
1503
                best_dts = dts;
1504
                sc = msc;
1505
            }
1506
        }
1507
    }
1508
    if (!sample)
1509
        return -1;
1510
    /* must be done just before reading, to avoid infinite loop on sample */
1511
    sc->current_sample++;
1512
    if (url_fseek(s->pb, sample->pos, SEEK_SET) != sample->pos) {
1513
        av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n", sc->ffindex, sample->pos);
1514
        return -1;
1515
    }
1516
#ifdef CONFIG_DV_DEMUXER
1517
    if (sc->dv_audio_container) {
1518
        dv_get_packet(mov->dv_demux, pkt);
1519
        dprintf(s, "dv audio pkt size %d\n", pkt->size);
1520
    } else {
1521
#endif
1522
        av_get_packet(s->pb, pkt, sample->size);
1523
#ifdef CONFIG_DV_DEMUXER
1524
        if (mov->dv_demux) {
1525
            void *pkt_destruct_func = pkt->destruct;
1526
            dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
1527
            pkt->destruct = pkt_destruct_func;
1528
        }
1529
    }
1530
#endif
1531
    pkt->stream_index = sc->ffindex;
1532
    pkt->dts = sample->timestamp;
1533
    if (sc->ctts_data) {
1534
        assert(sc->ctts_data[sc->sample_to_ctime_index].duration % sc->time_rate == 0);
1535
        pkt->pts = pkt->dts + sc->ctts_data[sc->sample_to_ctime_index].duration / sc->time_rate;
1536
        /* update ctts context */
1537
        sc->sample_to_ctime_sample++;
1538
        if (sc->sample_to_ctime_index < sc->ctts_count && sc->ctts_data[sc->sample_to_ctime_index].count == sc->sample_to_ctime_sample) {
1539
            sc->sample_to_ctime_index++;
1540
            sc->sample_to_ctime_sample = 0;
1541
        }
1542
    } else {
1543
        pkt->pts = pkt->dts;
1544
    }
1545
    pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
1546
    pkt->pos = sample->pos;
1547
    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);
1548
    return 0;
1549
}
1550

    
1551
static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
1552
{
1553
    MOVStreamContext *sc = st->priv_data;
1554
    int sample, time_sample;
1555
    int i;
1556

    
1557
    sample = av_index_search_timestamp(st, timestamp, flags);
1558
    dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
1559
    if (sample < 0) /* not sure what to do */
1560
        return -1;
1561
    sc->current_sample = sample;
1562
    dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
1563
    /* adjust ctts index */
1564
    if (sc->ctts_data) {
1565
        time_sample = 0;
1566
        for (i = 0; i < sc->ctts_count; i++) {
1567
            int next = time_sample + sc->ctts_data[i].count;
1568
            if (next > sc->current_sample) {
1569
                sc->sample_to_ctime_index = i;
1570
                sc->sample_to_ctime_sample = sc->current_sample - time_sample;
1571
                break;
1572
            }
1573
            time_sample = next;
1574
        }
1575
    }
1576
    return sample;
1577
}
1578

    
1579
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1580
{
1581
    AVStream *st;
1582
    int64_t seek_timestamp, timestamp;
1583
    int sample;
1584
    int i;
1585

    
1586
    if (stream_index >= s->nb_streams)
1587
        return -1;
1588

    
1589
    st = s->streams[stream_index];
1590
    sample = mov_seek_stream(st, sample_time, flags);
1591
    if (sample < 0)
1592
        return -1;
1593

    
1594
    /* adjust seek timestamp to found sample timestamp */
1595
    seek_timestamp = st->index_entries[sample].timestamp;
1596

    
1597
    for (i = 0; i < s->nb_streams; i++) {
1598
        st = s->streams[i];
1599
        if (stream_index == i || st->discard == AVDISCARD_ALL)
1600
            continue;
1601

    
1602
        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
1603
        mov_seek_stream(st, timestamp, flags);
1604
    }
1605
    return 0;
1606
}
1607

    
1608
static int mov_read_close(AVFormatContext *s)
1609
{
1610
    int i;
1611
    MOVContext *mov = s->priv_data;
1612
    for(i=0; i<s->nb_streams; i++) {
1613
        MOVStreamContext *sc = s->streams[i]->priv_data;
1614
        av_freep(&sc->ctts_data);
1615
    }
1616
    if(mov->dv_demux){
1617
        for(i=0; i<mov->dv_fctx->nb_streams; i++){
1618
            av_freep(&mov->dv_fctx->streams[i]->codec);
1619
            av_freep(&mov->dv_fctx->streams[i]);
1620
        }
1621
        av_freep(&mov->dv_fctx);
1622
        av_freep(&mov->dv_demux);
1623
    }
1624
    return 0;
1625
}
1626

    
1627
AVInputFormat mov_demuxer = {
1628
    "mov,mp4,m4a,3gp,3g2,mj2",
1629
    "QuickTime/MPEG4/Motion JPEG 2000 format",
1630
    sizeof(MOVContext),
1631
    mov_probe,
1632
    mov_read_header,
1633
    mov_read_packet,
1634
    mov_read_close,
1635
    mov_read_seek,
1636
};