Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 300aa2b0

History | View | Annotate | Download (56.5 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
    int pseudo_stream_id;
111
    int16_t audio_cid; ///< stsd audio compression id
112
} MOVStreamContext;
113

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

    
128

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

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

    
143
static const MOVParseTableEntry mov_default_parse_table[];
144

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

    
152
    a.offset = atom.offset;
153

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

    
182
        for (i = 0; mov_default_parse_table[i].type != 0
183
             && mov_default_parse_table[i].type != a.type; i++)
184
            /* empty */;
185

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

    
199
        a.offset += a.size;
200
        total_size += a.size;
201
    }
202

    
203
    if (!err && total_size < atom.size && atom.size < 0x7ffff) {
204
        url_fskip(pb, atom.size - total_size);
205
    }
206

    
207
    return err;
208
}
209

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

    
216
    get_byte(pb); /* version */
217
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
218

    
219
    /* component type */
220
    ctype = get_le32(pb);
221
    type = get_le32(pb); /* component subtype */
222

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

    
242
    if(atom.size <= 24)
243
        return 0; /* nothing left to read */
244

    
245
    url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
246
    return 0;
247
}
248

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

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

    
271
#define MP4ESDescrTag                   0x03
272
#define MP4DecConfigDescrTag            0x04
273
#define MP4DecSpecificDescrTag          0x05
274

    
275
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
276
{
277
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
278
    int tag, len;
279

    
280
    get_be32(pb); /* version + flags */
281
    len = mp4_read_descr(c, pb, &tag);
282
    if (tag == MP4ESDescrTag) {
283
        get_be16(pb); /* ID */
284
        get_byte(pb); /* priority */
285
    } else
286
        get_be16(pb); /* ID */
287

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

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

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

    
331
static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
332
{
333
    uint32_t type = get_le32(pb);
334

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

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

    
356

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

    
364
    if (version > 1)
365
        return 1; /* unsupported */
366

    
367
    get_byte(pb); get_byte(pb);
368
    get_byte(pb); /* flags */
369

    
370
    if (version == 1) {
371
        get_be64(pb);
372
        get_be64(pb);
373
    } else {
374
        get_be32(pb); /* creation time */
375
        get_be32(pb); /* modification time */
376
    }
377

    
378
    sc->time_scale = get_be32(pb);
379
    st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
380

    
381
    lang = get_be16(pb); /* language */
382
    ff_mov_lang_to_iso639(lang, st->language);
383
    get_be16(pb); /* quality */
384

    
385
    return 0;
386
}
387

    
388
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
389
{
390
    int version = get_byte(pb); /* version */
391
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
392

    
393
    if (version == 1) {
394
        get_be64(pb);
395
        get_be64(pb);
396
    } else {
397
        get_be32(pb); /* creation time */
398
        get_be32(pb); /* modification time */
399
    }
400
    c->time_scale = get_be32(pb); /* time scale */
401

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

    
404
    c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
405
    get_be32(pb); /* preferred scale */
406

    
407
    get_be16(pb); /* preferred volume */
408

    
409
    url_fskip(pb, 10); /* reserved */
410

    
411
    url_fskip(pb, 36); /* display matrix */
412

    
413
    get_be32(pb); /* preview time */
414
    get_be32(pb); /* preview duration */
415
    get_be32(pb); /* poster time */
416
    get_be32(pb); /* selection time */
417
    get_be32(pb); /* selection duration */
418
    get_be32(pb); /* current time */
419
    get_be32(pb); /* next track ID */
420

    
421
    return 0;
422
}
423

    
424
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
425
{
426
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
427

    
428
    if((uint64_t)atom.size > (1<<30))
429
        return -1;
430

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

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

    
444
    return 0;
445
}
446

    
447
static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
448
{
449
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
450
    int little_endian = get_be16(pb);
451

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

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

    
487
static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
488
{
489
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
490

    
491
    if((uint64_t)atom.size > (1<<30))
492
        return -1;
493

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

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

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

    
520
    if((uint64_t)atom.size > (1<<30))
521
        return -1;
522

    
523
    av_free(st->codec->extradata);
524

    
525
    st->codec->extradata_size = atom.size;
526
    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
527

    
528
    if (st->codec->extradata) {
529
        get_buffer(pb, st->codec->extradata, atom.size);
530
    } else
531
        url_fskip(pb, atom.size);
532

    
533
    return 0;
534
}
535

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

    
542
    get_byte(pb); /* version */
543
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
544

    
545
    entries = get_be32(pb);
546

    
547
    if(entries >= UINT_MAX/sizeof(int64_t))
548
        return -1;
549

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

    
565
    return 0;
566
}
567

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

    
576
    /* for palette traversal */
577
    unsigned int color_depth;
578
    unsigned int color_start;
579
    unsigned int color_count;
580
    unsigned int color_end;
581
    int color_index;
582
    int color_dec;
583
    int color_greyscale;
584
    const uint8_t *color_table;
585
    int j, pseudo_stream_id;
586
    unsigned char r, g, b;
587

    
588
    get_byte(pb); /* version */
589
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
590

    
591
    entries = get_be32(pb);
592

    
593
    for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) { //Parsing Sample description table
594
        enum CodecID id;
595
        MOV_atom_t a = { 0, 0, 0 };
596
        offset_t start_pos = url_ftell(pb);
597
        int size = get_be32(pb); /* size */
598
        format = get_le32(pb); /* data format */
599

    
600
        get_be32(pb); /* reserved */
601
        get_be16(pb); /* reserved */
602
        get_be16(pb); /* index */
603

    
604
        if (st->codec->codec_tag &&
605
            (c->fc->video_codec_id ? codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
606
                                   : st->codec->codec_tag != MKTAG('j', 'p', 'e', 'g'))
607
           ){
608
            /* multiple fourcc, we skip jpeg, this isnt correct, we should export it as
609
               seperate AVStream but this needs a few changes in the mov demuxer, patch
610
               welcome */
611
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
612
            continue;
613
        }
614
        sc->pseudo_stream_id= pseudo_stream_id;
615

    
616
        st->codec->codec_tag = format;
617
        id = codec_get_id(codec_movaudio_tags, format);
618
        if (id<=0 && (format&0xFFFF) == 'm' + ('s'<<8))
619
            id = codec_get_id(codec_wav_tags, bswap_32(format)&0xFFFF);
620

    
621
        if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
622
            st->codec->codec_type = CODEC_TYPE_AUDIO;
623
        } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
