Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 7df22143

History | View | Annotate | Download (88.1 KB)

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

    
23
#include <limits.h>
24

    
25
//#define DEBUG
26
//#define DEBUG_METADATA
27
//#define MOV_EXPORT_ALL_METADATA
28

    
29
#include "libavutil/intreadwrite.h"
30
#include "libavutil/avstring.h"
31
#include "avformat.h"
32
#include "riff.h"
33
#include "isom.h"
34
#include "libavcodec/mpeg4audio.h"
35
#include "libavcodec/mpegaudiodata.h"
36
#include "libavcodec/get_bits.h"
37

    
38
#if CONFIG_ZLIB
39
#include <zlib.h>
40
#endif
41

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

    
62
#include "qtpalette.h"
63

    
64

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

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

    
70
/* those functions parse an atom */
71
/* return code:
72
  0: continue to parse next atom
73
 <0: error occurred, exit
74
*/
75
/* links atom IDs to parse functions */
76
typedef struct MOVParseTableEntry {
77
    uint32_t type;
78
    int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOVAtom atom);
79
} MOVParseTableEntry;
80

    
81
static const MOVParseTableEntry mov_default_parse_table[];
82

    
83
static int mov_metadata_trkn(MOVContext *c, ByteIOContext *pb, unsigned len)
84
{
85
    char buf[16];
86

    
87
    get_be16(pb); // unknown
88
    snprintf(buf, sizeof(buf), "%d", get_be16(pb));
89
    av_metadata_set2(&c->fc->metadata, "track", buf, 0);
90

    
91
    get_be16(pb); // total tracks
92

    
93
    return 0;
94
}
95

    
96
static const uint32_t mac_to_unicode[128] = {
97
    0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
98
    0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
99
    0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
100
    0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
101
    0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
102
    0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
103
    0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
104
    0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
105
    0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
106
    0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
107
    0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
108
    0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
109
    0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
110
    0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
111
    0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
112
    0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
113
};
114

    
115
static int mov_read_mac_string(MOVContext *c, ByteIOContext *pb, int len,
116
                               char *dst, int dstlen)
117
{
118
    char *p = dst;
119
    char *end = dst+dstlen-1;
120
    int i;
121

    
122
    for (i = 0; i < len; i++) {
123
        uint8_t t, c = get_byte(pb);
124
        if (c < 0x80 && p < end)
125
            *p++ = c;
126
        else
127
            PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
128
    }
129
    *p = 0;
130
    return p - dst;
131
}
132

    
133
static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
134
{
135
#ifdef MOV_EXPORT_ALL_METADATA
136
    char tmp_key[5];
137
#endif
138
    char str[1024], key2[16], language[4] = {0};
139
    const char *key = NULL;
140
    uint16_t str_size, langcode = 0;
141
    uint32_t data_type = 0;
142
    int (*parse)(MOVContext*, ByteIOContext*, unsigned) = NULL;
143

    
144
    switch (atom.type) {
145
    case MKTAG(0xa9,'n','a','m'): key = "title";     break;
146
    case MKTAG(0xa9,'a','u','t'):
147
    case MKTAG(0xa9,'A','R','T'): key = "artist";    break;
148
    case MKTAG(0xa9,'w','r','t'): key = "composer";  break;
149
    case MKTAG( 'c','p','r','t'):
150
    case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
151
    case MKTAG(0xa9,'c','m','t'):
152
    case MKTAG(0xa9,'i','n','f'): key = "comment";   break;
153
    case MKTAG(0xa9,'a','l','b'): key = "album";     break;
154
    case MKTAG(0xa9,'d','a','y'): key = "date";      break;
155
    case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
156
    case MKTAG(0xa9,'t','o','o'):
157
    case MKTAG(0xa9,'s','w','r'): key = "encoder";   break;
158
    case MKTAG(0xa9,'e','n','c'): key = "encoder";   break;
159
    case MKTAG( 'd','e','s','c'): key = "description";break;
160
    case MKTAG( 'l','d','e','s'): key = "synopsis";  break;
161
    case MKTAG( 't','v','s','h'): key = "show";      break;
162
    case MKTAG( 't','v','e','n'): key = "episode_id";break;
163
    case MKTAG( 't','v','n','n'): key = "network";   break;
164
    case MKTAG( 't','r','k','n'): key = "track";
165
        parse = mov_metadata_trkn; break;
166
    }
167

    
168
    if (c->itunes_metadata && atom.size > 8) {
169
        int data_size = get_be32(pb);
170
        int tag = get_le32(pb);
171
        if (tag == MKTAG('d','a','t','a')) {
172
            data_type = get_be32(pb); // type
173
            get_be32(pb); // unknown
174
            str_size = data_size - 16;
175
            atom.size -= 16;
176
        } else return 0;
177
    } else if (atom.size > 4 && key && !c->itunes_metadata) {
178
        str_size = get_be16(pb); // string length
179
        langcode = get_be16(pb);
180
        ff_mov_lang_to_iso639(langcode, language);
181
        atom.size -= 4;
182
    } else
183
        str_size = atom.size;
184

    
185
#ifdef MOV_EXPORT_ALL_METADATA
186
    if (!key) {
187
        snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
188
        key = tmp_key;
189
    }
190
#endif
191

    
192
    if (!key)
193
        return 0;
194
    if (atom.size < 0)
195
        return -1;
196

    
197
    str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
198

    
199
    if (parse)
200
        parse(c, pb, str_size);
201
    else {
202
        if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
203
            mov_read_mac_string(c, pb, str_size, str, sizeof(str));
204
        } else {
205
            get_buffer(pb, str, str_size);
206
            str[str_size] = 0;
207
        }
208
        av_metadata_set2(&c->fc->metadata, key, str, 0);
209
        if (*language && strcmp(language, "und")) {
210
            snprintf(key2, sizeof(key2), "%s-%s", key, language);
211
            av_metadata_set2(&c->fc->metadata, key2, str, 0);
212
        }
213
    }
214
#ifdef DEBUG_METADATA
215
    av_log(c->fc, AV_LOG_DEBUG, "lang \"%3s\" ", language);
216
    av_log(c->fc, AV_LOG_DEBUG, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %lld\n",
217
           key, str, (char*)&atom.type, str_size, atom.size);
218
#endif
219

    
220
    return 0;
221
}
222

    
223
static int mov_read_chpl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
224
{
225
    int64_t start;
226
    int i, nb_chapters, str_len, version;
227
    char str[256+1];
228

    
229
    if ((atom.size -= 5) < 0)
230
        return 0;
231

    
232
    version = get_byte(pb);
233
    get_be24(pb);
234
    if (version)
235
        get_be32(pb); // ???
236
    nb_chapters = get_byte(pb);
237

    
238
    for (i = 0; i < nb_chapters; i++) {
239
        if (atom.size < 9)
240
            return 0;
241

    
242
        start = get_be64(pb);
243
        str_len = get_byte(pb);
244

    
245
        if ((atom.size -= 9+str_len) < 0)
246
            return 0;
247

    
248
        get_buffer(pb, str, str_len);
249
        str[str_len] = 0;
250
        ff_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
251
    }
252
    return 0;
253
}
254

    
255
static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
256
{
257
    int64_t total_size = 0;
258
    MOVAtom a;
259
    int i;
260

    
261
    if (atom.size < 0)
262
        atom.size = INT64_MAX;
263
    while (total_size + 8 < atom.size && !url_feof(pb)) {
264
        int (*parse)(MOVContext*, ByteIOContext*, MOVAtom) = NULL;
265
        a.size = atom.size;
266
        a.type=0;
267
        if(atom.size >= 8) {
268
            a.size = get_be32(pb);
269
            a.type = get_le32(pb);
270
        }
271
        dprintf(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
272
                a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
273
        total_size += 8;
274
        if (a.size == 1) { /* 64 bit extended size */
275
            a.size = get_be64(pb) - 8;
276
            total_size += 8;
277
        }
278
        if (a.size == 0) {
279
            a.size = atom.size - total_size;
280
            if (a.size <= 8)
281
                break;
282
        }
283
        a.size -= 8;
284
        if(a.size < 0)
285
            break;
286
        a.size = FFMIN(a.size, atom.size - total_size);
287

    
288
        for (i = 0; mov_default_parse_table[i].type; i++)
289
            if (mov_default_parse_table[i].type == a.type) {
290
                parse = mov_default_parse_table[i].parse;
291
                break;
292
            }
293

    
294
        // container is user data
295
        if (!parse && (atom.type == MKTAG('u','d','t','a') ||
296
                       atom.type == MKTAG('i','l','s','t')))
297
            parse = mov_read_udta_string;
298

    
299
        if (!parse) { /* skip leaf atoms data */
300
            url_fskip(pb, a.size);
301
        } else {
302
            int64_t start_pos = url_ftell(pb);
303
            int64_t left;
304
            int err = parse(c, pb, a);
305
            if (err < 0)
306
                return err;
307
            if (c->found_moov && c->found_mdat &&
308
                (url_is_streamed(pb) || start_pos + a.size == url_fsize(pb)))
309
                return 0;
310
            left = a.size - url_ftell(pb) + start_pos;
311
            if (left > 0) /* skip garbage at atom end */
312
                url_fskip(pb, left);
313
        }
314

    
315
        total_size += a.size;
316
    }
317

    
318
    if (total_size < atom.size && atom.size < 0x7ffff)
319
        url_fskip(pb, atom.size - total_size);
320

    
321
    return 0;
322
}
323

    
324
static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
325
{
326
    AVStream *st;
327
    MOVStreamContext *sc;
328
    int entries, i, j;
329

    
330
    if (c->fc->nb_streams < 1)
331
        return 0;
332
    st = c->fc->streams[c->fc->nb_streams-1];
333
    sc = st->priv_data;
334

    
335
    get_be32(pb); // version + flags
336
    entries = get_be32(pb);
337
    if (entries >= UINT_MAX / sizeof(*sc->drefs))
338
        return -1;
339
    sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
340
    if (!sc->drefs)
341
        return AVERROR(ENOMEM);
342
    sc->drefs_count = entries;
343

    
344
    for (i = 0; i < sc->drefs_count; i++) {
345
        MOVDref *dref = &sc->drefs[i];
346
        uint32_t size = get_be32(pb);
347
        int64_t next = url_ftell(pb) + size - 4;
348

    
349
        if (size < 12)
350
            return -1;
351

    
352
        dref->type = get_le32(pb);
353
        get_be32(pb); // version + flags
354
        dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
355

    
356
        if (dref->type == MKTAG('a','l','i','s') && size > 150) {
357
            /* macintosh alias record */
358
            uint16_t volume_len, len;
359
            int16_t type;
360

    
361
            url_fskip(pb, 10);
362

    
363
            volume_len = get_byte(pb);
364
            volume_len = FFMIN(volume_len, 27);
365
            get_buffer(pb, dref->volume, 27);
366
            dref->volume[volume_len] = 0;
367
            av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
368

    
369
            url_fskip(pb, 12);
370

    
371
            len = get_byte(pb);
372
            len = FFMIN(len, 63);
373
            get_buffer(pb, dref->filename, 63);
374
            dref->filename[len] = 0;
375
            av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
376

    
377
            url_fskip(pb, 16);
378

    
379
            /* read next level up_from_alias/down_to_target */
380
            dref->nlvl_from = get_be16(pb);
381
            dref->nlvl_to   = get_be16(pb);
382
            av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
383
                   dref->nlvl_from, dref->nlvl_to);
384

    
385
            url_fskip(pb, 16);
386

    
387
            for (type = 0; type != -1 && url_ftell(pb) < next; ) {
388
                type = get_be16(pb);
389
                len = get_be16(pb);
390
                av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
391
                if (len&1)
392
                    len += 1;
393
                if (type == 2) { // absolute path
394
                    av_free(dref->path);
395
                    dref->path = av_mallocz(len+1);
396
                    if (!dref->path)
397
                        return AVERROR(ENOMEM);
398
                    get_buffer(pb, dref->path, len);
399
                    if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
400
                        len -= volume_len;
401
                        memmove(dref->path, dref->path+volume_len, len);
402
                        dref->path[len] = 0;
403
                    }
404
                    for (j = 0; j < len; j++)
405
                        if (dref->path[j] == ':')
406
                            dref->path[j] = '/';
407
                    av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
408
                } else if (type == 0) { // directory name
409
                    av_free(dref->dir);
410
                    dref->dir = av_malloc(len+1);
411
                    if (!dref->dir)
412
                        return AVERROR(ENOMEM);
413
                    get_buffer(pb, dref->dir, len);
414
                    dref->dir[len] = 0;
415
                    for (j = 0; j < len; j++)
416
                        if (dref->dir[j] == ':')
417
                            dref->dir[j] = '/';
418
                    av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
419
                } else
420
                    url_fskip(pb, len);
421
            }
422
        }
423
        url_fseek(pb, next, SEEK_SET);
424
    }
