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