3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * first version by Francois Revol <revol@free.fr>
7 * seek function by Gael Chardon <gael.dev@4now.net>
9 * This file is part of FFmpeg.
11 * FFmpeg is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * FFmpeg is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with FFmpeg; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include "libavutil/attributes.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/intfloat.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/time_internal.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/display.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/aes.h"
42 #include "libavutil/aes_ctr.h"
43 #include "libavutil/sha.h"
44 #include "libavutil/timecode.h"
45 #include "libavcodec/ac3tab.h"
48 #include "avio_internal.h"
51 #include "libavcodec/get_bits.h"
54 #include "replaygain.h"
60 #include "qtpalette.h"
62 /* those functions parse an atom */
63 /* links atom IDs to parse functions */
64 typedef struct MOVParseTableEntry {
66 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
69 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
70 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
72 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
73 unsigned len, const char *key)
77 short current, total = 0;
78 avio_rb16(pb); // unknown
79 current = avio_rb16(pb);
81 total = avio_rb16(pb);
83 snprintf(buf, sizeof(buf), "%d", current);
85 snprintf(buf, sizeof(buf), "%d/%d", current, total);
86 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
87 av_dict_set(&c->fc->metadata, key, buf, 0);
92 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
93 unsigned len, const char *key)
95 /* bypass padding bytes */
100 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
101 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
106 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
107 unsigned len, const char *key)
109 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
110 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
115 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
116 unsigned len, const char *key)
120 avio_r8(pb); // unknown
123 if (genre < 1 || genre > ID3v1_GENRE_MAX)
125 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
126 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
131 static const uint32_t mac_to_unicode[128] = {
132 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
133 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
134 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
135 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
136 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
137 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
138 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
139 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
140 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
141 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
142 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
143 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
144 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
145 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
146 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
147 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
150 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
151 char *dst, int dstlen)
154 char *end = dst+dstlen-1;
157 for (i = 0; i < len; i++) {
158 uint8_t t, c = avio_r8(pb);
159 if (c < 0x80 && p < end)
162 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
168 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
172 MOVStreamContext *sc;
177 case 0xd: id = AV_CODEC_ID_MJPEG; break;
178 case 0xe: id = AV_CODEC_ID_PNG; break;
179 case 0x1b: id = AV_CODEC_ID_BMP; break;
181 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
186 st = avformat_new_stream(c->fc, NULL);
188 return AVERROR(ENOMEM);
189 sc = av_mallocz(sizeof(*sc));
191 return AVERROR(ENOMEM);
194 ret = av_get_packet(pb, &pkt, len);
198 if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
199 if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
200 id = AV_CODEC_ID_PNG;
202 id = AV_CODEC_ID_MJPEG;
206 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
208 st->attached_pic = pkt;
209 st->attached_pic.stream_index = st->index;
210 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
212 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
213 st->codecpar->codec_id = id;
219 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
221 char language[4] = { 0 };
222 char buf[200], place[100];
223 uint16_t langcode = 0;
224 double longitude, latitude, altitude;
225 const char *key = "location";
227 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
228 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
229 return AVERROR_INVALIDDATA;
232 avio_skip(pb, 4); // version+flags
233 langcode = avio_rb16(pb);
234 ff_mov_lang_to_iso639(langcode, language);
237 len -= avio_get_str(pb, len, place, sizeof(place));
239 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
240 return AVERROR_INVALIDDATA;
242 avio_skip(pb, 1); // role
246 av_log(c->fc, AV_LOG_ERROR,
247 "loci too short (%u bytes left, need at least %d)\n", len, 12);
248 return AVERROR_INVALIDDATA;
250 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
251 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
252 altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
254 // Try to output in the same format as the ?xyz field
255 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
257 av_strlcatf(buf, sizeof(buf), "%+f", altitude);
258 av_strlcatf(buf, sizeof(buf), "/%s", place);
260 if (*language && strcmp(language, "und")) {
262 snprintf(key2, sizeof(key2), "%s-%s", key, language);
263 av_dict_set(&c->fc->metadata, key2, buf, 0);
265 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
266 return av_dict_set(&c->fc->metadata, key, buf, 0);
269 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
272 char key2[32], language[4] = {0};
274 const char *key = NULL;
275 uint16_t langcode = 0;
276 uint32_t data_type = 0, str_size, str_size_alloc;
277 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
282 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
283 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
284 case MKTAG( 'X','M','P','_'):
285 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
286 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
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;
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;
297 case MKTAG( 'e','g','i','d'): key = "episode_uid";
298 parse = mov_metadata_int8_no_padding; break;
299 case MKTAG( 'g','n','r','e'): key = "genre";
300 parse = mov_metadata_gnre; break;
301 case MKTAG( 'h','d','v','d'): key = "hd_video";
302 parse = mov_metadata_int8_no_padding; break;
303 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
304 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
305 case MKTAG( 'l','o','c','i'):
306 return mov_metadata_loci(c, pb, atom.size);
307 case MKTAG( 'p','c','s','t'): key = "podcast";
308 parse = mov_metadata_int8_no_padding; break;
309 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
310 parse = mov_metadata_int8_no_padding; break;
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;
320 case MKTAG( 's','t','i','k'): key = "media_type";
321 parse = mov_metadata_int8_no_padding; break;
322 case MKTAG( 't','r','k','n'): key = "track";
323 parse = mov_metadata_track_or_disc_number; break;
324 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
325 case MKTAG( 't','v','e','s'): key = "episode_sort";
326 parse = mov_metadata_int8_bypass_padding; break;
327 case MKTAG( 't','v','n','n'): key = "network"; break;
328 case MKTAG( 't','v','s','h'): key = "show"; break;
329 case MKTAG( 't','v','s','n'): key = "season_number";
330 parse = mov_metadata_int8_bypass_padding; break;
331 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
332 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
333 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
334 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
335 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
336 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
337 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
338 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
339 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
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;
343 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
344 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
345 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
346 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
347 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
348 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
349 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
350 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
351 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
352 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
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;
358 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
359 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
360 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
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;
364 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
365 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
368 if (c->itunes_metadata && atom.size > 8) {
369 int data_size = avio_rb32(pb);
370 int tag = avio_rl32(pb);
371 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
372 data_type = avio_rb32(pb); // type
373 avio_rb32(pb); // unknown
374 str_size = data_size - 16;
377 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
378 int ret = mov_read_covr(c, pb, data_type, str_size);
380 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
383 } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
384 uint32_t index = AV_RB32(&atom.type);
385 if (index < c->meta_keys_count) {
386 key = c->meta_keys[index];
388 av_log(c->fc, AV_LOG_WARNING,
389 "The index of 'data' is out of range: %d >= %d.\n",
390 index, c->meta_keys_count);
394 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
395 str_size = avio_rb16(pb); // string length
396 if (str_size > atom.size) {
398 avio_seek(pb, -2, SEEK_CUR);
399 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
402 langcode = avio_rb16(pb);
403 ff_mov_lang_to_iso639(langcode, language);
406 str_size = atom.size;
408 if (c->export_all && !key) {
409 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
415 if (atom.size < 0 || str_size >= INT_MAX/2)
416 return AVERROR_INVALIDDATA;
418 // Allocates enough space if data_type is a int32 or float32 number, otherwise
419 // worst-case requirement for output string in case of utf8 coded input
420 num = (data_type >= 21 && data_type <= 23);
421 str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
422 str = av_mallocz(str_size_alloc);
424 return AVERROR(ENOMEM);
427 parse(c, pb, str_size, key);
429 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
430 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
431 } else if (data_type == 21) { // BE signed integer, variable size
434 val = (int8_t)avio_r8(pb);
435 else if (str_size == 2)
436 val = (int16_t)avio_rb16(pb);
437 else if (str_size == 3)
438 val = ((int32_t)(avio_rb24(pb)<<8))>>8;
439 else if (str_size == 4)
440 val = (int32_t)avio_rb32(pb);
441 if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
442 av_log(c->fc, AV_LOG_ERROR,
443 "Failed to store the number (%d) in string.\n", val);
445 return AVERROR_INVALIDDATA;
447 } else if (data_type == 22) { // BE unsigned integer, variable size
448 unsigned int val = 0;
451 else if (str_size == 2)
453 else if (str_size == 3)
455 else if (str_size == 4)
457 if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
458 av_log(c->fc, AV_LOG_ERROR,
459 "Failed to store the number (%u) in string.\n", val);
461 return AVERROR_INVALIDDATA;
463 } else if (data_type == 23 && str_size >= 4) { // BE float32
464 float val = av_int2float(avio_rb32(pb));
465 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
466 av_log(c->fc, AV_LOG_ERROR,
467 "Failed to store the float32 number (%f) in string.\n", val);
469 return AVERROR_INVALIDDATA;
472 int ret = ffio_read_size(pb, str, str_size);
479 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
480 av_dict_set(&c->fc->metadata, key, str, 0);
481 if (*language && strcmp(language, "und")) {
482 snprintf(key2, sizeof(key2), "%s-%s", key, language);
483 av_dict_set(&c->fc->metadata, key2, str, 0);
485 if (!strcmp(key, "encoder")) {
486 int major, minor, micro;
487 if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, µ) == 3) {
488 c->handbrake_version = 1000000*major + 1000*minor + micro;
492 av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
493 av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
494 key, str, (char*)&atom.type, str_size_alloc, atom.size);
500 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
503 int i, nb_chapters, str_len, version;
507 if (c->ignore_chapters)
510 if ((atom.size -= 5) < 0)
513 version = avio_r8(pb);
516 avio_rb32(pb); // ???
517 nb_chapters = avio_r8(pb);
519 for (i = 0; i < nb_chapters; i++) {
523 start = avio_rb64(pb);
524 str_len = avio_r8(pb);
526 if ((atom.size -= 9+str_len) < 0)
529 ret = ffio_read_size(pb, str, str_len);
533 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
538 #define MIN_DATA_ENTRY_BOX_SIZE 12
539 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
542 MOVStreamContext *sc;
545 if (c->fc->nb_streams < 1)
547 st = c->fc->streams[c->fc->nb_streams-1];
550 avio_rb32(pb); // version + flags
551 entries = avio_rb32(pb);
553 entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
554 entries >= UINT_MAX / sizeof(*sc->drefs))
555 return AVERROR_INVALIDDATA;
559 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
561 return AVERROR(ENOMEM);
562 sc->drefs_count = entries;
564 for (i = 0; i < entries; i++) {
565 MOVDref *dref = &sc->drefs[i];
566 uint32_t size = avio_rb32(pb);
567 int64_t next = avio_tell(pb) + size - 4;
570 return AVERROR_INVALIDDATA;
572 dref->type = avio_rl32(pb);
573 avio_rb32(pb); // version + flags
574 av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
576 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
577 /* macintosh alias record */
578 uint16_t volume_len, len;
584 volume_len = avio_r8(pb);
585 volume_len = FFMIN(volume_len, 27);
586 ret = ffio_read_size(pb, dref->volume, 27);
589 dref->volume[volume_len] = 0;
590 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
595 len = FFMIN(len, 63);
596 ret = ffio_read_size(pb, dref->filename, 63);
599 dref->filename[len] = 0;
600 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
604 /* read next level up_from_alias/down_to_target */
605 dref->nlvl_from = avio_rb16(pb);
606 dref->nlvl_to = avio_rb16(pb);
607 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
608 dref->nlvl_from, dref->nlvl_to);
612 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
615 type = avio_rb16(pb);
617 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
620 if (type == 2) { // absolute path
622 dref->path = av_mallocz(len+1);
624 return AVERROR(ENOMEM);
626 ret = ffio_read_size(pb, dref->path, len);
628 av_freep(&dref->path);
631 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
633 memmove(dref->path, dref->path+volume_len, len);
636 // trim string of any ending zeros
637 for (j = len - 1; j >= 0; j--) {
638 if (dref->path[j] == 0)
643 for (j = 0; j < len; j++)
644 if (dref->path[j] == ':' || dref->path[j] == 0)
646 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
647 } else if (type == 0) { // directory name
649 dref->dir = av_malloc(len+1);
651 return AVERROR(ENOMEM);
653 ret = ffio_read_size(pb, dref->dir, len);
655 av_freep(&dref->dir);
659 for (j = 0; j < len; j++)
660 if (dref->dir[j] == ':')
662 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
667 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x08%x size %d\n",
672 avio_seek(pb, next, SEEK_SET);
677 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
681 uint32_t av_unused ctype;
686 avio_r8(pb); /* version */
687 avio_rb24(pb); /* flags */
690 ctype = avio_rl32(pb);
691 type = avio_rl32(pb); /* component subtype */
693 av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
694 av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
696 if (c->trak_index < 0) { // meta not inside a trak
697 if (type == MKTAG('m','d','t','a')) {
698 c->found_hdlr_mdta = 1;
703 st = c->fc->streams[c->fc->nb_streams-1];
705 if (type == MKTAG('v','i','d','e'))
706 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
707 else if (type == MKTAG('s','o','u','n'))
708 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
709 else if (type == MKTAG('m','1','a',' '))
710 st->codecpar->codec_id = AV_CODEC_ID_MP2;
711 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
712 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
714 avio_rb32(pb); /* component manufacture */
715 avio_rb32(pb); /* component flags */
716 avio_rb32(pb); /* component flags mask */
718 title_size = atom.size - 24;
719 if (title_size > 0) {
720 title_str = av_malloc(title_size + 1); /* Add null terminator */
722 return AVERROR(ENOMEM);
724 ret = ffio_read_size(pb, title_str, title_size);
726 av_freep(&title_str);
729 title_str[title_size] = 0;
731 int off = (!c->isom && title_str[0] == title_size - 1);
732 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
734 av_freep(&title_str);
740 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
745 if (fc->nb_streams < 1)
747 st = fc->streams[fc->nb_streams-1];
749 avio_rb32(pb); /* version + flags */
750 ff_mp4_read_descr(fc, pb, &tag);
751 if (tag == MP4ESDescrTag) {
752 ff_mp4_parse_es_descr(pb, NULL);
754 avio_rb16(pb); /* ID */
756 ff_mp4_read_descr(fc, pb, &tag);
757 if (tag == MP4DecConfigDescrTag)
758 ff_mp4_read_dec_config_descr(fc, st, pb);
762 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
764 return ff_mov_read_esds(c->fc, pb);
767 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
770 enum AVAudioServiceType *ast;
771 int ac3info, acmod, lfeon, bsmod;
773 if (c->fc->nb_streams < 1)
775 st = c->fc->streams[c->fc->nb_streams-1];
777 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
780 return AVERROR(ENOMEM);
782 ac3info = avio_rb24(pb);
783 bsmod = (ac3info >> 14) & 0x7;
784 acmod = (ac3info >> 11) & 0x7;
785 lfeon = (ac3info >> 10) & 0x1;
786 st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
787 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
789 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
791 if (st->codecpar->channels > 1 && bsmod == 0x7)
792 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
794 #if FF_API_LAVF_AVCTX
795 FF_DISABLE_DEPRECATION_WARNINGS
796 st->codec->audio_service_type = *ast;
797 FF_ENABLE_DEPRECATION_WARNINGS
803 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
806 enum AVAudioServiceType *ast;
807 int eac3info, acmod, lfeon, bsmod;
809 if (c->fc->nb_streams < 1)
811 st = c->fc->streams[c->fc->nb_streams-1];
813 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
816 return AVERROR(ENOMEM);
818 /* No need to parse fields for additional independent substreams and its
819 * associated dependent substreams since libavcodec's E-AC-3 decoder
820 * does not support them yet. */
821 avio_rb16(pb); /* data_rate and num_ind_sub */
822 eac3info = avio_rb24(pb);
823 bsmod = (eac3info >> 12) & 0x1f;
824 acmod = (eac3info >> 9) & 0x7;
825 lfeon = (eac3info >> 8) & 0x1;
826 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
828 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
829 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
831 if (st->codecpar->channels > 1 && bsmod == 0x7)
832 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
834 #if FF_API_LAVF_AVCTX
835 FF_DISABLE_DEPRECATION_WARNINGS
836 st->codec->audio_service_type = *ast;
837 FF_ENABLE_DEPRECATION_WARNINGS
843 static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
845 const uint32_t ddts_size = 20;
848 uint32_t frame_duration_code = 0;
849 uint32_t channel_layout_code = 0;
852 buf = av_malloc(ddts_size + FF_INPUT_BUFFER_PADDING_SIZE);
854 return AVERROR(ENOMEM);
856 if (avio_read(pb, buf, ddts_size) < ddts_size) {
858 return AVERROR_INVALIDDATA;
861 init_get_bits(&gb, buf, 8*ddts_size);
863 if (c->fc->nb_streams < 1) {
866 st = c->fc->streams[c->fc->nb_streams-1];
868 st->codecpar->sample_rate = get_bits_long(&gb, 32);
869 skip_bits_long(&gb, 32); /* max bitrate */
870 st->codecpar->bit_rate = get_bits_long(&gb, 32);
871 st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
872 frame_duration_code = get_bits(&gb, 2);
873 skip_bits(&gb, 30); /* various fields */
874 channel_layout_code = get_bits(&gb, 16);
876 st->codecpar->frame_size =
877 (frame_duration_code == 0) ? 512 :
878 (frame_duration_code == 1) ? 1024 :
879 (frame_duration_code == 2) ? 2048 :
880 (frame_duration_code == 3) ? 4096 : 0;
882 if (channel_layout_code > 0xff) {
883 av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
885 st->codecpar->channel_layout =
886 ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
887 ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
888 ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
889 ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
890 ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
891 ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
893 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
898 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
902 if (c->fc->nb_streams < 1)
904 st = c->fc->streams[c->fc->nb_streams-1];
909 /* skip version and flags */
912 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
917 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
922 if (c->fc->nb_streams < 1)
924 st = c->fc->streams[c->fc->nb_streams-1];
926 if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
927 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
932 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
934 const int num = avio_rb32(pb);
935 const int den = avio_rb32(pb);
938 if (c->fc->nb_streams < 1)
940 st = c->fc->streams[c->fc->nb_streams-1];
942 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
943 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
944 av_log(c->fc, AV_LOG_WARNING,
945 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
946 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
948 } else if (den != 0) {
949 av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
955 /* this atom contains actual media data */
956 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
958 if (atom.size == 0) /* wrong one (MP4) */
961 return 0; /* now go for moov */
964 #define DRM_BLOB_SIZE 56
966 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
968 uint8_t intermediate_key[20];
969 uint8_t intermediate_iv[20];
972 uint8_t file_checksum[20];
973 uint8_t calculated_checksum[20];
977 uint8_t *activation_bytes = c->activation_bytes;
978 uint8_t *fixed_key = c->audible_fixed_key;
982 sha = av_sha_alloc();
984 return AVERROR(ENOMEM);
985 c->aes_decrypt = av_aes_alloc();
986 if (!c->aes_decrypt) {
987 ret = AVERROR(ENOMEM);
991 /* drm blob processing */
992 avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
993 avio_read(pb, input, DRM_BLOB_SIZE);
994 avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
995 avio_read(pb, file_checksum, 20);
997 av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
998 for (i = 0; i < 20; i++)
999 av_log(sha, AV_LOG_INFO, "%02x", file_checksum[i]);
1000 av_log(c->fc, AV_LOG_INFO, "\n");
1002 /* verify activation data */
1003 if (!activation_bytes) {
1004 av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
1005 ret = 0; /* allow ffprobe to continue working on .aax files */
1008 if (c->activation_bytes_size != 4) {
1009 av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
1010 ret = AVERROR(EINVAL);
1014 /* verify fixed key */
1015 if (c->audible_fixed_key_size != 16) {
1016 av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
1017 ret = AVERROR(EINVAL);
1021 /* AAX (and AAX+) key derivation */
1022 av_sha_init(sha, 160);
1023 av_sha_update(sha, fixed_key, 16);
1024 av_sha_update(sha, activation_bytes, 4);
1025 av_sha_final(sha, intermediate_key);
1026 av_sha_init(sha, 160);
1027 av_sha_update(sha, fixed_key, 16);
1028 av_sha_update(sha, intermediate_key, 20);
1029 av_sha_update(sha, activation_bytes, 4);
1030 av_sha_final(sha, intermediate_iv);
1031 av_sha_init(sha, 160);
1032 av_sha_update(sha, intermediate_key, 16);
1033 av_sha_update(sha, intermediate_iv, 16);
1034 av_sha_final(sha, calculated_checksum);
1035 if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
1036 av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
1037 ret = AVERROR_INVALIDDATA;
1040 av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
1041 av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
1042 for (i = 0; i < 4; i++) {
1043 // file data (in output) is stored in big-endian mode
1044 if (activation_bytes[i] != output[3 - i]) { // critical error
1045 av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
1046 ret = AVERROR_INVALIDDATA;
1050 memcpy(c->file_key, output + 8, 16);
1051 memcpy(input, output + 26, 16);
1052 av_sha_init(sha, 160);
1053 av_sha_update(sha, input, 16);
1054 av_sha_update(sha, c->file_key, 16);
1055 av_sha_update(sha, fixed_key, 16);
1056 av_sha_final(sha, c->file_iv);
1064 // Audible AAX (and AAX+) bytestream decryption
1065 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1068 unsigned char iv[16];
1070 memcpy(iv, c->file_iv, 16); // iv is overwritten
1071 blocks = size >> 4; // trailing bytes are not encrypted!
1072 av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1073 av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1078 /* read major brand, minor version and compatible brands and store them as metadata */
1079 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1082 int comp_brand_size;
1083 char* comp_brands_str;
1084 uint8_t type[5] = {0};
1085 int ret = ffio_read_size(pb, type, 4);
1089 if (strcmp(type, "qt "))
1091 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1092 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1093 minor_ver = avio_rb32(pb); /* minor version */
1094 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1096 comp_brand_size = atom.size - 8;
1097 if (comp_brand_size < 0)
1098 return AVERROR_INVALIDDATA;
1099 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1100 if (!comp_brands_str)
1101 return AVERROR(ENOMEM);
1103 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1105 av_freep(&comp_brands_str);
1108 comp_brands_str[comp_brand_size] = 0;
1109 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1110 av_freep(&comp_brands_str);
1115 /* this atom should contain all header atoms */
1116 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1120 if (c->found_moov) {
1121 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1122 avio_skip(pb, atom.size);
1126 if ((ret = mov_read_default(c, pb, atom)) < 0)
1128 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1129 /* so we don't parse the whole file if over a network */
1131 return 0; /* now go for mdat */
1134 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1136 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1137 c->has_looked_for_mfra = 1;
1140 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1142 if ((ret = mov_read_mfra(c, pb)) < 0) {
1143 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1144 "read the mfra (may be a live ismv)\n");
1147 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1148 "seekable, can not look for mfra\n");
1151 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
1152 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1153 return mov_read_default(c, pb, atom);
1156 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1160 struct tm *ptm, tmbuf;
1162 if(time >= 2082844800)
1163 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1165 ptm = gmtime_r(&timet, &tmbuf);
1167 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
1168 av_dict_set(metadata, "creation_time", buffer, 0);
1172 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1175 MOVStreamContext *sc;
1177 char language[4] = {0};
1179 int64_t creation_time;
1181 if (c->fc->nb_streams < 1)
1183 st = c->fc->streams[c->fc->nb_streams-1];
1186 if (sc->time_scale) {
1187 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1188 return AVERROR_INVALIDDATA;
1191 version = avio_r8(pb);
1193 avpriv_request_sample(c->fc, "Version %d", version);
1194 return AVERROR_PATCHWELCOME;
1196 avio_rb24(pb); /* flags */
1198 creation_time = avio_rb64(pb);
1201 creation_time = avio_rb32(pb);
1202 avio_rb32(pb); /* modification time */
1204 mov_metadata_creation_time(&st->metadata, creation_time);
1206 sc->time_scale = avio_rb32(pb);
1207 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1209 lang = avio_rb16(pb); /* language */
1210 if (ff_mov_lang_to_iso639(lang, language))
1211 av_dict_set(&st->metadata, "language", language, 0);
1212 avio_rb16(pb); /* quality */
1217 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1219 int64_t creation_time;
1220 int version = avio_r8(pb); /* version */
1221 avio_rb24(pb); /* flags */
1224 creation_time = avio_rb64(pb);
1227 creation_time = avio_rb32(pb);
1228 avio_rb32(pb); /* modification time */
1230 mov_metadata_creation_time(&c->fc->metadata, creation_time);
1231 c->time_scale = avio_rb32(pb); /* time scale */
1233 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1235 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1236 // set the AVCodecContext duration because the duration of individual tracks
1237 // may be inaccurate
1238 if (c->time_scale > 0 && !c->trex_data)
1239 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1240 avio_rb32(pb); /* preferred scale */
1242 avio_rb16(pb); /* preferred volume */
1244 avio_skip(pb, 10); /* reserved */
1246 avio_skip(pb, 36); /* display matrix */
1248 avio_rb32(pb); /* preview time */
1249 avio_rb32(pb); /* preview duration */
1250 avio_rb32(pb); /* poster time */
1251 avio_rb32(pb); /* selection time */
1252 avio_rb32(pb); /* selection duration */
1253 avio_rb32(pb); /* current time */
1254 avio_rb32(pb); /* next track ID */
1259 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1264 if (c->fc->nb_streams < 1)
1266 st = c->fc->streams[c->fc->nb_streams-1];
1268 little_endian = avio_rb16(pb) & 0xFF;
1269 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1270 if (little_endian == 1) {
1271 switch (st->codecpar->codec_id) {
1272 case AV_CODEC_ID_PCM_S24BE:
1273 st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
1275 case AV_CODEC_ID_PCM_S32BE:
1276 st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
1278 case AV_CODEC_ID_PCM_F32BE:
1279 st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
1281 case AV_CODEC_ID_PCM_F64BE:
1282 st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
1291 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1294 char color_parameter_type[5] = { 0 };
1295 uint16_t color_primaries, color_trc, color_matrix;
1298 if (c->fc->nb_streams < 1)
1300 st = c->fc->streams[c->fc->nb_streams - 1];
1302 ret = ffio_read_size(pb, color_parameter_type, 4);
1305 if (strncmp(color_parameter_type, "nclx", 4) &&
1306 strncmp(color_parameter_type, "nclc", 4)) {
1307 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1308 color_parameter_type);
1312 color_primaries = avio_rb16(pb);
1313 color_trc = avio_rb16(pb);
1314 color_matrix = avio_rb16(pb);
1316 av_log(c->fc, AV_LOG_TRACE,
1317 "%s: pri %d trc %d matrix %d",
1318 color_parameter_type, color_primaries, color_trc, color_matrix);
1320 if (!strncmp(color_parameter_type, "nclx", 4)) {
1321 uint8_t color_range = avio_r8(pb) >> 7;
1322 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1324 st->codecpar->color_range = AVCOL_RANGE_JPEG;
1326 st->codecpar->color_range = AVCOL_RANGE_MPEG;
1327 /* 14496-12 references JPEG XR specs (rather than the more complete
1328 * 23001-8) so some adjusting is required */
1329 if (color_primaries >= AVCOL_PRI_FILM)
1330 color_primaries = AVCOL_PRI_UNSPECIFIED;
1331 if ((color_trc >= AVCOL_TRC_LINEAR &&
1332 color_trc <= AVCOL_TRC_LOG_SQRT) ||
1333 color_trc >= AVCOL_TRC_BT2020_10)
1334 color_trc = AVCOL_TRC_UNSPECIFIED;
1335 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
1336 color_matrix = AVCOL_SPC_UNSPECIFIED;
1337 st->codecpar->color_primaries = color_primaries;
1338 st->codecpar->color_trc = color_trc;
1339 st->codecpar->color_space = color_matrix;
1340 } else if (!strncmp(color_parameter_type, "nclc", 4)) {
1341 /* color primaries, Table 4-4 */
1342 switch (color_primaries) {
1343 case 1: st->codecpar->color_primaries = AVCOL_PRI_BT709; break;
1344 case 5: st->codecpar->color_primaries = AVCOL_PRI_SMPTE170M; break;
1345 case 6: st->codecpar->color_primaries = AVCOL_PRI_SMPTE240M; break;
1347 /* color transfer, Table 4-5 */
1348 switch (color_trc) {
1349 case 1: st->codecpar->color_trc = AVCOL_TRC_BT709; break;
1350 case 7: st->codecpar->color_trc = AVCOL_TRC_SMPTE240M; break;
1352 /* color matrix, Table 4-6 */
1353 switch (color_matrix) {
1354 case 1: st->codecpar->color_space = AVCOL_SPC_BT709; break;
1355 case 6: st->codecpar->color_space = AVCOL_SPC_BT470BG; break;
1356 case 7: st->codecpar->color_space = AVCOL_SPC_SMPTE240M; break;
1359 av_log(c->fc, AV_LOG_TRACE, "\n");
1364 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1367 unsigned mov_field_order;
1368 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1370 if (c->fc->nb_streams < 1) // will happen with jp2 files
1372 st = c->fc->streams[c->fc->nb_streams-1];
1374 return AVERROR_INVALIDDATA;
1375 mov_field_order = avio_rb16(pb);
1376 if ((mov_field_order & 0xFF00) == 0x0100)
1377 decoded_field_order = AV_FIELD_PROGRESSIVE;
1378 else if ((mov_field_order & 0xFF00) == 0x0200) {
1379 switch (mov_field_order & 0xFF) {
1380 case 0x01: decoded_field_order = AV_FIELD_TT;
1382 case 0x06: decoded_field_order = AV_FIELD_BB;
1384 case 0x09: decoded_field_order = AV_FIELD_TB;
1386 case 0x0E: decoded_field_order = AV_FIELD_BT;
1390 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1391 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1393 st->codecpar->field_order = decoded_field_order;
1398 static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
1401 uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1402 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1403 return AVERROR_INVALIDDATA;
1404 if ((err = av_reallocp(&par->extradata, size)) < 0) {
1405 par->extradata_size = 0;
1408 par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1412 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1413 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1414 AVCodecParameters *par, uint8_t *buf)
1416 int64_t result = atom.size;
1419 AV_WB32(buf , atom.size + 8);
1420 AV_WL32(buf + 4, atom.type);
1421 err = ffio_read_size(pb, buf + 8, atom.size);
1423 par->extradata_size -= atom.size;
1425 } else if (err < atom.size) {
1426 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1427 par->extradata_size -= atom.size - err;
1430 memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1434 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1435 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1436 enum AVCodecID codec_id)
1439 uint64_t original_size;
1442 if (c->fc->nb_streams < 1) // will happen with jp2 files
1444 st = c->fc->streams[c->fc->nb_streams-1];
1446 if (st->codecpar->codec_id != codec_id)
1447 return 0; /* unexpected codec_id - don't mess with extradata */
1449 original_size = st->codecpar->extradata_size;
1450 err = mov_realloc_extradata(st->codecpar, atom);
1454 err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
1457 return 0; // Note: this is the original behavior to ignore truncation.
1460 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1461 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1463 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1466 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1468 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1471 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1473 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1476 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1478 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1481 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1483 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1485 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1489 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1491 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1493 if (!ret && c->fc->nb_streams >= 1) {
1494 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1495 if (par->extradata_size >= 40) {
1496 par->height = AV_RB16(&par->extradata[36]);
1497 par->width = AV_RB16(&par->extradata[38]);
1503 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1505 if (c->fc->nb_streams >= 1) {
1506 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1507 if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1508 par->codec_id == AV_CODEC_ID_H264 &&
1512 cid = avio_rb16(pb);
1513 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1514 if (cid == 0xd4d || cid == 0xd4e)
1517 } else if (par->codec_tag == MKTAG('A', 'V', 'd', '1') &&
1521 num = avio_rb32(pb);
1522 den = avio_rb32(pb);
1523 if (num <= 0 || den <= 0)
1525 switch (avio_rb32(pb)) {
1527 if (den >= INT_MAX / 2)
1531 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1532 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1539 return mov_read_avid(c, pb, atom);
1542 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1546 uint64_t original_size;
1547 if (c->fc->nb_streams >= 1) {
1548 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1549 if (par->codec_id == AV_CODEC_ID_H264)
1551 if (atom.size == 16) {
1552 original_size = par->extradata_size;
1553 ret = mov_realloc_extradata(par, atom);
1555 length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
1556 if (length == atom.size) {
1557 const uint8_t range_value = par->extradata[original_size + 19];
1558 switch (range_value) {
1560 par->color_range = AVCOL_RANGE_MPEG;
1563 par->color_range = AVCOL_RANGE_JPEG;
1566 av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1569 ff_dlog(c, "color_range: %d\n", par->color_range);
1571 /* For some reason the whole atom was not added to the extradata */
1572 av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1575 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1578 av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1585 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1587 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1590 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1595 if (c->fc->nb_streams < 1)
1597 st = c->fc->streams[c->fc->nb_streams-1];
1599 if ((uint64_t)atom.size > (1<<30))
1600 return AVERROR_INVALIDDATA;
1602 if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
1603 st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
1604 st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
1605 // pass all frma atom to codec, needed at least for QDMC and QDM2
1606 av_freep(&st->codecpar->extradata);
1607 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1610 } else if (atom.size > 8) { /* to read frma, esds atoms */
1611 if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1613 ret = ffio_ensure_seekback(pb, 8);
1616 buffer = avio_rb64(pb);
1618 if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1619 && buffer >> 32 <= atom.size
1620 && buffer >> 32 >= 8) {
1623 } else if (!st->codecpar->extradata_size) {
1624 #define ALAC_EXTRADATA_SIZE 36
1625 st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1626 if (!st->codecpar->extradata)
1627 return AVERROR(ENOMEM);
1628 st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
1629 AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE);
1630 AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
1631 AV_WB64(st->codecpar->extradata + 12, buffer);
1632 avio_read(pb, st->codecpar->extradata + 20, 16);
1633 avio_skip(pb, atom.size - 24);
1637 if ((ret = mov_read_default(c, pb, atom)) < 0)
1640 avio_skip(pb, atom.size);
1645 * This function reads atom content and puts data in extradata without tag
1646 * nor size unlike mov_read_extradata.
1648 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1653 if (c->fc->nb_streams < 1)
1655 st = c->fc->streams[c->fc->nb_streams-1];
1657 if ((uint64_t)atom.size > (1<<30))
1658 return AVERROR_INVALIDDATA;
1660 if (atom.size >= 10) {
1661 // Broken files created by legacy versions of libavformat will
1662 // wrap a whole fiel atom inside of a glbl atom.
1663 unsigned size = avio_rb32(pb);
1664 unsigned type = avio_rl32(pb);
1665 avio_seek(pb, -8, SEEK_CUR);
1666 if (type == MKTAG('f','i','e','l') && size == atom.size)
1667 return mov_read_default(c, pb, atom);
1669 if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
1670 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1673 av_freep(&st->codecpar->extradata);
1674 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1681 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1684 uint8_t profile_level;
1687 if (c->fc->nb_streams < 1)
1689 st = c->fc->streams[c->fc->nb_streams-1];
1691 if (atom.size >= (1<<28) || atom.size < 7)
1692 return AVERROR_INVALIDDATA;
1694 profile_level = avio_r8(pb);
1695 if ((profile_level & 0xf0) != 0xc0)
1698 avio_seek(pb, 6, SEEK_CUR);
1699 av_freep(&st->codecpar->extradata);
1700 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
1708 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1709 * but can have extradata appended at the end after the 40 bytes belonging
1712 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1717 if (c->fc->nb_streams < 1)
1719 if (atom.size <= 40)
1721 st = c->fc->streams[c->fc->nb_streams-1];
1723 if ((uint64_t)atom.size > (1<<30))
1724 return AVERROR_INVALIDDATA;
1727 av_freep(&st->codecpar->extradata);
1728 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
1735 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1738 MOVStreamContext *sc;
1739 unsigned int i, entries;
1741 if (c->fc->nb_streams < 1)
1743 st = c->fc->streams[c->fc->nb_streams-1];
1746 avio_r8(pb); /* version */
1747 avio_rb24(pb); /* flags */
1749 entries = avio_rb32(pb);
1754 if (sc->chunk_offsets)
1755 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1756 av_free(sc->chunk_offsets);
1757 sc->chunk_count = 0;
1758 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1759 if (!sc->chunk_offsets)
1760 return AVERROR(ENOMEM);
1761 sc->chunk_count = entries;
1763 if (atom.type == MKTAG('s','t','c','o'))
1764 for (i = 0; i < entries && !pb->eof_reached; i++)
1765 sc->chunk_offsets[i] = avio_rb32(pb);
1766 else if (atom.type == MKTAG('c','o','6','4'))
1767 for (i = 0; i < entries && !pb->eof_reached; i++)
1768 sc->chunk_offsets[i] = avio_rb64(pb);
1770 return AVERROR_INVALIDDATA;
1772 sc->chunk_count = i;
1774 if (pb->eof_reached)
1781 * Compute codec id for 'lpcm' tag.
1782 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1784 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1791 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1794 static int mov_codec_id(AVStream *st, uint32_t format)
1796 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1799 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1800 (format & 0xFFFF) == 'T' + ('S' << 8)))
1801 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1803 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1804 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1805 } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
1806 /* skip old ASF MPEG-4 tag */
1807 format && format != MKTAG('m','p','4','s')) {
1808 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1810 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1812 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
1813 else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
1814 (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1815 st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
1816 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1818 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
1822 st->codecpar->codec_tag = format;
1827 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1828 AVStream *st, MOVStreamContext *sc)
1830 uint8_t codec_name[32];
1834 /* The first 16 bytes of the video sample description are already
1835 * read in ff_mov_read_stsd_entries() */
1836 stsd_start = avio_tell(pb) - 16;
1838 avio_rb16(pb); /* version */
1839 avio_rb16(pb); /* revision level */
1840 avio_rb32(pb); /* vendor */
1841 avio_rb32(pb); /* temporal quality */
1842 avio_rb32(pb); /* spatial quality */
1844 st->codecpar->width = avio_rb16(pb); /* width */
1845 st->codecpar->height = avio_rb16(pb); /* height */
1847 avio_rb32(pb); /* horiz resolution */
1848 avio_rb32(pb); /* vert resolution */
1849 avio_rb32(pb); /* data size, always 0 */
1850 avio_rb16(pb); /* frames per samples */
1852 len = avio_r8(pb); /* codec name, pascal string */
1855 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1857 avio_skip(pb, 31 - len);
1860 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1862 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1863 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1864 st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
1865 st->codecpar->width &= ~1;
1866 st->codecpar->height &= ~1;
1868 /* Flash Media Server uses tag H.263 with Sorenson Spark */
1869 if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
1870 !memcmp(codec_name, "Sorenson H263", 13))
1871 st->codecpar->codec_id = AV_CODEC_ID_FLV1;
1873 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
1875 avio_seek(pb, stsd_start, SEEK_SET);
1877 if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
1878 st->codecpar->bits_per_coded_sample &= 0x1F;
1879 sc->has_palette = 1;
1883 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1884 AVStream *st, MOVStreamContext *sc)
1886 int bits_per_sample, flags;
1887 uint16_t version = avio_rb16(pb);
1888 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1890 avio_rb16(pb); /* revision level */
1891 avio_rb32(pb); /* vendor */
1893 st->codecpar->channels = avio_rb16(pb); /* channel count */
1894 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1895 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
1897 sc->audio_cid = avio_rb16(pb);
1898 avio_rb16(pb); /* packet size = 0 */
1900 st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
1902 // Read QT version 1 fields. In version 0 these do not exist.
1903 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1905 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1908 sc->samples_per_frame = avio_rb32(pb);
1909 avio_rb32(pb); /* bytes per packet */
1910 sc->bytes_per_frame = avio_rb32(pb);
1911 avio_rb32(pb); /* bytes per sample */
1912 } else if (version == 2) {
1913 avio_rb32(pb); /* sizeof struct only */
1914 st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
1915 st->codecpar->channels = avio_rb32(pb);
1916 avio_rb32(pb); /* always 0x7F000000 */
1917 st->codecpar->bits_per_coded_sample = avio_rb32(pb);
1919 flags = avio_rb32(pb); /* lpcm format specific flag */
1920 sc->bytes_per_frame = avio_rb32(pb);
1921 sc->samples_per_frame = avio_rb32(pb);
1922 if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
1923 st->codecpar->codec_id =
1924 ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
1927 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1928 /* can't correctly handle variable sized packet as audio unit */
1929 switch (st->codecpar->codec_id) {
1930 case AV_CODEC_ID_MP2:
1931 case AV_CODEC_ID_MP3:
1932 st->need_parsing = AVSTREAM_PARSE_FULL;
1938 if (sc->format == 0) {
1939 if (st->codecpar->bits_per_coded_sample == 8)
1940 st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
1941 else if (st->codecpar->bits_per_coded_sample == 16)
1942 st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
1945 switch (st->codecpar->codec_id) {
1946 case AV_CODEC_ID_PCM_S8:
1947 case AV_CODEC_ID_PCM_U8:
1948 if (st->codecpar->bits_per_coded_sample == 16)
1949 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
1951 case AV_CODEC_ID_PCM_S16LE:
1952 case AV_CODEC_ID_PCM_S16BE:
1953 if (st->codecpar->bits_per_coded_sample == 8)
1954 st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
1955 else if (st->codecpar->bits_per_coded_sample == 24)
1956 st->codecpar->codec_id =
1957 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
1958 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1959 else if (st->codecpar->bits_per_coded_sample == 32)
1960 st->codecpar->codec_id =
1961 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
1962 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1964 /* set values for old format before stsd version 1 appeared */
1965 case AV_CODEC_ID_MACE3:
1966 sc->samples_per_frame = 6;
1967 sc->bytes_per_frame = 2 * st->codecpar->channels;
1969 case AV_CODEC_ID_MACE6:
1970 sc->samples_per_frame = 6;
1971 sc->bytes_per_frame = 1 * st->codecpar->channels;
1973 case AV_CODEC_ID_ADPCM_IMA_QT:
1974 sc->samples_per_frame = 64;
1975 sc->bytes_per_frame = 34 * st->codecpar->channels;
1977 case AV_CODEC_ID_GSM:
1978 sc->samples_per_frame = 160;
1979 sc->bytes_per_frame = 33;
1985 bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
1986 if (bits_per_sample) {
1987 st->codecpar->bits_per_coded_sample = bits_per_sample;
1988 sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
1992 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1993 AVStream *st, MOVStreamContext *sc,
1996 // ttxt stsd contains display flags, justification, background
1997 // color, fonts, and default styles, so fake an atom to read it
1998 MOVAtom fake_atom = { .size = size };
1999 // mp4s contains a regular esds atom
2000 if (st->codecpar->codec_tag != AV_RL32("mp4s"))
2001 mov_read_glbl(c, pb, fake_atom);
2002 st->codecpar->width = sc->width;
2003 st->codecpar->height = sc->height;
2006 static uint32_t yuv_to_rgba(uint32_t ycbcr)
2011 y = (ycbcr >> 16) & 0xFF;
2012 cr = (ycbcr >> 8) & 0xFF;
2015 b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
2016 g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
2017 r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
2019 return (r << 16) | (g << 8) | b;
2022 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
2024 char buf[256] = {0};
2025 uint8_t *src = st->codecpar->extradata;
2028 if (st->codecpar->extradata_size != 64)
2031 if (st->codecpar->width > 0 && st->codecpar->height > 0)
2032 snprintf(buf, sizeof(buf), "size: %dx%d\n",
2033 st->codecpar->width, st->codecpar->height);
2034 av_strlcat(buf, "palette: ", sizeof(buf));
2036 for (i = 0; i < 16; i++) {
2037 uint32_t yuv = AV_RB32(src + i * 4);
2038 uint32_t rgba = yuv_to_rgba(yuv);
2040 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2043 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2046 av_freep(&st->codecpar->extradata);
2047 st->codecpar->extradata_size = 0;
2048 st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
2049 if (!st->codecpar->extradata)
2050 return AVERROR(ENOMEM);
2051 st->codecpar->extradata_size = strlen(buf);
2052 memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
2057 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2058 AVStream *st, MOVStreamContext *sc,
2063 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
2064 if ((int)size != size)
2065 return AVERROR(ENOMEM);
2067 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
2071 MOVStreamContext *tmcd_ctx = st->priv_data;
2073 val = AV_RB32(st->codecpar->extradata + 4);
2074 tmcd_ctx->tmcd_flags = val;
2075 st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
2076 st->avg_frame_rate.den = 1;
2077 #if FF_API_LAVF_AVCTX
2078 FF_DISABLE_DEPRECATION_WARNINGS
2079 st->codec->time_base = av_inv_q(st->avg_frame_rate);
2080 FF_ENABLE_DEPRECATION_WARNINGS
2082 /* adjust for per frame dur in counter mode */
2083 if (tmcd_ctx->tmcd_flags & 0x0008) {
2084 int timescale = AV_RB32(st->codecpar->extradata + 8);
2085 int framedur = AV_RB32(st->codecpar->extradata + 12);
2086 st->avg_frame_rate.num *= timescale;
2087 st->avg_frame_rate.den *= framedur;
2088 #if FF_API_LAVF_AVCTX
2089 FF_DISABLE_DEPRECATION_WARNINGS
2090 st->codec->time_base.den *= timescale;
2091 st->codec->time_base.num *= framedur;
2092 FF_ENABLE_DEPRECATION_WARNINGS
2096 uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
2097 uint32_t format = AV_RB32(st->codecpar->extradata + 22);
2098 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2099 uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
2100 if (str_size > 0 && size >= (int)str_size + 26) {
2101 char *reel_name = av_malloc(str_size + 1);
2103 return AVERROR(ENOMEM);
2104 memcpy(reel_name, st->codecpar->extradata + 30, str_size);
2105 reel_name[str_size] = 0; /* Add null terminator */
2106 /* don't add reel_name if emtpy string */
2107 if (*reel_name == 0) {
2110 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2117 /* other codec type, just skip (rtp, mp4s ...) */
2118 avio_skip(pb, size);
2123 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2124 AVStream *st, MOVStreamContext *sc)
2126 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2127 !st->codecpar->sample_rate && sc->time_scale > 1)
2128 st->codecpar->sample_rate = sc->time_scale;
2130 /* special codec parameters handling */
2131 switch (st->codecpar->codec_id) {
2132 #if CONFIG_DV_DEMUXER
2133 case AV_CODEC_ID_DVAUDIO:
2134 c->dv_fctx = avformat_alloc_context();
2136 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2137 return AVERROR(ENOMEM);
2139 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2141 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2142 return AVERROR(ENOMEM);
2144 sc->dv_audio_container = 1;
2145 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
2148 /* no ifdef since parameters are always those */
2149 case AV_CODEC_ID_QCELP:
2150 st->codecpar->channels = 1;
2151 // force sample rate for qcelp when not stored in mov
2152 if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
2153 st->codecpar->sample_rate = 8000;
2154 // FIXME: Why is the following needed for some files?
2155 sc->samples_per_frame = 160;
2156 if (!sc->bytes_per_frame)
2157 sc->bytes_per_frame = 35;
2159 case AV_CODEC_ID_AMR_NB:
2160 st->codecpar->channels = 1;
2161 /* force sample rate for amr, stsd in 3gp does not store sample rate */
2162 st->codecpar->sample_rate = 8000;
2164 case AV_CODEC_ID_AMR_WB:
2165 st->codecpar->channels = 1;
2166 st->codecpar->sample_rate = 16000;
2168 case AV_CODEC_ID_MP2:
2169 case AV_CODEC_ID_MP3:
2170 /* force type after stsd for m1a hdlr */
2171 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2173 case AV_CODEC_ID_GSM:
2174 case AV_CODEC_ID_ADPCM_MS:
2175 case AV_CODEC_ID_ADPCM_IMA_WAV:
2176 case AV_CODEC_ID_ILBC:
2177 case AV_CODEC_ID_MACE3:
2178 case AV_CODEC_ID_MACE6:
2179 case AV_CODEC_ID_QDM2:
2180 st->codecpar->block_align = sc->bytes_per_frame;
2182 case AV_CODEC_ID_ALAC:
2183 if (st->codecpar->extradata_size == 36) {
2184 st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
2185 st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
2188 case AV_CODEC_ID_AC3:
2189 case AV_CODEC_ID_EAC3:
2190 case AV_CODEC_ID_MPEG1VIDEO:
2191 case AV_CODEC_ID_VC1:
2192 st->need_parsing = AVSTREAM_PARSE_FULL;
2200 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2201 int codec_tag, int format,
2204 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2207 (codec_tag != format &&
2208 // prores is allowed to have differing data format and codec tag
2209 codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
2210 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2211 : codec_tag != MKTAG('j','p','e','g')))) {
2212 /* Multiple fourcc, we skip JPEG. This is not correct, we should
2213 * export it as a separate AVStream but this needs a few changes
2214 * in the MOV demuxer, patch welcome. */
2216 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2217 avio_skip(pb, size);
2220 if ( codec_tag == AV_RL32("hvc1") ||
2221 codec_tag == AV_RL32("hev1")
2223 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
2228 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2231 MOVStreamContext *sc;
2232 int pseudo_stream_id;
2234 if (c->fc->nb_streams < 1)
2236 st = c->fc->streams[c->fc->nb_streams-1];
2239 for (pseudo_stream_id = 0;
2240 pseudo_stream_id < entries && !pb->eof_reached;
2241 pseudo_stream_id++) {
2242 //Parsing Sample description table
2244 int ret, dref_id = 1;
2245 MOVAtom a = { AV_RL32("stsd") };
2246 int64_t start_pos = avio_tell(pb);
2247 int64_t size = avio_rb32(pb); /* size */
2248 uint32_t format = avio_rl32(pb); /* data format */
2251 avio_rb32(pb); /* reserved */
2252 avio_rb16(pb); /* reserved */
2253 dref_id = avio_rb16(pb);
2254 } else if (size <= 7) {
2255 av_log(c->fc, AV_LOG_ERROR,
2256 "invalid size %"PRId64" in stsd\n", size);
2257 return AVERROR_INVALIDDATA;
2260 if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
2261 size - (avio_tell(pb) - start_pos)))
2264 sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
2265 sc->dref_id= dref_id;
2266 sc->format = format;
2268 id = mov_codec_id(st, format);
2270 av_log(c->fc, AV_LOG_TRACE,
2271 "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
2272 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
2273 (format >> 24) & 0xff, format, st->codecpar->codec_type);
2275 if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
2276 st->codecpar->codec_id = id;
2277 mov_parse_stsd_video(c, pb, st, sc);
2278 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
2279 st->codecpar->codec_id = id;
2280 mov_parse_stsd_audio(c, pb, st, sc);
2281 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
2282 st->codecpar->codec_id = id;
2283 mov_parse_stsd_subtitle(c, pb, st, sc,
2284 size - (avio_tell(pb) - start_pos));
2286 ret = mov_parse_stsd_data(c, pb, st, sc,
2287 size - (avio_tell(pb) - start_pos));
2291 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2292 a.size = size - (avio_tell(pb) - start_pos);
2294 if ((ret = mov_read_default(c, pb, a)) < 0)
2296 } else if (a.size > 0)
2297 avio_skip(pb, a.size);
2299 if (sc->extradata) {
2300 int extra_size = st->codecpar->extradata_size;
2302 /* Move the current stream extradata to the stream context one. */
2303 sc->extradata_size[pseudo_stream_id] = extra_size;
2304 sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
2305 if (!sc->extradata[pseudo_stream_id])
2306 return AVERROR(ENOMEM);
2307 memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
2308 av_freep(&st->codecpar->extradata);
2309 st->codecpar->extradata_size = 0;
2313 if (pb->eof_reached)
2316 return mov_finalize_stsd_codec(c, pb, st, sc);
2319 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2322 MOVStreamContext *sc;
2325 if (c->fc->nb_streams < 1)
2327 st = c->fc->streams[c->fc->nb_streams - 1];
2330 avio_r8(pb); /* version */
2331 avio_rb24(pb); /* flags */
2332 sc->stsd_count = avio_rb32(pb); /* entries */
2334 /* Prepare space for hosting multiple extradata. */
2335 sc->extradata = av_mallocz_array(sc->stsd_count, sizeof(*sc->extradata));
2337 return AVERROR(ENOMEM);
2339 sc->extradata_size = av_mallocz_array(sc->stsd_count, sizeof(*sc->extradata_size));
2340 if (!sc->extradata_size)
2341 return AVERROR(ENOMEM);
2343 ret = ff_mov_read_stsd_entries(c, pb, sc->stsd_count);
2347 /* Restore back the primary extradata. */
2348 av_freep(&st->codecpar->extradata);
2349 st->codecpar->extradata_size = sc->extradata_size[0];
2350 if (sc->extradata_size[0]) {
2351 st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
2352 if (!st->codecpar->extradata)
2353 return AVERROR(ENOMEM);
2354 memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
2360 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2363 MOVStreamContext *sc;
2364 unsigned int i, entries;
2366 if (c->fc->nb_streams < 1)
2368 st = c->fc->streams[c->fc->nb_streams-1];
2371 avio_r8(pb); /* version */
2372 avio_rb24(pb); /* flags */
2374 entries = avio_rb32(pb);
2376 av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
2381 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2382 av_free(sc->stsc_data);
2384 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2386 return AVERROR(ENOMEM);
2388 for (i = 0; i < entries && !pb->eof_reached; i++) {
2389 sc->stsc_data[i].first = avio_rb32(pb);
2390 sc->stsc_data[i].count = avio_rb32(pb);
2391 sc->stsc_data[i].id = avio_rb32(pb);
2396 if (pb->eof_reached)
2402 /* Compute the samples value for the stsc entry at the given index. */
2403 static inline int mov_get_stsc_samples(MOVStreamContext *sc, int index)
2407 if (index < sc->stsc_count - 1)
2408 chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
2410 chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
2412 return sc->stsc_data[index].count * chunk_count;
2415 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2418 MOVStreamContext *sc;
2419 unsigned i, entries;
2421 if (c->fc->nb_streams < 1)
2423 st = c->fc->streams[c->fc->nb_streams-1];
2426 avio_rb32(pb); // version + flags
2428 entries = avio_rb32(pb);
2430 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2431 av_free(sc->stps_data);
2433 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2435 return AVERROR(ENOMEM);
2437 for (i = 0; i < entries && !pb->eof_reached; i++) {
2438 sc->stps_data[i] = avio_rb32(pb);
2439 //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
2444 if (pb->eof_reached)
2450 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2453 MOVStreamContext *sc;
2454 unsigned int i, entries;
2456 if (c->fc->nb_streams < 1)
2458 st = c->fc->streams[c->fc->nb_streams-1];
2461 avio_r8(pb); /* version */
2462 avio_rb24(pb); /* flags */
2464 entries = avio_rb32(pb);
2466 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
2470 sc->keyframe_absent = 1;
2471 if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2472 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2476 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2477 if (entries >= UINT_MAX / sizeof(int))
2478 return AVERROR_INVALIDDATA;
2479 av_freep(&sc->keyframes);
2480 sc->keyframe_count = 0;
2481 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2483 return AVERROR(ENOMEM);
2485 for (i = 0; i < entries && !pb->eof_reached; i++) {
2486 sc->keyframes[i] = avio_rb32(pb);
2487 //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
2490 sc->keyframe_count = i;
2492 if (pb->eof_reached)
2498 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2501 MOVStreamContext *sc;
2502 unsigned int i, entries, sample_size, field_size, num_bytes;
2507 if (c->fc->nb_streams < 1)
2509 st = c->fc->streams[c->fc->nb_streams-1];
2512 avio_r8(pb); /* version */
2513 avio_rb24(pb); /* flags */
2515 if (atom.type == MKTAG('s','t','s','z')) {
2516 sample_size = avio_rb32(pb);
2517 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2518 sc->sample_size = sample_size;
2519 sc->stsz_sample_size = sample_size;
2523 avio_rb24(pb); /* reserved */
2524 field_size = avio_r8(pb);
2526 entries = avio_rb32(pb);
2528 av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2530 sc->sample_count = entries;
2534 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2535 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2536 return AVERROR_INVALIDDATA;
2541 if (entries >= (UINT_MAX - 4) / field_size)
2542 return AVERROR_INVALIDDATA;
2543 if (sc->sample_sizes)
2544 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2545 av_free(sc->sample_sizes);
2546 sc->sample_count = 0;
2547 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2548 if (!sc->sample_sizes)
2549 return AVERROR(ENOMEM);
2551 num_bytes = (entries*field_size+4)>>3;
2553 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2555 av_freep(&sc->sample_sizes);
2556 return AVERROR(ENOMEM);
2559 ret = ffio_read_size(pb, buf, num_bytes);
2561 av_freep(&sc->sample_sizes);
2566 init_get_bits(&gb, buf, 8*num_bytes);
2568 for (i = 0; i < entries && !pb->eof_reached; i++) {
2569 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2570 sc->data_size += sc->sample_sizes[i];
2573 sc->sample_count = i;
2577 if (pb->eof_reached)
2583 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2586 MOVStreamContext *sc;
2587 unsigned int i, entries;
2589 int64_t total_sample_count=0;
2591 if (c->fc->nb_streams < 1)
2593 st = c->fc->streams[c->fc->nb_streams-1];
2596 avio_r8(pb); /* version */
2597 avio_rb24(pb); /* flags */
2598 entries = avio_rb32(pb);
2600 av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2601 c->fc->nb_streams-1, entries);
2604 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2605 av_free(sc->stts_data);
2607 sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2609 return AVERROR(ENOMEM);
2611 for (i = 0; i < entries && !pb->eof_reached; i++) {
2612 int sample_duration;
2615 sample_count=avio_rb32(pb);
2616 sample_duration = avio_rb32(pb);
2618 if (sample_count < 0) {
2619 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2620 return AVERROR_INVALIDDATA;
2622 sc->stts_data[i].count= sample_count;
2623 sc->stts_data[i].duration= sample_duration;
2625 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2626 sample_count, sample_duration);
2630 && sample_count == 1
2631 && total_sample_count > 100
2632 && sample_duration/10 > duration / total_sample_count)
2633 sample_duration = duration / total_sample_count;
2634 duration+=(int64_t)sample_duration*sample_count;
2635 total_sample_count+=sample_count;
2640 sc->duration_for_fps += duration;
2641 sc->nb_frames_for_fps += total_sample_count;
2643 if (pb->eof_reached)
2646 st->nb_frames= total_sample_count;
2648 st->duration= duration;
2649 sc->track_end = duration;
2653 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2656 if (duration == INT_MIN) {
2657 av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2660 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2664 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2667 MOVStreamContext *sc;
2668 unsigned int i, entries, ctts_count = 0;
2670 if (c->fc->nb_streams < 1)
2672 st = c->fc->streams[c->fc->nb_streams-1];
2675 avio_r8(pb); /* version */
2676 avio_rb24(pb); /* flags */
2677 entries = avio_rb32(pb);
2679 av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2683 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2684 return AVERROR_INVALIDDATA;
2685 av_freep(&sc->ctts_data);
2686 sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2688 return AVERROR(ENOMEM);
2690 for (i = 0; i < entries && !pb->eof_reached; i++) {
2691 int count =avio_rb32(pb);
2692 int duration =avio_rb32(pb);
2695 av_log(c->fc, AV_LOG_TRACE,
2696 "ignoring CTTS entry with count=%d duration=%d\n",
2701 sc->ctts_data[ctts_count].count = count;
2702 sc->ctts_data[ctts_count].duration = duration;
2705 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2708 if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2709 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2710 av_freep(&sc->ctts_data);
2716 mov_update_dts_shift(sc, duration);
2719 sc->ctts_count = ctts_count;
2721 if (pb->eof_reached)
2724 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2729 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2732 MOVStreamContext *sc;
2733 unsigned int i, entries;
2735 uint32_t grouping_type;
2737 if (c->fc->nb_streams < 1)
2739 st = c->fc->streams[c->fc->nb_streams-1];
2742 version = avio_r8(pb); /* version */
2743 avio_rb24(pb); /* flags */
2744 grouping_type = avio_rl32(pb);
2745 if (grouping_type != MKTAG( 'r','a','p',' '))
2746 return 0; /* only support 'rap ' grouping */
2748 avio_rb32(pb); /* grouping_type_parameter */
2750 entries = avio_rb32(pb);
2754 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2755 av_free(sc->rap_group);
2756 sc->rap_group_count = 0;
2757 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2759 return AVERROR(ENOMEM);
2761 for (i = 0; i < entries && !pb->eof_reached; i++) {
2762 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2763 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2766 sc->rap_group_count = i;
2768 return pb->eof_reached ? AVERROR_EOF : 0;
2771 static void mov_build_index(MOVContext *mov, AVStream *st)
2773 MOVStreamContext *sc = st->priv_data;
2774 int64_t current_offset;
2775 int64_t current_dts = 0;
2776 unsigned int stts_index = 0;
2777 unsigned int stsc_index = 0;
2778 unsigned int stss_index = 0;
2779 unsigned int stps_index = 0;
2781 uint64_t stream_size = 0;
2783 if (sc->elst_count) {
2784 int i, edit_start_index = 0, unsupported = 0;
2785 int64_t empty_duration = 0; // empty duration of the first edit list entry
2786 int64_t start_time = 0; // start time of the media
2788 for (i = 0; i < sc->elst_count; i++) {
2789 const MOVElst *e = &sc->elst_data[i];
2790 if (i == 0 && e->time == -1) {
2791 /* if empty, the first entry is the start time of the stream
2792 * relative to the presentation itself */
2793 empty_duration = e->duration;
2794 edit_start_index = 1;
2795 } else if (i == edit_start_index && e->time >= 0) {
2796 start_time = e->time;
2801 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
2802 "a/v desync might occur, patch welcome\n");
2804 /* adjust first dts according to edit list */
2805 if ((empty_duration || start_time) && mov->time_scale > 0) {
2807 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
2808 sc->time_offset = start_time - empty_duration;
2809 current_dts = -sc->time_offset;
2810 if (sc->ctts_count>0 && sc->stts_count>0 &&
2811 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2812 /* more than 16 frames delay, dts are likely wrong
2813 this happens with files created by iMovie */
2815 st->codecpar->video_delay = 1;
2819 if (!unsupported && st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
2820 sc->start_pad = start_time;
2823 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2824 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2825 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2826 unsigned int current_sample = 0;
2827 unsigned int stts_sample = 0;
2828 unsigned int sample_size;
2829 unsigned int distance = 0;
2830 unsigned int rap_group_index = 0;
2831 unsigned int rap_group_sample = 0;
2832 int64_t last_dts = 0;
2833 int64_t dts_correction = 0;
2834 int rap_group_present = sc->rap_group_count && sc->rap_group;
2835 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2837 current_dts -= sc->dts_shift;
2838 last_dts = current_dts;
2840 if (!sc->sample_count || st->nb_index_entries)
2842 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2844 if (av_reallocp_array(&st->index_entries,
2845 st->nb_index_entries + sc->sample_count,
2846 sizeof(*st->index_entries)) < 0) {
2847 st->nb_index_entries = 0;
2850 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2852 for (i = 0; i < sc->chunk_count; i++) {
2853 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2854 current_offset = sc->chunk_offsets[i];
2855 while (stsc_index + 1 < sc->stsc_count &&
2856 i + 1 == sc->stsc_data[stsc_index + 1].first)
2859 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2860 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2861 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2862 sc->stsz_sample_size = sc->sample_size;
2864 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2865 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2866 sc->stsz_sample_size = sc->sample_size;
2869 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2871 if (current_sample >= sc->sample_count) {
2872 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2876 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2878 if (stss_index + 1 < sc->keyframe_count)
2880 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2882 if (stps_index + 1 < sc->stps_count)
2885 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2886 if (sc->rap_group[rap_group_index].index > 0)
2888 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2889 rap_group_sample = 0;
2893 if (sc->keyframe_absent
2895 && !rap_group_present
2896 && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2900 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2901 if (sc->pseudo_stream_id == -1 ||
2902 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2904 if (sample_size > 0x3FFFFFFF) {
2905 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
2908 e = &st->index_entries[st->nb_index_entries++];
2909 e->pos = current_offset;
2910 e->timestamp = current_dts;
2911 e->size = sample_size;
2912 e->min_distance = distance;
2913 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2914 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2915 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2916 current_offset, current_dts, sample_size, distance, keyframe);
2917 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2918 ff_rfps_add_frame(mov->fc, st, current_dts);
2921 current_offset += sample_size;
2922 stream_size += sample_size;
2924 /* A negative sample duration is invalid based on the spec,
2925 * but some samples need it to correct the DTS. */
2926 if (sc->stts_data[stts_index].duration < 0) {
2927 av_log(mov->fc, AV_LOG_WARNING,
2928 "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2929 sc->stts_data[stts_index].duration, stts_index,
2931 dts_correction += sc->stts_data[stts_index].duration - 1;
2932 sc->stts_data[stts_index].duration = 1;
2934 current_dts += sc->stts_data[stts_index].duration;
2935 if (!dts_correction || current_dts + dts_correction > last_dts) {
2936 current_dts += dts_correction;
2939 /* Avoid creating non-monotonous DTS */
2940 dts_correction += current_dts - last_dts - 1;
2941 current_dts = last_dts + 1;
2943 last_dts = current_dts;
2947 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2953 if (st->duration > 0)
2954 st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
2956 unsigned chunk_samples, total = 0;
2958 // compute total chunk count
2959 for (i = 0; i < sc->stsc_count; i++) {
2960 unsigned count, chunk_count;
2962 chunk_samples = sc->stsc_data[i].count;
2963 if (i != sc->stsc_count - 1 &&
2964 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2965 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2969 if (sc->samples_per_frame >= 160) { // gsm
2970 count = chunk_samples / sc->samples_per_frame;
2971 } else if (sc->samples_per_frame > 1) {
2972 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2973 count = (chunk_samples+samples-1) / samples;
2975 count = (chunk_samples+1023) / 1024;
2978 if (i < sc->stsc_count - 1)
2979 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2981 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2982 total += chunk_count * count;
2985 av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2986 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2988 if (av_reallocp_array(&st->index_entries,
2989 st->nb_index_entries + total,
2990 sizeof(*st->index_entries)) < 0) {
2991 st->nb_index_entries = 0;
2994 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2997 for (i = 0; i < sc->chunk_count; i++) {
2998 current_offset = sc->chunk_offsets[i];
2999 if (stsc_index + 1 < sc->stsc_count &&
3000 i + 1 == sc->stsc_data[stsc_index + 1].first)
3002 chunk_samples = sc->stsc_data[stsc_index].count;
3004 while (chunk_samples > 0) {
3006 unsigned size, samples;
3008 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
3009 avpriv_request_sample(mov->fc,
3010 "Zero bytes per frame, but %d samples per frame",
3011 sc->samples_per_frame);
3015 if (sc->samples_per_frame >= 160) { // gsm
3016 samples = sc->samples_per_frame;
3017 size = sc->bytes_per_frame;
3019 if (sc->samples_per_frame > 1) {
3020 samples = FFMIN((1024 / sc->samples_per_frame)*
3021 sc->samples_per_frame, chunk_samples);
3022 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
3024 samples = FFMIN(1024, chunk_samples);
3025 size = samples * sc->sample_size;
3029 if (st->nb_index_entries >= total) {
3030 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
3033 if (size > 0x3FFFFFFF) {
3034 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
3037 e = &st->index_entries[st->nb_index_entries++];
3038 e->pos = current_offset;
3039 e->timestamp = current_dts;
3041 e->min_distance = 0;
3042 e->flags = AVINDEX_KEYFRAME;
3043 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
3044 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
3047 current_offset += size;
3048 current_dts += samples;
3049 chunk_samples -= samples;
3055 static int test_same_origin(const char *src, const char *ref) {
3065 av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
3066 av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
3068 if (strlen(src) == 0) {
3070 } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
3071 strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
3072 strlen(src_host) + 1 >= sizeof(src_host) ||
3073 strlen(ref_host) + 1 >= sizeof(ref_host)) {
3075 } else if (strcmp(src_proto, ref_proto) ||
3076 strcmp(src_auth, ref_auth) ||
3077 strcmp(src_host, ref_host) ||
3078 src_port != ref_port) {
3084 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
3086 /* try relative path, we do not try the absolute because it can leak information about our
3087 system to an attacker */
3088 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
3089 char filename[1025];
3090 const char *src_path;
3093 /* find a source dir */
3094 src_path = strrchr(src, '/');
3100 /* find a next level down to target */
3101 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
3102 if (ref->path[l] == '/') {
3103 if (i == ref->nlvl_to - 1)
3109 /* compose filename if next level down to target was found */
3110 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
3111 memcpy(filename, src, src_path - src);
3112 filename[src_path - src] = 0;
3114 for (i = 1; i < ref->nlvl_from; i++)
3115 av_strlcat(filename, "../", sizeof(filename));
3117 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
3118 if (!c->use_absolute_path) {
3119 int same_origin = test_same_origin(src, filename);
3122 av_log(c->fc, AV_LOG_ERROR,
3123 "Reference with mismatching origin, %s not tried for security reasons, "
3124 "set demuxer option use_absolute_path to allow it anyway\n",
3126 return AVERROR(ENOENT);
3129 if(strstr(ref->path + l + 1, "..") ||
3130 strstr(ref->path + l + 1, ":") ||
3131 (ref->nlvl_from > 1 && same_origin < 0) ||
3132 (filename[0] == '/' && src_path == src))
3133 return AVERROR(ENOENT);
3136 if (strlen(filename) + 1 == sizeof(filename))
3137 return AVERROR(ENOENT);
3138 if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
3141 } else if (c->use_absolute_path) {
3142 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
3143 "this is a possible security issue\n");
3144 if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
3147 av_log(c->fc, AV_LOG_ERROR,
3148 "Absolute path %s not tried for security reasons, "
3149 "set demuxer option use_absolute_path to allow absolute paths\n",
3153 return AVERROR(ENOENT);
3156 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
3158 if (sc->time_scale <= 0) {
3159 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
3160 sc->time_scale = c->time_scale;
3161 if (sc->time_scale <= 0)
3166 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3169 MOVStreamContext *sc;
3172 st = avformat_new_stream(c->fc, NULL);
3173 if (!st) return AVERROR(ENOMEM);
3174 st->id = c->fc->nb_streams;
3175 sc = av_mallocz(sizeof(MOVStreamContext));
3176 if (!sc) return AVERROR(ENOMEM);
3179 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
3180 sc->ffindex = st->index;
3181 c->trak_index = st->index;
3183 if ((ret = mov_read_default(c, pb, atom)) < 0)
3189 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
3190 (!sc->sample_size && !sc->sample_count))) {
3191 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
3196 fix_timescale(c, sc);
3198 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
3200 mov_build_index(c, st);
3202 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
3203 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
3204 if (c->enable_drefs) {
3205 if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
3206 av_log(c->fc, AV_LOG_ERROR,
3207 "stream %d, error opening alias: path='%s', dir='%s', "
3208 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
3209 st->index, dref->path, dref->dir, dref->filename,
3210 dref->volume, dref->nlvl_from, dref->nlvl_to);
3212 av_log(c->fc, AV_LOG_WARNING,
3213 "Skipped opening external track: "
3214 "stream %d, alias: path='%s', dir='%s', "
3215 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
3216 "Set enable_drefs to allow this.\n",
3217 st->index, dref->path, dref->dir, dref->filename,
3218 dref->volume, dref->nlvl_from, dref->nlvl_to);
3222 sc->pb_is_copied = 1;
3225 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3226 if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
3227 sc->height && sc->width &&
3228 (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
3229 st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
3230 ((double)st->codecpar->width * sc->height), INT_MAX);
3233 #if FF_API_R_FRAME_RATE
3234 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
3235 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
3236 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
3240 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3241 if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
3242 TAG_IS_AVCI(st->codecpar->codec_tag)) {
3243 ret = ff_generate_avci_extradata(st);
3248 switch (st->codecpar->codec_id) {
3249 #if CONFIG_H261_DECODER
3250 case AV_CODEC_ID_H261:
3252 #if CONFIG_H263_DECODER
3253 case AV_CODEC_ID_H263:
3255 #if CONFIG_MPEG4_DECODER
3256 case AV_CODEC_ID_MPEG4:
3258 st->codecpar->width = 0; /* let decoder init width/height */
3259 st->codecpar->height= 0;
3263 // If the duration of the mp3 packets is not constant, then they could need a parser
3264 if (st->codecpar->codec_id == AV_CODEC_ID_MP3
3265 && sc->stts_count > 3
3266 && sc->stts_count*10 > st->nb_frames
3267 && sc->time_scale == st->codecpar->sample_rate) {
3268 st->need_parsing = AVSTREAM_PARSE_FULL;
3270 /* Do not need those anymore. */
3271 av_freep(&sc->chunk_offsets);
3272 av_freep(&sc->sample_sizes);
3273 av_freep(&sc->keyframes);
3274 av_freep(&sc->stts_data);
3275 av_freep(&sc->stps_data);
3276 av_freep(&sc->elst_data);
3277 av_freep(&sc->rap_group);
3282 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3285 c->itunes_metadata = 1;
3286 ret = mov_read_default(c, pb, atom);
3287 c->itunes_metadata = 0;
3291 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3300 count = avio_rb32(pb);
3301 if (count > UINT_MAX / sizeof(*c->meta_keys)) {
3302 av_log(c->fc, AV_LOG_ERROR,
3303 "The 'keys' atom with the invalid key count: %d\n", count);
3304 return AVERROR_INVALIDDATA;
3307 c->meta_keys_count = count + 1;
3308 c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
3310 return AVERROR(ENOMEM);
3312 for (i = 1; i <= count; ++i) {
3313 uint32_t key_size = avio_rb32(pb);
3314 uint32_t type = avio_rl32(pb);
3316 av_log(c->fc, AV_LOG_ERROR,
3317 "The key# %d in meta has invalid size: %d\n", i, key_size);
3318 return AVERROR_INVALIDDATA;
3321 if (type != MKTAG('m','d','t','a')) {
3322 avio_skip(pb, key_size);
3324 c->meta_keys[i] = av_mallocz(key_size + 1);
3325 if (!c->meta_keys[i])
3326 return AVERROR(ENOMEM);
3327 avio_read(pb, c->meta_keys[i], key_size);
3333 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3335 int64_t end = avio_tell(pb) + atom.size;
3336 uint8_t *key = NULL, *val = NULL, *mean = NULL;
3340 MOVStreamContext *sc;
3342 if (c->fc->nb_streams < 1)
3344 st = c->fc->streams[c->fc->nb_streams-1];
3347 for (i = 0; i < 3; i++) {
3351 if (end - avio_tell(pb) <= 12)
3354 len = avio_rb32(pb);
3355 tag = avio_rl32(pb);
3356 avio_skip(pb, 4); // flags
3358 if (len < 12 || len - 12 > end - avio_tell(pb))
3362 if (tag == MKTAG('m', 'e', 'a', 'n'))
3364 else if (tag == MKTAG('n', 'a', 'm', 'e'))
3366 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
3373 *p = av_malloc(len + 1);
3376 ret = ffio_read_size(pb, *p, len);
3384 if (mean && key && val) {
3385 if (strcmp(key, "iTunSMPB") == 0) {
3386 int priming, remainder, samples;
3387 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
3388 if(priming>0 && priming<16384)
3389 sc->start_pad = priming;
3392 if (strcmp(key, "cdec") != 0) {
3393 av_dict_set(&c->fc->metadata, key, val,
3394 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
3398 av_log(c->fc, AV_LOG_VERBOSE,
3399 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
3402 avio_seek(pb, end, SEEK_SET);
3409 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3411 while (atom.size > 8) {
3412 uint32_t tag = avio_rl32(pb);
3414 if (tag == MKTAG('h','d','l','r')) {
3415 avio_seek(pb, -8, SEEK_CUR);
3417 return mov_read_default(c, pb, atom);
3423 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3428 int display_matrix[3][3];
3430 MOVStreamContext *sc;
3434 if (c->fc->nb_streams < 1)
3436 st = c->fc->streams[c->fc->nb_streams-1];
3439 version = avio_r8(pb);
3440 flags = avio_rb24(pb);
3441 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
3447 avio_rb32(pb); /* creation time */
3448 avio_rb32(pb); /* modification time */
3450 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
3451 avio_rb32(pb); /* reserved */
3453 /* highlevel (considering edits) duration in movie timebase */
3454 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
3455 avio_rb32(pb); /* reserved */
3456 avio_rb32(pb); /* reserved */
3458 avio_rb16(pb); /* layer */
3459 avio_rb16(pb); /* alternate group */
3460 avio_rb16(pb); /* volume */
3461 avio_rb16(pb); /* reserved */
3463 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
3464 // they're kept in fixed point format through all calculations
3465 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
3466 // side data, but the scale factor is not needed to calculate aspect ratio
3467 for (i = 0; i < 3; i++) {
3468 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
3469 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
3470 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
3473 width = avio_rb32(pb); // 16.16 fixed point track width
3474 height = avio_rb32(pb); // 16.16 fixed point track height
3475 sc->width = width >> 16;
3476 sc->height = height >> 16;
3478 // save the matrix and add rotate metadata when it is not the default
3480 if (display_matrix[0][0] != (1 << 16) ||
3481 display_matrix[1][1] != (1 << 16) ||
3482 display_matrix[2][2] != (1 << 30) ||
3483 display_matrix[0][1] || display_matrix[0][2] ||
3484 display_matrix[1][0] || display_matrix[1][2] ||
3485 display_matrix[2][0] || display_matrix[2][1]) {
3489 av_freep(&sc->display_matrix);
3490 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
3491 if (!sc->display_matrix)
3492 return AVERROR(ENOMEM);
3494 for (i = 0; i < 3; i++)
3495 for (j = 0; j < 3; j++)
3496 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
3498 rotate = av_display_rotation_get(sc->display_matrix);
3499 if (!isnan(rotate)) {
3500 char rotate_buf[64];
3502 if (rotate < 0) // for backward compatibility
3504 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
3505 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
3509 // transform the display width/height according to the matrix
3510 // to keep the same scale, use [width height 1<<16]
3511 if (width && height && sc->display_matrix) {
3512 double disp_transform[2];
3514 for (i = 0; i < 2; i++)
3515 disp_transform[i] = hypot(display_matrix[i][0], display_matrix[i][1]);
3517 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
3518 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
3519 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
3520 st->sample_aspect_ratio = av_d2q(
3521 disp_transform[0] / disp_transform[1],
3527 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3529 MOVFragment *frag = &c->fragment;
3530 MOVTrackExt *trex = NULL;
3531 MOVFragmentIndex* index = NULL;
3532 int flags, track_id, i, found = 0;
3534 avio_r8(pb); /* version */
3535 flags = avio_rb24(pb);
3537 track_id = avio_rb32(pb);
3539 return AVERROR_INVALIDDATA;
3540 frag->track_id = track_id;
3541 for (i = 0; i < c->trex_count; i++)
3542 if (c->trex_data[i].track_id == frag->track_id) {
3543 trex = &c->trex_data[i];
3547 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
3548 return AVERROR_INVALIDDATA;
3551 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
3552 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
3553 frag->moof_offset : frag->implicit_offset;
3554 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
3556 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
3557 avio_rb32(pb) : trex->duration;
3558 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
3559 avio_rb32(pb) : trex->size;
3560 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
3561 avio_rb32(pb) : trex->flags;
3562 frag->time = AV_NOPTS_VALUE;
3563 for (i = 0; i < c->fragment_index_count; i++) {
3565 MOVFragmentIndex* candidate = c->fragment_index_data[i];
3566 if (candidate->track_id == frag->track_id) {
3567 av_log(c->fc, AV_LOG_DEBUG,
3568 "found fragment index for track %u\n", frag->track_id);
3570 for (j = index->current_item; j < index->item_count; j++) {
3571 if (frag->implicit_offset == index->items[j].moof_offset) {
3572 av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
3573 "for track %u and moof_offset %"PRId64"\n",
3574 frag->track_id, index->items[j].moof_offset);
3575 frag->time = index->items[j].time;
3576 index->current_item = j + 1;
3585 if (index && !found) {
3586 av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
3587 "it doesn't have an (in-order) entry for moof_offset "
3588 "%"PRId64"\n", frag->track_id, frag->implicit_offset);
3590 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
3594 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3596 c->chapter_track = avio_rb32(pb);
3600 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3605 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
3606 return AVERROR_INVALIDDATA;
3607 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
3608 sizeof(*c->trex_data))) < 0) {
3613 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
3615 trex = &c->trex_data[c->trex_count++];
3616 avio_r8(pb); /* version */
3617 avio_rb24(pb); /* flags */
3618 trex->track_id = avio_rb32(pb);
3619 trex->stsd_id = avio_rb32(pb);
3620 trex->duration = avio_rb32(pb);
3621 trex->size = avio_rb32(pb);
3622 trex->flags = avio_rb32(pb);
3626 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3628 MOVFragment *frag = &c->fragment;
3629 AVStream *st = NULL;
3630 MOVStreamContext *sc;
3633 for (i = 0; i < c->fc->nb_streams; i++) {
3634 if (c->fc->streams[i]->id == frag->track_id) {
3635 st = c->fc->streams[i];
3640 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3641 return AVERROR_INVALIDDATA;
3644 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
3646 version = avio_r8(pb);
3647 avio_rb24(pb); /* flags */
3649 sc->track_end = avio_rb64(pb);
3651 sc->track_end = avio_rb32(pb);
3656 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3658 MOVFragment *frag = &c->fragment;
3659 AVStream *st = NULL;
3660 MOVStreamContext *sc;
3664 int data_offset = 0;
3665 unsigned entries, first_sample_flags = frag->flags;
3666 int flags, distance, i, err;
3668 for (i = 0; i < c->fc->nb_streams; i++) {
3669 if (c->fc->streams[i]->id == frag->track_id) {
3670 st = c->fc->streams[i];
3675 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3676 return AVERROR_INVALIDDATA;
3679 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3681 avio_r8(pb); /* version */
3682 flags = avio_rb24(pb);
3683 entries = avio_rb32(pb);
3684 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
3686 /* Always assume the presence of composition time offsets.
3687 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3688 * 1) in the initial movie, there are no samples.
3689 * 2) in the first movie fragment, there is only one sample without composition time offset.
3690 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
3691 if (!sc->ctts_count && sc->sample_count)
3693 /* Complement ctts table if moov atom doesn't have ctts atom. */
3694 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3696 return AVERROR(ENOMEM);
3697 sc->ctts_data = ctts_data;
3698 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3699 sc->ctts_data[sc->ctts_count].duration = 0;
3702 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3703 return AVERROR_INVALIDDATA;
3704 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3705 sizeof(*sc->ctts_data))) < 0) {
3709 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
3710 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3711 dts = sc->track_end - sc->time_offset;
3712 offset = frag->base_data_offset + data_offset;
3714 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3715 for (i = 0; i < entries && !pb->eof_reached; i++) {
3716 unsigned sample_size = frag->size;
3717 int sample_flags = i ? frag->flags : first_sample_flags;
3718 unsigned sample_duration = frag->duration;
3721 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3722 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
3723 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
3724 sc->ctts_data[sc->ctts_count].count = 1;
3725 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3727 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
3728 if (frag->time != AV_NOPTS_VALUE) {
3729 if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3730 int64_t pts = frag->time;
3731 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3732 " sc->dts_shift %d ctts.duration %d"
3733 " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3734 sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3735 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3736 dts = pts - sc->dts_shift;
3737 if (flags & MOV_TRUN_SAMPLE_CTS) {
3738 dts -= sc->ctts_data[sc->ctts_count].duration;
3740 dts -= sc->time_offset;
3742 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3744 dts = frag->time - sc->time_offset;
3745 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3746 ", using it for dts\n", dts);
3748 frag->time = AV_NOPTS_VALUE;
3751 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
3755 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3756 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3759 err = av_add_index_entry(st, offset, dts, sample_size, distance,
3760 keyframe ? AVINDEX_KEYFRAME : 0);
3762 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
3764 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3765 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3766 offset, dts, sample_size, distance, keyframe);
3768 dts += sample_duration;
3769 offset += sample_size;
3770 sc->data_size += sample_size;
3771 sc->duration_for_fps += sample_duration;
3772 sc->nb_frames_for_fps ++;
3775 if (pb->eof_reached)
3778 frag->implicit_offset = offset;
3780 sc->track_end = dts + sc->time_offset;
3781 if (st->duration < sc->track_end)
3782 st->duration = sc->track_end;
3787 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3789 int64_t offset = avio_tell(pb) + atom.size, pts;
3791 unsigned i, track_id;
3792 AVStream *st = NULL;
3793 MOVStreamContext *sc;
3794 MOVFragmentIndex *index = NULL;
3795 MOVFragmentIndex **tmp;
3796 AVRational timescale;
3798 version = avio_r8(pb);
3800 avpriv_request_sample(c->fc, "sidx version %u", version);
3804 avio_rb24(pb); // flags
3806 track_id = avio_rb32(pb); // Reference ID
3807 for (i = 0; i < c->fc->nb_streams; i++) {
3808 if (c->fc->streams[i]->id == track_id) {
3809 st = c->fc->streams[i];
3814 av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
3820 timescale = av_make_q(1, avio_rb32(pb));
3823 pts = avio_rb32(pb);
3824 offset += avio_rb32(pb);
3826 pts = avio_rb64(pb);
3827 offset += avio_rb64(pb);
3830 avio_rb16(pb); // reserved
3832 index = av_mallocz(sizeof(MOVFragmentIndex));
3834 return AVERROR(ENOMEM);
3836 index->track_id = track_id;
3838 index->item_count = avio_rb16(pb);
3839 index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
3841 if (!index->items) {
3843 return AVERROR(ENOMEM);
3846 for (i = 0; i < index->item_count; i++) {
3847 uint32_t size = avio_rb32(pb);
3848 uint32_t duration = avio_rb32(pb);
3849 if (size & 0x80000000) {
3850 avpriv_request_sample(c->fc, "sidx reference_type 1");
3851 av_freep(&index->items);
3853 return AVERROR_PATCHWELCOME;
3855 avio_rb32(pb); // sap_flags
3856 index->items[i].moof_offset = offset;
3857 index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
3862 st->duration = sc->track_end = pts;
3864 tmp = av_realloc_array(c->fragment_index_data,
3865 c->fragment_index_count + 1,
3866 sizeof(MOVFragmentIndex*));
3868 av_freep(&index->items);
3870 return AVERROR(ENOMEM);
3873 c->fragment_index_data = tmp;
3874 c->fragment_index_data[c->fragment_index_count++] = index;
3876 if (offset == avio_size(pb))
3877 c->fragment_index_complete = 1;
3882 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3883 /* like the files created with Adobe Premiere 5.0, for samples see */
3884 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3885 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3890 return 0; /* continue */
3891 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3892 avio_skip(pb, atom.size - 4);
3895 atom.type = avio_rl32(pb);
3897 if (atom.type != MKTAG('m','d','a','t')) {
3898 avio_skip(pb, atom.size);
3901 err = mov_read_mdat(c, pb, atom);
3905 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3910 uint8_t *moov_data; /* uncompressed data */
3911 long cmov_len, moov_len;
3914 avio_rb32(pb); /* dcom atom */
3915 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3916 return AVERROR_INVALIDDATA;
3917 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3918 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3919 return AVERROR_INVALIDDATA;
3921 avio_rb32(pb); /* cmvd atom */
3922 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3923 return AVERROR_INVALIDDATA;
3924 moov_len = avio_rb32(pb); /* uncompressed size */
3925 cmov_len = atom.size - 6 * 4;
3927 cmov_data = av_malloc(cmov_len);
3929 return AVERROR(ENOMEM);
3930 moov_data = av_malloc(moov_len);
3933 return AVERROR(ENOMEM);
3935 ret = ffio_read_size(pb, cmov_data, cmov_len);
3937 goto free_and_return;
3939 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3940 goto free_and_return;
3941 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3942 goto free_and_return;
3943 ctx.seekable = AVIO_SEEKABLE_NORMAL;
3944 atom.type = MKTAG('m','o','o','v');
3945 atom.size = moov_len;
3946 ret = mov_read_default(c, &ctx, atom);
3952 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3953 return AVERROR(ENOSYS);
3957 /* edit list atom */
3958 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3960 MOVStreamContext *sc;
3961 int i, edit_count, version;
3963 if (c->fc->nb_streams < 1 || c->ignore_editlist)
3965 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3967 version = avio_r8(pb); /* version */
3968 avio_rb24(pb); /* flags */
3969 edit_count = avio_rb32(pb); /* entries */
3974 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
3975 av_free(sc->elst_data);
3977 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
3979 return AVERROR(ENOMEM);
3981 av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3982 for (i = 0; i < edit_count && !pb->eof_reached; i++) {
3983 MOVElst *e = &sc->elst_data[i];
3986 e->duration = avio_rb64(pb);
3987 e->time = avio_rb64(pb);
3989 e->duration = avio_rb32(pb); /* segment duration */
3990 e->time = (int32_t)avio_rb32(pb); /* media time */
3992 e->rate = avio_rb32(pb) / 65536.0;
3993 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3994 e->duration, e->time, e->rate);
4001 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4003 MOVStreamContext *sc;
4005 if (c->fc->nb_streams < 1)
4006 return AVERROR_INVALIDDATA;
4007 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
4008 sc->timecode_track = avio_rb32(pb);
4012 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4016 static const uint8_t uuid_isml_manifest[] = {
4017 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
4018 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
4020 static const uint8_t uuid_xmp[] = {
4021 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
4022 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
4025 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
4026 return AVERROR_INVALIDDATA;
4028 ret = avio_read(pb, uuid, sizeof(uuid));
4031 } else if (ret != sizeof(uuid)) {
4032 return AVERROR_INVALIDDATA;
4034 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
4035 uint8_t *buffer, *ptr;
4037 size_t len = atom.size - sizeof(uuid);
4040 return AVERROR_INVALIDDATA;
4042 ret = avio_skip(pb, 4); // zeroes
4045 buffer = av_mallocz(len + 1);
4047 return AVERROR(ENOMEM);
4049 ret = avio_read(pb, buffer, len);
4053 } else if (ret != len) {
4055 return AVERROR_INVALIDDATA;
4059 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
4060 ptr += sizeof("systemBitrate=\"") - 1;
4061 c->bitrates_count++;
4062 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
4064 c->bitrates_count = 0;
4066 return AVERROR(ENOMEM);
4069 ret = strtol(ptr, &endptr, 10);
4070 if (ret < 0 || errno || *endptr != '"') {
4071 c->bitrates[c->bitrates_count - 1] = 0;
4073 c->bitrates[c->bitrates_count - 1] = ret;
4078 } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
4080 size_t len = atom.size - sizeof(uuid);
4082 buffer = av_mallocz(len + 1);
4084 return AVERROR(ENOMEM);
4086 ret = avio_read(pb, buffer, len);
4090 } else if (ret != len) {
4092 return AVERROR_INVALIDDATA;
4094 if (c->export_xmp) {
4096 av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
4103 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4106 uint8_t content[16];
4111 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
4117 && !memcmp(content, "Anevia\x1A\x1A", 8)
4118 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
4119 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
4125 static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4127 uint32_t format = avio_rl32(pb);
4128 MOVStreamContext *sc;
4132 if (c->fc->nb_streams < 1)
4134 st = c->fc->streams[c->fc->nb_streams - 1];
4139 case MKTAG('e','n','c','v'): // encrypted video
4140 case MKTAG('e','n','c','a'): // encrypted audio
4141 id = mov_codec_id(st, format);
4142 if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
4143 st->codecpar->codec_id != id) {
4144 av_log(c->fc, AV_LOG_WARNING,
4145 "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
4146 (char*)&format, st->codecpar->codec_id);
4150 st->codecpar->codec_id = id;
4151 sc->format = format;
4155 if (format != sc->format) {
4156 av_log(c->fc, AV_LOG_WARNING,
4157 "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
4158 (char*)&format, (char*)&sc->format);
4166 static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4169 MOVStreamContext *sc;
4170 size_t auxiliary_info_size;
4172 if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
4175 st = c->fc->streams[c->fc->nb_streams - 1];
4178 if (sc->cenc.aes_ctr) {
4179 av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
4180 return AVERROR_INVALIDDATA;
4183 avio_r8(pb); /* version */
4184 sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
4186 avio_rb32(pb); /* entries */
4188 if (atom.size < 8) {
4189 av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" too small\n", atom.size);
4190 return AVERROR_INVALIDDATA;
4193 /* save the auxiliary info as is */
4194 auxiliary_info_size = atom.size - 8;
4196 sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
4197 if (!sc->cenc.auxiliary_info) {
4198 return AVERROR(ENOMEM);
4201 sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
4203 sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
4205 if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
4206 av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
4207 return AVERROR_INVALIDDATA;
4210 /* initialize the cipher */
4211 sc->cenc.aes_ctr = av_aes_ctr_alloc();
4212 if (!sc->cenc.aes_ctr) {
4213 return AVERROR(ENOMEM);
4216 return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
4219 static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4222 MOVStreamContext *sc;
4224 int atom_header_size;
4227 if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
4230 st = c->fc->streams[c->fc->nb_streams - 1];
4233 if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
4234 av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
4235 return AVERROR_INVALIDDATA;
4238 atom_header_size = 9;
4240 avio_r8(pb); /* version */
4241 flags = avio_rb24(pb);
4243 if ((flags & 0x01) != 0) {
4244 atom_header_size += 8;
4246 avio_rb32(pb); /* info type */
4247 avio_rb32(pb); /* info type param */
4250 sc->cenc.auxiliary_info_default_size = avio_r8(pb);
4251 avio_rb32(pb); /* entries */
4253 if (atom.size <= atom_header_size) {
4257 /* save the auxiliary info sizes as is */
4258 data_size = atom.size - atom_header_size;
4260 sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
4261 if (!sc->cenc.auxiliary_info_sizes) {
4262 return AVERROR(ENOMEM);
4265 sc->cenc.auxiliary_info_sizes_count = data_size;
4267 if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
4268 av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
4269 return AVERROR_INVALIDDATA;
4275 static int cenc_filter(MOVContext *c, MOVStreamContext *sc, uint8_t *input, int size)
4277 uint32_t encrypted_bytes;
4278 uint16_t subsample_count;
4279 uint16_t clear_bytes;
4280 uint8_t* input_end = input + size;
4283 if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4284 av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
4285 return AVERROR_INVALIDDATA;
4288 av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
4289 sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
4291 if (!sc->cenc.use_subsamples)
4293 /* decrypt the whole packet */
4294 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
4298 /* read the subsample count */
4299 if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4300 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
4301 return AVERROR_INVALIDDATA;
4304 subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
4305 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
4307 for (; subsample_count > 0; subsample_count--)
4309 if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4310 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
4311 return AVERROR_INVALIDDATA;
4314 /* read the number of clear / encrypted bytes */
4315 clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
4316 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
4317 encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
4318 sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
4320 if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
4321 av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
4322 return AVERROR_INVALIDDATA;
4325 /* skip the clear bytes */
4326 input += clear_bytes;
4328 /* decrypt the encrypted bytes */
4329 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
4330 input += encrypted_bytes;
4333 if (input < input_end) {
4334 av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
4335 return AVERROR_INVALIDDATA;
4341 static int mov_seek_auxiliary_info(AVFormatContext *s, MOVStreamContext *sc)
4343 size_t auxiliary_info_seek_offset = 0;
4346 if (sc->cenc.auxiliary_info_default_size) {
4347 auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * sc->current_sample;
4348 } else if (sc->cenc.auxiliary_info_sizes) {
4349 if (sc->current_sample > sc->cenc.auxiliary_info_sizes_count) {
4350 av_log(s, AV_LOG_ERROR, "current sample %d greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
4351 sc->current_sample, sc->cenc.auxiliary_info_sizes_count);
4352 return AVERROR_INVALIDDATA;
4355 for (i = 0; i < sc->current_sample; i++) {
4356 auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
4360 if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
4361 av_log(s, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
4362 auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
4363 return AVERROR_INVALIDDATA;
4366 sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
4371 static const MOVParseTableEntry mov_default_parse_table[] = {
4372 { MKTAG('A','C','L','R'), mov_read_aclr },
4373 { MKTAG('A','P','R','G'), mov_read_avid },
4374 { MKTAG('A','A','L','P'), mov_read_avid },
4375 { MKTAG('A','R','E','S'), mov_read_ares },
4376 { MKTAG('a','v','s','s'), mov_read_avss },
4377 { MKTAG('c','h','p','l'), mov_read_chpl },
4378 { MKTAG('c','o','6','4'), mov_read_stco },
4379 { MKTAG('c','o','l','r'), mov_read_colr },
4380 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
4381 { MKTAG('d','i','n','f'), mov_read_default },
4382 { MKTAG('D','p','x','E'), mov_read_dpxe },
4383 { MKTAG('d','r','e','f'), mov_read_dref },
4384 { MKTAG('e','d','t','s'), mov_read_default },
4385 { MKTAG('e','l','s','t'), mov_read_elst },
4386 { MKTAG('e','n','d','a'), mov_read_enda },
4387 { MKTAG('f','i','e','l'), mov_read_fiel },
4388 { MKTAG('a','d','r','m'), mov_read_adrm },
4389 { MKTAG('f','t','y','p'), mov_read_ftyp },
4390 { MKTAG('g','l','b','l'), mov_read_glbl },
4391 { MKTAG('h','d','l','r'), mov_read_hdlr },
4392 { MKTAG('i','l','s','t'), mov_read_ilst },
4393 { MKTAG('j','p','2','h'), mov_read_jp2h },
4394 { MKTAG('m','d','a','t'), mov_read_mdat },
4395 { MKTAG('m','d','h','d'), mov_read_mdhd },
4396 { MKTAG('m','d','i','a'), mov_read_default },
4397 { MKTAG('m','e','t','a'), mov_read_meta },
4398 { MKTAG('m','i','n','f'), mov_read_default },
4399 { MKTAG('m','o','o','f'), mov_read_moof },
4400 { MKTAG('m','o','o','v'), mov_read_moov },
4401 { MKTAG('m','v','e','x'), mov_read_default },
4402 { MKTAG('m','v','h','d'), mov_read_mvhd },
4403 { MKTAG('S','M','I',' '), mov_read_svq3 },
4404 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
4405 { MKTAG('a','v','c','C'), mov_read_glbl },
4406 { MKTAG('p','a','s','p'), mov_read_pasp },
4407 { MKTAG('s','i','d','x'), mov_read_sidx },
4408 { MKTAG('s','t','b','l'), mov_read_default },
4409 { MKTAG('s','t','c','o'), mov_read_stco },
4410 { MKTAG('s','t','p','s'), mov_read_stps },
4411 { MKTAG('s','t','r','f'), mov_read_strf },
4412 { MKTAG('s','t','s','c'), mov_read_stsc },
4413 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
4414 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
4415 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
4416 { MKTAG('s','t','t','s'), mov_read_stts },
4417 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
4418 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
4419 { MKTAG('t','f','d','t'), mov_read_tfdt },
4420 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
4421 { MKTAG('t','r','a','k'), mov_read_trak },
4422 { MKTAG('t','r','a','f'), mov_read_default },
4423 { MKTAG('t','r','e','f'), mov_read_default },
4424 { MKTAG('t','m','c','d'), mov_read_tmcd },
4425 { MKTAG('c','h','a','p'), mov_read_chap },
4426 { MKTAG('t','r','e','x'), mov_read_trex },
4427 { MKTAG('t','r','u','n'), mov_read_trun },
4428 { MKTAG('u','d','t','a'), mov_read_default },
4429 { MKTAG('w','a','v','e'), mov_read_wave },
4430 { MKTAG('e','s','d','s'), mov_read_esds },
4431 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
4432 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
4433 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
4434 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
4435 { MKTAG('w','f','e','x'), mov_read_wfex },
4436 { MKTAG('c','m','o','v'), mov_read_cmov },
4437 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
4438 { MKTAG('d','v','c','1'), mov_read_dvc1 },
4439 { MKTAG('s','b','g','p'), mov_read_sbgp },
4440 { MKTAG('h','v','c','C'), mov_read_glbl },
4441 { MKTAG('u','u','i','d'), mov_read_uuid },
4442 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
4443 { MKTAG('f','r','e','e'), mov_read_free },
4444 { MKTAG('-','-','-','-'), mov_read_custom },
4445 { MKTAG('s','i','n','f'), mov_read_default },
4446 { MKTAG('f','r','m','a'), mov_read_frma },
4447 { MKTAG('s','e','n','c'), mov_read_senc },
4448 { MKTAG('s','a','i','z'), mov_read_saiz },
4452 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4454 int64_t total_size = 0;
4458 if (c->atom_depth > 10) {
4459 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
4460 return AVERROR_INVALIDDATA;
4465 atom.size = INT64_MAX;
4466 while (total_size + 8 <= atom.size && !avio_feof(pb)) {
4467 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
4470 if (atom.size >= 8) {
4471 a.size = avio_rb32(pb);
4472 a.type = avio_rl32(pb);
4473 if (a.type == MKTAG('f','r','e','e') &&
4477 uint32_t *type = (uint32_t *)buf + 1;
4478 if (avio_read(pb, buf, 8) != 8)
4479 return AVERROR_INVALIDDATA;
4480 avio_seek(pb, -8, SEEK_CUR);
4481 if (*type == MKTAG('m','v','h','d') ||
4482 *type == MKTAG('c','m','o','v')) {
4483 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
4484 a.type = MKTAG('m','o','o','v');
4487 if (atom.type != MKTAG('r','o','o','t') &&
4488 atom.type != MKTAG('m','o','o','v'))
4490 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
4492 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
4499 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
4500 a.size = avio_rb64(pb) - 8;
4504 av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
4505 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
4507 a.size = atom.size - total_size + 8;
4512 a.size = FFMIN(a.size, atom.size - total_size);
4514 for (i = 0; mov_default_parse_table[i].type; i++)
4515 if (mov_default_parse_table[i].type == a.type) {
4516 parse = mov_default_parse_table[i].parse;
4520 // container is user data
4521 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
4522 atom.type == MKTAG('i','l','s','t')))
4523 parse = mov_read_udta_string;
4525 // Supports parsing the QuickTime Metadata Keys.
4526 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
4527 if (!parse && c->found_hdlr_mdta &&
4528 atom.type == MKTAG('m','e','t','a') &&
4529 a.type == MKTAG('k','e','y','s')) {
4530 parse = mov_read_keys;
4533 if (!parse) { /* skip leaf atoms data */
4534 avio_skip(pb, a.size);
4536 int64_t start_pos = avio_tell(pb);
4538 int err = parse(c, pb, a);
4543 if (c->found_moov && c->found_mdat &&
4544 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
4545 start_pos + a.size == avio_size(pb))) {
4546 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
4547 c->next_root_atom = start_pos + a.size;
4551 left = a.size - avio_tell(pb) + start_pos;
4552 if (left > 0) /* skip garbage at atom end */
4553 avio_skip(pb, left);
4554 else if (left < 0) {
4555 av_log(c->fc, AV_LOG_WARNING,
4556 "overread end of atom '%.4s' by %"PRId64" bytes\n",
4557 (char*)&a.type, -left);
4558 avio_seek(pb, left, SEEK_CUR);
4562 total_size += a.size;
4565 if (total_size < atom.size && atom.size < 0x7ffff)
4566 avio_skip(pb, atom.size - total_size);
4572 static int mov_probe(AVProbeData *p)
4577 int moov_offset = -1;
4579 /* check file header */
4582 /* ignore invalid offset */
4583 if ((offset + 8) > (unsigned int)p->buf_size)
4585 tag = AV_RL32(p->buf + offset + 4);
4587 /* check for obvious tags */
4588 case MKTAG('m','o','o','v'):
4589 moov_offset = offset + 4;
4590 case MKTAG('m','d','a','t'):
4591 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
4592 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
4593 case MKTAG('f','t','y','p'):
4594 if (AV_RB32(p->buf+offset) < 8 &&
4595 (AV_RB32(p->buf+offset) != 1 ||
4596 offset + 12 > (unsigned int)p->buf_size ||
4597 AV_RB64(p->buf+offset + 8) == 0)) {
4598 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4599 } else if (tag == MKTAG('f','t','y','p') &&
4600 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
4601 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
4603 score = FFMAX(score, 5);
4605 score = AVPROBE_SCORE_MAX;
4607 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4609 /* those are more common words, so rate then a bit less */
4610 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
4611 case MKTAG('w','i','d','e'):
4612 case MKTAG('f','r','e','e'):
4613 case MKTAG('j','u','n','k'):
4614 case MKTAG('p','i','c','t'):
4615 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
4616 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4618 case MKTAG(0x82,0x82,0x7f,0x7d):
4619 case MKTAG('s','k','i','p'):
4620 case MKTAG('u','u','i','d'):
4621 case MKTAG('p','r','f','l'):
4622 /* if we only find those cause probedata is too small at least rate them */
4623 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4624 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4627 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4630 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
4631 /* moov atom in the header - we should make sure that this is not a
4632 * MOV-packed MPEG-PS */
4633 offset = moov_offset;
4635 while(offset < (p->buf_size - 16)){ /* Sufficient space */
4636 /* We found an actual hdlr atom */
4637 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
4638 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
4639 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
4640 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
4641 /* We found a media handler reference atom describing an
4642 * MPEG-PS-in-MOV, return a
4643 * low score to force expanding the probe window until
4644 * mpegps_probe finds what it needs */
4655 // must be done after parsing all trak because there's no order requirement
4656 static void mov_read_chapters(AVFormatContext *s)
4658 MOVContext *mov = s->priv_data;
4659 AVStream *st = NULL;
4660 MOVStreamContext *sc;
4664 for (i = 0; i < s->nb_streams; i++)
4665 if (s->streams[i]->id == mov->chapter_track) {
4670 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
4674 st->discard = AVDISCARD_ALL;
4676 cur_pos = avio_tell(sc->pb);
4678 for (i = 0; i < st->nb_index_entries; i++) {
4679 AVIndexEntry *sample = &st->index_entries[i];
4680 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
4685 if (end < sample->timestamp) {
4686 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
4687 end = AV_NOPTS_VALUE;
4690 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4691 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
4695 // the first two bytes are the length of the title
4696 len = avio_rb16(sc->pb);
4697 if (len > sample->size-2)
4699 title_len = 2*len + 1;
4700 if (!(title = av_mallocz(title_len)))
4703 // The samples could theoretically be in any encoding if there's an encd
4704 // atom following, but in practice are only utf-8 or utf-16, distinguished
4705 // instead by the presence of a BOM
4709 ch = avio_rb16(sc->pb);
4711 avio_get_str16be(sc->pb, len, title, title_len);
4712 else if (ch == 0xfffe)
4713 avio_get_str16le(sc->pb, len, title, title_len);
4716 if (len == 1 || len == 2)
4719 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
4723 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
4727 avio_seek(sc->pb, cur_pos, SEEK_SET);
4730 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
4731 uint32_t value, int flags)
4734 char buf[AV_TIMECODE_STR_SIZE];
4735 AVRational rate = st->avg_frame_rate;
4736 int ret = av_timecode_init(&tc, rate, flags, 0, s);
4739 av_dict_set(&st->metadata, "timecode",
4740 av_timecode_make_string(&tc, buf, value), 0);
4744 static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
4746 MOVStreamContext *sc = st->priv_data;
4747 char buf[AV_TIMECODE_STR_SIZE];
4748 int64_t cur_pos = avio_tell(sc->pb);
4749 int hh, mm, ss, ff, drop;
4751 if (!st->nb_index_entries)
4754 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
4755 avio_skip(s->pb, 13);
4756 hh = avio_r8(s->pb);
4757 mm = avio_r8(s->pb);
4758 ss = avio_r8(s->pb);
4759 drop = avio_r8(s->pb);
4760 ff = avio_r8(s->pb);
4761 snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
4762 hh, mm, ss, drop ? ';' : ':', ff);
4763 av_dict_set(&st->metadata, "timecode", buf, 0);
4765 avio_seek(sc->pb, cur_pos, SEEK_SET);
4769 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
4771 MOVStreamContext *sc = st->priv_data;
4773 int64_t cur_pos = avio_tell(sc->pb);
4776 if (!st->nb_index_entries)
4779 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
4780 value = avio_rb32(s->pb);
4782 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
4783 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
4784 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
4786 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
4787 * not the case) and thus assume "frame number format" instead of QT one.
4788 * No sample with tmcd track can be found with a QT timecode at the moment,
4789 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
4791 parse_timecode_in_framenum_format(s, st, value, flags);
4793 avio_seek(sc->pb, cur_pos, SEEK_SET);
4797 static int mov_read_close(AVFormatContext *s)
4799 MOVContext *mov = s->priv_data;
4802 for (i = 0; i < s->nb_streams; i++) {
4803 AVStream *st = s->streams[i];
4804 MOVStreamContext *sc = st->priv_data;
4809 av_freep(&sc->ctts_data);
4810 for (j = 0; j < sc->drefs_count; j++) {
4811 av_freep(&sc->drefs[j].path);
4812 av_freep(&sc->drefs[j].dir);
4814 av_freep(&sc->drefs);
4816 sc->drefs_count = 0;
4818 if (!sc->pb_is_copied)
4819 ff_format_io_close(s, &sc->pb);
4822 av_freep(&sc->chunk_offsets);
4823 av_freep(&sc->stsc_data);
4824 av_freep(&sc->sample_sizes);
4825 av_freep(&sc->keyframes);
4826 av_freep(&sc->stts_data);
4827 av_freep(&sc->stps_data);
4828 av_freep(&sc->elst_data);
4829 av_freep(&sc->rap_group);
4830 av_freep(&sc->display_matrix);
4832 for (j = 0; j < sc->stsd_count; j++)
4833 av_free(sc->extradata[j]);
4834 av_freep(&sc->extradata);
4835 av_freep(&sc->extradata_size);
4837 av_freep(&sc->cenc.auxiliary_info);
4838 av_freep(&sc->cenc.auxiliary_info_sizes);
4839 av_aes_ctr_free(sc->cenc.aes_ctr);
4842 if (mov->dv_demux) {
4843 avformat_free_context(mov->dv_fctx);
4844 mov->dv_fctx = NULL;
4847 if (mov->meta_keys) {
4848 for (i = 1; i < mov->meta_keys_count; i++) {
4849 av_freep(&mov->meta_keys[i]);
4851 av_freep(&mov->meta_keys);
4854 av_freep(&mov->trex_data);
4855 av_freep(&mov->bitrates);
4857 for (i = 0; i < mov->fragment_index_count; i++) {
4858 MOVFragmentIndex* index = mov->fragment_index_data[i];
4859 av_freep(&index->items);
4860 av_freep(&mov->fragment_index_data[i]);
4862 av_freep(&mov->fragment_index_data);
4864 av_freep(&mov->aes_decrypt);
4869 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
4873 for (i = 0; i < s->nb_streams; i++) {
4874 AVStream *st = s->streams[i];
4875 MOVStreamContext *sc = st->priv_data;
4877 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
4878 sc->timecode_track == tmcd_id)
4884 /* look for a tmcd track not referenced by any video track, and export it globally */
4885 static void export_orphan_timecode(AVFormatContext *s)
4889 for (i = 0; i < s->nb_streams; i++) {
4890 AVStream *st = s->streams[i];
4892 if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
4893 !tmcd_is_referenced(s, i + 1)) {
4894 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
4896 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
4903 static int read_tfra(MOVContext *mov, AVIOContext *f)
4905 MOVFragmentIndex* index = NULL;
4906 int version, fieldlength, i, j;
4907 int64_t pos = avio_tell(f);
4908 uint32_t size = avio_rb32(f);
4911 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
4914 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
4915 index = av_mallocz(sizeof(MOVFragmentIndex));
4917 return AVERROR(ENOMEM);
4920 tmp = av_realloc_array(mov->fragment_index_data,
4921 mov->fragment_index_count + 1,
4922 sizeof(MOVFragmentIndex*));
4925 return AVERROR(ENOMEM);
4927 mov->fragment_index_data = tmp;
4928 mov->fragment_index_data[mov->fragment_index_count++] = index;
4930 version = avio_r8(f);
4932 index->track_id = avio_rb32(f);
4933 fieldlength = avio_rb32(f);
4934 index->item_count = avio_rb32(f);
4935 index->items = av_mallocz_array(
4936 index->item_count, sizeof(MOVFragmentIndexItem));
4937 if (!index->items) {
4938 index->item_count = 0;
4939 return AVERROR(ENOMEM);
4941 for (i = 0; i < index->item_count; i++) {
4942 int64_t time, offset;
4944 time = avio_rb64(f);
4945 offset = avio_rb64(f);
4947 time = avio_rb32(f);
4948 offset = avio_rb32(f);
4950 index->items[i].time = time;
4951 index->items[i].moof_offset = offset;
4952 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
4954 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
4956 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
4960 avio_seek(f, pos + size, SEEK_SET);
4964 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
4966 int64_t stream_size = avio_size(f);
4967 int64_t original_pos = avio_tell(f);
4971 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
4975 mfra_size = avio_rb32(f);
4976 if (mfra_size < 0 || mfra_size > stream_size) {
4977 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
4980 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
4984 if (avio_rb32(f) != mfra_size) {
4985 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
4988 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
4989 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
4992 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
4994 ret = read_tfra(c, f);
5000 seek_ret = avio_seek(f, original_pos, SEEK_SET);
5002 av_log(c->fc, AV_LOG_ERROR,
5003 "failed to seek back after looking for mfra\n");
5009 static int mov_read_header(AVFormatContext *s)
5011 MOVContext *mov = s->priv_data;
5012 AVIOContext *pb = s->pb;
5014 MOVAtom atom = { AV_RL32("root") };
5017 if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
5018 av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
5019 mov->decryption_key_len, AES_CTR_KEY_SIZE);
5020 return AVERROR(EINVAL);
5024 mov->trak_index = -1;
5025 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
5027 atom.size = avio_size(pb);
5029 atom.size = INT64_MAX;
5031 /* check MOV header */
5033 if (mov->moov_retry)
5034 avio_seek(pb, 0, SEEK_SET);
5035 if ((err = mov_read_default(mov, pb, atom)) < 0) {
5036 av_log(s, AV_LOG_ERROR, "error reading header\n");
5040 } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
5041 if (!mov->found_moov) {
5042 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
5044 return AVERROR_INVALIDDATA;
5046 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
5049 if (mov->chapter_track > 0 && !mov->ignore_chapters)
5050 mov_read_chapters(s);
5051 for (i = 0; i < s->nb_streams; i++)
5052 if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
5053 mov_read_timecode_track(s, s->streams[i]);
5054 } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
5055 mov_read_rtmd_track(s, s->streams[i]);
5059 /* copy timecode metadata from tmcd tracks to the related video streams */
5060 for (i = 0; i < s->nb_streams; i++) {
5061 AVStream *st = s->streams[i];
5062 MOVStreamContext *sc = st->priv_data;
5063 if (sc->timecode_track > 0) {
5064 AVDictionaryEntry *tcr;
5065 int tmcd_st_id = -1;
5067 for (j = 0; j < s->nb_streams; j++)
5068 if (s->streams[j]->id == sc->timecode_track)
5071 if (tmcd_st_id < 0 || tmcd_st_id == i)
5073 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
5075 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
5078 export_orphan_timecode(s);
5080 for (i = 0; i < s->nb_streams; i++) {
5081 AVStream *st = s->streams[i];
5082 MOVStreamContext *sc = st->priv_data;
5083 fix_timescale(mov, sc);
5084 if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
5085 st->skip_samples = sc->start_pad;
5087 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
5088 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
5089 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
5090 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5091 if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
5092 st->codecpar->width = sc->width;
5093 st->codecpar->height = sc->height;
5095 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
5096 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
5100 if (mov->handbrake_version &&
5101 mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
5102 st->codecpar->codec_id == AV_CODEC_ID_MP3
5104 av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
5105 st->need_parsing = AVSTREAM_PARSE_FULL;
5109 if (mov->trex_data) {
5110 for (i = 0; i < s->nb_streams; i++) {
5111 AVStream *st = s->streams[i];
5112 MOVStreamContext *sc = st->priv_data;
5113 if (st->duration > 0)
5114 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
5118 if (mov->use_mfra_for > 0) {
5119 for (i = 0; i < s->nb_streams; i++) {
5120 AVStream *st = s->streams[i];
5121 MOVStreamContext *sc = st->priv_data;
5122 if (sc->duration_for_fps > 0) {
5123 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
5124 sc->duration_for_fps;
5129 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
5130 if (mov->bitrates[i]) {
5131 s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
5135 ff_rfps_calculate(s);
5137 for (i = 0; i < s->nb_streams; i++) {
5138 AVStream *st = s->streams[i];
5139 MOVStreamContext *sc = st->priv_data;
5141 switch (st->codecpar->codec_type) {
5142 case AVMEDIA_TYPE_AUDIO:
5143 err = ff_replaygain_export(st, s->metadata);
5149 case AVMEDIA_TYPE_VIDEO:
5150 if (sc->display_matrix) {
5151 AVPacketSideData *sd, *tmp;
5153 tmp = av_realloc_array(st->side_data,
5154 st->nb_side_data + 1, sizeof(*tmp));
5156 return AVERROR(ENOMEM);
5158 st->side_data = tmp;
5161 sd = &st->side_data[st->nb_side_data - 1];
5162 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
5163 sd->size = sizeof(int32_t) * 9;
5164 sd->data = (uint8_t*)sc->display_matrix;
5165 sc->display_matrix = NULL;
5170 ff_configure_buffers_for_index(s, AV_TIME_BASE);
5175 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
5177 AVIndexEntry *sample = NULL;
5178 int64_t best_dts = INT64_MAX;
5180 for (i = 0; i < s->nb_streams; i++) {
5181 AVStream *avst = s->streams[i];
5182 MOVStreamContext *msc = avst->priv_data;
5183 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
5184 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
5185 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
5186 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
5187 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
5189 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
5190 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
5191 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
5192 sample = current_sample;
5201 static int should_retry(AVIOContext *pb, int error_code) {
5202 if (error_code == AVERROR_EOF || avio_feof(pb))
5208 static int mov_switch_root(AVFormatContext *s, int64_t target)
5210 MOVContext *mov = s->priv_data;
5212 int already_read = 0;
5214 if (avio_seek(s->pb, target, SEEK_SET) != target) {
5215 av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
5216 return AVERROR_INVALIDDATA;
5219 mov->next_root_atom = 0;
5221 for (i = 0; i < mov->fragment_index_count; i++) {
5222 MOVFragmentIndex *index = mov->fragment_index_data[i];
5224 for (j = 0; j < index->item_count; j++) {
5225 MOVFragmentIndexItem *item = &index->items[j];
5227 mov->next_root_atom = item->moof_offset;
5228 break; // Advance to next index in outer loop
5229 } else if (item->moof_offset == target) {
5230 index->current_item = FFMIN(j, index->current_item);
5231 if (item->headers_read)
5233 item->headers_read = 1;
5238 index->current_item = 0;
5244 mov->found_mdat = 0;
5246 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
5249 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
5254 static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
5256 uint8_t *side, *extradata;
5259 /* Save the current index. */
5260 sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
5262 /* Notify the decoder that extradata changed. */
5263 extradata_size = sc->extradata_size[sc->last_stsd_index];
5264 extradata = sc->extradata[sc->last_stsd_index];
5265 if (extradata_size > 0 && extradata) {
5266 side = av_packet_new_side_data(pkt,
5267 AV_PKT_DATA_NEW_EXTRADATA,
5270 return AVERROR(ENOMEM);
5271 memcpy(side, extradata, extradata_size);
5277 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
5279 MOVContext *mov = s->priv_data;
5280 MOVStreamContext *sc;
5281 AVIndexEntry *sample;
5282 AVStream *st = NULL;
5286 sample = mov_find_next_sample(s, &st);
5287 if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
5288 if (!mov->next_root_atom)
5290 if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
5295 /* must be done just before reading, to avoid infinite loop on sample */
5296 sc->current_sample++;
5298 if (mov->next_root_atom) {
5299 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
5300 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
5303 if (st->discard != AVDISCARD_ALL) {
5304 int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
5305 if (ret64 != sample->pos) {
5306 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
5307 sc->ffindex, sample->pos);
5308 sc->current_sample -= should_retry(sc->pb, ret64);
5309 return AVERROR_INVALIDDATA;
5312 if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
5313 av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
5317 ret = av_get_packet(sc->pb, pkt, sample->size);
5319 sc->current_sample -= should_retry(sc->pb, ret);
5322 if (sc->has_palette) {
5325 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
5327 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
5329 memcpy(pal, sc->palette, AVPALETTE_SIZE);
5330 sc->has_palette = 0;
5333 #if CONFIG_DV_DEMUXER
5334 if (mov->dv_demux && sc->dv_audio_container) {
5335 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
5336 av_freep(&pkt->data);
5338 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
5345 pkt->stream_index = sc->ffindex;
5346 pkt->dts = sample->timestamp;
5347 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
5348 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
5349 /* update ctts context */
5351 if (sc->ctts_index < sc->ctts_count &&
5352 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
5354 sc->ctts_sample = 0;
5357 pkt->dts = AV_NOPTS_VALUE;
5359 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
5360 st->index_entries[sc->current_sample].timestamp : st->duration;
5361 pkt->duration = next_dts - pkt->dts;
5362 pkt->pts = pkt->dts;
5364 if (st->discard == AVDISCARD_ALL)
5366 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
5367 pkt->pos = sample->pos;
5369 /* Multiple stsd handling. */
5370 if (sc->stsc_data) {
5371 /* Keep track of the stsc index for the given sample, then check
5372 * if the stsd index is different from the last used one. */
5374 if (sc->stsc_index < sc->stsc_count - 1 &&
5375 mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
5377 sc->stsc_sample = 0;
5378 /* Do not check indexes after a switch. */
5379 } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
5380 sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
5381 sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
5382 ret = mov_change_extradata(sc, pkt);
5389 aax_filter(pkt->data, pkt->size, mov);
5391 if (sc->cenc.aes_ctr) {
5392 ret = cenc_filter(mov, sc, pkt->data, pkt->size);
5401 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
5403 MOVContext *mov = s->priv_data;
5406 if (!mov->fragment_index_complete)
5409 for (i = 0; i < mov->fragment_index_count; i++) {
5410 if (mov->fragment_index_data[i]->track_id == st->id) {
5411 MOVFragmentIndex *index = mov->fragment_index_data[i];
5412 for (j = index->item_count - 1; j >= 0; j--) {
5413 if (index->items[j].time <= timestamp) {
5414 if (index->items[j].headers_read)
5417 return mov_switch_root(s, index->items[j].moof_offset);
5426 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
5428 MOVStreamContext *sc = st->priv_data;
5429 int sample, time_sample;
5432 int ret = mov_seek_fragment(s, st, timestamp);
5436 sample = av_index_search_timestamp(st, timestamp, flags);
5437 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
5438 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
5440 if (sample < 0) /* not sure what to do */
5441 return AVERROR_INVALIDDATA;
5442 sc->current_sample = sample;
5443 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
5444 /* adjust ctts index */
5445 if (sc->ctts_data) {
5447 for (i = 0; i < sc->ctts_count; i++) {
5448 int next = time_sample + sc->ctts_data[i].count;
5449 if (next > sc->current_sample) {
5451 sc->ctts_sample = sc->current_sample - time_sample;
5458 /* adjust stsd index */
5460 for (i = 0; i < sc->stsc_count; i++) {
5461 int next = time_sample + mov_get_stsc_samples(sc, i);
5462 if (next > sc->current_sample) {
5464 sc->stsc_sample = sc->current_sample - time_sample;
5470 ret = mov_seek_auxiliary_info(s, sc);
5478 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
5480 MOVContext *mc = s->priv_data;
5485 if (stream_index >= s->nb_streams)
5486 return AVERROR_INVALIDDATA;
5488 st = s->streams[stream_index];
5489 sample = mov_seek_stream(s, st, sample_time, flags);
5493 if (mc->seek_individually) {
5494 /* adjust seek timestamp to found sample timestamp */
5495 int64_t seek_timestamp = st->index_entries[sample].timestamp;
5497 for (i = 0; i < s->nb_streams; i++) {
5499 MOVStreamContext *sc = s->streams[i]->priv_data;
5501 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
5503 if (stream_index == i)
5506 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
5507 mov_seek_stream(s, st, timestamp, flags);
5510 for (i = 0; i < s->nb_streams; i++) {
5511 MOVStreamContext *sc;
5514 sc->current_sample = 0;
5517 MOVStreamContext *sc;
5518 AVIndexEntry *entry = mov_find_next_sample(s, &st);
5520 return AVERROR_INVALIDDATA;
5522 if (sc->ffindex == stream_index && sc->current_sample == sample)
5524 sc->current_sample++;
5530 #define OFFSET(x) offsetof(MOVContext, x)
5531 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
5532 static const AVOption mov_options[] = {
5533 {"use_absolute_path",
5534 "allow using absolute path when opening alias, this is a possible security issue",
5535 OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
5537 {"seek_streams_individually",
5538 "Seek each stream individually to the to the closest point",
5539 OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
5541 {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
5543 {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
5546 "use mfra for fragment timestamps",
5547 OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
5548 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
5550 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
5551 FLAGS, "use_mfra_for" },
5552 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
5553 FLAGS, "use_mfra_for" },
5554 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
5555 FLAGS, "use_mfra_for" },
5556 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
5557 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5558 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
5559 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5560 { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
5561 AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5562 { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
5563 "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
5564 AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
5565 .flags = AV_OPT_FLAG_DECODING_PARAM },
5566 { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5567 { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
5568 {.i64 = 0}, 0, 1, FLAGS },
5573 static const AVClass mov_class = {
5574 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
5575 .item_name = av_default_item_name,
5576 .option = mov_options,
5577 .version = LIBAVUTIL_VERSION_INT,
5580 AVInputFormat ff_mov_demuxer = {
5581 .name = "mov,mp4,m4a,3gp,3g2,mj2",
5582 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5583 .priv_class = &mov_class,
5584 .priv_data_size = sizeof(MOVContext),
5585 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
5586 .read_probe = mov_probe,
5587 .read_header = mov_read_header,
5588 .read_packet = mov_read_packet,
5589 .read_close = mov_read_close,
5590 .read_seek = mov_read_seek,
5591 .flags = AVFMT_NO_BYTE_SEEK,