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