Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 798c6fac

History | View | Annotate | Download (85.2 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/get_bits.h"
35

    
36
#if CONFIG_ZLIB
37
#include <zlib.h>
38
#endif
39

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

    
60
#include "qtpalette.h"
61

    
62

    
63
#undef NDEBUG
64
#include <assert.h>
65

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

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

    
79
static const MOVParseTableEntry mov_default_parse_table[];
80

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

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

    
89
    get_be16(pb); // total tracks
90

    
91
    return 0;
92
}
93

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

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

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

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

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

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

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

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

    
195
    str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
196

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

    
218
    return 0;
219
}
220

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

    
227
    if ((atom.size -= 5) < 0)
228
        return 0;
229

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

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

    
240
        start = get_be64(pb);
241
        str_len = get_byte(pb);
242

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

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

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

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

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

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

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

    
313
        total_size += a.size;
314
    }
315

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

    
319
    return 0;
320
}
321

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

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

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

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

    
347
        if (size < 12)
348
            return -1;
349

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

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

    
359
            url_fskip(pb, 10);
360

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

    
367
            url_fskip(pb, 12);
368

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

    
375
            url_fskip(pb, 16);
376

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

    
383
            url_fskip(pb, 16);
384

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

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

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

    
435
    st = c->fc->streams[c->fc->nb_streams-1];
436

    
437
    get_byte(pb); /* version */
438
    get_be24(pb); /* flags */
439

    
440
    /* component type */
441
    ctype = get_le32(pb);
442
    type = get_le32(pb); /* component subtype */
443

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

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

    
456
    get_be32(pb); /* component  manufacture */
457
    get_be32(pb); /* component flags */
458
    get_be32(pb); /* component flags mask */
459

    
460
    return 0;
