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