Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 0c468f56

History | View | Annotate | Download (85.5 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 9106a698 Stefano Sabatini
#include "libavcodec/get_bits.h"
35 6cea494e Zdenek Kabelac
36 b250f9c6 Aurelien Jacobs
#if CONFIG_ZLIB
37 0147f198 François Revol
#include <zlib.h>
38
#endif
39
40 6cea494e Zdenek Kabelac
/*
41
 * First version by Francois Revol revol@free.fr
42 115329f1 Diego Biurrun
 * Seek function by Gael Chardon gael.dev@4now.net
43 5ca1d879 Zdenek Kabelac
 *
44 6cea494e Zdenek Kabelac
 * Features and limitations:
45 5ca1d879 Zdenek Kabelac
 * - reads most of the QT files I have (at least the structure),
46 6cea494e Zdenek Kabelac
 *   Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
47
 * - the code is quite ugly... maybe I won't do it recursive next time :-)
48 5ca1d879 Zdenek Kabelac
 *
49 6cea494e Zdenek Kabelac
 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
50
 * when coding this :) (it's a writer anyway)
51 5ca1d879 Zdenek Kabelac
 *
52 6cea494e Zdenek Kabelac
 * Reference documents:
53
 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
54
 * Apple:
55 baf25c9d Gael Chardon
 *  http://developer.apple.com/documentation/QuickTime/QTFF/
56 15c8dbe7 Sebastien Bechet
 *  http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
57 6cea494e Zdenek Kabelac
 * QuickTime is a trademark of Apple (AFAIK :))
58
 */
59
60 b595afaa Mike Melanson
#include "qtpalette.h"
61
62 baf25c9d Gael Chardon
63 cd7352d5 Michael Niedermayer
#undef NDEBUG
64
#include <assert.h>
65
66 6cea494e Zdenek Kabelac
/* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
67
68
/* those functions parse an atom */
69
/* return code:
70 e3c4740f Baptiste Coudurier
  0: continue to parse next atom
71 d9526386 Diego Biurrun
 <0: error occurred, exit
72 e3c4740f Baptiste Coudurier
*/
73 6cea494e Zdenek Kabelac
/* links atom IDs to parse functions */
74
typedef struct MOVParseTableEntry {
75 0c1a9eda Zdenek Kabelac
    uint32_t type;
76 c3e92a6c Baptiste Coudurier
    int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOVAtom atom);
77 6cea494e Zdenek Kabelac
} MOVParseTableEntry;
78
79 73d07c27 Baptiste Coudurier
static const MOVParseTableEntry mov_default_parse_table[];
80
81 c6026e43 Baptiste Coudurier
static int mov_metadata_trkn(MOVContext *c, ByteIOContext *pb, unsigned len)
82
{
83
    char buf[16];
84
85
    get_be16(pb); // unknown
86
    snprintf(buf, sizeof(buf), "%d", get_be16(pb));
87 2ef6c124 Stefano Sabatini
    av_metadata_set2(&c->fc->metadata, "track", buf, 0);
88 c6026e43 Baptiste Coudurier
89
    get_be16(pb); // total tracks
90
91
    return 0;
92
}
93
94 08a186c6 Baptiste Coudurier
static const uint32_t mac_to_unicode[128] = {
95
    0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
96
    0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
97
    0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
98
    0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
99
    0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
100
    0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
101
    0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
102
    0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
103
    0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
104
    0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
105
    0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
106
    0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
107
    0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
108
    0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
109
    0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
110
    0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
111
};
112
113
static int mov_read_mac_string(MOVContext *c, ByteIOContext *pb, int len,
114
                               char *dst, int dstlen)
115
{
116
    char *p = dst;
117
    char *end = dst+dstlen-1;
118
    int i;
119
120
    for (i = 0; i < len; i++) {
121
        uint8_t t, c = get_byte(pb);
122
        if (c < 0x80 && p < end)
123
            *p++ = c;
124
        else
125
            PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
126
    }
127
    *p = 0;
128
    return p - dst;
129
}
130
131 0fb44a4e Baptiste Coudurier
static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
132
{
133
#ifdef MOV_EXPORT_ALL_METADATA
134
    char tmp_key[5];
135
#endif
136
    char str[1024], key2[16], language[4] = {0};
137
    const char *key = NULL;
138 08a186c6 Baptiste Coudurier
    uint16_t str_size, langcode = 0;
139
    uint32_t data_type = 0;
140 c6026e43 Baptiste Coudurier
    int (*parse)(MOVContext*, ByteIOContext*, unsigned) = NULL;
141 0fb44a4e Baptiste Coudurier
142
    switch (atom.type) {
143
    case MKTAG(0xa9,'n','a','m'): key = "title";     break;
144
    case MKTAG(0xa9,'a','u','t'):
145 ea4c4d7f Baptiste Coudurier
    case MKTAG(0xa9,'A','R','T'): key = "artist";    break;
146 55d2e32a Baptiste Coudurier
    case MKTAG(0xa9,'w','r','t'): key = "composer";  break;
147 b9c78bca David Conrad
    case MKTAG( 'c','p','r','t'):
148 0fb44a4e Baptiste Coudurier
    case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
149
    case MKTAG(0xa9,'c','m','t'):
150
    case MKTAG(0xa9,'i','n','f'): key = "comment";   break;
151
    case MKTAG(0xa9,'a','l','b'): key = "album";     break;
152 ca76a119 Anton Khirnov
    case MKTAG(0xa9,'d','a','y'): key = "date";      break;
153 0fb44a4e Baptiste Coudurier
    case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
154
    case MKTAG(0xa9,'t','o','o'):
155 2b91d83e Baptiste Coudurier
    case MKTAG(0xa9,'s','w','r'): key = "encoder";   break;
156 a4cb56aa Baptiste Coudurier
    case MKTAG(0xa9,'e','n','c'): key = "encoder";   break;
157 7382902b David Conrad
    case MKTAG( 'd','e','s','c'): key = "description";break;
158
    case MKTAG( 'l','d','e','s'): key = "synopsis";  break;
159
    case MKTAG( 't','v','s','h'): key = "show";      break;
160
    case MKTAG( 't','v','e','n'): key = "episode_id";break;
161
    case MKTAG( 't','v','n','n'): key = "network";   break;
162 c6026e43 Baptiste Coudurier
    case MKTAG( 't','r','k','n'): key = "track";
163
        parse = mov_metadata_trkn; break;
164 0fb44a4e Baptiste Coudurier
    }
165
166
    if (c->itunes_metadata && atom.size > 8) {
167
        int data_size = get_be32(pb);
168
        int tag = get_le32(pb);
169
        if (tag == MKTAG('d','a','t','a')) {
170 08a186c6 Baptiste Coudurier
            data_type = get_be32(pb); // type
171 0fb44a4e Baptiste Coudurier
            get_be32(pb); // unknown
172
            str_size = data_size - 16;
173
            atom.size -= 16;
174
        } else return 0;
175
    } else if (atom.size > 4 && key && !c->itunes_metadata) {
176
        str_size = get_be16(pb); // string length
177 08a186c6 Baptiste Coudurier
        langcode = get_be16(pb);
178
        ff_mov_lang_to_iso639(langcode, language);
179 0fb44a4e Baptiste Coudurier
        atom.size -= 4;
180
    } else
181
        str_size = atom.size;
182
183
#ifdef MOV_EXPORT_ALL_METADATA
184
    if (!key) {
185
        snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
186
        key = tmp_key;
187
    }
188
#endif
189
190
    if (!key)
191
        return 0;
192
    if (atom.size < 0)
193
        return -1;
194
195
    str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
196 c6026e43 Baptiste Coudurier
197
    if (parse)
198
        parse(c, pb, str_size);
199
    else {
200 08a186c6 Baptiste Coudurier
        if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
201
            mov_read_mac_string(c, pb, str_size, str, sizeof(str));
202
        } else {
203
            get_buffer(pb, str, str_size);
204
            str[str_size] = 0;
205
        }
206 2ef6c124 Stefano Sabatini
        av_metadata_set2(&c->fc->metadata, key, str, 0);
207 f584386d Baptiste Coudurier
        if (*language && strcmp(language, "und")) {
208
            snprintf(key2, sizeof(key2), "%s-%s", key, language);
209 2ef6c124 Stefano Sabatini
            av_metadata_set2(&c->fc->metadata, key2, str, 0);
210 f584386d Baptiste Coudurier
        }
211 c6026e43 Baptiste Coudurier
    }
212 0fb44a4e Baptiste Coudurier
#ifdef DEBUG_METADATA
213
    av_log(c->fc, AV_LOG_DEBUG, "lang \"%3s\" ", language);
214
    av_log(c->fc, AV_LOG_DEBUG, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %lld\n",
215
           key, str, (char*)&atom.type, str_size, atom.size);
216
#endif
217
218
    return 0;
219
}
220 873358e5 Baptiste Coudurier
221 1cf9f6ed David Conrad
static int mov_read_chpl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
222
{
223
    int64_t start;
224 105b3785 David Conrad
    int i, nb_chapters, str_len, version;
225 1cf9f6ed David Conrad
    char str[256+1];
226
227
    if ((atom.size -= 5) < 0)
228
        return 0;
229
230 105b3785 David Conrad
    version = get_byte(pb);
231
    get_be24(pb);
232
    if (version)
233
        get_be32(pb); // ???
234 1cf9f6ed David Conrad
    nb_chapters = get_byte(pb);
235
236
    for (i = 0; i < nb_chapters; i++) {
237
        if (atom.size < 9)
238
            return 0;
239
240
        start = get_be64(pb);
241
        str_len = get_byte(pb);
242
243
        if ((atom.size -= 9+str_len) < 0)
244
            return 0;
245
246
        get_buffer(pb, str, str_len);
247
        str[str_len] = 0;
248
        ff_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
249
    }
250
    return 0;
251
}
252
253 c3e92a6c Baptiste Coudurier
static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
254 6cea494e Zdenek Kabelac
{
255 b6a17df4 Zdenek Kabelac
    int64_t total_size = 0;
256 c3e92a6c Baptiste Coudurier
    MOVAtom a;
257 6cea494e Zdenek Kabelac
    int i;
258 5ca1d879 Zdenek Kabelac
259 9ed83b0a Zdenek Kabelac
    if (atom.size < 0)
260 fa22ca22 Baptiste Coudurier
        atom.size = INT64_MAX;
261 7b1312fa Baptiste Coudurier
    while (total_size + 8 < atom.size && !url_feof(pb)) {
262 873358e5 Baptiste Coudurier
        int (*parse)(MOVContext*, ByteIOContext*, MOVAtom) = NULL;
263 bb270c08 Diego Biurrun
        a.size = atom.size;
264 bcfe2ba0 Baptiste Coudurier
        a.type=0;
265 5ca1d879 Zdenek Kabelac
        if(atom.size >= 8) {
266 bb270c08 Diego Biurrun
            a.size = get_be32(pb);
267 5ca1d879 Zdenek Kabelac
            a.type = get_le32(pb);
268 6cea494e Zdenek Kabelac
        }
269 3491866a Baptiste Coudurier
        dprintf(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
270
                a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
271 2209ffac Baptiste Coudurier
        total_size += 8;
272 5ca1d879 Zdenek Kabelac
        if (a.size == 1) { /* 64 bit extended size */
273 bb270c08 Diego Biurrun
            a.size = get_be64(pb) - 8;
274 5ca1d879 Zdenek Kabelac
            total_size += 8;
275 6cea494e Zdenek Kabelac
        }
276 bb270c08 Diego Biurrun
        if (a.size == 0) {
277
            a.size = atom.size - total_size;
278
            if (a.size <= 8)
279 5cd62665 Zdenek Kabelac
                break;
280 bb270c08 Diego Biurrun
        }
281
        a.size -= 8;
282 8622613d Baptiste Coudurier
        if(a.size < 0)
283 568e18b1 Michael Niedermayer
            break;
284 3d2308b0 Baptiste Coudurier
        a.size = FFMIN(a.size, atom.size - total_size);
285 115329f1 Diego Biurrun
286 873358e5 Baptiste Coudurier
        for (i = 0; mov_default_parse_table[i].type; i++)
287
            if (mov_default_parse_table[i].type == a.type) {
288
                parse = mov_default_parse_table[i].parse;
289
                break;
290
            }
291 11979c46 Baptiste Coudurier
292 873358e5 Baptiste Coudurier
        // container is user data
293
        if (!parse && (atom.type == MKTAG('u','d','t','a') ||
294
                       atom.type == MKTAG('i','l','s','t')))
295
            parse = mov_read_udta_string;
296
297
        if (!parse) { /* skip leaf atoms data */
298 5ca1d879 Zdenek Kabelac
            url_fskip(pb, a.size);
299 bb270c08 Diego Biurrun
        } else {
300 bc5c918e Diego Biurrun
            int64_t start_pos = url_ftell(pb);
301 5c72cad8 Baptiste Coudurier
            int64_t left;
302 a510991c Baptiste Coudurier
            int err = parse(c, pb, a);
303
            if (err < 0)
304
                return err;
305 49544546 Baptiste Coudurier
            if (c->found_moov && c->found_mdat &&
306
                (url_is_streamed(pb) || start_pos + a.size == url_fsize(pb)))
307
                return 0;
308 5c72cad8 Baptiste Coudurier
            left = a.size - url_ftell(pb) + start_pos;
309
            if (left > 0) /* skip garbage at atom end */
310
                url_fskip(pb, left);
311 bb270c08 Diego Biurrun
        }
312 6cea494e Zdenek Kabelac
313 5ca1d879 Zdenek Kabelac
        total_size += a.size;
314 6cea494e Zdenek Kabelac
    }
315
316 a510991c Baptiste Coudurier
    if (total_size < atom.size && atom.size < 0x7ffff)
317 5ca1d879 Zdenek Kabelac
        url_fskip(pb, atom.size - total_size);
318 5cd62665 Zdenek Kabelac
319 a510991c Baptiste Coudurier
    return 0;
320 6cea494e Zdenek Kabelac
}
321
322 c3e92a6c Baptiste Coudurier
static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
323 221e21b7 Baptiste Coudurier
{
324 6a63ff19 Baptiste Coudurier
    AVStream *st;
325
    MOVStreamContext *sc;
326 221e21b7 Baptiste Coudurier
    int entries, i, j;
327
328 6a63ff19 Baptiste Coudurier
    if (c->fc->nb_streams < 1)
329
        return 0;
330
    st = c->fc->streams[c->fc->nb_streams-1];
331
    sc = st->priv_data;
332
333 221e21b7 Baptiste Coudurier
    get_be32(pb); // version + flags
334
    entries = get_be32(pb);
335
    if (entries >= UINT_MAX / sizeof(*sc->drefs))
336
        return -1;
337
    sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
338 0d8f0abf Baptiste Coudurier
    if (!sc->drefs)
339
        return AVERROR(ENOMEM);
340
    sc->drefs_count = entries;
341 221e21b7 Baptiste Coudurier
342
    for (i = 0; i < sc->drefs_count; i++) {
343 c3e92a6c Baptiste Coudurier
        MOVDref *dref = &sc->drefs[i];
344 221e21b7 Baptiste Coudurier
        uint32_t size = get_be32(pb);
345 bc5c918e Diego Biurrun
        int64_t next = url_ftell(pb) + size - 4;
346 221e21b7 Baptiste Coudurier
347 0e7d436d Baptiste Coudurier
        if (size < 12)
348
            return -1;
349
350 221e21b7 Baptiste Coudurier
        dref->type = get_le32(pb);
351
        get_be32(pb); // version + flags
352
        dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
353
354
        if (dref->type == MKTAG('a','l','i','s') && size > 150) {
355
            /* macintosh alias record */
356
            uint16_t volume_len, len;
357
            int16_t type;
358
359
            url_fskip(pb, 10);
360
361
            volume_len = get_byte(pb);
362
            volume_len = FFMIN(volume_len, 27);
363 adeb9071 Baptiste Coudurier
            get_buffer(pb, dref->volume, 27);
364
            dref->volume[volume_len] = 0;
365
            av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
366 221e21b7 Baptiste Coudurier
367 adeb9071 Baptiste Coudurier
            url_fskip(pb, 12);
368
369
            len = get_byte(pb);
370
            len = FFMIN(len, 63);
371
            get_buffer(pb, dref->filename, 63);
372
            dref->filename[len] = 0;
373
            av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
374
375
            url_fskip(pb, 16);
376
377
            /* read next level up_from_alias/down_to_target */
378
            dref->nlvl_from = get_be16(pb);
379
            dref->nlvl_to   = get_be16(pb);
380
            av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
381
                   dref->nlvl_from, dref->nlvl_to);
382
383
            url_fskip(pb, 16);
384 221e21b7 Baptiste Coudurier
385
            for (type = 0; type != -1 && url_ftell(pb) < next; ) {
386
                type = get_be16(pb);
387
                len = get_be16(pb);
388
                av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
389
                if (len&1)
390
                    len += 1;
391
                if (type == 2) { // absolute path
392 dbb37657 Baptiste Coudurier
                    av_free(dref->path);
393 221e21b7 Baptiste Coudurier
                    dref->path = av_mallocz(len+1);
394 2f4568e5 Baptiste Coudurier
                    if (!dref->path)
395
                        return AVERROR(ENOMEM);
396 221e21b7 Baptiste Coudurier
                    get_buffer(pb, dref->path, len);
397 adeb9071 Baptiste Coudurier
                    if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
398 221e21b7 Baptiste Coudurier
                        len -= volume_len;
399
                        memmove(dref->path, dref->path+volume_len, len);
400
                        dref->path[len] = 0;
401
                    }
402
                    for (j = 0; j < len; j++)
403
                        if (dref->path[j] == ':')
404
                            dref->path[j] = '/';
405
                    av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
406 adeb9071 Baptiste Coudurier
                } else if (type == 0) { // directory name
407
                    av_free(dref->dir);
408
                    dref->dir = av_malloc(len+1);
409
                    if (!dref->dir)
410
                        return AVERROR(ENOMEM);
411
                    get_buffer(pb, dref->dir, len);
412
                    dref->dir[len] = 0;
413
                    for (j = 0; j < len; j++)
414
                        if (dref->dir[j] == ':')
415
                            dref->dir[j] = '/';
416
                    av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
417 221e21b7 Baptiste Coudurier
                } else
418
                    url_fskip(pb, len);
419
            }
420
        }
421
        url_fseek(pb, next, SEEK_SET);
422
    }