425
    return 0;
426
}
427

    
428
static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
429
{
430
    AVStream *st;
431
    uint32_t type;
432
    uint32_t ctype;
433

    
434
    if (c->fc->nb_streams < 1) // meta before first trak
435
        return 0;
436

    
437
    st = c->fc->streams[c->fc->nb_streams-1];
438

    
439
    get_byte(pb); /* version */
440
    get_be24(pb); /* flags */
441

    
442
    /* component type */
443
    ctype = get_le32(pb);
444
    type = get_le32(pb); /* component subtype */
445

    
446
    dprintf(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
447
    dprintf(c->fc, "stype= %.4s\n", (char*)&type);
448

    
449
    if     (type == MKTAG('v','i','d','e'))
450
        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
451
    else if(type == MKTAG('s','o','u','n'))
452
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
453
    else if(type == MKTAG('m','1','a',' '))
454
        st->codec->codec_id = CODEC_ID_MP2;
455
    else if(type == MKTAG('s','u','b','p'))
456
        st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
457

    
458
    get_be32(pb); /* component  manufacture */
459
    get_be32(pb); /* component flags */
460
    get_be32(pb); /* component flags mask */
461

    
462
    return 0;
463
}
464

    
465
int ff_mp4_read_descr_len(ByteIOContext *pb)
466
{
467
    int len = 0;
468
    int count = 4;
469
    while (count--) {
470
        int c = get_byte(pb);
471
        len = (len << 7) | (c & 0x7f);
472
        if (!(c & 0x80))
473
            break;
474
    }
475
    return len;
476
}
477

    
478
static int mp4_read_descr(AVFormatContext *fc, ByteIOContext *pb, int *tag)
479
{
480
    int len;
481
    *tag = get_byte(pb);
482
    len = ff_mp4_read_descr_len(pb);
483
    dprintf(fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
484
    return len;
485
}
486

    
487
#define MP4ESDescrTag                   0x03
488
#define MP4DecConfigDescrTag            0x04
489
#define MP4DecSpecificDescrTag          0x05
490

    
491
static const AVCodecTag mp4_audio_types[] = {
492
    { CODEC_ID_MP3ON4, AOT_PS   }, /* old mp3on4 draft */
493
    { CODEC_ID_MP3ON4, AOT_L1   }, /* layer 1 */
494
    { CODEC_ID_MP3ON4, AOT_L2   }, /* layer 2 */
495
    { CODEC_ID_MP3ON4, AOT_L3   }, /* layer 3 */
496
    { CODEC_ID_MP4ALS, AOT_ALS  }, /* MPEG-4 ALS */
497
    { CODEC_ID_NONE,   AOT_NULL },
498
};
499

    
500
int ff_mov_read_esds(AVFormatContext *fc, ByteIOContext *pb, MOVAtom atom)
501
{
502
    AVStream *st;
503
    int tag, len;
504

    
505
    if (fc->nb_streams < 1)
506
        return 0;
507
    st = fc->streams[fc->nb_streams-1];
508

    
509
    get_be32(pb); /* version + flags */
510
    len = mp4_read_descr(fc, pb, &tag);
511
    if (tag == MP4ESDescrTag) {
512
        get_be16(pb); /* ID */
513
        get_byte(pb); /* priority */
514
    } else
515
        get_be16(pb); /* ID */
516

    
517
    len = mp4_read_descr(fc, pb, &tag);
518
    if (tag == MP4DecConfigDescrTag) {
519
        int object_type_id = get_byte(pb);
520
        get_byte(pb); /* stream type */
521
        get_be24(pb); /* buffer size db */
522
        get_be32(pb); /* max bitrate */
523
        get_be32(pb); /* avg bitrate */
524

    
525
        st->codec->codec_id= ff_codec_get_id(ff_mp4_obj_type, object_type_id);
526
        dprintf(fc, "esds object type id 0x%02x\n", object_type_id);
527
        len = mp4_read_descr(fc, pb, &tag);
528
        if (tag == MP4DecSpecificDescrTag) {
529
            dprintf(fc, "Specific MPEG4 header len=%d\n", len);
530
            if((uint64_t)len > (1<<30))
531
                return -1;
532
            av_free(st->codec->extradata);
533
            st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
534
            if (!st->codec->extradata)
535
                return AVERROR(ENOMEM);
536
            get_buffer(pb, st->codec->extradata, len);
537
            st->codec->extradata_size = len;
538
            if (st->codec->codec_id == CODEC_ID_AAC) {
539
                MPEG4AudioConfig cfg;
540
                ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
541
                                         st->codec->extradata_size);
542
                st->codec->channels = cfg.channels;
543
                if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
544
                    st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
545
                else if (cfg.ext_sample_rate)
546
                    st->codec->sample_rate = cfg.ext_sample_rate;
547
                else
548
                    st->codec->sample_rate = cfg.sample_rate;
549
                dprintf(fc, "mp4a config channels %d obj %d ext obj %d "
550
                        "sample rate %d ext sample rate %d\n", st->codec->channels,
551
                        cfg.object_type, cfg.ext_object_type,
552
                        cfg.sample_rate, cfg.ext_sample_rate);
553
                if (!(st->codec->codec_id = ff_codec_get_id(mp4_audio_types,
554
                                                            cfg.object_type)))
555
                    st->codec->codec_id = CODEC_ID_AAC;
556
            }
557
        }
558
    }
559
    return 0;
560
}
561

    
562
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
563
{
564
    return ff_mov_read_esds(c->fc, pb, atom);
565
}
566

    
567
static int mov_read_dac3(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
568
{
569
    AVStream *st;
570
    int ac3info, acmod, lfeon;
571

    
572
    if (c->fc->nb_streams < 1)
573
        return 0;
574
    st = c->fc->streams[c->fc->nb_streams-1];
575

    
576
    ac3info = get_be24(pb);
577
    acmod = (ac3info >> 11) & 0x7;
578
    lfeon = (ac3info >> 10) & 0x1;
579
    st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
580

    
581
    return 0;
582
}
583

    
584
static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
585
{
586
    const int num = get_be32(pb);
587
    const int den = get_be32(pb);
588
    AVStream *st;
589

    
590
    if (c->fc->nb_streams < 1)
591
        return 0;
592
    st = c->fc->streams[c->fc->nb_streams-1];
593

    
594
    if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
595
        (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
596
        av_log(c->fc, AV_LOG_WARNING,
597
               "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
598
               st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
599
               num, den);
600
    } else if (den != 0) {
601
        st->sample_aspect_ratio.num = num;
602
        st->sample_aspect_ratio.den = den;
603
    }
604
    return 0;
605
}
606

    
607
/* this atom contains actual media data */
608
static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
609
{
610
    if(atom.size == 0) /* wrong one (MP4) */
611
        return 0;
612
    c->found_mdat=1;
613
    return 0; /* now go for moov */
614
}
615

    
616
/* read major brand, minor version and compatible brands and store them as metadata */
617
static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
618
{
619
    uint32_t minor_ver;
620
    int comp_brand_size;
621
    char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
622
    char* comp_brands_str;
623
    uint8_t type[5] = {0};
624

    
625
    get_buffer(pb, type, 4);
626
    if (strcmp(type, "qt  "))
627
        c->isom = 1;
628
    av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
629
    av_metadata_set2(&c->fc->metadata, "major_brand", type, 0);
630
    minor_ver = get_be32(pb); /* minor version */
631
    snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
632
    av_metadata_set2(&c->fc->metadata, "minor_version", minor_ver_str, 0);
633

    
634
    comp_brand_size = atom.size - 8;
635
    if (comp_brand_size < 0)
636
        return -1;
637
    comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
638
    if (!comp_brands_str)
639
        return AVERROR(ENOMEM);
640
    get_buffer(pb, comp_brands_str, comp_brand_size);
641
    comp_brands_str[comp_brand_size] = 0;
642
    av_metadata_set2(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
643
    av_freep(&comp_brands_str);
644

    
645
    return 0;
646
}
647

    
648
/* this atom should contain all header atoms */
649
static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
650
{
651
    if (mov_read_default(c, pb, atom) < 0)
652
        return -1;
653
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
654
    /* so we don't parse the whole file if over a network */
655
    c->found_moov=1;
656
    return 0; /* now go for mdat */
657
}
658

    
659
static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
660
{
661
    c->fragment.moof_offset = url_ftell(pb) - 8;
662
    dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
663
    return mov_read_default(c, pb, atom);
664
}
665

    
666
static void mov_metadata_creation_time(AVMetadata **metadata, time_t time)
667
{
668
    char buffer[32];
669
    if (time) {
670
        time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
671
        strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", gmtime(&time));
672
        av_metadata_set2(metadata, "creation_time", buffer, 0);
673
    }
674
}
675

    
676
static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
677
{
678
    AVStream *st;
679
    MOVStreamContext *sc;
680
    int version;
681
    char language[4] = {0};
682
    unsigned lang;
683
    time_t creation_time;
684

    
685
    if (c->fc->nb_streams < 1)
686
        return 0;
687
    st = c->fc->streams[c->fc->nb_streams-1];
688
    sc = st->priv_data;
689

    
690
    version = get_byte(pb);
691
    if (version > 1)
692
        return -1; /* unsupported */
693

    
694
    get_be24(pb); /* flags */
695
    if (version == 1) {
696
        creation_time = get_be64(pb);
697
        get_be64(pb);
698
    } else {
699
        creation_time = get_be32(pb);
700
        get_be32(pb); /* modification time */
701
    }
702
    mov_metadata_creation_time(&st->metadata, creation_time);
703

    
704
    sc->time_scale = get_be32(pb);
705
    st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
706

    
707
    lang = get_be16(pb); /* language */
708
    if (ff_mov_lang_to_iso639(lang, language))
709
        av_metadata_set2(&st->metadata, "language", language, 0);
710
    get_be16(pb); /* quality */
711

    
712
    return 0;
713
}
714

    
715
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
716
{
717
    time_t creation_time;
718
    int version = get_byte(pb); /* version */
719
    get_be24(pb); /* flags */
720

    
721
    if (version == 1) {
722
        creation_time = get_be64(pb);
723
        get_be64(pb);
724
    } else {
725
        creation_time = get_be32(pb);
726
        get_be32(pb); /* modification time */
727
    }
728
    mov_metadata_creation_time(&c->fc->metadata, creation_time);
729
    c->time_scale = get_be32(pb); /* time scale */
730

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

    
733
    c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
734
    get_be32(pb); /* preferred scale */
735

    
736
    get_be16(pb); /* preferred volume */
737

    
738
    url_fskip(pb, 10); /* reserved */
739

    
740
    url_fskip(pb, 36); /* display matrix */
741

    
742
    get_be32(pb); /* preview time */
743
    get_be32(pb); /* preview duration */
744
    get_be32(pb); /* poster time */
745
    get_be32(pb); /* selection time */
746
    get_be32(pb); /* selection duration */
747
    get_be32(pb); /* current time */
748
    get_be32(pb); /* next track ID */
749

    
750
    return 0;
751
}
752

    
753
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
754
{
755
    AVStream *st;
756

    
757
    if (c->fc->nb_streams < 1)
758
        return 0;
759
    st = c->fc->streams[c->fc->nb_streams-1];
760

    
761
    if((uint64_t)atom.size > (1<<30))
762
        return -1;
763

    
764
    // currently SVQ3 decoder expect full STSD header - so let's fake it
765
    // this should be fixed and just SMI header should be passed
766
    av_free(st->codec->extradata);
767
    st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
768
    if (!st->codec->extradata)
769
        return AVERROR(ENOMEM);
770
    st->codec->extradata_size = 0x5a + atom.size;
771
    memcpy(st->codec->extradata, "SVQ3", 4); // fake
772
    get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
773
    dprintf(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
774
    return 0;
775
}
776

    
777
static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
778
{
779
    AVStream *st;
780
    int little_endian;
781

    
782
    if (c->fc->nb_streams < 1)
783
        return 0;
784
    st = c->fc->streams[c->fc->nb_streams-1];
785

    
786
    little_endian = get_be16(pb);
787
    dprintf(c->fc, "enda %d\n", little_endian);
788
    if (little_endian == 1) {
789
        switch (st->codec->codec_id) {
790
        case CODEC_ID_PCM_S24BE:
791
            st->codec->codec_id = CODEC_ID_PCM_S24LE;
792
            break;
793
        case CODEC_ID_PCM_S32BE:
794
            st->codec->codec_id = CODEC_ID_PCM_S32LE;
795
            break;
796
        case CODEC_ID_PCM_F32BE:
797
            st->codec->codec_id = CODEC_ID_PCM_F32LE;
798
            break;
799
        case CODEC_ID_PCM_F64BE:
800
            st->codec->codec_id = CODEC_ID_PCM_F64LE;
801
            break;
802
        default:
803
            break;
804
        }
805
    }
806
    return 0;
807
}
808

    
809
/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
810
static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
811
{
812
    AVStream *st;
813
    uint64_t size;
814
    uint8_t *buf;
815

    
816
    if (c->fc->nb_streams < 1) // will happen with jp2 files
817
        return 0;
818
    st= c->fc->streams[c->fc->nb_streams-1];
819
    size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
820
    if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
821
        return -1;
822
    buf= av_realloc(st->codec->extradata, size);
823
    if(!buf)
824
        return -1;
825
    st->codec->extradata= buf;
826
    buf+= st->codec->extradata_size;
827
    st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
828
    AV_WB32(       buf    , atom.size + 8);
829
    AV_WL32(       buf + 4, atom.type);
830
    get_buffer(pb, buf + 8, atom.size);
831
    return 0;
832
}
833

    
834
static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
835
{
836
    AVStream *st;
837

    
838
    if (c->fc->nb_streams < 1)
839
        return 0;
840
    st = c->fc->streams[c->fc->nb_streams-1];
841

    
842
    if((uint64_t)atom.size > (1<<30))
843
        return -1;
844

    
845
    if (st->codec->codec_id == CODEC_ID_QDM2) {
846
        // pass all frma atom to codec, needed at least for QDM2
847
        av_free(st->codec->extradata);
848
        st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
849
        if (!st->codec->extradata)
850
            return AVERROR(ENOMEM);
851
        st->codec->extradata_size = atom.size;
852
        get_buffer(pb, st->codec->extradata, atom.size);
853
    } else if (atom.size > 8) { /* to read frma, esds atoms */
854
        if (mov_read_default(c, pb, atom) < 0)
855
            return -1;
856
    } else
857
        url_fskip(pb, atom.size);
858
    return 0;
859
}
860

    
861
/**
862
 * This function reads atom content and puts data in extradata without tag
863
 * nor size unlike mov_read_extradata.
864
 */
865
static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
866
{
867
    AVStream *st;
868

    
869
    if (c->fc->nb_streams < 1)
870
        return 0;
871
    st = c->fc->streams[c->fc->nb_streams-1];
872

    
873
    if((uint64_t)atom.size > (1<<30))
874
        return -1;
875

    
876
    av_free(st->codec->extradata);
877
    st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
878
    if (!st->codec->extradata)
879
        return AVERROR(ENOMEM);
880
    st->codec->extradata_size = atom.size;
881
    get_buffer(pb, st->codec->extradata, atom.size);
882
    return 0;
883
}
884

    
885
/**
886
 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
887
 * but can have extradata appended at the end after the 40 bytes belonging
888
 * to the struct.
889
 */
890
static int mov_read_strf(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
891
{
892
    AVStream *st;
893

    
894
    if (c->fc->nb_streams < 1)
895
        return 0;
896
    if (atom.size <= 40)
897
        return 0;
898
    st = c->fc->streams[c->fc->nb_streams-1];
899

    
900
    if((uint64_t)atom.size > (1<<30))
901
        return -1;
902

    
903
    av_free(st->codec->extradata);
904
    st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
905
    if (!st->codec->extradata)
906
        return AVERROR(ENOMEM);
907
    st->codec->extradata_size = atom.size - 40;
908
    url_fskip(pb, 40);
909
    get_buffer(pb, st->codec->extradata, atom.size - 40);
910
    return 0;
911
}
912

    
913
static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
914
{
915
    AVStream *st;
916
    MOVStreamContext *sc;
917
    unsigned int i, entries;
918

    
919
    if (c->fc->nb_streams < 1)
920
        return 0;
921
    st = c->fc->streams[c->fc->nb_streams-1];
922
    sc = st->priv_data;
923

    
924
    get_byte(pb); /* version */
925
    get_be24(pb); /* flags */
926

    
927
    entries = get_be32(pb);
928

    
929
    if(entries >= UINT_MAX/sizeof(int64_t))
930
        return -1;
931

    
932
    sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
933
    if (!sc->chunk_offsets)
934
        return AVERROR(ENOMEM);
935
    sc->chunk_count = entries;
936

    
937
    if      (atom.type == MKTAG('s','t','c','o'))
938
        for(i=0; i<entries; i++)
939
            sc->chunk_offsets[i] = get_be32(pb);
940
    else if (atom.type == MKTAG('c','o','6','4'))
941
        for(i=0; i<entries; i++)
942
            sc->chunk_offsets[i] = get_be64(pb);
943
    else
944
        return -1;
945

    
946
    return 0;
947
}
948

    
949
/**
950
 * Compute codec id for 'lpcm' tag.
951
 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
952
 */
953
enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
954
{
955
    if (flags & 1) { // floating point
956
        if (flags & 2) { // big endian
957
            if      (bps == 32) return CODEC_ID_PCM_F32BE;
958
            else if (bps == 64) return CODEC_ID_PCM_F64BE;
959
        } else {
960
            if      (bps == 32) return CODEC_ID_PCM_F32LE;
961
            else if (bps == 64) return CODEC_ID_PCM_F64LE;
962
        }
963
    } else {
964
        if (flags & 2) {
965
            if      (bps == 8)
966
                // signed integer
967
                if (flags & 4)  return CODEC_ID_PCM_S8;
968
                else            return CODEC_ID_PCM_U8;
969
            else if (bps == 16) return CODEC_ID_PCM_S16BE;
970
            else if (bps == 24) return CODEC_ID_PCM_S24BE;
971
            else if (bps == 32) return CODEC_ID_PCM_S32BE;
972
        } else {
973
            if      (bps == 8)
974
                if (flags & 4)  return CODEC_ID_PCM_S8;
975
                else            return CODEC_ID_PCM_U8;
976
            else if (bps == 16) return CODEC_ID_PCM_S16LE;
977
            else if (bps == 24) return CODEC_ID_PCM_S24LE;
978
            else if (bps == 32) return CODEC_ID_PCM_S32LE;
979
        }
980
    }
981
    return CODEC_ID_NONE;
982
}
983

    
984
int ff_mov_read_stsd_entries(MOVContext *c, ByteIOContext *pb, int entries)
985
{
986
    AVStream *st;
987
    MOVStreamContext *sc;
988
    int j, pseudo_stream_id;
989

    
990
    if (c->fc->nb_streams < 1)
991
        return 0;
992
    st = c->fc->streams[c->fc->nb_streams-1];
993
    sc = st->priv_data;
994

    
995
    for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
996
        //Parsing Sample description table
997
        enum CodecID id;
998
        int dref_id = 1;
999
        MOVAtom a = { AV_RL32("stsd") };
1000
        int64_t start_pos = url_ftell(pb);
1001
        int size = get_be32(pb); /* size */
1002
        uint32_t format = get_le32(pb); /* data format */
1003

    
1004
        if (size >= 16) {
1005
            get_be32(pb); /* reserved */
1006
            get_be16(pb); /* reserved */
1007
            dref_id = get_be16(pb);
1008
        }
1009

    
1010
        if (st->codec->codec_tag &&
1011
            st->codec->codec_tag != format &&
1012
            (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
1013
                                   : st->codec->codec_tag != MKTAG('j','p','e','g'))
1014
           ){
1015
            /* Multiple fourcc, we skip JPEG. This is not correct, we should
1016
             * export it as a separate AVStream but this needs a few changes
1017
             * in the MOV demuxer, patch welcome. */
1018
            av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1019
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
1020
            continue;
1021
        }
1022
        sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1023
        sc->dref_id= dref_id;
1024

    
1025
        st->codec->codec_tag = format;
1026
        id = ff_codec_get_id(codec_movaudio_tags, format);
1027
        if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1028
            id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1029

    
1030
        if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1031
            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1032
        } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1033
                   format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1034
            id = ff_codec_get_id(codec_movvideo_tags, format);
1035
            if (id <= 0)
1036
                id = ff_codec_get_id(ff_codec_bmp_tags, format);
1037
            if (id > 0)
1038
                st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1039
            else if(st->codec->codec_type == AVMEDIA_TYPE_DATA){
1040
                id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1041
                if(id > 0)
1042
                    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1043
            }
1044
        }
1045

    
1046
        dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1047
                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1048
                (format >> 24) & 0xff, st->codec->codec_type);
1049

    
1050
        if(st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1051
            unsigned int color_depth, len;
1052
            int color_greyscale;
1053

    
1054
            st->codec->codec_id = id;
1055
            get_be16(pb); /* version */
1056
            get_be16(pb); /* revision level */
1057
            get_be32(pb); /* vendor */
1058
            get_be32(pb); /* temporal quality */
1059
            get_be32(pb); /* spatial quality */
1060

    
1061
            st->codec->width = get_be16(pb); /* width */
1062
            st->codec->height = get_be16(pb); /* height */
1063

    
1064
            get_be32(pb); /* horiz resolution */
1065
            get_be32(pb); /* vert resolution */
1066
            get_be32(pb); /* data size, always 0 */
1067
            get_be16(pb); /* frames per samples */
1068

    
1069
            len = get_byte(pb); /* codec name, pascal string */
1070
            if (len > 31)
1071
                len = 31;
1072
            mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1073
            if (len < 31)
1074
                url_fskip(pb, 31 - len);
1075
            /* codec_tag YV12 triggers an UV swap in rawdec.c */
1076
            if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1077
                st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1078

    
1079
            st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
1080
            st->codec->color_table_id = get_be16(pb); /* colortable id */
1081
            dprintf(c->fc, "depth %d, ctab id %d\n",
1082
                   st->codec->bits_per_coded_sample, st->codec->color_table_id);
1083
            /* figure out the palette situation */
1084
            color_depth = st->codec->bits_per_coded_sample & 0x1F;
1085
            color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1086

    
1087
            /* if the depth is 2, 4, or 8 bpp, file is palettized */
1088
            if ((color_depth == 2) || (color_depth == 4) ||
1089
                (color_depth == 8)) {
1090
                /* for palette traversal */
1091
                unsigned int color_start, color_count, color_end;
1092
                unsigned char r, g, b;
1093

    
1094
                st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
1095
                if (color_greyscale) {
1096
                    int color_index, color_dec;
1097
                    /* compute the greyscale palette */
1098
                    st->codec->bits_per_coded_sample = color_depth;
1099
                    color_count = 1 << color_depth;
1100
                    color_index = 255;
1101
                    color_dec = 256 / (color_count - 1);
1102
                    for (j = 0; j < color_count; j++) {
1103
                        r = g = b = color_index;
1104
                        st->codec->palctrl->palette[j] =
1105
                            (r << 16) | (g << 8) | (b);
1106
                        color_index -= color_dec;
1107
                        if (color_index < 0)
1108
                            color_index = 0;
1109
                    }
1110
                } else if (st->codec->color_table_id) {
1111
                    const uint8_t *color_table;
1112
                    /* if flag bit 3 is set, use the default palette */
1113
                    color_count = 1 << color_depth;
1114
                    if (color_depth == 2)
1115
                        color_table = ff_qt_default_palette_4;
1116
                    else if (color_depth == 4)
1117
                        color_table = ff_qt_default_palette_16;
1118
                    else
1119
                        color_table = ff_qt_default_palette_256;
1120

    
1121
                    for (j = 0; j < color_count; j++) {
1122
                        r = color_table[j * 3 + 0];
1123
                        g = color_table[j * 3 + 1];
1124
                        b = color_table[j * 3 + 2];
1125
                        st->codec->palctrl->palette[j] =
1126
                            (r << 16) | (g << 8) | (b);
1127
                    }
1128
                } else {
1129
                    /* load the palette from the file */
1130
                    color_start = get_be32(pb);
1131
                    color_count = get_be16(pb);
1132
                    color_end = get_be16(pb);
1133
                    if ((color_start <= 255) &&
1134
                        (color_end <= 255)) {
1135
                        for (j = color_start; j <= color_end; j++) {
1136
                            /* each R, G, or B component is 16 bits;
1137
                             * only use the top 8 bits; skip alpha bytes
1138
                             * up front */
1139
                            get_byte(pb);
1140
                            get_byte(pb);
1141
                            r = get_byte(pb);
1142
                            get_byte(pb);
1143
                            g = get_byte(pb);
1144
                            get_byte(pb);
1145
                            b = get_byte(pb);
1146
                            get_byte(pb);
1147
                            st->codec->palctrl->palette[j] =
1148
                                (r << 16) | (g << 8) | (b);
1149
                        }
1150
                    }
1151
                }
1152
                st->codec->palctrl->palette_changed = 1;
1153
            }
1154
        } else if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1155
            int bits_per_sample, flags;
1156
            uint16_t version = get_be16(pb);
1157

    
1158
            st->codec->codec_id = id;
1159
            get_be16(pb); /* revision level */
1160
            get_be32(pb); /* vendor */
1161

    
1162
            st->codec->channels = get_be16(pb);             /* channel count */
1163
            dprintf(c->fc, "audio channels %d\n", st->codec->channels);
1164
            st->codec->bits_per_coded_sample = get_be16(pb);      /* sample size */
1165

    
1166
            sc->audio_cid = get_be16(pb);
1167
            get_be16(pb); /* packet size = 0 */
1168

    
1169
            st->codec->sample_rate = ((get_be32(pb) >> 16));
1170

    
1171
            //Read QT version 1 fields. In version 0 these do not exist.
1172
            dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
1173
            if(!c->isom) {
1174
                if(version==1) {
1175
                    sc->samples_per_frame = get_be32(pb);
1176
                    get_be32(pb); /* bytes per packet */
1177
                    sc->bytes_per_frame = get_be32(pb);
1178
                    get_be32(pb); /* bytes per sample */
1179
                } else if(version==2) {
1180
                    get_be32(pb); /* sizeof struct only */
1181
                    st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
1182
                    st->codec->channels = get_be32(pb);
1183
                    get_be32(pb); /* always 0x7F000000 */
1184
                    st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
1185
                    flags = get_be32(pb); /* lpcm format specific flag */
1186
                    sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
1187
                    sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
1188
                    if (format == MKTAG('l','p','c','m'))
1189
                        st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1190
                }
1191
            }
1192

    
1193
            switch (st->codec->codec_id) {
1194
            case CODEC_ID_PCM_S8:
1195
            case CODEC_ID_PCM_U8:
1196
                if (st->codec->bits_per_coded_sample == 16)
1197
                    st->codec->codec_id = CODEC_ID_PCM_S16BE;
1198
                break;
1199
            case CODEC_ID_PCM_S16LE:
1200
            case CODEC_ID_PCM_S16BE:
1201
                if (st->codec->bits_per_coded_sample == 8)
1202
                    st->codec->codec_id = CODEC_ID_PCM_S8;
1203
                else if (st->codec->bits_per_coded_sample == 24)
1204
                    st->codec->codec_id =
1205
                        st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1206
                        CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1207
                break;
1208
            /* set values for old format before stsd version 1 appeared */
1209
            case CODEC_ID_MACE3:
1210
                sc->samples_per_frame = 6;
1211
                sc->bytes_per_frame = 2*st->codec->channels;
1212
                break;
1213
            case CODEC_ID_MACE6:
1214
                sc->samples_per_frame = 6;
1215
                sc->bytes_per_frame = 1*st->codec->channels;
1216
                break;
1217
            case CODEC_ID_ADPCM_IMA_QT:
1218
                sc->samples_per_frame = 64;
1219
                sc->bytes_per_frame = 34*st->codec->channels;
1220
                break;
1221
            case CODEC_ID_GSM:
1222
                sc->samples_per_frame = 160;
1223
                sc->bytes_per_frame = 33;
1224
                break;
1225
            default:
1226
                break;
1227
            }
1228

    
1229
            bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1230
            if (bits_per_sample) {
1231
                st->codec->bits_per_coded_sample = bits_per_sample;
1232
                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1233
            }
1234
        } else if(st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1235
            // ttxt stsd contains display flags, justification, background
1236
            // color, fonts, and default styles, so fake an atom to read it
1237
            MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
1238
            if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1239
                mov_read_glbl(c, pb, fake_atom);
1240
            st->codec->codec_id= id;
1241
            st->codec->width = sc->width;
1242
            st->codec->height = sc->height;
1243
        } else {
1244
            /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1245
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
1246
        }
1247
        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1248
        a.size = size - (url_ftell(pb) - start_pos);
1249
        if (a.size > 8) {
1250
            if (mov_read_default(c, pb, a) < 0)
1251
                return -1;
1252
        } else if (a.size > 0)
1253
            url_fskip(pb, a.size);
1254
    }
1255

    
1256
    if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1257
        st->codec->sample_rate= sc->time_scale;
1258

    
1259
    /* special codec parameters handling */
1260
    switch (st->codec->codec_id) {
1261
#if CONFIG_DV_DEMUXER
1262
    case CODEC_ID_DVAUDIO:
1263
        c->dv_fctx = avformat_alloc_context();
1264
        c->dv_demux = dv_init_demux(c->dv_fctx);
1265
        if (!c->dv_demux) {
1266
            av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1267
            return -1;
1268
        }
1269
        sc->dv_audio_container = 1;
1270
        st->codec->codec_id = CODEC_ID_PCM_S16LE;
1271
        break;
1272
#endif
1273
    /* no ifdef since parameters are always those */
1274
    case CODEC_ID_QCELP:
1275
        // force sample rate for qcelp when not stored in mov
1276
        if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1277
            st->codec->sample_rate = 8000;
1278
        st->codec->frame_size= 160;
1279
        st->codec->channels= 1; /* really needed */
1280
        break;
1281
    case CODEC_ID_AMR_NB:
1282
    case CODEC_ID_AMR_WB:
1283
        st->codec->frame_size= sc->samples_per_frame;
1284
        st->codec->channels= 1; /* really needed */
1285
        /* force sample rate for amr, stsd in 3gp does not store sample rate */
1286
        if (st->codec->codec_id == CODEC_ID_AMR_NB)
1287
            st->codec->sample_rate = 8000;
1288
        else if (st->codec->codec_id == CODEC_ID_AMR_WB)
1289
            st->codec->sample_rate = 16000;
1290
        break;
1291
    case CODEC_ID_MP2:
1292
    case CODEC_ID_MP3:
1293
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1294
        st->need_parsing = AVSTREAM_PARSE_FULL;
1295
        break;
1296
    case CODEC_ID_GSM:
1297
    case CODEC_ID_ADPCM_MS:
1298
    case CODEC_ID_ADPCM_IMA_WAV:
1299
        st->codec->block_align = sc->bytes_per_frame;
1300
        break;
1301
    case CODEC_ID_ALAC:
1302
        if (st->codec->extradata_size == 36) {
1303
            st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1304
            st->codec->channels   = AV_RB8 (st->codec->extradata+21);
1305
        }
1306
        break;
1307
    default:
1308
        break;
1309
    }
1310

    
1311
    return 0;
1312
}
1313

    
1314
static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1315
{
1316
    int entries;
1317

    
1318
    get_byte(pb); /* version */
1319
    get_be24(pb); /* flags */
1320
    entries = get_be32(pb);
1321

    
1322
    return ff_mov_read_stsd_entries(c, pb, entries);
1323
}
1324

    
1325
static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1326
{
1327
    AVStream *st;
1328
    MOVStreamContext *sc;
1329
    unsigned int i, entries;
1330

    
1331
    if (c->fc->nb_streams < 1)
1332
        return 0;
1333
    st = c->fc->streams[c->fc->nb_streams-1];
1334
    sc = st->priv_data;
1335

    
1336
    get_byte(pb); /* version */
1337
    get_be24(pb); /* flags */
1338

    
1339
    entries = get_be32(pb);
1340

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

    
1343
    if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
1344
        return -1;
1345
    sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1346
    if (!sc->stsc_data)
1347
        return AVERROR(ENOMEM);
1348
    sc->stsc_count = entries;
1349

    
1350
    for(i=0; i<entries; i++) {
1351
        sc->stsc_data[i].first = get_be32(pb);
1352
        sc->stsc_data[i].count = get_be32(pb);
1353
        sc->stsc_data[i].id = get_be32(pb);
1354
    }
1355
    return 0;
1356
}
1357

    
1358
static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1359
{
1360
    AVStream *st;
1361
    MOVStreamContext *sc;
1362
    unsigned i, entries;
1363

    
1364
    if (c->fc->nb_streams < 1)
1365
        return 0;
1366
    st = c->fc->streams[c->fc->nb_streams-1];
1367
    sc = st->priv_data;
1368

    
1369
    get_be32(pb); // version + flags
1370

    
1371
    entries = get_be32(pb);
1372
    if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1373
        return -1;
1374
    sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1375
    if (!sc->stps_data)
1376
        return AVERROR(ENOMEM);
1377
    sc->stps_count = entries;
1378

    
1379
    for (i = 0; i < entries; i++) {
1380
        sc->stps_data[i] = get_be32(pb);
1381
        //dprintf(c->fc, "stps %d\n", sc->stps_data[i]);
1382
    }
1383

    
1384
    return 0;
1385
}
1386

    
1387
static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1388
{
1389
    AVStream *st;
1390
    MOVStreamContext *sc;
1391
    unsigned int i, entries;
1392

    
1393
    if (c->fc->nb_streams < 1)
1394
        return 0;
1395
    st = c->fc->streams[c->fc->nb_streams-1];
1396
    sc = st->priv_data;
1397

    
1398
    get_byte(pb); /* version */
1399
    get_be24(pb); /* flags */
1400

    
1401
    entries = get_be32(pb);
1402

    
1403
    dprintf(c->fc, "keyframe_count = %d\n", entries);
1404

    
1405
    if(entries >= UINT_MAX / sizeof(int))
1406
        return -1;
1407
    sc->keyframes = av_malloc(entries * sizeof(int));
1408
    if (!sc->keyframes)
1409
        return AVERROR(ENOMEM);
1410
    sc->keyframe_count = entries;
1411

    
1412
    for(i=0; i<entries; i++) {
1413
        sc->keyframes[i] = get_be32(pb);
1414
        //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1415
    }
1416
    return 0;
1417
}
1418

    
1419
static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1420
{
1421
    AVStream *st;
1422
    MOVStreamContext *sc;
1423
    unsigned int i, entries, sample_size, field_size, num_bytes;
1424
    GetBitContext gb;
1425
    unsigned char* buf;
1426

    
1427
    if (c->fc->nb_streams < 1)
1428
        return 0;
1429
    st = c->fc->streams[c->fc->nb_streams-1];
1430
    sc = st->priv_data;
1431

    
1432
    get_byte(pb); /* version */
1433
    get_be24(pb); /* flags */
1434

    
1435
    if (atom.type == MKTAG('s','t','s','z')) {
1436
        sample_size = get_be32(pb);
1437
        if (!sc->sample_size) /* do not overwrite value computed in stsd */
1438
            sc->sample_size = sample_size;
1439
        field_size = 32;
1440
    } else {
1441
        sample_size = 0;
1442
        get_be24(pb); /* reserved */
1443
        field_size = get_byte(pb);
1444
    }
1445
    entries = get_be32(pb);
1446

    
1447
    dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1448

    
1449
    sc->sample_count = entries;
1450
    if (sample_size)
1451
        return 0;
1452

    
1453
    if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1454
        av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1455
        return -1;
1456
    }
