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