Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ bbe46bc4

History | View | Annotate | Download (73.1 KB)

1 6cea494e Zdenek Kabelac
/*
2 7fbde343 Aurelien Jacobs
 * MOV demuxer
3 406792e7 Diego Biurrun
 * Copyright (c) 2001 Fabrice Bellard
4 7c4502c8 Baptiste Coudurier
 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
5 6cea494e Zdenek Kabelac
 *
6 b78e7197 Diego Biurrun
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9 19720f15 Fabrice Bellard
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11 b78e7197 Diego Biurrun
 * version 2.1 of the License, or (at your option) any later version.
12 6cea494e Zdenek Kabelac
 *
13 b78e7197 Diego Biurrun
 * FFmpeg is distributed in the hope that it will be useful,
14 6cea494e Zdenek Kabelac
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 19720f15 Fabrice Bellard
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17 6cea494e Zdenek Kabelac
 *
18 19720f15 Fabrice Bellard
 * You should have received a copy of the GNU Lesser General Public
19 b78e7197 Diego Biurrun
 * License along with FFmpeg; if not, write to the Free Software
20 5509bffa Diego Biurrun
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 6cea494e Zdenek Kabelac
 */
22 d957696f Michael Niedermayer
23
#include <limits.h>
24 115329f1 Diego Biurrun
25 bfc2a19d Baptiste Coudurier
//#define DEBUG
26 873358e5 Baptiste Coudurier
//#define DEBUG_METADATA
27
//#define MOV_EXPORT_ALL_METADATA
28 4e5ef14f Baptiste Coudurier
29 6a5d31ac Diego Biurrun
#include "libavutil/intreadwrite.h"
30 49674dd0 Aurelien Jacobs
#include "libavutil/avstring.h"
31 6cea494e Zdenek Kabelac
#include "avformat.h"
32 9d9f4119 Måns Rullgård
#include "riff.h"
33 e40ee6a2 Baptiste Coudurier
#include "isom.h"
34 245976da Diego Biurrun
#include "libavcodec/mpeg4audio.h"
35
#include "libavcodec/mpegaudiodata.h"
36 9106a698 Stefano Sabatini
#include "libavcodec/get_bits.h"
37 6cea494e Zdenek Kabelac
38 b250f9c6 Aurelien Jacobs
#if CONFIG_ZLIB
39 0147f198 François Revol
#include <zlib.h>
40
#endif
41
42 6cea494e Zdenek Kabelac
/*
43
 * First version by Francois Revol revol@free.fr
44 115329f1 Diego Biurrun
 * Seek function by Gael Chardon gael.dev@4now.net
45 5ca1d879 Zdenek Kabelac
 *
46 6cea494e Zdenek Kabelac
 * Features and limitations:
47 5ca1d879 Zdenek Kabelac
 * - reads most of the QT files I have (at least the structure),
48 6cea494e Zdenek Kabelac
 *   Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
49
 * - the code is quite ugly... maybe I won't do it recursive next time :-)
50 5ca1d879 Zdenek Kabelac
 *
51 6cea494e Zdenek Kabelac
 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
52
 * when coding this :) (it's a writer anyway)
53 5ca1d879 Zdenek Kabelac
 *
54 6cea494e Zdenek Kabelac
 * Reference documents:
55
 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
56
 * Apple:
57 baf25c9d Gael Chardon
 *  http://developer.apple.com/documentation/QuickTime/QTFF/
58 15c8dbe7 Sebastien Bechet
 *  http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
59 6cea494e Zdenek Kabelac
 * QuickTime is a trademark of Apple (AFAIK :))
60
 */
61
62 b595afaa Mike Melanson
#include "qtpalette.h"
63
64 baf25c9d Gael Chardon
65 cd7352d5 Michael Niedermayer
#undef NDEBUG
66
#include <assert.h>
67
68 6cea494e Zdenek Kabelac
/* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
69
70
/* those functions parse an atom */
71
/* return code:
72 e3c4740f Baptiste Coudurier
  0: continue to parse next atom
73 d9526386 Diego Biurrun
 <0: error occurred, exit
74 e3c4740f Baptiste Coudurier
*/
75 6cea494e Zdenek Kabelac
/* links atom IDs to parse functions */
76
typedef struct MOVParseTableEntry {
77 0c1a9eda Zdenek Kabelac
    uint32_t type;
78 c3e92a6c Baptiste Coudurier
    int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOVAtom atom);
79 6cea494e Zdenek Kabelac
} MOVParseTableEntry;
80
81 73d07c27 Baptiste Coudurier
static const MOVParseTableEntry mov_default_parse_table[];
82
83 c6026e43 Baptiste Coudurier
static int mov_metadata_trkn(MOVContext *c, ByteIOContext *pb, unsigned len)
84
{
85
    char buf[16];
86
87
    get_be16(pb); // unknown
88
    snprintf(buf, sizeof(buf), "%d", get_be16(pb));
89
    av_metadata_set(&c->fc->metadata, "track", buf);
90
91
    get_be16(pb); // total tracks
92
93
    return 0;
94
}
95
96 0fb44a4e Baptiste Coudurier
static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
97
{
98
#ifdef MOV_EXPORT_ALL_METADATA
99
    char tmp_key[5];
100
#endif
101
    char str[1024], key2[16], language[4] = {0};
102
    const char *key = NULL;
103
    uint16_t str_size;
104 c6026e43 Baptiste Coudurier
    int (*parse)(MOVContext*, ByteIOContext*, unsigned) = NULL;
105 0fb44a4e Baptiste Coudurier
106
    switch (atom.type) {
107
    case MKTAG(0xa9,'n','a','m'): key = "title";     break;
108
    case MKTAG(0xa9,'a','u','t'):
109
    case MKTAG(0xa9,'A','R','T'):
110
    case MKTAG(0xa9,'w','r','t'): key = "author";    break;
111
    case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
112
    case MKTAG(0xa9,'c','m','t'):
113
    case MKTAG(0xa9,'i','n','f'): key = "comment";   break;
114
    case MKTAG(0xa9,'a','l','b'): key = "album";     break;
115
    case MKTAG(0xa9,'d','a','y'): key = "year";      break;
116
    case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
117
    case MKTAG(0xa9,'t','o','o'):
118
    case MKTAG(0xa9,'e','n','c'): key = "muxer";     break;
119 c6026e43 Baptiste Coudurier
    case MKTAG( 't','r','k','n'): key = "track";
120
        parse = mov_metadata_trkn; break;
121 0fb44a4e Baptiste Coudurier
    }
122
123
    if (c->itunes_metadata && atom.size > 8) {
124
        int data_size = get_be32(pb);
125
        int tag = get_le32(pb);
126
        if (tag == MKTAG('d','a','t','a')) {
127
            get_be32(pb); // type
128
            get_be32(pb); // unknown
129
            str_size = data_size - 16;
130
            atom.size -= 16;
131
        } else return 0;
132
    } else if (atom.size > 4 && key && !c->itunes_metadata) {
133
        str_size = get_be16(pb); // string length
134
        ff_mov_lang_to_iso639(get_be16(pb), language);
135
        atom.size -= 4;
136
    } else
137
        str_size = atom.size;
138
139
#ifdef MOV_EXPORT_ALL_METADATA
140
    if (!key) {
141
        snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
142
        key = tmp_key;
143
    }
144
#endif
145
146
    if (!key)
147
        return 0;
148
    if (atom.size < 0)
149
        return -1;
150
151
    str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
152 c6026e43 Baptiste Coudurier
153
    if (parse)
154
        parse(c, pb, str_size);
155
    else {
156 f584386d Baptiste Coudurier
        get_buffer(pb, str, str_size);
157
        str[str_size] = 0;
158
        av_metadata_set(&c->fc->metadata, key, str);
159
        if (*language && strcmp(language, "und")) {
160
            snprintf(key2, sizeof(key2), "%s-%s", key, language);
161
            av_metadata_set(&c->fc->metadata, key2, str);
162
        }
163 c6026e43 Baptiste Coudurier
    }
164 0fb44a4e Baptiste Coudurier
#ifdef DEBUG_METADATA
165
    av_log(c->fc, AV_LOG_DEBUG, "lang \"%3s\" ", language);
166
    av_log(c->fc, AV_LOG_DEBUG, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %lld\n",
167
           key, str, (char*)&atom.type, str_size, atom.size);
168
#endif
169
170
    return 0;
171
}
172 873358e5 Baptiste Coudurier
173 c3e92a6c Baptiste Coudurier
static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
174 6cea494e Zdenek Kabelac
{
175 b6a17df4 Zdenek Kabelac
    int64_t total_size = 0;
176 c3e92a6c Baptiste Coudurier
    MOVAtom a;
177 6cea494e Zdenek Kabelac
    int i;
178
    int err = 0;
179 5ca1d879 Zdenek Kabelac
180
    a.offset = atom.offset;
181 6cea494e Zdenek Kabelac
182 9ed83b0a Zdenek Kabelac
    if (atom.size < 0)
183 fa22ca22 Baptiste Coudurier
        atom.size = INT64_MAX;
184 5ca1d879 Zdenek Kabelac
    while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
185 873358e5 Baptiste Coudurier
        int (*parse)(MOVContext*, ByteIOContext*, MOVAtom) = NULL;
186 bb270c08 Diego Biurrun
        a.size = atom.size;
187 bcfe2ba0 Baptiste Coudurier
        a.type=0;
188 5ca1d879 Zdenek Kabelac
        if(atom.size >= 8) {
189 bb270c08 Diego Biurrun
            a.size = get_be32(pb);
190 5ca1d879 Zdenek Kabelac
            a.type = get_le32(pb);
191 6cea494e Zdenek Kabelac
        }
192 bb270c08 Diego Biurrun
        total_size += 8;
193 5ca1d879 Zdenek Kabelac
        a.offset += 8;
194 29c90869 Baptiste Coudurier
        dprintf(c->fc, "type: %08x  %.4s  sz: %"PRIx64"  %"PRIx64"   %"PRIx64"\n",
195
                a.type, (char*)&a.type, a.size, atom.size, total_size);
196 5ca1d879 Zdenek Kabelac
        if (a.size == 1) { /* 64 bit extended size */
197 bb270c08 Diego Biurrun
            a.size = get_be64(pb) - 8;
198 5ca1d879 Zdenek Kabelac
            a.offset += 8;
199
            total_size += 8;
200 6cea494e Zdenek Kabelac
        }
201 bb270c08 Diego Biurrun
        if (a.size == 0) {
202
            a.size = atom.size - total_size;
203
            if (a.size <= 8)
204 5cd62665 Zdenek Kabelac
                break;
205 bb270c08 Diego Biurrun
        }
206
        a.size -= 8;
207 8622613d Baptiste Coudurier
        if(a.size < 0)
208 568e18b1 Michael Niedermayer
            break;
209 3d2308b0 Baptiste Coudurier
        a.size = FFMIN(a.size, atom.size - total_size);
210 115329f1 Diego Biurrun
211 873358e5 Baptiste Coudurier
        for (i = 0; mov_default_parse_table[i].type; i++)
212
            if (mov_default_parse_table[i].type == a.type) {
213
                parse = mov_default_parse_table[i].parse;
214
                break;
215
            }
216 11979c46 Baptiste Coudurier
217 873358e5 Baptiste Coudurier
        // container is user data
218
        if (!parse && (atom.type == MKTAG('u','d','t','a') ||
219
                       atom.type == MKTAG('i','l','s','t')))
220
            parse = mov_read_udta_string;
221
222
        if (!parse) { /* skip leaf atoms data */
223 5ca1d879 Zdenek Kabelac
            url_fskip(pb, a.size);
224 bb270c08 Diego Biurrun
        } else {
225 bc5c918e Diego Biurrun
            int64_t start_pos = url_ftell(pb);
226 5c72cad8 Baptiste Coudurier
            int64_t left;
227 873358e5 Baptiste Coudurier
            err = parse(c, pb, a);
228 db3ee6cc Baptiste Coudurier
            if (url_is_streamed(pb) && c->found_moov && c->found_mdat)
229 687f35f3 Baptiste Coudurier
                break;
230 5c72cad8 Baptiste Coudurier
            left = a.size - url_ftell(pb) + start_pos;
231
            if (left > 0) /* skip garbage at atom end */
232
                url_fskip(pb, left);
233 bb270c08 Diego Biurrun
        }
234 6cea494e Zdenek Kabelac
235 bb270c08 Diego Biurrun
        a.offset += a.size;
236 5ca1d879 Zdenek Kabelac
        total_size += a.size;
237 6cea494e Zdenek Kabelac
    }
238
239 9ce84dd8 Baptiste Coudurier
    if (!err && total_size < atom.size && atom.size < 0x7ffff)
240 5ca1d879 Zdenek Kabelac
        url_fskip(pb, atom.size - total_size);
241 5cd62665 Zdenek Kabelac
242 6cea494e Zdenek Kabelac
    return err;