624
                   format && format != MKTAG('m', 'p', '4', 's')) { /* skip old asf mpeg4 tag */
625
            id = codec_get_id(codec_movvideo_tags, format);
626
            if (id <= 0)
627
                id = codec_get_id(codec_bmp_tags, format);
628
            if (id > 0)
629
                st->codec->codec_type = CODEC_TYPE_VIDEO;
630
            else if(st->codec->codec_type == CODEC_TYPE_DATA){
631
                id = codec_get_id(ff_codec_movsubtitle_tags, format);
632
                if(id > 0)
633
                    st->codec->codec_type = CODEC_TYPE_SUBTITLE;
634
            }
635
        }
636

    
637
        dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
638
                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
639
                (format >> 24) & 0xff, st->codec->codec_type);
640

    
641
        if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
642
            st->codec->codec_id = id;
643
            get_be16(pb); /* version */
644
            get_be16(pb); /* revision level */
645
            get_be32(pb); /* vendor */
646
            get_be32(pb); /* temporal quality */
647
            get_be32(pb); /* spatial quality */
648

    
649
            st->codec->width = get_be16(pb); /* width */
650
            st->codec->height = get_be16(pb); /* height */
651

    
652
            get_be32(pb); /* horiz resolution */
653
            get_be32(pb); /* vert resolution */
654
            get_be32(pb); /* data size, always 0 */
655
            frames_per_sample = get_be16(pb); /* frames per samples */
656

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

    
659
            get_buffer(pb, codec_name, 32); /* codec name, pascal string (FIXME: true for mp4?) */
660
            if (codec_name[0] <= 31) {
661
                memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
662
                st->codec->codec_name[codec_name[0]] = 0;
663
            }
664

    
665
            st->codec->bits_per_sample = get_be16(pb); /* depth */
666
            st->codec->color_table_id = get_be16(pb); /* colortable id */
667

    
668
            /* figure out the palette situation */
669
            color_depth = st->codec->bits_per_sample & 0x1F;
670
            color_greyscale = st->codec->bits_per_sample & 0x20;
671

    
672
            /* if the depth is 2, 4, or 8 bpp, file is palettized */
