Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 0bc4728e

History | View | Annotate | Download (55.6 KB)

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

    
22
#include <limits.h>
23

    
24
//#define DEBUG
25

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

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

    
35
/*
36
 * First version by Francois Revol revol@free.fr
37
 * Seek function by Gael Chardon gael.dev@4now.net
38
 *
39
 * Features and limitations:
40
 * - reads most of the QT files I have (at least the structure),
41
 *   Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
42
 * - the code is quite ugly... maybe I won't do it recursive next time :-)
43
 *
44
 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
45
 * when coding this :) (it's a writer anyway)
46
 *
47
 * Reference documents:
48
 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
49
 * Apple:
50
 *  http://developer.apple.com/documentation/QuickTime/QTFF/
51
 *  http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
52
 * QuickTime is a trademark of Apple (AFAIK :))
53
 */
54

    
55
#include "qtpalette.h"
56

    
57

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

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

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

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

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

    
83
struct MOVParseTableEntry;
84

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

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

    
126

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

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

    
141
static const MOVParseTableEntry mov_default_parse_table[];
142

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

    
150
    a.offset = atom.offset;
151

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

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

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

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

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

    
205
    return err;
206
}
207

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

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

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

    
221
    dprintf(c->fc, "ctype= %c%c%c%c (0x%08x)\n", *((char *)&ctype), ((char *)&ctype)[1],
222
            ((char *)&ctype)[2], ((char *)&ctype)[3], (int) ctype);
223
    dprintf(c->fc, "stype= %c%c%c%c\n",
224
            *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
225
    if(!ctype)
226
        c->isom = 1;
227
    if(type == MKTAG('v', 'i', 'd', 'e'))
228
        st->codec->codec_type = CODEC_TYPE_VIDEO;
229
    else if(type == MKTAG('s', 'o', 'u', 'n'))
230
        st->codec->codec_type = CODEC_TYPE_AUDIO;
231
    else if(type == MKTAG('m', '1', 'a', ' '))
232
        st->codec->codec_id = CODEC_ID_MP2;
233
    else if(type == MKTAG('s', 'u', 'b', 'p')) {
234
        st->codec->codec_type = CODEC_TYPE_SUBTITLE;
235
        st->codec->codec_id = CODEC_ID_DVD_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;
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
    while(entries--) { //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 && st->codec->codec_tag != MKTAG('j', 'p', 'e', 'g')) {
604
            /* multiple fourcc, we skip jpeg, this isnt correct, we should export it as
605
               seperate AVStream but this needs a few changes in the mov demuxer, patch
606
               welcome */
607
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
608
            continue;
609
        }
610

    
611
        st->codec->codec_tag = format;
612
        id = codec_get_id(codec_movaudio_tags, format);
613
        if (id<=0 && (format&0xFFFF) == 'm' + ('s'<<8))
614
            id = codec_get_id(codec_wav_tags, bswap_32(format)&0xFFFF);
615

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

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

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

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

    
642
            get_be32(pb); /* horiz resolution */
643
            get_be32(pb); /* vert resolution */
644
            get_be32(pb); /* data size, always 0 */
645
            frames_per_sample = get_be16(pb); /* frames per samples */
646

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

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

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

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

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

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

    
727
            st->codec->codec_id = id;
728
            get_be16(pb); /* revision level */
729
            get_be32(pb); /* vendor */
730

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

    
736
            /* handle specific s8 codec */
737
            get_be16(pb); /* compression id = 0*/
738
            get_be16(pb); /* packet size = 0 */
739

    
740
            st->codec->sample_rate = ((get_be32(pb) >> 16));
741

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

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

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

    
797
    if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1) {
798
        st->codec->sample_rate= sc->time_scale;
799
    }
800

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

    
858
    return 0;
859
}
860

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

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

    
870
    entries = get_be32(pb);
871

    
872
    if(entries >= UINT_MAX / sizeof(MOV_stsc_t))
873
        return -1;
874

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

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

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

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

    
898
    entries = get_be32(pb);
899

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

    
903
    sc->keyframe_count = entries;
904

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

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

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

    
923
    get_byte(pb); /* version */
924
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
925

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

    
933
    sc->sample_count = entries;
934
    if (sample_size)
935
        return 0;
936

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

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

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

    
957
    get_byte(pb); /* version */
958
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
959
    entries = get_be32(pb);
960
    if(entries >= UINT_MAX / sizeof(MOV_stts_t))
961
        return -1;
962

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

    
969
    sc->time_rate=0;
970

    
971
    for(i=0; i<entries; i++) {
972
        int sample_duration;
973
        int sample_count;
974

    
975
        sample_count=get_be32(pb);
976
        sample_duration = get_be32(pb);
977
        sc->stts_data[i].count= sample_count;
978
        sc->stts_data[i].duration= sample_duration;
979

    
980
        sc->time_rate= ff_gcd(sc->time_rate, sample_duration);
981

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

    
984
        duration+=(int64_t)sample_duration*sample_count;
985
        total_sample_count+=sample_count;
986
    }