423
    return 0;
424
}
425
426 c3e92a6c Baptiste Coudurier
static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
427 6cea494e Zdenek Kabelac
{
428 fefe43ff Alex Converse
    AVStream *st;
429 0c1a9eda Zdenek Kabelac
    uint32_t type;
430
    uint32_t ctype;
431 b6a17df4 Zdenek Kabelac
432 fefe43ff Alex Converse
    if (c->fc->nb_streams < 1) // meta before first trak
433
        return 0;
434
435
    st = c->fc->streams[c->fc->nb_streams-1];
436
437 6cea494e Zdenek Kabelac
    get_byte(pb); /* version */
438 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
439 6cea494e Zdenek Kabelac
440
    /* component type */
441
    ctype = get_le32(pb);
442
    type = get_le32(pb); /* component subtype */
443
444 9bf1b268 Baptiste Coudurier
    dprintf(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
445
    dprintf(c->fc, "stype= %.4s\n", (char*)&type);
446 2229a5c6 Baptiste Coudurier
447 37ffe34b Baptiste Coudurier
    if     (type == MKTAG('v','i','d','e'))
448 72415b2a Stefano Sabatini
        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
449 1c126b4f Baptiste Coudurier
    else if(type == MKTAG('s','o','u','n'))
450 72415b2a Stefano Sabatini
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
451 1c126b4f Baptiste Coudurier
    else if(type == MKTAG('m','1','a',' '))
452 95a07973 Baptiste Coudurier
        st->codec->codec_id = CODEC_ID_MP2;
453 f05783c2 Baptiste Coudurier
    else if(type == MKTAG('s','u','b','p'))
454 72415b2a Stefano Sabatini
        st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
455 f05783c2 Baptiste Coudurier
456 6cea494e Zdenek Kabelac
    get_be32(pb); /* component  manufacture */
457
    get_be32(pb); /* component flags */
458
    get_be32(pb); /* component flags mask */
459
460
    return 0;
461
}
462
463 2d423666 Peter Ross
int ff_mov_read_esds(AVFormatContext *fc, ByteIOContext *pb, MOVAtom atom)
464 5cd62665 Zdenek Kabelac
{
465 6a63ff19 Baptiste Coudurier
    AVStream *st;
466 5cd62665 Zdenek Kabelac
    int tag, len;
467 b6a17df4 Zdenek Kabelac
468 2d423666 Peter Ross
    if (fc->nb_streams < 1)
469 6a63ff19 Baptiste Coudurier
        return 0;
470 2d423666 Peter Ross
    st = fc->streams[fc->nb_streams-1];
471 6a63ff19 Baptiste Coudurier
472 5cd62665 Zdenek Kabelac
    get_be32(pb); /* version + flags */
473 798c6fac Baptiste Coudurier
    len = ff_mp4_read_descr(fc, pb, &tag);
474 5cd62665 Zdenek Kabelac
    if (tag == MP4ESDescrTag) {
475 bb270c08 Diego Biurrun
        get_be16(pb); /* ID */
476
        get_byte(pb); /* priority */
477 5cd62665 Zdenek Kabelac
    } else
478 bb270c08 Diego Biurrun
        get_be16(pb); /* ID */
479 5cd62665 Zdenek Kabelac
480 798c6fac Baptiste Coudurier
    len = ff_mp4_read_descr(fc, pb, &tag);
481
    if (tag == MP4DecConfigDescrTag)
482
        ff_mp4_read_dec_config_descr(fc, st, pb);
483 5cd62665 Zdenek Kabelac
    return 0;
484
}
485
486 2d423666 Peter Ross
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
487
{
488
    return ff_mov_read_esds(c->fc, pb, atom);
489
}
490
491 bdecdd2b Justin Ruggles
static int mov_read_dac3(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
492
{
493
    AVStream *st;
494
    int ac3info, acmod, lfeon;
495
496 6d19fd5c Baptiste Coudurier
    if (c->fc->nb_streams < 1)
497
        return 0;
498 bdecdd2b Justin Ruggles
    st = c->fc->streams[c->fc->nb_streams-1];
499
500
    ac3info = get_be24(pb);
501
    acmod = (ac3info >> 11) & 0x7;
502
    lfeon = (ac3info >> 10) & 0x1;
503
    st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
504
505
    return 0;
506
}
507
508 6da54074 Baptiste Coudurier
static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
509
{
510
    const int num = get_be32(pb);
511
    const int den = get_be32(pb);
512 6a63ff19 Baptiste Coudurier
    AVStream *st;
513
514
    if (c->fc->nb_streams < 1)
515
        return 0;
516
    st = c->fc->streams[c->fc->nb_streams-1];
517
518 9044dd83 Baptiste Coudurier
    if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
519
        (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
520
        av_log(c->fc, AV_LOG_WARNING,
521
               "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
522
               st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
523
               num, den);
524
    } else if (den != 0) {
525 6da54074 Baptiste Coudurier
        st->sample_aspect_ratio.num = num;
526
        st->sample_aspect_ratio.den = den;
527
    }
528
    return 0;
529
}
530
531 5ca1d879 Zdenek Kabelac
/* this atom contains actual media data */
532 c3e92a6c Baptiste Coudurier
static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
533 6cea494e Zdenek Kabelac
{
534 5ca1d879 Zdenek Kabelac
    if(atom.size == 0) /* wrong one (MP4) */
535
        return 0;
536
    c->found_mdat=1;
537
    return 0; /* now go for moov */
538
}
539
540 7b5252ce haim alon
/* read major brand, minor version and compatible brands and store them as metadata */
541 c3e92a6c Baptiste Coudurier
static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
542 4ea28253 Baptiste Coudurier
{
543 7b5252ce haim alon
    uint32_t minor_ver;
544
    int comp_brand_size;
545
    char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
546
    char* comp_brands_str;
547
    uint8_t type[5] = {0};
548
549
    get_buffer(pb, type, 4);
550 a42bf191 Baptiste Coudurier
    if (strcmp(type, "qt  "))
551 152e9a43 Baptiste Coudurier
        c->isom = 1;
552 a512446e Baptiste Coudurier
    av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
553 2ef6c124 Stefano Sabatini
    av_metadata_set2(&c->fc->metadata, "major_brand", type, 0);
554 7b5252ce haim alon
    minor_ver = get_be32(pb); /* minor version */
555
    snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
556 2ef6c124 Stefano Sabatini
    av_metadata_set2(&c->fc->metadata, "minor_version", minor_ver_str, 0);
557 7b5252ce haim alon
558
    comp_brand_size = atom.size - 8;
559
    if (comp_brand_size < 0)
560
        return -1;
561
    comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
562
    if (!comp_brands_str)
563
        return AVERROR(ENOMEM);
564
    get_buffer(pb, comp_brands_str, comp_brand_size);
565
    comp_brands_str[comp_brand_size] = 0;
566 2ef6c124 Stefano Sabatini
    av_metadata_set2(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
567 7b5252ce haim alon
    av_freep(&comp_brands_str);
568
569 4ea28253 Baptiste Coudurier
    return 0;
570
}
571
572 5ca1d879 Zdenek Kabelac
/* this atom should contain all header atoms */
573 c3e92a6c Baptiste Coudurier
static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
574 5ca1d879 Zdenek Kabelac
{
575 9cf0419b Panagiotis Issaris
    if (mov_read_default(c, pb, atom) < 0)
576
        return -1;
577 5ca1d879 Zdenek Kabelac
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
578
    /* so we don't parse the whole file if over a network */
579
    c->found_moov=1;
580
    return 0; /* now go for mdat */
581
}
582
583 c3e92a6c Baptiste Coudurier
static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
584 61aedb0f Baptiste Coudurier
{
585
    c->fragment.moof_offset = url_ftell(pb) - 8;
586
    dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
587
    return mov_read_default(c, pb, atom);
588
}
589 5ca1d879 Zdenek Kabelac
590 7df22143 Aurelien Jacobs
static void mov_metadata_creation_time(AVMetadata **metadata, time_t time)
591
{
592
    char buffer[32];
593
    if (time) {
594 5e2202d6 Baptiste Coudurier
        struct tm *ptm;
595 7df22143 Aurelien Jacobs
        time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
596 5e2202d6 Baptiste Coudurier
        ptm = gmtime(&time);
597
        if (!ptm) return;
598
        strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
599 7df22143 Aurelien Jacobs
        av_metadata_set2(metadata, "creation_time", buffer, 0);
600
    }
601
}
602
603 c3e92a6c Baptiste Coudurier
static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
604 5ca1d879 Zdenek Kabelac
{
605 6a63ff19 Baptiste Coudurier
    AVStream *st;
606
    MOVStreamContext *sc;
607
    int version;
608 49674dd0 Aurelien Jacobs
    char language[4] = {0};
609 dce25564 Aurelien Jacobs
    unsigned lang;
610 7df22143 Aurelien Jacobs
    time_t creation_time;
611 5ca1d879 Zdenek Kabelac
612 6a63ff19 Baptiste Coudurier
    if (c->fc->nb_streams < 1)
613
        return 0;
614
    st = c->fc->streams[c->fc->nb_streams-1];
615
    sc = st->priv_data;
616
617
    version = get_byte(pb);
618 b9a87c4d François Revol
    if (version > 1)
619 7e627332 Baptiste Coudurier
        return -1; /* unsupported */
620 5ca1d879 Zdenek Kabelac
621 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
622 f444b977 Baptiste Coudurier
    if (version == 1) {
623 7df22143 Aurelien Jacobs
        creation_time = get_be64(pb);
624 f444b977 Baptiste Coudurier
        get_be64(pb);
625
    } else {
626 7df22143 Aurelien Jacobs
        creation_time = get_be32(pb);
627 f444b977 Baptiste Coudurier
        get_be32(pb); /* modification time */
628
    }
629 7df22143 Aurelien Jacobs
    mov_metadata_creation_time(&st->metadata, creation_time);
630 5ca1d879 Zdenek Kabelac
631 f444b977 Baptiste Coudurier
    sc->time_scale = get_be32(pb);
632
    st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
633 5ca1d879 Zdenek Kabelac
634 b9a87c4d François Revol
    lang = get_be16(pb); /* language */
635 49674dd0 Aurelien Jacobs
    if (ff_mov_lang_to_iso639(lang, language))
636 2ef6c124 Stefano Sabatini
        av_metadata_set2(&st->metadata, "language", language, 0);
637 5ca1d879 Zdenek Kabelac
    get_be16(pb); /* quality */
638
639
    return 0;
640
}
641
642 c3e92a6c Baptiste Coudurier
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
643 5ca1d879 Zdenek Kabelac
{
644 7df22143 Aurelien Jacobs
    time_t creation_time;
645 1175561e Baptiste Coudurier
    int version = get_byte(pb); /* version */
646 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
647 5ca1d879 Zdenek Kabelac
648 1175561e Baptiste Coudurier
    if (version == 1) {
649 7df22143 Aurelien Jacobs
        creation_time = get_be64(pb);
650 1175561e Baptiste Coudurier
        get_be64(pb);
651
    } else {
652 7df22143 Aurelien Jacobs
        creation_time = get_be32(pb);
653 1175561e Baptiste Coudurier
        get_be32(pb); /* modification time */
654
    }
655 7df22143 Aurelien Jacobs
    mov_metadata_creation_time(&c->fc->metadata, creation_time);
656 5ca1d879 Zdenek Kabelac
    c->time_scale = get_be32(pb); /* time scale */
657 f8c18cd7 Baptiste Coudurier
658
    dprintf(c->fc, "time scale = %i\n", c->time_scale);
659
660 1175561e Baptiste Coudurier
    c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
661 5ca1d879 Zdenek Kabelac
    get_be32(pb); /* preferred scale */
662
663
    get_be16(pb); /* preferred volume */
664
665
    url_fskip(pb, 10); /* reserved */
666
667
    url_fskip(pb, 36); /* display matrix */
668
669
    get_be32(pb); /* preview time */
670
    get_be32(pb); /* preview duration */
671
    get_be32(pb); /* poster time */
672
    get_be32(pb); /* selection time */
673
    get_be32(pb); /* selection duration */
674
    get_be32(pb); /* current time */
675
    get_be32(pb); /* next track ID */
676
677
    return 0;
678
}
679
680 c3e92a6c Baptiste Coudurier
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
681 9ed83b0a Zdenek Kabelac
{
682 6a63ff19 Baptiste Coudurier
    AVStream *st;
683
684
    if (c->fc->nb_streams < 1)
685
        return 0;
686
    st = c->fc->streams[c->fc->nb_streams-1];
687 9ed83b0a Zdenek Kabelac
688 568e18b1 Michael Niedermayer
    if((uint64_t)atom.size > (1<<30))
689
        return -1;
690 115329f1 Diego Biurrun
691 9ed83b0a Zdenek Kabelac
    // currently SVQ3 decoder expect full STSD header - so let's fake it
692
    // this should be fixed and just SMI header should be passed
693 01f4895c Michael Niedermayer
    av_free(st->codec->extradata);
694 b014dd76 Baptiste Coudurier
    st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
695
    if (!st->codec->extradata)
696
        return AVERROR(ENOMEM);
697 17871a02 Baptiste Coudurier
    st->codec->extradata_size = 0x5a + atom.size;
698
    memcpy(st->codec->extradata, "SVQ3", 4); // fake
699
    get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
700
    dprintf(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
701 9ed83b0a Zdenek Kabelac
    return 0;
702
}
703 5ca1d879 Zdenek Kabelac
704 c3e92a6c Baptiste Coudurier
static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
705 de23f234 Baptiste Coudurier
{
706 6a63ff19 Baptiste Coudurier
    AVStream *st;
707
    int little_endian;
708
709
    if (c->fc->nb_streams < 1)
710
        return 0;
711
    st = c->fc->streams[c->fc->nb_streams-1];
712 de23f234 Baptiste Coudurier
713 6a63ff19 Baptiste Coudurier
    little_endian = get_be16(pb);
714 fa50a027 Baptiste Coudurier
    dprintf(c->fc, "enda %d\n", little_endian);
715
    if (little_endian == 1) {
716 de23f234 Baptiste Coudurier
        switch (st->codec->codec_id) {
717
        case CODEC_ID_PCM_S24BE:
718
            st->codec->codec_id = CODEC_ID_PCM_S24LE;
719
            break;
720
        case CODEC_ID_PCM_S32BE:
721
            st->codec->codec_id = CODEC_ID_PCM_S32LE;
722
            break;
723 a1ef2c4b Peter Ross
        case CODEC_ID_PCM_F32BE:
724
            st->codec->codec_id = CODEC_ID_PCM_F32LE;
725
            break;
726
        case CODEC_ID_PCM_F64BE:
727
            st->codec->codec_id = CODEC_ID_PCM_F64LE;
728
            break;
729 de23f234 Baptiste Coudurier
        default:
730
            break;
731
        }
732
    }
733
    return 0;
734
}
735
736 014a5102 Baptiste Coudurier
/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
737 c3e92a6c Baptiste Coudurier
static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
738 de23f234 Baptiste Coudurier
{
739 27134437 Baptiste Coudurier
    AVStream *st;
740
    uint64_t size;
741 68bc33fa Baptiste Coudurier
    uint8_t *buf;
742 27134437 Baptiste Coudurier
743
    if (c->fc->nb_streams < 1) // will happen with jp2 files
744
        return 0;
745
    st= c->fc->streams[c->fc->nb_streams-1];
746
    size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
747 68bc33fa Baptiste Coudurier
    if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
748 014a5102 Baptiste Coudurier
        return -1;
749 68bc33fa Baptiste Coudurier
    buf= av_realloc(st->codec->extradata, size);
750
    if(!buf)
751
        return -1;
752
    st->codec->extradata= buf;
753
    buf+= st->codec->extradata_size;
754
    st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
755
    AV_WB32(       buf    , atom.size + 8);
756
    AV_WL32(       buf + 4, atom.type);
757
    get_buffer(pb, buf + 8, atom.size);
758 de23f234 Baptiste Coudurier
    return 0;
759
}
760
761 c3e92a6c Baptiste Coudurier
static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
762 d9b1c197 Roberto Togni
{
763 6a63ff19 Baptiste Coudurier
    AVStream *st;
764
765
    if (c->fc->nb_streams < 1)
766
        return 0;
767
    st = c->fc->streams[c->fc->nb_streams-1];
768 d9b1c197 Roberto Togni
769
    if((uint64_t)atom.size > (1<<30))
770
        return -1;
771 115329f1 Diego Biurrun
772 3840147e Michael Niedermayer
    if (st->codec->codec_id == CODEC_ID_QDM2) {
773
        // pass all frma atom to codec, needed at least for QDM2
774
        av_free(st->codec->extradata);
775 b014dd76 Baptiste Coudurier
        st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
776
        if (!st->codec->extradata)
777
            return AVERROR(ENOMEM);
778 3840147e Michael Niedermayer
        st->codec->extradata_size = atom.size;
779 b014dd76 Baptiste Coudurier
        get_buffer(pb, st->codec->extradata, atom.size);
780 3840147e Michael Niedermayer
    } else if (atom.size > 8) { /* to read frma, esds atoms */
781 9cf0419b Panagiotis Issaris
        if (mov_read_default(c, pb, atom) < 0)
782
            return -1;
783 5c72cad8 Baptiste Coudurier
    } else
784 bb270c08 Diego Biurrun
        url_fskip(pb, atom.size);
785 d9b1c197 Roberto Togni
    return 0;
786
}
787
788 bde24601 Baptiste Coudurier
/**
789
 * This function reads atom content and puts data in extradata without tag
790
 * nor size unlike mov_read_extradata.
791
 */
792 c3e92a6c Baptiste Coudurier
static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
793 169eb021 Mike Melanson
{
794 6a63ff19 Baptiste Coudurier
    AVStream *st;
795
796
    if (c->fc->nb_streams < 1)
797
        return 0;
798
    st = c->fc->streams[c->fc->nb_streams-1];
799 169eb021 Mike Melanson
800 568e18b1 Michael Niedermayer
    if((uint64_t)atom.size > (1<<30))
801
        return -1;
802
803 01f4895c Michael Niedermayer
    av_free(st->codec->extradata);
804 b014dd76 Baptiste Coudurier
    st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
805
    if (!st->codec->extradata)
806
        return AVERROR(ENOMEM);
807 01f4895c Michael Niedermayer
    st->codec->extradata_size = atom.size;
808 b014dd76 Baptiste Coudurier
    get_buffer(pb, st->codec->extradata, atom.size);
809 169eb021 Mike Melanson
    return 0;
810
}
811
812 653d7aeb Martin Storsjö
/**
813
 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
814
 * but can have extradata appended at the end after the 40 bytes belonging
815
 * to the struct.
816
 */
817
static int mov_read_strf(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
818
{
819
    AVStream *st;
820
821
    if (c->fc->nb_streams < 1)
822
        return 0;
823
    if (atom.size <= 40)
824
        return 0;
825
    st = c->fc->streams[c->fc->nb_streams-1];
826
827
    if((uint64_t)atom.size > (1<<30))
828
        return -1;
829
830
    av_free(st->codec->extradata);
831
    st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
832
    if (!st->codec->extradata)
833
        return AVERROR(ENOMEM);
834
    st->codec->extradata_size = atom.size - 40;
835
    url_fskip(pb, 40);
836
    get_buffer(pb, st->codec->extradata, atom.size - 40);
837
    return 0;
838
}
839
840 c3e92a6c Baptiste Coudurier
static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
841 5ca1d879 Zdenek Kabelac
{
842 6a63ff19 Baptiste Coudurier
    AVStream *st;
843
    MOVStreamContext *sc;
844 568e18b1 Michael Niedermayer
    unsigned int i, entries;
845 5ca1d879 Zdenek Kabelac
846 6a63ff19 Baptiste Coudurier
    if (c->fc->nb_streams < 1)
847
        return 0;
848
    st = c->fc->streams[c->fc->nb_streams-1];
849
    sc = st->priv_data;
850
851 5ca1d879 Zdenek Kabelac
    get_byte(pb); /* version */
852 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
853 5ca1d879 Zdenek Kabelac
854
    entries = get_be32(pb);
855 115329f1 Diego Biurrun
856 568e18b1 Michael Niedermayer
    if(entries >= UINT_MAX/sizeof(int64_t))
857
        return -1;
858 115329f1 Diego Biurrun
859 9a630c25 Baptiste Coudurier
    sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
860 5ca1d879 Zdenek Kabelac
    if (!sc->chunk_offsets)
861 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
862
    sc->chunk_count = entries;
863
864 37ffe34b Baptiste Coudurier
    if      (atom.type == MKTAG('s','t','c','o'))
865
        for(i=0; i<entries; i++)
866 5ca1d879 Zdenek Kabelac
            sc->chunk_offsets[i] = get_be32(pb);
867 37ffe34b Baptiste Coudurier
    else if (atom.type == MKTAG('c','o','6','4'))
868
        for(i=0; i<entries; i++)
869 5ca1d879 Zdenek Kabelac
            sc->chunk_offsets[i] = get_be64(pb);
870 37ffe34b Baptiste Coudurier
    else
871 5ca1d879 Zdenek Kabelac
        return -1;
872 115329f1 Diego Biurrun
873 5ca1d879 Zdenek Kabelac
    return 0;
874
}
875
876 2288834f Baptiste Coudurier
/**
877
 * Compute codec id for 'lpcm' tag.
878
 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
879
 */
880 2d423666 Peter Ross
enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
881 2288834f Baptiste Coudurier
{
882
    if (flags & 1) { // floating point
883
        if (flags & 2) { // big endian
884
            if      (bps == 32) return CODEC_ID_PCM_F32BE;
885 7e4b3fb8 Baptiste Coudurier
            else if (bps == 64) return CODEC_ID_PCM_F64BE;
886 2288834f Baptiste Coudurier
        } else {
887 7e4b3fb8 Baptiste Coudurier
            if      (bps == 32) return CODEC_ID_PCM_F32LE;
888
            else if (bps == 64) return CODEC_ID_PCM_F64LE;
889 2288834f Baptiste Coudurier
        }
890
    } else {
891
        if (flags & 2) {
892
            if      (bps == 8)
893
                // signed integer
894
                if (flags & 4)  return CODEC_ID_PCM_S8;
895
                else            return CODEC_ID_PCM_U8;
896
            else if (bps == 16) return CODEC_ID_PCM_S16BE;
897
            else if (bps == 24) return CODEC_ID_PCM_S24BE;
898
            else if (bps == 32) return CODEC_ID_PCM_S32BE;
899
        } else {
900
            if      (bps == 8)
901
                if (flags & 4)  return CODEC_ID_PCM_S8;
902
                else            return CODEC_ID_PCM_U8;
903 021b8ae3 Baptiste Coudurier
            else if (bps == 16) return CODEC_ID_PCM_S16LE;
904 2288834f Baptiste Coudurier
            else if (bps == 24) return CODEC_ID_PCM_S24LE;
905
            else if (bps == 32) return CODEC_ID_PCM_S32LE;
906
        }
907
    }
908 fb65d2ca Diego Pettenò
    return CODEC_ID_NONE;
909 2288834f Baptiste Coudurier
}
910
911 dc2cabd0 Martin Storsjö
int ff_mov_read_stsd_entries(MOVContext *c, ByteIOContext *pb, int entries)
912 5ca1d879 Zdenek Kabelac
{
913 6a63ff19 Baptiste Coudurier
    AVStream *st;
914
    MOVStreamContext *sc;
915 dc2cabd0 Martin Storsjö
    int j, pseudo_stream_id;
916 b595afaa Mike Melanson
917 6a63ff19 Baptiste Coudurier
    if (c->fc->nb_streams < 1)
918
        return 0;
919
    st = c->fc->streams[c->fc->nb_streams-1];
920
    sc = st->priv_data;
921
922 117a9190 Baptiste Coudurier
    for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
923
        //Parsing Sample description table
924 b6a17df4 Zdenek Kabelac
        enum CodecID id;
925 28155113 Baptiste Coudurier
        int dref_id = 1;
926 3491866a Baptiste Coudurier
        MOVAtom a = { AV_RL32("stsd") };
927 bc5c918e Diego Biurrun
        int64_t start_pos = url_ftell(pb);
928 bb270c08 Diego Biurrun
        int size = get_be32(pb); /* size */
929 baf9fb32 Baptiste Coudurier
        uint32_t format = get_le32(pb); /* data format */
930 5cd62665 Zdenek Kabelac
931 28155113 Baptiste Coudurier
        if (size >= 16) {
932
            get_be32(pb); /* reserved */
933
            get_be16(pb); /* reserved */
934
            dref_id = get_be16(pb);
935
        }
936 0e7eed09 Fabrice Bellard
937 744a9c75 Michael Niedermayer
        if (st->codec->codec_tag &&
938 978677a7 Baptiste Coudurier
            st->codec->codec_tag != format &&
939 1a40491e Daniel Verkamp
            (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
940 1c126b4f Baptiste Coudurier
                                   : st->codec->codec_tag != MKTAG('j','p','e','g'))
941 744a9c75 Michael Niedermayer
           ){
942 7ce68923 Diego Biurrun
            /* Multiple fourcc, we skip JPEG. This is not correct, we should
943
             * export it as a separate AVStream but this needs a few changes
944
             * in the MOV demuxer, patch welcome. */
945 adc73054 Baptiste Coudurier
        multiple_stsd:
946 285a3da9 Baptiste Coudurier
            av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
947 e7cc4b52 Baptiste Coudurier
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
948
            continue;
949
        }
950 adc73054 Baptiste Coudurier
        /* we cannot demux concatenated h264 streams because of different extradata */
951
        if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
952
            goto multiple_stsd;
953 978677a7 Baptiste Coudurier
        sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
954 221e21b7 Baptiste Coudurier
        sc->dref_id= dref_id;
955 e7cc4b52 Baptiste Coudurier
956 bb270c08 Diego Biurrun
        st->codec->codec_tag = format;
957 1a40491e Daniel Verkamp
        id = ff_codec_get_id(codec_movaudio_tags, format);
958 86b61d42 David Conrad
        if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
959 8fc0162a Måns Rullgård
            id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
960 bca7db35 Michael Niedermayer
961 72415b2a Stefano Sabatini
        if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
962
            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
963
        } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
964 1c126b4f Baptiste Coudurier
                   format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
965 1a40491e Daniel Verkamp
            id = ff_codec_get_id(codec_movvideo_tags, format);
966 99487f42 Baptiste Coudurier
            if (id <= 0)
967 1a40491e Daniel Verkamp
                id = ff_codec_get_id(ff_codec_bmp_tags, format);
968 99487f42 Baptiste Coudurier
            if (id > 0)
969 72415b2a Stefano Sabatini
                st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
970
            else if(st->codec->codec_type == AVMEDIA_TYPE_DATA){
971 1a40491e Daniel Verkamp
                id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
972 1e3c9307 Michael Niedermayer
                if(id > 0)
973 72415b2a Stefano Sabatini
                    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
974 1e3c9307 Michael Niedermayer
            }
975 99487f42 Baptiste Coudurier
        }
976
977 29c90869 Baptiste Coudurier
        dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
978
                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
979
                (format >> 24) & 0xff, st->codec->codec_type);
980 a20da52c Baptiste Coudurier
981 72415b2a Stefano Sabatini
        if(st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
982 08a186c6 Baptiste Coudurier
            unsigned int color_depth, len;
983 baf9fb32 Baptiste Coudurier
            int color_greyscale;
984
985 01f4895c Michael Niedermayer
            st->codec->codec_id = id;
986 6cea494e Zdenek Kabelac
            get_be16(pb); /* version */
987
            get_be16(pb); /* revision level */
988
            get_be32(pb); /* vendor */
989
            get_be32(pb); /* temporal quality */
990 94472c1d Diego Biurrun
            get_be32(pb); /* spatial quality */
991 3cb4ee51 Baptiste Coudurier
992
            st->codec->width = get_be16(pb); /* width */
993
            st->codec->height = get_be16(pb); /* height */
994
995 6cea494e Zdenek Kabelac
            get_be32(pb); /* horiz resolution */
996
            get_be32(pb); /* vert resolution */
997
            get_be32(pb); /* data size, always 0 */
998 43612ffe Baptiste Coudurier
            get_be16(pb); /* frames per samples */
999 f8c18cd7 Baptiste Coudurier
1000 08a186c6 Baptiste Coudurier
            len = get_byte(pb); /* codec name, pascal string */
1001
            if (len > 31)
1002
                len = 31;
1003
            mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1004
            if (len < 31)
1005
                url_fskip(pb, 31 - len);
1006
            /* codec_tag YV12 triggers an UV swap in rawdec.c */
1007
            if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1008
                st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1009 5cd62665 Zdenek Kabelac
1010 dd1c8f3e Luca Abeni
            st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
1011 01f4895c Michael Niedermayer
            st->codec->color_table_id = get_be16(pb); /* colortable id */
1012 0de2157f Baptiste Coudurier
            dprintf(c->fc, "depth %d, ctab id %d\n",
1013 dd1c8f3e Luca Abeni
                   st->codec->bits_per_coded_sample, st->codec->color_table_id);
1014 b595afaa Mike Melanson
            /* figure out the palette situation */
1015 dd1c8f3e Luca Abeni
            color_depth = st->codec->bits_per_coded_sample & 0x1F;
1016
            color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1017 b595afaa Mike Melanson
1018
            /* if the depth is 2, 4, or 8 bpp, file is palettized */
1019 115329f1 Diego Biurrun
            if ((color_depth == 2) || (color_depth == 4) ||
1020 b595afaa Mike Melanson
                (color_depth == 8)) {
1021 47e1d7ef Baptiste Coudurier
                /* for palette traversal */
1022
                unsigned int color_start, color_count, color_end;
1023
                unsigned char r, g, b;
1024
1025 e49da827 Baptiste Coudurier
                st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
1026 b595afaa Mike Melanson
                if (color_greyscale) {
1027 47e1d7ef Baptiste Coudurier
                    int color_index, color_dec;
1028 b595afaa Mike Melanson
                    /* compute the greyscale palette */
1029 dd1c8f3e Luca Abeni
                    st->codec->bits_per_coded_sample = color_depth;
1030 b595afaa Mike Melanson
                    color_count = 1 << color_depth;
1031
                    color_index = 255;
1032
                    color_dec = 256 / (color_count - 1);
1033
                    for (j = 0; j < color_count; j++) {
1034
                        r = g = b = color_index;
1035 e49da827 Baptiste Coudurier
                        st->codec->palctrl->palette[j] =
1036 b595afaa Mike Melanson
                            (r << 16) | (g << 8) | (b);
1037
                        color_index -= color_dec;
1038
                        if (color_index < 0)
1039
                            color_index = 0;
1040
                    }
1041 71f36235 Baptiste Coudurier
                } else if (st->codec->color_table_id) {
1042 47e1d7ef Baptiste Coudurier
                    const uint8_t *color_table;
1043 b595afaa Mike Melanson
                    /* if flag bit 3 is set, use the default palette */
1044
                    color_count = 1 << color_depth;
1045
                    if (color_depth == 2)
1046 a90466f7 Michael Niedermayer
                        color_table = ff_qt_default_palette_4;
1047 b595afaa Mike Melanson
                    else if (color_depth == 4)
1048 a90466f7 Michael Niedermayer
                        color_table = ff_qt_default_palette_16;
1049 b595afaa Mike Melanson
                    else
1050 a90466f7 Michael Niedermayer
                        color_table = ff_qt_default_palette_256;
1051 b595afaa Mike Melanson
1052
                    for (j = 0; j < color_count; j++) {
1053 2121b160 Ronald S. Bultje
                        r = color_table[j * 3 + 0];
1054
                        g = color_table[j * 3 + 1];
1055
                        b = color_table[j * 3 + 2];
1056 e49da827 Baptiste Coudurier
                        st->codec->palctrl->palette[j] =
1057 b595afaa Mike Melanson
                            (r << 16) | (g << 8) | (b);
1058
                    }
1059
                } else {
1060
                    /* load the palette from the file */
1061
                    color_start = get_be32(pb);
1062
                    color_count = get_be16(pb);
1063
                    color_end = get_be16(pb);
1064 8b35bd80 Mike Melanson
                    if ((color_start <= 255) &&
1065
                        (color_end <= 255)) {
1066 9de2919c Mike Melanson
                        for (j = color_start; j <= color_end; j++) {
1067
                            /* each R, G, or B component is 16 bits;
1068
                             * only use the top 8 bits; skip alpha bytes
1069
                             * up front */
1070
                            get_byte(pb);
1071
                            get_byte(pb);
1072
                            r = get_byte(pb);
1073
                            get_byte(pb);
1074
                            g = get_byte(pb);
1075
                            get_byte(pb);
1076
                            b = get_byte(pb);
1077
                            get_byte(pb);
1078 e49da827 Baptiste Coudurier
                            st->codec->palctrl->palette[j] =
1079 9de2919c Mike Melanson
                                (r << 16) | (g << 8) | (b);
1080 8b35bd80 Mike Melanson
                        }
1081 b595afaa Mike Melanson
                    }
1082
                }
1083 01f4895c Michael Niedermayer
                st->codec->palctrl->palette_changed = 1;
1084 e49da827 Baptiste Coudurier
            }
1085 72415b2a Stefano Sabatini
        } else if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1086 aaef2bb3 Baptiste Coudurier
            int bits_per_sample, flags;
1087 de23f234 Baptiste Coudurier
            uint16_t version = get_be16(pb);
1088 b595afaa Mike Melanson
1089 99487f42 Baptiste Coudurier
            st->codec->codec_id = id;
1090 de23f234 Baptiste Coudurier
            get_be16(pb); /* revision level */
1091
            get_be32(pb); /* vendor */
1092 6d6d7970 Mike Melanson
1093 de23f234 Baptiste Coudurier
            st->codec->channels = get_be16(pb);             /* channel count */
1094 318c5e05 Michel Bardiaux
            dprintf(c->fc, "audio channels %d\n", st->codec->channels);
1095 dd1c8f3e Luca Abeni
            st->codec->bits_per_coded_sample = get_be16(pb);      /* sample size */
1096 de23f234 Baptiste Coudurier
1097 77c75437 Baptiste Coudurier
            sc->audio_cid = get_be16(pb);
1098 de23f234 Baptiste Coudurier
            get_be16(pb); /* packet size = 0 */
1099
1100
            st->codec->sample_rate = ((get_be32(pb) >> 16));
1101
1102 5ef3ad59 Baptiste Coudurier
            //Read QT version 1 fields. In version 0 these do not exist.
1103
            dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
1104
            if(!c->isom) {
1105
                if(version==1) {
1106
                    sc->samples_per_frame = get_be32(pb);
1107
                    get_be32(pb); /* bytes per packet */
1108
                    sc->bytes_per_frame = get_be32(pb);
1109
                    get_be32(pb); /* bytes per sample */
1110
                } else if(version==2) {
1111
                    get_be32(pb); /* sizeof struct only */
1112
                    st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
1113
                    st->codec->channels = get_be32(pb);
1114
                    get_be32(pb); /* always 0x7F000000 */
1115 dd1c8f3e Luca Abeni
                    st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
1116 6866dd12 Jai Menon
                    flags = get_be32(pb); /* lpcm format specific flag */
1117 9184d53a Baptiste Coudurier
                    sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
1118
                    sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
1119 2288834f Baptiste Coudurier
                    if (format == MKTAG('l','p','c','m'))
1120 2d423666 Peter Ross
                        st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1121 5ef3ad59 Baptiste Coudurier
                }
1122
            }
1123
1124 de23f234 Baptiste Coudurier
            switch (st->codec->codec_id) {
1125 b72708f8 Baptiste Coudurier
            case CODEC_ID_PCM_S8:
1126
            case CODEC_ID_PCM_U8:
1127 dd1c8f3e Luca Abeni
                if (st->codec->bits_per_coded_sample == 16)
1128 b72708f8 Baptiste Coudurier
                    st->codec->codec_id = CODEC_ID_PCM_S16BE;
1129
                break;
1130 0dd39bfe Baptiste Coudurier
            case CODEC_ID_PCM_S16LE:
1131 de23f234 Baptiste Coudurier
            case CODEC_ID_PCM_S16BE:
1132 dd1c8f3e Luca Abeni
                if (st->codec->bits_per_coded_sample == 8)
1133 de23f234 Baptiste Coudurier
                    st->codec->codec_id = CODEC_ID_PCM_S8;
1134 dd1c8f3e Luca Abeni
                else if (st->codec->bits_per_coded_sample == 24)
1135 6b477e1b Baptiste Coudurier
                    st->codec->codec_id =
1136
                        st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1137
                        CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1138 de23f234 Baptiste Coudurier
                break;
1139 53152765 Baptiste Coudurier
            /* set values for old format before stsd version 1 appeared */
1140
            case CODEC_ID_MACE3:
1141
                sc->samples_per_frame = 6;
1142
                sc->bytes_per_frame = 2*st->codec->channels;
1143
                break;
1144
            case CODEC_ID_MACE6:
1145
                sc->samples_per_frame = 6;
1146
                sc->bytes_per_frame = 1*st->codec->channels;
1147
                break;
1148
            case CODEC_ID_ADPCM_IMA_QT:
1149
                sc->samples_per_frame = 64;
1150
                sc->bytes_per_frame = 34*st->codec->channels;
1151
                break;
1152 cc326d2b Baptiste Coudurier
            case CODEC_ID_GSM:
1153
                sc->samples_per_frame = 160;
1154
                sc->bytes_per_frame = 33;
1155
                break;
1156 de23f234 Baptiste Coudurier
            default:
1157
                break;
1158 6d6d7970 Mike Melanson
            }
1159 14342fd5 Johannes Carlsson
1160 9770089d Baptiste Coudurier
            bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1161
            if (bits_per_sample) {
1162 dd1c8f3e Luca Abeni
                st->codec->bits_per_coded_sample = bits_per_sample;
1163 9770089d Baptiste Coudurier
                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1164
            }
1165 72415b2a Stefano Sabatini
        } else if(st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1166 58e9f2ed David Conrad
            // ttxt stsd contains display flags, justification, background
1167
            // color, fonts, and default styles, so fake an atom to read it
1168
            MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
1169 fb9ac654 Reimar Döffinger
            if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1170 3dd36041 Reimar Döffinger
                mov_read_glbl(c, pb, fake_atom);
1171 cc8d87b7 Michael Niedermayer
            st->codec->codec_id= id;
1172 6cdbff63 David Conrad
            st->codec->width = sc->width;
1173
            st->codec->height = sc->height;
1174 de23f234 Baptiste Coudurier
        } else {
1175
            /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1176
            url_fskip(pb, size - (url_ftell(pb) - start_pos));
1177 6cea494e Zdenek Kabelac
        }
1178 de23f234 Baptiste Coudurier
        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1179
        a.size = size - (url_ftell(pb) - start_pos);
1180 9cf0419b Panagiotis Issaris
        if (a.size > 8) {
1181
            if (mov_read_default(c, pb, a) < 0)
1182
                return -1;
1183
        } else if (a.size > 0)
1184 de23f234 Baptiste Coudurier
            url_fskip(pb, a.size);
1185 6cea494e Zdenek Kabelac
    }
1186 115329f1 Diego Biurrun
1187 72415b2a Stefano Sabatini
    if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1188 302c389e Michael Niedermayer
        st->codec->sample_rate= sc->time_scale;
1189 e31bd3e3 Baptiste Coudurier
1190 d00f8e17 Baptiste Coudurier
    /* special codec parameters handling */
1191 e31bd3e3 Baptiste Coudurier
    switch (st->codec->codec_id) {
1192 b250f9c6 Aurelien Jacobs
#if CONFIG_DV_DEMUXER
1193 b60c0454 Baptiste Coudurier
    case CODEC_ID_DVAUDIO:
1194 8e2fd8e1 Stefano Sabatini
        c->dv_fctx = avformat_alloc_context();
1195 b60c0454 Baptiste Coudurier
        c->dv_demux = dv_init_demux(c->dv_fctx);
1196
        if (!c->dv_demux) {
1197
            av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1198
            return -1;
1199
        }
1200
        sc->dv_audio_container = 1;
1201
        st->codec->codec_id = CODEC_ID_PCM_S16LE;
1202
        break;
1203 989ac5a6 Baptiste Coudurier
#endif
1204 b95319a2 Baptiste Coudurier
    /* no ifdef since parameters are always those */
1205 3f78a3a9 Baptiste Coudurier
    case CODEC_ID_QCELP:
1206 17ad7b24 Baptiste Coudurier
        // force sample rate for qcelp when not stored in mov
1207
        if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1208
            st->codec->sample_rate = 8000;
1209 73b458e3 Kenan Gillet
        st->codec->frame_size= 160;
1210 061f407e Kenan Gillet
        st->codec->channels= 1; /* really needed */
1211 73b458e3 Kenan Gillet
        break;
1212 b95319a2 Baptiste Coudurier
    case CODEC_ID_AMR_NB:
1213 aeb62788 Baptiste Coudurier
    case CODEC_ID_AMR_WB:
1214 cfb5a2ab Baptiste Coudurier
        st->codec->frame_size= sc->samples_per_frame;
1215 b95319a2 Baptiste Coudurier
        st->codec->channels= 1; /* really needed */
1216 f06188d5 Baptiste Coudurier
        /* force sample rate for amr, stsd in 3gp does not store sample rate */
1217 5b9ce252 Baptiste Coudurier
        if (st->codec->codec_id == CODEC_ID_AMR_NB)
1218 f06188d5 Baptiste Coudurier
            st->codec->sample_rate = 8000;
1219 5b9ce252 Baptiste Coudurier
        else if (st->codec->codec_id == CODEC_ID_AMR_WB)
1220
            st->codec->sample_rate = 16000;
1221 b95319a2 Baptiste Coudurier
        break;
1222 a41104f8 Michael Niedermayer
    case CODEC_ID_MP2:
1223 c59f24e6 Baptiste Coudurier
    case CODEC_ID_MP3:
1224 72415b2a Stefano Sabatini
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1225 57004ff1 Aurelien Jacobs
        st->need_parsing = AVSTREAM_PARSE_FULL;
1226 a41104f8 Michael Niedermayer
        break;
1227 5610f20e Baptiste Coudurier
    case CODEC_ID_GSM:
1228 74e9b9ae Baptiste Coudurier
    case CODEC_ID_ADPCM_MS:
1229
    case CODEC_ID_ADPCM_IMA_WAV:
1230 d4e0130e Baptiste Coudurier
        st->codec->frame_size = sc->samples_per_frame;
1231 74e9b9ae Baptiste Coudurier
        st->codec->block_align = sc->bytes_per_frame;
1232
        break;
1233 be511925 Baptiste Coudurier
    case CODEC_ID_ALAC:
1234 a1532824 Baptiste Coudurier
        if (st->codec->extradata_size == 36) {
1235 364df7b7 Baptiste Coudurier
            st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1236
            st->codec->channels   = AV_RB8 (st->codec->extradata+21);
1237 c6f1e29a Baptiste Coudurier
            st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1238 a1532824 Baptiste Coudurier
        }
1239 be511925 Baptiste Coudurier
        break;
1240 e31bd3e3 Baptiste Coudurier
    default:
1241
        break;
1242
    }
1243 5cd62665 Zdenek Kabelac
1244 6cea494e Zdenek Kabelac
    return 0;
1245
}
1246
1247 dc2cabd0 Martin Storsjö
static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1248
{
1249
    int entries;
1250
1251
    get_byte(pb); /* version */
1252
    get_be24(pb); /* flags */
1253
    entries = get_be32(pb);
1254
1255
    return ff_mov_read_stsd_entries(c, pb, entries);
1256
}
1257
1258 c3e92a6c Baptiste Coudurier
static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1259 6cea494e Zdenek Kabelac
{
1260 6a63ff19 Baptiste Coudurier
    AVStream *st;
1261
    MOVStreamContext *sc;
1262 568e18b1 Michael Niedermayer
    unsigned int i, entries;
1263 b6a17df4 Zdenek Kabelac
1264 6a63ff19 Baptiste Coudurier
    if (c->fc->nb_streams < 1)
1265
        return 0;
1266
    st = c->fc->streams[c->fc->nb_streams-1];
1267
    sc = st->priv_data;
1268
1269 6cea494e Zdenek Kabelac
    get_byte(pb); /* version */
1270 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1271 6cea494e Zdenek Kabelac
1272
    entries = get_be32(pb);
1273 115329f1 Diego Biurrun
1274 f8c18cd7 Baptiste Coudurier
    dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1275
1276 0d8f0abf Baptiste Coudurier
    if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
1277
        return -1;
1278 04e06cfa Baptiste Coudurier
    sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1279
    if (!sc->stsc_data)
1280 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1281
    sc->stsc_count = entries;
1282
1283 6cea494e Zdenek Kabelac
    for(i=0; i<entries; i++) {
1284 04e06cfa Baptiste Coudurier
        sc->stsc_data[i].first = get_be32(pb);
1285
        sc->stsc_data[i].count = get_be32(pb);
1286
        sc->stsc_data[i].id = get_be32(pb);
1287 6cea494e Zdenek Kabelac
    }
1288
    return 0;
1289
}
1290
1291 171a3531 Baptiste Coudurier
static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1292
{
1293
    AVStream *st;
1294
    MOVStreamContext *sc;
1295
    unsigned i, entries;
1296
1297
    if (c->fc->nb_streams < 1)
1298
        return 0;
1299
    st = c->fc->streams[c->fc->nb_streams-1];
1300
    sc = st->priv_data;
1301
1302
    get_be32(pb); // version + flags
1303
1304
    entries = get_be32(pb);
1305
    if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1306
        return -1;
1307
    sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1308
    if (!sc->stps_data)
1309
        return AVERROR(ENOMEM);
1310
    sc->stps_count = entries;
1311
1312
    for (i = 0; i < entries; i++) {
1313
        sc->stps_data[i] = get_be32(pb);
1314
        //dprintf(c->fc, "stps %d\n", sc->stps_data[i]);
1315
    }
1316
1317
    return 0;
1318
}
1319
1320 c3e92a6c Baptiste Coudurier
static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1321 247d56f5 Brian Becker
{
1322 6a63ff19 Baptiste Coudurier
    AVStream *st;
1323
    MOVStreamContext *sc;
1324 568e18b1 Michael Niedermayer
    unsigned int i, entries;
1325 247d56f5 Brian Becker
1326 6a63ff19 Baptiste Coudurier
    if (c->fc->nb_streams < 1)
1327
        return 0;
1328
    st = c->fc->streams[c->fc->nb_streams-1];
1329
    sc = st->priv_data;
1330
1331 247d56f5 Brian Becker
    get_byte(pb); /* version */
1332 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1333 247d56f5 Brian Becker
1334
    entries = get_be32(pb);
1335 115329f1 Diego Biurrun
1336 0d8f0abf Baptiste Coudurier
    dprintf(c->fc, "keyframe_count = %d\n", entries);
1337
1338 1c02d96f Baptiste Coudurier
    if(entries >= UINT_MAX / sizeof(int))
1339 568e18b1 Michael Niedermayer
        return -1;
1340 1c02d96f Baptiste Coudurier
    sc->keyframes = av_malloc(entries * sizeof(int));
1341 247d56f5 Brian Becker
    if (!sc->keyframes)
1342 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1343
    sc->keyframe_count = entries;
1344
1345 247d56f5 Brian Becker
    for(i=0; i<entries; i++) {
1346
        sc->keyframes[i] = get_be32(pb);
1347 f8c18cd7 Baptiste Coudurier
        //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1348 247d56f5 Brian Becker
    }
1349
    return 0;
1350
}
1351
1352 c3e92a6c Baptiste Coudurier
static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1353 6cea494e Zdenek Kabelac
{
1354 6a63ff19 Baptiste Coudurier
    AVStream *st;
1355
    MOVStreamContext *sc;
1356 bd27eed6 Alex Converse
    unsigned int i, entries, sample_size, field_size, num_bytes;
1357
    GetBitContext gb;
1358
    unsigned char* buf;
1359 b6a17df4 Zdenek Kabelac
1360 6a63ff19 Baptiste Coudurier
    if (c->fc->nb_streams < 1)
1361
        return 0;
1362
    st = c->fc->streams[c->fc->nb_streams-1];
1363
    sc = st->priv_data;
1364
1365 6cea494e Zdenek Kabelac
    get_byte(pb); /* version */
1366 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1367 5cd62665 Zdenek Kabelac
1368 bd27eed6 Alex Converse
    if (atom.type == MKTAG('s','t','s','z')) {
1369 d0dab0ec Alex Converse
        sample_size = get_be32(pb);
1370
        if (!sc->sample_size) /* do not overwrite value computed in stsd */
1371
            sc->sample_size = sample_size;
1372
        field_size = 32;
1373 bd27eed6 Alex Converse
    } else {
1374
        sample_size = 0;
1375
        get_be24(pb); /* reserved */
1376
        field_size = get_byte(pb);
1377
    }
1378 6cea494e Zdenek Kabelac
    entries = get_be32(pb);
1379 0d8f0abf Baptiste Coudurier
1380
    dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1381 568e18b1 Michael Niedermayer
1382 6cea494e Zdenek Kabelac
    sc->sample_count = entries;
1383 b72708f8 Baptiste Coudurier
    if (sample_size)
1384
        return 0;
1385
1386 bd27eed6 Alex Converse
    if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1387
        av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1388
        return -1;
1389
    }
