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