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