1457

    
1458
    if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1459
        return -1;
1460
    sc->sample_sizes = av_malloc(entries * sizeof(int));
1461
    if (!sc->sample_sizes)
1462
        return AVERROR(ENOMEM);
1463

    
1464
    num_bytes = (entries*field_size+4)>>3;
1465

    
1466
    buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1467
    if (!buf) {
1468
        av_freep(&sc->sample_sizes);
1469
        return AVERROR(ENOMEM);
1470
    }
1471

    
1472
    if (get_buffer(pb, buf, num_bytes) < num_bytes) {
1473
        av_freep(&sc->sample_sizes);
1474
        av_free(buf);
1475
        return -1;
1476
    }
1477

    
1478
    init_get_bits(&gb, buf, 8*num_bytes);
1479

    
1480
    for(i=0; i<entries; i++)
1481
        sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1482

    
1483
    av_free(buf);
1484
    return 0;
1485
}
1486

    
1487
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1488
{
1489
    AVStream *st;
1490
    MOVStreamContext *sc;
1491
    unsigned int i, entries;
1492
    int64_t duration=0;
1493
    int64_t total_sample_count=0;
1494

    
1495
    if (c->fc->nb_streams < 1)
1496
        return 0;
1497
    st = c->fc->streams[c->fc->nb_streams-1];
1498
    sc = st->priv_data;
1499

    
1500
    get_byte(pb); /* version */
1501
    get_be24(pb); /* flags */
1502
    entries = get_be32(pb);
1503

    
1504
    dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1505

    
1506
    if(entries >= UINT_MAX / sizeof(*sc->stts_data))
1507
        return -1;
1508
    sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1509
    if (!sc->stts_data)
1510
        return AVERROR(ENOMEM);
1511
    sc->stts_count = entries;
1512

    
1513
    for(i=0; i<entries; i++) {
1514
        int sample_duration;
1515
        int sample_count;
1516

    
1517
        sample_count=get_be32(pb);
1518
        sample_duration = get_be32(pb);
1519
        sc->stts_data[i].count= sample_count;
1520
        sc->stts_data[i].duration= sample_duration;
1521

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

    
1524
        duration+=(int64_t)sample_duration*sample_count;
1525
        total_sample_count+=sample_count;
1526
    }
1527

    
1528
    st->nb_frames= total_sample_count;
1529
    if(duration)
1530
        st->duration= duration;
1531
    return 0;
1532
}
1533

    
1534
static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1535
{
1536
    AVStream *st;
1537
    MOVStreamContext *sc;
1538
    unsigned int i, entries;
1539

    
1540
    if (c->fc->nb_streams < 1)
1541
        return 0;
1542
    st = c->fc->streams[c->fc->nb_streams-1];
1543
    sc = st->priv_data;
1544

    
1545
    get_byte(pb); /* version */
1546
    get_be24(pb); /* flags */
1547
    entries = get_be32(pb);
1548

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

    
1551
    if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
1552
        return -1;
1553
    sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1554
    if (!sc->ctts_data)
1555
        return AVERROR(ENOMEM);
1556
    sc->ctts_count = entries;
1557

    
1558
    for(i=0; i<entries; i++) {
1559
        int count    =get_be32(pb);
1560
        int duration =get_be32(pb);
1561

    
1562
        sc->ctts_data[i].count   = count;
1563
        sc->ctts_data[i].duration= duration;
1564
        if (duration < 0)
1565
            sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1566
    }
1567

    
1568
    dprintf(c->fc, "dts shift %d\n", sc->dts_shift);
1569

    
1570
    return 0;
1571
}
1572

    
1573
static void mov_build_index(MOVContext *mov, AVStream *st)
1574
{
1575
    MOVStreamContext *sc = st->priv_data;
1576
    int64_t current_offset;
1577
    int64_t current_dts = 0;
1578
    unsigned int stts_index = 0;
1579
    unsigned int stsc_index = 0;
1580
    unsigned int stss_index = 0;
1581
    unsigned int stps_index = 0;
1582
    unsigned int i, j;
1583
    uint64_t stream_size = 0;
1584

    
1585
    /* adjust first dts according to edit list */
1586
    if (sc->time_offset) {
1587
        int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
1588
        current_dts = -rescaled;
1589
        if (sc->ctts_data && sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1590
            /* more than 16 frames delay, dts are likely wrong
1591
               this happens with files created by iMovie */
1592
            sc->wrong_dts = 1;
1593
            st->codec->has_b_frames = 1;
1594
        }
1595
    }
1596

    
1597
    /* only use old uncompressed audio chunk demuxing when stts specifies it */
1598
    if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1599
          sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1600
        unsigned int current_sample = 0;
1601
        unsigned int stts_sample = 0;
1602
        unsigned int sample_size;
1603
        unsigned int distance = 0;
1604
        int key_off = sc->keyframes && sc->keyframes[0] == 1;
1605

    
1606
        current_dts -= sc->dts_shift;
1607

    
1608
        if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
1609
            return;
1610
        st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
1611
        if (!st->index_entries)
1612
            return;
1613
        st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
1614

    
1615
        for (i = 0; i < sc->chunk_count; i++) {
1616
            current_offset = sc->chunk_offsets[i];
1617
            if (stsc_index + 1 < sc->stsc_count &&
1618
                i + 1 == sc->stsc_data[stsc_index + 1].first)
1619
                stsc_index++;
1620
            for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1621
                int keyframe = 0;
1622
                if (current_sample >= sc->sample_count) {
1623
                    av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1624
                    return;
1625
                }
1626

    
1627
                if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1628
                    keyframe = 1;
1629
                    if (stss_index + 1 < sc->keyframe_count)
1630
                        stss_index++;
1631
                } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1632
                    keyframe = 1;
1633
                    if (stps_index + 1 < sc->stps_count)
1634
                        stps_index++;
1635
                }