1390
1391 e4bc8af1 Baptiste Coudurier
    if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1392 0d8f0abf Baptiste Coudurier
        return -1;
1393 1c02d96f Baptiste Coudurier
    sc->sample_sizes = av_malloc(entries * sizeof(int));
1394 b6a17df4 Zdenek Kabelac
    if (!sc->sample_sizes)
1395 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1396
1397 bd27eed6 Alex Converse
    num_bytes = (entries*field_size+4)>>3;
1398
1399 08a5b4e9 Baptiste Coudurier
    buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1400 bd27eed6 Alex Converse
    if (!buf) {
1401
        av_freep(&sc->sample_sizes);
1402
        return AVERROR(ENOMEM);
1403
    }
1404
1405
    if (get_buffer(pb, buf, num_bytes) < num_bytes) {
1406
        av_freep(&sc->sample_sizes);
1407
        av_free(buf);
1408
        return -1;
1409
    }
1410
1411
    init_get_bits(&gb, buf, 8*num_bytes);
1412
1413 eb61405a Baptiste Coudurier
    for(i=0; i<entries; i++)
1414 bd27eed6 Alex Converse
        sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1415
1416
    av_free(buf);
1417 6cea494e Zdenek Kabelac
    return 0;
1418
}
1419
1420 c3e92a6c Baptiste Coudurier
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1421 0147f198 François Revol
{
1422 6a63ff19 Baptiste Coudurier
    AVStream *st;
1423
    MOVStreamContext *sc;
1424 568e18b1 Michael Niedermayer
    unsigned int i, entries;
1425 d957696f Michael Niedermayer
    int64_t duration=0;
1426
    int64_t total_sample_count=0;
1427 b6a17df4 Zdenek Kabelac
1428 6a63ff19 Baptiste Coudurier
    if (c->fc->nb_streams < 1)
1429
        return 0;
1430
    st = c->fc->streams[c->fc->nb_streams-1];
1431
    sc = st->priv_data;
1432
1433 0147f198 François Revol
    get_byte(pb); /* version */
1434 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1435 0147f198 François Revol
    entries = get_be32(pb);
1436 0d8f0abf Baptiste Coudurier
1437
    dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1438
1439 c3e92a6c Baptiste Coudurier
    if(entries >= UINT_MAX / sizeof(*sc->stts_data))
1440 568e18b1 Michael Niedermayer
        return -1;
1441 c3e92a6c Baptiste Coudurier
    sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1442 c1da59fa Baptiste Coudurier
    if (!sc->stts_data)
1443 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1444
    sc->stts_count = entries;
1445 cd7352d5 Michael Niedermayer
1446 0147f198 François Revol
    for(i=0; i<entries; i++) {
1447 cd461d48 Michael Niedermayer
        int sample_duration;
1448
        int sample_count;
1449 0147f198 François Revol
1450 891f64b3 joca@rixmail.se
        sample_count=get_be32(pb);
1451 0147f198 François Revol
        sample_duration = get_be32(pb);
1452 cd7352d5 Michael Niedermayer
        sc->stts_data[i].count= sample_count;
1453
        sc->stts_data[i].duration= sample_duration;
1454
1455 318c5e05 Michel Bardiaux
        dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1456 4e5ef14f Baptiste Coudurier
1457 7e815047 Baptiste Coudurier
        duration+=(int64_t)sample_duration*sample_count;
1458 891f64b3 joca@rixmail.se
        total_sample_count+=sample_count;
1459
    }
1460
1461 961e0ccd Michael Niedermayer
    st->nb_frames= total_sample_count;
1462
    if(duration)
1463
        st->duration= duration;
1464 0147f198 François Revol
    return 0;
1465
}
1466
1467 c3e92a6c Baptiste Coudurier
static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1468 c4ac052b Michael Niedermayer
{
1469 6a63ff19 Baptiste Coudurier
    AVStream *st;
1470
    MOVStreamContext *sc;
1471 c4ac052b Michael Niedermayer
    unsigned int i, entries;
1472
1473 6a63ff19 Baptiste Coudurier
    if (c->fc->nb_streams < 1)
1474
        return 0;
1475
    st = c->fc->streams[c->fc->nb_streams-1];
1476
    sc = st->priv_data;
1477
1478 c4ac052b Michael Niedermayer
    get_byte(pb); /* version */
1479 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1480 c4ac052b Michael Niedermayer
    entries = get_be32(pb);
1481 0d8f0abf Baptiste Coudurier
1482
    dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1483
1484 c3e92a6c Baptiste Coudurier
    if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
1485 c4ac052b Michael Niedermayer
        return -1;
1486 c3e92a6c Baptiste Coudurier
    sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1487 c1da59fa Baptiste Coudurier
    if (!sc->ctts_data)
1488 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
1489
    sc->ctts_count = entries;
1490 4e5ef14f Baptiste Coudurier
1491 c4ac052b Michael Niedermayer
    for(i=0; i<entries; i++) {
1492 70a61ed4 Michael Niedermayer
        int count    =get_be32(pb);
1493
        int duration =get_be32(pb);
1494
1495
        sc->ctts_data[i].count   = count;
1496
        sc->ctts_data[i].duration= duration;
1497 e7452721 Baptiste Coudurier
        if (duration < 0)
1498
            sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1499 c4ac052b Michael Niedermayer
    }
1500 e7452721 Baptiste Coudurier
1501 bddc2df5 Baptiste Coudurier
    dprintf(c->fc, "dts shift %d\n", sc->dts_shift);
1502 e7452721 Baptiste Coudurier
1503 c4ac052b Michael Niedermayer
    return 0;
1504
}
1505
1506 1e77810d Baptiste Coudurier
static void mov_build_index(MOVContext *mov, AVStream *st)
1507
{
1508
    MOVStreamContext *sc = st->priv_data;
1509 bc5c918e Diego Biurrun
    int64_t current_offset;
1510 1e77810d Baptiste Coudurier
    int64_t current_dts = 0;
1511
    unsigned int stts_index = 0;
1512
    unsigned int stsc_index = 0;
1513
    unsigned int stss_index = 0;
1514 171a3531 Baptiste Coudurier
    unsigned int stps_index = 0;
1515 1e77810d Baptiste Coudurier
    unsigned int i, j;
1516 c5898e86 haim alon
    uint64_t stream_size = 0;
1517 1e77810d Baptiste Coudurier
1518 baf2ffd3 Baptiste Coudurier
    /* adjust first dts according to edit list */
1519 c3024f9e Baptiste Coudurier
    if (sc->time_offset && mov->time_scale > 0) {
1520 2ac736a6 Reimar Döffinger
        int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
1521 bbe46bc4 Baptiste Coudurier
        current_dts = -rescaled;
1522 4af7166f Baptiste Coudurier
        if (sc->ctts_data && sc->stts_data &&
1523
            sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1524 f03a081d Baptiste Coudurier
            /* more than 16 frames delay, dts are likely wrong
1525
               this happens with files created by iMovie */
1526
            sc->wrong_dts = 1;
1527
            st->codec->has_b_frames = 1;
1528
        }
1529 baf2ffd3 Baptiste Coudurier
    }
1530
1531 d3bc61ac Baptiste Coudurier
    /* only use old uncompressed audio chunk demuxing when stts specifies it */
1532 72415b2a Stefano Sabatini
    if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1533 d3bc61ac Baptiste Coudurier
          sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1534 1e77810d Baptiste Coudurier
        unsigned int current_sample = 0;
1535
        unsigned int stts_sample = 0;
1536 171a3531 Baptiste Coudurier
        unsigned int sample_size;
1537 1e77810d Baptiste Coudurier
        unsigned int distance = 0;
1538
        int key_off = sc->keyframes && sc->keyframes[0] == 1;
1539
1540 4b29ed39 Baptiste Coudurier
        current_dts -= sc->dts_shift;
1541
1542 987e857f Baptiste Coudurier
        if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
1543
            return;
1544
        st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
1545
        if (!st->index_entries)
1546
            return;
1547
        st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
1548
1549 1e77810d Baptiste Coudurier
        for (i = 0; i < sc->chunk_count; i++) {
1550
            current_offset = sc->chunk_offsets[i];
1551 04e06cfa Baptiste Coudurier
            if (stsc_index + 1 < sc->stsc_count &&
1552
                i + 1 == sc->stsc_data[stsc_index + 1].first)
1553 1e77810d Baptiste Coudurier
                stsc_index++;
1554 04e06cfa Baptiste Coudurier
            for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1555 171a3531 Baptiste Coudurier
                int keyframe = 0;
1556 1e77810d Baptiste Coudurier
                if (current_sample >= sc->sample_count) {
1557
                    av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1558 f0f2218d Baptiste Coudurier
                    return;
1559 1e77810d Baptiste Coudurier
                }
1560 171a3531 Baptiste Coudurier
1561
                if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1562
                    keyframe = 1;
1563 1e77810d Baptiste Coudurier
                    if (stss_index + 1 < sc->keyframe_count)
1564
                        stss_index++;
1565 171a3531 Baptiste Coudurier
                } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1566
                    keyframe = 1;
1567
                    if (stps_index + 1 < sc->stps_count)
1568
                        stps_index++;
1569 1e77810d Baptiste Coudurier
                }