243
}
244
245 c3e92a6c Baptiste Coudurier
static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
246 221e21b7 Baptiste Coudurier
{
247
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
248
    MOVStreamContext *sc = st->priv_data;
249
    int entries, i, j;
250
251
    get_be32(pb); // version + flags
252
    entries = get_be32(pb);
253
    if (entries >= UINT_MAX / sizeof(*sc->drefs))
254
        return -1;
255
    sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
256 0d8f0abf Baptiste Coudurier
    if (!sc->drefs)
257
        return AVERROR(ENOMEM);
258
    sc->drefs_count = entries;
259 221e21b7 Baptiste Coudurier
260
    for (i = 0; i < sc->drefs_count; i++) {
261 c3e92a6c Baptiste Coudurier
        MOVDref *dref = &sc->drefs[i];
262 221e21b7 Baptiste Coudurier
        uint32_t size = get_be32(pb);
263 bc5c918e Diego Biurrun
        int64_t next = url_ftell(pb) + size - 4;
264 221e21b7 Baptiste Coudurier
265
        dref->type = get_le32(pb);
266
        get_be32(pb); // version + flags
267
        dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
268
269
        if (dref->type == MKTAG('a','l','i','s') && size > 150) {
270
            /* macintosh alias record */
271
            uint16_t volume_len, len;
272
            char volume[28];
273
            int16_t type;
274
275
            url_fskip(pb, 10);
276
277
            volume_len = get_byte(pb);
278
            volume_len = FFMIN(volume_len, 27);
279
            get_buffer(pb, volume, 27);
280
            volume[volume_len] = 0;
281
            av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", volume, volume_len);
282
283
            url_fskip(pb, 112);
284
285
            for (type = 0; type != -1 && url_ftell(pb) < next; ) {
286
                type = get_be16(pb);
287
                len = get_be16(pb);
288
                av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
289
                if (len&1)
290
                    len += 1;
291
                if (type == 2) { // absolute path
292 dbb37657 Baptiste Coudurier
                    av_free(dref->path);
293 221e21b7 Baptiste Coudurier
                    dref->path = av_mallocz(len+1);
294 2f4568e5 Baptiste Coudurier
                    if (!dref->path)
295
                        return AVERROR(ENOMEM);
296 221e21b7 Baptiste Coudurier
                    get_buffer(pb, dref->path, len);
297 dbb7cbf2 Baptiste Coudurier
                    if (len > volume_len && !strncmp(dref->path, volume, volume_len)) {
298 221e21b7 Baptiste Coudurier
                        len -= volume_len;
299
                        memmove(dref->path, dref->path+volume_len, len);
300
                        dref->path[len] = 0;
301
                    }
302
                    for (j = 0; j < len; j++)
303
                        if (dref->path[j] == ':')
304
                            dref->path[j] = '/';
305
                    av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
306
                } else
307
                    url_fskip(pb, len);
308
            }
309
        }
310
        url_fseek(pb, next, SEEK_SET);
311
    }
312
    return 0;
313
}
314
315 c3e92a6c Baptiste Coudurier
static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
316 6cea494e Zdenek Kabelac
{
317 fefe43ff Alex Converse
    AVStream *st;
318 0c1a9eda Zdenek Kabelac
    uint32_t type;
319
    uint32_t ctype;
320 b6a17df4 Zdenek Kabelac
321 fefe43ff Alex Converse
    if (c->fc->nb_streams < 1) // meta before first trak
322
        return 0;
323
324
    st = c->fc->streams[c->fc->nb_streams-1];
325
326 6cea494e Zdenek Kabelac
    get_byte(pb); /* version */
327 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
328 6cea494e Zdenek Kabelac
329
    /* component type */
330
    ctype = get_le32(pb);
331
    type = get_le32(pb); /* component subtype */
332
333 9bf1b268 Baptiste Coudurier
    dprintf(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
334
    dprintf(c->fc, "stype= %.4s\n", (char*)&type);
335 2229a5c6 Baptiste Coudurier
336 37ffe34b Baptiste Coudurier
    if     (type == MKTAG('v','i','d','e'))
337 73920f07 Baptiste Coudurier
        st->codec->codec_type = CODEC_TYPE_VIDEO;
338 1c126b4f Baptiste Coudurier
    else if(type == MKTAG('s','o','u','n'))
339 73920f07 Baptiste Coudurier
        st->codec->codec_type = CODEC_TYPE_AUDIO;
340 1c126b4f Baptiste Coudurier
    else if(type == MKTAG('m','1','a',' '))
341 95a07973 Baptiste Coudurier
        st->codec->codec_id = CODEC_ID_MP2;
342 f05783c2 Baptiste Coudurier
    else if(type == MKTAG('s','u','b','p'))
343 8cb97693 Baptiste Coudurier
        st->codec->codec_type = CODEC_TYPE_SUBTITLE;
344 f05783c2 Baptiste Coudurier
345 6cea494e Zdenek Kabelac
    get_be32(pb); /* component  manufacture */
346
    get_be32(pb); /* component flags */
347
    get_be32(pb); /* component flags mask */
348
349 5ca1d879 Zdenek Kabelac
    if(atom.size <= 24)
350 6cea494e Zdenek Kabelac
        return 0; /* nothing left to read */
351 5cd62665 Zdenek Kabelac
352 3c13647a Cedric Vincent
    url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
353 6cea494e Zdenek Kabelac
    return 0;
354
}
355
356 9e40addd Baptiste Coudurier
static int mp4_read_descr_len(ByteIOContext *pb)
357 0e7eed09 Fabrice Bellard
{
358 5cd62665 Zdenek Kabelac
    int len = 0;
359 5ca1d879 Zdenek Kabelac
    int count = 4;
360
    while (count--) {
361 5cd62665 Zdenek Kabelac
        int c = get_byte(pb);
362 bb270c08 Diego Biurrun
        len = (len << 7) | (c & 0x7f);
363
        if (!(c & 0x80))
364
            break;
365 0e7eed09 Fabrice Bellard
    }
366
    return len;
367
}
368
369 9e40addd Baptiste Coudurier
static int mp4_read_descr(MOVContext *c, ByteIOContext *pb, int *tag)
370 0e7eed09 Fabrice Bellard
{
371
    int len;
372
    *tag = get_byte(pb);
373 9e40addd Baptiste Coudurier
    len = mp4_read_descr_len(pb);
374 318c5e05 Michel Bardiaux
    dprintf(c->fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
375 0e7eed09 Fabrice Bellard
    return len;
376
}
377
378 0b07ac42 Baptiste Coudurier
#define MP4ESDescrTag                   0x03
379
#define MP4DecConfigDescrTag            0x04
380
#define MP4DecSpecificDescrTag          0x05
381
382 1dec3994 Baptiste Coudurier
static const AVCodecTag mp4_audio_types[] = {
383 5c3d507f Alex Converse
    { CODEC_ID_MP3ON4, AOT_PS   }, /* old mp3on4 draft */
384
    { CODEC_ID_MP3ON4, AOT_L1   }, /* layer 1 */
385
    { CODEC_ID_MP3ON4, AOT_L2   }, /* layer 2 */
386
    { CODEC_ID_MP3ON4, AOT_L3   }, /* layer 3 */
387 b24bbbb4 Jai Menon
    { CODEC_ID_MP4ALS, AOT_ALS  }, /* MPEG-4 ALS */
388 5c3d507f Alex Converse
    { CODEC_ID_NONE,   AOT_NULL },
389 1dec3994 Baptiste Coudurier
};
390
391 c3e92a6c Baptiste Coudurier
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
392 5cd62665 Zdenek Kabelac
{
393
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
394
    int tag, len;
395 b6a17df4 Zdenek Kabelac
396 5cd62665 Zdenek Kabelac
    get_be32(pb); /* version + flags */
397 9e40addd Baptiste Coudurier
    len = mp4_read_descr(c, pb, &tag);
398 5cd62665 Zdenek Kabelac
    if (tag == MP4ESDescrTag) {
399 bb270c08 Diego Biurrun
        get_be16(pb); /* ID */
400
        get_byte(pb); /* priority */
401 5cd62665 Zdenek Kabelac
    } else
402 bb270c08 Diego Biurrun
        get_be16(pb); /* ID */
403 5cd62665 Zdenek Kabelac
404 9e40addd Baptiste Coudurier
    len = mp4_read_descr(c, pb, &tag);
405 5cd62665 Zdenek Kabelac
    if (tag == MP4DecConfigDescrTag) {
406 0b07ac42 Baptiste Coudurier
        int object_type_id = get_byte(pb);
407
        get_byte(pb); /* stream type */
408
        get_be24(pb); /* buffer size db */
409
        get_be32(pb); /* max bitrate */
410
        get_be32(pb); /* avg bitrate */
411
412
        st->codec->codec_id= codec_get_id(ff_mp4_obj_type, object_type_id);
413
        dprintf(c->fc, "esds object type id %d\n", object_type_id);
414 9e40addd Baptiste Coudurier
        len = mp4_read_descr(c, pb, &tag);
415 bb270c08 Diego Biurrun
        if (tag == MP4DecSpecificDescrTag) {
416 318c5e05 Michel Bardiaux
            dprintf(c->fc, "Specific MPEG4 header len=%d\n", len);
417 852859ff Baptiste Coudurier
            if((uint64_t)len > (1<<30))
418
                return -1;
419 9a630c25 Baptiste Coudurier
            st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
420 b014dd76 Baptiste Coudurier
            if (!st->codec->extradata)
421
                return AVERROR(ENOMEM);
422 17871a02 Baptiste Coudurier
            get_buffer(pb, st->codec->extradata, len);
423
            st->codec->extradata_size = len;
424 1dec3994 Baptiste Coudurier
            if (st->codec->codec_id == CODEC_ID_AAC) {
425
                MPEG4AudioConfig cfg;
426
                ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
427
                                         st->codec->extradata_size);
428 391872e4 Baptiste Coudurier
                if (cfg.chan_config > 7)
429 45a97d30 Baptiste Coudurier
                    return -1;
430
                st->codec->channels = ff_mpeg4audio_channels[cfg.chan_config];
431
                if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
432
                    st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
433
                else
434
                    st->codec->sample_rate = cfg.sample_rate; // ext sample rate ?
435
                dprintf(c->fc, "mp4a config channels %d obj %d ext obj %d "
436
                        "sample rate %d ext sample rate %d\n", st->codec->channels,
437
                        cfg.object_type, cfg.ext_object_type,
438
                        cfg.sample_rate, cfg.ext_sample_rate);
439 1dec3994 Baptiste Coudurier
                if (!(st->codec->codec_id = codec_get_id(mp4_audio_types,
440
                                                         cfg.object_type)))
441
                    st->codec->codec_id = CODEC_ID_AAC;
442 17871a02 Baptiste Coudurier
            }
443 bb270c08 Diego Biurrun
        }
444 5cd62665 Zdenek Kabelac
    }
445
    return 0;
446
}
447
448 6da54074 Baptiste Coudurier
static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
449
{
450
    const int num = get_be32(pb);
451
    const int den = get_be32(pb);
452
    AVStream * const st = c->fc->streams[c->fc->nb_streams-1];
453
    if (den != 0) {
454 f53ee312 Baptiste Coudurier
        if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
455
            (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))
456 6da54074 Baptiste Coudurier
            av_log(c->fc, AV_LOG_WARNING,
457 f53ee312 Baptiste Coudurier
                   "sample aspect ratio already set to %d:%d, overriding by 'pasp' atom\n",
458
                   st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
459 6da54074 Baptiste Coudurier
        st->sample_aspect_ratio.num = num;
460
        st->sample_aspect_ratio.den = den;
461
    }
462
    return 0;
463
}
464
465 5ca1d879 Zdenek Kabelac
/* this atom contains actual media data */
466 c3e92a6c Baptiste Coudurier
static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
467 6cea494e Zdenek Kabelac
{
468 5ca1d879 Zdenek Kabelac
    if(atom.size == 0) /* wrong one (MP4) */
469
        return 0;
470
    c->found_mdat=1;
471
    return 0; /* now go for moov */
472
}
473
474 c3e92a6c Baptiste Coudurier
static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
475 4ea28253 Baptiste Coudurier
{
476
    uint32_t type = get_le32(pb);
477
478 152e9a43 Baptiste Coudurier
    if (type != MKTAG('q','t',' ',' '))
479
        c->isom = 1;
480 a512446e Baptiste Coudurier
    av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
481 4ea28253 Baptiste Coudurier
    get_be32(pb); /* minor version */
482
    url_fskip(pb, atom.size - 8);
483
    return 0;
484
}
485
486 5ca1d879 Zdenek Kabelac
/* this atom should contain all header atoms */
487 c3e92a6c Baptiste Coudurier
static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
488 5ca1d879 Zdenek Kabelac
{
489 9cf0419b Panagiotis Issaris
    if (mov_read_default(c, pb, atom) < 0)
490
        return -1;
491 5ca1d879 Zdenek Kabelac
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
492
    /* so we don't parse the whole file if over a network */
493
    c->found_moov=1;
494
    return 0; /* now go for mdat */
495
}
496
497 c3e92a6c Baptiste Coudurier
static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
498 61aedb0f Baptiste Coudurier
{
499
    c->fragment.moof_offset = url_ftell(pb) - 8;
500
    dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
501
    return mov_read_default(c, pb, atom);
502
}
503 5ca1d879 Zdenek Kabelac
504 c3e92a6c Baptiste Coudurier
static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
505 5ca1d879 Zdenek Kabelac
{
506 f444b977 Baptiste Coudurier
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
507 e4141433 Nicholas Tung
    MOVStreamContext *sc = st->priv_data;
508 f444b977 Baptiste Coudurier
    int version = get_byte(pb);
509 49674dd0 Aurelien Jacobs
    char language[4] = {0};
510 dce25564 Aurelien Jacobs
    unsigned lang;
511 5ca1d879 Zdenek Kabelac
512 b9a87c4d François Revol
    if (version > 1)
513 7e627332 Baptiste Coudurier
        return -1; /* unsupported */
514 5ca1d879 Zdenek Kabelac
515 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
516 f444b977 Baptiste Coudurier
    if (version == 1) {
517
        get_be64(pb);
518
        get_be64(pb);
519
    } else {
520
        get_be32(pb); /* creation time */
521
        get_be32(pb); /* modification time */
522
    }
523 5ca1d879 Zdenek Kabelac
524 f444b977 Baptiste Coudurier
    sc->time_scale = get_be32(pb);
525
    st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
526 5ca1d879 Zdenek Kabelac
527 b9a87c4d François Revol
    lang = get_be16(pb); /* language */
528 49674dd0 Aurelien Jacobs
    if (ff_mov_lang_to_iso639(lang, language))
529
        av_metadata_set(&st->metadata, "language", language);
530 5ca1d879 Zdenek Kabelac
    get_be16(pb); /* quality */
531
532
    return 0;
533
}
534
535 c3e92a6c Baptiste Coudurier
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
536 5ca1d879 Zdenek Kabelac
{
537 1175561e Baptiste Coudurier
    int version = get_byte(pb); /* version */
538 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
539 5ca1d879 Zdenek Kabelac
540 1175561e Baptiste Coudurier
    if (version == 1) {
541
        get_be64(pb);
542
        get_be64(pb);
543
    } else {
544
        get_be32(pb); /* creation time */
545
        get_be32(pb); /* modification time */
546
    }
547 5ca1d879 Zdenek Kabelac
    c->time_scale = get_be32(pb); /* time scale */
548 f8c18cd7 Baptiste Coudurier
549
    dprintf(c->fc, "time scale = %i\n", c->time_scale);
550
551 1175561e Baptiste Coudurier
    c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
552 5ca1d879 Zdenek Kabelac
    get_be32(pb); /* preferred scale */
553
554
    get_be16(pb); /* preferred volume */
555
556
    url_fskip(pb, 10); /* reserved */
557
558
    url_fskip(pb, 36); /* display matrix */
559
560
    get_be32(pb); /* preview time */
561
    get_be32(pb); /* preview duration */
562
    get_be32(pb); /* poster time */
563
    get_be32(pb); /* selection time */
564
    get_be32(pb); /* selection duration */
565
    get_be32(pb); /* current time */
566
    get_be32(pb); /* next track ID */
567
568
    return 0;
569
}
570
571 c3e92a6c Baptiste Coudurier
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
572 9ed83b0a Zdenek Kabelac
{
573
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
574
575 568e18b1 Michael Niedermayer
    if((uint64_t)atom.size > (1<<30))
576
        return -1;
577 115329f1 Diego Biurrun
578 9ed83b0a Zdenek Kabelac
    // currently SVQ3 decoder expect full STSD header - so let's fake it
579
    // this should be fixed and just SMI header should be passed
580 01f4895c Michael Niedermayer
    av_free(st->codec->extradata);
581 b014dd76 Baptiste Coudurier
    st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
582
    if (!st->codec->extradata)
583
        return AVERROR(ENOMEM);
584 17871a02 Baptiste Coudurier
    st->codec->extradata_size = 0x5a + atom.size;
585
    memcpy(st->codec->extradata, "SVQ3", 4); // fake
586
    get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
587
    dprintf(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
588 9ed83b0a Zdenek Kabelac
    return 0;
589
}
590 5ca1d879 Zdenek Kabelac
591 c3e92a6c Baptiste Coudurier
static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
592 de23f234 Baptiste Coudurier
{
593
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
594
    int little_endian = get_be16(pb);
595
596 fa50a027 Baptiste Coudurier
    dprintf(c->fc, "enda %d\n", little_endian);
597
    if (little_endian == 1) {
598 de23f234 Baptiste Coudurier
        switch (st->codec->codec_id) {
599
        case CODEC_ID_PCM_S24BE:
600
            st->codec->codec_id = CODEC_ID_PCM_S24LE;
601
            break;
602
        case CODEC_ID_PCM_S32BE:
603
            st->codec->codec_id = CODEC_ID_PCM_S32LE;
604
            break;
605 a1ef2c4b Peter Ross
        case CODEC_ID_PCM_F32BE:
606
            st->codec->codec_id = CODEC_ID_PCM_F32LE;
607
            break;
608
        case CODEC_ID_PCM_F64BE:
609
            st->codec->codec_id = CODEC_ID_PCM_F64LE;
610
            break;
611 de23f234 Baptiste Coudurier
        default:
612
            break;
613
        }
614
    }
615
    return 0;
616
}
617
618 014a5102 Baptiste Coudurier
/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
619 c3e92a6c Baptiste Coudurier
static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
620 de23f234 Baptiste Coudurier
{
621 27134437 Baptiste Coudurier
    AVStream *st;
622
    uint64_t size;
623 68bc33fa Baptiste Coudurier
    uint8_t *buf;
624 27134437 Baptiste Coudurier
625
    if (c->fc->nb_streams < 1) // will happen with jp2 files
626
        return 0;
627
    st= c->fc->streams[c->fc->nb_streams-1];
628
    size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
629 68bc33fa Baptiste Coudurier
    if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
630 014a5102 Baptiste Coudurier
        return -1;
631 68bc33fa Baptiste Coudurier
    buf= av_realloc(st->codec->extradata, size);
632
    if(!buf)
633
        return -1;
634
    st->codec->extradata= buf;
635
    buf+= st->codec->extradata_size;
636
    st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
637
    AV_WB32(       buf    , atom.size + 8);
638
    AV_WL32(       buf + 4, atom.type);
639
    get_buffer(pb, buf + 8, atom.size);
640 de23f234 Baptiste Coudurier
    return 0;
641
}
642
643 c3e92a6c Baptiste Coudurier
static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
644 d9b1c197 Roberto Togni
{
645
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
646
647
    if((uint64_t)atom.size > (1<<30))
648
        return -1;
649 115329f1 Diego Biurrun
650 3840147e Michael Niedermayer
    if (st->codec->codec_id == CODEC_ID_QDM2) {
651
        // pass all frma atom to codec, needed at least for QDM2
652
        av_free(st->codec->extradata);
653 b014dd76 Baptiste Coudurier
        st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
654
        if (!st->codec->extradata)
655
            return AVERROR(ENOMEM);
656 3840147e Michael Niedermayer
        st->codec->extradata_size = atom.size;
657 b014dd76 Baptiste Coudurier
        get_buffer(pb, st->codec->extradata, atom.size);
658 3840147e Michael Niedermayer
    } else if (atom.size > 8) { /* to read frma, esds atoms */
659 9cf0419b Panagiotis Issaris
        if (mov_read_default(c, pb, atom) < 0)
660
            return -1;
661 5c72cad8 Baptiste Coudurier
    } else
662 bb270c08 Diego Biurrun
        url_fskip(pb, atom.size);
663 d9b1c197 Roberto Togni
    return 0;
664
}
665
666 bde24601 Baptiste Coudurier
/**
667
 * This function reads atom content and puts data in extradata without tag
668
 * nor size unlike mov_read_extradata.
669
 */
670 c3e92a6c Baptiste Coudurier
static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
671 169eb021 Mike Melanson
{
672
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
673
674 568e18b1 Michael Niedermayer
    if((uint64_t)atom.size > (1<<30))
675
        return -1;
676
677 01f4895c Michael Niedermayer
    av_free(st->codec->extradata);
678 b014dd76 Baptiste Coudurier
    st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
679
    if (!st->codec->extradata)
680
        return AVERROR(ENOMEM);
681 01f4895c Michael Niedermayer
    st->codec->extradata_size = atom.size;
682 b014dd76 Baptiste Coudurier
    get_buffer(pb, st->codec->extradata, atom.size);
683 169eb021 Mike Melanson
    return 0;
684
}
685
686 c3e92a6c Baptiste Coudurier
static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
687 5ca1d879 Zdenek Kabelac
{
688
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
689 e4141433 Nicholas Tung
    MOVStreamContext *sc = st->priv_data;
690 568e18b1 Michael Niedermayer
    unsigned int i, entries;
691 5ca1d879 Zdenek Kabelac
692
    get_byte(pb); /* version */
693 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
694 5ca1d879 Zdenek Kabelac
695
    entries = get_be32(pb);
696 115329f1 Diego Biurrun
697 568e18b1 Michael Niedermayer
    if(entries >= UINT_MAX/sizeof(int64_t))
698
        return -1;
699 115329f1 Diego Biurrun
700 9a630c25 Baptiste Coudurier
    sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
701 5ca1d879 Zdenek Kabelac
    if (!sc->chunk_offsets)
702 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
703
    sc->chunk_count = entries;
704
705 37ffe34b Baptiste Coudurier
    if      (atom.type == MKTAG('s','t','c','o'))
706
        for(i=0; i<entries; i++)
707 5ca1d879 Zdenek Kabelac
            sc->chunk_offsets[i] = get_be32(pb);
708 37ffe34b Baptiste Coudurier
    else if (atom.type == MKTAG('c','o','6','4'))
709
        for(i=0; i<entries; i++)
710 5ca1d879 Zdenek Kabelac
            sc->chunk_offsets[i] = get_be64(pb);
711 37ffe34b Baptiste Coudurier
    else
712 5ca1d879 Zdenek Kabelac
        return -1;
713 115329f1 Diego Biurrun
714 5ca1d879 Zdenek Kabelac
    return 0;
715
}
716
717 2288834f Baptiste Coudurier
/**
718
 * Compute codec id for 'lpcm' tag.
719
 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
720
 */
721 fb65d2ca Diego Pettenò
static enum CodecID mov_get_lpcm_codec_id(int bps, int flags)
722 2288834f Baptiste Coudurier
{
723
    if (flags & 1) { // floating point
724
        if (flags & 2) { // big endian
725
            if      (bps == 32) return CODEC_ID_PCM_F32BE;
726 7e4b3fb8 Baptiste Coudurier
            else if (bps == 64) return CODEC_ID_PCM_F64BE;
727 2288834f Baptiste Coudurier
        } else {
728 7e4b3fb8 Baptiste Coudurier
            if      (bps == 32) return CODEC_ID_PCM_F32LE;
729
            else if (bps == 64) return CODEC_ID_PCM_F64LE;
730 2288834f Baptiste Coudurier
        }
731
    } else {
732
        if (flags & 2) {
733
            if      (bps == 8)
734
                // signed integer
735
                if (flags & 4)  return CODEC_ID_PCM_S8;
736
                else            return CODEC_ID_PCM_U8;
737
            else if (bps == 16) return CODEC_ID_PCM_S16BE;
738
            else if (bps == 24) return CODEC_ID_PCM_S24BE;
739
            else if (bps == 32) return CODEC_ID_PCM_S32BE;
740
        } else {
741
            if      (bps == 8)
742
                if (flags & 4)  return CODEC_ID_PCM_S8;
743
                else            return CODEC_ID_PCM_U8;
744 021b8ae3 Baptiste Coudurier
            else if (bps == 16) return CODEC_ID_PCM_S16LE;
745 2288834f Baptiste Coudurier
            else if (bps == 24) return CODEC_ID_PCM_S24LE;
746
            else if (bps == 32) return CODEC_ID_PCM_S32LE;
747
        }
748
    }
749 fb65d2ca Diego Pettenò
    return CODEC_ID_NONE;
750 2288834f Baptiste Coudurier
}
751
752 c3e92a6c Baptiste Coudurier
static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
753 5ca1d879 Zdenek Kabelac
{
754
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
755 e4141433 Nicholas Tung
    MOVStreamContext *sc = st->priv_data;
756 baf9fb32 Baptiste Coudurier
    int j, entries, pseudo_stream_id;
757 b595afaa Mike Melanson
758 6cea494e Zdenek Kabelac
    get_byte(pb); /* version */
759 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
760 6cea494e Zdenek Kabelac
761
    entries = get_be32(pb);
762
763 117a9190 Baptiste Coudurier
    for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
764
        //Parsing Sample description table
765 b6a17df4 Zdenek Kabelac
        enum CodecID id;
766 28155113 Baptiste Coudurier
        int dref_id = 1;
767 c3e92a6c Baptiste Coudurier
        MOVAtom a = { 0, 0, 0 };
768 bc5c918e Diego Biurrun
        int64_t start_pos = url_ftell(pb);
769 bb270c08 Diego Biurrun
        int size = get_be32(pb); /* size */
770 baf9fb32 Baptiste Coudurier
        uint32_t format = get_le32(pb); /* data format */
771 5cd62665 Zdenek Kabelac
772 28155113 Baptiste Coudurier
        if (size >= 16) {
773
            get_be32(pb); /* reserved */
774
            get_be16(pb); /* reserved */
775
            dref_id = get_be16(pb);
776
        }
777 0e7eed09 Fabrice Bellard
778 744a9c75 Michael Niedermayer
        if (st->codec->codec_tag &&
779 978677a7 Baptiste Coudurier
            st->codec->codec_tag != format &&
780 744a9c75 Michael Niedermayer
            (c->fc->video_codec_id ? codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
781 1c126b4f Baptiste Coudurier
                                   : st->codec->codec_tag != MKTAG('j','p','e','g'))
782 744a9c75 Michael Niedermayer
           ){
783 7ce68923 Diego Biurrun
            /* Multiple fourcc, we skip JPEG. This is not correct, we should
784
             * export it as a separate AVStream but this needs a few changes
785
             * in the MOV demuxer, patch welcome. */
786 285a3da9 Baptiste Coudurier
            av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
787 e7cc4b52 Baptiste Coudurier
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
788
            continue;
789
        }
790 978677a7 Baptiste Coudurier
        sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
791 221e21b7 Baptiste Coudurier
        sc->dref_id= dref_id;
792 e7cc4b52 Baptiste Coudurier
793 bb270c08 Diego Biurrun
        st->codec->codec_tag = format;
794 1e5f5e3b Baptiste Coudurier
        id = codec_get_id(codec_movaudio_tags, format);
795 1c126b4f Baptiste Coudurier
        if (id<=0 && (format&0xFFFF) == 'm'+('s'<<8))
796 bca7db35 Michael Niedermayer
            id = codec_get_id(codec_wav_tags, bswap_32(format)&0xFFFF);
797
798 48855b26 Baptiste Coudurier
        if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
799 99487f42 Baptiste Coudurier
            st->codec->codec_type = CODEC_TYPE_AUDIO;
800 48855b26 Baptiste Coudurier
        } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
801 1c126b4f Baptiste Coudurier
                   format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
802 1e5f5e3b Baptiste Coudurier
            id = codec_get_id(codec_movvideo_tags, format);
803 99487f42 Baptiste Coudurier
            if (id <= 0)
804 de23f234 Baptiste Coudurier
                id = codec_get_id(codec_bmp_tags, format);
805 99487f42 Baptiste Coudurier
            if (id > 0)
806
                st->codec->codec_type = CODEC_TYPE_VIDEO;
807 1e3c9307 Michael Niedermayer
            else if(st->codec->codec_type == CODEC_TYPE_DATA){
808
                id = codec_get_id(ff_codec_movsubtitle_tags, format);
809
                if(id > 0)
810
                    st->codec->codec_type = CODEC_TYPE_SUBTITLE;
811
            }
812 99487f42 Baptiste Coudurier
        }
813
814 29c90869 Baptiste Coudurier
        dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
815
                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
816
                (format >> 24) & 0xff, st->codec->codec_type);