673
            if ((color_depth == 2) || (color_depth == 4) ||
674
                (color_depth == 8)) {
675
                if (color_greyscale) {
676
                    /* compute the greyscale palette */
677
                    color_count = 1 << color_depth;
678
                    color_index = 255;
679
                    color_dec = 256 / (color_count - 1);
680
                    for (j = 0; j < color_count; j++) {
681
                        r = g = b = color_index;
682
                        c->palette_control.palette[j] =
683
                            (r << 16) | (g << 8) | (b);
684
                        color_index -= color_dec;
685
                        if (color_index < 0)
686
                            color_index = 0;
687
                    }
688
                } else if (st->codec->color_table_id & 0x08) {
689
                    /* if flag bit 3 is set, use the default palette */
690
                    color_count = 1 << color_depth;
691
                    if (color_depth == 2)
692
                        color_table = ff_qt_default_palette_4;
693
                    else if (color_depth == 4)
694
                        color_table = ff_qt_default_palette_16;
695
                    else
696
                        color_table = ff_qt_default_palette_256;
697

    
698
                    for (j = 0; j < color_count; j++) {
699
                        r = color_table[j * 4 + 0];
700
                        g = color_table[j * 4 + 1];
701
                        b = color_table[j * 4 + 2];
702
                        c->palette_control.palette[j] =
703
                            (r << 16) | (g << 8) | (b);
704
                    }
705
                } else {
706
                    /* load the palette from the file */
707
                    color_start = get_be32(pb);
708
                    color_count = get_be16(pb);
709
                    color_end = get_be16(pb);
710
                    if ((color_start <= 255) &&
711
                        (color_end <= 255)) {
712
                        for (j = color_start; j <= color_end; j++) {
713
                            /* each R, G, or B component is 16 bits;
714
                             * only use the top 8 bits; skip alpha bytes
715
                             * up front */
716
                            get_byte(pb);
717
                            get_byte(pb);
718
                            r = get_byte(pb);
719
                            get_byte(pb);
720
                            g = get_byte(pb);
721
                            get_byte(pb);
722
                            b = get_byte(pb);
723
                            get_byte(pb);
724
                            c->palette_control.palette[j] =
725
                                (r << 16) | (g << 8) | (b);
726
                        }
727
                    }
728
                }
729
                st->codec->palctrl = &c->palette_control;
730
                st->codec->palctrl->palette_changed = 1;
731
            } else
732
                st->codec->palctrl = NULL;
733
        } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
734
            int bits_per_sample;
735
            uint16_t version = get_be16(pb);
736

    
737
            st->codec->codec_id = id;
738
            get_be16(pb); /* revision level */
739
            get_be32(pb); /* vendor */
740

    
741
            st->codec->channels = get_be16(pb);             /* channel count */
742
            dprintf(c->fc, "audio channels %d\n", st->codec->channels);
743
            st->codec->bits_per_sample = get_be16(pb);      /* sample size */
744

    
745
            sc->audio_cid = get_be16(pb);
746
            get_be16(pb); /* packet size = 0 */
747

    
748
            st->codec->sample_rate = ((get_be32(pb) >> 16));
749

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

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

    
787
            bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
788
            if (bits_per_sample) {
789
                st->codec->bits_per_sample = bits_per_sample;
790
                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
791
            }
792
        } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){
793
            st->codec->codec_id= id;
794
        } else {
795
            /* other codec type, just skip (rtp, mp4s, tmcd ...) */
796
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
797
        }
798
        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
799
        a.size = size - (url_ftell(pb) - start_pos);
800
        if (a.size > 8) {
801
            if (mov_read_default(c, pb, a) < 0)
802
                return -1;
803
        } else if (a.size > 0)
804
            url_fskip(pb, a.size);
805
    }
806

    
807
    if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1) {
808
        st->codec->sample_rate= sc->time_scale;
809
    }
810

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

    
868
    return 0;
869
}
870

    
871
static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
872
{
873
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
874
    MOVStreamContext *sc = st->priv_data;
875
    unsigned int i, entries;
876

    
877
    get_byte(pb); /* version */
878
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
879

    
880
    entries = get_be32(pb);
881

    
882
    if(entries >= UINT_MAX / sizeof(MOV_stsc_t))
883
        return -1;
884

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

    
887
    sc->sample_to_chunk_sz = entries;
888
    sc->sample_to_chunk = av_malloc(entries * sizeof(MOV_stsc_t));
889
    if (!sc->sample_to_chunk)
890
        return -1;
891
    for(i=0; i<entries; i++) {
892
        sc->sample_to_chunk[i].first = get_be32(pb);
893
        sc->sample_to_chunk[i].count = get_be32(pb);
894
        sc->sample_to_chunk[i].id = get_be32(pb);
895
    }
896
    return 0;
897
}
898

    
899
static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
900
{
901
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
902
    MOVStreamContext *sc = st->priv_data;
903
    unsigned int i, entries;
904

    
905
    get_byte(pb); /* version */
906
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
907

    
908
    entries = get_be32(pb);
909

    
910
    if(entries >= UINT_MAX / sizeof(int))
911
        return -1;
912

    
913
    sc->keyframe_count = entries;
914

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

    
917
    sc->keyframes = av_malloc(entries * sizeof(int));
918
    if (!sc->keyframes)
919
        return -1;
920
    for(i=0; i<entries; i++) {
921
        sc->keyframes[i] = get_be32(pb);
922
        //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
923
    }
924
    return 0;
925
}
926

    
927
static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
928
{
929
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
930
    MOVStreamContext *sc = st->priv_data;
931
    unsigned int i, entries, sample_size;
932

    
933
    get_byte(pb); /* version */
934
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
935

    
936
    sample_size = get_be32(pb);
937
    if (!sc->sample_size) /* do not overwrite value computed in stsd */
938
        sc->sample_size = sample_size;
939
    entries = get_be32(pb);
940
    if(entries >= UINT_MAX / sizeof(int))
941
        return -1;
942

    
943
    sc->sample_count = entries;
944
    if (sample_size)
945
        return 0;
946

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

    
949
    sc->sample_sizes = av_malloc(entries * sizeof(int));
950
    if (!sc->sample_sizes)
951
        return -1;
952
    for(i=0; i<entries; i++) {
953
        sc->sample_sizes[i] = get_be32(pb);
954
        dprintf(c->fc, "sample_sizes[]=%d\n", sc->sample_sizes[i]);
955
    }
956
    return 0;
957
}
958

    
959
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
960
{
961
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
962
    MOVStreamContext *sc = st->priv_data;
963
    unsigned int i, entries;
964
    int64_t duration=0;
965
    int64_t total_sample_count=0;
966

    
967
    get_byte(pb); /* version */
968
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
969
    entries = get_be32(pb);
970
    if(entries >= UINT_MAX / sizeof(MOV_stts_t))
971
        return -1;
972

    
973
    sc->stts_count = entries;
974
    sc->stts_data = av_malloc(entries * sizeof(MOV_stts_t));
975
    if (!sc->stts_data)
976
        return -1;
977
    dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
978

    
979
    sc->time_rate=0;
980

    
981
    for(i=0; i<entries; i++) {
982
        int sample_duration;
983
        int sample_count;
984

    
985
        sample_count=get_be32(pb);
986
        sample_duration = get_be32(pb);
987
        sc->stts_data[i].count= sample_count;
988
        sc->stts_data[i].duration= sample_duration;
989

    
990
        sc->time_rate= ff_gcd(sc->time_rate, sample_duration);
991

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

    
994
        duration+=(int64_t)sample_duration*sample_count;
995
        total_sample_count+=sample_count;
996
    }
997

    
998
    st->nb_frames= total_sample_count;
999
    if(duration)
1000
        st->duration= duration;
1001
    return 0;
1002
}
1003

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

    
1010
    get_byte(pb); /* version */