1636
                if (keyframe)
1637
                    distance = 0;
1638
                sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1639
                if(sc->pseudo_stream_id == -1 ||
1640
                   sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1641
                    AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1642
                    e->pos = current_offset;
1643
                    e->timestamp = current_dts;
1644
                    e->size = sample_size;
1645
                    e->min_distance = distance;
1646
                    e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1647
                    dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1648
                            "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1649
                            current_offset, current_dts, sample_size, distance, keyframe);
1650
                }
1651

    
1652
                current_offset += sample_size;
1653
                stream_size += sample_size;
1654
                current_dts += sc->stts_data[stts_index].duration;
1655
                distance++;
1656
                stts_sample++;
1657
                current_sample++;
1658
                if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1659
                    stts_sample = 0;
1660
                    stts_index++;
1661
                }
1662
            }
1663
        }
1664
        if (st->duration > 0)
1665
            st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1666
    } else {
1667
        unsigned chunk_samples, total = 0;
1668

    
1669
        // compute total chunk count
1670
        for (i = 0; i < sc->stsc_count; i++) {
1671
            unsigned count, chunk_count;
1672

    
1673
            chunk_samples = sc->stsc_data[i].count;
1674
            if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1675
                av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1676
                return;
1677
            }
1678

    
1679
            if (sc->samples_per_frame >= 160) { // gsm
1680
                count = chunk_samples / sc->samples_per_frame;
1681
            } else if (sc->samples_per_frame > 1) {
1682
                unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1683
                count = (chunk_samples+samples-1) / samples;
1684
            } else {
1685
                count = (chunk_samples+1023) / 1024;
1686
            }
1687

    
1688
            if (i < sc->stsc_count - 1)
1689
                chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1690
            else
1691
                chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1692
            total += chunk_count * count;
1693
        }