817 a20da52c Baptiste Coudurier
818 99487f42 Baptiste Coudurier
        if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
819 baf9fb32 Baptiste Coudurier
            uint8_t codec_name[32];
820
            unsigned int color_depth;
821
            int color_greyscale;
822
823 01f4895c Michael Niedermayer
            st->codec->codec_id = id;
824 6cea494e Zdenek Kabelac
            get_be16(pb); /* version */
825
            get_be16(pb); /* revision level */
826
            get_be32(pb); /* vendor */
827
            get_be32(pb); /* temporal quality */
828 94472c1d Diego Biurrun
            get_be32(pb); /* spatial quality */
829 3cb4ee51 Baptiste Coudurier
830
            st->codec->width = get_be16(pb); /* width */
831
            st->codec->height = get_be16(pb); /* height */
832
833 6cea494e Zdenek Kabelac
            get_be32(pb); /* horiz resolution */
834
            get_be32(pb); /* vert resolution */
835
            get_be32(pb); /* data size, always 0 */
836 43612ffe Baptiste Coudurier
            get_be16(pb); /* frames per samples */
837 f8c18cd7 Baptiste Coudurier
838 eb034aca Baptiste Coudurier
            get_buffer(pb, codec_name, 32); /* codec name, pascal string */
839 576f1445 Baptiste Coudurier
            if (codec_name[0] <= 31) {
840
                memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
841
                st->codec->codec_name[codec_name[0]] = 0;
842
            }
