Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ c60208e7

History | View | Annotate | Download (71.7 KB)

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