461
}
462

    
463
int ff_mov_read_esds(AVFormatContext *fc, ByteIOContext *pb, MOVAtom atom)
464
{
465
    AVStream *st;
466
    int tag, len;
467

    
468
    if (fc->nb_streams < 1)
469
        return 0;
470
    st = fc->streams[fc->nb_streams-1];
471

    
472
    get_be32(pb); /* version + flags */
473
    len = ff_mp4_read_descr(fc, pb, &tag);
474
    if (tag == MP4ESDescrTag) {
475
        get_be16(pb); /* ID */
476
        get_byte(pb); /* priority */
477
    } else
478
        get_be16(pb); /* ID */
479

    
480
    len = ff_mp4_read_descr(fc, pb, &tag);
481
    if (tag == MP4DecConfigDescrTag)
482
        ff_mp4_read_dec_config_descr(fc, st, pb);
483
    return 0;
484
}
485

    
486
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
487
{
488
    return ff_mov_read_esds(c->fc, pb, atom);
489
}
490

    
491
static int mov_read_dac3(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
492
{
493
    AVStream *st;
494
    int ac3info, acmod, lfeon;
495

    
496
    if (c->fc->nb_streams < 1)
497
        return 0;
498
    st = c->fc->streams[c->fc->nb_streams-1];
499

    
500
    ac3info = get_be24(pb);
501
    acmod = (ac3info >> 11) & 0x7;
502
    lfeon = (ac3info >> 10) & 0x1;
503
    st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
504

    
505
    return 0;
506
}
507

    
508
static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
509
{
510
    const int num = get_be32(pb);
511
    const int den = get_be32(pb);
512
    AVStream *st;
513

    
514
    if (c->fc->nb_streams < 1)
515
        return 0;
516
    st = c->fc->streams[c->fc->nb_streams-1];
517

    
518
    if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
519
        (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
520
        av_log(c->fc, AV_LOG_WARNING,
521
               "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
522
               st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
523
               num, den);
524
    } else if (den != 0) {
525
        st->sample_aspect_ratio.num = num;
526
        st->sample_aspect_ratio.den = den;
527
    }
528
    return 0;
529
}
530

    
531
/* this atom contains actual media data */
532
static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
533
{
534
    if(atom.size == 0) /* wrong one (MP4) */
535
        return 0;
536
    c->found_mdat=1;
537
    return 0; /* now go for moov */
538
}
539

    
540
/* read major brand, minor version and compatible brands and store them as metadata */
541
static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
542
{
543
    uint32_t minor_ver;
544
    int comp_brand_size;
545
    char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
546
    char* comp_brands_str;
547
    uint8_t type[5] = {0};
548

    
549
    get_buffer(pb, type, 4);
550
    if (strcmp(type, "qt  "))
551
        c->isom = 1;
552
    av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
553
    av_metadata_set2(&c->fc->metadata, "major_brand", type, 0);
554
    minor_ver = get_be32(pb); /* minor version */
555
    snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
556
    av_metadata_set2(&c->fc->metadata, "minor_version", minor_ver_str, 0);
557

    
558
    comp_brand_size = atom.size - 8;
559
    if (comp_brand_size < 0)
560
        return -1;
561
    comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
562
    if (!comp_brands_str)
563
        return AVERROR(ENOMEM);
564
    get_buffer(pb, comp_brands_str, comp_brand_size);
565
    comp_brands_str[comp_brand_size] = 0;
566
    av_metadata_set2(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
567
    av_freep(&comp_brands_str);
568

    
569
    return 0;
570
}
571

    
572
/* this atom should contain all header atoms */
573
static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
574
{
575
    if (mov_read_default(c, pb, atom) < 0)
576
        return -1;
577
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
578
    /* so we don't parse the whole file if over a network */
579
    c->found_moov=1;
580
    return 0; /* now go for mdat */
581
}
582

    
583
static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
584
{
585
    c->fragment.moof_offset = url_ftell(pb) - 8;
586
    dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
587
    return mov_read_default(c, pb, atom);
588
}
589

    
590
static void mov_metadata_creation_time(AVMetadata **metadata, time_t time)
591
{
592
    char buffer[32];
593
    if (time) {
594
        time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
595
        strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", gmtime(&time));
596
        av_metadata_set2(metadata, "creation_time", buffer, 0);
597
    }
598
}
599

    
600
static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
601
{
602
    AVStream *st;
603
    MOVStreamContext *sc;
604
    int version;
605
    char language[4] = {0};
606
    unsigned lang;
607
    time_t creation_time;
608

    
609
    if (c->fc->nb_streams < 1)
610
        return 0;
611
    st = c->fc->streams[c->fc->nb_streams-1];
612
    sc = st->priv_data;
613

    
614
    version = get_byte(pb);
615
    if (version > 1)
616
        return -1; /* unsupported */
617

    
618
    get_be24(pb); /* flags */
619
    if (version == 1) {
620
        creation_time = get_be64(pb);
621
        get_be64(pb);
622
    } else {
623
        creation_time = get_be32(pb);
624
        get_be32(pb); /* modification time */
625
    }
626
    mov_metadata_creation_time(&st->metadata, creation_time);
627

    
628
    sc->time_scale = get_be32(pb);
629
    st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
630

    
631
    lang = get_be16(pb); /* language */
632
    if (ff_mov_lang_to_iso639(lang, language))
633
        av_metadata_set2(&st->metadata, "language", language, 0);
634
    get_be16(pb); /* quality */
635

    
636
    return 0;
637
}
638

    
639
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
640
{
641
    time_t creation_time;
642
    int version = get_byte(pb); /* version */
643
    get_be24(pb); /* flags */
644

    
645
    if (version == 1) {
646
        creation_time = get_be64(pb);
647
        get_be64(pb);
648
    } else {
649
        creation_time = get_be32(pb);
650
        get_be32(pb); /* modification time */
651
    }
652
    mov_metadata_creation_time(&c->fc->metadata, creation_time);
653
    c->time_scale = get_be32(pb); /* time scale */
654

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

    
657
    c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
658
    get_be32(pb); /* preferred scale */
659

    
660
    get_be16(pb); /* preferred volume */
661

    
662
    url_fskip(pb, 10); /* reserved */
663

    
664
    url_fskip(pb, 36); /* display matrix */
665

    
666
    get_be32(pb); /* preview time */
667
    get_be32(pb); /* preview duration */
668
    get_be32(pb); /* poster time */
669
    get_be32(pb); /* selection time */
670
    get_be32(pb); /* selection duration */
671
    get_be32(pb); /* current time */
672
    get_be32(pb); /* next track ID */
673

    
674
    return 0;
675
}
676

    
677
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
678
{
679
    AVStream *st;
680

    
681
    if (c->fc->nb_streams < 1)
682
        return 0;
683
    st = c->fc->streams[c->fc->nb_streams-1];
684

    
685
    if((uint64_t)atom.size > (1<<30))
686
        return -1;
687

    
688
    // currently SVQ3 decoder expect full STSD header - so let's fake it
689
    // this should be fixed and just SMI header should be passed
690
    av_free(st->codec->extradata);
691
    st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
692
    if (!st->codec->extradata)
693
        return AVERROR(ENOMEM);
694
    st->codec->extradata_size = 0x5a + atom.size;
695
    memcpy(st->codec->extradata, "SVQ3", 4); // fake
696
    get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
697
    dprintf(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
698
    return 0;
699
}
700

    
701
static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
702
{
703
    AVStream *st;
704
    int little_endian;
705

    
706
    if (c->fc->nb_streams < 1)
707
        return 0;
708
    st = c->fc->streams[c->fc->nb_streams-1];
709

    
710
    little_endian = get_be16(pb);
711
    dprintf(c->fc, "enda %d\n", little_endian);
712
    if (little_endian == 1) {
713
        switch (st->codec->codec_id) {
714
        case CODEC_ID_PCM_S24BE:
715
            st->codec->codec_id = CODEC_ID_PCM_S24LE;
716
            break;
717
        case CODEC_ID_PCM_S32BE:
718
            st->codec->codec_id = CODEC_ID_PCM_S32LE;
719
            break;
720
        case CODEC_ID_PCM_F32BE:
721
            st->codec->codec_id = CODEC_ID_PCM_F32LE;
722
            break;
723
        case CODEC_ID_PCM_F64BE:
724
            st->codec->codec_id = CODEC_ID_PCM_F64LE;
725
            break;
726
        default:
727
            break;
728
        }
729
    }
730
    return 0;
731
}
732

    
733
/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
734
static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
735
{
736
    AVStream *st;
737
    uint64_t size;
738
    uint8_t *buf;
739

    
740
    if (c->fc->nb_streams < 1) // will happen with jp2 files
741
        return 0;
742
    st= c->fc->streams[c->fc->nb_streams-1];
743
    size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
744
    if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
745
        return -1;
746
    buf= av_realloc(st->codec->extradata, size);
747
    if(!buf)
748
        return -1;
749
    st->codec->extradata= buf;
750
    buf+= st->codec->extradata_size;
751
    st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
752
    AV_WB32(       buf    , atom.size + 8);
753
    AV_WL32(       buf + 4, atom.type);
754
    get_buffer(pb, buf + 8, atom.size);
755
    return 0;
756
}
757

    
758
static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
759
{
760
    AVStream *st;
761

    
762
    if (c->fc->nb_streams < 1)
763
        return 0;
764
    st = c->fc->streams[c->fc->nb_streams-1];
765

    
766
    if((uint64_t)atom.size > (1<<30))
767
        return -1;
768

    
769
    if (st->codec->codec_id == CODEC_ID_QDM2) {
770
        // pass all frma atom to codec, needed at least for QDM2
771
        av_free(st->codec->extradata);
772
        st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
773
        if (!st->codec->extradata)
774
            return AVERROR(ENOMEM);
775
        st->codec->extradata_size = atom.size;
776
        get_buffer(pb, st->codec->extradata, atom.size);
777
    } else if (atom.size > 8) { /* to read frma, esds atoms */
778
        if (mov_read_default(c, pb, atom) < 0)
779
            return -1;
780
    } else
781
        url_fskip(pb, atom.size);
782
    return 0;
783
}
784

    
785
/**
786
 * This function reads atom content and puts data in extradata without tag
787
 * nor size unlike mov_read_extradata.
788
 */
789
static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
790
{
791
    AVStream *st;
792

    
793
    if (c->fc->nb_streams < 1)
794
        return 0;
795
    st = c->fc->streams[c->fc->nb_streams-1];
796

    
797
    if((uint64_t)atom.size > (1<<30))
798
        return -1;
799

    
800
    av_free(st->codec->extradata);
801
    st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
802
    if (!st->codec->extradata)
803
        return AVERROR(ENOMEM);
804
    st->codec->extradata_size = atom.size;
805
    get_buffer(pb, st->codec->extradata, atom.size);
806
    return 0;
807
}
808

    
809
/**
810
 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
811
 * but can have extradata appended at the end after the 40 bytes belonging
812
 * to the struct.
813
 */
814
static int mov_read_strf(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
815
{
816
    AVStream *st;
817

    
818
    if (c->fc->nb_streams < 1)
819
        return 0;
820
    if (atom.size <= 40)
821
        return 0;
822
    st = c->fc->streams[c->fc->nb_streams-1];
823

    
824
    if((uint64_t)atom.size > (1<<30))
825
        return -1;
826

    
827
    av_free(st->codec->extradata);
828
    st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
829
    if (!st->codec->extradata)
830
        return AVERROR(ENOMEM);
831
    st->codec->extradata_size = atom.size - 40;
832
    url_fskip(pb, 40);
833
    get_buffer(pb, st->codec->extradata, atom.size - 40);
834
    return 0;
835
}
836

    
837
static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
838
{
839
    AVStream *st;
840
    MOVStreamContext *sc;
841
    unsigned int i, entries;
842

    
843
    if (c->fc->nb_streams < 1)
844
        return 0;
845
    st = c->fc->streams[c->fc->nb_streams-1];
846
    sc = st->priv_data;
847

    
848
    get_byte(pb); /* version */
849
    get_be24(pb); /* flags */
850

    
851
    entries = get_be32(pb);
852

    
853
    if(entries >= UINT_MAX/sizeof(int64_t))
854
        return -1;
855

    
856
    sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
857
    if (!sc->chunk_offsets)
858
        return AVERROR(ENOMEM);
859
    sc->chunk_count = entries;
860

    
861
    if      (atom.type == MKTAG('s','t','c','o'))
862
        for(i=0; i<entries; i++)
863
            sc->chunk_offsets[i] = get_be32(pb);
864
    else if (atom.type == MKTAG('c','o','6','4'))
865
        for(i=0; i<entries; i++)
866
            sc->chunk_offsets[i] = get_be64(pb);
867
    else
868
        return -1;
869

    
870
    return 0;
871
}
872

    
873
/**
874
 * Compute codec id for 'lpcm' tag.
875
 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
876
 */
877
enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
878
{
879
    if (flags & 1) { // floating point
880
        if (flags & 2) { // big endian
881
            if      (bps == 32) return CODEC_ID_PCM_F32BE;
882
            else if (bps == 64) return CODEC_ID_PCM_F64BE;
883
        } else {
884
            if      (bps == 32) return CODEC_ID_PCM_F32LE;
885
            else if (bps == 64) return CODEC_ID_PCM_F64LE;
886
        }
887
    } else {
888
        if (flags & 2) {
889
            if      (bps == 8)
890
                // signed integer
891
                if (flags & 4)  return CODEC_ID_PCM_S8;
892
                else            return CODEC_ID_PCM_U8;
893
            else if (bps == 16) return CODEC_ID_PCM_S16BE;
894
            else if (bps == 24) return CODEC_ID_PCM_S24BE;
895
            else if (bps == 32) return CODEC_ID_PCM_S32BE;
896
        } else {
897
            if      (bps == 8)
898
                if (flags & 4)  return CODEC_ID_PCM_S8;
899
                else            return CODEC_ID_PCM_U8;
900
            else if (bps == 16) return CODEC_ID_PCM_S16LE;
901
            else if (bps == 24) return CODEC_ID_PCM_S24LE;
902
            else if (bps == 32) return CODEC_ID_PCM_S32LE;
903
        }
904
    }
905
    return CODEC_ID_NONE;
906
}
907

    
908
int ff_mov_read_stsd_entries(MOVContext *c, ByteIOContext *pb, int entries)
909
{
910
    AVStream *st;
911
    MOVStreamContext *sc;
912
    int j, pseudo_stream_id;
913

    
914
    if (c->fc->nb_streams < 1)
915
        return 0;
916
    st = c->fc->streams[c->fc->nb_streams-1];
917
    sc = st->priv_data;
918

    
919
    for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
920
        //Parsing Sample description table
921
        enum CodecID id;
922
        int dref_id = 1;
923
        MOVAtom a = { AV_RL32("stsd") };
924
        int64_t start_pos = url_ftell(pb);
925
        int size = get_be32(pb); /* size */
926
        uint32_t format = get_le32(pb); /* data format */
927

    
928
        if (size >= 16) {
929
            get_be32(pb); /* reserved */
930
            get_be16(pb); /* reserved */
931
            dref_id = get_be16(pb);
932
        }
933

    
934
        if (st->codec->codec_tag &&
935
            st->codec->codec_tag != format &&
936
            (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
937
                                   : st->codec->codec_tag != MKTAG('j','p','e','g'))
938
           ){
939
            /* Multiple fourcc, we skip JPEG. This is not correct, we should
940
             * export it as a separate AVStream but this needs a few changes
941
             * in the MOV demuxer, patch welcome. */
942
            av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
943
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
944
            continue;
945
        }
946
        sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
947
        sc->dref_id= dref_id;
948

    
949
        st->codec->codec_tag = format;
950
        id = ff_codec_get_id(codec_movaudio_tags, format);
951
        if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
952
            id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
953

    
954
        if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
955
            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
956
        } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
957
                   format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
958
            id = ff_codec_get_id(codec_movvideo_tags, format);
959
            if (id <= 0)
960
                id = ff_codec_get_id(ff_codec_bmp_tags, format);
961
            if (id > 0)
962
                st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
963
            else if(st->codec->codec_type == AVMEDIA_TYPE_DATA){
964
                id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
965
                if(id > 0)
966
                    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
967
            }
968
        }
969

    
970
        dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
971
                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
972
                (format >> 24) & 0xff, st->codec->codec_type);
973

    
974
        if(st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
975
            unsigned int color_depth, len;
976
            int color_greyscale;
977

    
978
            st->codec->codec_id = id;
979
            get_be16(pb); /* version */
980
            get_be16(pb); /* revision level */
981
            get_be32(pb); /* vendor */
982
            get_be32(pb); /* temporal quality */
983
            get_be32(pb); /* spatial quality */
984

    
985
            st->codec->width = get_be16(pb); /* width */
986
            st->codec->height = get_be16(pb); /* height */
987

    
988
            get_be32(pb); /* horiz resolution */
989
            get_be32(pb); /* vert resolution */
990
            get_be32(pb); /* data size, always 0 */
991
            get_be16(pb); /* frames per samples */
992

    
993
            len = get_byte(pb); /* codec name, pascal string */
994
            if (len > 31)
995
                len = 31;
996
            mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
997
            if (len < 31)
998
                url_fskip(pb, 31 - len);
999
            /* codec_tag YV12 triggers an UV swap in rawdec.c */
1000
            if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1001
                st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1002

    
1003
            st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
1004
            st->codec->color_table_id = get_be16(pb); /* colortable id */
1005
            dprintf(c->fc, "depth %d, ctab id %d\n",
1006
                   st->codec->bits_per_coded_sample, st->codec->color_table_id);
1007
            /* figure out the palette situation */
1008
            color_depth = st->codec->bits_per_coded_sample & 0x1F;
1009
            color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1010

    
1011
            /* if the depth is 2, 4, or 8 bpp, file is palettized */
1012
            if ((color_depth == 2) || (color_depth == 4) ||
1013
                (color_depth == 8)) {
1014
                /* for palette traversal */
1015
                unsigned int color_start, color_count, color_end;
1016
                unsigned char r, g, b;
1017

    
1018
                st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
1019
                if (color_greyscale) {
1020
                    int color_index, color_dec;
1021
                    /* compute the greyscale palette */
1022
                    st->codec->bits_per_coded_sample = color_depth;
1023
                    color_count = 1 << color_depth;
1024
                    color_index = 255;
1025
                    color_dec = 256 / (color_count - 1);
1026
                    for (j = 0; j < color_count; j++) {
1027
                        r = g = b = color_index;
1028
                        st->codec->palctrl->palette[j] =
1029
                            (r << 16) | (g << 8) | (b);
1030
                        color_index -= color_dec;
1031
                        if (color_index < 0)
1032
                            color_index = 0;
1033
                    }
1034
                } else if (st->codec->color_table_id) {
1035
                    const uint8_t *color_table;
1036
                    /* if flag bit 3 is set, use the default palette */
1037
                    color_count = 1 << color_depth;
1038
                    if (color_depth == 2)
1039
                        color_table = ff_qt_default_palette_4;
1040
                    else if (color_depth == 4)
1041
                        color_table = ff_qt_default_palette_16;
1042
                    else
1043
                        color_table = ff_qt_default_palette_256;
1044

    
1045
                    for (j = 0; j < color_count; j++) {
1046
                        r = color_table[j * 3 + 0];
1047
                        g = color_table[j * 3 + 1];
1048
                        b = color_table[j * 3 + 2];
1049
                        st->codec->palctrl->palette[j] =
1050
                            (r << 16) | (g << 8) | (b);
1051
                    }
1052
                } else {
1053
                    /* load the palette from the file */
1054
                    color_start = get_be32(pb);
1055
                    color_count = get_be16(pb);
1056
                    color_end = get_be16(pb);
1057
                    if ((color_start <= 255) &&
1058
                        (color_end <= 255)) {
1059
                        for (j = color_start; j <= color_end; j++) {
1060
                            /* each R, G, or B component is 16 bits;
1061
                             * only use the top 8 bits; skip alpha bytes
1062
                             * up front */
1063
                            get_byte(pb);
1064
                            get_byte(pb);
1065
                            r = get_byte(pb);
1066
                            get_byte(pb);
1067
                            g = get_byte(pb);
1068
                            get_byte(pb);
1069
                            b = get_byte(pb);
1070
                            get_byte(pb);
1071
                            st->codec->palctrl->palette[j] =
1072
                                (r << 16) | (g << 8) | (b);
1073
                        }
1074
                    }
1075
                }
1076
                st->codec->palctrl->palette_changed = 1;
1077
            }
1078
        } else if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1079
            int bits_per_sample, flags;
1080
            uint16_t version = get_be16(pb);
1081

    
1082
            st->codec->codec_id = id;
1083
            get_be16(pb); /* revision level */
1084
            get_be32(pb); /* vendor */
1085

    
1086
            st->codec->channels = get_be16(pb);             /* channel count */
1087
            dprintf(c->fc, "audio channels %d\n", st->codec->channels);
1088
            st->codec->bits_per_coded_sample = get_be16(pb);      /* sample size */
1089

    
1090
            sc->audio_cid = get_be16(pb);
1091
            get_be16(pb); /* packet size = 0 */
1092

    
1093
            st->codec->sample_rate = ((get_be32(pb) >> 16));
1094

    
1095
            //Read QT version 1 fields. In version 0 these do not exist.
1096
            dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
1097
            if(!c->isom) {
1098
                if(version==1) {
1099
                    sc->samples_per_frame = get_be32(pb);
1100
                    get_be32(pb); /* bytes per packet */
1101
                    sc->bytes_per_frame = get_be32(pb);
1102
                    get_be32(pb); /* bytes per sample */
1103
                } else if(version==2) {
1104
                    get_be32(pb); /* sizeof struct only */
1105
                    st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
1106
                    st->codec->channels = get_be32(pb);
1107
                    get_be32(pb); /* always 0x7F000000 */
1108
                    st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
1109
                    flags = get_be32(pb); /* lpcm format specific flag */
1110
                    sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
1111
                    sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
1112
                    if (format == MKTAG('l','p','c','m'))
1113
                        st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1114
                }
1115
            }
1116

    
1117
            switch (st->codec->codec_id) {
1118
            case CODEC_ID_PCM_S8:
1119
            case CODEC_ID_PCM_U8:
1120
                if (st->codec->bits_per_coded_sample == 16)
1121
                    st->codec->codec_id = CODEC_ID_PCM_S16BE;
1122
                break;
1123
            case CODEC_ID_PCM_S16LE:
1124
            case CODEC_ID_PCM_S16BE:
1125
                if (st->codec->bits_per_coded_sample == 8)
1126
                    st->codec->codec_id = CODEC_ID_PCM_S8;
1127
                else if (st->codec->bits_per_coded_sample == 24)
1128
                    st->codec->codec_id =
1129
                        st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1130
                        CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1131
                break;
1132
            /* set values for old format before stsd version 1 appeared */
1133
            case CODEC_ID_MACE3:
1134
                sc->samples_per_frame = 6;
1135
                sc->bytes_per_frame = 2*st->codec->channels;
1136
                break;
1137
            case CODEC_ID_MACE6:
1138
                sc->samples_per_frame = 6;
1139
                sc->bytes_per_frame = 1*st->codec->channels;
1140
                break;
1141
            case CODEC_ID_ADPCM_IMA_QT:
1142
                sc->samples_per_frame = 64;
1143
                sc->bytes_per_frame = 34*st->codec->channels;
1144
                break;
1145
            case CODEC_ID_GSM:
1146
                sc->samples_per_frame = 160;
1147
                sc->bytes_per_frame = 33;
1148
                break;
1149
            default:
1150
                break;
1151
            }
1152

    
1153
            bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1154
            if (bits_per_sample) {
1155
                st->codec->bits_per_coded_sample = bits_per_sample;
1156
                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1157
            }
1158
        } else if(st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1159
            // ttxt stsd contains display flags, justification, background
1160
            // color, fonts, and default styles, so fake an atom to read it
1161
            MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
1162
            if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1163
                mov_read_glbl(c, pb, fake_atom);
1164
            st->codec->codec_id= id;
1165
            st->codec->width = sc->width;
1166
            st->codec->height = sc->height;
1167
        } else {
1168
            /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1169
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
1170
        }
1171
        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1172
        a.size = size - (url_ftell(pb) - start_pos);
1173
        if (a.size > 8) {
1174
            if (mov_read_default(c, pb, a) < 0)
1175
                return -1;
1176
        } else if (a.size > 0)
1177
            url_fskip(pb, a.size);
1178
    }