843 5cd62665 Zdenek Kabelac
844 dd1c8f3e Luca Abeni
            st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
845 01f4895c Michael Niedermayer
            st->codec->color_table_id = get_be16(pb); /* colortable id */
846 0de2157f Baptiste Coudurier
            dprintf(c->fc, "depth %d, ctab id %d\n",
847 dd1c8f3e Luca Abeni
                   st->codec->bits_per_coded_sample, st->codec->color_table_id);
848 b595afaa Mike Melanson
            /* figure out the palette situation */
849 dd1c8f3e Luca Abeni
            color_depth = st->codec->bits_per_coded_sample & 0x1F;
850
            color_greyscale = st->codec->bits_per_coded_sample & 0x20;
851 b595afaa Mike Melanson
852
            /* if the depth is 2, 4, or 8 bpp, file is palettized */
853 115329f1 Diego Biurrun
            if ((color_depth == 2) || (color_depth == 4) ||
854 b595afaa Mike Melanson
                (color_depth == 8)) {
855 47e1d7ef Baptiste Coudurier
                /* for palette traversal */
856
                unsigned int color_start, color_count, color_end;
857
                unsigned char r, g, b;
858
859 e49da827 Baptiste Coudurier
                st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
860 b595afaa Mike Melanson
                if (color_greyscale) {
861 47e1d7ef Baptiste Coudurier
                    int color_index, color_dec;
862 b595afaa Mike Melanson
                    /* compute the greyscale palette */
863 dd1c8f3e Luca Abeni
                    st->codec->bits_per_coded_sample = color_depth;
864 b595afaa Mike Melanson
                    color_count = 1 << color_depth;
865
                    color_index = 255;
866
                    color_dec = 256 / (color_count - 1);
867
                    for (j = 0; j < color_count; j++) {
868
                        r = g = b = color_index;
869 e49da827 Baptiste Coudurier
                        st->codec->palctrl->palette[j] =
870 b595afaa Mike Melanson
                            (r << 16) | (g << 8) | (b);
871
                        color_index -= color_dec;
872
                        if (color_index < 0)
873
                            color_index = 0;
874
                    }
875 71f36235 Baptiste Coudurier
                } else if (st->codec->color_table_id) {
876 47e1d7ef Baptiste Coudurier
                    const uint8_t *color_table;
877 b595afaa Mike Melanson
                    /* if flag bit 3 is set, use the default palette */
878
                    color_count = 1 << color_depth;
879
                    if (color_depth == 2)
880 a90466f7 Michael Niedermayer
                        color_table = ff_qt_default_palette_4;
881 b595afaa Mike Melanson
                    else if (color_depth == 4)
882 a90466f7 Michael Niedermayer
                        color_table = ff_qt_default_palette_16;
883 b595afaa Mike Melanson
                    else
884 a90466f7 Michael Niedermayer
                        color_table = ff_qt_default_palette_256;
885 b595afaa Mike Melanson
886
                    for (j = 0; j < color_count; j++) {
887 2121b160 Ronald S. Bultje
                        r = color_table[j * 3 + 0];
888
                        g = color_table[j * 3 + 1];
889
                        b = color_table[j * 3 + 2];
890 e49da827 Baptiste Coudurier
                        st->codec->palctrl->palette[j] =
891 b595afaa Mike Melanson
                            (r << 16) | (g << 8) | (b);
892
                    }
893
                } else {
894
                    /* load the palette from the file */
895
                    color_start = get_be32(pb);
896
                    color_count = get_be16(pb);
897
                    color_end = get_be16(pb);
898 8b35bd80 Mike Melanson
                    if ((color_start <= 255) &&
899
                        (color_end <= 255)) {
900 9de2919c Mike Melanson
                        for (j = color_start; j <= color_end; j++) {
901
                            /* each R, G, or B component is 16 bits;
902
                             * only use the top 8 bits; skip alpha bytes
903
                             * up front */
904
                            get_byte(pb);
905
                            get_byte(pb);
906
                            r = get_byte(pb);
907
                            get_byte(pb);
908
                            g = get_byte(pb);
909
                            get_byte(pb);
910
                            b = get_byte(pb);
911
                            get_byte(pb);
912 e49da827 Baptiste Coudurier
                            st->codec->palctrl->palette[j] =
913 9de2919c Mike Melanson
                                (r << 16) | (g << 8) | (b);
914 8b35bd80 Mike Melanson
                        }
915 b595afaa Mike Melanson
                    }
916
                }
917 01f4895c Michael Niedermayer
                st->codec->palctrl->palette_changed = 1;
918 e49da827 Baptiste Coudurier
            }
919 de23f234 Baptiste Coudurier
        } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
920 aaef2bb3 Baptiste Coudurier
            int bits_per_sample, flags;
921 de23f234 Baptiste Coudurier
            uint16_t version = get_be16(pb);
922 b595afaa Mike Melanson
923 99487f42 Baptiste Coudurier
            st->codec->codec_id = id;
924 de23f234 Baptiste Coudurier
            get_be16(pb); /* revision level */
925
            get_be32(pb); /* vendor */
926 6d6d7970 Mike Melanson
927 de23f234 Baptiste Coudurier
            st->codec->channels = get_be16(pb);             /* channel count */
928 318c5e05 Michel Bardiaux
            dprintf(c->fc, "audio channels %d\n", st->codec->channels);
929 dd1c8f3e Luca Abeni
            st->codec->bits_per_coded_sample = get_be16(pb);      /* sample size */
930 de23f234 Baptiste Coudurier
931 77c75437 Baptiste Coudurier
            sc->audio_cid = get_be16(pb);
932 de23f234 Baptiste Coudurier
            get_be16(pb); /* packet size = 0 */
933
934
            st->codec->sample_rate = ((get_be32(pb) >> 16));
935
936 5ef3ad59 Baptiste Coudurier
            //Read QT version 1 fields. In version 0 these do not exist.
937
            dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
938
            if(!c->isom) {
939
                if(version==1) {
940
                    sc->samples_per_frame = get_be32(pb);
941
                    get_be32(pb); /* bytes per packet */
942
                    sc->bytes_per_frame = get_be32(pb);
943
                    get_be32(pb); /* bytes per sample */
944
                } else if(version==2) {
945
                    get_be32(pb); /* sizeof struct only */
946
                    st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
947
                    st->codec->channels = get_be32(pb);
948
                    get_be32(pb); /* always 0x7F000000 */
949 dd1c8f3e Luca Abeni
                    st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
950 aaef2bb3 Baptiste Coudurier
                    flags = get_be32(pb); /* lcpm format specific flag */
951 9184d53a Baptiste Coudurier
                    sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
952
                    sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
953 2288834f Baptiste Coudurier
                    if (format == MKTAG('l','p','c','m'))
954 dd1c8f3e Luca Abeni
                        st->codec->codec_id = mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
955 5ef3ad59 Baptiste Coudurier
                }
956
            }
957
958 de23f234 Baptiste Coudurier
            switch (st->codec->codec_id) {
959 b72708f8 Baptiste Coudurier
            case CODEC_ID_PCM_S8:
960
            case CODEC_ID_PCM_U8:
961 dd1c8f3e Luca Abeni
                if (st->codec->bits_per_coded_sample == 16)
962 b72708f8 Baptiste Coudurier
                    st->codec->codec_id = CODEC_ID_PCM_S16BE;
963
                break;
964 0dd39bfe Baptiste Coudurier
            case CODEC_ID_PCM_S16LE:
965 de23f234 Baptiste Coudurier
            case CODEC_ID_PCM_S16BE:
966 dd1c8f3e Luca Abeni
                if (st->codec->bits_per_coded_sample == 8)
967 de23f234 Baptiste Coudurier
                    st->codec->codec_id = CODEC_ID_PCM_S8;
968 dd1c8f3e Luca Abeni
                else if (st->codec->bits_per_coded_sample == 24)
969 6b477e1b Baptiste Coudurier
                    st->codec->codec_id =
970
                        st->codec->codec_id == CODEC_ID_PCM_S16BE ?
971
                        CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
972 de23f234 Baptiste Coudurier
                break;
973 53152765 Baptiste Coudurier
            /* set values for old format before stsd version 1 appeared */
974
            case CODEC_ID_MACE3:
975
                sc->samples_per_frame = 6;
976
                sc->bytes_per_frame = 2*st->codec->channels;
977
                break;
978
            case CODEC_ID_MACE6:
979
                sc->samples_per_frame = 6;
980
                sc->bytes_per_frame = 1*st->codec->channels;
981
                break;
982
            case CODEC_ID_ADPCM_IMA_QT:
983
                sc->samples_per_frame = 64;
984
                sc->bytes_per_frame = 34*st->codec->channels;
985
                break;
986 cc326d2b Baptiste Coudurier
            case CODEC_ID_GSM:
987
                sc->samples_per_frame = 160;
988
                sc->bytes_per_frame = 33;
989
                break;
990 de23f234 Baptiste Coudurier
            default:
991
                break;
992 6d6d7970 Mike Melanson
            }
993 14342fd5 Johannes Carlsson
994 9770089d Baptiste Coudurier
            bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
995
            if (bits_per_sample) {
996 dd1c8f3e Luca Abeni
                st->codec->bits_per_coded_sample = bits_per_sample;
997 9770089d Baptiste Coudurier
                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
998
            }
999 cc8d87b7 Michael Niedermayer
        } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){
1000 58e9f2ed David Conrad
            // ttxt stsd contains display flags, justification, background
1001
            // color, fonts, and default styles, so fake an atom to read it
1002
            MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
1003 fb9ac654 Reimar Döffinger
            if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1004 3dd36041 Reimar Döffinger
                mov_read_glbl(c, pb, fake_atom);
1005 cc8d87b7 Michael Niedermayer
            st->codec->codec_id= id;
1006 6cdbff63 David Conrad
            st->codec->width = sc->width;
1007
            st->codec->height = sc->height;
1008 de23f234 Baptiste Coudurier
        } else {
1009
            /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1010
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
1011 6cea494e Zdenek Kabelac
        }
1012 de23f234 Baptiste Coudurier
        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1013
        a.size = size - (url_ftell(pb) - start_pos);
1014 9cf0419b Panagiotis Issaris
        if (a.size > 8) {
1015
            if (mov_read_default(c, pb, a) < 0)
1016
                return -1;
1017
        } else if (a.size > 0)
1018 de23f234 Baptiste Coudurier
            url_fskip(pb, a.size);
1019 6cea494e Zdenek Kabelac
    }
1020 115329f1 Diego Biurrun
1021 60f5c96e Baptiste Coudurier
    if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1022 302c389e Michael Niedermayer
        st->codec->sample_rate= sc->time_scale;
1023 e31bd3e3 Baptiste Coudurier
1024 d00f8e17 Baptiste Coudurier
    /* special codec parameters handling */
1025 e31bd3e3 Baptiste Coudurier
    switch (st->codec->codec_id) {
1026 b250f9c6 Aurelien Jacobs
#if CONFIG_DV_DEMUXER
1027 b60c0454 Baptiste Coudurier
    case CODEC_ID_DVAUDIO:
1028 8e2fd8e1 Stefano Sabatini
        c->dv_fctx = avformat_alloc_context();
1029 b60c0454 Baptiste Coudurier
        c->dv_demux = dv_init_demux(c->dv_fctx);
1030
        if (!c->dv_demux) {
1031
            av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1032
            return -1;
1033
        }
1034
        sc->dv_audio_container = 1;
1035
        st->codec->codec_id = CODEC_ID_PCM_S16LE;
1036
        break;
1037 989ac5a6 Baptiste Coudurier
#endif
1038 b95319a2 Baptiste Coudurier
    /* no ifdef since parameters are always those */
1039 3f78a3a9 Baptiste Coudurier
    case CODEC_ID_QCELP:
1040 17ad7b24 Baptiste Coudurier
        // force sample rate for qcelp when not stored in mov
1041
        if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1042
            st->codec->sample_rate = 8000;
1043 73b458e3 Kenan Gillet
        st->codec->frame_size= 160;
1044 061f407e Kenan Gillet
        st->codec->channels= 1; /* really needed */
1045 73b458e3 Kenan Gillet
        break;
1046 b95319a2 Baptiste Coudurier
    case CODEC_ID_AMR_NB:
1047 aeb62788 Baptiste Coudurier
    case CODEC_ID_AMR_WB:
1048 cfb5a2ab Baptiste Coudurier
        st->codec->frame_size= sc->samples_per_frame;
1049 b95319a2 Baptiste Coudurier
        st->codec->channels= 1; /* really needed */
1050 f06188d5 Baptiste Coudurier
        /* force sample rate for amr, stsd in 3gp does not store sample rate */
1051 5b9ce252 Baptiste Coudurier
        if (st->codec->codec_id == CODEC_ID_AMR_NB)
1052 f06188d5 Baptiste Coudurier
            st->codec->sample_rate = 8000;
1053 5b9ce252 Baptiste Coudurier
        else if (st->codec->codec_id == CODEC_ID_AMR_WB)
1054
            st->codec->sample_rate = 16000;
1055 b95319a2 Baptiste Coudurier
        break;
1056 a41104f8 Michael Niedermayer
    case CODEC_ID_MP2:
1057 c59f24e6 Baptiste Coudurier
    case CODEC_ID_MP3:
1058 95a07973 Baptiste Coudurier
        st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1059 57004ff1 Aurelien Jacobs
        st->need_parsing = AVSTREAM_PARSE_FULL;
1060 a41104f8 Michael Niedermayer
        break;
1061 5610f20e Baptiste Coudurier
    case CODEC_ID_GSM:
1062 74e9b9ae Baptiste Coudurier
    case CODEC_ID_ADPCM_MS:
1063
    case CODEC_ID_ADPCM_IMA_WAV:
1064
        st->codec->block_align = sc->bytes_per_frame;
1065
        break;
1066 be511925 Baptiste Coudurier
    case CODEC_ID_ALAC:
1067 a1532824 Baptiste Coudurier
        if (st->codec->extradata_size == 36) {
1068 364df7b7 Baptiste Coudurier
            st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1069
            st->codec->channels   = AV_RB8 (st->codec->extradata+21);
1070 a1532824 Baptiste Coudurier
        }
1071 be511925 Baptiste Coudurier
        break;
1072 e31bd3e3 Baptiste Coudurier
    default:
1073
        break;
1074
    }