1570 171a3531 Baptiste Coudurier
                if (keyframe)
1571
                    distance = 0;
1572 1e77810d Baptiste Coudurier
                sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1573 978677a7 Baptiste Coudurier
                if(sc->pseudo_stream_id == -1 ||
1574 04e06cfa Baptiste Coudurier
                   sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1575 987e857f Baptiste Coudurier
                    AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1576
                    e->pos = current_offset;
1577
                    e->timestamp = current_dts;
1578
                    e->size = sample_size;
1579
                    e->min_distance = distance;
1580
                    e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1581 585dac65 Baptiste Coudurier
                    dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1582
                            "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1583
                            current_offset, current_dts, sample_size, distance, keyframe);
1584
                }
1585 6c00a9de Baptiste Coudurier
1586 1e77810d Baptiste Coudurier
                current_offset += sample_size;
1587 c5898e86 haim alon
                stream_size += sample_size;
1588 bbe46bc4 Baptiste Coudurier
                current_dts += sc->stts_data[stts_index].duration;
1589 1e77810d Baptiste Coudurier
                distance++;
1590
                stts_sample++;
1591
                current_sample++;
1592
                if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1593
                    stts_sample = 0;
1594
                    stts_index++;
1595
                }
1596
            }
1597
        }
1598 fedb1eca Baptiste Coudurier
        if (st->duration > 0)