1694

    
1695
        dprintf(mov->fc, "chunk count %d\n", total);
1696
        if (total >= UINT_MAX / sizeof(*st->index_entries))
1697
            return;
1698
        st->index_entries = av_malloc(total*sizeof(*st->index_entries));
1699
        if (!st->index_entries)
1700
            return;
1701
        st->index_entries_allocated_size = total*sizeof(*st->index_entries);
1702

    
1703
        // populate index
1704
        for (i = 0; i < sc->chunk_count; i++) {
1705
            current_offset = sc->chunk_offsets[i];
1706
            if (stsc_index + 1 < sc->stsc_count &&
1707
                i + 1 == sc->stsc_data[stsc_index + 1].first)
1708
                stsc_index++;
1709
            chunk_samples = sc->stsc_data[stsc_index].count;
1710

    
1711
            while (chunk_samples > 0) {
1712
                AVIndexEntry *e;
1713
                unsigned size, samples;
1714

    
1715
                if (sc->samples_per_frame >= 160) { // gsm
1716
                    samples = sc->samples_per_frame;
1717
                    size = sc->bytes_per_frame;
1718
                } else {
1719
                    if (sc->samples_per_frame > 1) {
1720
                        samples = FFMIN((1024 / sc->samples_per_frame)*
1721
                                        sc->samples_per_frame, chunk_samples);
1722
                        size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1723
                    } else {
1724
                        samples = FFMIN(1024, chunk_samples);
1725
                        size = samples * sc->sample_size;
1726
                    }
1727
                }
1728

    
1729
                if (st->nb_index_entries >= total) {
1730
                    av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1731
                    return;
1732
                }
1733
                e = &st->index_entries[st->nb_index_entries++];
1734
                e->pos = current_offset;
1735
                e->timestamp = current_dts;
1736
                e->size = size;
1737
                e->min_distance = 0;
1738
                e->flags = AVINDEX_KEYFRAME;
1739
                dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1740
                        "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1741
                        size, samples);
1742

    
1743
                current_offset += size;
1744
                current_dts += samples;
1745
                chunk_samples -= samples;
1746
            }