1011
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1012
    entries = get_be32(pb);
1013
    if(entries >= UINT_MAX / sizeof(MOV_stts_t))
1014
        return -1;
1015

    
1016
    sc->ctts_count = entries;
1017
    sc->ctts_data = av_malloc(entries * sizeof(MOV_stts_t));
1018
    if (!sc->ctts_data)
1019
        return -1;
1020
    dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1021

    
1022
    for(i=0; i<entries; i++) {
1023
        int count    =get_be32(pb);
1024
        int duration =get_be32(pb);
1025

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

    
1035
        sc->time_rate= ff_gcd(sc->time_rate, duration);
1036
    }
1037
    return 0;
1038
}
1039

    
1040
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1041
{
1042
    AVStream *st;
1043
    MOVStreamContext *sc;
1044

    
1045
    st = av_new_stream(c->fc, c->fc->nb_streams);
1046
    if (!st) return -2;
1047
    sc = av_mallocz(sizeof(MOVStreamContext));
1048
    if (!sc) {
1049
        av_free(st);
1050
        return -1;
1051
    }
1052

    
1053
    st->priv_data = sc;
1054
    st->codec->codec_type = CODEC_TYPE_DATA;
1055
    st->start_time = 0; /* XXX: check */
1056

    
1057
    return mov_read_default(c, pb, atom);
1058
}
1059

    
1060
static void mov_parse_udta_string(ByteIOContext *pb, char *str, int size)
1061
{
1062
    uint16_t str_size = get_be16(pb); /* string length */;
1063

    
1064
    get_be16(pb); /* skip language */
1065
    get_buffer(pb, str, FFMIN(size, str_size));
1066
}
1067

    
1068
static int mov_read_udta(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1069
{
1070
    uint64_t end = url_ftell(pb) + atom.size;
1071

    
1072
    while (url_ftell(pb) + 8 < end) {
1073
        uint32_t tag_size = get_be32(pb);
1074
        uint32_t tag      = get_le32(pb);
1075
        uint64_t next     = url_ftell(pb) + tag_size - 8;
1076

    
1077
        if (next > end) // stop if tag_size is wrong
1078
            break;
1079

    
1080
        switch (tag) {
1081
        case MKTAG(0xa9,'n','a','m'):
1082
            mov_parse_udta_string(pb, c->fc->title,     sizeof(c->fc->title));
1083
            break;
1084
        case MKTAG(0xa9,'w','r','t'):
1085
            mov_parse_udta_string(pb, c->fc->author,    sizeof(c->fc->author));
1086
            break;
1087
        case MKTAG(0xa9,'c','p','y'):
1088
            mov_parse_udta_string(pb, c->fc->copyright, sizeof(c->fc->copyright));
1089
            break;
1090
        case MKTAG(0xa9,'i','n','f'):
1091
            mov_parse_udta_string(pb, c->fc->comment,   sizeof(c->fc->comment));
1092
            break;
1093
        default:
1094
            break;
1095
        }
1096

    
1097
        url_fseek(pb, next, SEEK_SET);
1098
    }
1099

    
1100
    return 0;
1101
}
1102

    
1103
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1104
{
1105
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1106
    int version = get_byte(pb);
1107

    
1108
    get_byte(pb); get_byte(pb);
1109
    get_byte(pb); /* flags */
1110
    /*
1111
    MOV_TRACK_ENABLED 0x0001
1112
    MOV_TRACK_IN_MOVIE 0x0002
1113
    MOV_TRACK_IN_PREVIEW 0x0004
1114
    MOV_TRACK_IN_POSTER 0x0008
1115
    */
1116

    
1117
    if (version == 1) {
1118
        get_be64(pb);
1119
        get_be64(pb);
1120
    } else {
1121
        get_be32(pb); /* creation time */
1122
        get_be32(pb); /* modification time */
1123
    }
1124
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1125
    get_be32(pb); /* reserved */
1126
    st->start_time = 0; /* check */
1127
    (version == 1) ? get_be64(pb) : get_be32(pb); /* highlevel (considering edits) duration in movie timebase */
1128
    get_be32(pb); /* reserved */
1129
    get_be32(pb); /* reserved */
1130

    
1131
    get_be16(pb); /* layer */
1132
    get_be16(pb); /* alternate group */
1133
    get_be16(pb); /* volume */
1134
    get_be16(pb); /* reserved */
1135

    
1136
    url_fskip(pb, 36); /* display matrix */
1137

    
1138
    /* those are fixed-point */
1139
    get_be32(pb); /* track width */
1140
    get_be32(pb); /* track height */
1141

    
1142
    return 0;
1143
}
1144

    
1145
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1146
/* like the files created with Adobe Premiere 5.0, for samples see */
1147
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1148
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1149
{
1150
    int err;
1151

    
1152
    if (atom.size < 8)
1153
        return 0; /* continue */
1154
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1155
        url_fskip(pb, atom.size - 4);
1156
        return 0;
1157
    }
1158
    atom.type = get_le32(pb);
1159
    atom.offset += 8;
1160
    atom.size -= 8;
1161
    if (atom.type != MKTAG('m', 'd', 'a', 't')) {
1162
        url_fskip(pb, atom.size);
1163
        return 0;
1164
    }
1165
    err = mov_read_mdat(c, pb, atom);
1166
    return err;
1167
}
1168

    
1169
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1170
{
1171
#ifdef CONFIG_ZLIB
1172
    ByteIOContext ctx;
1173
    uint8_t *cmov_data;
1174
    uint8_t *moov_data; /* uncompressed data */
1175
    long cmov_len, moov_len;
1176
    int ret;
1177

    
1178
    get_be32(pb); /* dcom atom */
1179
    if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
1180
        return -1;
1181
    if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
1182
        av_log(NULL, AV_LOG_ERROR, "unknown compression for cmov atom !");
1183
        return -1;
1184
    }
