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