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