1179

    
1180
    if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1181
        st->codec->sample_rate= sc->time_scale;
1182

    
1183
    /* special codec parameters handling */
1184
    switch (st->codec->codec_id) {
1185
#if CONFIG_DV_DEMUXER
1186
    case CODEC_ID_DVAUDIO:
1187
        c->dv_fctx = avformat_alloc_context();
1188
        c->dv_demux = dv_init_demux(c->dv_fctx);
1189
        if (!c->dv_demux) {
1190
            av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1191
            return -1;
1192
        }
1193
        sc->dv_audio_container = 1;
1194
        st->codec->codec_id = CODEC_ID_PCM_S16LE;
1195
        break;
1196
#endif
1197
    /* no ifdef since parameters are always those */
1198
    case CODEC_ID_QCELP:
1199
        // force sample rate for qcelp when not stored in mov
1200
        if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1201
            st->codec->sample_rate = 8000;
1202
        st->codec->frame_size= 160;
1203
        st->codec->channels= 1; /* really needed */
1204
        break;
1205
    case CODEC_ID_AMR_NB:
1206
    case CODEC_ID_AMR_WB:
1207
        st->codec->frame_size= sc->samples_per_frame;
1208
        st->codec->channels= 1; /* really needed */
1209
        /* force sample rate for amr, stsd in 3gp does not store sample rate */
1210
        if (st->codec->codec_id == CODEC_ID_AMR_NB)
1211
            st->codec->sample_rate = 8000;
1212
        else if (st->codec->codec_id == CODEC_ID_AMR_WB)
1213
            st->codec->sample_rate = 16000;
1214
        break;
1215
    case CODEC_ID_MP2:
1216
    case CODEC_ID_MP3:
1217
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1218
        st->need_parsing = AVSTREAM_PARSE_FULL;
1219
        break;
1220
    case CODEC_ID_GSM:
1221
    case CODEC_ID_ADPCM_MS:
1222
    case CODEC_ID_ADPCM_IMA_WAV:
1223
        st->codec->block_align = sc->bytes_per_frame;
1224
        break;
1225
    case CODEC_ID_ALAC:
1226
        if (st->codec->extradata_size == 36) {
1227
            st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1228
            st->codec->channels   = AV_RB8 (st->codec->extradata+21);
1229
        }
1230
        break;
1231
    default:
1232
        break;
1233
    }