1185
    get_be32(pb); /* cmvd atom */
1186
    if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
1187
        return -1;
1188
    moov_len = get_be32(pb); /* uncompressed size */
1189
    cmov_len = atom.size - 6 * 4;
1190

    
1191
    cmov_data = av_malloc(cmov_len);
1192
    if (!cmov_data)
1193
        return -1;
1194
    moov_data = av_malloc(moov_len);
1195
    if (!moov_data) {
1196
        av_free(cmov_data);
1197
        return -1;
1198
    }
1199
    get_buffer(pb, cmov_data, cmov_len);
1200
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1201
        return -1;
1202
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
1203
        return -1;
1204
    atom.type = MKTAG( 'm', 'o', 'o', 'v' );
1205
    atom.offset = 0;
1206
    atom.size = moov_len;
1207
#ifdef DEBUG
1208
//    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1209
#endif
1210
    ret = mov_read_default(c, &ctx, atom);
1211
    av_free(moov_data);
1212
    av_free(cmov_data);
1213
    return ret;
1214
#else
1215
    av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
1216
    return -1;
1217
#endif
1218
}
1219

    
1220
/* edit list atom */
1221
static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1222
{
1223
    MOVStreamContext *sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
1224
    int i, edit_count;
1225

    
1226
    get_byte(pb); /* version */
1227
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1228
    edit_count= sc->edit_count = get_be32(pb);     /* entries */
1229

    
1230
    for(i=0; i<edit_count; i++){
1231
        get_be32(pb); /* Track duration */
1232
        get_be32(pb); /* Media time */
1233
        get_be32(pb); /* Media rate */
1234
    }
1235
    dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, sc->edit_count);
1236
    return 0;