1075 5cd62665 Zdenek Kabelac
1076 6cea494e Zdenek Kabelac
    return 0;
1077
}
1078
1079 c3e92a6c Baptiste Coudurier
static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1080 6cea494e Zdenek Kabelac
{
1081 5ca1d879 Zdenek Kabelac
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1082 e4141433 Nicholas Tung
    MOVStreamContext *sc = st->priv_data;
1083 568e18b1 Michael Niedermayer
    unsigned int i, entries;
1084 b6a17df4 Zdenek Kabelac
1085 6cea494e Zdenek Kabelac
    get_byte(pb); /* version */
1086 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1087 6cea494e Zdenek Kabelac
1088
    entries = get_be32(pb);
1089 115329f1 Diego Biurrun
1090 f8c18cd7 Baptiste Coudurier
    dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1091
1092 0d8f0abf Baptiste Coudurier
    if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
1093
        return -1;
1094 04e06cfa Baptiste Coudurier
    sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1095
    if (!sc->stsc_data)
1096 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1097
    sc->stsc_count = entries;
1098
1099 6cea494e Zdenek Kabelac
    for(i=0; i<entries; i++) {
1100 04e06cfa Baptiste Coudurier
        sc->stsc_data[i].first = get_be32(pb);
1101
        sc->stsc_data[i].count = get_be32(pb);
1102
        sc->stsc_data[i].id = get_be32(pb);
1103 6cea494e Zdenek Kabelac
    }
1104
    return 0;
1105
}
1106
1107 171a3531 Baptiste Coudurier
static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1108
{
1109
    AVStream *st;
1110
    MOVStreamContext *sc;
1111
    unsigned i, entries;
1112
1113
    if (c->fc->nb_streams < 1)
1114
        return 0;
1115
    st = c->fc->streams[c->fc->nb_streams-1];
1116
    sc = st->priv_data;
1117
1118
    get_be32(pb); // version + flags
1119
1120
    entries = get_be32(pb);
1121
    if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1122
        return -1;
1123
    sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1124
    if (!sc->stps_data)
1125
        return AVERROR(ENOMEM);
1126
    sc->stps_count = entries;
1127
1128
    for (i = 0; i < entries; i++) {
1129
        sc->stps_data[i] = get_be32(pb);
1130
        //dprintf(c->fc, "stps %d\n", sc->stps_data[i]);
1131
    }
1132
1133
    return 0;
1134
}
1135
1136 c3e92a6c Baptiste Coudurier
static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1137 247d56f5 Brian Becker
{
1138
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1139 e4141433 Nicholas Tung
    MOVStreamContext *sc = st->priv_data;
1140 568e18b1 Michael Niedermayer
    unsigned int i, entries;
1141 247d56f5 Brian Becker
1142
    get_byte(pb); /* version */
1143 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1144 247d56f5 Brian Becker
1145
    entries = get_be32(pb);
1146 115329f1 Diego Biurrun
1147 0d8f0abf Baptiste Coudurier
    dprintf(c->fc, "keyframe_count = %d\n", entries);
1148
1149 1c02d96f Baptiste Coudurier
    if(entries >= UINT_MAX / sizeof(int))
1150 568e18b1 Michael Niedermayer
        return -1;
1151 1c02d96f Baptiste Coudurier
    sc->keyframes = av_malloc(entries * sizeof(int));
1152 247d56f5 Brian Becker
    if (!sc->keyframes)
1153 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1154
    sc->keyframe_count = entries;
1155
1156 247d56f5 Brian Becker
    for(i=0; i<entries; i++) {
1157
        sc->keyframes[i] = get_be32(pb);
1158 f8c18cd7 Baptiste Coudurier
        //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1159 247d56f5 Brian Becker
    }
1160
    return 0;
1161
}
1162
1163 c3e92a6c Baptiste Coudurier
static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1164 6cea494e Zdenek Kabelac
{
1165 5ca1d879 Zdenek Kabelac
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1166 e4141433 Nicholas Tung
    MOVStreamContext *sc = st->priv_data;
1167 bd27eed6 Alex Converse
    unsigned int i, entries, sample_size, field_size, num_bytes;
1168
    GetBitContext gb;
1169
    unsigned char* buf;
1170 b6a17df4 Zdenek Kabelac
1171 6cea494e Zdenek Kabelac
    get_byte(pb); /* version */
1172 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1173 5cd62665 Zdenek Kabelac
1174 bd27eed6 Alex Converse
    if (atom.type == MKTAG('s','t','s','z')) {
1175 d0dab0ec Alex Converse
        sample_size = get_be32(pb);
1176
        if (!sc->sample_size) /* do not overwrite value computed in stsd */
1177
            sc->sample_size = sample_size;
1178
        field_size = 32;
1179 bd27eed6 Alex Converse
    } else {
1180
        sample_size = 0;
1181
        get_be24(pb); /* reserved */
1182
        field_size = get_byte(pb);
1183
    }
1184 6cea494e Zdenek Kabelac
    entries = get_be32(pb);
1185 0d8f0abf Baptiste Coudurier
1186
    dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1187 568e18b1 Michael Niedermayer
1188 6cea494e Zdenek Kabelac
    sc->sample_count = entries;
1189 b72708f8 Baptiste Coudurier
    if (sample_size)
1190
        return 0;
1191
1192 bd27eed6 Alex Converse
    if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1193
        av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1194
        return -1;
1195
    }
1196
1197 0d8f0abf Baptiste Coudurier
    if(entries >= UINT_MAX / sizeof(int))
1198
        return -1;
1199 1c02d96f Baptiste Coudurier
    sc->sample_sizes = av_malloc(entries * sizeof(int));
1200 b6a17df4 Zdenek Kabelac
    if (!sc->sample_sizes)
1201 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1202
1203 bd27eed6 Alex Converse
    num_bytes = (entries*field_size+4)>>3;
1204
1205 08a5b4e9 Baptiste Coudurier
    buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1206 bd27eed6 Alex Converse
    if (!buf) {
1207
        av_freep(&sc->sample_sizes);
1208
        return AVERROR(ENOMEM);
1209
    }
1210
1211
    if (get_buffer(pb, buf, num_bytes) < num_bytes) {
1212
        av_freep(&sc->sample_sizes);
1213
        av_free(buf);
1214
        return -1;
1215
    }
1216
1217
    init_get_bits(&gb, buf, 8*num_bytes);
1218
1219 eb61405a Baptiste Coudurier
    for(i=0; i<entries; i++)
1220 bd27eed6 Alex Converse
        sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1221
1222
    av_free(buf);
1223 6cea494e Zdenek Kabelac
    return 0;
1224
}
1225
1226 c3e92a6c Baptiste Coudurier
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1227 0147f198 François Revol
{
1228 5ca1d879 Zdenek Kabelac
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1229 e4141433 Nicholas Tung
    MOVStreamContext *sc = st->priv_data;
1230 568e18b1 Michael Niedermayer
    unsigned int i, entries;
1231 d957696f Michael Niedermayer
    int64_t duration=0;
1232
    int64_t total_sample_count=0;
1233 b6a17df4 Zdenek Kabelac
1234 0147f198 François Revol
    get_byte(pb); /* version */
1235 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1236 0147f198 François Revol
    entries = get_be32(pb);
1237 0d8f0abf Baptiste Coudurier
1238
    dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1239
1240 c3e92a6c Baptiste Coudurier
    if(entries >= UINT_MAX / sizeof(*sc->stts_data))
1241 568e18b1 Michael Niedermayer
        return -1;
1242 c3e92a6c Baptiste Coudurier
    sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1243 c1da59fa Baptiste Coudurier
    if (!sc->stts_data)
1244 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1245
    sc->stts_count = entries;
1246 cd7352d5 Michael Niedermayer
1247 0147f198 François Revol
    for(i=0; i<entries; i++) {
1248 cd461d48 Michael Niedermayer
        int sample_duration;
1249
        int sample_count;
1250 0147f198 François Revol
1251 891f64b3 joca@rixmail.se
        sample_count=get_be32(pb);
1252 0147f198 François Revol
        sample_duration = get_be32(pb);
1253 cd7352d5 Michael Niedermayer
        sc->stts_data[i].count= sample_count;
1254
        sc->stts_data[i].duration= sample_duration;
1255
1256 318c5e05 Michel Bardiaux
        dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1257 4e5ef14f Baptiste Coudurier
1258 7e815047 Baptiste Coudurier
        duration+=(int64_t)sample_duration*sample_count;
1259 891f64b3 joca@rixmail.se
        total_sample_count+=sample_count;
1260
    }
1261
1262 961e0ccd Michael Niedermayer
    st->nb_frames= total_sample_count;
1263
    if(duration)
1264
        st->duration= duration;
1265 0147f198 François Revol
    return 0;
1266
}
1267
1268 4b29ed39 Baptiste Coudurier
static int mov_read_cslg(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1269
{
1270
    AVStream *st;
1271
    MOVStreamContext *sc;
1272
1273 41e64999 Baptiste Coudurier
    if (c->fc->nb_streams < 1)
1274 4b29ed39 Baptiste Coudurier
        return 0;
1275
    st = c->fc->streams[c->fc->nb_streams-1];
1276
    sc = st->priv_data;
1277
1278
    get_be32(pb); // version + flags
1279
1280
    sc->dts_shift = get_be32(pb);
1281
    dprintf(c->fc, "dts shift %d\n", sc->dts_shift);
1282
1283
    get_be32(pb); // least dts to pts delta
1284
    get_be32(pb); // greatest dts to pts delta
1285
    get_be32(pb); // pts start
1286
    get_be32(pb); // pts end
1287
1288
    return 0;
1289
}
1290
1291 c3e92a6c Baptiste Coudurier
static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1292 c4ac052b Michael Niedermayer
{
1293 70a61ed4 Michael Niedermayer
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1294 e4141433 Nicholas Tung
    MOVStreamContext *sc = st->priv_data;
1295 c4ac052b Michael Niedermayer
    unsigned int i, entries;
1296
1297
    get_byte(pb); /* version */
1298 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1299 c4ac052b Michael Niedermayer
    entries = get_be32(pb);
1300 0d8f0abf Baptiste Coudurier
1301
    dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1302
1303 c3e92a6c Baptiste Coudurier
    if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
1304 c4ac052b Michael Niedermayer
        return -1;
1305 c3e92a6c Baptiste Coudurier
    sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1306 c1da59fa Baptiste Coudurier
    if (!sc->ctts_data)
1307 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1308
    sc->ctts_count = entries;
1309 4e5ef14f Baptiste Coudurier
1310 c4ac052b Michael Niedermayer
    for(i=0; i<entries; i++) {
1311 70a61ed4 Michael Niedermayer
        int count    =get_be32(pb);
1312
        int duration =get_be32(pb);
1313
1314
        sc->ctts_data[i].count   = count;
1315
        sc->ctts_data[i].duration= duration;
1316 c4ac052b Michael Niedermayer
    }
1317
    return 0;
1318
}
1319
1320 1e77810d Baptiste Coudurier
static void mov_build_index(MOVContext *mov, AVStream *st)
1321
{
1322
    MOVStreamContext *sc = st->priv_data;
1323 bc5c918e Diego Biurrun
    int64_t current_offset;
1324 1e77810d Baptiste Coudurier
    int64_t current_dts = 0;
1325
    unsigned int stts_index = 0;
1326
    unsigned int stsc_index = 0;
1327
    unsigned int stss_index = 0;
1328 171a3531 Baptiste Coudurier
    unsigned int stps_index = 0;
1329 1e77810d Baptiste Coudurier
    unsigned int i, j;
1330
1331 baf2ffd3 Baptiste Coudurier
    /* adjust first dts according to edit list */
1332
    if (sc->time_offset) {
1333 2ac736a6 Reimar Döffinger
        int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
1334 bbe46bc4 Baptiste Coudurier
        current_dts = -rescaled;
1335 f03a081d Baptiste Coudurier
        if (sc->ctts_data && sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1336
            /* more than 16 frames delay, dts are likely wrong
1337
               this happens with files created by iMovie */
1338
            sc->wrong_dts = 1;
1339
            st->codec->has_b_frames = 1;
1340
        }
1341 baf2ffd3 Baptiste Coudurier
    }
1342
1343 d3bc61ac Baptiste Coudurier
    /* only use old uncompressed audio chunk demuxing when stts specifies it */
1344
    if (!(st->codec->codec_type == CODEC_TYPE_AUDIO &&
1345
          sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1346 1e77810d Baptiste Coudurier
        unsigned int current_sample = 0;
1347
        unsigned int stts_sample = 0;
1348 171a3531 Baptiste Coudurier
        unsigned int sample_size;
1349 1e77810d Baptiste Coudurier
        unsigned int distance = 0;
1350
        int key_off = sc->keyframes && sc->keyframes[0] == 1;
1351
1352 4b29ed39 Baptiste Coudurier
        current_dts -= sc->dts_shift;
1353
1354 1e77810d Baptiste Coudurier
        st->nb_frames = sc->sample_count;
1355
        for (i = 0; i < sc->chunk_count; i++) {
1356
            current_offset = sc->chunk_offsets[i];
1357 04e06cfa Baptiste Coudurier
            if (stsc_index + 1 < sc->stsc_count &&
1358
                i + 1 == sc->stsc_data[stsc_index + 1].first)
1359 1e77810d Baptiste Coudurier
                stsc_index++;
1360 04e06cfa Baptiste Coudurier
            for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1361 171a3531 Baptiste Coudurier
                int keyframe = 0;
1362 1e77810d Baptiste Coudurier
                if (current_sample >= sc->sample_count) {
1363
                    av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1364 f0f2218d Baptiste Coudurier
                    return;
1365 1e77810d Baptiste Coudurier
                }
1366 171a3531 Baptiste Coudurier
1367
                if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1368
                    keyframe = 1;
1369 1e77810d Baptiste Coudurier
                    if (stss_index + 1 < sc->keyframe_count)
1370
                        stss_index++;
1371 171a3531 Baptiste Coudurier
                } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1372
                    keyframe = 1;
1373
                    if (stps_index + 1 < sc->stps_count)
1374
                        stps_index++;
1375 1e77810d Baptiste Coudurier
                }
1376 171a3531 Baptiste Coudurier
                if (keyframe)
1377
                    distance = 0;
1378 1e77810d Baptiste Coudurier
                sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1379 978677a7 Baptiste Coudurier
                if(sc->pseudo_stream_id == -1 ||
1380 04e06cfa Baptiste Coudurier
                   sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1381 1e77810d Baptiste Coudurier
                    av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
1382
                                    keyframe ? AVINDEX_KEYFRAME : 0);
1383 585dac65 Baptiste Coudurier
                    dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1384
                            "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1385
                            current_offset, current_dts, sample_size, distance, keyframe);
1386
                }
1387 6c00a9de Baptiste Coudurier
1388 1e77810d Baptiste Coudurier
                current_offset += sample_size;
1389 bbe46bc4 Baptiste Coudurier
                current_dts += sc->stts_data[stts_index].duration;
1390 1e77810d Baptiste Coudurier
                distance++;
1391
                stts_sample++;
1392
                current_sample++;
1393
                if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1394
                    stts_sample = 0;
1395
                    stts_index++;
1396
                }