1234

    
1235
    return 0;
1236
}
1237

    
1238
static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1239
{
1240
    int entries;
1241

    
1242
    get_byte(pb); /* version */
1243
    get_be24(pb); /* flags */
1244
    entries = get_be32(pb);
1245

    
1246
    return ff_mov_read_stsd_entries(c, pb, entries);
1247
}
1248

    
1249
static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1250
{
1251
    AVStream *st;
1252
    MOVStreamContext *sc;
1253
    unsigned int i, entries;
1254

    
1255
    if (c->fc->nb_streams < 1)
1256
        return 0;
1257
    st = c->fc->streams[c->fc->nb_streams-1];
1258
    sc = st->priv_data;
1259

    
1260
    get_byte(pb); /* version */
1261
    get_be24(pb); /* flags */
1262

    
1263
    entries = get_be32(pb);
1264

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

    
1267
    if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
1268
        return -1;
1269
    sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1270
    if (!sc->stsc_data)
1271
        return AVERROR(ENOMEM);
1272
    sc->stsc_count = entries;
1273

    
1274
    for(i=0; i<entries; i++) {
1275
        sc->stsc_data[i].first = get_be32(pb);
1276
        sc->stsc_data[i].count = get_be32(pb);
1277
        sc->stsc_data[i].id = get_be32(pb);
1278
    }
1279
    return 0;
1280
}
1281

    
1282
static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1283
{
1284
    AVStream *st;
1285
    MOVStreamContext *sc;
1286
    unsigned i, entries;
1287

    
1288
    if (c->fc->nb_streams < 1)
1289
        return 0;
1290
    st = c->fc->streams[c->fc->nb_streams-1];
1291
    sc = st->priv_data;
1292

    
1293
    get_be32(pb); // version + flags
1294

    
1295
    entries = get_be32(pb);
1296
    if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1297
        return -1;
1298
    sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1299
    if (!sc->stps_data)
1300
        return AVERROR(ENOMEM);
1301
    sc->stps_count = entries;
1302

    
1303
    for (i = 0; i < entries; i++) {
1304
        sc->stps_data[i] = get_be32(pb);
1305
        //dprintf(c->fc, "stps %d\n", sc->stps_data[i]);
1306
    }
1307

    
1308
    return 0;
1309
}
1310

    
1311
static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1312
{
1313
    AVStream *st;
1314
    MOVStreamContext *sc;
1315
    unsigned int i, entries;
1316

    
1317
    if (c->fc->nb_streams < 1)
1318
        return 0;
1319
    st = c->fc->streams[c->fc->nb_streams-1];
1320
    sc = st->priv_data;
1321

    
1322
    get_byte(pb); /* version */
1323
    get_be24(pb); /* flags */
1324

    
1325
    entries = get_be32(pb);
1326

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

    
1329
    if(entries >= UINT_MAX / sizeof(int))
1330
        return -1;
1331
    sc->keyframes = av_malloc(entries * sizeof(int));
1332
    if (!sc->keyframes)
1333
        return AVERROR(ENOMEM);
1334
    sc->keyframe_count = entries;
1335

    
1336
    for(i=0; i<entries; i++) {
1337
        sc->keyframes[i] = get_be32(pb);
1338
        //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1339
    }
1340
    return 0;
1341
}
1342

    
1343
static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1344
{
1345
    AVStream *st;
1346
    MOVStreamContext *sc;
1347
    unsigned int i, entries, sample_size, field_size, num_bytes;
1348
    GetBitContext gb;
1349
    unsigned char* buf;
1350

    
1351
    if (c->fc->nb_streams < 1)
1352
        return 0;
1353
    st = c->fc->streams[c->fc->nb_streams-1];
1354
    sc = st->priv_data;
1355

    
1356
    get_byte(pb); /* version */
1357
    get_be24(pb); /* flags */
1358

    
1359
    if (atom.type == MKTAG('s','t','s','z')) {
1360
        sample_size = get_be32(pb);
1361
        if (!sc->sample_size) /* do not overwrite value computed in stsd */
1362
            sc->sample_size = sample_size;
1363
        field_size = 32;
1364
    } else {
1365
        sample_size = 0;
1366
        get_be24(pb); /* reserved */
1367
        field_size = get_byte(pb);
1368
    }
1369
    entries = get_be32(pb);
1370

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

    
1373
    sc->sample_count = entries;
1374
    if (sample_size)
1375
        return 0;
1376

    
1377
    if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1378
        av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1379
        return -1;
1380
    }
1381

    
1382
    if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1383
        return -1;
1384
    sc->sample_sizes = av_malloc(entries * sizeof(int));
1385
    if (!sc->sample_sizes)
1386
        return AVERROR(ENOMEM);
1387

    
1388
    num_bytes = (entries*field_size+4)>>3;
1389

    
1390
    buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1391
    if (!buf) {
1392
        av_freep(&sc->sample_sizes);
1393
        return AVERROR(ENOMEM);
1394
    }
1395

    
1396
    if (get_buffer(pb, buf, num_bytes) < num_bytes) {
1397
        av_freep(&sc->sample_sizes);
1398
        av_free(buf);
1399
        return -1;
1400
    }
1401

    
1402
    init_get_bits(&gb, buf, 8*num_bytes);
1403

    
1404
    for(i=0; i<entries; i++)
1405
        sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1406

    
1407
    av_free(buf);
1408
    return 0;
1409
}
1410

    
1411
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1412
{
1413
    AVStream *st;
1414
    MOVStreamContext *sc;
1415
    unsigned int i, entries;
1416
    int64_t duration=0;
1417
    int64_t total_sample_count=0;
1418

    
1419
    if (c->fc->nb_streams < 1)
1420
        return 0;
1421
    st = c->fc->streams[c->fc->nb_streams-1];
1422
    sc = st->priv_data;
1423

    
1424
    get_byte(pb); /* version */
1425
    get_be24(pb); /* flags */
1426
    entries = get_be32(pb);
1427

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

    
1430
    if(entries >= UINT_MAX / sizeof(*sc->stts_data))
1431
        return -1;
1432
    sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1433
    if (!sc->stts_data)
1434
        return AVERROR(ENOMEM);
1435
    sc->stts_count = entries;
1436

    
1437
    for(i=0; i<entries; i++) {
1438
        int sample_duration;
1439
        int sample_count;
1440

    
1441
        sample_count=get_be32(pb);
1442
        sample_duration = get_be32(pb);
1443
        sc->stts_data[i].count= sample_count;
1444
        sc->stts_data[i].duration= sample_duration;
1445

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

    
1448
        duration+=(int64_t)sample_duration*sample_count;
1449
        total_sample_count+=sample_count;
1450
    }
1451

    
1452
    st->nb_frames= total_sample_count;
1453
    if(duration)
1454
        st->duration= duration;
1455
    return 0;
1456
}
1457

    
1458
static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1459
{
1460
    AVStream *st;
1461
    MOVStreamContext *sc;
1462
    unsigned int i, entries;
1463

    
1464
    if (c->fc->nb_streams < 1)
1465
        return 0;
1466
    st = c->fc->streams[c->fc->nb_streams-1];
1467
    sc = st->priv_data;
1468

    
1469
    get_byte(pb); /* version */
1470
    get_be24(pb); /* flags */
1471
    entries = get_be32(pb);
1472

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

    
1475
    if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
1476
        return -1;
1477
    sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1478
    if (!sc->ctts_data)
1479
        return AVERROR(ENOMEM);
1480
    sc->ctts_count = entries;
1481

    
1482
    for(i=0; i<entries; i++) {
1483
        int count    =get_be32(pb);
1484
        int duration =get_be32(pb);
1485

    
1486
        sc->ctts_data[i].count   = count;
1487
        sc->ctts_data[i].duration= duration;
1488
        if (duration < 0)
1489
            sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1490
    }
1491

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

    
1494
    return 0;
1495
}
1496

    
1497
static void mov_build_index(MOVContext *mov, AVStream *st)
1498
{
1499
    MOVStreamContext *sc = st->priv_data;
1500
    int64_t current_offset;
1501
    int64_t current_dts = 0;
1502
    unsigned int stts_index = 0;
1503
    unsigned int stsc_index = 0;
1504
    unsigned int stss_index = 0;
1505
    unsigned int stps_index = 0;
1506
    unsigned int i, j;
1507
    uint64_t stream_size = 0;
1508

    
1509
    /* adjust first dts according to edit list */
1510
    if (sc->time_offset) {
1511
        int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
1512
        current_dts = -rescaled;
1513
        if (sc->ctts_data && sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1514
            /* more than 16 frames delay, dts are likely wrong
1515
               this happens with files created by iMovie */
1516
            sc->wrong_dts = 1;
1517
            st->codec->has_b_frames = 1;
1518
        }
1519
    }
1520

    
1521
    /* only use old uncompressed audio chunk demuxing when stts specifies it */
1522
    if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1523
          sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1524
        unsigned int current_sample = 0;
1525
        unsigned int stts_sample = 0;
1526
        unsigned int sample_size;
1527
        unsigned int distance = 0;
1528
        int key_off = sc->keyframes && sc->keyframes[0] == 1;
1529

    
1530
        current_dts -= sc->dts_shift;
1531

    
1532
        if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
1533
            return;
1534
        st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
1535
        if (!st->index_entries)
1536
            return;
1537
        st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
1538

    
1539
        for (i = 0; i < sc->chunk_count; i++) {
1540
            current_offset = sc->chunk_offsets[i];
1541
            if (stsc_index + 1 < sc->stsc_count &&
1542
                i + 1 == sc->stsc_data[stsc_index + 1].first)
1543
                stsc_index++;
1544
            for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1545
                int keyframe = 0;
1546
                if (current_sample >= sc->sample_count) {
1547
                    av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1548
                    return;
1549
                }
1550

    
1551
                if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1552
                    keyframe = 1;
1553
                    if (stss_index + 1 < sc->keyframe_count)
1554
                        stss_index++;
1555
                } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1556
                    keyframe = 1;
1557
                    if (stps_index + 1 < sc->stps_count)
1558
                        stps_index++;
1559
                }
