mov: Refactor codec id selection in mov_codec_id
[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
ae628ec1 1103int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
5ca1d879 1104{
6a63ff19
BC
1105 AVStream *st;
1106 MOVStreamContext *sc;
dc2cabd0 1107 int j, pseudo_stream_id;
b595afaa 1108
6a63ff19
BC
1109 if (c->fc->nb_streams < 1)
1110 return 0;
1111 st = c->fc->streams[c->fc->nb_streams-1];
1112 sc = st->priv_data;
1113
9888ffb1
LB
1114 for (pseudo_stream_id = 0;
1115 pseudo_stream_id < entries && !pb->eof_reached;
1116 pseudo_stream_id++) {
117a9190 1117 //Parsing Sample description table
36ef5369 1118 enum AVCodecID id;
28155113 1119 int dref_id = 1;
3491866a 1120 MOVAtom a = { AV_RL32("stsd") };
a2704c97 1121 int64_t start_pos = avio_tell(pb);
a5ea623b 1122 uint32_t size = avio_rb32(pb); /* size */
b7effd4e 1123 uint32_t format = avio_rl32(pb); /* data format */
5cd62665 1124
28155113 1125 if (size >= 16) {
b7effd4e
AK
1126 avio_rb32(pb); /* reserved */
1127 avio_rb16(pb); /* reserved */
1128 dref_id = avio_rb16(pb);
a5ea623b
MN
1129 } else {
1130 av_log(c->fc, AV_LOG_ERROR, "invalid size %d in stsd\n", size);
1131 return AVERROR_INVALIDDATA;
28155113 1132 }
0e7eed09 1133
744a9c75 1134 if (st->codec->codec_tag &&
978677a7 1135 st->codec->codec_tag != format &&
167f3b8d 1136 (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
1c126b4f 1137 : st->codec->codec_tag != MKTAG('j','p','e','g'))
744a9c75 1138 ){
7ce68923
DB
1139 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1140 * export it as a separate AVStream but this needs a few changes
1141 * in the MOV demuxer, patch welcome. */
adc73054 1142 multiple_stsd:
285a3da9 1143 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
45a8a02a 1144 avio_skip(pb, size - (avio_tell(pb) - start_pos));
e7cc4b52
BC
1145 continue;
1146 }
adc73054
BC
1147 /* we cannot demux concatenated h264 streams because of different extradata */
1148 if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1149 goto multiple_stsd;
978677a7 1150 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
221e21b7 1151 sc->dref_id= dref_id;
e7cc4b52 1152
bf985625 1153 id = mov_codec_id(st, format);
99487f42 1154
dfd2a005 1155 av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
29c90869
BC
1156 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1157 (format >> 24) & 0xff, st->codec->codec_type);
a20da52c 1158
5a7ba586 1159 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
08a186c6 1160 unsigned int color_depth, len;
baf9fb32 1161 int color_greyscale;
4f07f819 1162 int color_table_id;
baf9fb32 1163
01f4895c 1164 st->codec->codec_id = id;
b7effd4e
AK
1165 avio_rb16(pb); /* version */
1166 avio_rb16(pb); /* revision level */
1167 avio_rb32(pb); /* vendor */
1168 avio_rb32(pb); /* temporal quality */
1169 avio_rb32(pb); /* spatial quality */
3cb4ee51 1170
b7effd4e
AK
1171 st->codec->width = avio_rb16(pb); /* width */
1172 st->codec->height = avio_rb16(pb); /* height */
3cb4ee51 1173
b7effd4e
AK
1174 avio_rb32(pb); /* horiz resolution */
1175 avio_rb32(pb); /* vert resolution */
1176 avio_rb32(pb); /* data size, always 0 */
1177 avio_rb16(pb); /* frames per samples */
f8c18cd7 1178
b7effd4e 1179 len = avio_r8(pb); /* codec name, pascal string */
08a186c6
BC
1180 if (len > 31)
1181 len = 31;
1182 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1183 if (len < 31)
45a8a02a 1184 avio_skip(pb, 31 - len);
08a186c6
BC
1185 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1186 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1187 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
bb2bab92
JG
1188 /* Flash Media Server uses tag H263 with Sorenson Spark */
1189 if (format == MKTAG('H','2','6','3') &&
1190 !memcmp(st->codec->codec_name, "Sorenson H263", 13))
1191 st->codec->codec_id = AV_CODEC_ID_FLV1;
5cd62665 1192
b7effd4e 1193 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
4f07f819 1194 color_table_id = avio_rb16(pb); /* colortable id */
dfd2a005 1195 av_dlog(c->fc, "depth %d, ctab id %d\n",
4f07f819 1196 st->codec->bits_per_coded_sample, color_table_id);
b595afaa 1197 /* figure out the palette situation */
dd1c8f3e
LA
1198 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1199 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
b595afaa
MM
1200
1201 /* if the depth is 2, 4, or 8 bpp, file is palettized */
115329f1 1202 if ((color_depth == 2) || (color_depth == 4) ||
b595afaa 1203 (color_depth == 8)) {
47e1d7ef
BC
1204 /* for palette traversal */
1205 unsigned int color_start, color_count, color_end;
1206 unsigned char r, g, b;
1207
b595afaa 1208 if (color_greyscale) {
47e1d7ef 1209 int color_index, color_dec;
b595afaa 1210 /* compute the greyscale palette */
dd1c8f3e 1211 st->codec->bits_per_coded_sample = color_depth;
b595afaa
MM
1212 color_count = 1 << color_depth;
1213 color_index = 255;
1214 color_dec = 256 / (color_count - 1);
1215 for (j = 0; j < color_count; j++) {
1216 r = g = b = color_index;
2d8591c2 1217 sc->palette[j] =
b595afaa
MM
1218 (r << 16) | (g << 8) | (b);
1219 color_index -= color_dec;
1220 if (color_index < 0)
1221 color_index = 0;
1222 }
4f07f819 1223 } else if (color_table_id) {
47e1d7ef 1224 const uint8_t *color_table;
b595afaa
MM
1225 /* if flag bit 3 is set, use the default palette */
1226 color_count = 1 << color_depth;
1227 if (color_depth == 2)
a90466f7 1228 color_table = ff_qt_default_palette_4;
b595afaa 1229 else if (color_depth == 4)
a90466f7 1230 color_table = ff_qt_default_palette_16;
b595afaa 1231 else
a90466f7 1232 color_table = ff_qt_default_palette_256;
b595afaa
MM
1233
1234 for (j = 0; j < color_count; j++) {
2121b160
RB
1235 r = color_table[j * 3 + 0];
1236 g = color_table[j * 3 + 1];
1237 b = color_table[j * 3 + 2];
2d8591c2 1238 sc->palette[j] =
b595afaa
MM
1239 (r << 16) | (g << 8) | (b);
1240 }
b595afaa 1241 } else {
b595afaa 1242 /* load the palette from the file */
b7effd4e
AK
1243 color_start = avio_rb32(pb);
1244 color_count = avio_rb16(pb);
1245 color_end = avio_rb16(pb);
8b35bd80
MM
1246 if ((color_start <= 255) &&
1247 (color_end <= 255)) {
9de2919c
MM
1248 for (j = color_start; j <= color_end; j++) {
1249 /* each R, G, or B component is 16 bits;
1250 * only use the top 8 bits; skip alpha bytes
1251 * up front */
b7effd4e
AK
1252 avio_r8(pb);
1253 avio_r8(pb);
1254 r = avio_r8(pb);
1255 avio_r8(pb);
1256 g = avio_r8(pb);
1257 avio_r8(pb);
1258 b = avio_r8(pb);
1259 avio_r8(pb);
2d8591c2 1260 sc->palette[j] =
9de2919c 1261 (r << 16) | (g << 8) | (b);
8b35bd80 1262 }
b595afaa
MM
1263 }
1264 }
2d8591c2 1265 sc->has_palette = 1;
e49da827 1266 }
5a7ba586 1267 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
aaef2bb3 1268 int bits_per_sample, flags;
b7effd4e 1269 uint16_t version = avio_rb16(pb);
b595afaa 1270
99487f42 1271 st->codec->codec_id = id;
b7effd4e
AK
1272 avio_rb16(pb); /* revision level */
1273 avio_rb32(pb); /* vendor */
6d6d7970 1274
b7effd4e 1275 st->codec->channels = avio_rb16(pb); /* channel count */
dfd2a005 1276 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
b7effd4e 1277 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
de23f234 1278
b7effd4e
AK
1279 sc->audio_cid = avio_rb16(pb);
1280 avio_rb16(pb); /* packet size = 0 */
de23f234 1281
b7effd4e 1282 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
de23f234 1283
5ef3ad59 1284 //Read QT version 1 fields. In version 0 these do not exist.
dfd2a005 1285 av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
5a7ba586
LB
1286 if (!c->isom) {
1287 if (version==1) {
b7effd4e
AK
1288 sc->samples_per_frame = avio_rb32(pb);
1289 avio_rb32(pb); /* bytes per packet */
1290 sc->bytes_per_frame = avio_rb32(pb);
1291 avio_rb32(pb); /* bytes per sample */
5a7ba586 1292 } else if (version==2) {
b7effd4e 1293 avio_rb32(pb); /* sizeof struct only */
3383a53e 1294 st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
b7effd4e
AK
1295 st->codec->channels = avio_rb32(pb);
1296 avio_rb32(pb); /* always 0x7F000000 */
1297 st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1298 flags = avio_rb32(pb); /* lpcm format specific flag */
1299 sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1300 sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
2288834f 1301 if (format == MKTAG('l','p','c','m'))
2d423666 1302 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
5ef3ad59
BC
1303 }
1304 }
1305
de23f234 1306 switch (st->codec->codec_id) {
36ef5369
AK
1307 case AV_CODEC_ID_PCM_S8:
1308 case AV_CODEC_ID_PCM_U8:
dd1c8f3e 1309 if (st->codec->bits_per_coded_sample == 16)
36ef5369 1310 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
b72708f8 1311 break;
36ef5369
AK
1312 case AV_CODEC_ID_PCM_S16LE:
1313 case AV_CODEC_ID_PCM_S16BE:
dd1c8f3e 1314 if (st->codec->bits_per_coded_sample == 8)
36ef5369 1315 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
dd1c8f3e 1316 else if (st->codec->bits_per_coded_sample == 24)
6b477e1b 1317 st->codec->codec_id =
36ef5369
AK
1318 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1319 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
de23f234 1320 break;
53152765 1321 /* set values for old format before stsd version 1 appeared */
36ef5369 1322 case AV_CODEC_ID_MACE3:
53152765
BC
1323 sc->samples_per_frame = 6;
1324 sc->bytes_per_frame = 2*st->codec->channels;
1325 break;
36ef5369 1326 case AV_CODEC_ID_MACE6:
53152765
BC
1327 sc->samples_per_frame = 6;
1328 sc->bytes_per_frame = 1*st->codec->channels;
1329 break;
36ef5369 1330 case AV_CODEC_ID_ADPCM_IMA_QT:
53152765
BC
1331 sc->samples_per_frame = 64;
1332 sc->bytes_per_frame = 34*st->codec->channels;
1333 break;
36ef5369 1334 case AV_CODEC_ID_GSM:
cc326d2b
BC
1335 sc->samples_per_frame = 160;
1336 sc->bytes_per_frame = 33;
1337 break;
de23f234
BC
1338 default:
1339 break;
6d6d7970 1340 }
14342fd5 1341
9770089d
BC
1342 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1343 if (bits_per_sample) {
dd1c8f3e 1344 st->codec->bits_per_coded_sample = bits_per_sample;
9770089d
BC
1345 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1346 }
5a7ba586 1347 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
58e9f2ed
DC
1348 // ttxt stsd contains display flags, justification, background
1349 // color, fonts, and default styles, so fake an atom to read it
a2704c97 1350 MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
fb9ac654 1351 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
3dd36041 1352 mov_read_glbl(c, pb, fake_atom);
cc8d87b7 1353 st->codec->codec_id= id;
6cdbff63
DC
1354 st->codec->width = sc->width;
1355 st->codec->height = sc->height;
de23f234
BC
1356 } else {
1357 /* other codec type, just skip (rtp, mp4s, tmcd ...) */
45a8a02a 1358 avio_skip(pb, size - (avio_tell(pb) - start_pos));
6cea494e 1359 }
de23f234 1360 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
a2704c97 1361 a.size = size - (avio_tell(pb) - start_pos);
9cf0419b 1362 if (a.size > 8) {
bcd5d979
DH
1363 int ret;
1364 if ((ret = mov_read_default(c, pb, a)) < 0)
1365 return ret;
9cf0419b 1366 } else if (a.size > 0)
45a8a02a 1367 avio_skip(pb, a.size);
6cea494e 1368 }
115329f1 1369
9888ffb1
LB
1370 if (pb->eof_reached)
1371 return AVERROR_EOF;
1372
5a7ba586 1373 if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
302c389e 1374 st->codec->sample_rate= sc->time_scale;
e31bd3e3 1375
d00f8e17 1376 /* special codec parameters handling */
e31bd3e3 1377 switch (st->codec->codec_id) {
b250f9c6 1378#if CONFIG_DV_DEMUXER
36ef5369 1379 case AV_CODEC_ID_DVAUDIO:
8e2fd8e1 1380 c->dv_fctx = avformat_alloc_context();
ab88b25f 1381 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
b60c0454
BC
1382 if (!c->dv_demux) {
1383 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
bcd5d979 1384 return AVERROR(ENOMEM);
b60c0454
BC
1385 }
1386 sc->dv_audio_container = 1;
36ef5369 1387 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
b60c0454 1388 break;
989ac5a6 1389#endif
b95319a2 1390 /* no ifdef since parameters are always those */
36ef5369 1391 case AV_CODEC_ID_QCELP:
17ad7b24
BC
1392 // force sample rate for qcelp when not stored in mov
1393 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1394 st->codec->sample_rate = 8000;
061f407e 1395 st->codec->channels= 1; /* really needed */
73b458e3 1396 break;
36ef5369 1397 case AV_CODEC_ID_AMR_NB:
b95319a2 1398 st->codec->channels= 1; /* really needed */
f06188d5 1399 /* force sample rate for amr, stsd in 3gp does not store sample rate */
237f1329 1400 st->codec->sample_rate = 8000;
237f1329 1401 break;
36ef5369 1402 case AV_CODEC_ID_AMR_WB:
237f1329
CEH
1403 st->codec->channels = 1;
1404 st->codec->sample_rate = 16000;
b95319a2 1405 break;
36ef5369
AK
1406 case AV_CODEC_ID_MP2:
1407 case AV_CODEC_ID_MP3:
72415b2a 1408 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
57004ff1 1409 st->need_parsing = AVSTREAM_PARSE_FULL;
a41104f8 1410 break;
36ef5369
AK
1411 case AV_CODEC_ID_GSM:
1412 case AV_CODEC_ID_ADPCM_MS:
1413 case AV_CODEC_ID_ADPCM_IMA_WAV:
1414 case AV_CODEC_ID_ILBC:
74e9b9ae
BC
1415 st->codec->block_align = sc->bytes_per_frame;
1416 break;
36ef5369 1417 case AV_CODEC_ID_ALAC:
a1532824 1418 if (st->codec->extradata_size == 36) {
364df7b7 1419 st->codec->channels = AV_RB8 (st->codec->extradata+21);
c6f1e29a 1420 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
a1532824 1421 }
be511925 1422 break;
36ef5369 1423 case AV_CODEC_ID_VC1:
755cd419
AK
1424 st->need_parsing = AVSTREAM_PARSE_FULL;
1425 break;
e31bd3e3
BC
1426 default:
1427 break;
1428 }
5cd62665 1429
6cea494e
ZK
1430 return 0;
1431}
1432
ae628ec1 1433static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
dc2cabd0
MS
1434{
1435 int entries;
1436
b7effd4e
AK
1437 avio_r8(pb); /* version */
1438 avio_rb24(pb); /* flags */
1439 entries = avio_rb32(pb);
dc2cabd0
MS
1440
1441 return ff_mov_read_stsd_entries(c, pb, entries);
1442}
1443
ae628ec1 1444static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6cea494e 1445{
6a63ff19
BC
1446 AVStream *st;
1447 MOVStreamContext *sc;
568e18b1 1448 unsigned int i, entries;
b6a17df4 1449
6a63ff19
BC
1450 if (c->fc->nb_streams < 1)
1451 return 0;
1452 st = c->fc->streams[c->fc->nb_streams-1];
1453 sc = st->priv_data;
1454
b7effd4e
AK
1455 avio_r8(pb); /* version */
1456 avio_rb24(pb); /* flags */
6cea494e 1457
b7effd4e 1458 entries = avio_rb32(pb);
115329f1 1459
dfd2a005 1460 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
f8c18cd7 1461
52401b82
AC
1462 if (!entries)
1463 return 0;
5a7ba586 1464 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
bcd5d979 1465 return AVERROR_INVALIDDATA;
04e06cfa
BC
1466 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1467 if (!sc->stsc_data)
0d8f0abf 1468 return AVERROR(ENOMEM);
0d8f0abf 1469
9888ffb1 1470 for (i = 0; i < entries && !pb->eof_reached; i++) {
b7effd4e
AK
1471 sc->stsc_data[i].first = avio_rb32(pb);
1472 sc->stsc_data[i].count = avio_rb32(pb);
1473 sc->stsc_data[i].id = avio_rb32(pb);
6cea494e 1474 }
9888ffb1
LB
1475
1476 sc->stsc_count = i;
1477
1478 if (pb->eof_reached)
1479 return AVERROR_EOF;
1480
6cea494e
ZK
1481 return 0;
1482}
1483
ae628ec1 1484static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
171a3531
BC
1485{
1486 AVStream *st;
1487 MOVStreamContext *sc;
1488 unsigned i, entries;
1489
1490 if (c->fc->nb_streams < 1)
1491 return 0;
1492 st = c->fc->streams[c->fc->nb_streams-1];
1493 sc = st->priv_data;
1494
b7effd4e 1495 avio_rb32(pb); // version + flags
171a3531 1496
b7effd4e 1497 entries = avio_rb32(pb);
171a3531 1498 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
bcd5d979 1499 return AVERROR_INVALIDDATA;
171a3531
BC
1500 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1501 if (!sc->stps_data)
1502 return AVERROR(ENOMEM);
171a3531 1503
9888ffb1 1504 for (i = 0; i < entries && !pb->eof_reached; i++) {
b7effd4e 1505 sc->stps_data[i] = avio_rb32(pb);
dfd2a005 1506 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
171a3531
BC
1507 }
1508
9888ffb1
LB
1509 sc->stps_count = i;
1510
1511 if (pb->eof_reached)
1512 return AVERROR_EOF;
1513
171a3531
BC
1514 return 0;
1515}
1516
ae628ec1 1517static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
247d56f5 1518{
6a63ff19
BC
1519 AVStream *st;
1520 MOVStreamContext *sc;
568e18b1 1521 unsigned int i, entries;
247d56f5 1522
6a63ff19
BC
1523 if (c->fc->nb_streams < 1)
1524 return 0;
1525 st = c->fc->streams[c->fc->nb_streams-1];
1526 sc = st->priv_data;
1527
b7effd4e
AK
1528 avio_r8(pb); /* version */
1529 avio_rb24(pb); /* flags */
247d56f5 1530
b7effd4e 1531 entries = avio_rb32(pb);
115329f1 1532
dfd2a005 1533 av_dlog(c->fc, "keyframe_count = %d\n", entries);
0d8f0abf 1534
29a20ac4 1535 if (!entries)
accea4d9
YN
1536 {
1537 sc->keyframe_absent = 1;
29a20ac4 1538 return 0;
accea4d9 1539 }
5a7ba586 1540 if (entries >= UINT_MAX / sizeof(int))
bcd5d979 1541 return AVERROR_INVALIDDATA;
1c02d96f 1542 sc->keyframes = av_malloc(entries * sizeof(int));
247d56f5 1543 if (!sc->keyframes)
0d8f0abf 1544 return AVERROR(ENOMEM);
0d8f0abf 1545
9888ffb1 1546 for (i = 0; i < entries && !pb->eof_reached; i++) {
b7effd4e 1547 sc->keyframes[i] = avio_rb32(pb);
dfd2a005 1548 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
247d56f5 1549 }
9888ffb1
LB
1550
1551 sc->keyframe_count = i;
1552
1553 if (pb->eof_reached)
1554 return AVERROR_EOF;
1555
247d56f5
BB
1556 return 0;
1557}
1558
ae628ec1 1559static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6cea494e 1560{
6a63ff19
BC
1561 AVStream *st;
1562 MOVStreamContext *sc;
bd27eed6
AC
1563 unsigned int i, entries, sample_size, field_size, num_bytes;
1564 GetBitContext gb;
1565 unsigned char* buf;
b6a17df4 1566
6a63ff19
BC
1567 if (c->fc->nb_streams < 1)
1568 return 0;
1569 st = c->fc->streams[c->fc->nb_streams-1];
1570 sc = st->priv_data;
1571
b7effd4e
AK
1572 avio_r8(pb); /* version */
1573 avio_rb24(pb); /* flags */
5cd62665 1574
bd27eed6 1575 if (atom.type == MKTAG('s','t','s','z')) {
b7effd4e 1576 sample_size = avio_rb32(pb);
d0dab0ec
AC
1577 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1578 sc->sample_size = sample_size;
1579 field_size = 32;
bd27eed6
AC
1580 } else {
1581 sample_size = 0;
b7effd4e
AK
1582 avio_rb24(pb); /* reserved */
1583 field_size = avio_r8(pb);
bd27eed6 1584 }
b7effd4e 1585 entries = avio_rb32(pb);
0d8f0abf 1586
dfd2a005 1587 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
568e18b1 1588
6cea494e 1589 sc->sample_count = entries;
b72708f8
BC
1590 if (sample_size)
1591 return 0;
1592
bd27eed6
AC
1593 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1594 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
bcd5d979 1595 return AVERROR_INVALIDDATA;
bd27eed6
AC
1596 }
1597
52401b82
AC
1598 if (!entries)
1599 return 0;
e4bc8af1 1600 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
bcd5d979 1601 return AVERROR_INVALIDDATA;
1c02d96f 1602 sc->sample_sizes = av_malloc(entries * sizeof(int));
b6a17df4 1603 if (!sc->sample_sizes)
0d8f0abf
BC
1604 return AVERROR(ENOMEM);
1605
bd27eed6
AC
1606 num_bytes = (entries*field_size+4)>>3;
1607
08a5b4e9 1608 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
bd27eed6
AC
1609 if (!buf) {
1610 av_freep(&sc->sample_sizes);
1611 return AVERROR(ENOMEM);
1612 }
1613
b7effd4e 1614 if (avio_read(pb, buf, num_bytes) < num_bytes) {
bd27eed6
AC
1615 av_freep(&sc->sample_sizes);
1616 av_free(buf);
bcd5d979 1617 return AVERROR_INVALIDDATA;
bd27eed6
AC
1618 }
1619
1620 init_get_bits(&gb, buf, 8*num_bytes);
1621
9888ffb1 1622 for (i = 0; i < entries && !pb->eof_reached; i++) {
bd27eed6 1623 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
bc7d0517
MS
1624 sc->data_size += sc->sample_sizes[i];
1625 }
bd27eed6 1626
9888ffb1
LB
1627 sc->sample_count = i;
1628
1629 if (pb->eof_reached)
1630 return AVERROR_EOF;
1631
bd27eed6 1632 av_free(buf);
6cea494e
ZK
1633 return 0;
1634}
1635
ae628ec1 1636static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
0147f198 1637{
6a63ff19
BC
1638 AVStream *st;
1639 MOVStreamContext *sc;
568e18b1 1640 unsigned int i, entries;
d957696f
MN
1641 int64_t duration=0;
1642 int64_t total_sample_count=0;
b6a17df4 1643
6a63ff19
BC
1644 if (c->fc->nb_streams < 1)
1645 return 0;
1646 st = c->fc->streams[c->fc->nb_streams-1];
1647 sc = st->priv_data;
1648
b7effd4e
AK
1649 avio_r8(pb); /* version */
1650 avio_rb24(pb); /* flags */
1651 entries = avio_rb32(pb);
0d8f0abf 1652
5a7ba586
LB
1653 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1654 c->fc->nb_streams-1, entries);
0d8f0abf 1655
6d23d197
AC
1656 if (!entries)
1657 return 0;
1658 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
30c3d976 1659 return AVERROR(EINVAL);
5a7ba586 1660
c3e92a6c 1661 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
c1da59fa 1662 if (!sc->stts_data)
0d8f0abf 1663 return AVERROR(ENOMEM);
5a7ba586 1664
9888ffb1 1665 for (i = 0; i < entries && !pb->eof_reached; i++) {
cd461d48
MN
1666 int sample_duration;
1667 int sample_count;
0147f198 1668
b7effd4e
AK
1669 sample_count=avio_rb32(pb);
1670 sample_duration = avio_rb32(pb);
cd7352d5
MN
1671 sc->stts_data[i].count= sample_count;
1672 sc->stts_data[i].duration= sample_duration;
1673
5a7ba586
LB
1674 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1675 sample_count, sample_duration);
4e5ef14f 1676
7e815047 1677 duration+=(int64_t)sample_duration*sample_count;
891f64b3 1678 total_sample_count+=sample_count;
891f64b3 1679 }
1680
9888ffb1
LB
1681 sc->stts_count = i;
1682
1683 if (pb->eof_reached)
1684 return AVERROR_EOF;
1685
961e0ccd 1686 st->nb_frames= total_sample_count;
5a7ba586 1687 if (duration)
961e0ccd 1688 st->duration= duration;
7f19bdc2 1689 sc->track_end = duration;
0147f198
FR
1690 return 0;
1691}
1692
ae628ec1 1693static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
c4ac052b 1694{
6a63ff19
BC
1695 AVStream *st;
1696 MOVStreamContext *sc;
c4ac052b
MN
1697 unsigned int i, entries;
1698
6a63ff19
BC
1699 if (c->fc->nb_streams < 1)
1700 return 0;
1701 st = c->fc->streams[c->fc->nb_streams-1];
1702 sc = st->priv_data;
1703
b7effd4e
AK
1704 avio_r8(pb); /* version */
1705 avio_rb24(pb); /* flags */
1706 entries = avio_rb32(pb);
0d8f0abf 1707
dfd2a005 1708 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
0d8f0abf 1709
52401b82
AC
1710 if (!entries)
1711 return 0;
5a7ba586 1712 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
bcd5d979 1713 return AVERROR_INVALIDDATA;
c3e92a6c 1714 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
c1da59fa 1715 if (!sc->ctts_data)
0d8f0abf 1716 return AVERROR(ENOMEM);
4e5ef14f 1717
9888ffb1 1718 for (i = 0; i < entries && !pb->eof_reached; i++) {
b7effd4e
AK
1719 int count =avio_rb32(pb);
1720 int duration =avio_rb32(pb);
70a61ed4
MN
1721
1722 sc->ctts_data[i].count = count;
1723 sc->ctts_data[i].duration= duration;
e7452721
BC
1724 if (duration < 0)
1725 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
c4ac052b 1726 }
e7452721 1727
9888ffb1
LB
1728 sc->ctts_count = i;
1729
1730 if (pb->eof_reached)
1731 return AVERROR_EOF;
1732
dfd2a005 1733 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
e7452721 1734
c4ac052b
MN
1735 return 0;
1736}
1737
d17d0ec8
YN
1738static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1739{
1740 AVStream *st;
1741 MOVStreamContext *sc;
1742 unsigned int i, entries;
1743 uint8_t version;
1744 uint32_t grouping_type;
1745
1746 if (c->fc->nb_streams < 1)
1747 return 0;
1748 st = c->fc->streams[c->fc->nb_streams-1];
1749 sc = st->priv_data;
1750
1751 version = avio_r8(pb); /* version */
1752 avio_rb24(pb); /* flags */
1753 grouping_type = avio_rl32(pb);
1754 if (grouping_type != MKTAG( 'r','a','p',' '))
1755 return 0; /* only support 'rap ' grouping */
1756 if (version == 1)
1757 avio_rb32(pb); /* grouping_type_parameter */
1758
1759 entries = avio_rb32(pb);
1760 if (!entries)
1761 return 0;
1762 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
1763 return AVERROR_INVALIDDATA;
1764 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
1765 if (!sc->rap_group)
1766 return AVERROR(ENOMEM);
1767
1768 for (i = 0; i < entries && !pb->eof_reached; i++) {
1769 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
1770 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
1771 }
1772
1773 sc->rap_group_count = i;
1774
1775 return pb->eof_reached ? AVERROR_EOF : 0;
1776}
1777
1e77810d
BC
1778static void mov_build_index(MOVContext *mov, AVStream *st)
1779{
1780 MOVStreamContext *sc = st->priv_data;
bc5c918e 1781 int64_t current_offset;
1e77810d
BC
1782 int64_t current_dts = 0;
1783 unsigned int stts_index = 0;
1784 unsigned int stsc_index = 0;
1785 unsigned int stss_index = 0;
171a3531 1786 unsigned int stps_index = 0;
1e77810d 1787 unsigned int i, j;
c5898e86 1788 uint64_t stream_size = 0;
4f7c7624 1789 AVIndexEntry *mem;
1e77810d 1790
baf2ffd3 1791 /* adjust first dts according to edit list */
c3024f9e 1792 if (sc->time_offset && mov->time_scale > 0) {
f33a6a22
YN
1793 if (sc->time_offset < 0)
1794 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
1795 current_dts = -sc->time_offset;
69e7ad8d 1796 if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
4af7166f 1797 sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
f03a081d
BC
1798 /* more than 16 frames delay, dts are likely wrong
1799 this happens with files created by iMovie */
1800 sc->wrong_dts = 1;
1801 st->codec->has_b_frames = 1;
1802 }
baf2ffd3
BC
1803 }
1804
d3bc61ac 1805 /* only use old uncompressed audio chunk demuxing when stts specifies it */
72415b2a 1806 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
d3bc61ac 1807 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1e77810d
BC
1808 unsigned int current_sample = 0;
1809 unsigned int stts_sample = 0;
171a3531 1810 unsigned int sample_size;
1e77810d 1811 unsigned int distance = 0;
d17d0ec8
YN
1812 unsigned int rap_group_index = 0;
1813 unsigned int rap_group_sample = 0;
1814 int rap_group_present = sc->rap_group_count && sc->rap_group;
94c9bf88 1815 int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
1e77810d 1816
4b29ed39
BC
1817 current_dts -= sc->dts_shift;
1818
52401b82
AC
1819 if (!sc->sample_count)
1820 return;
4f7c7624 1821 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
987e857f 1822 return;
4f7c7624
RB
1823 mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1824 if (!mem)
987e857f 1825 return;
4f7c7624
RB
1826 st->index_entries = mem;
1827 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
987e857f 1828
1e77810d
BC
1829 for (i = 0; i < sc->chunk_count; i++) {
1830 current_offset = sc->chunk_offsets[i];
9dd94f83 1831 while (stsc_index + 1 < sc->stsc_count &&
04e06cfa 1832 i + 1 == sc->stsc_data[stsc_index + 1].first)
1e77810d 1833 stsc_index++;
04e06cfa 1834 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
171a3531 1835 int keyframe = 0;
1e77810d
BC
1836 if (current_sample >= sc->sample_count) {
1837 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
f0f2218d 1838 return;
1e77810d 1839 }
171a3531 1840
accea4d9 1841 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
171a3531 1842 keyframe = 1;
1e77810d
BC
1843 if (stss_index + 1 < sc->keyframe_count)
1844 stss_index++;
171a3531
BC
1845 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1846 keyframe = 1;
1847 if (stps_index + 1 < sc->stps_count)
1848 stps_index++;
1e77810d 1849 }
d17d0ec8
YN
1850 if (rap_group_present && rap_group_index < sc->rap_group_count) {
1851 if (sc->rap_group[rap_group_index].index > 0)
1852 keyframe = 1;
1853 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
1854 rap_group_sample = 0;
1855 rap_group_index++;
1856 }
1857 }
171a3531
BC
1858 if (keyframe)
1859 distance = 0;
1e77810d 1860 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
5a7ba586 1861 if (sc->pseudo_stream_id == -1 ||
04e06cfa 1862 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
987e857f
BC
1863 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1864 e->pos = current_offset;
1865 e->timestamp = current_dts;
1866 e->size = sample_size;
1867 e->min_distance = distance;
1868 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
dfd2a005 1869 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
585dac65
BC
1870 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1871 current_offset, current_dts, sample_size, distance, keyframe);
1872 }
6c00a9de 1873
1e77810d 1874 current_offset += sample_size;
c5898e86 1875 stream_size += sample_size;
bbe46bc4 1876 current_dts += sc->stts_data[stts_index].duration;
1e77810d
BC
1877 distance++;
1878 stts_sample++;
1879 current_sample++;
1880 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1881 stts_sample = 0;
1882 stts_index++;
1883 }
1884 }
1885 }
fedb1eca
BC
1886 if (st->duration > 0)
1887 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
7e69621f 1888 } else {
987e857f 1889 unsigned chunk_samples, total = 0;
7e69621f 1890
987e857f
BC
1891 // compute total chunk count
1892 for (i = 0; i < sc->stsc_count; i++) {
1893 unsigned count, chunk_count;
7e69621f 1894
987e857f 1895 chunk_samples = sc->stsc_data[i].count;
a294a7a1
CEH
1896 if (i != sc->stsc_count - 1 &&
1897 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
7e69621f
BC
1898 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1899 return;
1900 }
1901
987e857f
BC
1902 if (sc->samples_per_frame >= 160) { // gsm
1903 count = chunk_samples / sc->samples_per_frame;
1904 } else if (sc->samples_per_frame > 1) {
1905 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1906 count = (chunk_samples+samples-1) / samples;
1907 } else {
1908 count = (chunk_samples+1023) / 1024;
1909 }
1910
1911 if (i < sc->stsc_count - 1)
1912 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1913 else
1914 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1915 total += chunk_count * count;
1916 }
1917
dfd2a005 1918 av_dlog(mov->fc, "chunk count %d\n", total);
4f7c7624 1919 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
987e857f 1920 return;
4f7c7624
RB
1921 mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
1922 if (!mem)
987e857f 1923 return;
4f7c7624
RB
1924 st->index_entries = mem;
1925 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
987e857f
BC
1926
1927 // populate index
1928 for (i = 0; i < sc->chunk_count; i++) {
1929 current_offset = sc->chunk_offsets[i];
1930 if (stsc_index + 1 < sc->stsc_count &&
1931 i + 1 == sc->stsc_data[stsc_index + 1].first)
1932 stsc_index++;
1933 chunk_samples = sc->stsc_data[stsc_index].count;
1934
7e69621f 1935 while (chunk_samples > 0) {
987e857f 1936 AVIndexEntry *e;
7e69621f
BC
1937 unsigned size, samples;
1938
1939 if (sc->samples_per_frame >= 160) { // gsm
1940 samples = sc->samples_per_frame;
1941 size = sc->bytes_per_frame;
1942 } else {
1943 if (sc->samples_per_frame > 1) {
1944 samples = FFMIN((1024 / sc->samples_per_frame)*
1945 sc->samples_per_frame, chunk_samples);
1946 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1e77810d 1947 } else {
7e69621f
BC
1948 samples = FFMIN(1024, chunk_samples);
1949 size = samples * sc->sample_size;
1e77810d
BC
1950 }
1951 }
7e69621f 1952
987e857f
BC
1953 if (st->nb_index_entries >= total) {
1954 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1955 return;
1956 }
1957 e = &st->index_entries[st->nb_index_entries++];
1958 e->pos = current_offset;
1959 e->timestamp = current_dts;
1960 e->size = size;
1961 e->min_distance = 0;
1962 e->flags = AVINDEX_KEYFRAME;
dfd2a005 1963 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
117a9190 1964 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
7e69621f
BC
1965 size, samples);
1966
1967 current_offset += size;
bbe46bc4 1968 current_dts += samples;
7e69621f 1969 chunk_samples -= samples;
1e77810d
BC
1970 }
1971 }
1972 }
1e77810d 1973}
bd991df2 1974
9d77a8fa
MS
1975static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
1976 AVIOInterruptCB *int_cb)
adeb9071 1977{
6a245905
MN
1978 /* try relative path, we do not try the absolute because it can leak information about our
1979 system to an attacker */
adeb9071
BC
1980 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1981 char filename[1024];
1982 char *src_path;
1983 int i, l;
1984
1985 /* find a source dir */
1986 src_path = strrchr(src, '/');
1987 if (src_path)
1988 src_path++;
1989 else
1990 src_path = src;
1991
1992 /* find a next level down to target */
1993 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1994 if (ref->path[l] == '/') {
1995 if (i == ref->nlvl_to - 1)
1996 break;
1997 else
1998 i++;
1999 }
2000
2001 /* compose filename if next level down to target was found */
bbdf0d22 2002 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
adeb9071
BC
2003 memcpy(filename, src, src_path - src);
2004 filename[src_path - src] = 0;
2005
2006 for (i = 1; i < ref->nlvl_from; i++)
2007 av_strlcat(filename, "../", 1024);
2008
2009 av_strlcat(filename, ref->path + l + 1, 1024);
2010
9d77a8fa 2011 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
adeb9071
BC
2012 return 0;
2013 }
2014 }
2015
2016 return AVERROR(ENOENT);
628b16f4 2017}
adeb9071 2018
ae628ec1 2019static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5ca1d879
ZK
2020{
2021 AVStream *st;
2022 MOVStreamContext *sc;
bd991df2 2023 int ret;
5ca1d879 2024
84ad31ff 2025 st = avformat_new_stream(c->fc, NULL);
3efe8848 2026 if (!st) return AVERROR(ENOMEM);
84ad31ff 2027 st->id = c->fc->nb_streams;
9a630c25 2028 sc = av_mallocz(sizeof(MOVStreamContext));
2922cbdb 2029 if (!sc) return AVERROR(ENOMEM);
5ca1d879 2030
5ca1d879 2031 st->priv_data = sc;
72415b2a 2032 st->codec->codec_type = AVMEDIA_TYPE_DATA;
64d50fa5 2033 sc->ffindex = st->index;
5ca1d879 2034
bd991df2
BC
2035 if ((ret = mov_read_default(c, pb, atom)) < 0)
2036 return ret;
2037
2038 /* sanity checks */
6c00a9de
BC
2039 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2040 (!sc->sample_size && !sc->sample_count))) {
6282c5f4
BC
2041 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2042 st->index);
bd991df2
BC
2043 return 0;
2044 }
6c00a9de 2045
c3024f9e 2046 if (sc->time_scale <= 0) {
507330b9 2047 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
6c00a9de 2048 sc->time_scale = c->time_scale;
c3024f9e 2049 if (sc->time_scale <= 0)
507330b9
BC
2050 sc->time_scale = 1;
2051 }
6c00a9de 2052
c3f9ebf7 2053 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
bd991df2 2054
bd991df2
BC
2055 mov_build_index(c, st);
2056
2057 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
adeb9071 2058 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
9d77a8fa 2059 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
adeb9071
BC
2060 av_log(c->fc, AV_LOG_ERROR,
2061 "stream %d, error opening alias: path='%s', dir='%s', "
2062 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2063 st->index, dref->path, dref->dir, dref->filename,
2064 dref->volume, dref->nlvl_from, dref->nlvl_to);
bd991df2
BC
2065 } else
2066 sc->pb = c->fc->pb;
2067
72415b2a 2068 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
525fcb27
AW
2069 if (!st->sample_aspect_ratio.num &&
2070 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2071 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2072 ((double)st->codec->width * sc->height), INT_MAX);
c3aeaa54
BC
2073 }
2074
80b6b314
JG
2075 if (st->duration != AV_NOPTS_VALUE)
2076 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2077 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
c9566115
BC
2078 }
2079
bd991df2 2080 switch (st->codec->codec_id) {
b250f9c6 2081#if CONFIG_H261_DECODER
36ef5369 2082 case AV_CODEC_ID_H261:
bd991df2 2083#endif
b250f9c6 2084#if CONFIG_H263_DECODER
36ef5369 2085 case AV_CODEC_ID_H263:
bd991df2 2086#endif
b250f9c6 2087#if CONFIG_MPEG4_DECODER
36ef5369 2088 case AV_CODEC_ID_MPEG4:
bd991df2 2089#endif
6c00a9de 2090 st->codec->width = 0; /* let decoder init width/height */
bd991df2
BC
2091 st->codec->height= 0;
2092 break;
bd991df2 2093 }
f9900374
BC
2094
2095 /* Do not need those anymore. */
2096 av_freep(&sc->chunk_offsets);
04e06cfa 2097 av_freep(&sc->stsc_data);
f9900374
BC
2098 av_freep(&sc->sample_sizes);
2099 av_freep(&sc->keyframes);
2100 av_freep(&sc->stts_data);
171a3531 2101 av_freep(&sc->stps_data);
d17d0ec8 2102 av_freep(&sc->rap_group);
f9900374 2103
bd991df2 2104 return 0;
5ca1d879
ZK
2105}
2106
ae628ec1 2107static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
51c15201
BC
2108{
2109 int ret;
2110 c->itunes_metadata = 1;
2111 ret = mov_read_default(c, pb, atom);
2112 c->itunes_metadata = 0;
2113 return ret;
2114}
2115
ae628ec1 2116static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
51c15201 2117{
df8843c6 2118 while (atom.size > 8) {
b7effd4e 2119 uint32_t tag = avio_rl32(pb);
df8843c6
BC
2120 atom.size -= 4;
2121 if (tag == MKTAG('h','d','l','r')) {
6b4aa5da 2122 avio_seek(pb, -8, SEEK_CUR);
df8843c6
BC
2123 atom.size += 8;
2124 return mov_read_default(c, pb, atom);
2125 }
2126 }
2127 return 0;
51c15201
BC
2128}
2129
ae628ec1 2130static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5ca1d879 2131{
ec072669
JS
2132 int i;
2133 int width;
2134 int height;
2135 int64_t disp_transform[2];
2136 int display_matrix[3][2];
6a63ff19
BC
2137 AVStream *st;
2138 MOVStreamContext *sc;
2139 int version;
1f70a5ad 2140 int flags;
6a63ff19
BC
2141
2142 if (c->fc->nb_streams < 1)
2143 return 0;
2144 st = c->fc->streams[c->fc->nb_streams-1];
2145 sc = st->priv_data;
5ca1d879 2146
b7effd4e 2147 version = avio_r8(pb);
1f70a5ad
JS
2148 flags = avio_rb24(pb);
2149 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
5ca1d879 2150
1175561e 2151 if (version == 1) {
b7effd4e
AK
2152 avio_rb64(pb);
2153 avio_rb64(pb);
1175561e 2154 } else {
b7effd4e
AK
2155 avio_rb32(pb); /* creation time */
2156 avio_rb32(pb); /* modification time */
1175561e 2157 }
b7effd4e
AK
2158 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2159 avio_rb32(pb); /* reserved */
fcdd622c 2160
117a9190 2161 /* highlevel (considering edits) duration in movie timebase */
b7effd4e
AK
2162 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2163 avio_rb32(pb); /* reserved */
2164 avio_rb32(pb); /* reserved */
5ca1d879 2165
b7effd4e
AK
2166 avio_rb16(pb); /* layer */
2167 avio_rb16(pb); /* alternate group */
2168 avio_rb16(pb); /* volume */
2169 avio_rb16(pb); /* reserved */
5ca1d879 2170
ec072669
JS
2171 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2172 // they're kept in fixed point format through all calculations
2173 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2174 for (i = 0; i < 3; i++) {
b7effd4e
AK
2175 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2176 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2177 avio_rb32(pb); // 2.30 fixed point (not used)
ec072669 2178 }
5ca1d879 2179
b7effd4e
AK
2180 width = avio_rb32(pb); // 16.16 fixed point track width
2181 height = avio_rb32(pb); // 16.16 fixed point track height
6cdbff63
DC
2182 sc->width = width >> 16;
2183 sc->height = height >> 16;
ec072669 2184
d862fce7 2185 // transform the display width/height according to the matrix
ec072669 2186 // skip this if the display matrix is the default identity matrix
d862fce7 2187 // or if it is rotating the picture, ex iPhone 3GS
ec072669
JS
2188 // to keep the same scale, use [width height 1<<16]
2189 if (width && height &&
d862fce7
BC
2190 ((display_matrix[0][0] != 65536 ||
2191 display_matrix[1][1] != 65536) &&
2192 !display_matrix[0][1] &&
2193 !display_matrix[1][0] &&
2194 !display_matrix[2][0] && !display_matrix[2][1])) {
ec072669
JS
2195 for (i = 0; i < 2; i++)
2196 disp_transform[i] =
2197 (int64_t) width * display_matrix[0][i] +
2198 (int64_t) height * display_matrix[1][i] +
2199 ((int64_t) display_matrix[2][i] << 16);
2200
2201 //sample aspect ratio is new width/height divided by old width/height
59729451 2202 st->sample_aspect_ratio = av_d2q(
ec072669
JS
2203 ((double) disp_transform[0] * height) /
2204 ((double) disp_transform[1] * width), INT_MAX);
2205 }
5ca1d879
ZK
2206 return 0;
2207}
2208
ae628ec1 2209static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
61aedb0f
BC
2210{
2211 MOVFragment *frag = &c->fragment;
2212 MOVTrackExt *trex = NULL;
2213 int flags, track_id, i;
2214
b7effd4e
AK
2215 avio_r8(pb); /* version */
2216 flags = avio_rb24(pb);
61aedb0f 2217
b7effd4e 2218 track_id = avio_rb32(pb);
63581eb1 2219 if (!track_id)
bcd5d979 2220 return AVERROR_INVALIDDATA;
61aedb0f
BC
2221 frag->track_id = track_id;
2222 for (i = 0; i < c->trex_count; i++)
2223 if (c->trex_data[i].track_id == frag->track_id) {
2224 trex = &c->trex_data[i];
2225 break;
2226 }
2227 if (!trex) {
2228 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
bcd5d979 2229 return AVERROR_INVALIDDATA;
61aedb0f
BC
2230 }
2231
73328f24
MS
2232 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2233 avio_rb64(pb) : frag->moof_offset;
2234 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2235
2236 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2237 avio_rb32(pb) : trex->duration;
2238 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2239 avio_rb32(pb) : trex->size;
2240 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2241 avio_rb32(pb) : trex->flags;
dfd2a005 2242 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
61aedb0f
BC
2243 return 0;
2244}
2245
ae628ec1 2246static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
7221579b 2247{
b7effd4e 2248 c->chapter_track = avio_rb32(pb);
7221579b
DC
2249 return 0;
2250}
2251
ae628ec1 2252static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
61aedb0f
BC
2253{
2254 MOVTrackExt *trex;
2255
2256 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
bcd5d979 2257 return AVERROR_INVALIDDATA;
0d8f0abf
BC
2258 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2259 if (!trex)
61aedb0f 2260 return AVERROR(ENOMEM);
0d8f0abf 2261 c->trex_data = trex;
61aedb0f 2262 trex = &c->trex_data[c->trex_count++];
b7effd4e
AK
2263 avio_r8(pb); /* version */
2264 avio_rb24(pb); /* flags */
2265 trex->track_id = avio_rb32(pb);
2266 trex->stsd_id = avio_rb32(pb);
2267 trex->duration = avio_rb32(pb);
2268 trex->size = avio_rb32(pb);
2269 trex->flags = avio_rb32(pb);
61aedb0f
BC
2270 return 0;
2271}
2272
ae628ec1 2273static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
61aedb0f
BC
2274{
2275 MOVFragment *frag = &c->fragment;
63581eb1 2276 AVStream *st = NULL;
44e43aab 2277 MOVStreamContext *sc;
45a811b5 2278 MOVStts *ctts_data;
61aedb0f
BC
2279 uint64_t offset;
2280 int64_t dts;
2281 int data_offset = 0;
2282 unsigned entries, first_sample_flags = frag->flags;
a5c50913 2283 int flags, distance, i, found_keyframe = 0;
61aedb0f 2284
63581eb1
AC
2285 for (i = 0; i < c->fc->nb_streams; i++) {
2286 if (c->fc->streams[i]->id == frag->track_id) {
2287 st = c->fc->streams[i];
2288 break;
2289 }
2290 }
2291 if (!st) {
2292 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
bcd5d979 2293 return AVERROR_INVALIDDATA;
63581eb1 2294 }
44e43aab 2295 sc = st->priv_data;
61aedb0f
BC
2296 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2297 return 0;
b7effd4e
AK
2298 avio_r8(pb); /* version */
2299 flags = avio_rb24(pb);
2300 entries = avio_rb32(pb);
dfd2a005 2301 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
45a811b5
YN
2302
2303 /* Always assume the presence of composition time offsets.
2304 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2305 * 1) in the initial movie, there are no samples.
2306 * 2) in the first movie fragment, there is only one sample without composition time offset.
2307 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2308 if (!sc->ctts_count && sc->sample_count)
2309 {
2310 /* Complement ctts table if moov atom doesn't have ctts atom. */
2311 ctts_data = av_malloc(sizeof(*sc->ctts_data));
0d8f0abf 2312 if (!ctts_data)
61aedb0f 2313 return AVERROR(ENOMEM);
0d8f0abf 2314 sc->ctts_data = ctts_data;
45a811b5
YN
2315 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2316 sc->ctts_data[sc->ctts_count].duration = 0;
2317 sc->ctts_count++;
61aedb0f 2318 }
45a811b5 2319 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
bcd5d979 2320 return AVERROR_INVALIDDATA;
45a811b5
YN
2321 ctts_data = av_realloc(sc->ctts_data,
2322 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2323 if (!ctts_data)
2324 return AVERROR(ENOMEM);
2325 sc->ctts_data = ctts_data;
2326
3eec23f3
MS
2327 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2328 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
7f19bdc2 2329 dts = sc->track_end - sc->time_offset;
61aedb0f
BC
2330 offset = frag->base_data_offset + data_offset;
2331 distance = 0;
dfd2a005 2332 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
9888ffb1 2333 for (i = 0; i < entries && !pb->eof_reached; i++) {
61aedb0f
BC
2334 unsigned sample_size = frag->size;
2335 int sample_flags = i ? frag->flags : first_sample_flags;
2336 unsigned sample_duration = frag->duration;
a5c50913 2337 int keyframe = 0;
61aedb0f 2338
3eec23f3
MS
2339 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2340 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2341 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
45a811b5 2342 sc->ctts_data[sc->ctts_count].count = 1;
3eec23f3
MS
2343 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2344 avio_rb32(pb) : 0;
45a811b5 2345 sc->ctts_count++;
a5c50913
MS
2346 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2347 keyframe = 1;
2348 else if (!found_keyframe)
2349 keyframe = found_keyframe =
2350 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2351 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2352 if (keyframe)
61aedb0f
BC
2353 distance = 0;
2354 av_add_index_entry(st, offset, dts, sample_size, distance,
2355 keyframe ? AVINDEX_KEYFRAME : 0);
dfd2a005 2356 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
61aedb0f
BC
2357 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2358 offset, dts, sample_size, distance, keyframe);
2359 distance++;
bbe46bc4 2360 dts += sample_duration;
61aedb0f 2361 offset += sample_size;
bc7d0517 2362 sc->data_size += sample_size;
61aedb0f 2363 }
9888ffb1
LB
2364
2365 if (pb->eof_reached)
2366 return AVERROR_EOF;
2367
61aedb0f 2368 frag->moof_offset = offset;
7f19bdc2 2369 st->duration = sc->track_end = dts + sc->time_offset;
61aedb0f
BC
2370 return 0;
2371}
2372
5ca1d879
ZK
2373/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2374/* like the files created with Adobe Premiere 5.0, for samples see */
2375/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
ae628ec1 2376static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5ca1d879
ZK
2377{
2378 int err;
5ca1d879 2379
5ca1d879
ZK
2380 if (atom.size < 8)
2381 return 0; /* continue */
b7effd4e 2382 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
45a8a02a 2383 avio_skip(pb, atom.size - 4);
5ca1d879
ZK
2384 return 0;
2385 }
b7effd4e 2386 atom.type = avio_rl32(pb);
5ca1d879 2387 atom.size -= 8;
1c126b4f 2388 if (atom.type != MKTAG('m','d','a','t')) {
45a8a02a 2389 avio_skip(pb, atom.size);
5ca1d879
ZK
2390 return 0;
2391 }
2392 err = mov_read_mdat(c, pb, atom);
5ca1d879
ZK
2393 return err;
2394}
2395
ae628ec1 2396static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
0147f198 2397{
b250f9c6 2398#if CONFIG_ZLIB
ae628ec1 2399 AVIOContext ctx;
b6a17df4
ZK
2400 uint8_t *cmov_data;
2401 uint8_t *moov_data; /* uncompressed data */
0147f198 2402 long cmov_len, moov_len;
6f04eb1e 2403 int ret = -1;
b6a17df4 2404
b7effd4e
AK
2405 avio_rb32(pb); /* dcom atom */
2406 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
bcd5d979 2407 return AVERROR_INVALIDDATA;
b7effd4e 2408 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
f3592353 2409 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
bcd5d979 2410 return AVERROR_INVALIDDATA;
0147f198 2411 }
b7effd4e
AK
2412 avio_rb32(pb); /* cmvd atom */
2413 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
bcd5d979 2414 return AVERROR_INVALIDDATA;
b7effd4e 2415 moov_len = avio_rb32(pb); /* uncompressed size */
5ca1d879 2416 cmov_len = atom.size - 6 * 4;
5cd62665 2417
9a630c25 2418 cmov_data = av_malloc(cmov_len);
0147f198 2419 if (!cmov_data)
0d8f0abf 2420 return AVERROR(ENOMEM);
9a630c25 2421 moov_data = av_malloc(moov_len);
0147f198
FR
2422 if (!moov_data) {
2423 av_free(cmov_data);
0d8f0abf 2424 return AVERROR(ENOMEM);
0147f198 2425 }
b7effd4e 2426 avio_read(pb, cmov_data, cmov_len);
5a7ba586 2427 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
6f04eb1e 2428 goto free_and_return;
5a7ba586 2429 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
6f04eb1e 2430 goto free_and_return;
1c126b4f 2431 atom.type = MKTAG('m','o','o','v');
5ca1d879
ZK
2432 atom.size = moov_len;
2433 ret = mov_read_default(c, &ctx, atom);
6f04eb1e 2434free_and_return:
0147f198
FR
2435 av_free(moov_data);
2436 av_free(cmov_data);
2437 return ret;
d966b2f0
BC
2438#else
2439 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
bcd5d979 2440 return AVERROR(ENOSYS);
0147f198 2441#endif
d966b2f0 2442}
0147f198 2443
baf25c9d 2444/* edit list atom */
ae628ec1 2445static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
baf25c9d 2446{
1c4bf2ec 2447 MOVStreamContext *sc;
5f0bb0ba 2448 int i, edit_count, version;
e0977c80 2449
1c4bf2ec
BC
2450 if (c->fc->nb_streams < 1)
2451 return 0;
2452 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2453
5f0bb0ba 2454 version = avio_r8(pb); /* version */
b7effd4e
AK
2455 avio_rb24(pb); /* flags */
2456 edit_count = avio_rb32(pb); /* entries */
e0977c80 2457
5a7ba586 2458 if ((uint64_t)edit_count*12+8 > atom.size)
bcd5d979 2459 return AVERROR_INVALIDDATA;
53e099de 2460
5a7ba586 2461 for (i=0; i<edit_count; i++){
5f0bb0ba
YN
2462 int64_t time;
2463 int64_t duration;
2464 if (version == 1) {
2465 duration = avio_rb64(pb);
2466 time = avio_rb64(pb);
2467 } else {
2468 duration = avio_rb32(pb); /* segment duration */
ae88e9cf 2469 time = (int32_t)avio_rb32(pb); /* media time */
5f0bb0ba 2470 }
b7effd4e 2471 avio_rb32(pb); /* Media rate */
2ac736a6
RD
2472 if (i == 0 && time >= -1) {
2473 sc->time_offset = time != -1 ? time : -duration;
a5929abe 2474 }
e0977c80 2475 }
baf2ffd3 2476
5a7ba586 2477 if (edit_count > 1)
baf2ffd3
BC
2478 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2479 "a/v desync might occur, patch welcome\n");
2480
dfd2a005 2481 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
e0977c80 2482 return 0;
baf25c9d
GC
2483}
2484
6cea494e 2485static const MOVParseTableEntry mov_default_parse_table[] = {
d4fdba0d 2486{ MKTAG('a','v','s','s'), mov_read_extradata },
1cf9f6ed 2487{ MKTAG('c','h','p','l'), mov_read_chpl },
1c126b4f
BC
2488{ MKTAG('c','o','6','4'), mov_read_stco },
2489{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2490{ MKTAG('d','i','n','f'), mov_read_default },
2491{ MKTAG('d','r','e','f'), mov_read_dref },
2492{ MKTAG('e','d','t','s'), mov_read_default },
2493{ MKTAG('e','l','s','t'), mov_read_elst },
2494{ MKTAG('e','n','d','a'), mov_read_enda },
4bf3c8f2 2495{ MKTAG('f','i','e','l'), mov_read_fiel },
1c126b4f
BC
2496{ MKTAG('f','t','y','p'), mov_read_ftyp },
2497{ MKTAG('g','l','b','l'), mov_read_glbl },
2498{ MKTAG('h','d','l','r'), mov_read_hdlr },
51c15201 2499{ MKTAG('i','l','s','t'), mov_read_ilst },
1c126b4f
BC
2500{ MKTAG('j','p','2','h'), mov_read_extradata },
2501{ MKTAG('m','d','a','t'), mov_read_mdat },
2502{ MKTAG('m','d','h','d'), mov_read_mdhd },
2503{ MKTAG('m','d','i','a'), mov_read_default },
51c15201 2504{ MKTAG('m','e','t','a'), mov_read_meta },
1c126b4f
BC
2505{ MKTAG('m','i','n','f'), mov_read_default },
2506{ MKTAG('m','o','o','f'), mov_read_moof },
2507{ MKTAG('m','o','o','v'), mov_read_moov },
2508{ MKTAG('m','v','e','x'), mov_read_default },
2509{ MKTAG('m','v','h','d'), mov_read_mvhd },
2510{ MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2511{ MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2512{ MKTAG('a','v','c','C'), mov_read_glbl },
6da54074 2513{ MKTAG('p','a','s','p'), mov_read_pasp },
1c126b4f
BC
2514{ MKTAG('s','t','b','l'), mov_read_default },
2515{ MKTAG('s','t','c','o'), mov_read_stco },
171a3531 2516{ MKTAG('s','t','p','s'), mov_read_stps },
653d7aeb 2517{ MKTAG('s','t','r','f'), mov_read_strf },
1c126b4f
BC
2518{ MKTAG('s','t','s','c'), mov_read_stsc },
2519{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2520{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2521{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2522{ MKTAG('s','t','t','s'), mov_read_stts },
bd27eed6 2523{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
1c126b4f
BC
2524{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2525{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2526{ MKTAG('t','r','a','k'), mov_read_trak },
2527{ MKTAG('t','r','a','f'), mov_read_default },
7221579b
DC
2528{ MKTAG('t','r','e','f'), mov_read_default },
2529{ MKTAG('c','h','a','p'), mov_read_chap },
1c126b4f
BC
2530{ MKTAG('t','r','e','x'), mov_read_trex },
2531{ MKTAG('t','r','u','n'), mov_read_trun },
86b0affd 2532{ MKTAG('u','d','t','a'), mov_read_default },
1c126b4f
BC
2533{ MKTAG('w','a','v','e'), mov_read_wave },
2534{ MKTAG('e','s','d','s'), mov_read_esds },
bdecdd2b 2535{ MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
546adc1f 2536{ MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
1c126b4f 2537{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
85e9e3a9 2538{ MKTAG('w','f','e','x'), mov_read_wfex },
1c126b4f 2539{ MKTAG('c','m','o','v'), mov_read_cmov },
1fdf18f4 2540{ MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
89415b8e 2541{ MKTAG('d','v','c','1'), mov_read_dvc1 },
d17d0ec8 2542{ MKTAG('s','b','g','p'), mov_read_sbgp },
bcfe2ba0 2543{ 0, NULL }
6cea494e
ZK
2544};
2545
1ce1e636
RB
2546static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2547{
2548 int64_t total_size = 0;
2549 MOVAtom a;
2550 int i;
2551
2552 if (atom.size < 0)
2553 atom.size = INT64_MAX;
2554 while (total_size + 8 < atom.size && !pb->eof_reached) {
2555 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
2556 a.size = atom.size;
2557 a.type=0;
2558 if (atom.size >= 8) {
2559 a.size = avio_rb32(pb);
2560 a.type = avio_rl32(pb);
2561 }
2562 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
2563 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
2564 total_size += 8;
2565 if (a.size == 1) { /* 64 bit extended size */
2566 a.size = avio_rb64(pb) - 8;
2567 total_size += 8;
2568 }
2569 if (a.size == 0) {
2570 a.size = atom.size - total_size;
2571 if (a.size <= 8)
2572 break;
2573 }
2574 a.size -= 8;
2575 if (a.size < 0)
2576 break;
2577 a.size = FFMIN(a.size, atom.size - total_size);
2578
2579 for (i = 0; mov_default_parse_table[i].type; i++)
2580 if (mov_default_parse_table[i].type == a.type) {
2581 parse = mov_default_parse_table[i].parse;
2582 break;
2583 }
2584
2585 // container is user data
2586 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
2587 atom.type == MKTAG('i','l','s','t')))
2588 parse = mov_read_udta_string;
2589
2590 if (!parse) { /* skip leaf atoms data */
2591 avio_skip(pb, a.size);
2592 } else {
2593 int64_t start_pos = avio_tell(pb);
2594 int64_t left;
2595 int err = parse(c, pb, a);
2596 if (err < 0)
2597 return err;
2598 if (c->found_moov && c->found_mdat &&
2599 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
2600 start_pos + a.size == avio_size(pb))) {
2601 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
2602 c->next_root_atom = start_pos + a.size;
2603 return 0;
2604 }
2605 left = a.size - avio_tell(pb) + start_pos;
2606 if (left > 0) /* skip garbage at atom end */
2607 avio_skip(pb, left);
5b4eb243
MS
2608 else if (left < 0) {
2609 av_log(c->fc, AV_LOG_WARNING,
2610 "overread end of atom '%.4s' by %"PRId64" bytes\n",
2611 (char*)&a.type, -left);
2612 avio_seek(pb, left, SEEK_CUR);
2613 }
1ce1e636
RB
2614 }
2615
2616 total_size += a.size;
2617 }
2618
2619 if (total_size < atom.size && atom.size < 0x7ffff)
2620 avio_skip(pb, atom.size - total_size);
2621
2622 return 0;
2623}
2624
c9a65ca8
FB
2625static int mov_probe(AVProbeData *p)
2626{
0e7eed09
FB
2627 unsigned int offset;
2628 uint32_t tag;
2497479f 2629 int score = 0;
3ffe3793 2630
c9a65ca8 2631 /* check file header */
0e7eed09 2632 offset = 0;
5a7ba586 2633 for (;;) {
0e7eed09
FB
2634 /* ignore invalid offset */
2635 if ((offset + 8) > (unsigned int)p->buf_size)
2497479f 2636 return score;
fead30d4 2637 tag = AV_RL32(p->buf + offset + 4);
0e7eed09 2638 switch(tag) {
2497479f 2639 /* check for obvious tags */
1c126b4f
BC
2640 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2641 case MKTAG('m','o','o','v'):
2642 case MKTAG('m','d','a','t'):
2643 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2644 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
40e7aaa3 2645 case MKTAG('f','t','y','p'):
3ffe3793 2646 return AVPROBE_SCORE_MAX;
2497479f 2647 /* those are more common words, so rate then a bit less */
1c126b4f
BC
2648 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2649 case MKTAG('w','i','d','e'):
2650 case MKTAG('f','r','e','e'):
2651 case MKTAG('j','u','n','k'):
2652 case MKTAG('p','i','c','t'):
2497479f 2653 return AVPROBE_SCORE_MAX - 5;
5469b788 2654 case MKTAG(0x82,0x82,0x7f,0x7d):
1c126b4f
BC
2655 case MKTAG('s','k','i','p'):
2656 case MKTAG('u','u','i','d'):
2657 case MKTAG('p','r','f','l'):
fead30d4 2658 offset = AV_RB32(p->buf+offset) + offset;
2497479f 2659 /* if we only find those cause probedata is too small at least rate them */
e0f8be64 2660 score = AVPROBE_SCORE_EXTENSION;
0e7eed09
FB
2661 break;
2662 default:
2663 /* unrecognized tag */
2497479f 2664 return score;
0e7eed09 2665 }
3ffe3793 2666 }
c9a65ca8
FB
2667}
2668
7221579b
DC
2669// must be done after parsing all trak because there's no order requirement
2670static void mov_read_chapters(AVFormatContext *s)
2671{
2672 MOVContext *mov = s->priv_data;
2673 AVStream *st = NULL;
2674 MOVStreamContext *sc;
2675 int64_t cur_pos;
225b6d7f 2676 int i;
7221579b
DC
2677
2678 for (i = 0; i < s->nb_streams; i++)
2679 if (s->streams[i]->id == mov->chapter_track) {
2680 st = s->streams[i];
2681 break;
2682 }
2683 if (!st) {
2684 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2685 return;
2686 }
2687
2688 st->discard = AVDISCARD_ALL;
2689 sc = st->priv_data;
a2704c97 2690 cur_pos = avio_tell(sc->pb);
7221579b
DC
2691
2692 for (i = 0; i < st->nb_index_entries; i++) {
2693 AVIndexEntry *sample = &st->index_entries[i];
2694 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
225b6d7f
AK
2695 uint8_t *title;
2696 uint16_t ch;
2697 int len, title_len;
7221579b 2698
6b4aa5da 2699 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
7221579b
DC
2700 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2701 goto finish;
2702 }
2703
7221579b 2704 // the first two bytes are the length of the title
b7effd4e 2705 len = avio_rb16(sc->pb);
7221579b
DC
2706 if (len > sample->size-2)
2707 continue;
225b6d7f
AK
2708 title_len = 2*len + 1;
2709 if (!(title = av_mallocz(title_len)))
2710 goto finish;
7221579b
DC
2711
2712 // The samples could theoretically be in any encoding if there's an encd
2713 // atom following, but in practice are only utf-8 or utf-16, distinguished
2714 // instead by the presence of a BOM
8fb22c3d
AC
2715 if (!len) {
2716 title[0] = 0;
2717 } else {
2718 ch = avio_rb16(sc->pb);
2719 if (ch == 0xfeff)
2720 avio_get_str16be(sc->pb, len, title, title_len);
2721 else if (ch == 0xfffe)
2722 avio_get_str16le(sc->pb, len, title, title_len);
2723 else {
2724 AV_WB16(title, ch);
2725 if (len == 1 || len == 2)
7ad06beb 2726 title[len] = 0;
8fb22c3d
AC
2727 else
2728 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
2729 }
7221579b
DC
2730 }
2731
1fa395e4 2732 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
c4f8765a 2733 av_freep(&title);
7221579b
DC
2734 }
2735finish:
6b4aa5da 2736 avio_seek(sc->pb, cur_pos, SEEK_SET);
7221579b
DC
2737}
2738
c788782c
DC
2739static int mov_read_close(AVFormatContext *s)
2740{
2741 MOVContext *mov = s->priv_data;
2742 int i, j;
2743
2744 for (i = 0; i < s->nb_streams; i++) {
2745 AVStream *st = s->streams[i];
2746 MOVStreamContext *sc = st->priv_data;
2747
2748 av_freep(&sc->ctts_data);
2749 for (j = 0; j < sc->drefs_count; j++) {
2750 av_freep(&sc->drefs[j].path);
2751 av_freep(&sc->drefs[j].dir);
2752 }
2753 av_freep(&sc->drefs);
2754 if (sc->pb && sc->pb != s->pb)
2755 avio_close(sc->pb);
2756 }
2757
2758 if (mov->dv_demux) {
2759 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2760 av_freep(&mov->dv_fctx->streams[i]->codec);
2761 av_freep(&mov->dv_fctx->streams[i]);
2762 }
2763 av_freep(&mov->dv_fctx);
2764 av_freep(&mov->dv_demux);
2765 }
2766
2767 av_freep(&mov->trex_data);
2768
2769 return 0;
2770}
2771
6e9651d1 2772static int mov_read_header(AVFormatContext *s)
6cea494e 2773{
e4141433 2774 MOVContext *mov = s->priv_data;
ae628ec1 2775 AVIOContext *pb = s->pb;
f9900374 2776 int err;
3491866a 2777 MOVAtom atom = { AV_RL32("root") };
6cea494e 2778
6cea494e 2779 mov->fc = s;
117a9190 2780 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
5a7ba586 2781 if (pb->seekable)
76aa876e 2782 atom.size = avio_size(pb);
6cea494e 2783 else
fa22ca22 2784 atom.size = INT64_MAX;
6cea494e 2785
6cea494e 2786 /* check MOV header */
612b5cbb
BC
2787 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2788 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
c788782c 2789 mov_read_close(s);
612b5cbb
BC
2790 return err;
2791 }
2792 if (!mov->found_moov) {
2793 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
c788782c 2794 mov_read_close(s);
bcd5d979 2795 return AVERROR_INVALIDDATA;
6cea494e 2796 }
3583d7cf 2797 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
4e5ef14f 2798
8978feda 2799 if (pb->seekable && mov->chapter_track > 0)
7221579b
DC
2800 mov_read_chapters(s);
2801
bc7d0517
MS
2802 if (mov->trex_data) {
2803 int i;
2804 for (i = 0; i < s->nb_streams; i++) {
2805 AVStream *st = s->streams[i];
2806 MOVStreamContext *sc = st->priv_data;
2807 if (st->duration)
2808 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
2809 }
2810 }
2811
6cea494e
ZK
2812 return 0;
2813}
2814
5dc5c43b 2815static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
6cea494e 2816{
5dc5c43b 2817 AVIndexEntry *sample = NULL;
86d8602f 2818 int64_t best_dts = INT64_MAX;
5dc5c43b 2819 int i;
11f16b66 2820 for (i = 0; i < s->nb_streams; i++) {
69fc436c
RD
2821 AVStream *avst = s->streams[i];
2822 MOVStreamContext *msc = avst->priv_data;
3fe4d5d4 2823 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
69fc436c 2824 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
bbe46bc4 2825 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
dfd2a005 2826 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
8978feda
AK
2827 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2828 (s->pb->seekable &&
221e21b7 2829 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
687f35f3 2830 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
221e21b7 2831 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
b72708f8
BC
2832 sample = current_sample;
2833 best_dts = dts;
5dc5c43b 2834 *st = avst;
86d8602f 2835 }
6cea494e 2836 }
6cea494e 2837 }
5dc5c43b
RD
2838 return sample;
2839}
2840
2841static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2842{
2843 MOVContext *mov = s->priv_data;
2844 MOVStreamContext *sc;
2845 AVIndexEntry *sample;
2846 AVStream *st = NULL;
2847 int ret;
2848 retry:
2849 sample = mov_find_next_sample(s, &st);
433aeb62
BC
2850 if (!sample) {
2851 mov->found_mdat = 0;
383a3b64
MS
2852 if (!mov->next_root_atom)
2853 return AVERROR_EOF;
2854 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
2855 mov->next_root_atom = 0;
2856 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
66e5b1df 2857 s->pb->eof_reached)
350f2c2c 2858 return AVERROR_EOF;
3583d7cf 2859 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
433aeb62
BC
2860 goto retry;
2861 }
69fc436c 2862 sc = st->priv_data;
b72708f8
BC
2863 /* must be done just before reading, to avoid infinite loop on sample */
2864 sc->current_sample++;
3fe4d5d4
RD
2865
2866 if (st->discard != AVDISCARD_ALL) {
6b4aa5da 2867 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
e1c1b0ff
RD
2868 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2869 sc->ffindex, sample->pos);
bcd5d979 2870 return AVERROR_INVALIDDATA;
e1c1b0ff
RD
2871 }
2872 ret = av_get_packet(sc->pb, pkt, sample->size);
a2f38511
RD
2873 if (ret < 0)
2874 return ret;
2d8591c2
KS
2875 if (sc->has_palette) {
2876 uint8_t *pal;
2877
2878 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2879 if (!pal) {
2880 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2881 } else {
2882 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2883 sc->has_palette = 0;
2884 }
2885 }
e1c1b0ff
RD
2886#if CONFIG_DV_DEMUXER
2887 if (mov->dv_demux && sc->dv_audio_container) {
ab88b25f 2888 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
e1c1b0ff
RD
2889 av_free(pkt->data);
2890 pkt->size = 0;
ab88b25f 2891 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
e1c1b0ff
RD
2892 if (ret < 0)
2893 return ret;
2894 }
312954f0 2895#endif
3fe4d5d4
RD
2896 }
2897
b72708f8
BC
2898 pkt->stream_index = sc->ffindex;
2899 pkt->dts = sample->timestamp;
86f2ae06 2900 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
bbe46bc4 2901 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
b72708f8 2902 /* update ctts context */
a234e38d
BC
2903 sc->ctts_sample++;
2904 if (sc->ctts_index < sc->ctts_count &&
2905 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2906 sc->ctts_index++;
2907 sc->ctts_sample = 0;
b565ea09 2908 }
0c5f76f7
BC
2909 if (sc->wrong_dts)
2910 pkt->dts = AV_NOPTS_VALUE;
b72708f8 2911 } else {
f0f2218d 2912 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
e8430214
HG
2913 st->index_entries[sc->current_sample].timestamp : st->duration;
2914 pkt->duration = next_dts - pkt->dts;
b72708f8 2915 pkt->pts = pkt->dts;
b565ea09 2916 }
3fe4d5d4
RD
2917 if (st->discard == AVDISCARD_ALL)
2918 goto retry;
cc947f04 2919 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
b72708f8 2920 pkt->pos = sample->pos;
dfd2a005 2921 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
29c90869 2922 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
b72708f8
BC
2923 return 0;
2924}
3ffe3793 2925
e26df9eb 2926static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
b72708f8
BC
2927{
2928 MOVStreamContext *sc = st->priv_data;
2929 int sample, time_sample;
2930 int i;
115329f1 2931
b72708f8 2932 sample = av_index_search_timestamp(st, timestamp, flags);
dfd2a005 2933 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
380966a8
JS
2934 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2935 sample = 0;
b72708f8 2936 if (sample < 0) /* not sure what to do */
bcd5d979 2937 return AVERROR_INVALIDDATA;
b72708f8 2938 sc->current_sample = sample;
dfd2a005 2939 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
b72708f8
BC
2940 /* adjust ctts index */
2941 if (sc->ctts_data) {
2942 time_sample = 0;
2943 for (i = 0; i < sc->ctts_count; i++) {
54a5c719
BC
2944 int next = time_sample + sc->ctts_data[i].count;
2945 if (next > sc->current_sample) {
a234e38d
BC
2946 sc->ctts_index = i;
2947 sc->ctts_sample = sc->current_sample - time_sample;
b72708f8 2948 break;
115329f1 2949 }
54a5c719 2950 time_sample = next;
247d56f5 2951 }
247d56f5 2952 }
b72708f8 2953 return sample;
6cea494e
ZK
2954}
2955
961e0ccd 2956static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
baf25c9d 2957{
b72708f8
BC
2958 AVStream *st;
2959 int64_t seek_timestamp, timestamp;
2960 int sample;
2961 int i;
baf25c9d 2962
b72708f8 2963 if (stream_index >= s->nb_streams)
bcd5d979 2964 return AVERROR_INVALIDDATA;
8dc81a45
BC
2965 if (sample_time < 0)
2966 sample_time = 0;
baf25c9d 2967
b72708f8 2968 st = s->streams[stream_index];
e26df9eb 2969 sample = mov_seek_stream(s, st, sample_time, flags);
b72708f8 2970 if (sample < 0)
bcd5d979 2971 return sample;
baf25c9d 2972
b72708f8
BC
2973 /* adjust seek timestamp to found sample timestamp */
2974 seek_timestamp = st->index_entries[sample].timestamp;
baf25c9d 2975
b72708f8
BC
2976 for (i = 0; i < s->nb_streams; i++) {
2977 st = s->streams[i];
3fe4d5d4 2978 if (stream_index == i)
b72708f8 2979 continue;
baf25c9d 2980
b72708f8 2981 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
e26df9eb 2982 mov_seek_stream(s, st, timestamp, flags);
115329f1 2983 }
baf25c9d
GC
2984 return 0;
2985}
baf25c9d 2986
c6610a21 2987AVInputFormat ff_mov_demuxer = {
dfc2c4d9 2988 .name = "mov,mp4,m4a,3gp,3g2,mj2",
0177b7d2 2989 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
dfc2c4d9
AK
2990 .priv_data_size = sizeof(MOVContext),
2991 .read_probe = mov_probe,
2992 .read_header = mov_read_header,
2993 .read_packet = mov_read_packet,
2994 .read_close = mov_read_close,
2995 .read_seek = mov_read_seek,
6cea494e 2996};