1237
}
1238

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

    
1277
/* XXX: is it sufficient ? */
1278
static int mov_probe(AVProbeData *p)
1279
{
1280
    unsigned int offset;
1281
    uint32_t tag;
1282
    int score = 0;
1283

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

    
1321
static void mov_build_index(MOVContext *mov, AVStream *st)
1322
{
1323
    MOVStreamContext *sc = st->priv_data;
1324
    offset_t current_offset;
1325
    int64_t current_dts = 0;
1326
    unsigned int stts_index = 0;
1327
    unsigned int stsc_index = 0;
1328
    unsigned int stss_index = 0;
1329
    unsigned int i, j, k;
1330

    
1331
    if (sc->sample_sizes || st->codec->codec_type == CODEC_TYPE_VIDEO ||
1332
        sc->audio_cid == -2) {
1333
        unsigned int current_sample = 0;
1334
        unsigned int stts_sample = 0;
1335
        unsigned int keyframe, sample_size;
1336
        unsigned int distance = 0;
1337

    
1338
        st->nb_frames = sc->sample_count;
1339
        for (i = 0; i < sc->chunk_count; i++) {
1340
            current_offset = sc->chunk_offsets[i];
1341
            if (stsc_index + 1 < sc->sample_to_chunk_sz &&
1342
                i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1343
                stsc_index++;
1344
            for (j = 0; j < sc->sample_to_chunk[stsc_index].count; j++) {
1345
                if (current_sample >= sc->sample_count) {
1346
                    av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1347
                    goto out;
1348
                }
1349
                keyframe = !sc->keyframe_count || current_sample + 1 == sc->keyframes[stss_index];
1350
                if (keyframe) {
1351
                    distance = 0;
1352
                    if (stss_index + 1 < sc->keyframe_count)
1353
                        stss_index++;
1354
                }
1355
                sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1356
                dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1357
                        "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1358
                        current_offset, current_dts, sample_size, distance, keyframe);
1359
                if(sc->sample_to_chunk[stsc_index].id - 1 == sc->pseudo_stream_id)
1360
                    av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
1361
                                    keyframe ? AVINDEX_KEYFRAME : 0);
1362
                current_offset += sample_size;
1363
                assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
1364
                current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
1365
                distance++;
1366
                stts_sample++;
1367
                current_sample++;
1368
                if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1369
                    stts_sample = 0;
1370
                    stts_index++;
1371
                }
1372
            }
1373
        }
1374
    } else { /* read whole chunk */
1375
        unsigned int chunk_samples, chunk_size, chunk_duration;
1376
        unsigned int frames = 1;
1377
        for (i = 0; i < sc->chunk_count; i++) {
1378
            current_offset = sc->chunk_offsets[i];
1379
            if (stsc_index + 1 < sc->sample_to_chunk_sz &&
1380
                i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1381
                stsc_index++;
1382
            chunk_samples = sc->sample_to_chunk[stsc_index].count;
1383
            /* get chunk size */
1384
            if (sc->sample_size > 1 ||
1385
                st->codec->codec_id == CODEC_ID_PCM_U8 || st->codec->codec_id == CODEC_ID_PCM_S8)
1386
                chunk_size = chunk_samples * sc->sample_size;
1387
            else if (sc->samples_per_frame > 0 &&
1388
                     (chunk_samples * sc->bytes_per_frame % sc->samples_per_frame == 0)) {
1389
                if (sc->samples_per_frame < 1024)
1390
                    chunk_size = chunk_samples * sc->bytes_per_frame / sc->samples_per_frame;
1391
                else {
1392
                    chunk_size = sc->bytes_per_frame;
1393
                    frames = chunk_samples / sc->samples_per_frame;
1394
                    chunk_samples = sc->samples_per_frame;
1395
                }
1396
            } else { /* workaround to find nearest next chunk offset */
1397
                chunk_size = INT_MAX;
1398
                for (j = 0; j < mov->fc->nb_streams; j++) {
1399
                    MOVStreamContext *msc = mov->fc->streams[j]->priv_data;
1400
                    for (k = msc->next_chunk; k < msc->chunk_count; k++) {
1401
                        if (msc->chunk_offsets[k] > current_offset &&
1402
                            msc->chunk_offsets[k] - current_offset < chunk_size) {
1403
                            chunk_size = msc->chunk_offsets[k] - current_offset;
1404
                            msc->next_chunk = k;
1405
                            break;
1406
                        }
1407
                    }
1408
                }
1409
                /* check for last chunk */
1410
                if (chunk_size == INT_MAX)
1411
                    for (j = 0; j < mov->mdat_count; j++) {
1412
                        dprintf(mov->fc, "mdat %d, offset %"PRIx64", size %"PRId64", current offset %"PRIx64"\n",
1413
                                j, mov->mdat_list[j].offset, mov->mdat_list[j].size, current_offset);
1414
                        if (mov->mdat_list[j].offset <= current_offset &&
1415
                            mov->mdat_list[j].offset + mov->mdat_list[j].size > current_offset)
1416
                            chunk_size = mov->mdat_list[j].offset + mov->mdat_list[j].size - current_offset;
1417
                    }
1418
                assert(chunk_size != INT_MAX);
1419
                for (j = 0; j < mov->fc->nb_streams; j++) {
1420
                    MOVStreamContext *msc = mov->fc->streams[j]->priv_data;
1421
                    msc->next_chunk = 0;
1422
                }
1423
            }
1424
            for (j = 0; j < frames; j++) {
1425
            av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
1426
            /* get chunk duration */
1427
            chunk_duration = 0;
1428
            while (chunk_samples > 0) {
1429
                if (chunk_samples < sc->stts_data[stts_index].count) {
1430
                    chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1431
                    sc->stts_data[stts_index].count -= chunk_samples;
1432
                    break;
1433
                } else {
1434
                    chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1435
                    chunk_samples -= sc->stts_data[stts_index].count;
1436
                    if (stts_index + 1 < sc->stts_count)
1437
                        stts_index++;
1438
                }
1439
            }
1440
            current_offset += sc->bytes_per_frame;
1441
            dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", size %d, "
1442
                    "duration %d\n", st->index, i, current_offset, current_dts, chunk_size, chunk_duration);
1443
            assert(chunk_duration % sc->time_rate == 0);
1444
            current_dts += chunk_duration / sc->time_rate;
1445
            }
1446
        }
1447
    }