1560
                if (keyframe)
1561
                    distance = 0;
1562
                sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1563
                if(sc->pseudo_stream_id == -1 ||
1564
                   sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1565
                    AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1566
                    e->pos = current_offset;
1567
                    e->timestamp = current_dts;
1568
                    e->size = sample_size;
1569
                    e->min_distance = distance;
1570
                    e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1571
                    dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1572
                            "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1573
                            current_offset, current_dts, sample_size, distance, keyframe);
1574
                }
1575

    
1576
                current_offset += sample_size;
1577
                stream_size += sample_size;
1578
                current_dts += sc->stts_data[stts_index].duration;
1579
                distance++;
1580
                stts_sample++;
1581
                current_sample++;
1582
                if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1583
                    stts_sample = 0;
1584
                    stts_index++;
1585
                }
1586
            }
1587
        }
1588
        if (st->duration > 0)
1589
            st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1590
    } else {
1591
        unsigned chunk_samples, total = 0;
1592

    
1593
        // compute total chunk count
1594
        for (i = 0; i < sc->stsc_count; i++) {
1595
            unsigned count, chunk_count;
1596

    
1597
            chunk_samples = sc->stsc_data[i].count;
1598
            if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1599
                av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1600
                return;
1601
            }
1602

    
1603
            if (sc->samples_per_frame >= 160) { // gsm
1604
                count = chunk_samples / sc->samples_per_frame;
1605
            } else if (sc->samples_per_frame > 1) {
1606
                unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1607
                count = (chunk_samples+samples-1) / samples;
1608
            } else {
1609
                count = (chunk_samples+1023) / 1024;
1610
            }
1611

    
1612
            if (i < sc->stsc_count - 1)
1613
                chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1614
            else
1615
                chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1616
            total += chunk_count * count;
1617
        }
1618

    
1619
        dprintf(mov->fc, "chunk count %d\n", total);
1620
        if (total >= UINT_MAX / sizeof(*st->index_entries))
1621
            return;
1622
        st->index_entries = av_malloc(total*sizeof(*st->index_entries));
1623
        if (!st->index_entries)
1624
            return;
1625
        st->index_entries_allocated_size = total*sizeof(*st->index_entries);
1626

    
1627
        // populate index
1628
        for (i = 0; i < sc->chunk_count; i++) {
1629
            current_offset = sc->chunk_offsets[i];
1630
            if (stsc_index + 1 < sc->stsc_count &&
1631
                i + 1 == sc->stsc_data[stsc_index + 1].first)
1632
                stsc_index++;
1633
            chunk_samples = sc->stsc_data[stsc_index].count;
1634

    
1635
            while (chunk_samples > 0) {
1636
                AVIndexEntry *e;
1637
                unsigned size, samples;
1638

    
1639
                if (sc->samples_per_frame >= 160) { // gsm
1640
                    samples = sc->samples_per_frame;
1641
                    size = sc->bytes_per_frame;
1642
                } else {
1643
                    if (sc->samples_per_frame > 1) {
1644
                        samples = FFMIN((1024 / sc->samples_per_frame)*
1645
                                        sc->samples_per_frame, chunk_samples);
1646
                        size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1647
                    } else {
1648
                        samples = FFMIN(1024, chunk_samples);
1649
                        size = samples * sc->sample_size;
1650
                    }
1651
                }
1652

    
1653
                if (st->nb_index_entries >= total) {
1654
                    av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1655
                    return;
1656
                }
1657
                e = &st->index_entries[st->nb_index_entries++];
1658
                e->pos = current_offset;
1659
                e->timestamp = current_dts;
1660
                e->size = size;
1661
                e->min_distance = 0;
1662
                e->flags = AVINDEX_KEYFRAME;
1663
                dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1664
                        "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1665
                        size, samples);
1666

    
1667
                current_offset += size;
1668
                current_dts += samples;
1669
                chunk_samples -= samples;
1670
            }
1671
        }
1672
    }
1673
}
1674

    
1675
static int mov_open_dref(ByteIOContext **pb, char *src, MOVDref *ref)
1676
{
1677
    /* try relative path, we do not try the absolute because it can leak information about our
1678
       system to an attacker */
1679
    if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1680
        char filename[1024];
1681
        char *src_path;
1682
        int i, l;
1683

    
1684
        /* find a source dir */
1685
        src_path = strrchr(src, '/');
1686
        if (src_path)
1687
            src_path++;
1688
        else
1689
            src_path = src;
1690

    
1691
        /* find a next level down to target */
1692
        for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1693
            if (ref->path[l] == '/') {
1694
                if (i == ref->nlvl_to - 1)
1695
                    break;
1696
                else
1697
                    i++;
1698
            }
1699

    
1700
        /* compose filename if next level down to target was found */
1701
        if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
1702
            memcpy(filename, src, src_path - src);
1703
            filename[src_path - src] = 0;
1704

    
1705
            for (i = 1; i < ref->nlvl_from; i++)
1706
                av_strlcat(filename, "../", 1024);
1707

    
1708
            av_strlcat(filename, ref->path + l + 1, 1024);
1709

    
1710
            if (!url_fopen(pb, filename, URL_RDONLY))
1711
                return 0;
1712
        }
1713
    }
1714

    
1715
    return AVERROR(ENOENT);
1716
};
1717

    
1718
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1719
{
1720
    AVStream *st;
1721
    MOVStreamContext *sc;
1722
    int ret;
1723

    
1724
    st = av_new_stream(c->fc, c->fc->nb_streams);
1725
    if (!st) return AVERROR(ENOMEM);
1726
    sc = av_mallocz(sizeof(MOVStreamContext));
1727
    if (!sc) return AVERROR(ENOMEM);
1728

    
1729
    st->priv_data = sc;
1730
    st->codec->codec_type = AVMEDIA_TYPE_DATA;
1731
    sc->ffindex = st->index;
1732

    
1733
    if ((ret = mov_read_default(c, pb, atom)) < 0)
1734
        return ret;
1735

    
1736
    /* sanity checks */
1737
    if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1738
                            (!sc->sample_size && !sc->sample_count))) {
1739
        av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1740
               st->index);
1741
        return 0;
1742
    }
1743

    
1744
    if (!sc->time_scale) {
1745
        av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
1746
        sc->time_scale = c->time_scale;
1747
        if (!sc->time_scale)
1748
            sc->time_scale = 1;
1749
    }
1750

    
1751
    av_set_pts_info(st, 64, 1, sc->time_scale);
1752

    
1753
    if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1754
        !st->codec->frame_size && sc->stts_count == 1) {
1755
        st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
1756
                                           st->codec->sample_rate, sc->time_scale);
1757
        dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
1758
    }
1759

    
1760
    mov_build_index(c, st);
1761

    
1762
    if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1763
        MOVDref *dref = &sc->drefs[sc->dref_id - 1];
1764
        if (mov_open_dref(&sc->pb, c->fc->filename, dref) < 0)
1765
            av_log(c->fc, AV_LOG_ERROR,
1766
                   "stream %d, error opening alias: path='%s', dir='%s', "
1767
                   "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
1768
                   st->index, dref->path, dref->dir, dref->filename,
1769
                   dref->volume, dref->nlvl_from, dref->nlvl_to);
1770
    } else
1771
        sc->pb = c->fc->pb;
1772

    
1773
    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1774
        if (!st->sample_aspect_ratio.num &&
1775
            (st->codec->width != sc->width || st->codec->height != sc->height)) {
1776
            st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
1777
                                             ((double)st->codec->width * sc->height), INT_MAX);
1778
        }
1779

    
1780
        av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1781
                  sc->time_scale*st->nb_frames, st->duration, INT_MAX);
1782
    }
