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