1448
 out:
1449
    /* adjust sample count to avindex entries */
1450
    sc->sample_count = st->nb_index_entries;
1451
}
1452

    
1453
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1454
{
1455
    MOVContext *mov = s->priv_data;
1456
    ByteIOContext *pb = s->pb;
1457
    int i, err;
1458
    MOV_atom_t atom = { 0, 0, 0 };
1459

    
1460
    mov->fc = s;
1461

    
1462
    if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1463
        atom.size = url_fsize(pb);
1464
    else
1465
        atom.size = INT64_MAX;
1466

    
1467
    /* check MOV header */
1468
    err = mov_read_default(mov, pb, atom);
1469
    if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
1470
        av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%"PRId64"\n",
1471
                err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1472
        return -1;
1473
    }
1474
    dprintf(mov->fc, "on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1475

    
1476
    for(i=0; i<s->nb_streams; i++) {
1477
        AVStream *st = s->streams[i];
1478
        MOVStreamContext *sc = st->priv_data;
1479
        /* sanity checks */
1480
        if(!sc->stts_count || !sc->chunk_count || !sc->sample_to_chunk_sz ||
1481
           (!sc->sample_size && !sc->sample_count)){
1482
            av_log(s, AV_LOG_ERROR, "missing mandatory atoms, broken header\n");
1483
            sc->sample_count = 0; //ignore track
1484
            continue;
1485
        }
1486
        if(!sc->time_rate)
1487
            sc->time_rate=1;
1488
        if(!sc->time_scale)
1489
            sc->time_scale= mov->time_scale;
1490
        av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
1491

    
1492
        if (st->codec->codec_type == CODEC_TYPE_AUDIO && sc->stts_count == 1)
1493
            st->codec->frame_size = sc->stts_data[0].duration;
1494

    
1495
        if(st->duration != AV_NOPTS_VALUE){
1496
            assert(st->duration % sc->time_rate == 0);
1497
            st->duration /= sc->time_rate;
1498
        }
1499
        sc->ffindex = i;
1500
        mov_build_index(mov, st);
1501
    }
1502

    
1503
    for(i=0; i<s->nb_streams; i++) {
1504
        MOVStreamContext *sc = s->streams[i]->priv_data;
1505
        /* Do not need those anymore. */
1506
        av_freep(&sc->chunk_offsets);
1507
        av_freep(&sc->sample_to_chunk);
1508
        av_freep(&sc->sample_sizes);
1509
        av_freep(&sc->keyframes);
1510
        av_freep(&sc->stts_data);
1511
    }
1512
    av_freep(&mov->mdat_list);
1513
    return 0;
1514
}
1515

    
1516
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1517
{
1518
    MOVContext *mov = s->priv_data;
1519
    MOVStreamContext *sc = 0;
1520
    AVIndexEntry *sample = 0;
1521
    int64_t best_dts = INT64_MAX;
1522
    int i;
1523

    
1524
    for (i = 0; i < s->nb_streams; i++) {
1525
        AVStream *st = s->streams[i];
1526
        MOVStreamContext *msc = st->priv_data;
1527
        if (st->discard != AVDISCARD_ALL && msc->current_sample < msc->sample_count) {
1528
            AVIndexEntry *current_sample = &st->index_entries[msc->current_sample];
1529
            int64_t dts = av_rescale(current_sample->timestamp * (int64_t)msc->time_rate,
1530
                                     AV_TIME_BASE, msc->time_scale);
1531
            dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
1532
            if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
1533
                (!url_is_streamed(s->pb) &&
1534
                 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
1535
                  (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))) {
1536
                sample = current_sample;
1537
                best_dts = dts;
1538
                sc = msc;
1539
            }
1540
        }
1541
    }