1599
            st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1600 7e69621f Baptiste Coudurier
    } else {
1601 987e857f Baptiste Coudurier
        unsigned chunk_samples, total = 0;
1602 7e69621f Baptiste Coudurier
1603 987e857f Baptiste Coudurier
        // compute total chunk count
1604
        for (i = 0; i < sc->stsc_count; i++) {
1605
            unsigned count, chunk_count;
1606 7e69621f Baptiste Coudurier
1607 987e857f Baptiste Coudurier
            chunk_samples = sc->stsc_data[i].count;
1608 7e69621f Baptiste Coudurier
            if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1609
                av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1610
                return;
1611
            }
1612
1613 987e857f Baptiste Coudurier
            if (sc->samples_per_frame >= 160) { // gsm
1614
                count = chunk_samples / sc->samples_per_frame;
1615
            } else if (sc->samples_per_frame > 1) {
1616
                unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1617
                count = (chunk_samples+samples-1) / samples;
1618
            } else {
1619
                count = (chunk_samples+1023) / 1024;
1620
            }
1621
1622
            if (i < sc->stsc_count - 1)
1623
                chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1624
            else
1625
                chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1626
            total += chunk_count * count;
1627
        }
1628
1629
        dprintf(mov->fc, "chunk count %d\n", total);
1630
        if (total >= UINT_MAX / sizeof(*st->index_entries))
1631
            return;
1632
        st->index_entries = av_malloc(total*sizeof(*st->index_entries));
1633
        if (!st->index_entries)
1634
            return;
