mov: Refactor video specific parsing in mov_parse_stsd_video
[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 *
ac9362c5
DB
6 * first version by Francois Revol <revol@free.fr>
7 * seek function by Gael Chardon <gael.dev@4now.net>
8 *
2912e87a 9 * This file is part of Libav.
b78e7197 10 *
2912e87a 11 * Libav is free software; you can redistribute it and/or
19720f15
FB
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
b78e7197 14 * version 2.1 of the License, or (at your option) any later version.
6cea494e 15 *
2912e87a 16 * Libav is distributed in the hope that it will be useful,
6cea494e 17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19720f15
FB
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
6cea494e 20 *
19720f15 21 * You should have received a copy of the GNU Lesser General Public
2912e87a 22 * License along with Libav; if not, write to the Free Software
5509bffa 23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6cea494e 24 */
d957696f
MN
25
26#include <limits.h>
115329f1 27
873358e5 28//#define MOV_EXPORT_ALL_METADATA
4e5ef14f 29
30b1961c 30#include "libavutil/attributes.h"
a903f8f0 31#include "libavutil/channel_layout.h"
6a5d31ac 32#include "libavutil/intreadwrite.h"
3383a53e 33#include "libavutil/intfloat.h"
0ebcdf5c 34#include "libavutil/mathematics.h"
49674dd0 35#include "libavutil/avstring.h"
d2d67e42 36#include "libavutil/dict.h"
3798205a 37#include "libavcodec/ac3tab.h"
6cea494e 38#include "avformat.h"
c3f9ebf7 39#include "internal.h"
e731b8d8 40#include "avio_internal.h"
9d9f4119 41#include "riff.h"
e40ee6a2 42#include "isom.h"
9106a698 43#include "libavcodec/get_bits.h"
94395fbf 44#include "id3v1.h"
1fdf18f4 45#include "mov_chan.h"
6cea494e 46
b250f9c6 47#if CONFIG_ZLIB
0147f198
FR
48#include <zlib.h>
49#endif
50
b595afaa
MM
51#include "qtpalette.h"
52
baf25c9d 53
cd7352d5
MN
54#undef NDEBUG
55#include <assert.h>
56
6cea494e 57/* those functions parse an atom */
6cea494e
ZK
58/* links atom IDs to parse functions */
59typedef struct MOVParseTableEntry {
0c1a9eda 60 uint32_t type;
ae628ec1 61 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
6cea494e
ZK
62} MOVParseTableEntry;
63
1ce1e636 64static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
73d07c27 65
dff41775
RH
66static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
67 unsigned len, const char *key)
c6026e43
BC
68{
69 char buf[16];
70
fbcaceb1 71 short current, total = 0;
b7effd4e 72 avio_rb16(pb); // unknown
dff41775 73 current = avio_rb16(pb);
fbcaceb1
CEH
74 if (len >= 6)
75 total = avio_rb16(pb);
dff41775
RH
76 if (!total)
77 snprintf(buf, sizeof(buf), "%d", current);
78 else
79 snprintf(buf, sizeof(buf), "%d/%d", current, total);
80 av_dict_set(&c->fc->metadata, key, buf, 0);
c6026e43
BC
81
82 return 0;
83}
84
80951f5c
RH
85static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
86 unsigned len, const char *key)
f0556353 87{
80951f5c 88 char buf[16];
f0556353 89
80951f5c
RH
90 /* bypass padding bytes */
91 avio_r8(pb);
92 avio_r8(pb);
93 avio_r8(pb);
f0556353 94
028a2375 95 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
80951f5c 96 av_dict_set(&c->fc->metadata, key, buf, 0);
f0556353 97
80951f5c 98 return 0;
f0556353
RH
99}
100
5da35d1c
RH
101static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
102 unsigned len, const char *key)
f0556353 103{
5da35d1c 104 char buf[16];
f0556353 105
028a2375 106 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
5da35d1c 107 av_dict_set(&c->fc->metadata, key, buf, 0);
f0556353 108
5da35d1c 109 return 0;
f0556353
RH
110}
111
94395fbf
RH
112static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
113 unsigned len, const char *key)
114{
115 short genre;
116 char buf[20];
117
118 avio_r8(pb); // unknown
119
120 genre = avio_r8(pb);
121 if (genre < 1 || genre > ID3v1_GENRE_MAX)
122 return 0;
123 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
124 av_dict_set(&c->fc->metadata, key, buf, 0);
125
126 return 0;
127}
128
08a186c6
BC
129static const uint32_t mac_to_unicode[128] = {
130 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
131 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
132 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
133 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
134 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
135 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
136 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
137 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
138 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
139 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
140 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
141 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
142 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
143 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
144 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
145 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
146};
147
ae628ec1 148static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
08a186c6
BC
149 char *dst, int dstlen)
150{
151 char *p = dst;
152 char *end = dst+dstlen-1;
153 int i;
154
155 for (i = 0; i < len; i++) {
b7effd4e 156 uint8_t t, c = avio_r8(pb);
08a186c6
BC
157 if (c < 0x80 && p < end)
158 *p++ = c;
159 else
160 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
161 }
162 *p = 0;
163 return p - dst;
164}
165
a02b8c69
AK
166static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
167{
168 AVPacket pkt;
169 AVStream *st;
170 MOVStreamContext *sc;
36ef5369 171 enum AVCodecID id;
a02b8c69
AK
172 int ret;
173
174 switch (type) {
36ef5369
AK
175 case 0xd: id = AV_CODEC_ID_MJPEG; break;
176 case 0xe: id = AV_CODEC_ID_PNG; break;
177 case 0x1b: id = AV_CODEC_ID_BMP; break;
a02b8c69
AK
178 default:
179 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
180 avio_skip(pb, len);
181 return 0;
182 }
183
184 st = avformat_new_stream(c->fc, NULL);
185 if (!st)
186 return AVERROR(ENOMEM);
187 sc = av_mallocz(sizeof(*sc));
188 if (!sc)
189 return AVERROR(ENOMEM);
190 st->priv_data = sc;
191
192 ret = av_get_packet(pb, &pkt, len);
193 if (ret < 0)
194 return ret;
195
196 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
197
198 st->attached_pic = pkt;
199 st->attached_pic.stream_index = st->index;
200 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
201
202 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
203 st->codec->codec_id = id;
204
205 return 0;
206}
207
ae628ec1 208static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
0fb44a4e
BC
209{
210#ifdef MOV_EXPORT_ALL_METADATA
211 char tmp_key[5];
212#endif
213 char str[1024], key2[16], language[4] = {0};
214 const char *key = NULL;
a7b8ff94
AK
215 uint16_t langcode = 0;
216 uint32_t data_type = 0, str_size;
dff41775 217 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
0fb44a4e
BC
218
219 switch (atom.type) {
220 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
221 case MKTAG(0xa9,'a','u','t'):
ea4c4d7f 222 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
2804d320 223 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
55d2e32a 224 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
b9c78bca 225 case MKTAG( 'c','p','r','t'):
0fb44a4e
BC
226 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
227 case MKTAG(0xa9,'c','m','t'):
228 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
229 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
ca76a119 230 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
0fb44a4e 231 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
94395fbf
RH
232 case MKTAG( 'g','n','r','e'): key = "genre";
233 parse = mov_metadata_gnre; break;
0fb44a4e 234 case MKTAG(0xa9,'t','o','o'):
2b91d83e 235 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
a4cb56aa 236 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
7382902b
DC
237 case MKTAG( 'd','e','s','c'): key = "description";break;
238 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
239 case MKTAG( 't','v','s','h'): key = "show"; break;
240 case MKTAG( 't','v','e','n'): key = "episode_id";break;
241 case MKTAG( 't','v','n','n'): key = "network"; break;
c6026e43 242 case MKTAG( 't','r','k','n'): key = "track";
dff41775
RH
243 parse = mov_metadata_track_or_disc_number; break;
244 case MKTAG( 'd','i','s','k'): key = "disc";
245 parse = mov_metadata_track_or_disc_number; break;
f0556353 246 case MKTAG( 't','v','e','s'): key = "episode_sort";
80951f5c 247 parse = mov_metadata_int8_bypass_padding; break;
f0556353 248 case MKTAG( 't','v','s','n'): key = "season_number";
80951f5c 249 parse = mov_metadata_int8_bypass_padding; break;
f0556353 250 case MKTAG( 's','t','i','k'): key = "media_type";
5da35d1c 251 parse = mov_metadata_int8_no_padding; break;
b06df707
RH
252 case MKTAG( 'h','d','v','d'): key = "hd_video";
253 parse = mov_metadata_int8_no_padding; break;
254 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
255 parse = mov_metadata_int8_no_padding; break;
0fb44a4e
BC
256 }
257
258 if (c->itunes_metadata && atom.size > 8) {
b7effd4e
AK
259 int data_size = avio_rb32(pb);
260 int tag = avio_rl32(pb);
0fb44a4e 261 if (tag == MKTAG('d','a','t','a')) {
b7effd4e
AK
262 data_type = avio_rb32(pb); // type
263 avio_rb32(pb); // unknown
0fb44a4e
BC
264 str_size = data_size - 16;
265 atom.size -= 16;
a02b8c69
AK
266
267 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
268 int ret = mov_read_covr(c, pb, data_type, str_size);
269 if (ret < 0) {
270 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
271 return ret;
272 }
273 }
0fb44a4e
BC
274 } else return 0;
275 } else if (atom.size > 4 && key && !c->itunes_metadata) {
b7effd4e
AK
276 str_size = avio_rb16(pb); // string length
277 langcode = avio_rb16(pb);
08a186c6 278 ff_mov_lang_to_iso639(langcode, language);
0fb44a4e
BC
279 atom.size -= 4;
280 } else
281 str_size = atom.size;
282
283#ifdef MOV_EXPORT_ALL_METADATA
284 if (!key) {
285 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
286 key = tmp_key;
287 }
288#endif
289
290 if (!key)
291 return 0;
292 if (atom.size < 0)
bcd5d979 293 return AVERROR_INVALIDDATA;
0fb44a4e
BC
294
295 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
c6026e43
BC
296
297 if (parse)
dff41775 298 parse(c, pb, str_size, key);
c6026e43 299 else {
08a186c6
BC
300 if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
301 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
302 } else {
b7effd4e 303 avio_read(pb, str, str_size);
08a186c6
BC
304 str[str_size] = 0;
305 }
d2d67e42 306 av_dict_set(&c->fc->metadata, key, str, 0);
f584386d
BC
307 if (*language && strcmp(language, "und")) {
308 snprintf(key2, sizeof(key2), "%s-%s", key, language);
d2d67e42 309 av_dict_set(&c->fc->metadata, key2, str, 0);
f584386d 310 }
c6026e43 311 }
02a8d43a
DB
312 av_dlog(c->fc, "lang \"%3s\" ", language);
313 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
314 key, str, (char*)&atom.type, str_size, atom.size);
0fb44a4e
BC
315
316 return 0;
317}
873358e5 318
ae628ec1 319static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1cf9f6ed
DC
320{
321 int64_t start;
105b3785 322 int i, nb_chapters, str_len, version;
1cf9f6ed
DC
323 char str[256+1];
324
325 if ((atom.size -= 5) < 0)
326 return 0;
327
b7effd4e
AK
328 version = avio_r8(pb);
329 avio_rb24(pb);
105b3785 330 if (version)
b7effd4e
AK
331 avio_rb32(pb); // ???
332 nb_chapters = avio_r8(pb);
1cf9f6ed
DC
333
334 for (i = 0; i < nb_chapters; i++) {
335 if (atom.size < 9)
336 return 0;
337
b7effd4e
AK
338 start = avio_rb64(pb);
339 str_len = avio_r8(pb);
1cf9f6ed
DC
340
341 if ((atom.size -= 9+str_len) < 0)
342 return 0;
343
b7effd4e 344 avio_read(pb, str, str_len);
1cf9f6ed 345 str[str_len] = 0;
1fa395e4 346 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
1cf9f6ed
DC
347 }
348 return 0;
349}
350
8cc2fa1e 351#define MIN_DATA_ENTRY_BOX_SIZE 12
ae628ec1 352static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
221e21b7 353{
6a63ff19
BC
354 AVStream *st;
355 MOVStreamContext *sc;
221e21b7
BC
356 int entries, i, j;
357
6a63ff19
BC
358 if (c->fc->nb_streams < 1)
359 return 0;
360 st = c->fc->streams[c->fc->nb_streams-1];
361 sc = st->priv_data;
362
b7effd4e
AK
363 avio_rb32(pb); // version + flags
364 entries = avio_rb32(pb);
8cc2fa1e
JG
365 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
366 entries >= UINT_MAX / sizeof(*sc->drefs))
bcd5d979 367 return AVERROR_INVALIDDATA;
4ebd422c 368 av_free(sc->drefs);
221e21b7 369 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
0d8f0abf
BC
370 if (!sc->drefs)
371 return AVERROR(ENOMEM);
372 sc->drefs_count = entries;
221e21b7
BC
373
374 for (i = 0; i < sc->drefs_count; i++) {
c3e92a6c 375 MOVDref *dref = &sc->drefs[i];
b7effd4e 376 uint32_t size = avio_rb32(pb);
a2704c97 377 int64_t next = avio_tell(pb) + size - 4;
221e21b7 378
0e7d436d 379 if (size < 12)
bcd5d979 380 return AVERROR_INVALIDDATA;
0e7d436d 381
b7effd4e
AK
382 dref->type = avio_rl32(pb);
383 avio_rb32(pb); // version + flags
dfd2a005 384 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
221e21b7
BC
385
386 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
387 /* macintosh alias record */
388 uint16_t volume_len, len;
221e21b7
BC
389 int16_t type;
390
45a8a02a 391 avio_skip(pb, 10);
221e21b7 392
b7effd4e 393 volume_len = avio_r8(pb);
221e21b7 394 volume_len = FFMIN(volume_len, 27);
b7effd4e 395 avio_read(pb, dref->volume, 27);
adeb9071
BC
396 dref->volume[volume_len] = 0;
397 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
221e21b7 398
45a8a02a 399 avio_skip(pb, 12);
adeb9071 400
b7effd4e 401 len = avio_r8(pb);
adeb9071 402 len = FFMIN(len, 63);
b7effd4e 403 avio_read(pb, dref->filename, 63);
adeb9071
BC
404 dref->filename[len] = 0;
405 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
406
45a8a02a 407 avio_skip(pb, 16);
adeb9071
BC
408
409 /* read next level up_from_alias/down_to_target */
b7effd4e
AK
410 dref->nlvl_from = avio_rb16(pb);
411 dref->nlvl_to = avio_rb16(pb);
adeb9071
BC
412 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
413 dref->nlvl_from, dref->nlvl_to);
414
45a8a02a 415 avio_skip(pb, 16);
221e21b7 416
a2704c97 417 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
9db67bed
MN
418 if (pb->eof_reached)
419 return AVERROR_EOF;
b7effd4e
AK
420 type = avio_rb16(pb);
421 len = avio_rb16(pb);
221e21b7
BC
422 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
423 if (len&1)
424 len += 1;
425 if (type == 2) { // absolute path
dbb37657 426 av_free(dref->path);
221e21b7 427 dref->path = av_mallocz(len+1);
2f4568e5
BC
428 if (!dref->path)
429 return AVERROR(ENOMEM);
b7effd4e 430 avio_read(pb, dref->path, len);
adeb9071 431 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
221e21b7
BC
432 len -= volume_len;
433 memmove(dref->path, dref->path+volume_len, len);
434 dref->path[len] = 0;
435 }
436 for (j = 0; j < len; j++)
437 if (dref->path[j] == ':')
438 dref->path[j] = '/';
439 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
adeb9071
BC
440 } else if (type == 0) { // directory name
441 av_free(dref->dir);
442 dref->dir = av_malloc(len+1);
443 if (!dref->dir)
444 return AVERROR(ENOMEM);
b7effd4e 445 avio_read(pb, dref->dir, len);
adeb9071
BC
446 dref->dir[len] = 0;
447 for (j = 0; j < len; j++)
448 if (dref->dir[j] == ':')
449 dref->dir[j] = '/';
450 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
221e21b7 451 } else
45a8a02a 452 avio_skip(pb, len);
221e21b7
BC
453 }
454 }
6b4aa5da 455 avio_seek(pb, next, SEEK_SET);
221e21b7
BC
456 }
457 return 0;
458}
459
ae628ec1 460static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6cea494e 461{
fefe43ff 462 AVStream *st;
0c1a9eda 463 uint32_t type;
5e1166b3 464 uint32_t av_unused ctype;
b6a17df4 465
fefe43ff
AC
466 if (c->fc->nb_streams < 1) // meta before first trak
467 return 0;
468
469 st = c->fc->streams[c->fc->nb_streams-1];
470
b7effd4e
AK
471 avio_r8(pb); /* version */
472 avio_rb24(pb); /* flags */
6cea494e
ZK
473
474 /* component type */
b7effd4e
AK
475 ctype = avio_rl32(pb);
476 type = avio_rl32(pb); /* component subtype */
6cea494e 477
dfd2a005
LB
478 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
479 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
2229a5c6 480
37ffe34b 481 if (type == MKTAG('v','i','d','e'))
72415b2a 482 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
5a7ba586 483 else if (type == MKTAG('s','o','u','n'))
72415b2a 484 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
5a7ba586 485 else if (type == MKTAG('m','1','a',' '))
36ef5369 486 st->codec->codec_id = AV_CODEC_ID_MP2;
5a7ba586 487 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
72415b2a 488 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
f05783c2 489
b7effd4e
AK
490 avio_rb32(pb); /* component manufacture */
491 avio_rb32(pb); /* component flags */
492 avio_rb32(pb); /* component flags mask */
6cea494e 493
6cea494e
ZK
494 return 0;
495}
496
ae628ec1 497int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
5cd62665 498{
6a63ff19 499 AVStream *st;
e65ab9d9 500 int tag;
b6a17df4 501
2d423666 502 if (fc->nb_streams < 1)
6a63ff19 503 return 0;
2d423666 504 st = fc->streams[fc->nb_streams-1];
6a63ff19 505
b7effd4e 506 avio_rb32(pb); /* version + flags */
e65ab9d9 507 ff_mp4_read_descr(fc, pb, &tag);
5cd62665 508 if (tag == MP4ESDescrTag) {
ad6c7c1b 509 ff_mp4_parse_es_descr(pb, NULL);
5cd62665 510 } else
b7effd4e 511 avio_rb16(pb); /* ID */
5cd62665 512
e65ab9d9 513 ff_mp4_read_descr(fc, pb, &tag);
798c6fac
BC
514 if (tag == MP4DecConfigDescrTag)
515 ff_mp4_read_dec_config_descr(fc, st, pb);
5cd62665
ZK
516 return 0;
517}
518
ae628ec1 519static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2d423666
PR
520{
521 return ff_mov_read_esds(c->fc, pb, atom);
522}
523
ae628ec1 524static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
bdecdd2b
JR
525{
526 AVStream *st;
eb81cf86 527 int ac3info, acmod, lfeon, bsmod;
bdecdd2b 528
6d19fd5c
BC
529 if (c->fc->nb_streams < 1)
530 return 0;
bdecdd2b
JR
531 st = c->fc->streams[c->fc->nb_streams-1];
532
b7effd4e 533 ac3info = avio_rb24(pb);
eb81cf86 534 bsmod = (ac3info >> 14) & 0x7;
bdecdd2b
JR
535 acmod = (ac3info >> 11) & 0x7;
536 lfeon = (ac3info >> 10) & 0x1;
537 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
3798205a
JR
538 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
539 if (lfeon)
540 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
eb81cf86
JR
541 st->codec->audio_service_type = bsmod;
542 if (st->codec->channels > 1 && bsmod == 0x7)
543 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
bdecdd2b
JR
544
545 return 0;
546}
547
546adc1f
YN
548static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
549{
550 AVStream *st;
551 int eac3info, acmod, lfeon, bsmod;
552
553 if (c->fc->nb_streams < 1)
554 return 0;
555 st = c->fc->streams[c->fc->nb_streams-1];
556
557 /* No need to parse fields for additional independent substreams and its
558 * associated dependent substreams since libavcodec's E-AC-3 decoder
559 * does not support them yet. */
560 avio_rb16(pb); /* data_rate and num_ind_sub */
561 eac3info = avio_rb24(pb);
562 bsmod = (eac3info >> 12) & 0x1f;
563 acmod = (eac3info >> 9) & 0x7;
564 lfeon = (eac3info >> 8) & 0x1;
565 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
566 if (lfeon)
567 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
568 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
569 st->codec->audio_service_type = bsmod;
570 if (st->codec->channels > 1 && bsmod == 0x7)
571 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
572
573 return 0;
574}
575
1fdf18f4
JR
576static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
577{
578 AVStream *st;
1fdf18f4
JR
579
580 if (c->fc->nb_streams < 1)
581 return 0;
582 st = c->fc->streams[c->fc->nb_streams-1];
583
584 if (atom.size < 16)
585 return 0;
586
9afb7061 587 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
1fdf18f4
JR
588
589 return 0;
590}
591
85e9e3a9
AC
592static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
593{
594 AVStream *st;
595
596 if (c->fc->nb_streams < 1)
597 return 0;
598 st = c->fc->streams[c->fc->nb_streams-1];
599
600 ff_get_wav_header(pb, st->codec, atom.size);
601
602 return 0;
603}
604
ae628ec1 605static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6da54074 606{
b7effd4e
AK
607 const int num = avio_rb32(pb);
608 const int den = avio_rb32(pb);
6a63ff19
BC
609 AVStream *st;
610
611 if (c->fc->nb_streams < 1)
612 return 0;
613 st = c->fc->streams[c->fc->nb_streams-1];
614
9044dd83
BC
615 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
616 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
617 av_log(c->fc, AV_LOG_WARNING,
618 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
619 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
620 num, den);
621 } else if (den != 0) {
6da54074
BC
622 st->sample_aspect_ratio.num = num;
623 st->sample_aspect_ratio.den = den;
624 }
625 return 0;
626}
627
5ca1d879 628/* this atom contains actual media data */
ae628ec1 629static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6cea494e 630{
5a7ba586 631 if (atom.size == 0) /* wrong one (MP4) */
5ca1d879
ZK
632 return 0;
633 c->found_mdat=1;
5ca1d879
ZK
634 return 0; /* now go for moov */
635}
636
7b5252ce 637/* read major brand, minor version and compatible brands and store them as metadata */
ae628ec1 638static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4ea28253 639{
7b5252ce 640 uint32_t minor_ver;
641 int comp_brand_size;
642 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
643 char* comp_brands_str;
644 uint8_t type[5] = {0};
645
b7effd4e 646 avio_read(pb, type, 4);
a42bf191 647 if (strcmp(type, "qt "))
152e9a43 648 c->isom = 1;
a512446e 649 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
d2d67e42 650 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
b7effd4e 651 minor_ver = avio_rb32(pb); /* minor version */
7b5252ce 652 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
d2d67e42 653 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
7b5252ce 654
655 comp_brand_size = atom.size - 8;
656 if (comp_brand_size < 0)
bcd5d979 657 return AVERROR_INVALIDDATA;
7b5252ce 658 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
659 if (!comp_brands_str)
660 return AVERROR(ENOMEM);
b7effd4e 661 avio_read(pb, comp_brands_str, comp_brand_size);
7b5252ce 662 comp_brands_str[comp_brand_size] = 0;
d2d67e42 663 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
7b5252ce 664 av_freep(&comp_brands_str);
665
4ea28253
BC
666 return 0;
667}
668
5ca1d879 669/* this atom should contain all header atoms */
ae628ec1 670static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5ca1d879 671{
bcd5d979
DH
672 int ret;
673
674 if ((ret = mov_read_default(c, pb, atom)) < 0)
675 return ret;
5ca1d879
ZK
676 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
677 /* so we don't parse the whole file if over a network */
678 c->found_moov=1;
5ca1d879
ZK
679 return 0; /* now go for mdat */
680}
681
ae628ec1 682static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
61aedb0f 683{
a2704c97 684 c->fragment.moof_offset = avio_tell(pb) - 8;
3583d7cf 685 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
61aedb0f
BC
686 return mov_read_default(c, pb, atom);
687}
5ca1d879 688
d2d67e42 689static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
7df22143
AJ
690{
691 char buffer[32];
692 if (time) {
5e2202d6 693 struct tm *ptm;
7df22143 694 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
5e2202d6
BC
695 ptm = gmtime(&time);
696 if (!ptm) return;
697 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
d2d67e42 698 av_dict_set(metadata, "creation_time", buffer, 0);
7df22143
AJ
699 }
700}
701
ae628ec1 702static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5ca1d879 703{
6a63ff19
BC
704 AVStream *st;
705 MOVStreamContext *sc;
706 int version;
49674dd0 707 char language[4] = {0};
dce25564 708 unsigned lang;
7df22143 709 time_t creation_time;
5ca1d879 710
6a63ff19
BC
711 if (c->fc->nb_streams < 1)
712 return 0;
713 st = c->fc->streams[c->fc->nb_streams-1];
714 sc = st->priv_data;
715
31931520
MS
716 if (sc->time_scale) {
717 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
718 return AVERROR_INVALIDDATA;
719 }
720
b7effd4e 721 version = avio_r8(pb);
bcd5d979 722 if (version > 1) {
1ecdf891 723 avpriv_request_sample(c->fc, "Version %d", version);
bcd5d979
DH
724 return AVERROR_PATCHWELCOME;
725 }
b7effd4e 726 avio_rb24(pb); /* flags */
f444b977 727 if (version == 1) {
b7effd4e
AK
728 creation_time = avio_rb64(pb);
729 avio_rb64(pb);
f444b977 730 } else {
b7effd4e
AK
731 creation_time = avio_rb32(pb);
732 avio_rb32(pb); /* modification time */
f444b977 733 }
7df22143 734 mov_metadata_creation_time(&st->metadata, creation_time);
5ca1d879 735
b7effd4e
AK
736 sc->time_scale = avio_rb32(pb);
737 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
5ca1d879 738
b7effd4e 739 lang = avio_rb16(pb); /* language */
49674dd0 740 if (ff_mov_lang_to_iso639(lang, language))
d2d67e42 741 av_dict_set(&st->metadata, "language", language, 0);
b7effd4e 742 avio_rb16(pb); /* quality */
5ca1d879
ZK
743
744 return 0;
745}
746
ae628ec1 747static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5ca1d879 748{
7df22143 749 time_t creation_time;
b7effd4e
AK
750 int version = avio_r8(pb); /* version */
751 avio_rb24(pb); /* flags */
5ca1d879 752
1175561e 753 if (version == 1) {
b7effd4e
AK
754 creation_time = avio_rb64(pb);
755 avio_rb64(pb);
1175561e 756 } else {
b7effd4e
AK
757 creation_time = avio_rb32(pb);
758 avio_rb32(pb); /* modification time */
1175561e 759 }
7df22143 760 mov_metadata_creation_time(&c->fc->metadata, creation_time);
b7effd4e 761 c->time_scale = avio_rb32(pb); /* time scale */
f8c18cd7 762
dfd2a005 763 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
f8c18cd7 764
b7effd4e
AK
765 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
766 avio_rb32(pb); /* preferred scale */
5ca1d879 767
b7effd4e 768 avio_rb16(pb); /* preferred volume */
5ca1d879 769
45a8a02a 770 avio_skip(pb, 10); /* reserved */
5ca1d879 771
45a8a02a 772 avio_skip(pb, 36); /* display matrix */
5ca1d879 773
b7effd4e
AK
774 avio_rb32(pb); /* preview time */
775 avio_rb32(pb); /* preview duration */
776 avio_rb32(pb); /* poster time */
777 avio_rb32(pb); /* selection time */
778 avio_rb32(pb); /* selection duration */
779 avio_rb32(pb); /* current time */
780 avio_rb32(pb); /* next track ID */
5ca1d879
ZK
781
782 return 0;
783}
784
ae628ec1 785static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
9ed83b0a 786{
6a63ff19
BC
787 AVStream *st;
788
789 if (c->fc->nb_streams < 1)
790 return 0;
791 st = c->fc->streams[c->fc->nb_streams-1];
9ed83b0a 792
5a7ba586 793 if ((uint64_t)atom.size > (1<<30))
bcd5d979 794 return AVERROR_INVALIDDATA;
115329f1 795
9ed83b0a
ZK
796 // currently SVQ3 decoder expect full STSD header - so let's fake it
797 // this should be fixed and just SMI header should be passed
01f4895c 798 av_free(st->codec->extradata);
b014dd76
BC
799 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
800 if (!st->codec->extradata)
801 return AVERROR(ENOMEM);
17871a02
BC
802 st->codec->extradata_size = 0x5a + atom.size;
803 memcpy(st->codec->extradata, "SVQ3", 4); // fake
b7effd4e 804 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
dfd2a005 805 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
9ed83b0a
ZK
806 return 0;
807}
5ca1d879 808
ae628ec1 809static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
de23f234 810{
6a63ff19
BC
811 AVStream *st;
812 int little_endian;
813
814 if (c->fc->nb_streams < 1)
815 return 0;
816 st = c->fc->streams[c->fc->nb_streams-1];
de23f234 817
b7effd4e 818 little_endian = avio_rb16(pb);
dfd2a005 819 av_dlog(c->fc, "enda %d\n", little_endian);
fa50a027 820 if (little_endian == 1) {
de23f234 821 switch (st->codec->codec_id) {
36ef5369
AK
822 case AV_CODEC_ID_PCM_S24BE:
823 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
de23f234 824 break;
36ef5369
AK
825 case AV_CODEC_ID_PCM_S32BE:
826 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
de23f234 827 break;
36ef5369
AK
828 case AV_CODEC_ID_PCM_F32BE:
829 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
a1ef2c4b 830 break;
36ef5369
AK
831 case AV_CODEC_ID_PCM_F64BE:
832 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
a1ef2c4b 833 break;
de23f234
BC
834 default:
835 break;
836 }
837 }
838 return 0;
839}
840
4bf3c8f2
AC
841static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
842{
843 AVStream *st;
844 unsigned mov_field_order;
845 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
846
847 if (c->fc->nb_streams < 1) // will happen with jp2 files
848 return 0;
849 st = c->fc->streams[c->fc->nb_streams-1];
850 if (atom.size < 2)
851 return AVERROR_INVALIDDATA;
852 mov_field_order = avio_rb16(pb);
853 if ((mov_field_order & 0xFF00) == 0x0100)
854 decoded_field_order = AV_FIELD_PROGRESSIVE;
855 else if ((mov_field_order & 0xFF00) == 0x0200) {
856 switch (mov_field_order & 0xFF) {
857 case 0x01: decoded_field_order = AV_FIELD_TT;
858 break;
859 case 0x06: decoded_field_order = AV_FIELD_BB;
860 break;
861 case 0x09: decoded_field_order = AV_FIELD_TB;
862 break;
863 case 0x0E: decoded_field_order = AV_FIELD_BT;
864 break;
865 }
866 }
867 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
868 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
869 }
870 st->codec->field_order = decoded_field_order;
871
872 return 0;
873}
874
014a5102 875/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
ae628ec1 876static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
de23f234 877{
27134437
BC
878 AVStream *st;
879 uint64_t size;
68bc33fa 880 uint8_t *buf;
27134437
BC
881
882 if (c->fc->nb_streams < 1) // will happen with jp2 files
883 return 0;
884 st= c->fc->streams[c->fc->nb_streams-1];
885 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
5a7ba586 886 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
bcd5d979 887 return AVERROR_INVALIDDATA;
68bc33fa 888 buf= av_realloc(st->codec->extradata, size);
5a7ba586 889 if (!buf)
bcd5d979 890 return AVERROR(ENOMEM);
68bc33fa
BC
891 st->codec->extradata= buf;
892 buf+= st->codec->extradata_size;
893 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
894 AV_WB32( buf , atom.size + 8);
895 AV_WL32( buf + 4, atom.type);
b7effd4e 896 avio_read(pb, buf + 8, atom.size);
de23f234
BC
897 return 0;
898}
899
ae628ec1 900static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
d9b1c197 901{
6a63ff19
BC
902 AVStream *st;
903
904 if (c->fc->nb_streams < 1)
905 return 0;
906 st = c->fc->streams[c->fc->nb_streams-1];
d9b1c197 907
5a7ba586 908 if ((uint64_t)atom.size > (1<<30))
bcd5d979 909 return AVERROR_INVALIDDATA;
115329f1 910
36ef5369 911 if (st->codec->codec_id == AV_CODEC_ID_QDM2 || st->codec->codec_id == AV_CODEC_ID_QDMC) {
ed19fafd 912 // pass all frma atom to codec, needed at least for QDMC and QDM2
3840147e 913 av_free(st->codec->extradata);
b014dd76
BC
914 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
915 if (!st->codec->extradata)
916 return AVERROR(ENOMEM);
3840147e 917 st->codec->extradata_size = atom.size;
b7effd4e 918 avio_read(pb, st->codec->extradata, atom.size);
3840147e 919 } else if (atom.size > 8) { /* to read frma, esds atoms */
bcd5d979
DH
920 int ret;
921 if ((ret = mov_read_default(c, pb, atom)) < 0)
922 return ret;
5c72cad8 923 } else
45a8a02a 924 avio_skip(pb, atom.size);
d9b1c197
RT
925 return 0;
926}
927
bde24601
BC
928/**
929 * This function reads atom content and puts data in extradata without tag
930 * nor size unlike mov_read_extradata.
931 */
ae628ec1 932static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
169eb021 933{
6a63ff19
BC
934 AVStream *st;
935
936 if (c->fc->nb_streams < 1)
937 return 0;
938 st = c->fc->streams[c->fc->nb_streams-1];
169eb021 939
5a7ba586 940 if ((uint64_t)atom.size > (1<<30))
bcd5d979 941 return AVERROR_INVALIDDATA;
568e18b1 942
4bf3c8f2 943 if (atom.size >= 10) {
59cbc4ee 944 // Broken files created by legacy versions of libavformat will
4bf3c8f2
AC
945 // wrap a whole fiel atom inside of a glbl atom.
946 unsigned size = avio_rb32(pb);
947 unsigned type = avio_rl32(pb);
948 avio_seek(pb, -8, SEEK_CUR);
949 if (type == MKTAG('f','i','e','l') && size == atom.size)
950 return mov_read_default(c, pb, atom);
951 }
01f4895c 952 av_free(st->codec->extradata);
b014dd76
BC
953 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
954 if (!st->codec->extradata)
955 return AVERROR(ENOMEM);
01f4895c 956 st->codec->extradata_size = atom.size;
b7effd4e 957 avio_read(pb, st->codec->extradata, atom.size);
169eb021
MM
958 return 0;
959}
960
89415b8e
MS
961static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
962{
963 AVStream *st;
964 uint8_t profile_level;
965
966 if (c->fc->nb_streams < 1)
967 return 0;
968 st = c->fc->streams[c->fc->nb_streams-1];
969
970 if (atom.size >= (1<<28) || atom.size < 7)
971 return AVERROR_INVALIDDATA;
972
973 profile_level = avio_r8(pb);
f1f37c70 974 if ((profile_level & 0xf0) != 0xc0)
89415b8e
MS
975 return 0;
976
977 av_free(st->codec->extradata);
978 st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
979 if (!st->codec->extradata)
980 return AVERROR(ENOMEM);
981 st->codec->extradata_size = atom.size - 7;
982 avio_seek(pb, 6, SEEK_CUR);
983 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
984 return 0;
985}
986
653d7aeb
MS
987/**
988 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
989 * but can have extradata appended at the end after the 40 bytes belonging
990 * to the struct.
991 */
ae628ec1 992static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
653d7aeb
MS
993{
994 AVStream *st;
995
996 if (c->fc->nb_streams < 1)
997 return 0;
998 if (atom.size <= 40)
999 return 0;
1000 st = c->fc->streams[c->fc->nb_streams-1];
1001
5a7ba586 1002 if ((uint64_t)atom.size > (1<<30))
bcd5d979 1003 return AVERROR_INVALIDDATA;
653d7aeb
MS
1004
1005 av_free(st->codec->extradata);
1006 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1007 if (!st->codec->extradata)
1008 return AVERROR(ENOMEM);
1009 st->codec->extradata_size = atom.size - 40;
45a8a02a 1010 avio_skip(pb, 40);
b7effd4e 1011 avio_read(pb, st->codec->extradata, atom.size - 40);
653d7aeb
MS
1012 return 0;
1013}
1014
ae628ec1 1015static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5ca1d879 1016{
6a63ff19
BC
1017 AVStream *st;
1018 MOVStreamContext *sc;
568e18b1 1019 unsigned int i, entries;
5ca1d879 1020
6a63ff19
BC
1021 if (c->fc->nb_streams < 1)
1022 return 0;
1023 st = c->fc->streams[c->fc->nb_streams-1];
1024 sc = st->priv_data;
1025
b7effd4e
AK
1026 avio_r8(pb); /* version */
1027 avio_rb24(pb); /* flags */
5ca1d879 1028
b7effd4e 1029 entries = avio_rb32(pb);
115329f1 1030
52401b82
AC
1031 if (!entries)
1032 return 0;
5a7ba586 1033 if (entries >= UINT_MAX/sizeof(int64_t))
bcd5d979 1034 return AVERROR_INVALIDDATA;
115329f1 1035
9a630c25 1036 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
5ca1d879 1037 if (!sc->chunk_offsets)
0d8f0abf
BC
1038 return AVERROR(ENOMEM);
1039 sc->chunk_count = entries;
1040
37ffe34b 1041 if (atom.type == MKTAG('s','t','c','o'))
9888ffb1 1042 for (i = 0; i < entries && !pb->eof_reached; i++)
b7effd4e 1043 sc->chunk_offsets[i] = avio_rb32(pb);
37ffe34b 1044 else if (atom.type == MKTAG('c','o','6','4'))
9888ffb1 1045 for (i = 0; i < entries && !pb->eof_reached; i++)
b7effd4e 1046 sc->chunk_offsets[i] = avio_rb64(pb);
37ffe34b 1047 else
bcd5d979 1048 return AVERROR_INVALIDDATA;
115329f1 1049
9888ffb1
LB
1050 sc->chunk_count = i;
1051
1052 if (pb->eof_reached)
1053 return AVERROR_EOF;
1054
5ca1d879
ZK
1055 return 0;
1056}
1057
2288834f
BC
1058/**
1059 * Compute codec id for 'lpcm' tag.
1060 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1061 */
36ef5369 1062enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
2288834f 1063{
261e9348
JR
1064 /* lpcm flags:
1065 * 0x1 = float
1066 * 0x2 = big-endian
1067 * 0x4 = signed
1068 */
1069 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
2288834f
BC
1070}
1071
bf985625
LB
1072static int mov_codec_id(AVStream *st, uint32_t format)
1073{
1074 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1075
1076 if (id <= 0 &&
1077 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1078 (format & 0xFFFF) == 'T' + ('S' << 8)))
1079 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1080
1081 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1082 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1083 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1084 /* skip old asf mpeg4 tag */
1085 format && format != MKTAG('m','p','4','s')) {
1086 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1087 if (id <= 0)
1088 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1089 if (id > 0)
1090 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1091 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
1092 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1093 if (id > 0)
1094 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1095 }
1096 }
1097
1098 st->codec->codec_tag = format;
1099
1100 return id;
1101}
1102
a3b53ff0
LB
1103static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1104 AVStream *st, MOVStreamContext *sc)
1105{
1106 unsigned int color_depth, len, j;
1107 int color_greyscale;
1108 int color_table_id;
1109
1110 avio_rb16(pb); /* version */
1111 avio_rb16(pb); /* revision level */
1112 avio_rb32(pb); /* vendor */
1113 avio_rb32(pb); /* temporal quality */
1114 avio_rb32(pb); /* spatial quality */
1115
1116 st->codec->width = avio_rb16(pb); /* width */
1117 st->codec->height = avio_rb16(pb); /* height */
1118
1119 avio_rb32(pb); /* horiz resolution */
1120 avio_rb32(pb); /* vert resolution */
1121 avio_rb32(pb); /* data size, always 0 */
1122 avio_rb16(pb); /* frames per samples */
1123
1124 len = avio_r8(pb); /* codec name, pascal string */
1125 if (len > 31)
1126 len = 31;
1127 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1128 if (len < 31)
1129 avio_skip(pb, 31 - len);
1130 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1131 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1132 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1133 /* Flash Media Server uses tag H263 with Sorenson Spark */
1134 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1135 !memcmp(st->codec->codec_name, "Sorenson H263", 13))
1136 st->codec->codec_id = AV_CODEC_ID_FLV1;
1137
1138 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1139 color_table_id = avio_rb16(pb); /* colortable id */
1140 av_dlog(c->fc, "depth %d, ctab id %d\n",
1141 st->codec->bits_per_coded_sample, color_table_id);
1142 /* figure out the palette situation */
1143 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1144 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1145
1146 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1147 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1148 /* for palette traversal */
1149 unsigned int color_start, color_count, color_end;
1150 unsigned char r, g, b;
1151
1152 if (color_greyscale) {
1153 int color_index, color_dec;
1154 /* compute the greyscale palette */
1155 st->codec->bits_per_coded_sample = color_depth;
1156 color_count = 1 << color_depth;
1157 color_index = 255;
1158 color_dec = 256 / (color_count - 1);
1159 for (j = 0; j < color_count; j++) {
1160 r = g = b = color_index;
1161 sc->palette[j] = (r << 16) | (g << 8) | (b);
1162 color_index -= color_dec;
1163 if (color_index < 0)
1164 color_index = 0;
1165 }
1166 } else if (color_table_id) {
1167 const uint8_t *color_table;
1168 /* if flag bit 3 is set, use the default palette */
1169 color_count = 1 << color_depth;
1170 if (color_depth == 2)
1171 color_table = ff_qt_default_palette_4;
1172 else if (color_depth == 4)
1173 color_table = ff_qt_default_palette_16;
1174 else
1175 color_table = ff_qt_default_palette_256;
1176
1177 for (j = 0; j < color_count; j++) {
1178 r = color_table[j * 3 + 0];
1179 g = color_table[j * 3 + 1];
1180 b = color_table[j * 3 + 2];
1181 sc->palette[j] = (r << 16) | (g << 8) | (b);
1182 }
1183 } else {
1184 /* load the palette from the file */
1185 color_start = avio_rb32(pb);
1186 color_count = avio_rb16(pb);
1187 color_end = avio_rb16(pb);
1188 if ((color_start <= 255) && (color_end <= 255)) {
1189 for (j = color_start; j <= color_end; j++) {
1190 /* each R, G, or B component is 16 bits;
1191 * only use the top 8 bits; skip alpha bytes
1192 * up front */
1193 avio_r8(pb);
1194 avio_r8(pb);
1195 r = avio_r8(pb);
1196 avio_r8(pb);
1197 g = avio_r8(pb);
1198 avio_r8(pb);
1199 b = avio_r8(pb);
1200 avio_r8(pb);
1201 sc->palette[j] = (r << 16) | (g << 8) | (b);
1202 }
1203 }
1204 }
1205 sc->has_palette = 1;
1206 }
1207}
1208
ae628ec1 1209int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
5ca1d879 1210{
6a63ff19
BC
1211 AVStream *st;
1212 MOVStreamContext *sc;
a3b53ff0 1213 int pseudo_stream_id;
b595afaa 1214
6a63ff19
BC
1215 if (c->fc->nb_streams < 1)
1216 return 0;
1217 st = c->fc->streams[c->fc->nb_streams-1];
1218 sc = st->priv_data;
1219
9888ffb1
LB
1220 for (pseudo_stream_id = 0;
1221 pseudo_stream_id < entries && !pb->eof_reached;
1222 pseudo_stream_id++) {
117a9190 1223 //Parsing Sample description table
36ef5369 1224 enum AVCodecID id;
28155113 1225 int dref_id = 1;
3491866a 1226 MOVAtom a = { AV_RL32("stsd") };
a2704c97 1227 int64_t start_pos = avio_tell(pb);
a5ea623b 1228 uint32_t size = avio_rb32(pb); /* size */
b7effd4e 1229 uint32_t format = avio_rl32(pb); /* data format */
5cd62665 1230
28155113 1231 if (size >= 16) {
b7effd4e
AK
1232 avio_rb32(pb); /* reserved */
1233 avio_rb16(pb); /* reserved */
1234 dref_id = avio_rb16(pb);
a5ea623b
MN
1235 } else {
1236 av_log(c->fc, AV_LOG_ERROR, "invalid size %d in stsd\n", size);
1237 return AVERROR_INVALIDDATA;
28155113 1238 }
0e7eed09 1239
744a9c75 1240 if (st->codec->codec_tag &&
978677a7 1241 st->codec->codec_tag != format &&
167f3b8d 1242 (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
1c126b4f 1243 : st->codec->codec_tag != MKTAG('j','p','e','g'))
744a9c75 1244 ){
7ce68923
DB
1245 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1246 * export it as a separate AVStream but this needs a few changes
1247 * in the MOV demuxer, patch welcome. */
adc73054 1248 multiple_stsd:
285a3da9 1249 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
45a8a02a 1250 avio_skip(pb, size - (avio_tell(pb) - start_pos));
e7cc4b52
BC
1251 continue;
1252 }
adc73054
BC
1253 /* we cannot demux concatenated h264 streams because of different extradata */
1254 if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1255 goto multiple_stsd;
978677a7 1256 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
221e21b7 1257 sc->dref_id= dref_id;
e7cc4b52 1258
bf985625 1259 id = mov_codec_id(st, format);
99487f42 1260
dfd2a005 1261 av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
29c90869
BC
1262 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1263 (format >> 24) & 0xff, st->codec->codec_type);
a20da52c 1264
5a7ba586 1265 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
01f4895c 1266 st->codec->codec_id = id;
a3b53ff0 1267 mov_parse_stsd_video(c, pb, st, sc);
5a7ba586 1268 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
aaef2bb3 1269 int bits_per_sample, flags;
b7effd4e 1270 uint16_t version = avio_rb16(pb);
b595afaa 1271
99487f42 1272 st->codec->codec_id = id;
b7effd4e
AK
1273 avio_rb16(pb); /* revision level */
1274 avio_rb32(pb); /* vendor */
6d6d7970 1275
b7effd4e 1276 st->codec->channels = avio_rb16(pb); /* channel count */
dfd2a005 1277 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
b7effd4e 1278 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
de23f234 1279
b7effd4e
AK
1280 sc->audio_cid = avio_rb16(pb);
1281 avio_rb16(pb); /* packet size = 0 */
de23f234 1282
b7effd4e 1283 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
de23f234 1284
5ef3ad59 1285 //Read QT version 1 fields. In version 0 these do not exist.
dfd2a005 1286 av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
5a7ba586
LB
1287 if (!c->isom) {
1288 if (version==1) {
b7effd4e
AK
1289 sc->samples_per_frame = avio_rb32(pb);
1290 avio_rb32(pb); /* bytes per packet */
1291 sc->bytes_per_frame = avio_rb32(pb);
1292 avio_rb32(pb); /* bytes per sample */
5a7ba586 1293 } else if (version==2) {
b7effd4e 1294 avio_rb32(pb); /* sizeof struct only */
3383a53e 1295 st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
b7effd4e
AK
1296 st->codec->channels = avio_rb32(pb);
1297 avio_rb32(pb); /* always 0x7F000000 */
1298 st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1299 flags = avio_rb32(pb); /* lpcm format specific flag */
1300 sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1301 sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
2288834f 1302 if (format == MKTAG('l','p','c','m'))
2d423666 1303 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
5ef3ad59
BC
1304 }
1305 }
1306
de23f234 1307 switch (st->codec->codec_id) {
36ef5369
AK
1308 case AV_CODEC_ID_PCM_S8:
1309 case AV_CODEC_ID_PCM_U8:
dd1c8f3e 1310 if (st->codec->bits_per_coded_sample == 16)
36ef5369 1311 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
b72708f8 1312 break;
36ef5369
AK
1313 case AV_CODEC_ID_PCM_S16LE:
1314 case AV_CODEC_ID_PCM_S16BE:
dd1c8f3e 1315 if (st->codec->bits_per_coded_sample == 8)
36ef5369 1316 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
dd1c8f3e 1317 else if (st->codec->bits_per_coded_sample == 24)
6b477e1b 1318 st->codec->codec_id =
36ef5369
AK
1319 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1320 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
de23f234 1321 break;
53152765 1322 /* set values for old format before stsd version 1 appeared */
36ef5369 1323 case AV_CODEC_ID_MACE3:
53152765
BC
1324 sc->samples_per_frame = 6;
1325 sc->bytes_per_frame = 2*st->codec->channels;
1326 break;
36ef5369 1327 case AV_CODEC_ID_MACE6:
53152765
BC
1328 sc->samples_per_frame = 6;
1329 sc->bytes_per_frame = 1*st->codec->channels;
1330 break;
36ef5369 1331 case AV_CODEC_ID_ADPCM_IMA_QT:
53152765
BC
1332 sc->samples_per_frame = 64;
1333 sc->bytes_per_frame = 34*st->codec->channels;
1334 break;
36ef5369 1335 case AV_CODEC_ID_GSM:
cc326d2b
BC
1336 sc->samples_per_frame = 160;
1337 sc->bytes_per_frame = 33;
1338 break;
de23f234
BC
1339 default:
1340 break;
6d6d7970 1341 }
14342fd5 1342
9770089d
BC
1343 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1344 if (bits_per_sample) {
dd1c8f3e 1345 st->codec->bits_per_coded_sample = bits_per_sample;
9770089d
BC
1346 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1347 }
5a7ba586 1348 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
58e9f2ed
DC
1349 // ttxt stsd contains display flags, justification, background
1350 // color, fonts, and default styles, so fake an atom to read it
a2704c97 1351 MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
fb9ac654 1352 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
3dd36041 1353 mov_read_glbl(c, pb, fake_atom);
cc8d87b7 1354 st->codec->codec_id= id;
6cdbff63
DC
1355 st->codec->width = sc->width;
1356 st->codec->height = sc->height;
de23f234
BC
1357 } else {
1358 /* other codec type, just skip (rtp, mp4s, tmcd ...) */
45a8a02a 1359 avio_skip(pb, size - (avio_tell(pb) - start_pos));
6cea494e 1360 }
de23f234 1361 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
a2704c97 1362 a.size = size - (avio_tell(pb) - start_pos);
9cf0419b 1363 if (a.size > 8) {
bcd5d979
DH
1364 int ret;
1365 if ((ret = mov_read_default(c, pb, a)) < 0)
1366 return ret;
9cf0419b 1367 } else if (a.size > 0)
45a8a02a 1368 avio_skip(pb, a.size);
6cea494e 1369 }
115329f1 1370
9888ffb1
LB
1371 if (pb->eof_reached)
1372 return AVERROR_EOF;
1373
5a7ba586 1374 if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
302c389e 1375 st->codec->sample_rate= sc->time_scale;
e31bd3e3 1376
d00f8e17 1377 /* special codec parameters handling */
e31bd3e3 1378 switch (st->codec->codec_id) {
b250f9c6 1379#if CONFIG_DV_DEMUXER
36ef5369 1380 case AV_CODEC_ID_DVAUDIO:
8e2fd8e1 1381 c->dv_fctx = avformat_alloc_context();
ab88b25f 1382 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
b60c0454
BC
1383 if (!c->dv_demux) {
1384 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
bcd5d979 1385 return AVERROR(ENOMEM);
b60c0454
BC
1386 }
1387 sc->dv_audio_container = 1;
36ef5369 1388 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
b60c0454 1389 break;
989ac5a6 1390#endif
b95319a2 1391 /* no ifdef since parameters are always those */
36ef5369 1392 case AV_CODEC_ID_QCELP:
17ad7b24
BC
1393 // force sample rate for qcelp when not stored in mov
1394 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1395 st->codec->sample_rate = 8000;
061f407e 1396 st->codec->channels= 1; /* really needed */
73b458e3 1397 break;
36ef5369 1398 case AV_CODEC_ID_AMR_NB:
b95319a2 1399 st->codec->channels= 1; /* really needed */
f06188d5 1400 /* force sample rate for amr, stsd in 3gp does not store sample rate */
237f1329 1401 st->codec->sample_rate = 8000;
237f1329 1402 break;
36ef5369 1403 case AV_CODEC_ID_AMR_WB:
237f1329
CEH
1404 st->codec->channels = 1;
1405 st->codec->sample_rate = 16000;
b95319a2 1406 break;
36ef5369
AK
1407 case AV_CODEC_ID_MP2:
1408 case AV_CODEC_ID_MP3:
72415b2a 1409 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
57004ff1 1410 st->need_parsing = AVSTREAM_PARSE_FULL;
a41104f8 1411 break;
36ef5369
AK
1412 case AV_CODEC_ID_GSM:
1413 case AV_CODEC_ID_ADPCM_MS:
1414 case AV_CODEC_ID_ADPCM_IMA_WAV:
1415 case AV_CODEC_ID_ILBC:
74e9b9ae
BC
1416 st->codec->block_align = sc->bytes_per_frame;
1417 break;
36ef5369 1418 case AV_CODEC_ID_ALAC:
a1532824 1419 if (st->codec->extradata_size == 36) {
364df7b7 1420 st->codec->channels = AV_RB8 (st->codec->extradata+21);
c6f1e29a 1421 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
a1532824 1422 }
be511925 1423 break;
36ef5369 1424 case AV_CODEC_ID_VC1:
755cd419
AK
1425 st->need_parsing = AVSTREAM_PARSE_FULL;
1426 break;
e31bd3e3
BC
1427 default:
1428 break;
1429 }
5cd62665 1430
6cea494e
ZK
1431 return 0;
1432}
1433
ae628ec1 1434static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
dc2cabd0
MS
1435{
1436 int entries;
1437
b7effd4e
AK
1438 avio_r8(pb); /* version */
1439 avio_rb24(pb); /* flags */
1440 entries = avio_rb32(pb);
dc2cabd0
MS
1441
1442 return ff_mov_read_stsd_entries(c, pb, entries);
1443}
1444
ae628ec1 1445static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6cea494e 1446{
6a63ff19
BC
1447 AVStream *st;
1448 MOVStreamContext *sc;
568e18b1 1449 unsigned int i, entries;
b6a17df4 1450
6a63ff19
BC
1451 if (c->fc->nb_streams < 1)
1452 return 0;
1453 st = c->fc->streams[c->fc->nb_streams-1];
1454 sc = st->priv_data;
1455
b7effd4e
AK
1456 avio_r8(pb); /* version */
1457 avio_rb24(pb); /* flags */
6cea494e 1458
b7effd4e 1459 entries = avio_rb32(pb);
115329f1 1460
dfd2a005 1461 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
f8c18cd7 1462
52401b82
AC
1463 if (!entries)
1464 return 0;
5a7ba586 1465 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
bcd5d979 1466 return AVERROR_INVALIDDATA;
04e06cfa
BC
1467 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1468 if (!sc->stsc_data)
0d8f0abf 1469 return AVERROR(ENOMEM);
0d8f0abf 1470
9888ffb1 1471 for (i = 0; i < entries && !pb->eof_reached; i++) {
b7effd4e
AK
1472 sc->stsc_data[i].first = avio_rb32(pb);
1473 sc->stsc_data[i].count = avio_rb32(pb);
1474 sc->stsc_data[i].id = avio_rb32(pb);
6cea494e 1475 }
9888ffb1
LB
1476
1477 sc->stsc_count = i;
1478
1479 if (pb->eof_reached)
1480 return AVERROR_EOF;
1481
6cea494e
ZK
1482 return 0;
1483}
1484
ae628ec1 1485static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
171a3531
BC
1486{
1487 AVStream *st;
1488 MOVStreamContext *sc;
1489 unsigned i, entries;
1490
1491 if (c->fc->nb_streams < 1)
1492 return 0;
1493 st = c->fc->streams[c->fc->nb_streams-1];
1494 sc = st->priv_data;
1495
b7effd4e 1496 avio_rb32(pb); // version + flags
171a3531 1497
b7effd4e 1498 entries = avio_rb32(pb);
171a3531 1499 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
bcd5d979 1500 return AVERROR_INVALIDDATA;
171a3531
BC
1501 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1502 if (!sc->stps_data)
1503 return AVERROR(ENOMEM);
171a3531 1504
9888ffb1 1505 for (i = 0; i < entries && !pb->eof_reached; i++) {
b7effd4e 1506 sc->stps_data[i] = avio_rb32(pb);
dfd2a005 1507 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
171a3531
BC
1508 }
1509
9888ffb1
LB
1510 sc->stps_count = i;
1511
1512 if (pb->eof_reached)
1513 return AVERROR_EOF;
1514
171a3531
BC
1515 return 0;
1516}
1517
ae628ec1 1518static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
247d56f5 1519{
6a63ff19
BC
1520 AVStream *st;
1521 MOVStreamContext *sc;
568e18b1 1522 unsigned int i, entries;
247d56f5 1523
6a63ff19
BC
1524 if (c->fc->nb_streams < 1)
1525 return 0;
1526 st = c->fc->streams[c->fc->nb_streams-1];
1527 sc = st->priv_data;
1528
b7effd4e
AK
1529 avio_r8(pb); /* version */
1530 avio_rb24(pb); /* flags */
247d56f5 1531
b7effd4e 1532 entries = avio_rb32(pb);
115329f1 1533
dfd2a005 1534 av_dlog(c->fc, "keyframe_count = %d\n", entries);
0d8f0abf 1535
29a20ac4 1536 if (!entries)
accea4d9
YN
1537 {
1538 sc->keyframe_absent = 1;
29a20ac4 1539 return 0;
accea4d9 1540 }
5a7ba586 1541 if (entries >= UINT_MAX / sizeof(int))
bcd5d979 1542 return AVERROR_INVALIDDATA;
1c02d96f 1543 sc->keyframes = av_malloc(entries * sizeof(int));
247d56f5 1544 if (!sc->keyframes)
0d8f0abf 1545 return AVERROR(ENOMEM);
0d8f0abf 1546
9888ffb1 1547 for (i = 0; i < entries && !pb->eof_reached; i++) {
b7effd4e 1548 sc->keyframes[i] = avio_rb32(pb);
dfd2a005 1549 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
247d56f5 1550 }
9888ffb1
LB
1551
1552 sc->keyframe_count = i;
1553
1554 if (pb->eof_reached)
1555 return AVERROR_EOF;
1556
247d56f5
BB
1557 return 0;
1558}
1559
ae628ec1 1560static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6cea494e 1561{
6a63ff19
BC
1562 AVStream *st;
1563 MOVStreamContext *sc;
bd27eed6
AC
1564 unsigned int i, entries, sample_size, field_size, num_bytes;
1565 GetBitContext gb;
1566 unsigned char* buf;
b6a17df4 1567
6a63ff19
BC
1568 if (c->fc->nb_streams < 1)
1569 return 0;
1570 st = c->fc->streams[c->fc->nb_streams-1];
1571 sc = st->priv_data;
1572
b7effd4e
AK
1573 avio_r8(pb); /* version */
1574 avio_rb24(pb); /* flags */
5cd62665 1575
bd27eed6 1576 if (atom.type == MKTAG('s','t','s','z')) {
b7effd4e 1577 sample_size = avio_rb32(pb);
d0dab0ec
AC
1578 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1579 sc->sample_size = sample_size;
1580 field_size = 32;
bd27eed6
AC
1581 } else {
1582 sample_size = 0;
b7effd4e
AK
1583 avio_rb24(pb); /* reserved */
1584 field_size = avio_r8(pb);
bd27eed6 1585 }
b7effd4e 1586 entries = avio_rb32(pb);
0d8f0abf 1587
dfd2a005 1588 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
568e18b1 1589
6cea494e 1590 sc->sample_count = entries;
b72708f8
BC
1591 if (sample_size)
1592 return 0;
1593
bd27eed6
AC
1594 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1595 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
bcd5d979 1596 return AVERROR_INVALIDDATA;
bd27eed6
AC
1597 }
1598
52401b82
AC
1599 if (!entries)
1600 return 0;
e4bc8af1 1601 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
bcd5d979 1602 return AVERROR_INVALIDDATA;
1c02d96f 1603 sc->sample_sizes = av_malloc(entries * sizeof(int));
b6a17df4 1604 if (!sc->sample_sizes)
0d8f0abf
BC
1605 return AVERROR(ENOMEM);
1606
bd27eed6
AC
1607 num_bytes = (entries*field_size+4)>>3;
1608
08a5b4e9 1609 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
bd27eed6
AC
1610 if (!buf) {
1611 av_freep(&sc->sample_sizes);
1612 return AVERROR(ENOMEM);
1613 }
1614
b7effd4e 1615 if (avio_read(pb, buf, num_bytes) < num_bytes) {
bd27eed6
AC
1616 av_freep(&sc->sample_sizes);
1617 av_free(buf);
bcd5d979 1618 return AVERROR_INVALIDDATA;
bd27eed6
AC
1619 }
1620
1621 init_get_bits(&gb, buf, 8*num_bytes);
1622
9888ffb1 1623 for (i = 0; i < entries && !pb->eof_reached; i++) {
bd27eed6 1624 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
bc7d0517
MS
1625 sc->data_size += sc->sample_sizes[i];
1626 }
bd27eed6 1627
9888ffb1
LB
1628 sc->sample_count = i;
1629
1630 if (pb->eof_reached)
1631 return AVERROR_EOF;
1632
bd27eed6 1633 av_free(buf);
6cea494e
ZK
1634 return 0;
1635}
1636
ae628ec1 1637static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
0147f198 1638{
6a63ff19
BC
1639 AVStream *st;
1640 MOVStreamContext *sc;
568e18b1 1641 unsigned int i, entries;
d957696f
MN
1642 int64_t duration=0;
1643 int64_t total_sample_count=0;
b6a17df4 1644
6a63ff19
BC
1645 if (c->fc->nb_streams < 1)
1646 return 0;
1647 st = c->fc->streams[c->fc->nb_streams-1];
1648 sc = st->priv_data;
1649
b7effd4e
AK
1650 avio_r8(pb); /* version */
1651 avio_rb24(pb); /* flags */
1652 entries = avio_rb32(pb);
0d8f0abf 1653
5a7ba586
LB
1654 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1655 c->fc->nb_streams-1, entries);
0d8f0abf 1656
6d23d197
AC
1657 if (!entries)
1658 return 0;
1659 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
30c3d976 1660 return AVERROR(EINVAL);
5a7ba586 1661
c3e92a6c 1662 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
c1da59fa 1663 if (!sc->stts_data)
0d8f0abf 1664 return AVERROR(ENOMEM);
5a7ba586 1665
9888ffb1 1666 for (i = 0; i < entries && !pb->eof_reached; i++) {
cd461d48
MN
1667 int sample_duration;
1668 int sample_count;
0147f198 1669
b7effd4e
AK
1670 sample_count=avio_rb32(pb);
1671 sample_duration = avio_rb32(pb);
cd7352d5
MN
1672 sc->stts_data[i].count= sample_count;
1673 sc->stts_data[i].duration= sample_duration;
1674
5a7ba586
LB
1675 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1676 sample_count, sample_duration);
4e5ef14f 1677
7e815047 1678 duration+=(int64_t)sample_duration*sample_count;
891f64b3 1679 total_sample_count+=sample_count;
891f64b3 1680 }
1681
9888ffb1
LB
1682 sc->stts_count = i;
1683
1684 if (pb->eof_reached)
1685 return AVERROR_EOF;
1686
961e0ccd 1687 st->nb_frames= total_sample_count;
5a7ba586 1688 if (duration)
961e0ccd 1689 st->duration= duration;
7f19bdc2 1690 sc->track_end = duration;
0147f198
FR
1691 return 0;
1692}
1693
ae628ec1 1694static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
c4ac052b 1695{
6a63ff19
BC
1696 AVStream *st;
1697 MOVStreamContext *sc;
c4ac052b
MN
1698 unsigned int i, entries;
1699
6a63ff19
BC
1700 if (c->fc->nb_streams < 1)
1701 return 0;
1702 st = c->fc->streams[c->fc->nb_streams-1];
1703 sc = st->priv_data;
1704
b7effd4e
AK
1705 avio_r8(pb); /* version */
1706 avio_rb24(pb); /* flags */
1707 entries = avio_rb32(pb);
0d8f0abf 1708
dfd2a005 1709 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
0d8f0abf 1710
52401b82
AC
1711 if (!entries)
1712 return 0;
5a7ba586 1713 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
bcd5d979 1714 return AVERROR_INVALIDDATA;
c3e92a6c 1715 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
c1da59fa 1716 if (!sc->ctts_data)
0d8f0abf 1717 return AVERROR(ENOMEM);
4e5ef14f 1718
9888ffb1 1719 for (i = 0; i < entries && !pb->eof_reached; i++) {
b7effd4e
AK
1720 int count =avio_rb32(pb);
1721 int duration =avio_rb32(pb);
70a61ed4
MN
1722
1723 sc->ctts_data[i].count = count;
1724 sc->ctts_data[i].duration= duration;
e7452721
BC
1725 if (duration < 0)
1726 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
c4ac052b 1727 }
e7452721 1728
9888ffb1
LB
1729 sc->ctts_count = i;
1730
1731 if (pb->eof_reached)
1732 return AVERROR_EOF;
1733
dfd2a005 1734 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
e7452721 1735
c4ac052b
MN
1736 return 0;
1737}
1738
d17d0ec8
YN
1739static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1740{
1741 AVStream *st;
1742 MOVStreamContext *sc;
1743 unsigned int i, entries;
1744 uint8_t version;
1745 uint32_t grouping_type;
1746
1747 if (c->fc->nb_streams < 1)
1748 return 0;
1749 st = c->fc->streams[c->fc->nb_streams-1];
1750 sc = st->priv_data;
1751
1752 version = avio_r8(pb); /* version */
1753 avio_rb24(pb); /* flags */
1754 grouping_type = avio_rl32(pb);
1755 if (grouping_type != MKTAG( 'r','a','p',' '))
1756 return 0; /* only support 'rap ' grouping */
1757 if (version == 1)
1758 avio_rb32(pb); /* grouping_type_parameter */
1759
1760 entries = avio_rb32(pb);
1761 if (!entries)
1762 return 0;
1763 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
1764 return AVERROR_INVALIDDATA;
1765 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
1766 if (!sc->rap_group)
1767 return AVERROR(ENOMEM);
1768
1769 for (i = 0; i < entries && !pb->eof_reached; i++) {
1770 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
1771 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
1772 }
1773
1774 sc->rap_group_count = i;
1775
1776 return pb->eof_reached ? AVERROR_EOF : 0;
1777}
1778
1e77810d
BC
1779static void mov_build_index(MOVContext *mov, AVStream *st)
1780{
1781 MOVStreamContext *sc = st->priv_data;
bc5c918e 1782 int64_t current_offset;
1e77810d
BC
1783 int64_t current_dts = 0;
1784 unsigned int stts_index = 0;
1785 unsigned int stsc_index = 0;
1786 unsigned int stss_index = 0;
171a3531 1787 unsigned int stps_index = 0;
1e77810d 1788 unsigned int i, j;
c5898e86 1789 uint64_t stream_size = 0;
4f7c7624 1790 AVIndexEntry *mem;
1e77810d 1791
baf2ffd3 1792 /* adjust first dts according to edit list */
c3024f9e 1793 if (sc->time_offset && mov->time_scale > 0) {
f33a6a22
YN
1794 if (sc->time_offset < 0)
1795 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
1796 current_dts = -sc->time_offset;
69e7ad8d 1797 if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
4af7166f 1798 sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
f03a081d
BC
1799 /* more than 16 frames delay, dts are likely wrong
1800 this happens with files created by iMovie */
1801 sc->wrong_dts = 1;
1802 st->codec->has_b_frames = 1;
1803 }
baf2ffd3
BC
1804 }
1805
d3bc61ac 1806 /* only use old uncompressed audio chunk demuxing when stts specifies it */
72415b2a 1807 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
d3bc61ac 1808 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1e77810d
BC
1809 unsigned int current_sample = 0;
1810 unsigned int stts_sample = 0;
171a3531 1811 unsigned int sample_size;
1e77810d 1812 unsigned int distance = 0;
d17d0ec8
YN
1813 unsigned int rap_group_index = 0;
1814 unsigned int rap_group_sample = 0;
1815 int rap_group_present = sc->rap_group_count && sc->rap_group;
94c9bf88 1816 int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
1e77810d 1817
4b29ed39
BC
1818 current_dts -= sc->dts_shift;
1819
52401b82
AC
1820 if (!sc->sample_count)
1821 return;
4f7c7624 1822 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
987e857f 1823 return;
4f7c7624
RB
1824 mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1825 if (!mem)
987e857f 1826 return;
4f7c7624
RB
1827 st->index_entries = mem;
1828 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
987e857f 1829
1e77810d
BC
1830 for (i = 0; i < sc->chunk_count; i++) {
1831 current_offset = sc->chunk_offsets[i];
9dd94f83 1832 while (stsc_index + 1 < sc->stsc_count &&
04e06cfa 1833 i + 1 == sc->stsc_data[stsc_index + 1].first)
1e77810d 1834 stsc_index++;
04e06cfa 1835 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
171a3531 1836 int keyframe = 0;
1e77810d
BC
1837 if (current_sample >= sc->sample_count) {
1838 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
f0f2218d 1839 return;
1e77810d 1840 }
171a3531 1841
accea4d9 1842 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
171a3531 1843 keyframe = 1;
1e77810d
BC
1844 if (stss_index + 1 < sc->keyframe_count)
1845 stss_index++;
171a3531
BC
1846 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1847 keyframe = 1;
1848 if (stps_index + 1 < sc->stps_count)
1849 stps_index++;
1e77810d 1850 }
d17d0ec8
YN
1851 if (rap_group_present && rap_group_index < sc->rap_group_count) {
1852 if (sc->rap_group[rap_group_index].index > 0)
1853 keyframe = 1;
1854 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
1855 rap_group_sample = 0;
1856 rap_group_index++;
1857 }
1858 }
171a3531
BC
1859 if (keyframe)
1860 distance = 0;
1e77810d 1861 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
5a7ba586 1862 if (sc->pseudo_stream_id == -1 ||
04e06cfa 1863 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
987e857f
BC
1864 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1865 e->pos = current_offset;
1866 e->timestamp = current_dts;
1867 e->size = sample_size;
1868 e->min_distance = distance;
1869 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
dfd2a005 1870 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
585dac65
BC
1871 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1872 current_offset, current_dts, sample_size, distance, keyframe);
1873 }
6c00a9de 1874
1e77810d 1875 current_offset += sample_size;
c5898e86 1876 stream_size += sample_size;
bbe46bc4 1877 current_dts += sc->stts_data[stts_index].duration;
1e77810d
BC
1878 distance++;
1879 stts_sample++;
1880 current_sample++;
1881 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1882 stts_sample = 0;
1883 stts_index++;
1884 }
1885 }
1886 }
fedb1eca
BC
1887 if (st->duration > 0)
1888 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
7e69621f 1889 } else {
987e857f 1890 unsigned chunk_samples, total = 0;
7e69621f 1891
987e857f
BC
1892 // compute total chunk count
1893 for (i = 0; i < sc->stsc_count; i++) {
1894 unsigned count, chunk_count;
7e69621f 1895
987e857f 1896 chunk_samples = sc->stsc_data[i].count;
a294a7a1
CEH
1897 if (i != sc->stsc_count - 1 &&
1898 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
7e69621f
BC
1899 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1900 return;
1901 }
1902
987e857f
BC
1903 if (sc->samples_per_frame >= 160) { // gsm
1904 count = chunk_samples / sc->samples_per_frame;
1905 } else if (sc->samples_per_frame > 1) {
1906 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1907 count = (chunk_samples+samples-1) / samples;
1908 } else {
1909 count = (chunk_samples+1023) / 1024;
1910 }
1911
1912 if (i < sc->stsc_count - 1)
1913 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1914 else
1915 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1916 total += chunk_count * count;
1917 }
1918
dfd2a005 1919 av_dlog(mov->fc, "chunk count %d\n", total);
4f7c7624 1920 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
987e857f 1921 return;
4f7c7624
RB
1922 mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
1923 if (!mem)
987e857f 1924 return;
4f7c7624
RB
1925 st->index_entries = mem;
1926 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
987e857f
BC
1927
1928 // populate index
1929 for (i = 0; i < sc->chunk_count; i++) {
1930 current_offset = sc->chunk_offsets[i];
1931 if (stsc_index + 1 < sc->stsc_count &&
1932 i + 1 == sc->stsc_data[stsc_index + 1].first)
1933 stsc_index++;
1934 chunk_samples = sc->stsc_data[stsc_index].count;
1935
7e69621f 1936 while (chunk_samples > 0) {
987e857f 1937 AVIndexEntry *e;
7e69621f
BC
1938 unsigned size, samples;
1939
1940 if (sc->samples_per_frame >= 160) { // gsm
1941 samples = sc->samples_per_frame;
1942 size = sc->bytes_per_frame;
1943 } else {
1944 if (sc->samples_per_frame > 1) {
1945 samples = FFMIN((1024 / sc->samples_per_frame)*
1946 sc->samples_per_frame, chunk_samples);
1947 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1e77810d 1948 } else {
7e69621f
BC
1949 samples = FFMIN(1024, chunk_samples);
1950 size = samples * sc->sample_size;
1e77810d
BC
1951 }
1952 }
7e69621f 1953
987e857f
BC
1954 if (st->nb_index_entries >= total) {
1955 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1956 return;
1957 }
1958 e = &st->index_entries[st->nb_index_entries++];
1959 e->pos = current_offset;
1960 e->timestamp = current_dts;
1961 e->size = size;
1962 e->min_distance = 0;
1963 e->flags = AVINDEX_KEYFRAME;
dfd2a005 1964 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
117a9190 1965 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
7e69621f
BC
1966 size, samples);
1967
1968 current_offset += size;
bbe46bc4 1969 current_dts += samples;
7e69621f 1970 chunk_samples -= samples;
1e77810d
BC
1971 }
1972 }
1973 }
1e77810d 1974}
bd991df2 1975
9d77a8fa
MS
1976static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
1977 AVIOInterruptCB *int_cb)
adeb9071 1978{
6a245905
MN
1979 /* try relative path, we do not try the absolute because it can leak information about our
1980 system to an attacker */
adeb9071
BC
1981 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1982 char filename[1024];
1983 char *src_path;
1984 int i, l;
1985
1986 /* find a source dir */
1987 src_path = strrchr(src, '/');
1988 if (src_path)
1989 src_path++;
1990 else
1991 src_path = src;
1992
1993 /* find a next level down to target */
1994 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1995 if (ref->path[l] == '/') {
1996 if (i == ref->nlvl_to - 1)
1997 break;
1998 else
1999 i++;
2000 }
2001
2002 /* compose filename if next level down to target was found */
bbdf0d22 2003 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
adeb9071
BC
2004 memcpy(filename, src, src_path - src);
2005 filename[src_path - src] = 0;
2006
2007 for (i = 1; i < ref->nlvl_from; i++)
2008 av_strlcat(filename, "../", 1024);
2009
2010 av_strlcat(filename, ref->path + l + 1, 1024);
2011
9d77a8fa 2012 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
adeb9071
BC
2013 return 0;
2014 }
2015 }
2016
2017 return AVERROR(ENOENT);
628b16f4 2018}
adeb9071 2019
ae628ec1 2020static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5ca1d879
ZK
2021{
2022 AVStream *st;
2023 MOVStreamContext *sc;
bd991df2 2024 int ret;
5ca1d879 2025
84ad31ff 2026 st = avformat_new_stream(c->fc, NULL);
3efe8848 2027 if (!st) return AVERROR(ENOMEM);
84ad31ff 2028 st->id = c->fc->nb_streams;
9a630c25 2029 sc = av_mallocz(sizeof(MOVStreamContext));
2922cbdb 2030 if (!sc) return AVERROR(ENOMEM);
5ca1d879 2031
5ca1d879 2032 st->priv_data = sc;
72415b2a 2033 st->codec->codec_type = AVMEDIA_TYPE_DATA;
64d50fa5 2034 sc->ffindex = st->index;
5ca1d879 2035
bd991df2
BC
2036 if ((ret = mov_read_default(c, pb, atom)) < 0)
2037 return ret;
2038
2039 /* sanity checks */
6c00a9de
BC
2040 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2041 (!sc->sample_size && !sc->sample_count))) {
6282c5f4
BC
2042 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2043 st->index);
bd991df2
BC
2044 return 0;
2045 }
6c00a9de 2046
c3024f9e 2047 if (sc->time_scale <= 0) {
507330b9 2048 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
6c00a9de 2049 sc->time_scale = c->time_scale;
c3024f9e 2050 if (sc->time_scale <= 0)
507330b9
BC
2051 sc->time_scale = 1;
2052 }
6c00a9de 2053
c3f9ebf7 2054 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
bd991df2 2055
bd991df2
BC
2056 mov_build_index(c, st);
2057
2058 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
adeb9071 2059 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
9d77a8fa 2060 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
adeb9071
BC
2061 av_log(c->fc, AV_LOG_ERROR,
2062 "stream %d, error opening alias: path='%s', dir='%s', "
2063 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2064 st->index, dref->path, dref->dir, dref->filename,
2065 dref->volume, dref->nlvl_from, dref->nlvl_to);
bd991df2
BC
2066 } else
2067 sc->pb = c->fc->pb;
2068
72415b2a 2069 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
525fcb27
AW
2070 if (!st->sample_aspect_ratio.num &&
2071 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2072 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2073 ((double)st->codec->width * sc->height), INT_MAX);
c3aeaa54
BC
2074 }
2075
80b6b314
JG
2076 if (st->duration != AV_NOPTS_VALUE)
2077 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2078 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
c9566115
BC
2079 }
2080
bd991df2 2081 switch (st->codec->codec_id) {
b250f9c6 2082#if CONFIG_H261_DECODER
36ef5369 2083 case AV_CODEC_ID_H261:
bd991df2 2084#endif
b250f9c6 2085#if CONFIG_H263_DECODER
36ef5369 2086 case AV_CODEC_ID_H263:
bd991df2 2087#endif
b250f9c6 2088#if CONFIG_MPEG4_DECODER
36ef5369 2089 case AV_CODEC_ID_MPEG4:
bd991df2 2090#endif
6c00a9de 2091 st->codec->width = 0; /* let decoder init width/height */
bd991df2
BC
2092 st->codec->height= 0;
2093 break;
bd991df2 2094 }
f9900374
BC
2095
2096 /* Do not need those anymore. */
2097 av_freep(&sc->chunk_offsets);
04e06cfa 2098 av_freep(&sc->stsc_data);
f9900374
BC
2099 av_freep(&sc->sample_sizes);
2100 av_freep(&sc->keyframes);
2101 av_freep(&sc->stts_data);
171a3531 2102 av_freep(&sc->stps_data);
d17d0ec8 2103 av_freep(&sc->rap_group);
f9900374 2104
bd991df2 2105 return 0;
5ca1d879
ZK
2106}
2107
ae628ec1 2108static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
51c15201
BC
2109{
2110 int ret;
2111 c->itunes_metadata = 1;
2112 ret = mov_read_default(c, pb, atom);
2113 c->itunes_metadata = 0;
2114 return ret;
2115}
2116
ae628ec1 2117static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
51c15201 2118{
df8843c6 2119 while (atom.size > 8) {
b7effd4e 2120 uint32_t tag = avio_rl32(pb);
df8843c6
BC
2121 atom.size -= 4;
2122 if (tag == MKTAG('h','d','l','r')) {
6b4aa5da 2123 avio_seek(pb, -8, SEEK_CUR);
df8843c6
BC
2124 atom.size += 8;
2125 return mov_read_default(c, pb, atom);
2126 }
2127 }
2128 return 0;
51c15201
BC
2129}
2130
ae628ec1 2131static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5ca1d879 2132{
ec072669
JS
2133 int i;
2134 int width;
2135 int height;
2136 int64_t disp_transform[2];
2137 int display_matrix[3][2];
6a63ff19
BC
2138 AVStream *st;
2139 MOVStreamContext *sc;
2140 int version;
1f70a5ad 2141 int flags;
6a63ff19
BC
2142
2143 if (c->fc->nb_streams < 1)
2144 return 0;
2145 st = c->fc->streams[c->fc->nb_streams-1];
2146 sc = st->priv_data;
5ca1d879 2147
b7effd4e 2148 version = avio_r8(pb);
1f70a5ad
JS
2149 flags = avio_rb24(pb);
2150 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
5ca1d879 2151
1175561e 2152 if (version == 1) {
b7effd4e
AK
2153 avio_rb64(pb);
2154 avio_rb64(pb);
1175561e 2155 } else {
b7effd4e
AK
2156 avio_rb32(pb); /* creation time */
2157 avio_rb32(pb); /* modification time */
1175561e 2158 }
b7effd4e
AK
2159 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2160 avio_rb32(pb); /* reserved */
fcdd622c 2161
117a9190 2162 /* highlevel (considering edits) duration in movie timebase */
b7effd4e
AK
2163 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2164 avio_rb32(pb); /* reserved */
2165 avio_rb32(pb); /* reserved */
5ca1d879 2166
b7effd4e
AK
2167 avio_rb16(pb); /* layer */
2168 avio_rb16(pb); /* alternate group */
2169 avio_rb16(pb); /* volume */
2170 avio_rb16(pb); /* reserved */
5ca1d879 2171
ec072669
JS
2172 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2173 // they're kept in fixed point format through all calculations
2174 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2175 for (i = 0; i < 3; i++) {
b7effd4e
AK
2176 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2177 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2178 avio_rb32(pb); // 2.30 fixed point (not used)
ec072669 2179 }
5ca1d879 2180
b7effd4e
AK
2181 width = avio_rb32(pb); // 16.16 fixed point track width
2182 height = avio_rb32(pb); // 16.16 fixed point track height
6cdbff63
DC
2183 sc->width = width >> 16;
2184 sc->height = height >> 16;
ec072669 2185
d862fce7 2186 // transform the display width/height according to the matrix
ec072669 2187 // skip this if the display matrix is the default identity matrix
d862fce7 2188 // or if it is rotating the picture, ex iPhone 3GS
ec072669
JS
2189 // to keep the same scale, use [width height 1<<16]
2190 if (width && height &&
d862fce7
BC
2191 ((display_matrix[0][0] != 65536 ||
2192 display_matrix[1][1] != 65536) &&
2193 !display_matrix[0][1] &&
2194 !display_matrix[1][0] &&
2195 !display_matrix[2][0] && !display_matrix[2][1])) {
ec072669
JS
2196 for (i = 0; i < 2; i++)
2197 disp_transform[i] =
2198 (int64_t) width * display_matrix[0][i] +
2199 (int64_t) height * display_matrix[1][i] +
2200 ((int64_t) display_matrix[2][i] << 16);
2201
2202 //sample aspect ratio is new width/height divided by old width/height
59729451 2203 st->sample_aspect_ratio = av_d2q(
ec072669
JS
2204 ((double) disp_transform[0] * height) /
2205 ((double) disp_transform[1] * width), INT_MAX);
2206 }
5ca1d879
ZK
2207 return 0;
2208}
2209
ae628ec1 2210static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
61aedb0f
BC
2211{
2212 MOVFragment *frag = &c->fragment;
2213 MOVTrackExt *trex = NULL;
2214 int flags, track_id, i;
2215
b7effd4e
AK
2216 avio_r8(pb); /* version */
2217 flags = avio_rb24(pb);
61aedb0f 2218
b7effd4e 2219 track_id = avio_rb32(pb);
63581eb1 2220 if (!track_id)
bcd5d979 2221 return AVERROR_INVALIDDATA;
61aedb0f
BC
2222 frag->track_id = track_id;
2223 for (i = 0; i < c->trex_count; i++)
2224 if (c->trex_data[i].track_id == frag->track_id) {
2225 trex = &c->trex_data[i];
2226 break;
2227 }
2228 if (!trex) {
2229 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
bcd5d979 2230 return AVERROR_INVALIDDATA;
61aedb0f
BC
2231 }
2232
73328f24
MS
2233 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2234 avio_rb64(pb) : frag->moof_offset;
2235 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2236
2237 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2238 avio_rb32(pb) : trex->duration;
2239 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2240 avio_rb32(pb) : trex->size;
2241 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2242 avio_rb32(pb) : trex->flags;
dfd2a005 2243 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
61aedb0f
BC
2244 return 0;
2245}
2246
ae628ec1 2247static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
7221579b 2248{
b7effd4e 2249 c->chapter_track = avio_rb32(pb);
7221579b
DC
2250 return 0;
2251}
2252
ae628ec1 2253static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
61aedb0f
BC
2254{
2255 MOVTrackExt *trex;
2256
2257 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
bcd5d979 2258 return AVERROR_INVALIDDATA;
0d8f0abf
BC
2259 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2260 if (!trex)
61aedb0f 2261 return AVERROR(ENOMEM);
0d8f0abf 2262 c->trex_data = trex;
61aedb0f 2263 trex = &c->trex_data[c->trex_count++];
b7effd4e
AK
2264 avio_r8(pb); /* version */
2265 avio_rb24(pb); /* flags */
2266 trex->track_id = avio_rb32(pb);
2267 trex->stsd_id = avio_rb32(pb);
2268 trex->duration = avio_rb32(pb);
2269 trex->size = avio_rb32(pb);
2270 trex->flags = avio_rb32(pb);
61aedb0f
BC
2271 return 0;
2272}
2273
ae628ec1 2274static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
61aedb0f
BC
2275{
2276 MOVFragment *frag = &c->fragment;
63581eb1 2277 AVStream *st = NULL;
44e43aab 2278 MOVStreamContext *sc;
45a811b5 2279 MOVStts *ctts_data;
61aedb0f
BC
2280 uint64_t offset;
2281 int64_t dts;
2282 int data_offset = 0;
2283 unsigned entries, first_sample_flags = frag->flags;
a5c50913 2284 int flags, distance, i, found_keyframe = 0;
61aedb0f 2285
63581eb1
AC
2286 for (i = 0; i < c->fc->nb_streams; i++) {
2287 if (c->fc->streams[i]->id == frag->track_id) {
2288 st = c->fc->streams[i];
2289 break;
2290 }
2291 }
2292 if (!st) {
2293 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
bcd5d979 2294 return AVERROR_INVALIDDATA;
63581eb1 2295 }
44e43aab 2296 sc = st->priv_data;
61aedb0f
BC
2297 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2298 return 0;
b7effd4e
AK
2299 avio_r8(pb); /* version */
2300 flags = avio_rb24(pb);
2301 entries = avio_rb32(pb);
dfd2a005 2302 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
45a811b5
YN
2303
2304 /* Always assume the presence of composition time offsets.
2305 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2306 * 1) in the initial movie, there are no samples.
2307 * 2) in the first movie fragment, there is only one sample without composition time offset.
2308 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2309 if (!sc->ctts_count && sc->sample_count)
2310 {
2311 /* Complement ctts table if moov atom doesn't have ctts atom. */
2312 ctts_data = av_malloc(sizeof(*sc->ctts_data));
0d8f0abf 2313 if (!ctts_data)
61aedb0f 2314 return AVERROR(ENOMEM);
0d8f0abf 2315 sc->ctts_data = ctts_data;
45a811b5
YN
2316 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2317 sc->ctts_data[sc->ctts_count].duration = 0;
2318 sc->ctts_count++;
61aedb0f 2319 }
45a811b5 2320 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
bcd5d979 2321 return AVERROR_INVALIDDATA;
45a811b5
YN
2322 ctts_data = av_realloc(sc->ctts_data,
2323 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2324 if (!ctts_data)
2325 return AVERROR(ENOMEM);
2326 sc->ctts_data = ctts_data;
2327
3eec23f3
MS
2328 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2329 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
7f19bdc2 2330 dts = sc->track_end - sc->time_offset;
61aedb0f
BC
2331 offset = frag->base_data_offset + data_offset;
2332 distance = 0;
dfd2a005 2333 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
9888ffb1 2334 for (i = 0; i < entries && !pb->eof_reached; i++) {
61aedb0f
BC
2335 unsigned sample_size = frag->size;
2336 int sample_flags = i ? frag->flags : first_sample_flags;
2337 unsigned sample_duration = frag->duration;
a5c50913 2338 int keyframe = 0;
61aedb0f 2339
3eec23f3
MS
2340 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2341 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2342 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
45a811b5 2343 sc->ctts_data[sc->ctts_count].count = 1;
3eec23f3
MS
2344 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2345 avio_rb32(pb) : 0;
45a811b5 2346 sc->ctts_count++;
a5c50913
MS
2347 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2348 keyframe = 1;
2349 else if (!found_keyframe)
2350 keyframe = found_keyframe =
2351 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2352 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2353 if (keyframe)
61aedb0f
BC
2354 distance = 0;
2355 av_add_index_entry(st, offset, dts, sample_size, distance,
2356 keyframe ? AVINDEX_KEYFRAME : 0);
dfd2a005 2357 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
61aedb0f
BC
2358 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2359 offset, dts, sample_size, distance, keyframe);
2360 distance++;
bbe46bc4 2361 dts += sample_duration;
61aedb0f 2362 offset += sample_size;
bc7d0517 2363 sc->data_size += sample_size;
61aedb0f 2364 }
9888ffb1
LB
2365
2366 if (pb->eof_reached)
2367 return AVERROR_EOF;
2368
61aedb0f 2369 frag->moof_offset = offset;
7f19bdc2 2370 st->duration = sc->track_end = dts + sc->time_offset;
61aedb0f
BC
2371 return 0;
2372}
2373
5ca1d879
ZK
2374/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2375/* like the files created with Adobe Premiere 5.0, for samples see */
2376/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
ae628ec1 2377static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5ca1d879
ZK
2378{
2379 int err;
5ca1d879 2380
5ca1d879
ZK
2381 if (atom.size < 8)
2382 return 0; /* continue */
b7effd4e 2383 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
45a8a02a 2384 avio_skip(pb, atom.size - 4);
5ca1d879
ZK
2385 return 0;
2386 }
b7effd4e 2387 atom.type = avio_rl32(pb);
5ca1d879 2388 atom.size -= 8;
1c126b4f 2389 if (atom.type != MKTAG('m','d','a','t')) {
45a8a02a 2390 avio_skip(pb, atom.size);
5ca1d879
ZK
2391 return 0;
2392 }
2393 err = mov_read_mdat(c, pb, atom);
5ca1d879
ZK
2394 return err;
2395}
2396
ae628ec1 2397static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
0147f198 2398{
b250f9c6 2399#if CONFIG_ZLIB
ae628ec1 2400 AVIOContext ctx;
b6a17df4
ZK
2401 uint8_t *cmov_data;
2402 uint8_t *moov_data; /* uncompressed data */
0147f198 2403 long cmov_len, moov_len;
6f04eb1e 2404 int ret = -1;
b6a17df4 2405
b7effd4e
AK
2406 avio_rb32(pb); /* dcom atom */
2407 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
bcd5d979 2408 return AVERROR_INVALIDDATA;
b7effd4e 2409 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
f3592353 2410 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
bcd5d979 2411 return AVERROR_INVALIDDATA;
0147f198 2412 }
b7effd4e
AK
2413 avio_rb32(pb); /* cmvd atom */
2414 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
bcd5d979 2415 return AVERROR_INVALIDDATA;
b7effd4e 2416 moov_len = avio_rb32(pb); /* uncompressed size */
5ca1d879 2417 cmov_len = atom.size - 6 * 4;
5cd62665 2418
9a630c25 2419 cmov_data = av_malloc(cmov_len);
0147f198 2420 if (!cmov_data)
0d8f0abf 2421 return AVERROR(ENOMEM);
9a630c25 2422 moov_data = av_malloc(moov_len);
0147f198
FR
2423 if (!moov_data) {
2424 av_free(cmov_data);
0d8f0abf 2425 return AVERROR(ENOMEM);
0147f198 2426 }
b7effd4e 2427 avio_read(pb, cmov_data, cmov_len);
5a7ba586 2428 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
6f04eb1e 2429 goto free_and_return;
5a7ba586 2430 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
6f04eb1e 2431 goto free_and_return;
1c126b4f 2432 atom.type = MKTAG('m','o','o','v');
5ca1d879
ZK
2433 atom.size = moov_len;
2434 ret = mov_read_default(c, &ctx, atom);
6f04eb1e 2435free_and_return:
0147f198
FR
2436 av_free(moov_data);
2437 av_free(cmov_data);
2438 return ret;
d966b2f0
BC
2439#else
2440 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
bcd5d979 2441 return AVERROR(ENOSYS);
0147f198 2442#endif
d966b2f0 2443}
0147f198 2444
baf25c9d 2445/* edit list atom */
ae628ec1 2446static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
baf25c9d 2447{
1c4bf2ec 2448 MOVStreamContext *sc;
5f0bb0ba 2449 int i, edit_count, version;
e0977c80 2450
1c4bf2ec
BC
2451 if (c->fc->nb_streams < 1)
2452 return 0;
2453 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2454
5f0bb0ba 2455 version = avio_r8(pb); /* version */
b7effd4e
AK
2456 avio_rb24(pb); /* flags */
2457 edit_count = avio_rb32(pb); /* entries */
e0977c80 2458
5a7ba586 2459 if ((uint64_t)edit_count*12+8 > atom.size)
bcd5d979 2460 return AVERROR_INVALIDDATA;
53e099de 2461
5a7ba586 2462 for (i=0; i<edit_count; i++){
5f0bb0ba
YN
2463 int64_t time;
2464 int64_t duration;
2465 if (version == 1) {
2466 duration = avio_rb64(pb);
2467 time = avio_rb64(pb);
2468 } else {
2469 duration = avio_rb32(pb); /* segment duration */
ae88e9cf 2470 time = (int32_t)avio_rb32(pb); /* media time */
5f0bb0ba 2471 }
b7effd4e 2472 avio_rb32(pb); /* Media rate */
2ac736a6
RD
2473 if (i == 0 && time >= -1) {
2474 sc->time_offset = time != -1 ? time : -duration;
a5929abe 2475 }
e0977c80 2476 }
baf2ffd3 2477
5a7ba586 2478 if (edit_count > 1)
baf2ffd3
BC
2479 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2480 "a/v desync might occur, patch welcome\n");
2481
dfd2a005 2482 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
e0977c80 2483 return 0;
baf25c9d
GC
2484}
2485
6cea494e 2486static const MOVParseTableEntry mov_default_parse_table[] = {
d4fdba0d 2487{ MKTAG('a','v','s','s'), mov_read_extradata },
1cf9f6ed 2488{ MKTAG('c','h','p','l'), mov_read_chpl },
1c126b4f
BC
2489{ MKTAG('c','o','6','4'), mov_read_stco },
2490{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2491{ MKTAG('d','i','n','f'), mov_read_default },
2492{ MKTAG('d','r','e','f'), mov_read_dref },
2493{ MKTAG('e','d','t','s'), mov_read_default },
2494{ MKTAG('e','l','s','t'), mov_read_elst },
2495{ MKTAG('e','n','d','a'), mov_read_enda },
4bf3c8f2 2496{ MKTAG('f','i','e','l'), mov_read_fiel },
1c126b4f
BC
2497{ MKTAG('f','t','y','p'), mov_read_ftyp },
2498{ MKTAG('g','l','b','l'), mov_read_glbl },
2499{ MKTAG('h','d','l','r'), mov_read_hdlr },
51c15201 2500{ MKTAG('i','l','s','t'), mov_read_ilst },
1c126b4f
BC
2501{ MKTAG('j','p','2','h'), mov_read_extradata },
2502{ MKTAG('m','d','a','t'), mov_read_mdat },
2503{ MKTAG('m','d','h','d'), mov_read_mdhd },
2504{ MKTAG('m','d','i','a'), mov_read_default },
51c15201 2505{ MKTAG('m','e','t','a'), mov_read_meta },
1c126b4f
BC
2506{ MKTAG('m','i','n','f'), mov_read_default },
2507{ MKTAG('m','o','o','f'), mov_read_moof },
2508{ MKTAG('m','o','o','v'), mov_read_moov },
2509{ MKTAG('m','v','e','x'), mov_read_default },
2510{ MKTAG('m','v','h','d'), mov_read_mvhd },
2511{ MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2512{ MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2513{ MKTAG('a','v','c','C'), mov_read_glbl },
6da54074 2514{ MKTAG('p','a','s','p'), mov_read_pasp },
1c126b4f
BC
2515{ MKTAG('s','t','b','l'), mov_read_default },
2516{ MKTAG('s','t','c','o'), mov_read_stco },
171a3531 2517{ MKTAG('s','t','p','s'), mov_read_stps },
653d7aeb 2518{ MKTAG('s','t','r','f'), mov_read_strf },
1c126b4f
BC
2519{ MKTAG('s','t','s','c'), mov_read_stsc },
2520{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2521{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2522{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2523{ MKTAG('s','t','t','s'), mov_read_stts },
bd27eed6 2524{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
1c126b4f
BC
2525{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2526{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2527{ MKTAG('t','r','a','k'), mov_read_trak },
2528{ MKTAG('t','r','a','f'), mov_read_default },
7221579b
DC
2529{ MKTAG('t','r','e','f'), mov_read_default },
2530{ MKTAG('c','h','a','p'), mov_read_chap },
1c126b4f
BC
2531{ MKTAG('t','r','e','x'), mov_read_trex },
2532{ MKTAG('t','r','u','n'), mov_read_trun },
86b0affd 2533{ MKTAG('u','d','t','a'), mov_read_default },
1c126b4f
BC
2534{ MKTAG('w','a','v','e'), mov_read_wave },
2535{ MKTAG('e','s','d','s'), mov_read_esds },
bdecdd2b 2536{ MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
546adc1f 2537{ MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
1c126b4f 2538{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
85e9e3a9 2539{ MKTAG('w','f','e','x'), mov_read_wfex },
1c126b4f 2540{ MKTAG('c','m','o','v'), mov_read_cmov },
1fdf18f4 2541{ MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
89415b8e 2542{ MKTAG('d','v','c','1'), mov_read_dvc1 },
d17d0ec8 2543{ MKTAG('s','b','g','p'), mov_read_sbgp },
bcfe2ba0 2544{ 0, NULL }
6cea494e
ZK
2545};
2546
1ce1e636
RB
2547static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2548{
2549 int64_t total_size = 0;
2550 MOVAtom a;
2551 int i;
2552
2553 if (atom.size < 0)
2554 atom.size = INT64_MAX;
2555 while (total_size + 8 < atom.size && !pb->eof_reached) {
2556 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
2557 a.size = atom.size;
2558 a.type=0;
2559 if (atom.size >= 8) {
2560 a.size = avio_rb32(pb);
2561 a.type = avio_rl32(pb);
2562 }
2563 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
2564 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
2565 total_size += 8;
2566 if (a.size == 1) { /* 64 bit extended size */
2567 a.size = avio_rb64(pb) - 8;
2568 total_size += 8;
2569 }
2570 if (a.size == 0) {
2571 a.size = atom.size - total_size;
2572 if (a.size <= 8)
2573 break;
2574 }
2575 a.size -= 8;
2576 if (a.size < 0)
2577 break;
2578 a.size = FFMIN(a.size, atom.size - total_size);
2579
2580 for (i = 0; mov_default_parse_table[i].type; i++)
2581 if (mov_default_parse_table[i].type == a.type) {
2582 parse = mov_default_parse_table[i].parse;
2583 break;
2584 }
2585
2586 // container is user data
2587 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
2588 atom.type == MKTAG('i','l','s','t')))
2589 parse = mov_read_udta_string;
2590
2591 if (!parse) { /* skip leaf atoms data */
2592 avio_skip(pb, a.size);
2593 } else {
2594 int64_t start_pos = avio_tell(pb);
2595 int64_t left;
2596 int err = parse(c, pb, a);
2597 if (err < 0)
2598 return err;
2599 if (c->found_moov && c->found_mdat &&
2600 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
2601 start_pos + a.size == avio_size(pb))) {
2602 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
2603 c->next_root_atom = start_pos + a.size;
2604 return 0;
2605 }
2606 left = a.size - avio_tell(pb) + start_pos;
2607 if (left > 0) /* skip garbage at atom end */
2608 avio_skip(pb, left);
5b4eb243
MS
2609 else if (left < 0) {
2610 av_log(c->fc, AV_LOG_WARNING,
2611 "overread end of atom '%.4s' by %"PRId64" bytes\n",
2612 (char*)&a.type, -left);
2613 avio_seek(pb, left, SEEK_CUR);
2614 }
1ce1e636
RB
2615 }
2616
2617 total_size += a.size;
2618 }
2619
2620 if (total_size < atom.size && atom.size < 0x7ffff)
2621 avio_skip(pb, atom.size - total_size);
2622
2623 return 0;
2624}
2625
c9a65ca8
FB
2626static int mov_probe(AVProbeData *p)
2627{
0e7eed09
FB
2628 unsigned int offset;
2629 uint32_t tag;
2497479f 2630 int score = 0;
3ffe3793 2631
c9a65ca8 2632 /* check file header */
0e7eed09 2633 offset = 0;
5a7ba586 2634 for (;;) {
0e7eed09
FB
2635 /* ignore invalid offset */
2636 if ((offset + 8) > (unsigned int)p->buf_size)
2497479f 2637 return score;
fead30d4 2638 tag = AV_RL32(p->buf + offset + 4);
0e7eed09 2639 switch(tag) {
2497479f 2640 /* check for obvious tags */
1c126b4f
BC
2641 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2642 case MKTAG('m','o','o','v'):
2643 case MKTAG('m','d','a','t'):
2644 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2645 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
40e7aaa3 2646 case MKTAG('f','t','y','p'):
3ffe3793 2647 return AVPROBE_SCORE_MAX;
2497479f 2648 /* those are more common words, so rate then a bit less */
1c126b4f
BC
2649 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2650 case MKTAG('w','i','d','e'):
2651 case MKTAG('f','r','e','e'):
2652 case MKTAG('j','u','n','k'):
2653 case MKTAG('p','i','c','t'):
2497479f 2654 return AVPROBE_SCORE_MAX - 5;
5469b788 2655 case MKTAG(0x82,0x82,0x7f,0x7d):
1c126b4f
BC
2656 case MKTAG('s','k','i','p'):
2657 case MKTAG('u','u','i','d'):
2658 case MKTAG('p','r','f','l'):
fead30d4 2659 offset = AV_RB32(p->buf+offset) + offset;
2497479f 2660 /* if we only find those cause probedata is too small at least rate them */
e0f8be64 2661 score = AVPROBE_SCORE_EXTENSION;
0e7eed09
FB
2662 break;
2663 default:
2664 /* unrecognized tag */
2497479f 2665 return score;
0e7eed09 2666 }
3ffe3793 2667 }
c9a65ca8
FB
2668}
2669
7221579b
DC
2670// must be done after parsing all trak because there's no order requirement
2671static void mov_read_chapters(AVFormatContext *s)
2672{
2673 MOVContext *mov = s->priv_data;
2674 AVStream *st = NULL;
2675 MOVStreamContext *sc;
2676 int64_t cur_pos;
225b6d7f 2677 int i;
7221579b
DC
2678
2679 for (i = 0; i < s->nb_streams; i++)
2680 if (s->streams[i]->id == mov->chapter_track) {
2681 st = s->streams[i];
2682 break;
2683 }
2684 if (!st) {
2685 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2686 return;
2687 }
2688
2689 st->discard = AVDISCARD_ALL;
2690 sc = st->priv_data;
a2704c97 2691 cur_pos = avio_tell(sc->pb);
7221579b
DC
2692
2693 for (i = 0; i < st->nb_index_entries; i++) {
2694 AVIndexEntry *sample = &st->index_entries[i];
2695 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
225b6d7f
AK
2696 uint8_t *title;
2697 uint16_t ch;
2698 int len, title_len;
7221579b 2699
6b4aa5da 2700 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
7221579b
DC
2701 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2702 goto finish;
2703 }
2704
7221579b 2705 // the first two bytes are the length of the title
b7effd4e 2706 len = avio_rb16(sc->pb);
7221579b
DC
2707 if (len > sample->size-2)
2708 continue;
225b6d7f
AK
2709 title_len = 2*len + 1;
2710 if (!(title = av_mallocz(title_len)))
2711 goto finish;
7221579b
DC
2712
2713 // The samples could theoretically be in any encoding if there's an encd
2714 // atom following, but in practice are only utf-8 or utf-16, distinguished
2715 // instead by the presence of a BOM
8fb22c3d
AC
2716 if (!len) {
2717 title[0] = 0;
2718 } else {
2719 ch = avio_rb16(sc->pb);
2720 if (ch == 0xfeff)
2721 avio_get_str16be(sc->pb, len, title, title_len);
2722 else if (ch == 0xfffe)
2723 avio_get_str16le(sc->pb, len, title, title_len);
2724 else {
2725 AV_WB16(title, ch);
2726 if (len == 1 || len == 2)
7ad06beb 2727 title[len] = 0;
8fb22c3d
AC
2728 else
2729 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
2730 }
7221579b
DC
2731 }
2732
1fa395e4 2733 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
c4f8765a 2734 av_freep(&title);
7221579b
DC
2735 }
2736finish:
6b4aa5da 2737 avio_seek(sc->pb, cur_pos, SEEK_SET);
7221579b
DC
2738}
2739
c788782c
DC
2740static int mov_read_close(AVFormatContext *s)
2741{
2742 MOVContext *mov = s->priv_data;
2743 int i, j;
2744
2745 for (i = 0; i < s->nb_streams; i++) {
2746 AVStream *st = s->streams[i];
2747 MOVStreamContext *sc = st->priv_data;
2748
2749 av_freep(&sc->ctts_data);
2750 for (j = 0; j < sc->drefs_count; j++) {
2751 av_freep(&sc->drefs[j].path);
2752 av_freep(&sc->drefs[j].dir);
2753 }
2754 av_freep(&sc->drefs);
2755 if (sc->pb && sc->pb != s->pb)
2756 avio_close(sc->pb);
2757 }
2758
2759 if (mov->dv_demux) {
2760 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2761 av_freep(&mov->dv_fctx->streams[i]->codec);
2762 av_freep(&mov->dv_fctx->streams[i]);
2763 }
2764 av_freep(&mov->dv_fctx);
2765 av_freep(&mov->dv_demux);
2766 }
2767
2768 av_freep(&mov->trex_data);
2769
2770 return 0;
2771}
2772
6e9651d1 2773static int mov_read_header(AVFormatContext *s)
6cea494e 2774{
e4141433 2775 MOVContext *mov = s->priv_data;
ae628ec1 2776 AVIOContext *pb = s->pb;
f9900374 2777 int err;
3491866a 2778 MOVAtom atom = { AV_RL32("root") };
6cea494e 2779
6cea494e 2780 mov->fc = s;
117a9190 2781 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
5a7ba586 2782 if (pb->seekable)
76aa876e 2783 atom.size = avio_size(pb);
6cea494e 2784 else
fa22ca22 2785 atom.size = INT64_MAX;
6cea494e 2786
6cea494e 2787 /* check MOV header */
612b5cbb
BC
2788 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2789 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
c788782c 2790 mov_read_close(s);
612b5cbb
BC
2791 return err;
2792 }
2793 if (!mov->found_moov) {
2794 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
c788782c 2795 mov_read_close(s);
bcd5d979 2796 return AVERROR_INVALIDDATA;
6cea494e 2797 }
3583d7cf 2798 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
4e5ef14f 2799
8978feda 2800 if (pb->seekable && mov->chapter_track > 0)
7221579b
DC
2801 mov_read_chapters(s);
2802
bc7d0517
MS
2803 if (mov->trex_data) {
2804 int i;
2805 for (i = 0; i < s->nb_streams; i++) {
2806 AVStream *st = s->streams[i];
2807 MOVStreamContext *sc = st->priv_data;
2808 if (st->duration)
2809 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
2810 }
2811 }
2812
6cea494e
ZK
2813 return 0;
2814}
2815
5dc5c43b 2816static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
6cea494e 2817{
5dc5c43b 2818 AVIndexEntry *sample = NULL;
86d8602f 2819 int64_t best_dts = INT64_MAX;
5dc5c43b 2820 int i;
11f16b66 2821 for (i = 0; i < s->nb_streams; i++) {
69fc436c
RD
2822 AVStream *avst = s->streams[i];
2823 MOVStreamContext *msc = avst->priv_data;
3fe4d5d4 2824 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
69fc436c 2825 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
bbe46bc4 2826 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
dfd2a005 2827 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
8978feda
AK
2828 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2829 (s->pb->seekable &&
221e21b7 2830 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
687f35f3 2831 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
221e21b7 2832 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
b72708f8
BC
2833 sample = current_sample;
2834 best_dts = dts;
5dc5c43b 2835 *st = avst;
86d8602f 2836 }
6cea494e 2837 }
6cea494e 2838 }
5dc5c43b
RD
2839 return sample;
2840}
2841
2842static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2843{
2844 MOVContext *mov = s->priv_data;
2845 MOVStreamContext *sc;
2846 AVIndexEntry *sample;
2847 AVStream *st = NULL;
2848 int ret;
2849 retry:
2850 sample = mov_find_next_sample(s, &st);
433aeb62
BC
2851 if (!sample) {
2852 mov->found_mdat = 0;
383a3b64
MS
2853 if (!mov->next_root_atom)
2854 return AVERROR_EOF;
2855 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
2856 mov->next_root_atom = 0;
2857 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
66e5b1df 2858 s->pb->eof_reached)
350f2c2c 2859 return AVERROR_EOF;
3583d7cf 2860 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
433aeb62
BC
2861 goto retry;
2862 }
69fc436c 2863 sc = st->priv_data;
b72708f8
BC
2864 /* must be done just before reading, to avoid infinite loop on sample */
2865 sc->current_sample++;
3fe4d5d4
RD
2866
2867 if (st->discard != AVDISCARD_ALL) {
6b4aa5da 2868 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
e1c1b0ff
RD
2869 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2870 sc->ffindex, sample->pos);
bcd5d979 2871 return AVERROR_INVALIDDATA;
e1c1b0ff
RD
2872 }
2873 ret = av_get_packet(sc->pb, pkt, sample->size);
a2f38511
RD
2874 if (ret < 0)
2875 return ret;
2d8591c2
KS
2876 if (sc->has_palette) {
2877 uint8_t *pal;
2878
2879 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2880 if (!pal) {
2881 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2882 } else {
2883 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2884 sc->has_palette = 0;
2885 }
2886 }
e1c1b0ff
RD
2887#if CONFIG_DV_DEMUXER
2888 if (mov->dv_demux && sc->dv_audio_container) {
ab88b25f 2889 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
e1c1b0ff
RD
2890 av_free(pkt->data);
2891 pkt->size = 0;
ab88b25f 2892 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
e1c1b0ff
RD
2893 if (ret < 0)
2894 return ret;
2895 }
312954f0 2896#endif
3fe4d5d4
RD
2897 }
2898
b72708f8
BC
2899 pkt->stream_index = sc->ffindex;
2900 pkt->dts = sample->timestamp;
86f2ae06 2901 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
bbe46bc4 2902 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
b72708f8 2903 /* update ctts context */
a234e38d
BC
2904 sc->ctts_sample++;
2905 if (sc->ctts_index < sc->ctts_count &&
2906 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2907 sc->ctts_index++;
2908 sc->ctts_sample = 0;
b565ea09 2909 }
0c5f76f7
BC
2910 if (sc->wrong_dts)
2911 pkt->dts = AV_NOPTS_VALUE;
b72708f8 2912 } else {
f0f2218d 2913 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
e8430214
HG
2914 st->index_entries[sc->current_sample].timestamp : st->duration;
2915 pkt->duration = next_dts - pkt->dts;
b72708f8 2916 pkt->pts = pkt->dts;
b565ea09 2917 }
3fe4d5d4
RD
2918 if (st->discard == AVDISCARD_ALL)
2919 goto retry;
cc947f04 2920 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
b72708f8 2921 pkt->pos = sample->pos;
dfd2a005 2922 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
29c90869 2923 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
b72708f8
BC
2924 return 0;
2925}
3ffe3793 2926
e26df9eb 2927static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
b72708f8
BC
2928{
2929 MOVStreamContext *sc = st->priv_data;
2930 int sample, time_sample;
2931 int i;
115329f1 2932
b72708f8 2933 sample = av_index_search_timestamp(st, timestamp, flags);
dfd2a005 2934 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
380966a8
JS
2935 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2936 sample = 0;
b72708f8 2937 if (sample < 0) /* not sure what to do */
bcd5d979 2938 return AVERROR_INVALIDDATA;
b72708f8 2939 sc->current_sample = sample;
dfd2a005 2940 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
b72708f8
BC
2941 /* adjust ctts index */
2942 if (sc->ctts_data) {
2943 time_sample = 0;
2944 for (i = 0; i < sc->ctts_count; i++) {
54a5c719
BC
2945 int next = time_sample + sc->ctts_data[i].count;
2946 if (next > sc->current_sample) {
a234e38d
BC
2947 sc->ctts_index = i;
2948 sc->ctts_sample = sc->current_sample - time_sample;
b72708f8 2949 break;
115329f1 2950 }
54a5c719 2951 time_sample = next;
247d56f5 2952 }
247d56f5 2953 }
b72708f8 2954 return sample;
6cea494e
ZK
2955}
2956
961e0ccd 2957static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
baf25c9d 2958{
b72708f8
BC
2959 AVStream *st;
2960 int64_t seek_timestamp, timestamp;
2961 int sample;
2962 int i;
baf25c9d 2963
b72708f8 2964 if (stream_index >= s->nb_streams)
bcd5d979 2965 return AVERROR_INVALIDDATA;
8dc81a45
BC
2966 if (sample_time < 0)
2967 sample_time = 0;
baf25c9d 2968
b72708f8 2969 st = s->streams[stream_index];
e26df9eb 2970 sample = mov_seek_stream(s, st, sample_time, flags);
b72708f8 2971 if (sample < 0)
bcd5d979 2972 return sample;
baf25c9d 2973
b72708f8
BC
2974 /* adjust seek timestamp to found sample timestamp */
2975 seek_timestamp = st->index_entries[sample].timestamp;
baf25c9d 2976
b72708f8
BC
2977 for (i = 0; i < s->nb_streams; i++) {
2978 st = s->streams[i];
3fe4d5d4 2979 if (stream_index == i)
b72708f8 2980 continue;
baf25c9d 2981
b72708f8 2982 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
e26df9eb 2983 mov_seek_stream(s, st, timestamp, flags);
115329f1 2984 }
baf25c9d
GC
2985 return 0;
2986}
baf25c9d 2987
c6610a21 2988AVInputFormat ff_mov_demuxer = {
dfc2c4d9 2989 .name = "mov,mp4,m4a,3gp,3g2,mj2",
0177b7d2 2990 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
dfc2c4d9
AK
2991 .priv_data_size = sizeof(MOVContext),
2992 .read_probe = mov_probe,
2993 .read_header = mov_read_header,
2994 .read_packet = mov_read_packet,
2995 .read_close = mov_read_close,
2996 .read_seek = mov_read_seek,
6cea494e 2997};