1747
        }
1748
    }
1749
}
1750

    
1751
static int mov_open_dref(ByteIOContext **pb, char *src, MOVDref *ref)
1752
{
1753
    /* try relative path, we do not try the absolute because it can leak information about our
1754
       system to an attacker */
1755
    if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1756
        char filename[1024];
1757
        char *src_path;
1758
        int i, l;
1759

    
1760
        /* find a source dir */
1761
        src_path = strrchr(src, '/');
1762
        if (src_path)
1763
            src_path++;
1764
        else
1765
            src_path = src;
1766

    
1767
        /* find a next level down to target */
1768
        for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1769
            if (ref->path[l] == '/') {
1770
                if (i == ref->nlvl_to - 1)
1771
                    break;
1772
                else
1773
                    i++;
1774
            }
1775

    
1776
        /* compose filename if next level down to target was found */
1777
        if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
1778
            memcpy(filename, src, src_path - src);
1779
            filename[src_path - src] = 0;
1780

    
1781
            for (i = 1; i < ref->nlvl_from; i++)
1782
                av_strlcat(filename, "../", 1024);
1783

    
1784
            av_strlcat(filename, ref->path + l + 1, 1024);
1785

    
1786
            if (!url_fopen(pb, filename, URL_RDONLY))
1787
                return 0;
1788
        }
1789
    }
1790

    
1791
    return AVERROR(ENOENT);
1792
};
1793

    
1794
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1795
{
1796
    AVStream *st;
1797
    MOVStreamContext *sc;
1798
    int ret;
1799

    
1800
    st = av_new_stream(c->fc, c->fc->nb_streams);
1801
    if (!st) return AVERROR(ENOMEM);
1802
    sc = av_mallocz(sizeof(MOVStreamContext));
1803
    if (!sc) return AVERROR(ENOMEM);
1804

    
1805
    st->priv_data = sc;
1806
    st->codec->codec_type = AVMEDIA_TYPE_DATA;
1807
    sc->ffindex = st->index;
1808

    
1809
    if ((ret = mov_read_default(c, pb, atom)) < 0)
1810
        return ret;
1811

    
1812
    /* sanity checks */
1813
    if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1814
                            (!sc->sample_size && !sc->sample_count))) {
1815
        av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1816
               st->index);
1817
        return 0;
1818
    }
1819

    
1820
    if (!sc->time_scale) {
1821
        av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
1822
        sc->time_scale = c->time_scale;
1823
        if (!sc->time_scale)
1824
            sc->time_scale = 1;
1825
    }
1826

    
1827
    av_set_pts_info(st, 64, 1, sc->time_scale);
1828

    
1829
    if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1830
        !st->codec->frame_size && sc->stts_count == 1) {
1831
        st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
1832
                                           st->codec->sample_rate, sc->time_scale);
1833
        dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
1834
    }
1835

    
1836
    mov_build_index(c, st);
1837

    
1838
    if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1839
        MOVDref *dref = &sc->drefs[sc->dref_id - 1];
1840
        if (mov_open_dref(&sc->pb, c->fc->filename, dref) < 0)
1841
            av_log(c->fc, AV_LOG_ERROR,
1842
                   "stream %d, error opening alias: path='%s', dir='%s', "
1843
                   "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
1844
                   st->index, dref->path, dref->dir, dref->filename,
1845
                   dref->volume, dref->nlvl_from, dref->nlvl_to);
1846
    } else
1847
        sc->pb = c->fc->pb;
1848

    
1849
    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1850
        if (!st->sample_aspect_ratio.num &&
1851
            (st->codec->width != sc->width || st->codec->height != sc->height)) {
1852
            st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
1853
                                             ((double)st->codec->width * sc->height), INT_MAX);
1854
        }
1855

    
1856
        av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1857
                  sc->time_scale*st->nb_frames, st->duration, INT_MAX);
1858
    }
1859

    
1860
    switch (st->codec->codec_id) {
1861
#if CONFIG_H261_DECODER
1862
    case CODEC_ID_H261:
1863
#endif
1864
#if CONFIG_H263_DECODER
1865
    case CODEC_ID_H263:
1866
#endif
1867
#if CONFIG_H264_DECODER
1868
    case CODEC_ID_H264:
1869
#endif
1870
#if CONFIG_MPEG4_DECODER
1871
    case CODEC_ID_MPEG4:
1872
#endif
1873
        st->codec->width = 0; /* let decoder init width/height */
1874
        st->codec->height= 0;
1875
        break;
1876
    }
1877

    
1878
    /* Do not need those anymore. */
1879
    av_freep(&sc->chunk_offsets);
1880
    av_freep(&sc->stsc_data);
1881
    av_freep(&sc->sample_sizes);
1882
    av_freep(&sc->keyframes);
1883
    av_freep(&sc->stts_data);
1884
    av_freep(&sc->stps_data);
1885

    
1886
    return 0;
