Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 744a9c75

History | View | Annotate | Download (56.3 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
} MOVStreamContext;
112

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

    
127

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

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

    
142
static const MOVParseTableEntry mov_default_parse_table[];
143

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

    
151
    a.offset = atom.offset;
152

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

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

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

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

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

    
206
    return err;
207
}
208

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
355

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

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

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

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

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

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

    
384
    return 0;
385
}
386

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

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

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

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

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

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

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

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

    
420
    return 0;
421
}
422

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

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

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

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

    
443
    return 0;
444
}
445

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

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

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

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

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

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

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

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

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

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

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

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

    
532
    return 0;
533
}
534

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

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

    
544
    entries = get_be32(pb);
545

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

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

    
564
    return 0;
565
}
566

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

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

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

    
590
    entries = get_be32(pb);
591

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
740
            st->codec->channels = get_be16(pb);             /* channel count */
741
            dprintf(c->fc, "audio channels %d\n", st->codec->channels);
742
            st->codec->bits_per_sample = get_be16(pb);      /* sample size */
743
            /* do we need to force to 16 for AMR ? */
744

    
745
            /* handle specific s8 codec */
746
            get_be16(pb); /* compression id = 0*/
747
            get_be16(pb); /* packet size = 0 */
748

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

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

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

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

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

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

    
869
    return 0;
870
}
871

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

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

    
881
    entries = get_be32(pb);
882

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

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

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

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

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

    
909
    entries = get_be32(pb);
910

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

    
914
    sc->keyframe_count = entries;
915

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

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

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

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

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

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

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

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

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

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

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

    
980
    sc->time_rate=0;
981

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1101
    return 0;
1102
}
1103

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

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

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

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

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

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

    
1143
    return 0;
1144
}
1145

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

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

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

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

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

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

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

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

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

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

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

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

    
1332
    if (sc->sample_sizes || st->codec->codec_type == CODEC_TYPE_VIDEO || sc->dv_audio_container) {
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
        for (i = 0; i < sc->chunk_count; i++) {
1377
            current_offset = sc->chunk_offsets[i];
1378
            if (stsc_index + 1 < sc->sample_to_chunk_sz &&
1379
                i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1380
                stsc_index++;
1381
            chunk_samples = sc->sample_to_chunk[stsc_index].count;
1382
            /* get chunk size */
1383
            if (sc->sample_size > 1 ||
1384
                st->codec->codec_id == CODEC_ID_PCM_U8 || st->codec->codec_id == CODEC_ID_PCM_S8)
1385
                chunk_size = chunk_samples * sc->sample_size;
1386
            else if (sc->samples_per_frame > 0 &&
1387
                     (chunk_samples * sc->bytes_per_frame % sc->samples_per_frame == 0))
1388
                chunk_size = chunk_samples * sc->bytes_per_frame / sc->samples_per_frame;
1389
            else { /* workaround to find nearest next chunk offset */
1390
                chunk_size = INT_MAX;
1391
                for (j = 0; j < mov->fc->nb_streams; j++) {
1392
                    MOVStreamContext *msc = mov->fc->streams[j]->priv_data;
1393
                    for (k = msc->next_chunk; k < msc->chunk_count; k++) {
1394
                        if (msc->chunk_offsets[k] > current_offset &&
1395
                            msc->chunk_offsets[k] - current_offset < chunk_size) {
1396
                            chunk_size = msc->chunk_offsets[k] - current_offset;
1397
                            msc->next_chunk = k;
1398
                            break;
1399
                        }
1400
                    }
1401
                }
1402
                /* check for last chunk */
1403
                if (chunk_size == INT_MAX)
1404
                    for (j = 0; j < mov->mdat_count; j++) {
1405
                        dprintf(mov->fc, "mdat %d, offset %"PRIx64", size %"PRId64", current offset %"PRIx64"\n",
1406
                                j, mov->mdat_list[j].offset, mov->mdat_list[j].size, current_offset);
1407
                        if (mov->mdat_list[j].offset <= current_offset &&
1408
                            mov->mdat_list[j].offset + mov->mdat_list[j].size > current_offset)
1409
                            chunk_size = mov->mdat_list[j].offset + mov->mdat_list[j].size - current_offset;
1410
                    }
1411
                assert(chunk_size != INT_MAX);
1412
                for (j = 0; j < mov->fc->nb_streams; j++) {
1413
                    MOVStreamContext *msc = mov->fc->streams[j]->priv_data;
1414
                    msc->next_chunk = 0;
1415
                }
1416
            }
1417
            av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
1418
            /* get chunk duration */
1419
            chunk_duration = 0;
1420
            while (chunk_samples > 0) {
1421
                if (chunk_samples < sc->stts_data[stts_index].count) {
1422
                    chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1423
                    sc->stts_data[stts_index].count -= chunk_samples;
1424
                    break;
1425
                } else {
1426
                    chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1427
                    chunk_samples -= sc->stts_data[stts_index].count;
1428
                    if (stts_index + 1 < sc->stts_count) {
1429
                        stts_index++;
1430
                    }
1431
                }
1432
            }
1433
            dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", size %d, "
1434
                    "duration %d\n", st->index, i, current_offset, current_dts, chunk_size, chunk_duration);
1435
            assert(chunk_duration % sc->time_rate == 0);
1436
            current_dts += chunk_duration / sc->time_rate;
1437
        }
1438
    }