1635
        st->index_entries_allocated_size = total*sizeof(*st->index_entries);
1636
1637
        // populate index
1638
        for (i = 0; i < sc->chunk_count; i++) {
1639
            current_offset = sc->chunk_offsets[i];
1640
            if (stsc_index + 1 < sc->stsc_count &&
1641
                i + 1 == sc->stsc_data[stsc_index + 1].first)
1642
                stsc_index++;
1643
            chunk_samples = sc->stsc_data[stsc_index].count;
1644
1645 7e69621f Baptiste Coudurier
            while (chunk_samples > 0) {
1646 987e857f Baptiste Coudurier
                AVIndexEntry *e;
1647 7e69621f Baptiste Coudurier
                unsigned size, samples;
1648
1649
                if (sc->samples_per_frame >= 160) { // gsm
1650
                    samples = sc->samples_per_frame;
1651
                    size = sc->bytes_per_frame;
1652
                } else {
1653
                    if (sc->samples_per_frame > 1) {
1654
                        samples = FFMIN((1024 / sc->samples_per_frame)*
1655
                                        sc->samples_per_frame, chunk_samples);
1656
                        size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1657 1e77810d Baptiste Coudurier
                    } else {
1658 7e69621f Baptiste Coudurier
                        samples = FFMIN(1024, chunk_samples);
1659
                        size = samples * sc->sample_size;
1660 1e77810d Baptiste Coudurier
                    }
1661
                }
1662 7e69621f Baptiste Coudurier
1663 987e857f Baptiste Coudurier
                if (st->nb_index_entries >= total) {
1664
                    av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1665
                    return;
1666
                }
1667
                e = &st->index_entries[st->nb_index_entries++];
1668
                e->pos = current_offset;
1669
                e->timestamp = current_dts;
1670
                e->size = size;
1671
                e->min_distance = 0;
1672
                e->flags = AVINDEX_KEYFRAME;
1673 117a9190 Baptiste Coudurier
                dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1674
                        "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1675 7e69621f Baptiste Coudurier
                        size, samples);
1676
1677
                current_offset += size;
1678 bbe46bc4 Baptiste Coudurier
                current_dts += samples;
1679 7e69621f Baptiste Coudurier
                chunk_samples -= samples;
1680 1e77810d Baptiste Coudurier
            }
1681
        }
1682
    }
1683
}
1684 bd991df2 Baptiste Coudurier
1685 adeb9071 Baptiste Coudurier
static int mov_open_dref(ByteIOContext **pb, char *src, MOVDref *ref)
1686
{
1687 6a245905 Michael Niedermayer
    /* try relative path, we do not try the absolute because it can leak information about our
1688
       system to an attacker */
1689 adeb9071 Baptiste Coudurier
    if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1690
        char filename[1024];
1691
        char *src_path;
1692
        int i, l;
1693
1694
        /* find a source dir */
1695
        src_path = strrchr(src, '/');
1696
        if (src_path)
1697
            src_path++;
1698
        else
1699
            src_path = src;
1700
1701
        /* find a next level down to target */
1702
        for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1703
            if (ref->path[l] == '/') {
1704
                if (i == ref->nlvl_to - 1)
1705
                    break;
1706
                else
1707
                    i++;
1708
            }
1709
1710
        /* compose filename if next level down to target was found */
1711 bbdf0d22 Michael Niedermayer
        if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
1712 adeb9071 Baptiste Coudurier
            memcpy(filename, src, src_path - src);
1713
            filename[src_path - src] = 0;
1714
1715
            for (i = 1; i < ref->nlvl_from; i++)
1716
                av_strlcat(filename, "../", 1024);
1717
1718
            av_strlcat(filename, ref->path + l + 1, 1024);
1719
1720
            if (!url_fopen(pb, filename, URL_RDONLY))
1721
                return 0;
1722
        }
1723
    }
1724
1725
    return AVERROR(ENOENT);
1726
};
1727
1728 c3e92a6c Baptiste Coudurier
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1729 5ca1d879 Zdenek Kabelac
{
1730
    AVStream *st;
1731
    MOVStreamContext *sc;
1732 bd991df2 Baptiste Coudurier
    int ret;
1733 5ca1d879 Zdenek Kabelac
1734
    st = av_new_stream(c->fc, c->fc->nb_streams);
1735 3efe8848 Baptiste Coudurier
    if (!st) return AVERROR(ENOMEM);
1736 9a630c25 Baptiste Coudurier
    sc = av_mallocz(sizeof(MOVStreamContext));
1737 2922cbdb Baptiste Coudurier
    if (!sc) return AVERROR(ENOMEM);
1738 5ca1d879 Zdenek Kabelac
1739
    st->priv_data = sc;
1740 72415b2a Stefano Sabatini
    st->codec->codec_type = AVMEDIA_TYPE_DATA;
1741 64d50fa5 Baptiste Coudurier
    sc->ffindex = st->index;
1742 5ca1d879 Zdenek Kabelac
1743 bd991df2 Baptiste Coudurier
    if ((ret = mov_read_default(c, pb, atom)) < 0)
1744
        return ret;
1745
1746
    /* sanity checks */
1747 6c00a9de Baptiste Coudurier
    if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1748
                            (!sc->sample_size && !sc->sample_count))) {
1749 6282c5f4 Baptiste Coudurier
        av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1750
               st->index);
1751 bd991df2 Baptiste Coudurier
        return 0;
1752
    }
1753 6c00a9de Baptiste Coudurier
1754 c3024f9e Baptiste Coudurier
    if (sc->time_scale <= 0) {
1755 507330b9 Baptiste Coudurier
        av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
1756 6c00a9de Baptiste Coudurier
        sc->time_scale = c->time_scale;
1757 c3024f9e Baptiste Coudurier
        if (sc->time_scale <= 0)
1758 507330b9 Baptiste Coudurier
            sc->time_scale = 1;
1759
    }
1760 6c00a9de Baptiste Coudurier
1761 bbe46bc4 Baptiste Coudurier
    av_set_pts_info(st, 64, 1, sc->time_scale);
1762 bd991df2 Baptiste Coudurier
1763 72415b2a Stefano Sabatini
    if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1764 5b4f5e5d Baptiste Coudurier
        !st->codec->frame_size && sc->stts_count == 1) {
1765
        st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
1766
                                           st->codec->sample_rate, sc->time_scale);
1767
        dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
1768
    }
1769 bd991df2 Baptiste Coudurier
1770
    mov_build_index(c, st);
1771
1772
    if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1773 adeb9071 Baptiste Coudurier
        MOVDref *dref = &sc->drefs[sc->dref_id - 1];
1774
        if (mov_open_dref(&sc->pb, c->fc->filename, dref) < 0)
1775
            av_log(c->fc, AV_LOG_ERROR,
1776
                   "stream %d, error opening alias: path='%s', dir='%s', "
1777
                   "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
1778
                   st->index, dref->path, dref->dir, dref->filename,
1779
                   dref->volume, dref->nlvl_from, dref->nlvl_to);
1780 bd991df2 Baptiste Coudurier
    } else
1781
        sc->pb = c->fc->pb;
1782
1783 72415b2a Stefano Sabatini
    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1784 525fcb27 Andrew Wason
        if (!st->sample_aspect_ratio.num &&
1785
            (st->codec->width != sc->width || st->codec->height != sc->height)) {
1786
            st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
1787
                                             ((double)st->codec->width * sc->height), INT_MAX);
1788 c3aeaa54 Baptiste Coudurier
        }
1789
1790
        av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1791
                  sc->time_scale*st->nb_frames, st->duration, INT_MAX);
1792 f6253caf Baptiste Coudurier
1793
        if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
1794
            av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
1795
                      sc->time_scale, sc->stts_data[0].duration, INT_MAX);
1796 c9566115 Baptiste Coudurier
    }
1797
1798 bd991df2 Baptiste Coudurier
    switch (st->codec->codec_id) {
1799 b250f9c6 Aurelien Jacobs
#if CONFIG_H261_DECODER
1800 bd991df2 Baptiste Coudurier
    case CODEC_ID_H261:
1801
#endif
1802 b250f9c6 Aurelien Jacobs
#if CONFIG_H263_DECODER
1803 bd991df2 Baptiste Coudurier
    case CODEC_ID_H263:
1804
#endif
1805 a0dd3c00 Baptiste Coudurier
#if CONFIG_H264_DECODER
1806
    case CODEC_ID_H264:
1807
#endif
1808 b250f9c6 Aurelien Jacobs
#if CONFIG_MPEG4_DECODER
1809 bd991df2 Baptiste Coudurier
    case CODEC_ID_MPEG4:
1810
#endif
1811 6c00a9de Baptiste Coudurier
        st->codec->width = 0; /* let decoder init width/height */
1812 bd991df2 Baptiste Coudurier
        st->codec->height= 0;
1813
        break;
1814
    }
1815 f9900374 Baptiste Coudurier
1816
    /* Do not need those anymore. */
1817
    av_freep(&sc->chunk_offsets);
1818 04e06cfa Baptiste Coudurier
    av_freep(&sc->stsc_data);
1819 f9900374 Baptiste Coudurier
    av_freep(&sc->sample_sizes);
1820
    av_freep(&sc->keyframes);
1821
    av_freep(&sc->stts_data);
1822 171a3531 Baptiste Coudurier
    av_freep(&sc->stps_data);
1823 f9900374 Baptiste Coudurier
1824 bd991df2 Baptiste Coudurier
    return 0;