1887
}
1888

    
1889
static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1890
{
1891
    int ret;
1892
    c->itunes_metadata = 1;
1893
    ret = mov_read_default(c, pb, atom);
1894
    c->itunes_metadata = 0;
1895
    return ret;
1896
}
1897

    
1898
static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1899
{
1900
    while (atom.size > 8) {
1901
        uint32_t tag = get_le32(pb);
1902
        atom.size -= 4;
1903
        if (tag == MKTAG('h','d','l','r')) {
1904
            url_fseek(pb, -8, SEEK_CUR);
1905
            atom.size += 8;
1906
            return mov_read_default(c, pb, atom);
1907
        }
1908
    }
1909
    return 0;
1910
}
1911

    
1912
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1913
{
1914
    int i;
1915
    int width;
1916
    int height;
1917
    int64_t disp_transform[2];
1918
    int display_matrix[3][2];
1919
    AVStream *st;
1920
    MOVStreamContext *sc;
1921
    int version;
1922

    
1923
    if (c->fc->nb_streams < 1)
1924
        return 0;
1925
    st = c->fc->streams[c->fc->nb_streams-1];
1926
    sc = st->priv_data;
1927

    
1928
    version = get_byte(pb);
1929
    get_be24(pb); /* flags */
1930
    /*
1931
    MOV_TRACK_ENABLED 0x0001
1932
    MOV_TRACK_IN_MOVIE 0x0002
1933
    MOV_TRACK_IN_PREVIEW 0x0004
1934
    MOV_TRACK_IN_POSTER 0x0008
1935
    */
1936

    
1937
    if (version == 1) {
1938
        get_be64(pb);
1939
        get_be64(pb);
1940
    } else {
1941
        get_be32(pb); /* creation time */
1942
        get_be32(pb); /* modification time */
1943
    }
1944
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1945
    get_be32(pb); /* reserved */
1946

    
1947
    /* highlevel (considering edits) duration in movie timebase */
1948
    (version == 1) ? get_be64(pb) : get_be32(pb);
1949
    get_be32(pb); /* reserved */
1950
    get_be32(pb); /* reserved */
1951

    
1952
    get_be16(pb); /* layer */
1953
    get_be16(pb); /* alternate group */
1954
    get_be16(pb); /* volume */
1955
    get_be16(pb); /* reserved */
1956

    
1957
    //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
1958
    // they're kept in fixed point format through all calculations
1959
    // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
1960
    for (i = 0; i < 3; i++) {
1961
        display_matrix[i][0] = get_be32(pb);   // 16.16 fixed point
1962
        display_matrix[i][1] = get_be32(pb);   // 16.16 fixed point
1963
        get_be32(pb);           // 2.30 fixed point (not used)
1964
    }
1965

    
1966
    width = get_be32(pb);       // 16.16 fixed point track width
1967
    height = get_be32(pb);      // 16.16 fixed point track height
1968
    sc->width = width >> 16;
1969
    sc->height = height >> 16;
1970

    
1971
    // transform the display width/height according to the matrix
1972
    // skip this if the display matrix is the default identity matrix
1973
    // or if it is rotating the picture, ex iPhone 3GS
1974
    // to keep the same scale, use [width height 1<<16]
1975
    if (width && height &&
1976
        ((display_matrix[0][0] != 65536  ||
1977
          display_matrix[1][1] != 65536) &&
1978
         !display_matrix[0][1] &&
1979
         !display_matrix[1][0] &&
1980
         !display_matrix[2][0] && !display_matrix[2][1])) {
1981
        for (i = 0; i < 2; i++)
1982
            disp_transform[i] =
1983
                (int64_t)  width  * display_matrix[0][i] +
1984
                (int64_t)  height * display_matrix[1][i] +
1985
                ((int64_t) display_matrix[2][i] << 16);
1986

    
1987
        //sample aspect ratio is new width/height divided by old width/height
1988
        st->sample_aspect_ratio = av_d2q(
1989
            ((double) disp_transform[0] * height) /
1990
            ((double) disp_transform[1] * width), INT_MAX);
1991
    }
1992
    return 0;
1993
}
1994

    
1995
static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1996
{
1997
    MOVFragment *frag = &c->fragment;
1998
    MOVTrackExt *trex = NULL;
1999
    int flags, track_id, i;
2000

    
2001
    get_byte(pb); /* version */
2002
    flags = get_be24(pb);
2003

    
2004
    track_id = get_be32(pb);
2005
    if (!track_id)
2006
        return -1;
2007
    frag->track_id = track_id;
2008
    for (i = 0; i < c->trex_count; i++)
2009
        if (c->trex_data[i].track_id == frag->track_id) {
2010
            trex = &c->trex_data[i];
2011
            break;
2012
        }
2013
    if (!trex) {
2014
        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2015
        return -1;
2016
    }
2017

    
2018
    if (flags & 0x01) frag->base_data_offset = get_be64(pb);
2019
    else              frag->base_data_offset = frag->moof_offset;
2020
    if (flags & 0x02) frag->stsd_id          = get_be32(pb);
2021
    else              frag->stsd_id          = trex->stsd_id;
2022

    
2023
    frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
2024
    frag->size     = flags & 0x10 ? get_be32(pb) : trex->size;
2025
    frag->flags    = flags & 0x20 ? get_be32(pb) : trex->flags;
2026
    dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
2027
    return 0;
2028
}
2029

    
2030
static int mov_read_chap(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2031
{
2032
    c->chapter_track = get_be32(pb);
2033
    return 0;
2034
}
2035

    
2036
static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2037
{
2038
    MOVTrackExt *trex;
2039

    
2040
    if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2041
        return -1;
2042
    trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2043
    if (!trex)
2044
        return AVERROR(ENOMEM);
2045
    c->trex_data = trex;
2046
    trex = &c->trex_data[c->trex_count++];
2047
    get_byte(pb); /* version */
2048
    get_be24(pb); /* flags */
2049
    trex->track_id = get_be32(pb);
2050
    trex->stsd_id  = get_be32(pb);
2051
    trex->duration = get_be32(pb);
2052
    trex->size     = get_be32(pb);
2053
    trex->flags    = get_be32(pb);
2054
    return 0;
2055
}
2056

    
2057
static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2058
{
2059
    MOVFragment *frag = &c->fragment;
2060
    AVStream *st = NULL;
2061
    MOVStreamContext *sc;
2062
    uint64_t offset;
2063
    int64_t dts;
2064
    int data_offset = 0;
2065
    unsigned entries, first_sample_flags = frag->flags;
2066
    int flags, distance, i;
2067

    
2068
    for (i = 0; i < c->fc->nb_streams; i++) {
2069
        if (c->fc->streams[i]->id == frag->track_id) {
2070
            st = c->fc->streams[i];
2071
            break;
2072
        }
2073
    }
2074
    if (!st) {
2075
        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2076
        return -1;
2077
    }
2078
    sc = st->priv_data;
2079
    if (sc->pseudo_stream_id+1 != frag->stsd_id)
2080
        return 0;
2081
    get_byte(pb); /* version */
2082
    flags = get_be24(pb);
2083
    entries = get_be32(pb);
2084
    dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
2085
    if (flags & 0x001) data_offset        = get_be32(pb);
2086
    if (flags & 0x004) first_sample_flags = get_be32(pb);
2087
    if (flags & 0x800) {
2088
        MOVStts *ctts_data;
2089
        if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2090
            return -1;
2091
        ctts_data = av_realloc(sc->ctts_data,
2092
                               (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2093
        if (!ctts_data)
2094
            return AVERROR(ENOMEM);
2095
        sc->ctts_data = ctts_data;
2096
    }
2097
    dts = st->duration;
2098
    offset = frag->base_data_offset + data_offset;
2099
    distance = 0;
2100
    dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2101
    for (i = 0; i < entries; i++) {
2102
        unsigned sample_size = frag->size;
2103
        int sample_flags = i ? frag->flags : first_sample_flags;
2104
        unsigned sample_duration = frag->duration;
2105
        int keyframe;
2106

    
2107
        if (flags & 0x100) sample_duration = get_be32(pb);
2108
        if (flags & 0x200) sample_size     = get_be32(pb);
2109
        if (flags & 0x400) sample_flags    = get_be32(pb);
2110
        if (flags & 0x800) {
2111
            sc->ctts_data[sc->ctts_count].count = 1;
2112
            sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
2113
            sc->ctts_count++;
2114
        }
2115
        if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
2116
             (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
2117
            distance = 0;
2118
        av_add_index_entry(st, offset, dts, sample_size, distance,
2119
                           keyframe ? AVINDEX_KEYFRAME : 0);
2120
        dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2121
                "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2122
                offset, dts, sample_size, distance, keyframe);
2123
        distance++;
2124
        dts += sample_duration;
2125
        offset += sample_size;
2126
    }
2127
    frag->moof_offset = offset;
2128
    st->duration = dts;
2129
    return 0;
2130
}
2131

    
2132
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2133
/* like the files created with Adobe Premiere 5.0, for samples see */
2134
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2135
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2136
{
2137
    int err;
2138

    
2139
    if (atom.size < 8)
2140
        return 0; /* continue */
2141
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2142
        url_fskip(pb, atom.size - 4);
2143
        return 0;
2144
    }
2145
    atom.type = get_le32(pb);
2146
    atom.size -= 8;
2147
    if (atom.type != MKTAG('m','d','a','t')) {
2148
        url_fskip(pb, atom.size);
2149
        return 0;
2150
    }
2151
    err = mov_read_mdat(c, pb, atom);
2152
    return err;
2153
}
2154

    
2155
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2156
{
2157
#if CONFIG_ZLIB
2158
    ByteIOContext ctx;
2159
    uint8_t *cmov_data;
2160
    uint8_t *moov_data; /* uncompressed data */
2161
    long cmov_len, moov_len;
2162
    int ret = -1;
2163

    
2164
    get_be32(pb); /* dcom atom */
2165
    if (get_le32(pb) != MKTAG('d','c','o','m'))
2166
        return -1;
2167
    if (get_le32(pb) != MKTAG('z','l','i','b')) {
2168
        av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2169
        return -1;
2170
    }
2171
    get_be32(pb); /* cmvd atom */
2172
    if (get_le32(pb) != MKTAG('c','m','v','d'))
2173
        return -1;
2174
    moov_len = get_be32(pb); /* uncompressed size */
2175
    cmov_len = atom.size - 6 * 4;
2176

    
2177
    cmov_data = av_malloc(cmov_len);
2178
    if (!cmov_data)
2179
        return AVERROR(ENOMEM);
2180
    moov_data = av_malloc(moov_len);
2181
    if (!moov_data) {
2182
        av_free(cmov_data);
2183
        return AVERROR(ENOMEM);
2184
    }
2185
    get_buffer(pb, cmov_data, cmov_len);
2186
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2187
        goto free_and_return;
2188
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2189
        goto free_and_return;
2190
    atom.type = MKTAG('m','o','o','v');
2191
    atom.size = moov_len;
2192
#ifdef DEBUG
2193
//    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
2194
#endif
2195
    ret = mov_read_default(c, &ctx, atom);
2196
free_and_return:
2197
    av_free(moov_data);
2198
    av_free(cmov_data);
2199
    return ret;
2200
#else
2201
    av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2202
    return -1;
2203
#endif
2204
}
2205

    
2206
/* edit list atom */
2207
static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2208
{
2209
    MOVStreamContext *sc;
2210
    int i, edit_count;
2211

    
2212
    if (c->fc->nb_streams < 1)
2213
        return 0;
2214
    sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2215

    
2216
    get_byte(pb); /* version */
2217
    get_be24(pb); /* flags */
2218
    edit_count = get_be32(pb); /* entries */
2219

    
2220
    if((uint64_t)edit_count*12+8 > atom.size)
2221
        return -1;
2222

    
2223
    for(i=0; i<edit_count; i++){
2224
        int time;
2225
        int duration = get_be32(pb); /* Track duration */
2226
        time = get_be32(pb); /* Media time */
2227
        get_be32(pb); /* Media rate */
2228
        if (i == 0 && time >= -1) {
2229
            sc->time_offset = time != -1 ? time : -duration;
2230
        }
2231
    }
2232

    
2233
    if(edit_count > 1)
2234
        av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2235
               "a/v desync might occur, patch welcome\n");
2236

    
2237
    dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2238
    return 0;
2239
}
2240

    
2241
static const MOVParseTableEntry mov_default_parse_table[] = {
2242
{ MKTAG('a','v','s','s'), mov_read_extradata },
2243
{ MKTAG('c','h','p','l'), mov_read_chpl },
2244
{ MKTAG('c','o','6','4'), mov_read_stco },
2245
{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2246
{ MKTAG('d','i','n','f'), mov_read_default },
2247
{ MKTAG('d','r','e','f'), mov_read_dref },
2248
{ MKTAG('e','d','t','s'), mov_read_default },
2249
{ MKTAG('e','l','s','t'), mov_read_elst },
2250
{ MKTAG('e','n','d','a'), mov_read_enda },
2251
{ MKTAG('f','i','e','l'), mov_read_extradata },
2252
{ MKTAG('f','t','y','p'), mov_read_ftyp },
2253
{ MKTAG('g','l','b','l'), mov_read_glbl },
2254
{ MKTAG('h','d','l','r'), mov_read_hdlr },
2255
{ MKTAG('i','l','s','t'), mov_read_ilst },
2256
{ MKTAG('j','p','2','h'), mov_read_extradata },
2257
{ MKTAG('m','d','a','t'), mov_read_mdat },
2258
{ MKTAG('m','d','h','d'), mov_read_mdhd },
2259
{ MKTAG('m','d','i','a'), mov_read_default },
2260
{ MKTAG('m','e','t','a'), mov_read_meta },
2261
{ MKTAG('m','i','n','f'), mov_read_default },
2262
{ MKTAG('m','o','o','f'), mov_read_moof },
2263
{ MKTAG('m','o','o','v'), mov_read_moov },
2264
{ MKTAG('m','v','e','x'), mov_read_default },
2265
{ MKTAG('m','v','h','d'), mov_read_mvhd },
2266
{ MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2267
{ MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2268
{ MKTAG('a','v','c','C'), mov_read_glbl },
2269
{ MKTAG('p','a','s','p'), mov_read_pasp },
2270
{ MKTAG('s','t','b','l'), mov_read_default },
2271
{ MKTAG('s','t','c','o'), mov_read_stco },
2272
{ MKTAG('s','t','p','s'), mov_read_stps },
2273
{ MKTAG('s','t','r','f'), mov_read_strf },
2274
{ MKTAG('s','t','s','c'), mov_read_stsc },
2275
{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2276
{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2277
{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2278
{ MKTAG('s','t','t','s'), mov_read_stts },
2279
{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2280
{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2281
{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2282
{ MKTAG('t','r','a','k'), mov_read_trak },
2283
{ MKTAG('t','r','a','f'), mov_read_default },
2284
{ MKTAG('t','r','e','f'), mov_read_default },
2285
{ MKTAG('c','h','a','p'), mov_read_chap },
2286
{ MKTAG('t','r','e','x'), mov_read_trex },
2287
{ MKTAG('t','r','u','n'), mov_read_trun },
2288
{ MKTAG('u','d','t','a'), mov_read_default },
2289
{ MKTAG('w','a','v','e'), mov_read_wave },
2290
{ MKTAG('e','s','d','s'), mov_read_esds },
2291
{ MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2292
{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2293
{ MKTAG('c','m','o','v'), mov_read_cmov },
2294
{ 0, NULL }
2295
};
2296

    
2297
static int mov_probe(AVProbeData *p)
2298
{
2299
    unsigned int offset;
2300
    uint32_t tag;
2301
    int score = 0;
2302

    
2303
    /* check file header */
2304
    offset = 0;
2305
    for(;;) {
2306
        /* ignore invalid offset */
2307
        if ((offset + 8) > (unsigned int)p->buf_size)
2308
            return score;
2309
        tag = AV_RL32(p->buf + offset + 4);
2310
        switch(tag) {
2311
        /* check for obvious tags */
2312
        case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2313
        case MKTAG('m','o','o','v'):
2314
        case MKTAG('m','d','a','t'):
2315
        case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2316
        case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2317
        case MKTAG('f','t','y','p'):
2318
            return AVPROBE_SCORE_MAX;
2319
        /* those are more common words, so rate then a bit less */
2320
        case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2321
        case MKTAG('w','i','d','e'):
2322
        case MKTAG('f','r','e','e'):
2323
        case MKTAG('j','u','n','k'):
2324
        case MKTAG('p','i','c','t'):
2325
            return AVPROBE_SCORE_MAX - 5;
2326
        case MKTAG(0x82,0x82,0x7f,0x7d):
2327
        case MKTAG('s','k','i','p'):
2328
        case MKTAG('u','u','i','d'):
2329
        case MKTAG('p','r','f','l'):
2330
            offset = AV_RB32(p->buf+offset) + offset;
2331
            /* if we only find those cause probedata is too small at least rate them */
2332
            score = AVPROBE_SCORE_MAX - 50;
2333
            break;
2334
        default:
2335
            /* unrecognized tag */
2336
            return score;
2337
        }
2338
    }
2339
    return score;
2340
}
2341

    
2342
// must be done after parsing all trak because there's no order requirement
2343
static void mov_read_chapters(AVFormatContext *s)
2344
{
2345
    MOVContext *mov = s->priv_data;
2346
    AVStream *st = NULL;
2347
    MOVStreamContext *sc;
2348
    int64_t cur_pos;
2349
    uint8_t *title = NULL;
2350
    int i, len, i8, i16;
2351

    
2352
    for (i = 0; i < s->nb_streams; i++)
2353
        if (s->streams[i]->id == mov->chapter_track) {
2354
            st = s->streams[i];
2355
            break;
2356
        }
2357
    if (!st) {
2358
        av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2359
        return;
2360
    }
2361

    
2362
    st->discard = AVDISCARD_ALL;
2363
    sc = st->priv_data;
2364
    cur_pos = url_ftell(sc->pb);
2365

    
2366
    for (i = 0; i < st->nb_index_entries; i++) {
2367
        AVIndexEntry *sample = &st->index_entries[i];
2368
        int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2369

    
2370
        if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2371
            av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2372
            goto finish;
2373
        }
2374

    
2375
        title = av_malloc(sample->size+2);
2376
        get_buffer(sc->pb, title, sample->size);
2377

    
2378
        // the first two bytes are the length of the title
2379
        len = AV_RB16(title);
2380
        if (len > sample->size-2)
2381
            continue;
2382

    
2383
        // The samples could theoretically be in any encoding if there's an encd
2384
        // atom following, but in practice are only utf-8 or utf-16, distinguished
2385
        // instead by the presence of a BOM
2386
        if (AV_RB16(title+2) == 0xfeff) {
2387
            uint8_t *utf8 = av_malloc(2*len+3);
2388

    
2389
            i8 = i16 = 0;
2390
            while (i16 < len) {
2391
                uint32_t ch;
2392
                uint8_t tmp;
2393
                GET_UTF16(ch, i16 < len ? AV_RB16(title + (i16+=2)) : 0, break;)
2394
                PUT_UTF8(ch, tmp, if (i8 < 2*len) utf8[2+i8++] = tmp;)
2395
            }
2396
            utf8[2+i8] = 0;
2397
            av_freep(&title);
2398
            title = utf8;
2399
        }
2400

    
2401
        ff_new_chapter(s, i, st->time_base, sample->timestamp, end, title+2);
2402
        av_freep(&title);
2403
    }
2404
finish:
2405
    av_free(title);
2406
    url_fseek(sc->pb, cur_pos, SEEK_SET);
2407
}
2408

    
2409
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
2410
{
2411
    MOVContext *mov = s->priv_data;
2412
    ByteIOContext *pb = s->pb;
2413
    int err;
2414
    MOVAtom atom = { AV_RL32("root") };
2415

    
2416
    mov->fc = s;
2417
    /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2418
    if(!url_is_streamed(pb))
2419
        atom.size = url_fsize(pb);
2420
    else
2421
        atom.size = INT64_MAX;
2422

    
2423
    /* check MOV header */
2424
    if ((err = mov_read_default(mov, pb, atom)) < 0) {
2425
        av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2426
        return err;
2427
    }
2428
    if (!mov->found_moov) {
2429
        av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2430
        return -1;
2431
    }
2432
    dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
2433

    
2434
    if (!url_is_streamed(pb) && mov->chapter_track > 0)
2435
        mov_read_chapters(s);
2436

    
2437
    return 0;
2438
}
2439

    
2440
static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2441
{
2442
    AVIndexEntry *sample = NULL;
2443
    int64_t best_dts = INT64_MAX;
2444
    int i;
2445
    for (i = 0; i < s->nb_streams; i++) {
2446
        AVStream *avst = s->streams[i];
2447
        MOVStreamContext *msc = avst->priv_data;
2448
        if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2449
            AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2450
            int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2451
            dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2452
            if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
2453
                (!url_is_streamed(s->pb) &&
2454
                 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2455
                 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2456
                  (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2457
                sample = current_sample;
2458
                best_dts = dts;
2459
                *st = avst;
2460
            }
2461
        }
2462
    }
2463
    return sample;
2464
}
2465

    
2466
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2467
{
2468
    MOVContext *mov = s->priv_data;
2469
    MOVStreamContext *sc;
2470
    AVIndexEntry *sample;
2471
    AVStream *st = NULL;
2472
    int ret;
2473
 retry:
2474
    sample = mov_find_next_sample(s, &st);
2475
    if (!sample) {
2476
        mov->found_mdat = 0;
2477
        if (!url_is_streamed(s->pb) ||
2478
            mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2479
            url_feof(s->pb))
2480
            return AVERROR_EOF;
2481
        dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
2482
        goto retry;
2483
    }
2484
    sc = st->priv_data;
2485
    /* must be done just before reading, to avoid infinite loop on sample */
2486
    sc->current_sample++;
2487

    
2488
    if (st->discard != AVDISCARD_ALL) {
2489
        if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2490
            av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2491
                   sc->ffindex, sample->pos);
2492
            return -1;
2493
        }
2494
        ret = av_get_packet(sc->pb, pkt, sample->size);
2495
        if (ret < 0)
2496
            return ret;
2497
#if CONFIG_DV_DEMUXER
2498
        if (mov->dv_demux && sc->dv_audio_container) {
2499
            dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2500
            av_free(pkt->data);
2501
            pkt->size = 0;
2502
            ret = dv_get_packet(mov->dv_demux, pkt);
2503
            if (ret < 0)
2504
                return ret;
2505
        }
2506
#endif
2507
    }
2508

    
2509
    pkt->stream_index = sc->ffindex;
2510
    pkt->dts = sample->timestamp;
2511
    if (sc->ctts_data) {
2512
        pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2513
        /* update ctts context */
2514
        sc->ctts_sample++;
2515
        if (sc->ctts_index < sc->ctts_count &&
2516
            sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2517
            sc->ctts_index++;
2518
            sc->ctts_sample = 0;
2519
        }
2520
        if (sc->wrong_dts)
2521
            pkt->dts = AV_NOPTS_VALUE;
2522
    } else {
2523
        int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2524
            st->index_entries[sc->current_sample].timestamp : st->duration;
2525
        pkt->duration = next_dts - pkt->dts;
2526
        pkt->pts = pkt->dts;
2527
    }
2528
    if (st->discard == AVDISCARD_ALL)
2529
        goto retry;
2530
    pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2531
    pkt->pos = sample->pos;
2532
    dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2533
            pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2534
    return 0;
2535
}
2536

    
2537
static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2538
{
2539
    MOVStreamContext *sc = st->priv_data;
2540
    int sample, time_sample;
2541
    int i;
2542

    
2543
    sample = av_index_search_timestamp(st, timestamp, flags);
2544
    dprintf(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2545
    if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2546
        sample = 0;
2547
    if (sample < 0) /* not sure what to do */
2548
        return -1;
2549
    sc->current_sample = sample;
2550
    dprintf(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2551
    /* adjust ctts index */
2552
    if (sc->ctts_data) {
2553
        time_sample = 0;
2554
        for (i = 0; i < sc->ctts_count; i++) {
2555
            int next = time_sample + sc->ctts_data[i].count;
2556
            if (next > sc->current_sample) {
2557
                sc->ctts_index = i;
2558
                sc->ctts_sample = sc->current_sample - time_sample;
2559
                break;
2560
            }
2561
            time_sample = next;
2562
        }
2563
    }
2564
    return sample;
2565
}
2566

    
2567
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2568
{
2569
    AVStream *st;
2570
    int64_t seek_timestamp, timestamp;
2571
    int sample;
2572
    int i;
2573

    
2574
    if (stream_index >= s->nb_streams)
2575
        return -1;
2576
    if (sample_time < 0)
2577
        sample_time = 0;
2578

    
2579
    st = s->streams[stream_index];
2580
    sample = mov_seek_stream(s, st, sample_time, flags);
2581
    if (sample < 0)
2582
        return -1;
2583

    
2584
    /* adjust seek timestamp to found sample timestamp */
2585
    seek_timestamp = st->index_entries[sample].timestamp;
2586

    
2587
    for (i = 0; i < s->nb_streams; i++) {
2588
        st = s->streams[i];
2589
        if (stream_index == i)
2590
            continue;
2591

    
2592
        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2593
        mov_seek_stream(s, st, timestamp, flags);
2594
    }
2595
    return 0;
2596
}
2597

    
2598
static int mov_read_close(AVFormatContext *s)
2599
{
2600
    MOVContext *mov = s->priv_data;
2601
    int i, j;
2602

    
2603
    for (i = 0; i < s->nb_streams; i++) {
2604
        AVStream *st = s->streams[i];
2605
        MOVStreamContext *sc = st->priv_data;
2606

    
2607
        av_freep(&sc->ctts_data);
2608
        for (j = 0; j < sc->drefs_count; j++) {
2609
            av_freep(&sc->drefs[j].path);
2610
            av_freep(&sc->drefs[j].dir);
2611
        }
2612
        av_freep(&sc->drefs);
2613
        if (sc->pb && sc->pb != s->pb)
2614
            url_fclose(sc->pb);
2615

    
2616
        av_freep(&st->codec->palctrl);
2617
    }
2618

    
2619
    if (mov->dv_demux) {
2620
        for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
2621
            av_freep(&mov->dv_fctx->streams[i]->codec);
2622
            av_freep(&mov->dv_fctx->streams[i]);
2623
        }
2624
        av_freep(&mov->dv_fctx);
2625
        av_freep(&mov->dv_demux);
2626
    }
2627

    
2628
    av_freep(&mov->trex_data);
2629

    
2630
    return 0;
2631
}
2632

    
2633
AVInputFormat mov_demuxer = {
2634
    "mov,mp4,m4a,3gp,3g2,mj2",
2635
    NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2636
    sizeof(MOVContext),
2637
    mov_probe,
2638
    mov_read_header,
2639
    mov_read_packet,
2640
    mov_read_close,
2641
    mov_read_seek,
2642
};