987

    
988
    st->nb_frames= total_sample_count;
989
    if(duration)
990
        st->duration= duration;
991
    return 0;
992
}
993

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

    
1000
    get_byte(pb); /* version */
1001
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1002
    entries = get_be32(pb);
1003
    if(entries >= UINT_MAX / sizeof(MOV_stts_t))
1004
        return -1;
1005

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

    
1012
    for(i=0; i<entries; i++) {
1013
        int count    =get_be32(pb);
1014
        int duration =get_be32(pb);
1015

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

    
1025
        sc->time_rate= ff_gcd(sc->time_rate, duration);
1026
    }
1027
    return 0;
1028
}
1029

    
1030
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1031
{
1032
    AVStream *st;
1033
    MOVStreamContext *sc;
1034

    
1035
    st = av_new_stream(c->fc, c->fc->nb_streams);
1036
    if (!st) return -2;
1037
    sc = av_mallocz(sizeof(MOVStreamContext));
1038
    if (!sc) {
1039
        av_free(st);
1040
        return -1;
1041
    }
1042

    
1043
    st->priv_data = sc;
1044
    st->codec->codec_type = CODEC_TYPE_DATA;
1045
    st->start_time = 0; /* XXX: check */
1046

    
1047
    return mov_read_default(c, pb, atom);
1048
}
1049

    
1050
static void mov_parse_udta_string(ByteIOContext *pb, char *str, int size)
1051
{
1052
    uint16_t str_size = get_be16(pb); /* string length */;
1053

    
1054
    get_be16(pb); /* skip language */
1055
    get_buffer(pb, str, FFMIN(size, str_size));
1056
}
1057

    
1058
static int mov_read_udta(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1059
{
1060
    uint64_t end = url_ftell(pb) + atom.size;
1061

    
1062
    while (url_ftell(pb) + 8 < end) {
1063
        uint32_t tag_size = get_be32(pb);
1064
        uint32_t tag      = get_le32(pb);
1065
        uint64_t next     = url_ftell(pb) + tag_size - 8;
1066

    
1067
        if (next > end) // stop if tag_size is wrong
1068
            break;
1069

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

    
1087
        url_fseek(pb, next, SEEK_SET);
1088
    }
1089

    
1090
    return 0;
1091
}
1092

    
1093
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1094
{
1095
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1096
    int version = get_byte(pb);
1097

    
1098
    get_byte(pb); get_byte(pb);
1099
    get_byte(pb); /* flags */
1100
    /*
1101
    MOV_TRACK_ENABLED 0x0001
1102
    MOV_TRACK_IN_MOVIE 0x0002
1103
    MOV_TRACK_IN_PREVIEW 0x0004
1104
    MOV_TRACK_IN_POSTER 0x0008
1105
    */
1106

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

    
1121
    get_be16(pb); /* layer */
1122
    get_be16(pb); /* alternate group */
1123
    get_be16(pb); /* volume */
1124
    get_be16(pb); /* reserved */
1125

    
1126
    url_fskip(pb, 36); /* display matrix */
1127

    
1128
    /* those are fixed-point */
1129
    get_be32(pb); /* track width */
1130
    get_be32(pb); /* track height */
1131

    
1132
    return 0;
1133
}
1134

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

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

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

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

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

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

    
1216
    get_byte(pb); /* version */
1217
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1218
    edit_count= sc->edit_count = get_be32(pb);     /* entries */
1219

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

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

    
1267
/* XXX: is it sufficient ? */
1268
static int mov_probe(AVProbeData *p)
1269
{
1270
    unsigned int offset;
1271
    uint32_t tag;
1272
    int score = 0;
1273

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

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

    
1321
    if (sc->sample_sizes || st->codec->codec_type == CODEC_TYPE_VIDEO || sc->dv_audio_container) {
1322
        unsigned int current_sample = 0;
1323
        unsigned int stts_sample = 0;
1324
        unsigned int keyframe, sample_size;
1325
        unsigned int distance = 0;
1326

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

    
1432
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1433
{
1434
    MOVContext *mov = s->priv_data;
1435
    ByteIOContext *pb = s->pb;
1436
    int i, err;
1437
    MOV_atom_t atom = { 0, 0, 0 };
1438

    
1439
    mov->fc = s;
1440

    
1441
    if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1442
        atom.size = url_fsize(pb);
1443
    else
1444
        atom.size = INT64_MAX;
1445

    
1446
    /* check MOV header */
1447
    err = mov_read_default(mov, pb, atom);
1448
    if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
1449
        av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%"PRId64"\n",
1450
                err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1451
        return -1;
1452
    }
1453
    dprintf(mov->fc, "on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1454

    
1455
    for(i=0; i<s->nb_streams; i++) {
1456
        AVStream *st = s->streams[i];
1457
        MOVStreamContext *sc = st->priv_data;
1458
        /* sanity checks */
1459
        if(!sc->stts_count || !sc->chunk_count || !sc->sample_to_chunk_sz ||
1460
           (!sc->sample_size && !sc->sample_count)){
1461
            av_log(s, AV_LOG_ERROR, "missing mandatory atoms, broken header\n");
1462
            sc->sample_count = 0; //ignore track
1463
            continue;
1464
        }
1465
        if(!sc->time_rate)
1466
            sc->time_rate=1;
1467
        if(!sc->time_scale)
1468
            sc->time_scale= mov->time_scale;
1469
        av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
1470

    
1471
        if (st->codec->codec_type == CODEC_TYPE_AUDIO && sc->stts_count == 1)
1472
            st->codec->frame_size = sc->stts_data[0].duration;
1473

    
1474
        if(st->duration != AV_NOPTS_VALUE){
1475
            assert(st->duration % sc->time_rate == 0);
1476
            st->duration /= sc->time_rate;
1477
        }
1478
        sc->ffindex = i;
1479
        mov_build_index(mov, st);
1480
    }
1481

    
1482
    for(i=0; i<s->nb_streams; i++) {
1483
        MOVStreamContext *sc = s->streams[i]->priv_data;
1484
        /* Do not need those anymore. */
1485
        av_freep(&sc->chunk_offsets);
1486
        av_freep(&sc->sample_to_chunk);
1487
        av_freep(&sc->sample_sizes);
1488
        av_freep(&sc->keyframes);
1489
        av_freep(&sc->stts_data);
1490
    }
1491
    av_freep(&mov->mdat_list);
1492
    return 0;
1493
}
1494

    
1495
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1496
{
1497
    MOVContext *mov = s->priv_data;
1498
    MOVStreamContext *sc = 0;
1499
    AVIndexEntry *sample = 0;
1500
    int64_t best_dts = INT64_MAX;
1501
    int i;
1502

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

    
1567
static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
1568
{
1569
    MOVStreamContext *sc = st->priv_data;
1570
    int sample, time_sample;
1571
    int i;
1572

    
1573
    sample = av_index_search_timestamp(st, timestamp, flags);
1574
    dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
1575
    if (sample < 0) /* not sure what to do */
1576
        return -1;
1577
    sc->current_sample = sample;
1578
    dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
1579
    /* adjust ctts index */
1580
    if (sc->ctts_data) {
1581
        time_sample = 0;
1582
        for (i = 0; i < sc->ctts_count; i++) {
1583
            int next = time_sample + sc->ctts_data[i].count;
1584
            if (next > sc->current_sample) {
1585
                sc->sample_to_ctime_index = i;
1586
                sc->sample_to_ctime_sample = sc->current_sample - time_sample;
1587
                break;
1588
            }
1589
            time_sample = next;
1590
        }
1591
    }
1592
    return sample;
1593
}
1594

    
1595
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1596
{
1597
    AVStream *st;
1598
    int64_t seek_timestamp, timestamp;
1599
    int sample;
1600
    int i;
1601

    
1602
    if (stream_index >= s->nb_streams)
1603
        return -1;
1604

    
1605
    st = s->streams[stream_index];
1606
    sample = mov_seek_stream(st, sample_time, flags);
1607
    if (sample < 0)
1608
        return -1;
1609

    
1610
    /* adjust seek timestamp to found sample timestamp */
1611
    seek_timestamp = st->index_entries[sample].timestamp;
1612

    
1613
    for (i = 0; i < s->nb_streams; i++) {
1614
        st = s->streams[i];
1615
        if (stream_index == i || st->discard == AVDISCARD_ALL)
1616
            continue;
1617

    
1618
        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
1619
        mov_seek_stream(st, timestamp, flags);
1620
    }
1621
    return 0;
1622
}
1623

    
1624
static int mov_read_close(AVFormatContext *s)
1625
{
1626
    int i;
1627
    MOVContext *mov = s->priv_data;
1628
    for(i=0; i<s->nb_streams; i++) {
1629
        MOVStreamContext *sc = s->streams[i]->priv_data;
1630
        av_freep(&sc->ctts_data);
1631
    }
1632
    if(mov->dv_demux){
1633
        for(i=0; i<mov->dv_fctx->nb_streams; i++){
1634
            av_freep(&mov->dv_fctx->streams[i]->codec);
1635
            av_freep(&mov->dv_fctx->streams[i]);
1636
        }
1637
        av_freep(&mov->dv_fctx);
1638
        av_freep(&mov->dv_demux);
1639
    }
1640
    return 0;
1641
}
1642

    
1643
AVInputFormat mov_demuxer = {
1644
    "mov,mp4,m4a,3gp,3g2,mj2",
1645
    "QuickTime/MPEG4/Motion JPEG 2000 format",
1646
    sizeof(MOVContext),
1647
    mov_probe,
1648
    mov_read_header,
1649
    mov_read_packet,
1650
    mov_read_close,
1651
    mov_read_seek,
1652
};