1825 5ca1d879 Zdenek Kabelac
}
1826
1827 c3e92a6c Baptiste Coudurier
static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1828 51c15201 Baptiste Coudurier
{
1829
    int ret;
1830
    c->itunes_metadata = 1;
1831
    ret = mov_read_default(c, pb, atom);
1832
    c->itunes_metadata = 0;
1833
    return ret;
1834
}
1835
1836 c3e92a6c Baptiste Coudurier
static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1837 51c15201 Baptiste Coudurier
{
1838 df8843c6 Baptiste Coudurier
    while (atom.size > 8) {
1839
        uint32_t tag = get_le32(pb);
1840
        atom.size -= 4;
1841
        if (tag == MKTAG('h','d','l','r')) {
1842
            url_fseek(pb, -8, SEEK_CUR);
1843
            atom.size += 8;
1844
            return mov_read_default(c, pb, atom);
1845
        }
1846
    }
1847
    return 0;
1848 51c15201 Baptiste Coudurier
}
1849
1850 c3e92a6c Baptiste Coudurier
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1851 5ca1d879 Zdenek Kabelac
{
1852 ec072669 John Schmiederer
    int i;
1853
    int width;
1854
    int height;
1855
    int64_t disp_transform[2];
1856
    int display_matrix[3][2];
1857 6a63ff19 Baptiste Coudurier
    AVStream *st;
1858
    MOVStreamContext *sc;
1859
    int version;
1860
1861
    if (c->fc->nb_streams < 1)
1862
        return 0;
1863
    st = c->fc->streams[c->fc->nb_streams-1];
1864
    sc = st->priv_data;
1865 5ca1d879 Zdenek Kabelac
1866 6a63ff19 Baptiste Coudurier
    version = get_byte(pb);
1867 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
1868 5ca1d879 Zdenek Kabelac
    /*
1869
    MOV_TRACK_ENABLED 0x0001
1870
    MOV_TRACK_IN_MOVIE 0x0002
1871
    MOV_TRACK_IN_PREVIEW 0x0004
1872
    MOV_TRACK_IN_POSTER 0x0008
1873
    */
1874
1875 1175561e Baptiste Coudurier
    if (version == 1) {
1876
        get_be64(pb);
1877
        get_be64(pb);
1878
    } else {
1879
        get_be32(pb); /* creation time */
1880
        get_be32(pb); /* modification time */
1881
    }
1882 5ca1d879 Zdenek Kabelac
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1883
    get_be32(pb); /* reserved */
1884 fcdd622c Baptiste Coudurier
1885 117a9190 Baptiste Coudurier
    /* highlevel (considering edits) duration in movie timebase */
1886
    (version == 1) ? get_be64(pb) : get_be32(pb);
1887 5ca1d879 Zdenek Kabelac
    get_be32(pb); /* reserved */
1888
    get_be32(pb); /* reserved */
1889
1890
    get_be16(pb); /* layer */
1891
    get_be16(pb); /* alternate group */
1892
    get_be16(pb); /* volume */
1893
    get_be16(pb); /* reserved */
1894
1895 ec072669 John Schmiederer
    //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
1896
    // they're kept in fixed point format through all calculations
1897
    // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
1898
    for (i = 0; i < 3; i++) {
1899
        display_matrix[i][0] = get_be32(pb);   // 16.16 fixed point
1900
        display_matrix[i][1] = get_be32(pb);   // 16.16 fixed point
1901
        get_be32(pb);           // 2.30 fixed point (not used)
1902
    }
1903 5ca1d879 Zdenek Kabelac
1904 ec072669 John Schmiederer
    width = get_be32(pb);       // 16.16 fixed point track width
1905
    height = get_be32(pb);      // 16.16 fixed point track height
1906 6cdbff63 David Conrad
    sc->width = width >> 16;
1907
    sc->height = height >> 16;
1908 ec072669 John Schmiederer
1909 d862fce7 Baptiste Coudurier
    // transform the display width/height according to the matrix
1910 ec072669 John Schmiederer
    // skip this if the display matrix is the default identity matrix
1911 d862fce7 Baptiste Coudurier
    // or if it is rotating the picture, ex iPhone 3GS
1912 ec072669 John Schmiederer
    // to keep the same scale, use [width height 1<<16]
1913
    if (width && height &&
1914 d862fce7 Baptiste Coudurier
        ((display_matrix[0][0] != 65536  ||
1915
          display_matrix[1][1] != 65536) &&
1916
         !display_matrix[0][1] &&
1917
         !display_matrix[1][0] &&
1918
         !display_matrix[2][0] && !display_matrix[2][1])) {
1919 ec072669 John Schmiederer
        for (i = 0; i < 2; i++)
1920
            disp_transform[i] =
1921
                (int64_t)  width  * display_matrix[0][i] +
1922
                (int64_t)  height * display_matrix[1][i] +
1923
                ((int64_t) display_matrix[2][i] << 16);
1924
1925
        //sample aspect ratio is new width/height divided by old width/height
1926 59729451 Aurelien Jacobs
        st->sample_aspect_ratio = av_d2q(
1927 ec072669 John Schmiederer
            ((double) disp_transform[0] * height) /
1928
            ((double) disp_transform[1] * width), INT_MAX);
1929
    }
1930 5ca1d879 Zdenek Kabelac
    return 0;
1931
}
1932
1933 c3e92a6c Baptiste Coudurier
static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1934 61aedb0f Baptiste Coudurier
{
1935
    MOVFragment *frag = &c->fragment;
1936
    MOVTrackExt *trex = NULL;
1937
    int flags, track_id, i;
1938
1939
    get_byte(pb); /* version */
1940
    flags = get_be24(pb);
1941
1942
    track_id = get_be32(pb);
1943 63581eb1 Alex Converse
    if (!track_id)
1944 61aedb0f Baptiste Coudurier
        return -1;
1945
    frag->track_id = track_id;
1946
    for (i = 0; i < c->trex_count; i++)
1947
        if (c->trex_data[i].track_id == frag->track_id) {
1948
            trex = &c->trex_data[i];
1949
            break;
1950
        }
1951
    if (!trex) {
1952
        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
1953
        return -1;
1954
    }
1955
1956
    if (flags & 0x01) frag->base_data_offset = get_be64(pb);
1957
    else              frag->base_data_offset = frag->moof_offset;
1958
    if (flags & 0x02) frag->stsd_id          = get_be32(pb);
1959
    else              frag->stsd_id          = trex->stsd_id;
1960
1961
    frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
1962
    frag->size     = flags & 0x10 ? get_be32(pb) : trex->size;
1963
    frag->flags    = flags & 0x20 ? get_be32(pb) : trex->flags;
1964
    dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
1965
    return 0;
1966
}
1967
1968 7221579b David Conrad
static int mov_read_chap(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1969
{
1970
    c->chapter_track = get_be32(pb);
1971
    return 0;
1972
}
1973
1974 c3e92a6c Baptiste Coudurier
static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1975 61aedb0f Baptiste Coudurier
{
1976
    MOVTrackExt *trex;
1977
1978
    if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
1979
        return -1;
1980 0d8f0abf Baptiste Coudurier
    trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
1981
    if (!trex)
1982 61aedb0f Baptiste Coudurier
        return AVERROR(ENOMEM);
1983 0d8f0abf Baptiste Coudurier
    c->trex_data = trex;
1984 61aedb0f Baptiste Coudurier
    trex = &c->trex_data[c->trex_count++];
1985
    get_byte(pb); /* version */
1986
    get_be24(pb); /* flags */
1987
    trex->track_id = get_be32(pb);
1988
    trex->stsd_id  = get_be32(pb);
1989
    trex->duration = get_be32(pb);
1990
    trex->size     = get_be32(pb);
1991
    trex->flags    = get_be32(pb);
1992
    return 0;
1993
}
1994
1995 c3e92a6c Baptiste Coudurier
static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1996 61aedb0f Baptiste Coudurier
{
1997
    MOVFragment *frag = &c->fragment;
1998 63581eb1 Alex Converse
    AVStream *st = NULL;
1999 44e43aab Baptiste Coudurier
    MOVStreamContext *sc;
2000 61aedb0f Baptiste Coudurier
    uint64_t offset;
2001
    int64_t dts;
2002
    int data_offset = 0;
2003
    unsigned entries, first_sample_flags = frag->flags;
2004
    int flags, distance, i;
2005
2006 63581eb1 Alex Converse
    for (i = 0; i < c->fc->nb_streams; i++) {
2007
        if (c->fc->streams[i]->id == frag->track_id) {
2008
            st = c->fc->streams[i];
2009
            break;
2010
        }
2011
    }
2012
    if (!st) {
2013
        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2014 44e43aab Baptiste Coudurier
        return -1;
2015 63581eb1 Alex Converse
    }
2016 44e43aab Baptiste Coudurier
    sc = st->priv_data;
2017 61aedb0f Baptiste Coudurier
    if (sc->pseudo_stream_id+1 != frag->stsd_id)
2018
        return 0;
2019
    get_byte(pb); /* version */
2020
    flags = get_be24(pb);
2021
    entries = get_be32(pb);
2022
    dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
2023
    if (flags & 0x001) data_offset        = get_be32(pb);
2024
    if (flags & 0x004) first_sample_flags = get_be32(pb);
2025
    if (flags & 0x800) {
2026 0d8f0abf Baptiste Coudurier
        MOVStts *ctts_data;
2027 61aedb0f Baptiste Coudurier
        if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2028
            return -1;
2029 0d8f0abf Baptiste Coudurier
        ctts_data = av_realloc(sc->ctts_data,
2030
                               (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2031
        if (!ctts_data)
2032 61aedb0f Baptiste Coudurier
            return AVERROR(ENOMEM);
2033 0d8f0abf Baptiste Coudurier
        sc->ctts_data = ctts_data;
2034 61aedb0f Baptiste Coudurier
    }
2035
    dts = st->duration;
2036
    offset = frag->base_data_offset + data_offset;
2037
    distance = 0;
2038
    dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2039
    for (i = 0; i < entries; i++) {
2040
        unsigned sample_size = frag->size;
2041
        int sample_flags = i ? frag->flags : first_sample_flags;
2042
        unsigned sample_duration = frag->duration;
2043
        int keyframe;
2044
2045
        if (flags & 0x100) sample_duration = get_be32(pb);
2046
        if (flags & 0x200) sample_size     = get_be32(pb);
2047
        if (flags & 0x400) sample_flags    = get_be32(pb);
2048
        if (flags & 0x800) {
2049
            sc->ctts_data[sc->ctts_count].count = 1;
2050
            sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
2051
            sc->ctts_count++;
2052
        }
2053 72415b2a Stefano Sabatini
        if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
2054 61aedb0f Baptiste Coudurier
             (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
2055
            distance = 0;
2056
        av_add_index_entry(st, offset, dts, sample_size, distance,
2057
                           keyframe ? AVINDEX_KEYFRAME : 0);
2058
        dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2059
                "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2060
                offset, dts, sample_size, distance, keyframe);
2061
        distance++;
2062 bbe46bc4 Baptiste Coudurier
        dts += sample_duration;
2063 61aedb0f Baptiste Coudurier
        offset += sample_size;
2064
    }
2065
    frag->moof_offset = offset;
2066
    st->duration = dts;
2067
    return 0;
2068
}
2069
2070 5ca1d879 Zdenek Kabelac
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2071
/* like the files created with Adobe Premiere 5.0, for samples see */
2072
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2073 c3e92a6c Baptiste Coudurier
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2074 5ca1d879 Zdenek Kabelac
{
2075
    int err;
2076
2077
    if (atom.size < 8)
2078
        return 0; /* continue */
2079
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2080
        url_fskip(pb, atom.size - 4);
2081
        return 0;
2082
    }
2083
    atom.type = get_le32(pb);
2084
    atom.size -= 8;
2085 1c126b4f Baptiste Coudurier
    if (atom.type != MKTAG('m','d','a','t')) {
2086 5ca1d879 Zdenek Kabelac
        url_fskip(pb, atom.size);
2087
        return 0;
2088
    }
2089
    err = mov_read_mdat(c, pb, atom);
2090
    return err;
2091
}
2092
2093 c3e92a6c Baptiste Coudurier
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2094 0147f198 François Revol
{
2095 b250f9c6 Aurelien Jacobs
#if CONFIG_ZLIB
2096 0147f198 François Revol
    ByteIOContext ctx;
2097 b6a17df4 Zdenek Kabelac
    uint8_t *cmov_data;
2098
    uint8_t *moov_data; /* uncompressed data */
2099 0147f198 François Revol
    long cmov_len, moov_len;
2100 6f04eb1e Albert Astals Cid
    int ret = -1;
2101 b6a17df4 Zdenek Kabelac
2102 0147f198 François Revol
    get_be32(pb); /* dcom atom */
2103 1c126b4f Baptiste Coudurier
    if (get_le32(pb) != MKTAG('d','c','o','m'))
2104 0147f198 François Revol
        return -1;
2105 1c126b4f Baptiste Coudurier
    if (get_le32(pb) != MKTAG('z','l','i','b')) {
2106 f3592353 Benoit Fouet
        av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2107 0147f198 François Revol
        return -1;
2108
    }
2109
    get_be32(pb); /* cmvd atom */
2110 1c126b4f Baptiste Coudurier
    if (get_le32(pb) != MKTAG('c','m','v','d'))
2111 0147f198 François Revol
        return -1;
2112
    moov_len = get_be32(pb); /* uncompressed size */
2113 5ca1d879 Zdenek Kabelac
    cmov_len = atom.size - 6 * 4;
2114 5cd62665 Zdenek Kabelac
2115 9a630c25 Baptiste Coudurier
    cmov_data = av_malloc(cmov_len);
2116 0147f198 François Revol
    if (!cmov_data)
2117 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
2118 9a630c25 Baptiste Coudurier
    moov_data = av_malloc(moov_len);
2119 0147f198 François Revol
    if (!moov_data) {
2120
        av_free(cmov_data);
2121 0d8f0abf Baptiste Coudurier
        return AVERROR(ENOMEM);
2122 0147f198 François Revol
    }
2123
    get_buffer(pb, cmov_data, cmov_len);
2124 b6a17df4 Zdenek Kabelac
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2125 6f04eb1e Albert Astals Cid
        goto free_and_return;
2126 942f3bb5 Michael Niedermayer
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2127 6f04eb1e Albert Astals Cid
        goto free_and_return;
2128 1c126b4f Baptiste Coudurier
    atom.type = MKTAG('m','o','o','v');
2129 5ca1d879 Zdenek Kabelac
    atom.size = moov_len;
2130 9ed83b0a Zdenek Kabelac
#ifdef DEBUG
2131 dbb4f00a Michael Niedermayer
//    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
2132 9ed83b0a Zdenek Kabelac
#endif
2133 5ca1d879 Zdenek Kabelac
    ret = mov_read_default(c, &ctx, atom);
2134 6f04eb1e Albert Astals Cid
free_and_return:
2135 0147f198 François Revol
    av_free(moov_data);
2136
    av_free(cmov_data);
2137
    return ret;
2138 d966b2f0 Baptiste Coudurier
#else
2139
    av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2140
    return -1;
2141 0147f198 François Revol
#endif
2142 d966b2f0 Baptiste Coudurier
}
2143 0147f198 François Revol
2144 baf25c9d Gael Chardon
/* edit list atom */
2145 c3e92a6c Baptiste Coudurier
static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2146 baf25c9d Gael Chardon
{
2147 1c4bf2ec Baptiste Coudurier
    MOVStreamContext *sc;
2148 e0977c80 Baptiste Coudurier
    int i, edit_count;
2149
2150 1c4bf2ec Baptiste Coudurier
    if (c->fc->nb_streams < 1)
2151
        return 0;
2152
    sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2153
2154 e0977c80 Baptiste Coudurier
    get_byte(pb); /* version */
2155 23f08617 Baptiste Coudurier
    get_be24(pb); /* flags */
2156 1975c52c Baptiste Coudurier
    edit_count = get_be32(pb); /* entries */
2157 e0977c80 Baptiste Coudurier
2158 53e099de Baptiste Coudurier
    if((uint64_t)edit_count*12+8 > atom.size)
2159
        return -1;
2160
2161 e0977c80 Baptiste Coudurier
    for(i=0; i<edit_count; i++){
2162 d435e520 Baptiste Coudurier
        int time;
2163 2ac736a6 Reimar Döffinger
        int duration = get_be32(pb); /* Track duration */
2164 d435e520 Baptiste Coudurier
        time = get_be32(pb); /* Media time */
2165 e0977c80 Baptiste Coudurier
        get_be32(pb); /* Media rate */
2166 2ac736a6 Reimar Döffinger
        if (i == 0 && time >= -1) {
2167
            sc->time_offset = time != -1 ? time : -duration;
2168 a5929abe Baptiste Coudurier
        }
2169 e0977c80 Baptiste Coudurier
    }
2170 baf2ffd3 Baptiste Coudurier
2171
    if(edit_count > 1)
2172
        av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2173
               "a/v desync might occur, patch welcome\n");
2174
2175 4c125b8f Baptiste Coudurier
    dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2176 e0977c80 Baptiste Coudurier
    return 0;
2177 baf25c9d Gael Chardon
}
2178
2179 6cea494e Zdenek Kabelac
static const MOVParseTableEntry mov_default_parse_table[] = {
2180 d4fdba0d Baptiste Coudurier
{ MKTAG('a','v','s','s'), mov_read_extradata },
2181 1cf9f6ed David Conrad
{ MKTAG('c','h','p','l'), mov_read_chpl },
2182 1c126b4f Baptiste Coudurier
{ MKTAG('c','o','6','4'), mov_read_stco },
2183
{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2184
{ MKTAG('d','i','n','f'), mov_read_default },
2185
{ MKTAG('d','r','e','f'), mov_read_dref },
2186
{ MKTAG('e','d','t','s'), mov_read_default },
2187
{ MKTAG('e','l','s','t'), mov_read_elst },
2188
{ MKTAG('e','n','d','a'), mov_read_enda },
2189
{ MKTAG('f','i','e','l'), mov_read_extradata },
2190
{ MKTAG('f','t','y','p'), mov_read_ftyp },
2191
{ MKTAG('g','l','b','l'), mov_read_glbl },
2192
{ MKTAG('h','d','l','r'), mov_read_hdlr },
2193 51c15201 Baptiste Coudurier
{ MKTAG('i','l','s','t'), mov_read_ilst },
2194 1c126b4f Baptiste Coudurier
{ MKTAG('j','p','2','h'), mov_read_extradata },
2195
{ MKTAG('m','d','a','t'), mov_read_mdat },
2196
{ MKTAG('m','d','h','d'), mov_read_mdhd },
2197
{ MKTAG('m','d','i','a'), mov_read_default },
2198 51c15201 Baptiste Coudurier
{ MKTAG('m','e','t','a'), mov_read_meta },
2199 1c126b4f Baptiste Coudurier
{ MKTAG('m','i','n','f'), mov_read_default },
2200
{ MKTAG('m','o','o','f'), mov_read_moof },
2201
{ MKTAG('m','o','o','v'), mov_read_moov },
2202
{ MKTAG('m','v','e','x'), mov_read_default },
2203
{ MKTAG('m','v','h','d'), mov_read_mvhd },
2204
{ MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2205
{ MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2206
{ MKTAG('a','v','c','C'), mov_read_glbl },
2207 6da54074 Baptiste Coudurier
{ MKTAG('p','a','s','p'), mov_read_pasp },
2208 1c126b4f Baptiste Coudurier
{ MKTAG('s','t','b','l'), mov_read_default },
2209
{ MKTAG('s','t','c','o'), mov_read_stco },
2210 171a3531 Baptiste Coudurier
{ MKTAG('s','t','p','s'), mov_read_stps },
2211 653d7aeb Martin Storsjö
{ MKTAG('s','t','r','f'), mov_read_strf },
2212 1c126b4f Baptiste Coudurier
{ MKTAG('s','t','s','c'), mov_read_stsc },
2213
{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2214
{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2215
{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2216
{ MKTAG('s','t','t','s'), mov_read_stts },
2217 bd27eed6 Alex Converse
{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2218 1c126b4f Baptiste Coudurier
{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2219
{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2220
{ MKTAG('t','r','a','k'), mov_read_trak },
2221
{ MKTAG('t','r','a','f'), mov_read_default },
2222 7221579b David Conrad
{ MKTAG('t','r','e','f'), mov_read_default },
2223
{ MKTAG('c','h','a','p'), mov_read_chap },
2224 1c126b4f Baptiste Coudurier
{ MKTAG('t','r','e','x'), mov_read_trex },
2225
{ MKTAG('t','r','u','n'), mov_read_trun },
2226 86b0affd Baptiste Coudurier
{ MKTAG('u','d','t','a'), mov_read_default },
2227 1c126b4f Baptiste Coudurier
{ MKTAG('w','a','v','e'), mov_read_wave },
2228
{ MKTAG('e','s','d','s'), mov_read_esds },
2229 bdecdd2b Justin Ruggles
{ MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2230 1c126b4f Baptiste Coudurier
{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2231
{ MKTAG('c','m','o','v'), mov_read_cmov },
2232 bcfe2ba0 Baptiste Coudurier
{ 0, NULL }
2233 6cea494e Zdenek Kabelac
};
2234
2235 c9a65ca8 Fabrice Bellard
static int mov_probe(AVProbeData *p)
2236
{
2237 0e7eed09 Fabrice Bellard
    unsigned int offset;
2238
    uint32_t tag;
2239 2497479f François Revol
    int score = 0;
2240 3ffe3793 François Revol
2241 c9a65ca8 Fabrice Bellard
    /* check file header */
2242 0e7eed09 Fabrice Bellard
    offset = 0;
2243
    for(;;) {
2244
        /* ignore invalid offset */
2245
        if ((offset + 8) > (unsigned int)p->buf_size)
2246 2497479f François Revol
            return score;
2247 fead30d4 Alex Beregszaszi
        tag = AV_RL32(p->buf + offset + 4);
2248 0e7eed09 Fabrice Bellard
        switch(tag) {
2249 2497479f François Revol
        /* check for obvious tags */
2250 1c126b4f Baptiste Coudurier
        case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2251
        case MKTAG('m','o','o','v'):
2252
        case MKTAG('m','d','a','t'):
2253
        case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2254
        case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2255 40e7aaa3 Baptiste Coudurier
        case MKTAG('f','t','y','p'):
2256 3ffe3793 François Revol
            return AVPROBE_SCORE_MAX;
2257 2497479f François Revol
        /* those are more common words, so rate then a bit less */
2258 1c126b4f Baptiste Coudurier
        case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2259
        case MKTAG('w','i','d','e'):
2260
        case MKTAG('f','r','e','e'):
2261
        case MKTAG('j','u','n','k'):
2262
        case MKTAG('p','i','c','t'):
2263 2497479f François Revol
            return AVPROBE_SCORE_MAX - 5;
2264 5469b788 Baptiste Coudurier
        case MKTAG(0x82,0x82,0x7f,0x7d):
2265 1c126b4f Baptiste Coudurier
        case MKTAG('s','k','i','p'):
2266
        case MKTAG('u','u','i','d'):
2267
        case MKTAG('p','r','f','l'):
2268 fead30d4 Alex Beregszaszi
            offset = AV_RB32(p->buf+offset) + offset;
2269 2497479f François Revol
            /* if we only find those cause probedata is too small at least rate them */
2270
            score = AVPROBE_SCORE_MAX - 50;
2271 0e7eed09 Fabrice Bellard
            break;
2272
        default:
2273
            /* unrecognized tag */
2274 2497479f François Revol
            return score;
2275 0e7eed09 Fabrice Bellard
        }
2276 3ffe3793 François Revol
    }
2277 2497479f François Revol
    return score;
2278 c9a65ca8 Fabrice Bellard
}
2279
2280 7221579b David Conrad
// must be done after parsing all trak because there's no order requirement
2281
static void mov_read_chapters(AVFormatContext *s)
2282
{
2283
    MOVContext *mov = s->priv_data;
2284
    AVStream *st = NULL;
2285
    MOVStreamContext *sc;
2286
    int64_t cur_pos;
2287 0c468f56 Anton Khirnov
    int i;
2288 7221579b David Conrad
2289
    for (i = 0; i < s->nb_streams; i++)
2290
        if (s->streams[i]->id == mov->chapter_track) {
2291
            st = s->streams[i];
2292
            break;
2293
        }
2294
    if (!st) {
2295
        av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2296
        return;
2297
    }
2298
2299
    st->discard = AVDISCARD_ALL;
2300
    sc = st->priv_data;
2301
    cur_pos = url_ftell(sc->pb);
2302
2303
    for (i = 0; i < st->nb_index_entries; i++) {
2304
        AVIndexEntry *sample = &st->index_entries[i];
2305
        int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2306 0c468f56 Anton Khirnov
        uint8_t title[512];
2307
        uint16_t ch;
2308
        int len;
2309 7221579b David Conrad
2310
        if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2311
            av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2312
            goto finish;
2313
        }
2314
2315
        // the first two bytes are the length of the title
2316 0c468f56 Anton Khirnov
        len = get_be16(sc->pb);
2317 7221579b David Conrad
        if (len > sample->size-2)
2318
            continue;
2319
2320
        // The samples could theoretically be in any encoding if there's an encd
2321
        // atom following, but in practice are only utf-8 or utf-16, distinguished
2322
        // instead by the presence of a BOM
2323 0c468f56 Anton Khirnov
        if ((ch = get_be16(sc->pb)) == 0xfeff)
2324
            avio_get_str16be(sc->pb, len, title, sizeof(title));
2325
        else {
2326
            AV_WB16(title, ch);
2327
            get_buffer(sc->pb, title + sizeof(ch), sizeof(title) - sizeof(ch));
2328 7221579b David Conrad
        }
2329
2330 0c468f56 Anton Khirnov
        ff_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2331 7221579b David Conrad
    }
2332
finish:
2333
    url_fseek(sc->pb, cur_pos, SEEK_SET);
2334
}
2335
2336 a266644f Zdenek Kabelac
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
2337 6cea494e Zdenek Kabelac
{
2338 e4141433 Nicholas Tung
    MOVContext *mov = s->priv_data;
2339 899681cd Björn Axelsson
    ByteIOContext *pb = s->pb;
2340 f9900374 Baptiste Coudurier
    int err;
2341 3491866a Baptiste Coudurier
    MOVAtom atom = { AV_RL32("root") };
2342 6cea494e Zdenek Kabelac
2343
    mov->fc = s;
2344 117a9190 Baptiste Coudurier
    /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2345
    if(!url_is_streamed(pb))
2346 bb270c08 Diego Biurrun
        atom.size = url_fsize(pb);
2347 6cea494e Zdenek Kabelac
    else
2348 fa22ca22 Baptiste Coudurier
        atom.size = INT64_MAX;
2349 6cea494e Zdenek Kabelac
2350
    /* check MOV header */
2351 612b5cbb Baptiste Coudurier
    if ((err = mov_read_default(mov, pb, atom)) < 0) {
2352
        av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2353
        return err;
2354
    }
2355
    if (!mov->found_moov) {
2356
        av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2357 bb270c08 Diego Biurrun
        return -1;
2358 6cea494e Zdenek Kabelac
    }
2359 0265fe81 Baptiste Coudurier
    dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
2360 4e5ef14f Baptiste Coudurier
2361 7221579b David Conrad
    if (!url_is_streamed(pb) && mov->chapter_track > 0)
2362
        mov_read_chapters(s);
2363
2364 6cea494e Zdenek Kabelac
    return 0;
2365
}
2366
2367 5dc5c43b Reimar Döffinger
static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2368 6cea494e Zdenek Kabelac
{
2369 5dc5c43b Reimar Döffinger
    AVIndexEntry *sample = NULL;
2370 86d8602f Michael Niedermayer
    int64_t best_dts = INT64_MAX;
2371 5dc5c43b Reimar Döffinger
    int i;
2372 11f16b66 Baptiste Coudurier
    for (i = 0; i < s->nb_streams; i++) {
2373 69fc436c Reimar Döffinger
        AVStream *avst = s->streams[i];
2374
        MOVStreamContext *msc = avst->priv_data;
2375 3fe4d5d4 Reimar Döffinger
        if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2376 69fc436c Reimar Döffinger
            AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2377 bbe46bc4 Baptiste Coudurier
            int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2378 1c02d96f Baptiste Coudurier
            dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2379 687f35f3 Baptiste Coudurier
            if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
2380
                (!url_is_streamed(s->pb) &&
2381 221e21b7 Baptiste Coudurier
                 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2382 687f35f3 Baptiste Coudurier
                 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2383 221e21b7 Baptiste Coudurier
                  (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2384 b72708f8 Baptiste Coudurier
                sample = current_sample;
2385
                best_dts = dts;
2386 5dc5c43b Reimar Döffinger
                *st = avst;
2387 86d8602f Michael Niedermayer
            }
2388 6cea494e Zdenek Kabelac
        }
2389
    }
2390 5dc5c43b Reimar Döffinger
    return sample;
2391
}
2392
2393
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2394
{
2395
    MOVContext *mov = s->priv_data;
2396
    MOVStreamContext *sc;
2397
    AVIndexEntry *sample;
2398
    AVStream *st = NULL;
2399
    int ret;
2400
 retry:
2401
    sample = mov_find_next_sample(s, &st);
2402 433aeb62 Baptiste Coudurier
    if (!sample) {
2403
        mov->found_mdat = 0;
2404
        if (!url_is_streamed(s->pb) ||
2405 3491866a Baptiste Coudurier
            mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2406 433aeb62 Baptiste Coudurier
            url_feof(s->pb))
2407 350f2c2c Baptiste Coudurier
            return AVERROR_EOF;
2408 433aeb62 Baptiste Coudurier
        dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
2409
        goto retry;
2410
    }
2411 69fc436c Reimar Döffinger
    sc = st->priv_data;
2412 b72708f8 Baptiste Coudurier
    /* must be done just before reading, to avoid infinite loop on sample */
2413
    sc->current_sample++;
2414 3fe4d5d4 Reimar Döffinger
2415
    if (st->discard != AVDISCARD_ALL) {
2416 e1c1b0ff Reimar Döffinger
        if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2417
            av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2418
                   sc->ffindex, sample->pos);
2419
            return -1;
2420
        }
2421
        ret = av_get_packet(sc->pb, pkt, sample->size);
2422 a2f38511 Reimar Döffinger
        if (ret < 0)
2423
            return ret;
2424 e1c1b0ff Reimar Döffinger
#if CONFIG_DV_DEMUXER
2425
        if (mov->dv_demux && sc->dv_audio_container) {
2426
            dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2427
            av_free(pkt->data);
2428
            pkt->size = 0;
2429
            ret = dv_get_packet(mov->dv_demux, pkt);
2430
            if (ret < 0)
2431
                return ret;
2432
        }
2433 312954f0 Baptiste Coudurier
#endif
2434 3fe4d5d4 Reimar Döffinger
    }
2435
2436 b72708f8 Baptiste Coudurier
    pkt->stream_index = sc->ffindex;
2437
    pkt->dts = sample->timestamp;
2438
    if (sc->ctts_data) {
2439 bbe46bc4 Baptiste Coudurier
        pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2440 b72708f8 Baptiste Coudurier
        /* update ctts context */
2441 a234e38d Baptiste Coudurier
        sc->ctts_sample++;
2442
        if (sc->ctts_index < sc->ctts_count &&
2443
            sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2444
            sc->ctts_index++;
2445
            sc->ctts_sample = 0;
2446 b565ea09 Baptiste Coudurier
        }
2447 0c5f76f7 Baptiste Coudurier
        if (sc->wrong_dts)
2448
            pkt->dts = AV_NOPTS_VALUE;
2449 b72708f8 Baptiste Coudurier
    } else {
2450 f0f2218d Baptiste Coudurier
        int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2451 e8430214 Henrik Gulbrandsen
            st->index_entries[sc->current_sample].timestamp : st->duration;
2452
        pkt->duration = next_dts - pkt->dts;
2453 b72708f8 Baptiste Coudurier
        pkt->pts = pkt->dts;
2454 b565ea09 Baptiste Coudurier
    }
2455 3fe4d5d4 Reimar Döffinger
    if (st->discard == AVDISCARD_ALL)
2456
        goto retry;
2457 cc947f04 Jean-Daniel Dupas
    pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2458 b72708f8 Baptiste Coudurier
    pkt->pos = sample->pos;
2459 29c90869 Baptiste Coudurier
    dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2460
            pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2461 b72708f8 Baptiste Coudurier
    return 0;
2462
}
2463 3ffe3793 François Revol
2464 e26df9eb Baptiste Coudurier
static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2465 b72708f8 Baptiste Coudurier
{
2466
    MOVStreamContext *sc = st->priv_data;
2467
    int sample, time_sample;
2468
    int i;
2469 115329f1 Diego Biurrun
2470 b72708f8 Baptiste Coudurier
    sample = av_index_search_timestamp(st, timestamp, flags);
2471 e26df9eb Baptiste Coudurier
    dprintf(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2472 380966a8 John Stebbins
    if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2473
        sample = 0;
2474 b72708f8 Baptiste Coudurier
    if (sample < 0) /* not sure what to do */
2475
        return -1;
2476
    sc->current_sample = sample;
2477 e26df9eb Baptiste Coudurier
    dprintf(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2478 b72708f8 Baptiste Coudurier
    /* adjust ctts index */
2479
    if (sc->ctts_data) {
2480
        time_sample = 0;
2481
        for (i = 0; i < sc->ctts_count; i++) {
2482 54a5c719 Baptiste Coudurier
            int next = time_sample + sc->ctts_data[i].count;
2483
            if (next > sc->current_sample) {
2484 a234e38d Baptiste Coudurier
                sc->ctts_index = i;
2485
                sc->ctts_sample = sc->current_sample - time_sample;
2486 b72708f8 Baptiste Coudurier
                break;
2487 115329f1 Diego Biurrun
            }
2488 54a5c719 Baptiste Coudurier
            time_sample = next;
2489 247d56f5 Brian Becker
        }
2490
    }
2491 b72708f8 Baptiste Coudurier
    return sample;
2492 6cea494e Zdenek Kabelac
}
2493
2494 961e0ccd Michael Niedermayer
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2495 baf25c9d Gael Chardon
{
2496 b72708f8 Baptiste Coudurier
    AVStream *st;
2497
    int64_t seek_timestamp, timestamp;
2498
    int sample;
2499
    int i;
2500 baf25c9d Gael Chardon
2501 b72708f8 Baptiste Coudurier
    if (stream_index >= s->nb_streams)
2502 baf25c9d Gael Chardon
        return -1;
2503 8dc81a45 Baptiste Coudurier
    if (sample_time < 0)
2504
        sample_time = 0;
2505 baf25c9d Gael Chardon
2506 b72708f8 Baptiste Coudurier
    st = s->streams[stream_index];
2507 e26df9eb Baptiste Coudurier
    sample = mov_seek_stream(s, st, sample_time, flags);
2508 b72708f8 Baptiste Coudurier
    if (sample < 0)
2509 baf25c9d Gael Chardon
        return -1;
2510
2511 b72708f8 Baptiste Coudurier
    /* adjust seek timestamp to found sample timestamp */
2512
    seek_timestamp = st->index_entries[sample].timestamp;
2513 baf25c9d Gael Chardon
2514 b72708f8 Baptiste Coudurier
    for (i = 0; i < s->nb_streams; i++) {
2515
        st = s->streams[i];
2516 3fe4d5d4 Reimar Döffinger
        if (stream_index == i)
2517 b72708f8 Baptiste Coudurier
            continue;
2518 baf25c9d Gael Chardon
2519 b72708f8 Baptiste Coudurier
        timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2520 e26df9eb Baptiste Coudurier
        mov_seek_stream(s, st, timestamp, flags);
2521 115329f1 Diego Biurrun
    }
2522 baf25c9d Gael Chardon
    return 0;
2523
}
2524
2525 a266644f Zdenek Kabelac
static int mov_read_close(AVFormatContext *s)
2526 6cea494e Zdenek Kabelac
{
2527 e4141433 Nicholas Tung
    MOVContext *mov = s->priv_data;
2528 6c00a9de Baptiste Coudurier
    int i, j;
2529
2530
    for (i = 0; i < s->nb_streams; i++) {
2531 e49da827 Baptiste Coudurier
        AVStream *st = s->streams[i];
2532
        MOVStreamContext *sc = st->priv_data;
2533 6c00a9de Baptiste Coudurier
2534 7c622eed Baptiste Coudurier
        av_freep(&sc->ctts_data);
2535 adeb9071 Baptiste Coudurier
        for (j = 0; j < sc->drefs_count; j++) {
2536 221e21b7 Baptiste Coudurier
            av_freep(&sc->drefs[j].path);
2537 adeb9071 Baptiste Coudurier
            av_freep(&sc->drefs[j].dir);
2538
        }
2539 221e21b7 Baptiste Coudurier
        av_freep(&sc->drefs);
2540
        if (sc->pb && sc->pb != s->pb)
2541
            url_fclose(sc->pb);
2542 e49da827 Baptiste Coudurier
2543
        av_freep(&st->codec->palctrl);
2544 4440b118 Baptiste Coudurier
    }
2545 6c00a9de Baptiste Coudurier
2546
    if (mov->dv_demux) {
2547
        for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
2548 b60c0454 Baptiste Coudurier
            av_freep(&mov->dv_fctx->streams[i]->codec);
2549
            av_freep(&mov->dv_fctx->streams[i]);
2550
        }
2551
        av_freep(&mov->dv_fctx);
2552
        av_freep(&mov->dv_demux);
2553
    }
2554 6c00a9de Baptiste Coudurier
2555 61aedb0f Baptiste Coudurier
    av_freep(&mov->trex_data);
2556 6c00a9de Baptiste Coudurier
2557 6cea494e Zdenek Kabelac
    return 0;
2558
}
2559
2560 ff70e601 Måns Rullgård
AVInputFormat mov_demuxer = {
2561 fc5188f3 Baptiste Coudurier
    "mov,mp4,m4a,3gp,3g2,mj2",
2562 bde15e74 Stefano Sabatini
    NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2563 c9a65ca8 Fabrice Bellard
    sizeof(MOVContext),
2564
    mov_probe,
2565 6cea494e Zdenek Kabelac
    mov_read_header,
2566
    mov_read_packet,
2567
    mov_read_close,
2568 baf25c9d Gael Chardon
    mov_read_seek,
2569 6cea494e Zdenek Kabelac
};