1542
    if (!sample)
1543
        return -1;
1544
    /* must be done just before reading, to avoid infinite loop on sample */
1545
    sc->current_sample++;
1546
    if (url_fseek(s->pb, sample->pos, SEEK_SET) != sample->pos) {
1547
        av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
1548
               sc->ffindex, sample->pos);
1549
        return -1;
1550
    }
1551
    av_get_packet(s->pb, pkt, sample->size);
1552
#ifdef CONFIG_DV_DEMUXER
1553
    if (mov->dv_demux && sc->dv_audio_container) {
1554
        dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
1555
        av_free(pkt->data);
1556
        pkt->size = 0;
1557
        if (dv_get_packet(mov->dv_demux, pkt) < 0)
1558
            return -1;
1559
    }
1560
#endif
1561
    pkt->stream_index = sc->ffindex;
1562
    pkt->dts = sample->timestamp;
1563
    if (sc->ctts_data) {
1564
        assert(sc->ctts_data[sc->sample_to_ctime_index].duration % sc->time_rate == 0);
1565
        pkt->pts = pkt->dts + sc->ctts_data[sc->sample_to_ctime_index].duration / sc->time_rate;
1566
        /* update ctts context */
1567
        sc->sample_to_ctime_sample++;
1568
        if (sc->sample_to_ctime_index < sc->ctts_count &&
1569
            sc->ctts_data[sc->sample_to_ctime_index].count == sc->sample_to_ctime_sample) {
1570
            sc->sample_to_ctime_index++;
1571
            sc->sample_to_ctime_sample = 0;
1572
        }
1573
    } else {
1574
        pkt->pts = pkt->dts;
1575
    }
1576
    pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
1577
    pkt->pos = sample->pos;
1578
    dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
1579
            pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
1580
    return 0;
1581
}
1582

    
1583
static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
1584
{
1585
    MOVStreamContext *sc = st->priv_data;
1586
    int sample, time_sample;
1587
    int i;
1588

    
1589
    sample = av_index_search_timestamp(st, timestamp, flags);
1590
    dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
1591
    if (sample < 0) /* not sure what to do */
1592
        return -1;
1593
    sc->current_sample = sample;
1594
    dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
1595
    /* adjust ctts index */
1596
    if (sc->ctts_data) {
1597
        time_sample = 0;
1598
        for (i = 0; i < sc->ctts_count; i++) {
1599
            int next = time_sample + sc->ctts_data[i].count;
1600
            if (next > sc->current_sample) {
1601
                sc->sample_to_ctime_index = i;
1602
                sc->sample_to_ctime_sample = sc->current_sample - time_sample;
1603
                break;
1604
            }
1605
            time_sample = next;
1606
        }
1607
    }
1608
    return sample;
1609
}
1610

    
1611
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1612
{
1613
    AVStream *st;
1614
    int64_t seek_timestamp, timestamp;
1615
    int sample;
1616
    int i;
1617

    
1618
    if (stream_index >= s->nb_streams)
1619
        return -1;
1620

    
1621
    st = s->streams[stream_index];
1622
    sample = mov_seek_stream(st, sample_time, flags);
1623
    if (sample < 0)
1624
        return -1;
1625

    
1626
    /* adjust seek timestamp to found sample timestamp */
1627
    seek_timestamp = st->index_entries[sample].timestamp;
1628

    
1629
    for (i = 0; i < s->nb_streams; i++) {
1630
        st = s->streams[i];
1631
        if (stream_index == i || st->discard == AVDISCARD_ALL)
1632
            continue;
1633

    
1634
        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
1635
        mov_seek_stream(st, timestamp, flags);
1636
    }
1637
    return 0;
1638
}
1639

    
1640
static int mov_read_close(AVFormatContext *s)
1641
{
1642
    int i;
1643
    MOVContext *mov = s->priv_data;
1644
    for(i=0; i<s->nb_streams; i++) {
1645
        MOVStreamContext *sc = s->streams[i]->priv_data;
1646
        av_freep(&sc->ctts_data);
1647
    }
1648
    if(mov->dv_demux){
1649
        for(i=0; i<mov->dv_fctx->nb_streams; i++){
1650
            av_freep(&mov->dv_fctx->streams[i]->codec);
1651
            av_freep(&mov->dv_fctx->streams[i]);
1652
        }
1653
        av_freep(&mov->dv_fctx);
1654
        av_freep(&mov->dv_demux);
1655
    }
1656
    return 0;
1657
}
1658

    
1659
AVInputFormat mov_demuxer = {
1660
    "mov,mp4,m4a,3gp,3g2,mj2",
1661
    "QuickTime/MPEG4/Motion JPEG 2000 format",
1662
    sizeof(MOVContext),
1663
    mov_probe,
1664
    mov_read_header,
1665
    mov_read_packet,
1666
    mov_read_close,
1667
    mov_read_seek,
1668
};