1783

    
1784
    switch (st->codec->codec_id) {
1785
#if CONFIG_H261_DECODER
1786
    case CODEC_ID_H261:
1787
#endif
1788
#if CONFIG_H263_DECODER
1789
    case CODEC_ID_H263:
1790
#endif
1791
#if CONFIG_H264_DECODER
1792
    case CODEC_ID_H264:
1793
#endif
1794
#if CONFIG_MPEG4_DECODER
1795
    case CODEC_ID_MPEG4:
1796
#endif
1797
        st->codec->width = 0; /* let decoder init width/height */
1798
        st->codec->height= 0;
1799
        break;
1800
    }
1801

    
1802
    /* Do not need those anymore. */
1803
    av_freep(&sc->chunk_offsets);
1804
    av_freep(&sc->stsc_data);
1805
    av_freep(&sc->sample_sizes);
1806
    av_freep(&sc->keyframes);
1807
    av_freep(&sc->stts_data);
1808
    av_freep(&sc->stps_data);
1809

    
1810
    return 0;
1811
}
1812

    
1813
static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1814
{
1815
    int ret;
1816
    c->itunes_metadata = 1;
1817
    ret = mov_read_default(c, pb, atom);
1818
    c->itunes_metadata = 0;
1819
    return ret;
1820
}
1821

    
1822
static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1823
{
1824
    while (atom.size > 8) {
1825
        uint32_t tag = get_le32(pb);
1826
        atom.size -= 4;
1827
        if (tag == MKTAG('h','d','l','r')) {
1828
            url_fseek(pb, -8, SEEK_CUR);
1829
            atom.size += 8;
1830
            return mov_read_default(c, pb, atom);
1831
        }
1832
    }
1833
    return 0;
1834
}
1835

    
1836
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1837
{
1838
    int i;
1839
    int width;
1840
    int height;
1841
    int64_t disp_transform[2];
1842
    int display_matrix[3][2];
1843
    AVStream *st;
1844
    MOVStreamContext *sc;
1845
    int version;
1846

    
1847
    if (c->fc->nb_streams < 1)
1848
        return 0;
1849
    st = c->fc->streams[c->fc->nb_streams-1];
1850
    sc = st->priv_data;
1851

    
1852
    version = get_byte(pb);
1853
    get_be24(pb); /* flags */
1854
    /*
1855
    MOV_TRACK_ENABLED 0x0001
1856
    MOV_TRACK_IN_MOVIE 0x0002
1857
    MOV_TRACK_IN_PREVIEW 0x0004
1858
    MOV_TRACK_IN_POSTER 0x0008
1859
    */
1860

    
1861
    if (version == 1) {
1862
        get_be64(pb);
1863
        get_be64(pb);
1864
    } else {
1865
        get_be32(pb); /* creation time */
1866
        get_be32(pb); /* modification time */
1867
    }
1868
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1869
    get_be32(pb); /* reserved */
1870

    
1871
    /* highlevel (considering edits) duration in movie timebase */
1872
    (version == 1) ? get_be64(pb) : get_be32(pb);
1873
    get_be32(pb); /* reserved */
1874
    get_be32(pb); /* reserved */
1875

    
1876
    get_be16(pb); /* layer */
1877
    get_be16(pb); /* alternate group */
1878
    get_be16(pb); /* volume */
1879
    get_be16(pb); /* reserved */
1880

    
1881
    //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
1882
    // they're kept in fixed point format through all calculations
1883
    // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
1884
    for (i = 0; i < 3; i++) {
1885
        display_matrix[i][0] = get_be32(pb);   // 16.16 fixed point
1886
        display_matrix[i][1] = get_be32(pb);   // 16.16 fixed point
1887
        get_be32(pb);           // 2.30 fixed point (not used)
1888
    }
1889

    
1890
    width = get_be32(pb);       // 16.16 fixed point track width
1891
    height = get_be32(pb);      // 16.16 fixed point track height
1892
    sc->width = width >> 16;
1893
    sc->height = height >> 16;
1894

    
1895
    // transform the display width/height according to the matrix
1896
    // skip this if the display matrix is the default identity matrix
1897
    // or if it is rotating the picture, ex iPhone 3GS
1898
    // to keep the same scale, use [width height 1<<16]
1899
    if (width && height &&
1900
        ((display_matrix[0][0] != 65536  ||
1901
          display_matrix[1][1] != 65536) &&
1902
         !display_matrix[0][1] &&
1903
         !display_matrix[1][0] &&
1904
         !display_matrix[2][0] && !display_matrix[2][1])) {
1905
        for (i = 0; i < 2; i++)
1906
            disp_transform[i] =
1907
                (int64_t)  width  * display_matrix[0][i] +
1908
                (int64_t)  height * display_matrix[1][i] +
1909
                ((int64_t) display_matrix[2][i] << 16);
1910

    
1911
        //sample aspect ratio is new width/height divided by old width/height
1912
        st->sample_aspect_ratio = av_d2q(
1913
            ((double) disp_transform[0] * height) /
1914
            ((double) disp_transform[1] * width), INT_MAX);
1915
    }
1916
    return 0;
1917
}
1918

    
1919
static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1920
{
1921
    MOVFragment *frag = &c->fragment;
1922
    MOVTrackExt *trex = NULL;
1923
    int flags, track_id, i;
1924

    
1925
    get_byte(pb); /* version */
1926
    flags = get_be24(pb);
1927

    
1928
    track_id = get_be32(pb);
1929
    if (!track_id)
1930
        return -1;
1931
    frag->track_id = track_id;
1932
    for (i = 0; i < c->trex_count; i++)
1933
        if (c->trex_data[i].track_id == frag->track_id) {
1934
            trex = &c->trex_data[i];
1935
            break;
1936
        }
1937
    if (!trex) {
1938
        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
1939
        return -1;
1940
    }
1941

    
1942
    if (flags & 0x01) frag->base_data_offset = get_be64(pb);
1943
    else              frag->base_data_offset = frag->moof_offset;
1944
    if (flags & 0x02) frag->stsd_id          = get_be32(pb);
1945
    else              frag->stsd_id          = trex->stsd_id;
1946

    
1947
    frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
1948
    frag->size     = flags & 0x10 ? get_be32(pb) : trex->size;
1949
    frag->flags    = flags & 0x20 ? get_be32(pb) : trex->flags;
1950
    dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
1951
    return 0;
1952
}
1953

    
1954
static int mov_read_chap(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1955
{
1956
    c->chapter_track = get_be32(pb);
1957
    return 0;
1958
}
1959

    
1960
static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1961
{
1962
    MOVTrackExt *trex;
1963

    
1964
    if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
1965
        return -1;
1966
    trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
1967
    if (!trex)
1968
        return AVERROR(ENOMEM);
1969
    c->trex_data = trex;
1970
    trex = &c->trex_data[c->trex_count++];
1971
    get_byte(pb); /* version */
1972
    get_be24(pb); /* flags */
1973
    trex->track_id = get_be32(pb);
1974
    trex->stsd_id  = get_be32(pb);
1975
    trex->duration = get_be32(pb);
1976
    trex->size     = get_be32(pb);
1977
    trex->flags    = get_be32(pb);
1978
    return 0;
1979
}
1980

    
1981
static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1982
{
1983
    MOVFragment *frag = &c->fragment;
1984
    AVStream *st = NULL;
1985
    MOVStreamContext *sc;
1986
    uint64_t offset;
1987
    int64_t dts;
1988
    int data_offset = 0;
1989
    unsigned entries, first_sample_flags = frag->flags;
1990
    int flags, distance, i;
1991

    
1992
    for (i = 0; i < c->fc->nb_streams; i++) {
1993
        if (c->fc->streams[i]->id == frag->track_id) {
1994
            st = c->fc->streams[i];
1995
            break;
1996
        }
1997
    }
1998
    if (!st) {
1999
        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2000
        return -1;
2001
    }
2002
    sc = st->priv_data;
2003
    if (sc->pseudo_stream_id+1 != frag->stsd_id)
2004
        return 0;
2005
    get_byte(pb); /* version */
2006
    flags = get_be24(pb);
2007
    entries = get_be32(pb);
2008
    dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
2009
    if (flags & 0x001) data_offset        = get_be32(pb);
2010
    if (flags & 0x004) first_sample_flags = get_be32(pb);
2011
    if (flags & 0x800) {
2012
        MOVStts *ctts_data;
2013
        if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2014
            return -1;
2015
        ctts_data = av_realloc(sc->ctts_data,
2016
                               (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2017
        if (!ctts_data)
2018
            return AVERROR(ENOMEM);
2019
        sc->ctts_data = ctts_data;
2020
    }
2021
    dts = st->duration;
2022
    offset = frag->base_data_offset + data_offset;
2023
    distance = 0;
2024
    dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2025
    for (i = 0; i < entries; i++) {
2026
        unsigned sample_size = frag->size;
2027
        int sample_flags = i ? frag->flags : first_sample_flags;
2028
        unsigned sample_duration = frag->duration;
2029
        int keyframe;
2030

    
2031
        if (flags & 0x100) sample_duration = get_be32(pb);
2032
        if (flags & 0x200) sample_size     = get_be32(pb);
2033
        if (flags & 0x400) sample_flags    = get_be32(pb);
2034
        if (flags & 0x800) {
2035
            sc->ctts_data[sc->ctts_count].count = 1;
2036
            sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
2037
            sc->ctts_count++;
2038
        }
2039
        if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
2040
             (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
2041
            distance = 0;
2042
        av_add_index_entry(st, offset, dts, sample_size, distance,
2043
                           keyframe ? AVINDEX_KEYFRAME : 0);
2044
        dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2045
                "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2046
                offset, dts, sample_size, distance, keyframe);
2047
        distance++;
2048
        dts += sample_duration;
2049
        offset += sample_size;
2050
    }
2051
    frag->moof_offset = offset;
2052
    st->duration = dts;
2053
    return 0;
2054
}
2055

    
2056
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2057
/* like the files created with Adobe Premiere 5.0, for samples see */
2058
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2059
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2060
{
2061
    int err;
2062

    
2063
    if (atom.size < 8)
2064
        return 0; /* continue */
2065
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2066
        url_fskip(pb, atom.size - 4);
2067
        return 0;
2068
    }
2069
    atom.type = get_le32(pb);
2070
    atom.size -= 8;
2071
    if (atom.type != MKTAG('m','d','a','t')) {
2072
        url_fskip(pb, atom.size);
2073
        return 0;
2074
    }
2075
    err = mov_read_mdat(c, pb, atom);
2076
    return err;
2077
}
2078

    
2079
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2080
{
2081
#if CONFIG_ZLIB
2082
    ByteIOContext ctx;
2083
    uint8_t *cmov_data;
2084
    uint8_t *moov_data; /* uncompressed data */
2085
    long cmov_len, moov_len;
2086
    int ret = -1;
2087

    
2088
    get_be32(pb); /* dcom atom */
2089
    if (get_le32(pb) != MKTAG('d','c','o','m'))
2090
        return -1;
2091
    if (get_le32(pb) != MKTAG('z','l','i','b')) {
2092
        av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2093
        return -1;
2094
    }
2095
    get_be32(pb); /* cmvd atom */
2096
    if (get_le32(pb) != MKTAG('c','m','v','d'))
2097
        return -1;
2098
    moov_len = get_be32(pb); /* uncompressed size */
2099
    cmov_len = atom.size - 6 * 4;
2100

    
2101
    cmov_data = av_malloc(cmov_len);
2102
    if (!cmov_data)
2103
        return AVERROR(ENOMEM);
2104
    moov_data = av_malloc(moov_len);
2105
    if (!moov_data) {
2106
        av_free(cmov_data);
2107
        return AVERROR(ENOMEM);
2108
    }
2109
    get_buffer(pb, cmov_data, cmov_len);
2110
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2111
        goto free_and_return;
2112
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2113
        goto free_and_return;
2114
    atom.type = MKTAG('m','o','o','v');
2115
    atom.size = moov_len;
2116
#ifdef DEBUG
2117
//    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
2118
#endif
2119
    ret = mov_read_default(c, &ctx, atom);
2120
free_and_return:
2121
    av_free(moov_data);
2122
    av_free(cmov_data);
2123
    return ret;
2124
#else
2125
    av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2126
    return -1;
2127
#endif
2128
}
2129

    
2130
/* edit list atom */
2131
static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2132
{
2133
    MOVStreamContext *sc;
2134
    int i, edit_count;
2135

    
2136
    if (c->fc->nb_streams < 1)
2137
        return 0;
2138
    sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2139

    
2140
    get_byte(pb); /* version */
2141
    get_be24(pb); /* flags */
2142
    edit_count = get_be32(pb); /* entries */
2143

    
2144
    if((uint64_t)edit_count*12+8 > atom.size)
2145
        return -1;
2146

    
2147
    for(i=0; i<edit_count; i++){
2148
        int time;
2149
        int duration = get_be32(pb); /* Track duration */
2150
        time = get_be32(pb); /* Media time */
2151
        get_be32(pb); /* Media rate */
2152
        if (i == 0 && time >= -1) {
2153
            sc->time_offset = time != -1 ? time : -duration;
2154
        }
2155
    }
2156

    
2157
    if(edit_count > 1)
2158
        av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2159
               "a/v desync might occur, patch welcome\n");
2160

    
2161
    dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2162
    return 0;
2163
}
2164

    
2165
static const MOVParseTableEntry mov_default_parse_table[] = {
2166
{ MKTAG('a','v','s','s'), mov_read_extradata },
2167
{ MKTAG('c','h','p','l'), mov_read_chpl },
2168
{ MKTAG('c','o','6','4'), mov_read_stco },
2169
{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2170
{ MKTAG('d','i','n','f'), mov_read_default },
2171
{ MKTAG('d','r','e','f'), mov_read_dref },
2172
{ MKTAG('e','d','t','s'), mov_read_default },
2173
{ MKTAG('e','l','s','t'), mov_read_elst },
2174
{ MKTAG('e','n','d','a'), mov_read_enda },
2175
{ MKTAG('f','i','e','l'), mov_read_extradata },
2176
{ MKTAG('f','t','y','p'), mov_read_ftyp },
2177
{ MKTAG('g','l','b','l'), mov_read_glbl },
2178
{ MKTAG('h','d','l','r'), mov_read_hdlr },
2179
{ MKTAG('i','l','s','t'), mov_read_ilst },
2180
{ MKTAG('j','p','2','h'), mov_read_extradata },
2181
{ MKTAG('m','d','a','t'), mov_read_mdat },
2182
{ MKTAG('m','d','h','d'), mov_read_mdhd },
2183
{ MKTAG('m','d','i','a'), mov_read_default },
2184
{ MKTAG('m','e','t','a'), mov_read_meta },
2185
{ MKTAG('m','i','n','f'), mov_read_default },
2186
{ MKTAG('m','o','o','f'), mov_read_moof },
2187
{ MKTAG('m','o','o','v'), mov_read_moov },
2188
{ MKTAG('m','v','e','x'), mov_read_default },
2189
{ MKTAG('m','v','h','d'), mov_read_mvhd },
2190
{ MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2191
{ MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2192
{ MKTAG('a','v','c','C'), mov_read_glbl },
2193
{ MKTAG('p','a','s','p'), mov_read_pasp },
2194
{ MKTAG('s','t','b','l'), mov_read_default },
2195
{ MKTAG('s','t','c','o'), mov_read_stco },
2196
{ MKTAG('s','t','p','s'), mov_read_stps },
2197
{ MKTAG('s','t','r','f'), mov_read_strf },
2198
{ MKTAG('s','t','s','c'), mov_read_stsc },
2199
{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2200
{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2201
{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2202
{ MKTAG('s','t','t','s'), mov_read_stts },
2203
{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2204
{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2205
{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2206
{ MKTAG('t','r','a','k'), mov_read_trak },
2207
{ MKTAG('t','r','a','f'), mov_read_default },
2208
{ MKTAG('t','r','e','f'), mov_read_default },
2209
{ MKTAG('c','h','a','p'), mov_read_chap },
2210
{ MKTAG('t','r','e','x'), mov_read_trex },
2211
{ MKTAG('t','r','u','n'), mov_read_trun },
2212
{ MKTAG('u','d','t','a'), mov_read_default },
2213
{ MKTAG('w','a','v','e'), mov_read_wave },
2214
{ MKTAG('e','s','d','s'), mov_read_esds },
2215
{ MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2216
{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2217
{ MKTAG('c','m','o','v'), mov_read_cmov },
2218
{ 0, NULL }
2219
};
2220

    
2221
static int mov_probe(AVProbeData *p)
2222
{
2223
    unsigned int offset;
2224
    uint32_t tag;
2225
    int score = 0;
2226

    
2227
    /* check file header */
2228
    offset = 0;
2229
    for(;;) {
2230
        /* ignore invalid offset */
2231
        if ((offset + 8) > (unsigned int)p->buf_size)
2232
            return score;
2233
        tag = AV_RL32(p->buf + offset + 4);
2234
        switch(tag) {
2235
        /* check for obvious tags */
2236
        case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2237
        case MKTAG('m','o','o','v'):
2238
        case MKTAG('m','d','a','t'):
2239
        case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2240
        case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2241
        case MKTAG('f','t','y','p'):
2242
            return AVPROBE_SCORE_MAX;
2243
        /* those are more common words, so rate then a bit less */
2244
        case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2245
        case MKTAG('w','i','d','e'):
2246
        case MKTAG('f','r','e','e'):
2247
        case MKTAG('j','u','n','k'):
2248
        case MKTAG('p','i','c','t'):
2249
            return AVPROBE_SCORE_MAX - 5;
2250
        case MKTAG(0x82,0x82,0x7f,0x7d):
2251
        case MKTAG('s','k','i','p'):
2252
        case MKTAG('u','u','i','d'):
2253
        case MKTAG('p','r','f','l'):
2254
            offset = AV_RB32(p->buf+offset) + offset;
2255
            /* if we only find those cause probedata is too small at least rate them */
2256
            score = AVPROBE_SCORE_MAX - 50;
2257
            break;
2258
        default:
2259
            /* unrecognized tag */
2260
            return score;
2261
        }
2262
    }
2263
    return score;
2264
}
2265

    
2266
// must be done after parsing all trak because there's no order requirement
2267
static void mov_read_chapters(AVFormatContext *s)
2268
{
2269
    MOVContext *mov = s->priv_data;
2270
    AVStream *st = NULL;
2271
    MOVStreamContext *sc;
2272
    int64_t cur_pos;
2273
    uint8_t *title = NULL;
2274
    int i, len, i8, i16;
2275

    
2276
    for (i = 0; i < s->nb_streams; i++)
2277
        if (s->streams[i]->id == mov->chapter_track) {
2278
            st = s->streams[i];
2279
            break;
2280
        }
2281
    if (!st) {
2282
        av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2283
        return;
2284
    }
2285

    
2286
    st->discard = AVDISCARD_ALL;
2287
    sc = st->priv_data;
2288
    cur_pos = url_ftell(sc->pb);
2289

    
2290
    for (i = 0; i < st->nb_index_entries; i++) {
2291
        AVIndexEntry *sample = &st->index_entries[i];
2292
        int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2293

    
2294
        if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2295
            av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2296
            goto finish;
2297
        }
2298

    
2299
        title = av_malloc(sample->size+2);
2300
        get_buffer(sc->pb, title, sample->size);
2301

    
2302
        // the first two bytes are the length of the title
2303
        len = AV_RB16(title);
2304
        if (len > sample->size-2)
2305
            continue;
2306

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

    
2313
            i8 = i16 = 0;
2314
            while (i16 < len) {
2315
                uint32_t ch;
2316
                uint8_t tmp;
2317
                GET_UTF16(ch, i16 < len ? AV_RB16(title + (i16+=2)) : 0, break;)
2318
                PUT_UTF8(ch, tmp, if (i8 < 2*len) utf8[2+i8++] = tmp;)
2319
            }
2320
            utf8[2+i8] = 0;
2321
            av_freep(&title);
2322
            title = utf8;
2323
        }
2324

    
2325
        ff_new_chapter(s, i, st->time_base, sample->timestamp, end, title+2);
2326
        av_freep(&title);
2327
    }
2328
finish:
2329
    av_free(title);
2330
    url_fseek(sc->pb, cur_pos, SEEK_SET);
2331
}
2332

    
2333
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
2334
{
2335
    MOVContext *mov = s->priv_data;
2336
    ByteIOContext *pb = s->pb;
2337
    int err;
2338
    MOVAtom atom = { AV_RL32("root") };
2339

    
2340
    mov->fc = s;
2341
    /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2342
    if(!url_is_streamed(pb))
2343
        atom.size = url_fsize(pb);
2344
    else
2345
        atom.size = INT64_MAX;
2346

    
2347
    /* check MOV header */
2348
    if ((err = mov_read_default(mov, pb, atom)) < 0) {
2349
        av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2350
        return err;
2351
    }
2352
    if (!mov->found_moov) {
2353
        av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2354
        return -1;
2355
    }
2356
    dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
2357

    
2358
    if (!url_is_streamed(pb) && mov->chapter_track > 0)
2359
        mov_read_chapters(s);
2360

    
2361
    return 0;
2362
}
2363

    
2364
static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2365
{
2366
    AVIndexEntry *sample = NULL;
2367
    int64_t best_dts = INT64_MAX;
2368
    int i;
2369
    for (i = 0; i < s->nb_streams; i++) {
2370
        AVStream *avst = s->streams[i];
2371
        MOVStreamContext *msc = avst->priv_data;
2372
        if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2373
            AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2374
            int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2375
            dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2376
            if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
2377
                (!url_is_streamed(s->pb) &&
2378
                 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2379
                 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2380
                  (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2381
                sample = current_sample;
2382
                best_dts = dts;
2383
                *st = avst;
2384
            }
2385
        }
2386
    }
2387
    return sample;
2388
}
2389

    
2390
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2391
{
2392
    MOVContext *mov = s->priv_data;
2393
    MOVStreamContext *sc;
2394
    AVIndexEntry *sample;
2395
    AVStream *st = NULL;
2396
    int ret;
2397
 retry:
2398
    sample = mov_find_next_sample(s, &st);
2399
    if (!sample) {
2400
        mov->found_mdat = 0;
2401
        if (!url_is_streamed(s->pb) ||
2402
            mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2403
            url_feof(s->pb))
2404
            return AVERROR_EOF;
2405
        dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
2406
        goto retry;
2407
    }
2408
    sc = st->priv_data;
2409
    /* must be done just before reading, to avoid infinite loop on sample */
2410
    sc->current_sample++;
2411

    
2412
    if (st->discard != AVDISCARD_ALL) {
2413
        if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2414
            av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2415
                   sc->ffindex, sample->pos);
2416
            return -1;
2417
        }
2418
        ret = av_get_packet(sc->pb, pkt, sample->size);
2419
        if (ret < 0)
2420
            return ret;
2421
#if CONFIG_DV_DEMUXER
2422
        if (mov->dv_demux && sc->dv_audio_container) {
2423
            dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2424
            av_free(pkt->data);
2425
            pkt->size = 0;
2426
            ret = dv_get_packet(mov->dv_demux, pkt);
2427
            if (ret < 0)
2428
                return ret;
2429
        }
2430
#endif
2431
    }
2432

    
2433
    pkt->stream_index = sc->ffindex;
2434
    pkt->dts = sample->timestamp;
2435
    if (sc->ctts_data) {
2436
        pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2437
        /* update ctts context */
2438
        sc->ctts_sample++;
2439
        if (sc->ctts_index < sc->ctts_count &&
2440
            sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2441
            sc->ctts_index++;
2442
            sc->ctts_sample = 0;
2443
        }
2444
        if (sc->wrong_dts)
2445
            pkt->dts = AV_NOPTS_VALUE;
2446
    } else {
2447
        int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2448
            st->index_entries[sc->current_sample].timestamp : st->duration;
2449
        pkt->duration = next_dts - pkt->dts;
2450
        pkt->pts = pkt->dts;
2451
    }
2452
    if (st->discard == AVDISCARD_ALL)
2453
        goto retry;
2454
    pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2455
    pkt->pos = sample->pos;
2456
    dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2457
            pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2458
    return 0;
2459
}
2460

    
2461
static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2462
{
2463
    MOVStreamContext *sc = st->priv_data;
2464
    int sample, time_sample;
2465
    int i;
2466

    
2467
    sample = av_index_search_timestamp(st, timestamp, flags);
2468
    dprintf(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2469
    if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2470
        sample = 0;
2471
    if (sample < 0) /* not sure what to do */
2472
        return -1;
2473
    sc->current_sample = sample;
2474
    dprintf(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2475
    /* adjust ctts index */
2476
    if (sc->ctts_data) {
2477
        time_sample = 0;
2478
        for (i = 0; i < sc->ctts_count; i++) {
2479
            int next = time_sample + sc->ctts_data[i].count;
2480
            if (next > sc->current_sample) {
2481
                sc->ctts_index = i;
2482
                sc->ctts_sample = sc->current_sample - time_sample;
2483
                break;
2484
            }
2485
            time_sample = next;
2486
        }
2487
    }
2488
    return sample;
2489
}
2490

    
2491
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2492
{
2493
    AVStream *st;
2494
    int64_t seek_timestamp, timestamp;
2495
    int sample;
2496
    int i;
2497

    
2498
    if (stream_index >= s->nb_streams)
2499
        return -1;
2500
    if (sample_time < 0)
2501
        sample_time = 0;
2502

    
2503
    st = s->streams[stream_index];
2504
    sample = mov_seek_stream(s, st, sample_time, flags);
2505
    if (sample < 0)
2506
        return -1;
2507

    
2508
    /* adjust seek timestamp to found sample timestamp */
2509
    seek_timestamp = st->index_entries[sample].timestamp;
2510

    
2511
    for (i = 0; i < s->nb_streams; i++) {
2512
        st = s->streams[i];
2513
        if (stream_index == i)
2514
            continue;
2515

    
2516
        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2517
        mov_seek_stream(s, st, timestamp, flags);
2518
    }
2519
    return 0;
2520
}
2521

    
2522
static int mov_read_close(AVFormatContext *s)
2523
{
2524
    MOVContext *mov = s->priv_data;
2525
    int i, j;
2526

    
2527
    for (i = 0; i < s->nb_streams; i++) {
2528
        AVStream *st = s->streams[i];
2529
        MOVStreamContext *sc = st->priv_data;
2530

    
2531
        av_freep(&sc->ctts_data);
2532
        for (j = 0; j < sc->drefs_count; j++) {
2533
            av_freep(&sc->drefs[j].path);
2534
            av_freep(&sc->drefs[j].dir);
2535
        }
2536
        av_freep(&sc->drefs);
2537
        if (sc->pb && sc->pb != s->pb)
2538
            url_fclose(sc->pb);
2539

    
2540
        av_freep(&st->codec->palctrl);
2541
    }
2542

    
2543
    if (mov->dv_demux) {
2544
        for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
2545
            av_freep(&mov->dv_fctx->streams[i]->codec);
2546
            av_freep(&mov->dv_fctx->streams[i]);
2547
        }
2548
        av_freep(&mov->dv_fctx);
2549
        av_freep(&mov->dv_demux);
2550
    }
2551

    
2552
    av_freep(&mov->trex_data);
2553

    
2554
    return 0;
2555
}
2556

    
2557
AVInputFormat mov_demuxer = {
2558
    "mov,mp4,m4a,3gp,3g2,mj2",
2559
    NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2560
    sizeof(MOVContext),
2561
    mov_probe,
2562
    mov_read_header,
2563
    mov_read_packet,
2564
    mov_read_close,
2565
    mov_read_seek,
2566
};