1397
            }
1398
        }
1399 7e69621f Baptiste Coudurier
    } else {
1400 1e77810d Baptiste Coudurier
        for (i = 0; i < sc->chunk_count; i++) {
1401 7e69621f Baptiste Coudurier
            unsigned chunk_samples;
1402
1403 1e77810d Baptiste Coudurier
            current_offset = sc->chunk_offsets[i];
1404 04e06cfa Baptiste Coudurier
            if (stsc_index + 1 < sc->stsc_count &&
1405
                i + 1 == sc->stsc_data[stsc_index + 1].first)
1406 1e77810d Baptiste Coudurier
                stsc_index++;
1407 04e06cfa Baptiste Coudurier
            chunk_samples = sc->stsc_data[stsc_index].count;
1408 7e69621f Baptiste Coudurier
1409
            if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1410
                av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1411
                return;
1412
            }
1413
1414
            while (chunk_samples > 0) {
1415
                unsigned size, samples;
1416
1417
                if (sc->samples_per_frame >= 160) { // gsm
1418
                    samples = sc->samples_per_frame;
1419
                    size = sc->bytes_per_frame;
1420
                } else {
1421
                    if (sc->samples_per_frame > 1) {
1422
                        samples = FFMIN((1024 / sc->samples_per_frame)*
1423
                                        sc->samples_per_frame, chunk_samples);
1424
                        size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1425 1e77810d Baptiste Coudurier
                    } else {
1426 7e69621f Baptiste Coudurier
                        samples = FFMIN(1024, chunk_samples);
1427
                        size = samples * sc->sample_size;
1428 1e77810d Baptiste Coudurier
                    }
1429
                }
1430 7e69621f Baptiste Coudurier
1431
                av_add_index_entry(st, current_offset, current_dts, size, 0, AVINDEX_KEYFRAME);
1432 117a9190 Baptiste Coudurier
                dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1433
                        "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1434 7e69621f Baptiste Coudurier
                        size, samples);
1435
1436
                current_offset += size;
1437 bbe46bc4 Baptiste Coudurier
                current_dts += samples;
1438 7e69621f Baptiste Coudurier
                chunk_samples -= samples;
1439 1e77810d Baptiste Coudurier
            }
1440
        }
1441
    }
1442
}
1443 bd991df2 Baptiste Coudurier
1444 c3e92a6c Baptiste Coudurier
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1445 5ca1d879 Zdenek Kabelac
{
1446
    AVStream *st;
1447
    MOVStreamContext *sc;
1448 bd991df2 Baptiste Coudurier
    int ret;
1449 5ca1d879 Zdenek Kabelac
1450
    st = av_new_stream(c->fc, c->fc->nb_streams);
1451 3efe8848 Baptiste Coudurier
    if (!st) return AVERROR(ENOMEM);
1452 9a630c25 Baptiste Coudurier
    sc = av_mallocz(sizeof(MOVStreamContext));
1453 2922cbdb Baptiste Coudurier
    if (!sc) return AVERROR(ENOMEM);
1454 5ca1d879 Zdenek Kabelac
1455
    st->priv_data = sc;
1456 05edc1a7 Baptiste Coudurier
    st->codec->codec_type = CODEC_TYPE_DATA;
1457 64d50fa5 Baptiste Coudurier
    sc->ffindex = st->index;
1458 5ca1d879 Zdenek Kabelac
1459 bd991df2 Baptiste Coudurier
    if ((ret = mov_read_default(c, pb, atom)) < 0)
1460
        return ret;
1461
1462
    /* sanity checks */
1463 6c00a9de Baptiste Coudurier
    if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1464
                            (!sc->sample_size && !sc->sample_count))) {
1465 6282c5f4 Baptiste Coudurier
        av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1466
               st->index);
1467 bd991df2 Baptiste Coudurier
        return 0;
1468
    }
1469 6c00a9de Baptiste Coudurier
1470
    if (!sc->time_scale)
1471
        sc->time_scale = c->time_scale;
1472
1473 bbe46bc4 Baptiste Coudurier
    av_set_pts_info(st, 64, 1, sc->time_scale);
1474 bd991df2 Baptiste Coudurier
1475 3f78a3a9 Baptiste Coudurier
    if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
1476 5b4f5e5d Baptiste Coudurier
        !st->codec->frame_size && sc->stts_count == 1) {
1477
        st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
1478
                                           st->codec->sample_rate, sc->time_scale);
1479
        dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
1480
    }
1481 bd991df2 Baptiste Coudurier
1482
    mov_build_index(c, st);
1483
1484
    if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1485
        if (url_fopen(&sc->pb, sc->drefs[sc->dref_id-1].path, URL_RDONLY) < 0)
1486 9e81a0ce Baptiste Coudurier
            av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening file %s: %s\n",
1487
                   st->index, sc->drefs[sc->dref_id-1].path, strerror(errno));
1488 bd991df2 Baptiste Coudurier
    } else
1489
        sc->pb = c->fc->pb;
1490
1491
    switch (st->codec->codec_id) {
1492 b250f9c6 Aurelien Jacobs
#if CONFIG_H261_DECODER
1493 bd991df2 Baptiste Coudurier
    case CODEC_ID_H261:
1494
#endif
1495 b250f9c6 Aurelien Jacobs
#if CONFIG_H263_DECODER
1496 bd991df2 Baptiste Coudurier
    case CODEC_ID_H263:
1497
#endif
1498 a0dd3c00 Baptiste Coudurier
#if CONFIG_H264_DECODER
1499
    case CODEC_ID_H264:
1500
#endif
1501 b250f9c6 Aurelien Jacobs
#if CONFIG_MPEG4_DECODER
1502 bd991df2 Baptiste Coudurier
    case CODEC_ID_MPEG4:
1503
#endif
1504 6c00a9de Baptiste Coudurier
        st->codec->width = 0; /* let decoder init width/height */
1505 bd991df2 Baptiste Coudurier
        st->codec->height= 0;
1506
        break;
1507
    }
1508 f9900374 Baptiste Coudurier
1509
    /* Do not need those anymore. */
1510
    av_freep(&sc->chunk_offsets);
1511 04e06cfa Baptiste Coudurier
    av_freep(&sc->stsc_data);
1512 f9900374 Baptiste Coudurier
    av_freep(&sc->sample_sizes);
1513
    av_freep(&sc->keyframes);
1514
    av_freep(&sc->stts_data);
1515 171a3531 Baptiste Coudurier
    av_freep(&sc->stps_data);
1516 f9900374 Baptiste Coudurier
1517 bd991df2 Baptiste Coudurier
    return 0;