1439
 out:
1440
    /* adjust sample count to avindex entries */
1441
    sc->sample_count = st->nb_index_entries;
1442
}
1443

    
1444
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1445
{
1446
    MOVContext *mov = s->priv_data;
1447
    ByteIOContext *pb = s->pb;
1448
    int i, err;
1449
    MOV_atom_t atom = { 0, 0, 0 };
1450

    
1451
    mov->fc = s;
1452

    
1453
    if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1454
        atom.size = url_fsize(pb);
1455
    else
1456
        atom.size = INT64_MAX;
1457

    
1458
    /* check MOV header */
1459
    err = mov_read_default(mov, pb, atom);
1460
    if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
1461
        av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%"PRId64"\n",
1462
                err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1463
        return -1;
1464
    }
1465
    dprintf(mov->fc, "on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1466

    
1467
    for(i=0; i<s->nb_streams; i++) {
1468
        AVStream *st = s->streams[i];
1469
        MOVStreamContext *sc = st->priv_data;
1470
        /* sanity checks */
1471
        if(!sc->stts_count || !sc->chunk_count || !sc->sample_to_chunk_sz ||
1472
           (!sc->sample_size && !sc->sample_count)){
1473
            av_log(s, AV_LOG_ERROR, "missing mandatory atoms, broken header\n");
1474
            sc->sample_count = 0; //ignore track
1475
            continue;
1476
        }
1477
        if(!sc->time_rate)
1478
            sc->time_rate=1;
1479
        if(!sc->time_scale)
1480
            sc->time_scale= mov->time_scale;
1481
        av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
1482

    
1483
        if (st->codec->codec_type == CODEC_TYPE_AUDIO && sc->stts_count == 1)
1484
            st->codec->frame_size = sc->stts_data[0].duration;
1485

    
1486
        if(st->duration != AV_NOPTS_VALUE){
1487
            assert(st->duration % sc->time_rate == 0);
1488
            st->duration /= sc->time_rate;
1489
        }
1490
        sc->ffindex = i;
1491
        mov_build_index(mov, st);
1492
    }
1493

    
1494
    for(i=0; i<s->nb_streams; i++) {
1495
        MOVStreamContext *sc = s->streams[i]->priv_data;
1496
        /* Do not need those anymore. */
1497
        av_freep(&sc->chunk_offsets);
1498
        av_freep(&sc->sample_to_chunk);
1499
        av_freep(&sc->sample_sizes);
1500
        av_freep(&sc->keyframes);
1501
        av_freep(&sc->stts_data);
1502
    }
1503
    av_freep(&mov->mdat_list);
1504
    return 0;
1505
}
1506

    
1507
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1508
{
1509
    MOVContext *mov = s->priv_data;
1510
    MOVStreamContext *sc = 0;
1511
    AVIndexEntry *sample = 0;
1512
    int64_t best_dts = INT64_MAX;
1513
    int i;
1514

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

    
1579
static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
1580
{
1581
    MOVStreamContext *sc = st->priv_data;
1582
    int sample, time_sample;
1583
    int i;
1584

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

    
1607
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1608
{
1609
    AVStream *st;
1610
    int64_t seek_timestamp, timestamp;
1611
    int sample;
1612
    int i;
1613

    
1614
    if (stream_index >= s->nb_streams)
1615
        return -1;
1616

    
1617
    st = s->streams[stream_index];
1618
    sample = mov_seek_stream(st, sample_time, flags);
1619
    if (sample < 0)
1620
        return -1;
1621

    
1622
    /* adjust seek timestamp to found sample timestamp */
1623
    seek_timestamp = st->index_entries[sample].timestamp;
1624

    
1625
    for (i = 0; i < s->nb_streams; i++) {
1626
        st = s->streams[i];
1627
        if (stream_index == i || st->discard == AVDISCARD_ALL)
1628
            continue;
1629

    
1630
        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
1631
        mov_seek_stream(st, timestamp, flags);
1632
    }
1633
    return 0;
1634
}
1635

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

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