1518 5ca1d879 Zdenek Kabelac
}
1519
1520 c3e92a6c Baptiste Coudurier
static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1521 51c15201 Baptiste Coudurier
{
1522
    int ret;
1523
    c->itunes_metadata = 1;
1524
    ret = mov_read_default(c, pb, atom);
1525
    c->itunes_metadata = 0;
1526
    return ret;
1527
}
1528
1529 c3e92a6c Baptiste Coudurier
static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1530 51c15201 Baptiste Coudurier
{
1531 df8843c6 Baptiste Coudurier
    while (atom.size > 8) {
1532
        uint32_t tag = get_le32(pb);
1533
        atom.size -= 4;
1534
        if (tag == MKTAG('h','d','l','r')) {
1535
            url_fseek(pb, -8, SEEK_CUR);
1536
            atom.size += 8;
1537
            return mov_read_default(c, pb, atom);
1538
        }
1539
    }
1540
    return 0;
1541 51c15201 Baptiste Coudurier
}
1542
1543 c3e92a6c Baptiste Coudurier
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1544 5ca1d879 Zdenek Kabelac
{
1545 ec072669 John Schmiederer
    int i;
1546
    int width;
1547
    int height;
1548
    int64_t disp_transform[2];
1549
    int display_matrix[3][2];
1550 f444b977 Baptiste Coudurier
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1551 6cdbff63 David Conrad
    MOVStreamContext *sc = st->priv_data;
1552 f444b977 Baptiste Coudurier
    int version = get_byte(pb);
1553 5ca1d879 Zdenek Kabelac
1554 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1555 5ca1d879 Zdenek Kabelac
    /*
1556
    MOV_TRACK_ENABLED 0x0001
1557
    MOV_TRACK_IN_MOVIE 0x0002
1558
    MOV_TRACK_IN_PREVIEW 0x0004
1559
    MOV_TRACK_IN_POSTER 0x0008
1560
    */
1561
1562 1175561e Baptiste Coudurier
    if (version == 1) {
1563
        get_be64(pb);
1564
        get_be64(pb);
1565
    } else {
1566
        get_be32(pb); /* creation time */
1567
        get_be32(pb); /* modification time */
1568
    }
1569 5ca1d879 Zdenek Kabelac
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1570
    get_be32(pb); /* reserved */
1571 fcdd622c Baptiste Coudurier
1572 117a9190 Baptiste Coudurier
    /* highlevel (considering edits) duration in movie timebase */
1573
    (version == 1) ? get_be64(pb) : get_be32(pb);
1574 5ca1d879 Zdenek Kabelac
    get_be32(pb); /* reserved */
1575
    get_be32(pb); /* reserved */
1576
1577
    get_be16(pb); /* layer */
1578
    get_be16(pb); /* alternate group */
1579
    get_be16(pb); /* volume */
1580
    get_be16(pb); /* reserved */
1581
1582 ec072669 John Schmiederer
    //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
1583
    // they're kept in fixed point format through all calculations
1584
    // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
1585
    for (i = 0; i < 3; i++) {
1586
        display_matrix[i][0] = get_be32(pb);   // 16.16 fixed point
1587
        display_matrix[i][1] = get_be32(pb);   // 16.16 fixed point
1588
        get_be32(pb);           // 2.30 fixed point (not used)
1589
    }
1590 5ca1d879 Zdenek Kabelac
1591 ec072669 John Schmiederer
    width = get_be32(pb);       // 16.16 fixed point track width
1592
    height = get_be32(pb);      // 16.16 fixed point track height
1593 6cdbff63 David Conrad
    sc->width = width >> 16;
1594
    sc->height = height >> 16;
1595 ec072669 John Schmiederer
1596
    //transform the display width/height according to the matrix
1597
    // skip this if the display matrix is the default identity matrix
1598
    // to keep the same scale, use [width height 1<<16]
1599
    if (width && height &&
1600
        (display_matrix[0][0] != 65536 || display_matrix[0][1]           ||
1601
        display_matrix[1][0]           || display_matrix[1][1] != 65536  ||
1602
        display_matrix[2][0]           || display_matrix[2][1])) {
1603
        for (i = 0; i < 2; i++)
1604
            disp_transform[i] =
1605
                (int64_t)  width  * display_matrix[0][i] +
1606
                (int64_t)  height * display_matrix[1][i] +
1607
                ((int64_t) display_matrix[2][i] << 16);
1608
1609
        //sample aspect ratio is new width/height divided by old width/height
1610 59729451 Aurelien Jacobs
        st->sample_aspect_ratio = av_d2q(
1611 ec072669 John Schmiederer
            ((double) disp_transform[0] * height) /
1612
            ((double) disp_transform[1] * width), INT_MAX);
1613
    }
1614 5ca1d879 Zdenek Kabelac
    return 0;
1615
}
1616
1617 c3e92a6c Baptiste Coudurier
static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1618 61aedb0f Baptiste Coudurier
{
1619
    MOVFragment *frag = &c->fragment;
1620
    MOVTrackExt *trex = NULL;
1621
    int flags, track_id, i;
1622
1623
    get_byte(pb); /* version */
1624
    flags = get_be24(pb);
1625
1626
    track_id = get_be32(pb);
1627 63581eb1 Alex Converse
    if (!track_id)
1628 61aedb0f Baptiste Coudurier
        return -1;
1629
    frag->track_id = track_id;
1630
    for (i = 0; i < c->trex_count; i++)
1631
        if (c->trex_data[i].track_id == frag->track_id) {
1632
            trex = &c->trex_data[i];
1633
            break;
1634
        }
1635
    if (!trex) {
1636
        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
1637
        return -1;
1638
    }
1639
1640
    if (flags & 0x01) frag->base_data_offset = get_be64(pb);
1641
    else              frag->base_data_offset = frag->moof_offset;
1642
    if (flags & 0x02) frag->stsd_id          = get_be32(pb);
1643
    else              frag->stsd_id          = trex->stsd_id;
1644
1645
    frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
1646
    frag->size     = flags & 0x10 ? get_be32(pb) : trex->size;
1647
    frag->flags    = flags & 0x20 ? get_be32(pb) : trex->flags;
1648
    dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
1649
    return 0;
1650
}
1651
1652 c3e92a6c Baptiste Coudurier
static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1653 61aedb0f Baptiste Coudurier
{
1654
    MOVTrackExt *trex;
1655
1656
    if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
1657
        return -1;
1658 0d8f0abf Baptiste Coudurier
    trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
1659
    if (!trex)
1660 61aedb0f Baptiste Coudurier
        return AVERROR(ENOMEM);
1661 0d8f0abf Baptiste Coudurier
    c->trex_data = trex;
1662 61aedb0f Baptiste Coudurier
    trex = &c->trex_data[c->trex_count++];
1663
    get_byte(pb); /* version */
1664
    get_be24(pb); /* flags */
1665
    trex->track_id = get_be32(pb);
1666
    trex->stsd_id  = get_be32(pb);
1667
    trex->duration = get_be32(pb);
1668
    trex->size     = get_be32(pb);
1669
    trex->flags    = get_be32(pb);
1670
    return 0;
1671
}
1672
1673 c3e92a6c Baptiste Coudurier
static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1674 61aedb0f Baptiste Coudurier
{
1675
    MOVFragment *frag = &c->fragment;
1676 63581eb1 Alex Converse
    AVStream *st = NULL;
1677 44e43aab Baptiste Coudurier
    MOVStreamContext *sc;
1678 61aedb0f Baptiste Coudurier
    uint64_t offset;
1679
    int64_t dts;
1680
    int data_offset = 0;
1681
    unsigned entries, first_sample_flags = frag->flags;
1682
    int flags, distance, i;
1683
1684 63581eb1 Alex Converse
    for (i = 0; i < c->fc->nb_streams; i++) {
1685
        if (c->fc->streams[i]->id == frag->track_id) {
1686
            st = c->fc->streams[i];
1687
            break;
1688
        }
1689
    }
1690
    if (!st) {
1691
        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
1692 44e43aab Baptiste Coudurier
        return -1;
1693 63581eb1 Alex Converse
    }
1694 44e43aab Baptiste Coudurier
    sc = st->priv_data;
1695 61aedb0f Baptiste Coudurier
    if (sc->pseudo_stream_id+1 != frag->stsd_id)
1696
        return 0;
1697
    get_byte(pb); /* version */
1698
    flags = get_be24(pb);
1699
    entries = get_be32(pb);
1700
    dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
1701
    if (flags & 0x001) data_offset        = get_be32(pb);
1702
    if (flags & 0x004) first_sample_flags = get_be32(pb);
1703
    if (flags & 0x800) {
1704 0d8f0abf Baptiste Coudurier
        MOVStts *ctts_data;
1705 61aedb0f Baptiste Coudurier
        if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
1706
            return -1;
1707 0d8f0abf Baptiste Coudurier
        ctts_data = av_realloc(sc->ctts_data,
1708
                               (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
1709
        if (!ctts_data)
1710 61aedb0f Baptiste Coudurier
            return AVERROR(ENOMEM);
1711 0d8f0abf Baptiste Coudurier
        sc->ctts_data = ctts_data;
1712 61aedb0f Baptiste Coudurier
    }
1713
    dts = st->duration;
1714
    offset = frag->base_data_offset + data_offset;
1715
    distance = 0;
1716
    dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
1717
    for (i = 0; i < entries; i++) {
1718
        unsigned sample_size = frag->size;
1719
        int sample_flags = i ? frag->flags : first_sample_flags;
1720
        unsigned sample_duration = frag->duration;
1721
        int keyframe;
1722
1723
        if (flags & 0x100) sample_duration = get_be32(pb);
1724
        if (flags & 0x200) sample_size     = get_be32(pb);
1725
        if (flags & 0x400) sample_flags    = get_be32(pb);
1726
        if (flags & 0x800) {
1727
            sc->ctts_data[sc->ctts_count].count = 1;
1728
            sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
1729
            sc->ctts_count++;
1730
        }
1731
        if ((keyframe = st->codec->codec_type == CODEC_TYPE_AUDIO ||
1732
             (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
1733
            distance = 0;
1734
        av_add_index_entry(st, offset, dts, sample_size, distance,
1735
                           keyframe ? AVINDEX_KEYFRAME : 0);
1736
        dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1737
                "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
1738
                offset, dts, sample_size, distance, keyframe);
1739
        distance++;
1740 bbe46bc4 Baptiste Coudurier
        dts += sample_duration;
1741 61aedb0f Baptiste Coudurier
        offset += sample_size;
1742
    }
1743
    frag->moof_offset = offset;
1744
    st->duration = dts;
1745
    return 0;
1746
}
1747
1748 5ca1d879 Zdenek Kabelac
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1749
/* like the files created with Adobe Premiere 5.0, for samples see */
1750
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1751 c3e92a6c Baptiste Coudurier
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1752 5ca1d879 Zdenek Kabelac
{
1753
    int err;
1754
1755
    if (atom.size < 8)
1756
        return 0; /* continue */
1757
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1758
        url_fskip(pb, atom.size - 4);
1759
        return 0;
1760
    }
1761
    atom.type = get_le32(pb);
1762
    atom.offset += 8;
1763
    atom.size -= 8;
1764 1c126b4f Baptiste Coudurier
    if (atom.type != MKTAG('m','d','a','t')) {
1765 5ca1d879 Zdenek Kabelac
        url_fskip(pb, atom.size);
1766
        return 0;
1767
    }
1768
    err = mov_read_mdat(c, pb, atom);
1769
    return err;
1770
}
1771
1772 c3e92a6c Baptiste Coudurier
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1773 0147f198 François Revol
{
1774 b250f9c6 Aurelien Jacobs
#if CONFIG_ZLIB
1775 0147f198 François Revol
    ByteIOContext ctx;
1776 b6a17df4 Zdenek Kabelac
    uint8_t *cmov_data;
1777
    uint8_t *moov_data; /* uncompressed data */
1778 0147f198 François Revol
    long cmov_len, moov_len;
1779 6f04eb1e Albert Astals Cid
    int ret = -1;
1780 b6a17df4 Zdenek Kabelac
1781 0147f198 François Revol
    get_be32(pb); /* dcom atom */
1782 1c126b4f Baptiste Coudurier
    if (get_le32(pb) != MKTAG('d','c','o','m'))
1783 0147f198 François Revol
        return -1;
1784 1c126b4f Baptiste Coudurier
    if (get_le32(pb) != MKTAG('z','l','i','b')) {
1785 f3592353 Benoit Fouet
        av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
1786 0147f198 François Revol
        return -1;
1787
    }
1788
    get_be32(pb); /* cmvd atom */
1789 1c126b4f Baptiste Coudurier
    if (get_le32(pb) != MKTAG('c','m','v','d'))
1790 0147f198 François Revol
        return -1;
1791
    moov_len = get_be32(pb); /* uncompressed size */
1792 5ca1d879 Zdenek Kabelac
    cmov_len = atom.size - 6 * 4;
1793 5cd62665 Zdenek Kabelac
1794 9a630c25 Baptiste Coudurier
    cmov_data = av_malloc(cmov_len);
1795 0147f198 François Revol
    if (!cmov_data)
1796 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1797 9a630c25 Baptiste Coudurier
    moov_data = av_malloc(moov_len);
1798 0147f198 François Revol
    if (!moov_data) {
1799
        av_free(cmov_data);
1800 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1801 0147f198 François Revol
    }
1802
    get_buffer(pb, cmov_data, cmov_len);
1803 b6a17df4 Zdenek Kabelac
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1804 6f04eb1e Albert Astals Cid
        goto free_and_return;
1805 942f3bb5 Michael Niedermayer
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
1806 6f04eb1e Albert Astals Cid
        goto free_and_return;
1807 1c126b4f Baptiste Coudurier
    atom.type = MKTAG('m','o','o','v');
1808 5ca1d879 Zdenek Kabelac
    atom.offset = 0;
1809
    atom.size = moov_len;
1810 9ed83b0a Zdenek Kabelac
#ifdef DEBUG
1811 dbb4f00a Michael Niedermayer
//    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1812 9ed83b0a Zdenek Kabelac
#endif
1813 5ca1d879 Zdenek Kabelac
    ret = mov_read_default(c, &ctx, atom);
1814 6f04eb1e Albert Astals Cid
free_and_return:
1815 0147f198 François Revol
    av_free(moov_data);
1816
    av_free(cmov_data);
1817
    return ret;
1818 d966b2f0 Baptiste Coudurier
#else
1819
    av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
1820
    return -1;
1821 0147f198 François Revol
#endif
1822 d966b2f0 Baptiste Coudurier
}
1823 0147f198 François Revol
1824 baf25c9d Gael Chardon
/* edit list atom */
1825 c3e92a6c Baptiste Coudurier
static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1826 baf25c9d Gael Chardon
{
1827 7c622eed Baptiste Coudurier
    MOVStreamContext *sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
1828 e0977c80 Baptiste Coudurier
    int i, edit_count;
1829
1830
    get_byte(pb); /* version */
1831 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1832 1975c52c Baptiste Coudurier
    edit_count = get_be32(pb); /* entries */
1833 e0977c80 Baptiste Coudurier
1834
    for(i=0; i<edit_count; i++){
1835 d435e520 Baptiste Coudurier
        int time;
1836 2ac736a6 Reimar Döffinger
        int duration = get_be32(pb); /* Track duration */
1837 d435e520 Baptiste Coudurier
        time = get_be32(pb); /* Media time */
1838 e0977c80 Baptiste Coudurier
        get_be32(pb); /* Media rate */
1839 2ac736a6 Reimar Döffinger
        if (i == 0 && time >= -1) {
1840
            sc->time_offset = time != -1 ? time : -duration;
1841 a5929abe Baptiste Coudurier
        }
1842 e0977c80 Baptiste Coudurier
    }
1843 baf2ffd3 Baptiste Coudurier
1844
    if(edit_count > 1)
1845
        av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
1846
               "a/v desync might occur, patch welcome\n");
1847
1848 4c125b8f Baptiste Coudurier
    dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
1849 e0977c80 Baptiste Coudurier
    return 0;
1850 baf25c9d Gael Chardon
}
1851
1852 6cea494e Zdenek Kabelac
static const MOVParseTableEntry mov_default_parse_table[] = {
1853 d4fdba0d Baptiste Coudurier
{ MKTAG('a','v','s','s'), mov_read_extradata },
1854 1c126b4f Baptiste Coudurier
{ MKTAG('c','o','6','4'), mov_read_stco },
1855 4b29ed39 Baptiste Coudurier
{ MKTAG('c','s','l','g'), mov_read_cslg },
1856 1c126b4f Baptiste Coudurier
{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
1857
{ MKTAG('d','i','n','f'), mov_read_default },
1858
{ MKTAG('d','r','e','f'), mov_read_dref },
1859
{ MKTAG('e','d','t','s'), mov_read_default },
1860
{ MKTAG('e','l','s','t'), mov_read_elst },
1861
{ MKTAG('e','n','d','a'), mov_read_enda },
1862
{ MKTAG('f','i','e','l'), mov_read_extradata },
1863
{ MKTAG('f','t','y','p'), mov_read_ftyp },
1864
{ MKTAG('g','l','b','l'), mov_read_glbl },
1865
{ MKTAG('h','d','l','r'), mov_read_hdlr },
1866 51c15201 Baptiste Coudurier
{ MKTAG('i','l','s','t'), mov_read_ilst },
1867 1c126b4f Baptiste Coudurier
{ MKTAG('j','p','2','h'), mov_read_extradata },
1868
{ MKTAG('m','d','a','t'), mov_read_mdat },
1869
{ MKTAG('m','d','h','d'), mov_read_mdhd },
1870
{ MKTAG('m','d','i','a'), mov_read_default },
1871 51c15201 Baptiste Coudurier
{ MKTAG('m','e','t','a'), mov_read_meta },
1872 1c126b4f Baptiste Coudurier
{ MKTAG('m','i','n','f'), mov_read_default },
1873
{ MKTAG('m','o','o','f'), mov_read_moof },
1874
{ MKTAG('m','o','o','v'), mov_read_moov },
1875
{ MKTAG('m','v','e','x'), mov_read_default },
1876
{ MKTAG('m','v','h','d'), mov_read_mvhd },
1877
{ MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
1878
{ MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
1879
{ MKTAG('a','v','c','C'), mov_read_glbl },
1880 6da54074 Baptiste Coudurier
{ MKTAG('p','a','s','p'), mov_read_pasp },
1881 1c126b4f Baptiste Coudurier
{ MKTAG('s','t','b','l'), mov_read_default },
1882
{ MKTAG('s','t','c','o'), mov_read_stco },
1883 171a3531 Baptiste Coudurier
{ MKTAG('s','t','p','s'), mov_read_stps },
1884 1c126b4f Baptiste Coudurier
{ MKTAG('s','t','s','c'), mov_read_stsc },
1885
{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
1886
{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
1887
{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
1888
{ MKTAG('s','t','t','s'), mov_read_stts },
1889 bd27eed6 Alex Converse
{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
1890 1c126b4f Baptiste Coudurier
{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
1891
{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
1892
{ MKTAG('t','r','a','k'), mov_read_trak },
1893
{ MKTAG('t','r','a','f'), mov_read_default },
1894
{ MKTAG('t','r','e','x'), mov_read_trex },
1895
{ MKTAG('t','r','u','n'), mov_read_trun },
1896 86b0affd Baptiste Coudurier
{ MKTAG('u','d','t','a'), mov_read_default },
1897 1c126b4f Baptiste Coudurier
{ MKTAG('w','a','v','e'), mov_read_wave },
1898
{ MKTAG('e','s','d','s'), mov_read_esds },
1899
{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
1900
{ MKTAG('c','m','o','v'), mov_read_cmov },
1901 bcfe2ba0 Baptiste Coudurier
{ 0, NULL }
1902 6cea494e Zdenek Kabelac
};
1903
1904 c9a65ca8 Fabrice Bellard
static int mov_probe(AVProbeData *p)
1905
{
1906 0e7eed09 Fabrice Bellard
    unsigned int offset;
1907
    uint32_t tag;
1908 2497479f François Revol
    int score = 0;
1909 3ffe3793 François Revol
1910 c9a65ca8 Fabrice Bellard
    /* check file header */
1911 0e7eed09 Fabrice Bellard
    offset = 0;
1912
    for(;;) {
1913
        /* ignore invalid offset */
1914
        if ((offset + 8) > (unsigned int)p->buf_size)
1915 2497479f François Revol
            return score;
1916 fead30d4 Alex Beregszaszi
        tag = AV_RL32(p->buf + offset + 4);
1917 0e7eed09 Fabrice Bellard
        switch(tag) {
1918 2497479f François Revol
        /* check for obvious tags */
1919 1c126b4f Baptiste Coudurier
        case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
1920
        case MKTAG('m','o','o','v'):
1921
        case MKTAG('m','d','a','t'):
1922
        case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
1923
        case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
1924 40e7aaa3 Baptiste Coudurier
        case MKTAG('f','t','y','p'):
1925 3ffe3793 François Revol
            return AVPROBE_SCORE_MAX;
1926 2497479f François Revol
        /* those are more common words, so rate then a bit less */
1927 1c126b4f Baptiste Coudurier
        case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
1928
        case MKTAG('w','i','d','e'):
1929
        case MKTAG('f','r','e','e'):
1930
        case MKTAG('j','u','n','k'):
1931
        case MKTAG('p','i','c','t'):
1932 2497479f François Revol
            return AVPROBE_SCORE_MAX - 5;
1933 5469b788 Baptiste Coudurier
        case MKTAG(0x82,0x82,0x7f,0x7d):
1934 1c126b4f Baptiste Coudurier
        case MKTAG('s','k','i','p'):
1935
        case MKTAG('u','u','i','d'):
1936
        case MKTAG('p','r','f','l'):
1937 fead30d4 Alex Beregszaszi
            offset = AV_RB32(p->buf+offset) + offset;
1938 2497479f François Revol
            /* if we only find those cause probedata is too small at least rate them */
1939
            score = AVPROBE_SCORE_MAX - 50;
1940 0e7eed09 Fabrice Bellard
            break;
1941
        default:
1942
            /* unrecognized tag */
1943 2497479f François Revol
            return score;
1944 0e7eed09 Fabrice Bellard
        }
1945 3ffe3793 François Revol
    }
1946 2497479f François Revol
    return score;
1947 c9a65ca8 Fabrice Bellard
}
1948
1949 a266644f Zdenek Kabelac
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1950 6cea494e Zdenek Kabelac
{
1951 e4141433 Nicholas Tung
    MOVContext *mov = s->priv_data;
1952 899681cd Björn Axelsson
    ByteIOContext *pb = s->pb;
1953 f9900374 Baptiste Coudurier
    int err;
1954 c3e92a6c Baptiste Coudurier
    MOVAtom atom = { 0, 0, 0 };
1955 6cea494e Zdenek Kabelac
1956
    mov->fc = s;
1957 117a9190 Baptiste Coudurier
    /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1958
    if(!url_is_streamed(pb))
1959 bb270c08 Diego Biurrun
        atom.size = url_fsize(pb);
1960 6cea494e Zdenek Kabelac
    else
1961 fa22ca22 Baptiste Coudurier
        atom.size = INT64_MAX;
1962 6cea494e Zdenek Kabelac
1963
    /* check MOV header */
1964 612b5cbb Baptiste Coudurier
    if ((err = mov_read_default(mov, pb, atom)) < 0) {
1965
        av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
1966
        return err;
1967
    }
1968
    if (!mov->found_moov) {
1969
        av_log(s, AV_LOG_ERROR, "moov atom not found\n");
1970 bb270c08 Diego Biurrun
        return -1;
1971 6cea494e Zdenek Kabelac
    }
1972 0265fe81 Baptiste Coudurier
    dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
1973 4e5ef14f Baptiste Coudurier
1974 6cea494e Zdenek Kabelac
    return 0;
1975
}
1976
1977 a266644f Zdenek Kabelac
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1978 6cea494e Zdenek Kabelac
{
1979 b72708f8 Baptiste Coudurier
    MOVContext *mov = s->priv_data;
1980
    MOVStreamContext *sc = 0;
1981
    AVIndexEntry *sample = 0;
1982 86d8602f Michael Niedermayer
    int64_t best_dts = INT64_MAX;
1983 bc64cb96 Baptiste Coudurier
    int i, ret;
1984 433aeb62 Baptiste Coudurier
 retry:
1985 11f16b66 Baptiste Coudurier
    for (i = 0; i < s->nb_streams; i++) {
1986 7c622eed Baptiste Coudurier
        AVStream *st = s->streams[i];
1987
        MOVStreamContext *msc = st->priv_data;
1988 f0f2218d Baptiste Coudurier
        if (st->discard != AVDISCARD_ALL && msc->pb && msc->current_sample < st->nb_index_entries) {
1989 7c622eed Baptiste Coudurier
            AVIndexEntry *current_sample = &st->index_entries[msc->current_sample];
1990 bbe46bc4 Baptiste Coudurier
            int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
1991 1c02d96f Baptiste Coudurier
            dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
1992 687f35f3 Baptiste Coudurier
            if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
1993
                (!url_is_streamed(s->pb) &&
1994 221e21b7 Baptiste Coudurier
                 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
1995 687f35f3 Baptiste Coudurier
                 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
1996 221e21b7 Baptiste Coudurier
                  (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
1997 b72708f8 Baptiste Coudurier
                sample = current_sample;
1998
                best_dts = dts;
1999
                sc = msc;
2000 86d8602f Michael Niedermayer
            }
2001 6cea494e Zdenek Kabelac
        }
2002
    }
2003 433aeb62 Baptiste Coudurier
    if (!sample) {
2004
        mov->found_mdat = 0;
2005
        if (!url_is_streamed(s->pb) ||
2006 c3e92a6c Baptiste Coudurier
            mov_read_default(mov, s->pb, (MOVAtom){ 0, 0, INT64_MAX }) < 0 ||
2007 433aeb62 Baptiste Coudurier
            url_feof(s->pb))
2008 350f2c2c Baptiste Coudurier
            return AVERROR_EOF;
2009 433aeb62 Baptiste Coudurier
        dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
2010
        goto retry;
2011
    }
2012 b72708f8 Baptiste Coudurier
    /* must be done just before reading, to avoid infinite loop on sample */
2013
    sc->current_sample++;
2014 221e21b7 Baptiste Coudurier
    if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2015 29c90869 Baptiste Coudurier
        av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2016
               sc->ffindex, sample->pos);
2017 bb270c08 Diego Biurrun
        return -1;
2018 6cea494e Zdenek Kabelac
    }
2019 bc64cb96 Baptiste Coudurier
    ret = av_get_packet(sc->pb, pkt, sample->size);
2020
    if (ret < 0)
2021
        return ret;
2022 b250f9c6 Aurelien Jacobs
#if CONFIG_DV_DEMUXER
2023 56ea717b Baptiste Coudurier
    if (mov->dv_demux && sc->dv_audio_container) {
2024
        dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2025
        av_free(pkt->data);
2026 300aa2b0 Baptiste Coudurier
        pkt->size = 0;
2027
        if (dv_get_packet(mov->dv_demux, pkt) < 0)
2028
            return -1;
2029 56ea717b Baptiste Coudurier
    }
2030 312954f0 Baptiste Coudurier
#endif
2031 b72708f8 Baptiste Coudurier
    pkt->stream_index = sc->ffindex;
2032
    pkt->dts = sample->timestamp;
2033
    if (sc->ctts_data) {
2034 bbe46bc4 Baptiste Coudurier
        pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2035 b72708f8 Baptiste Coudurier
        /* update ctts context */
2036 a234e38d Baptiste Coudurier
        sc->ctts_sample++;
2037
        if (sc->ctts_index < sc->ctts_count &&
2038
            sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2039
            sc->ctts_index++;
2040
            sc->ctts_sample = 0;
2041 b565ea09 Baptiste Coudurier
        }
2042 0c5f76f7 Baptiste Coudurier
        if (sc->wrong_dts)
2043
            pkt->dts = AV_NOPTS_VALUE;
2044 b72708f8 Baptiste Coudurier
    } else {
2045 e8430214 Henrik Gulbrandsen
        AVStream *st = s->streams[sc->ffindex];
2046 f0f2218d Baptiste Coudurier
        int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2047 e8430214 Henrik Gulbrandsen
            st->index_entries[sc->current_sample].timestamp : st->duration;
2048
        pkt->duration = next_dts - pkt->dts;
2049 b72708f8 Baptiste Coudurier
        pkt->pts = pkt->dts;
2050 b565ea09 Baptiste Coudurier
    }
2051 b72708f8 Baptiste Coudurier
    pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
2052
    pkt->pos = sample->pos;
2053 29c90869 Baptiste Coudurier
    dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2054
            pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2055 b72708f8 Baptiste Coudurier
    return 0;
2056
}
2057 3ffe3793 François Revol
2058 b72708f8 Baptiste Coudurier
static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
2059
{
2060
    MOVStreamContext *sc = st->priv_data;
2061
    int sample, time_sample;
2062
    int i;
2063 115329f1 Diego Biurrun
2064 b72708f8 Baptiste Coudurier
    sample = av_index_search_timestamp(st, timestamp, flags);
2065 318c5e05 Michel Bardiaux
    dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2066 b72708f8 Baptiste Coudurier
    if (sample < 0) /* not sure what to do */
2067
        return -1;
2068
    sc->current_sample = sample;
2069 1c02d96f Baptiste Coudurier
    dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
2070 b72708f8 Baptiste Coudurier
    /* adjust ctts index */
2071
    if (sc->ctts_data) {
2072
        time_sample = 0;
2073
        for (i = 0; i < sc->ctts_count; i++) {
2074 54a5c719 Baptiste Coudurier
            int next = time_sample + sc->ctts_data[i].count;
2075
            if (next > sc->current_sample) {
2076 a234e38d Baptiste Coudurier
                sc->ctts_index = i;
2077
                sc->ctts_sample = sc->current_sample - time_sample;
2078 b72708f8 Baptiste Coudurier
                break;
2079 115329f1 Diego Biurrun
            }
2080 54a5c719 Baptiste Coudurier
            time_sample = next;
2081 247d56f5 Brian Becker
        }
2082
    }
2083 b72708f8 Baptiste Coudurier
    return sample;
2084 6cea494e Zdenek Kabelac
}
2085
2086 961e0ccd Michael Niedermayer
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2087 baf25c9d Gael Chardon
{
2088 b72708f8 Baptiste Coudurier
    AVStream *st;
2089
    int64_t seek_timestamp, timestamp;
2090
    int sample;
2091
    int i;
2092 baf25c9d Gael Chardon
2093 b72708f8 Baptiste Coudurier
    if (stream_index >= s->nb_streams)
2094 baf25c9d Gael Chardon
        return -1;
2095 8dc81a45 Baptiste Coudurier
    if (sample_time < 0)
2096
        sample_time = 0;
2097 baf25c9d Gael Chardon
2098 b72708f8 Baptiste Coudurier
    st = s->streams[stream_index];
2099
    sample = mov_seek_stream(st, sample_time, flags);
2100
    if (sample < 0)
2101 baf25c9d Gael Chardon
        return -1;
2102
2103 b72708f8 Baptiste Coudurier
    /* adjust seek timestamp to found sample timestamp */
2104
    seek_timestamp = st->index_entries[sample].timestamp;
2105 baf25c9d Gael Chardon
2106 b72708f8 Baptiste Coudurier
    for (i = 0; i < s->nb_streams; i++) {
2107
        st = s->streams[i];
2108
        if (stream_index == i || st->discard == AVDISCARD_ALL)
2109
            continue;
2110 baf25c9d Gael Chardon
2111 b72708f8 Baptiste Coudurier
        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2112
        mov_seek_stream(st, timestamp, flags);
2113 115329f1 Diego Biurrun
    }
2114 baf25c9d Gael Chardon
    return 0;
2115
}
2116
2117 a266644f Zdenek Kabelac
static int mov_read_close(AVFormatContext *s)
2118 6cea494e Zdenek Kabelac
{
2119 e4141433 Nicholas Tung
    MOVContext *mov = s->priv_data;
2120 6c00a9de Baptiste Coudurier
    int i, j;
2121
2122
    for (i = 0; i < s->nb_streams; i++) {
2123 e49da827 Baptiste Coudurier
        AVStream *st = s->streams[i];
2124
        MOVStreamContext *sc = st->priv_data;
2125 6c00a9de Baptiste Coudurier
2126 7c622eed Baptiste Coudurier
        av_freep(&sc->ctts_data);
2127 6c00a9de Baptiste Coudurier
        for (j = 0; j < sc->drefs_count; j++)
2128 221e21b7 Baptiste Coudurier
            av_freep(&sc->drefs[j].path);
2129
        av_freep(&sc->drefs);
2130
        if (sc->pb && sc->pb != s->pb)
2131
            url_fclose(sc->pb);
2132 e49da827 Baptiste Coudurier
2133
        av_freep(&st->codec->palctrl);
2134 4440b118 Baptiste Coudurier
    }
2135 6c00a9de Baptiste Coudurier
2136
    if (mov->dv_demux) {
2137
        for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
2138 b60c0454 Baptiste Coudurier
            av_freep(&mov->dv_fctx->streams[i]->codec);
2139
            av_freep(&mov->dv_fctx->streams[i]);
2140
        }
2141
        av_freep(&mov->dv_fctx);
2142
        av_freep(&mov->dv_demux);
2143
    }
2144 6c00a9de Baptiste Coudurier
2145 61aedb0f Baptiste Coudurier
    av_freep(&mov->trex_data);
2146 6c00a9de Baptiste Coudurier
2147 6cea494e Zdenek Kabelac
    return 0;
2148
}
2149
2150 ff70e601 Måns Rullgård
AVInputFormat mov_demuxer = {
2151 fc5188f3 Baptiste Coudurier
    "mov,mp4,m4a,3gp,3g2,mj2",
2152 bde15e74 Stefano Sabatini
    NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2153 c9a65ca8 Fabrice Bellard
    sizeof(MOVContext),
2154
    mov_probe,
2155 6cea494e Zdenek Kabelac
    mov_read_header,
2156
    mov_read_packet,
2157
    mov_read_close,
2158 baf25c9d Gael Chardon
    mov_read_seek,
2159 6cea494e Zdenek Kabelac
};