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/avassert.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/display.h"
41 #include "libavutil/opt.h"
42 #include "libavutil/aes.h"
43 #include "libavutil/aes_ctr.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/sha.h"
46 #include "libavutil/spherical.h"
47 #include "libavutil/stereo3d.h"
48 #include "libavutil/timecode.h"
49 #include "libavcodec/ac3tab.h"
50 #include "libavcodec/flac.h"
51 #include "libavcodec/mpegaudiodecheader.h"
54 #include "avio_internal.h"
57 #include "libavcodec/get_bits.h"
60 #include "replaygain.h"
66 #include "qtpalette.h"
68 /* those functions parse an atom */
69 /* links atom IDs to parse functions */
70 typedef struct MOVParseTableEntry {
72 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
75 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
76 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
77 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
78 int count, int duration);
80 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
81 unsigned len, const char *key)
85 short current, total = 0;
86 avio_rb16(pb); // unknown
87 current = avio_rb16(pb);
89 total = avio_rb16(pb);
91 snprintf(buf, sizeof(buf), "%d", current);
93 snprintf(buf, sizeof(buf), "%d/%d", current, total);
94 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
95 av_dict_set(&c->fc->metadata, key, buf, 0);
100 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
101 unsigned len, const char *key)
103 /* bypass padding bytes */
108 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
109 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
114 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
115 unsigned len, const char *key)
117 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
118 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
123 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
124 unsigned len, const char *key)
128 avio_r8(pb); // unknown
131 if (genre < 1 || genre > ID3v1_GENRE_MAX)
133 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
134 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
139 static const uint32_t mac_to_unicode[128] = {
140 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
141 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
142 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
143 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
144 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
145 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
146 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
147 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
148 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
149 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
150 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
151 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
152 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
153 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
154 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
155 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
158 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
159 char *dst, int dstlen)
162 char *end = dst+dstlen-1;
165 for (i = 0; i < len; i++) {
166 uint8_t t, c = avio_r8(pb);
174 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
180 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
184 MOVStreamContext *sc;
189 case 0xd: id = AV_CODEC_ID_MJPEG; break;
190 case 0xe: id = AV_CODEC_ID_PNG; break;
191 case 0x1b: id = AV_CODEC_ID_BMP; break;
193 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
198 st = avformat_new_stream(c->fc, NULL);
200 return AVERROR(ENOMEM);
201 sc = av_mallocz(sizeof(*sc));
203 return AVERROR(ENOMEM);
206 ret = av_get_packet(pb, &pkt, len);
210 if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
211 if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
212 id = AV_CODEC_ID_PNG;
214 id = AV_CODEC_ID_MJPEG;
218 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
220 st->attached_pic = pkt;
221 st->attached_pic.stream_index = st->index;
222 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
224 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
225 st->codecpar->codec_id = id;
231 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
233 char language[4] = { 0 };
234 char buf[200], place[100];
235 uint16_t langcode = 0;
236 double longitude, latitude, altitude;
237 const char *key = "location";
239 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
240 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
241 return AVERROR_INVALIDDATA;
244 avio_skip(pb, 4); // version+flags
245 langcode = avio_rb16(pb);
246 ff_mov_lang_to_iso639(langcode, language);
249 len -= avio_get_str(pb, len, place, sizeof(place));
251 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
252 return AVERROR_INVALIDDATA;
254 avio_skip(pb, 1); // role
258 av_log(c->fc, AV_LOG_ERROR,
259 "loci too short (%u bytes left, need at least %d)\n", len, 12);
260 return AVERROR_INVALIDDATA;
262 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
263 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
264 altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
266 // Try to output in the same format as the ?xyz field
267 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
269 av_strlcatf(buf, sizeof(buf), "%+f", altitude);
270 av_strlcatf(buf, sizeof(buf), "/%s", place);
272 if (*language && strcmp(language, "und")) {
274 snprintf(key2, sizeof(key2), "%s-%s", key, language);
275 av_dict_set(&c->fc->metadata, key2, buf, 0);
277 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
278 return av_dict_set(&c->fc->metadata, key, buf, 0);
281 static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
287 if (c->ignore_chapters)
290 n_hmmt = avio_rb32(pb);
291 for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
292 int moment_time = avio_rb32(pb);
293 avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
298 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
301 char key2[32], language[4] = {0};
303 const char *key = NULL;
304 uint16_t langcode = 0;
305 uint32_t data_type = 0, str_size, str_size_alloc;
306 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
311 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
312 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
313 case MKTAG( 'X','M','P','_'):
314 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
315 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
316 case MKTAG( 'a','k','I','D'): key = "account_type";
317 parse = mov_metadata_int8_no_padding; break;
318 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
319 case MKTAG( 'c','a','t','g'): key = "category"; break;
320 case MKTAG( 'c','p','i','l'): key = "compilation";
321 parse = mov_metadata_int8_no_padding; break;
322 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
323 case MKTAG( 'd','e','s','c'): key = "description"; break;
324 case MKTAG( 'd','i','s','k'): key = "disc";
325 parse = mov_metadata_track_or_disc_number; break;
326 case MKTAG( 'e','g','i','d'): key = "episode_uid";
327 parse = mov_metadata_int8_no_padding; break;
328 case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
329 case MKTAG( 'g','n','r','e'): key = "genre";
330 parse = mov_metadata_gnre; break;
331 case MKTAG( 'h','d','v','d'): key = "hd_video";
332 parse = mov_metadata_int8_no_padding; break;
333 case MKTAG( 'H','M','M','T'):
334 return mov_metadata_hmmt(c, pb, atom.size);
335 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
336 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
337 case MKTAG( 'l','o','c','i'):
338 return mov_metadata_loci(c, pb, atom.size);
339 case MKTAG( 'p','c','s','t'): key = "podcast";
340 parse = mov_metadata_int8_no_padding; break;
341 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
342 parse = mov_metadata_int8_no_padding; break;
343 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
344 case MKTAG( 'r','t','n','g'): key = "rating";
345 parse = mov_metadata_int8_no_padding; break;
346 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
347 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
348 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
349 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
350 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
351 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
352 case MKTAG( 's','t','i','k'): key = "media_type";
353 parse = mov_metadata_int8_no_padding; break;
354 case MKTAG( 't','r','k','n'): key = "track";
355 parse = mov_metadata_track_or_disc_number; break;
356 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
357 case MKTAG( 't','v','e','s'): key = "episode_sort";
358 parse = mov_metadata_int8_bypass_padding; break;
359 case MKTAG( 't','v','n','n'): key = "network"; break;
360 case MKTAG( 't','v','s','h'): key = "show"; break;
361 case MKTAG( 't','v','s','n'): key = "season_number";
362 parse = mov_metadata_int8_bypass_padding; break;
363 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
364 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
365 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
366 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
367 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
368 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
369 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
370 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
371 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
372 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
373 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
374 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
375 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
376 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
377 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
378 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
379 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
380 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
381 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
382 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
383 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
384 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
385 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
386 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
387 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
388 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
389 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
390 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
391 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
392 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
393 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
394 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
395 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
396 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
397 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
400 if (c->itunes_metadata && atom.size > 8) {
401 int data_size = avio_rb32(pb);
402 int tag = avio_rl32(pb);
403 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
404 data_type = avio_rb32(pb); // type
405 avio_rb32(pb); // unknown
406 str_size = data_size - 16;
409 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
410 int ret = mov_read_covr(c, pb, data_type, str_size);
412 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
415 } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
416 uint32_t index = AV_RB32(&atom.type);
417 if (index < c->meta_keys_count && index > 0) {
418 key = c->meta_keys[index];
420 av_log(c->fc, AV_LOG_WARNING,
421 "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n",
422 index, c->meta_keys_count);
426 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
427 str_size = avio_rb16(pb); // string length
428 if (str_size > atom.size) {
430 avio_seek(pb, -2, SEEK_CUR);
431 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
434 langcode = avio_rb16(pb);
435 ff_mov_lang_to_iso639(langcode, language);
438 str_size = atom.size;
440 if (c->export_all && !key) {
441 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
447 if (atom.size < 0 || str_size >= INT_MAX/2)
448 return AVERROR_INVALIDDATA;
450 // Allocates enough space if data_type is a int32 or float32 number, otherwise
451 // worst-case requirement for output string in case of utf8 coded input
452 num = (data_type >= 21 && data_type <= 23);
453 str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
454 str = av_mallocz(str_size_alloc);
456 return AVERROR(ENOMEM);
459 parse(c, pb, str_size, key);
461 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
462 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
463 } else if (data_type == 21) { // BE signed integer, variable size
466 val = (int8_t)avio_r8(pb);
467 else if (str_size == 2)
468 val = (int16_t)avio_rb16(pb);
469 else if (str_size == 3)
470 val = ((int32_t)(avio_rb24(pb)<<8))>>8;
471 else if (str_size == 4)
472 val = (int32_t)avio_rb32(pb);
473 if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
474 av_log(c->fc, AV_LOG_ERROR,
475 "Failed to store the number (%d) in string.\n", val);
477 return AVERROR_INVALIDDATA;
479 } else if (data_type == 22) { // BE unsigned integer, variable size
480 unsigned int val = 0;
483 else if (str_size == 2)
485 else if (str_size == 3)
487 else if (str_size == 4)
489 if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
490 av_log(c->fc, AV_LOG_ERROR,
491 "Failed to store the number (%u) in string.\n", val);
493 return AVERROR_INVALIDDATA;
495 } else if (data_type == 23 && str_size >= 4) { // BE float32
496 float val = av_int2float(avio_rb32(pb));
497 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
498 av_log(c->fc, AV_LOG_ERROR,
499 "Failed to store the float32 number (%f) in string.\n", val);
501 return AVERROR_INVALIDDATA;
504 int ret = ffio_read_size(pb, str, str_size);
511 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
512 av_dict_set(&c->fc->metadata, key, str, 0);
513 if (*language && strcmp(language, "und")) {
514 snprintf(key2, sizeof(key2), "%s-%s", key, language);
515 av_dict_set(&c->fc->metadata, key2, str, 0);
517 if (!strcmp(key, "encoder")) {
518 int major, minor, micro;
519 if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, µ) == 3) {
520 c->handbrake_version = 1000000*major + 1000*minor + micro;
529 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
532 int i, nb_chapters, str_len, version;
536 if (c->ignore_chapters)
539 if ((atom.size -= 5) < 0)
542 version = avio_r8(pb);
545 avio_rb32(pb); // ???
546 nb_chapters = avio_r8(pb);
548 for (i = 0; i < nb_chapters; i++) {
552 start = avio_rb64(pb);
553 str_len = avio_r8(pb);
555 if ((atom.size -= 9+str_len) < 0)
558 ret = ffio_read_size(pb, str, str_len);
562 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
567 #define MIN_DATA_ENTRY_BOX_SIZE 12
568 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
571 MOVStreamContext *sc;
574 if (c->fc->nb_streams < 1)
576 st = c->fc->streams[c->fc->nb_streams-1];
579 avio_rb32(pb); // version + flags
580 entries = avio_rb32(pb);
582 entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
583 entries >= UINT_MAX / sizeof(*sc->drefs))
584 return AVERROR_INVALIDDATA;
588 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
590 return AVERROR(ENOMEM);
591 sc->drefs_count = entries;
593 for (i = 0; i < entries; i++) {
594 MOVDref *dref = &sc->drefs[i];
595 uint32_t size = avio_rb32(pb);
596 int64_t next = avio_tell(pb) + size - 4;
599 return AVERROR_INVALIDDATA;
601 dref->type = avio_rl32(pb);
602 avio_rb32(pb); // version + flags
604 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
605 /* macintosh alias record */
606 uint16_t volume_len, len;
612 volume_len = avio_r8(pb);
613 volume_len = FFMIN(volume_len, 27);
614 ret = ffio_read_size(pb, dref->volume, 27);
617 dref->volume[volume_len] = 0;
618 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
623 len = FFMIN(len, 63);
624 ret = ffio_read_size(pb, dref->filename, 63);
627 dref->filename[len] = 0;
628 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
632 /* read next level up_from_alias/down_to_target */
633 dref->nlvl_from = avio_rb16(pb);
634 dref->nlvl_to = avio_rb16(pb);
635 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
636 dref->nlvl_from, dref->nlvl_to);
640 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
643 type = avio_rb16(pb);
645 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
648 if (type == 2) { // absolute path
650 dref->path = av_mallocz(len+1);
652 return AVERROR(ENOMEM);
654 ret = ffio_read_size(pb, dref->path, len);
656 av_freep(&dref->path);
659 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
661 memmove(dref->path, dref->path+volume_len, len);
664 // trim string of any ending zeros
665 for (j = len - 1; j >= 0; j--) {
666 if (dref->path[j] == 0)
671 for (j = 0; j < len; j++)
672 if (dref->path[j] == ':' || dref->path[j] == 0)
674 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
675 } else if (type == 0) { // directory name
677 dref->dir = av_malloc(len+1);
679 return AVERROR(ENOMEM);
681 ret = ffio_read_size(pb, dref->dir, len);
683 av_freep(&dref->dir);
687 for (j = 0; j < len; j++)
688 if (dref->dir[j] == ':')
690 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
695 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n",
700 avio_seek(pb, next, SEEK_SET);
705 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
714 avio_r8(pb); /* version */
715 avio_rb24(pb); /* flags */
718 ctype = avio_rl32(pb);
719 type = avio_rl32(pb); /* component subtype */
721 av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype));
722 av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type));
724 if (c->trak_index < 0) { // meta not inside a trak
725 if (type == MKTAG('m','d','t','a')) {
726 c->found_hdlr_mdta = 1;
731 st = c->fc->streams[c->fc->nb_streams-1];
733 if (type == MKTAG('v','i','d','e'))
734 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
735 else if (type == MKTAG('s','o','u','n'))
736 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
737 else if (type == MKTAG('m','1','a',' '))
738 st->codecpar->codec_id = AV_CODEC_ID_MP2;
739 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
740 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
742 avio_rb32(pb); /* component manufacture */
743 avio_rb32(pb); /* component flags */
744 avio_rb32(pb); /* component flags mask */
746 title_size = atom.size - 24;
747 if (title_size > 0) {
748 if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
749 return AVERROR_INVALIDDATA;
750 title_str = av_malloc(title_size + 1); /* Add null terminator */
752 return AVERROR(ENOMEM);
754 ret = ffio_read_size(pb, title_str, title_size);
756 av_freep(&title_str);
759 title_str[title_size] = 0;
761 int off = (!c->isom && title_str[0] == title_size - 1);
762 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
764 av_freep(&title_str);
770 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
775 if (fc->nb_streams < 1)
777 st = fc->streams[fc->nb_streams-1];
779 avio_rb32(pb); /* version + flags */
780 ff_mp4_read_descr(fc, pb, &tag);
781 if (tag == MP4ESDescrTag) {
782 ff_mp4_parse_es_descr(pb, NULL);
784 avio_rb16(pb); /* ID */
786 ff_mp4_read_descr(fc, pb, &tag);
787 if (tag == MP4DecConfigDescrTag)
788 ff_mp4_read_dec_config_descr(fc, st, pb);
792 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
794 return ff_mov_read_esds(c->fc, pb);
797 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
800 enum AVAudioServiceType *ast;
801 int ac3info, acmod, lfeon, bsmod;
803 if (c->fc->nb_streams < 1)
805 st = c->fc->streams[c->fc->nb_streams-1];
807 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
810 return AVERROR(ENOMEM);
812 ac3info = avio_rb24(pb);
813 bsmod = (ac3info >> 14) & 0x7;
814 acmod = (ac3info >> 11) & 0x7;
815 lfeon = (ac3info >> 10) & 0x1;
816 st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
817 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
819 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
821 if (st->codecpar->channels > 1 && bsmod == 0x7)
822 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
824 #if FF_API_LAVF_AVCTX
825 FF_DISABLE_DEPRECATION_WARNINGS
826 st->codec->audio_service_type = *ast;
827 FF_ENABLE_DEPRECATION_WARNINGS
833 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
836 enum AVAudioServiceType *ast;
837 int eac3info, acmod, lfeon, bsmod;
839 if (c->fc->nb_streams < 1)
841 st = c->fc->streams[c->fc->nb_streams-1];
843 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
846 return AVERROR(ENOMEM);
848 /* No need to parse fields for additional independent substreams and its
849 * associated dependent substreams since libavcodec's E-AC-3 decoder
850 * does not support them yet. */
851 avio_rb16(pb); /* data_rate and num_ind_sub */
852 eac3info = avio_rb24(pb);
853 bsmod = (eac3info >> 12) & 0x1f;
854 acmod = (eac3info >> 9) & 0x7;
855 lfeon = (eac3info >> 8) & 0x1;
856 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
858 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
859 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
861 if (st->codecpar->channels > 1 && bsmod == 0x7)
862 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
864 #if FF_API_LAVF_AVCTX
865 FF_DISABLE_DEPRECATION_WARNINGS
866 st->codec->audio_service_type = *ast;
867 FF_ENABLE_DEPRECATION_WARNINGS
873 static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
875 const uint32_t ddts_size = 20;
878 uint32_t frame_duration_code = 0;
879 uint32_t channel_layout_code = 0;
882 buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE);
884 return AVERROR(ENOMEM);
886 if (avio_read(pb, buf, ddts_size) < ddts_size) {
888 return AVERROR_INVALIDDATA;
891 init_get_bits(&gb, buf, 8*ddts_size);
893 if (c->fc->nb_streams < 1) {
897 st = c->fc->streams[c->fc->nb_streams-1];
899 st->codecpar->sample_rate = get_bits_long(&gb, 32);
900 if (st->codecpar->sample_rate <= 0) {
901 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
903 return AVERROR_INVALIDDATA;
905 skip_bits_long(&gb, 32); /* max bitrate */
906 st->codecpar->bit_rate = get_bits_long(&gb, 32);
907 st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
908 frame_duration_code = get_bits(&gb, 2);
909 skip_bits(&gb, 30); /* various fields */
910 channel_layout_code = get_bits(&gb, 16);
912 st->codecpar->frame_size =
913 (frame_duration_code == 0) ? 512 :
914 (frame_duration_code == 1) ? 1024 :
915 (frame_duration_code == 2) ? 2048 :
916 (frame_duration_code == 3) ? 4096 : 0;
918 if (channel_layout_code > 0xff) {
919 av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
921 st->codecpar->channel_layout =
922 ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
923 ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
924 ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
925 ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
926 ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
927 ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
929 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
935 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
939 if (c->fc->nb_streams < 1)
941 st = c->fc->streams[c->fc->nb_streams-1];
946 /* skip version and flags */
949 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
954 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
959 if (c->fc->nb_streams < 1)
961 st = c->fc->streams[c->fc->nb_streams-1];
963 if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
964 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
969 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
971 const int num = avio_rb32(pb);
972 const int den = avio_rb32(pb);
975 if (c->fc->nb_streams < 1)
977 st = c->fc->streams[c->fc->nb_streams-1];
979 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
980 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
981 av_log(c->fc, AV_LOG_WARNING,
982 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
983 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
985 } else if (den != 0) {
986 av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
992 /* this atom contains actual media data */
993 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
995 if (atom.size == 0) /* wrong one (MP4) */
998 return 0; /* now go for moov */
1001 #define DRM_BLOB_SIZE 56
1003 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1005 uint8_t intermediate_key[20];
1006 uint8_t intermediate_iv[20];
1009 uint8_t file_checksum[20];
1010 uint8_t calculated_checksum[20];
1014 uint8_t *activation_bytes = c->activation_bytes;
1015 uint8_t *fixed_key = c->audible_fixed_key;
1019 sha = av_sha_alloc();
1021 return AVERROR(ENOMEM);
1022 c->aes_decrypt = av_aes_alloc();
1023 if (!c->aes_decrypt) {
1024 ret = AVERROR(ENOMEM);
1028 /* drm blob processing */
1029 avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
1030 avio_read(pb, input, DRM_BLOB_SIZE);
1031 avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
1032 avio_read(pb, file_checksum, 20);
1034 av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
1035 for (i = 0; i < 20; i++)
1036 av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
1037 av_log(c->fc, AV_LOG_INFO, "\n");
1039 /* verify activation data */
1040 if (!activation_bytes) {
1041 av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
1042 ret = 0; /* allow ffprobe to continue working on .aax files */
1045 if (c->activation_bytes_size != 4) {
1046 av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
1047 ret = AVERROR(EINVAL);
1051 /* verify fixed key */
1052 if (c->audible_fixed_key_size != 16) {
1053 av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
1054 ret = AVERROR(EINVAL);
1058 /* AAX (and AAX+) key derivation */
1059 av_sha_init(sha, 160);
1060 av_sha_update(sha, fixed_key, 16);
1061 av_sha_update(sha, activation_bytes, 4);
1062 av_sha_final(sha, intermediate_key);
1063 av_sha_init(sha, 160);
1064 av_sha_update(sha, fixed_key, 16);
1065 av_sha_update(sha, intermediate_key, 20);
1066 av_sha_update(sha, activation_bytes, 4);
1067 av_sha_final(sha, intermediate_iv);
1068 av_sha_init(sha, 160);
1069 av_sha_update(sha, intermediate_key, 16);
1070 av_sha_update(sha, intermediate_iv, 16);
1071 av_sha_final(sha, calculated_checksum);
1072 if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
1073 av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
1074 ret = AVERROR_INVALIDDATA;
1077 av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
1078 av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
1079 for (i = 0; i < 4; i++) {
1080 // file data (in output) is stored in big-endian mode
1081 if (activation_bytes[i] != output[3 - i]) { // critical error
1082 av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
1083 ret = AVERROR_INVALIDDATA;
1087 memcpy(c->file_key, output + 8, 16);
1088 memcpy(input, output + 26, 16);
1089 av_sha_init(sha, 160);
1090 av_sha_update(sha, input, 16);
1091 av_sha_update(sha, c->file_key, 16);
1092 av_sha_update(sha, fixed_key, 16);
1093 av_sha_final(sha, c->file_iv);
1101 // Audible AAX (and AAX+) bytestream decryption
1102 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1105 unsigned char iv[16];
1107 memcpy(iv, c->file_iv, 16); // iv is overwritten
1108 blocks = size >> 4; // trailing bytes are not encrypted!
1109 av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1110 av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1115 /* read major brand, minor version and compatible brands and store them as metadata */
1116 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1119 int comp_brand_size;
1120 char* comp_brands_str;
1121 uint8_t type[5] = {0};
1122 int ret = ffio_read_size(pb, type, 4);
1126 if (strcmp(type, "qt "))
1128 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1129 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1130 minor_ver = avio_rb32(pb); /* minor version */
1131 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1133 comp_brand_size = atom.size - 8;
1134 if (comp_brand_size < 0)
1135 return AVERROR_INVALIDDATA;
1136 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1137 if (!comp_brands_str)
1138 return AVERROR(ENOMEM);
1140 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1142 av_freep(&comp_brands_str);
1145 comp_brands_str[comp_brand_size] = 0;
1146 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1147 av_freep(&comp_brands_str);
1152 /* this atom should contain all header atoms */
1153 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1157 if (c->found_moov) {
1158 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1159 avio_skip(pb, atom.size);
1163 if ((ret = mov_read_default(c, pb, atom)) < 0)
1165 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1166 /* so we don't parse the whole file if over a network */
1168 return 0; /* now go for mdat */
1171 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1173 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1174 c->has_looked_for_mfra = 1;
1175 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
1177 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1179 if ((ret = mov_read_mfra(c, pb)) < 0) {
1180 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1181 "read the mfra (may be a live ismv)\n");
1184 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1185 "seekable, can not look for mfra\n");
1188 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
1189 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1190 return mov_read_default(c, pb, atom);
1193 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1196 if(time >= 2082844800)
1197 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1199 if ((int64_t)(time * 1000000ULL) / 1000000 != time) {
1200 av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n");
1204 avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
1208 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1211 MOVStreamContext *sc;
1213 char language[4] = {0};
1215 int64_t creation_time;
1217 if (c->fc->nb_streams < 1)
1219 st = c->fc->streams[c->fc->nb_streams-1];
1222 if (sc->time_scale) {
1223 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1224 return AVERROR_INVALIDDATA;
1227 version = avio_r8(pb);
1229 avpriv_request_sample(c->fc, "Version %d", version);
1230 return AVERROR_PATCHWELCOME;
1232 avio_rb24(pb); /* flags */
1234 creation_time = avio_rb64(pb);
1237 creation_time = avio_rb32(pb);
1238 avio_rb32(pb); /* modification time */
1240 mov_metadata_creation_time(&st->metadata, creation_time);
1242 sc->time_scale = avio_rb32(pb);
1243 if (sc->time_scale <= 0) {
1244 av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale);
1247 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1249 lang = avio_rb16(pb); /* language */
1250 if (ff_mov_lang_to_iso639(lang, language))
1251 av_dict_set(&st->metadata, "language", language, 0);
1252 avio_rb16(pb); /* quality */
1257 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1260 int64_t creation_time;
1261 int version = avio_r8(pb); /* version */
1262 avio_rb24(pb); /* flags */
1265 creation_time = avio_rb64(pb);
1268 creation_time = avio_rb32(pb);
1269 avio_rb32(pb); /* modification time */
1271 mov_metadata_creation_time(&c->fc->metadata, creation_time);
1272 c->time_scale = avio_rb32(pb); /* time scale */
1273 if (c->time_scale <= 0) {
1274 av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale);
1277 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1279 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1280 // set the AVCodecContext duration because the duration of individual tracks
1281 // may be inaccurate
1282 if (c->time_scale > 0 && !c->trex_data)
1283 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1284 avio_rb32(pb); /* preferred scale */
1286 avio_rb16(pb); /* preferred volume */
1288 avio_skip(pb, 10); /* reserved */
1290 /* movie display matrix, store it in main context and use it later on */
1291 for (i = 0; i < 3; i++) {
1292 c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
1293 c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
1294 c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
1297 avio_rb32(pb); /* preview time */
1298 avio_rb32(pb); /* preview duration */
1299 avio_rb32(pb); /* poster time */
1300 avio_rb32(pb); /* selection time */
1301 avio_rb32(pb); /* selection duration */
1302 avio_rb32(pb); /* current time */
1303 avio_rb32(pb); /* next track ID */
1308 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1313 if (c->fc->nb_streams < 1)
1315 st = c->fc->streams[c->fc->nb_streams-1];
1317 little_endian = avio_rb16(pb) & 0xFF;
1318 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1319 if (little_endian == 1) {
1320 switch (st->codecpar->codec_id) {
1321 case AV_CODEC_ID_PCM_S24BE:
1322 st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
1324 case AV_CODEC_ID_PCM_S32BE:
1325 st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
1327 case AV_CODEC_ID_PCM_F32BE:
1328 st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
1330 case AV_CODEC_ID_PCM_F64BE:
1331 st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
1340 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1343 char color_parameter_type[5] = { 0 };
1344 uint16_t color_primaries, color_trc, color_matrix;
1347 if (c->fc->nb_streams < 1)
1349 st = c->fc->streams[c->fc->nb_streams - 1];
1351 ret = ffio_read_size(pb, color_parameter_type, 4);
1354 if (strncmp(color_parameter_type, "nclx", 4) &&
1355 strncmp(color_parameter_type, "nclc", 4)) {
1356 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1357 color_parameter_type);
1361 color_primaries = avio_rb16(pb);
1362 color_trc = avio_rb16(pb);
1363 color_matrix = avio_rb16(pb);
1365 av_log(c->fc, AV_LOG_TRACE,
1366 "%s: pri %d trc %d matrix %d",
1367 color_parameter_type, color_primaries, color_trc, color_matrix);
1369 if (!strncmp(color_parameter_type, "nclx", 4)) {
1370 uint8_t color_range = avio_r8(pb) >> 7;
1371 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1373 st->codecpar->color_range = AVCOL_RANGE_JPEG;
1375 st->codecpar->color_range = AVCOL_RANGE_MPEG;
1378 if (!av_color_primaries_name(color_primaries))
1379 color_primaries = AVCOL_PRI_UNSPECIFIED;
1380 if (!av_color_transfer_name(color_trc))
1381 color_trc = AVCOL_TRC_UNSPECIFIED;
1382 if (!av_color_space_name(color_matrix))
1383 color_matrix = AVCOL_SPC_UNSPECIFIED;
1385 st->codecpar->color_primaries = color_primaries;
1386 st->codecpar->color_trc = color_trc;
1387 st->codecpar->color_space = color_matrix;
1388 av_log(c->fc, AV_LOG_TRACE, "\n");
1393 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1396 unsigned mov_field_order;
1397 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1399 if (c->fc->nb_streams < 1) // will happen with jp2 files
1401 st = c->fc->streams[c->fc->nb_streams-1];
1403 return AVERROR_INVALIDDATA;
1404 mov_field_order = avio_rb16(pb);
1405 if ((mov_field_order & 0xFF00) == 0x0100)
1406 decoded_field_order = AV_FIELD_PROGRESSIVE;
1407 else if ((mov_field_order & 0xFF00) == 0x0200) {
1408 switch (mov_field_order & 0xFF) {
1409 case 0x01: decoded_field_order = AV_FIELD_TT;
1411 case 0x06: decoded_field_order = AV_FIELD_BB;
1413 case 0x09: decoded_field_order = AV_FIELD_TB;
1415 case 0x0E: decoded_field_order = AV_FIELD_BT;
1419 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1420 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1422 st->codecpar->field_order = decoded_field_order;
1427 static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
1430 uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1431 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1432 return AVERROR_INVALIDDATA;
1433 if ((err = av_reallocp(&par->extradata, size)) < 0) {
1434 par->extradata_size = 0;
1437 par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1441 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1442 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1443 AVCodecParameters *par, uint8_t *buf)
1445 int64_t result = atom.size;
1448 AV_WB32(buf , atom.size + 8);
1449 AV_WL32(buf + 4, atom.type);
1450 err = ffio_read_size(pb, buf + 8, atom.size);
1452 par->extradata_size -= atom.size;
1454 } else if (err < atom.size) {
1455 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1456 par->extradata_size -= atom.size - err;
1459 memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1463 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1464 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1465 enum AVCodecID codec_id)
1468 uint64_t original_size;
1471 if (c->fc->nb_streams < 1) // will happen with jp2 files
1473 st = c->fc->streams[c->fc->nb_streams-1];
1475 if (st->codecpar->codec_id != codec_id)
1476 return 0; /* unexpected codec_id - don't mess with extradata */
1478 original_size = st->codecpar->extradata_size;
1479 err = mov_realloc_extradata(st->codecpar, atom);
1483 err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
1486 return 0; // Note: this is the original behavior to ignore truncation.
1489 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1490 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1492 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1495 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1497 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1500 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1502 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1505 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1507 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1510 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1512 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1514 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1518 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1520 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1522 if (!ret && c->fc->nb_streams >= 1) {
1523 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1524 if (par->extradata_size >= 40) {
1525 par->height = AV_RB16(&par->extradata[36]);
1526 par->width = AV_RB16(&par->extradata[38]);
1532 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1534 if (c->fc->nb_streams >= 1) {
1535 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1536 if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1537 par->codec_id == AV_CODEC_ID_H264 &&
1541 cid = avio_rb16(pb);
1542 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1543 if (cid == 0xd4d || cid == 0xd4e)
1546 } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
1547 par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
1551 num = avio_rb32(pb);
1552 den = avio_rb32(pb);
1553 if (num <= 0 || den <= 0)
1555 switch (avio_rb32(pb)) {
1557 if (den >= INT_MAX / 2)
1561 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1562 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1569 return mov_read_avid(c, pb, atom);
1572 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1576 uint64_t original_size;
1577 if (c->fc->nb_streams >= 1) {
1578 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1579 if (par->codec_id == AV_CODEC_ID_H264)
1581 if (atom.size == 16) {
1582 original_size = par->extradata_size;
1583 ret = mov_realloc_extradata(par, atom);
1585 length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
1586 if (length == atom.size) {
1587 const uint8_t range_value = par->extradata[original_size + 19];
1588 switch (range_value) {
1590 par->color_range = AVCOL_RANGE_MPEG;
1593 par->color_range = AVCOL_RANGE_JPEG;
1596 av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1599 ff_dlog(c, "color_range: %d\n", par->color_range);
1601 /* For some reason the whole atom was not added to the extradata */
1602 av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1605 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1608 av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1615 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1617 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1620 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1625 if (c->fc->nb_streams < 1)
1627 st = c->fc->streams[c->fc->nb_streams-1];
1629 if ((uint64_t)atom.size > (1<<30))
1630 return AVERROR_INVALIDDATA;
1632 if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
1633 st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
1634 st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
1635 // pass all frma atom to codec, needed at least for QDMC and QDM2
1636 av_freep(&st->codecpar->extradata);
1637 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1640 } else if (atom.size > 8) { /* to read frma, esds atoms */
1641 if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1643 ret = ffio_ensure_seekback(pb, 8);
1646 buffer = avio_rb64(pb);
1648 if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1649 && buffer >> 32 <= atom.size
1650 && buffer >> 32 >= 8) {
1653 } else if (!st->codecpar->extradata_size) {
1654 #define ALAC_EXTRADATA_SIZE 36
1655 st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1656 if (!st->codecpar->extradata)
1657 return AVERROR(ENOMEM);
1658 st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
1659 AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE);
1660 AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
1661 AV_WB64(st->codecpar->extradata + 12, buffer);
1662 avio_read(pb, st->codecpar->extradata + 20, 16);
1663 avio_skip(pb, atom.size - 24);
1667 if ((ret = mov_read_default(c, pb, atom)) < 0)
1670 avio_skip(pb, atom.size);
1675 * This function reads atom content and puts data in extradata without tag
1676 * nor size unlike mov_read_extradata.
1678 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1683 if (c->fc->nb_streams < 1)
1685 st = c->fc->streams[c->fc->nb_streams-1];
1687 if ((uint64_t)atom.size > (1<<30))
1688 return AVERROR_INVALIDDATA;
1690 if (atom.size >= 10) {
1691 // Broken files created by legacy versions of libavformat will
1692 // wrap a whole fiel atom inside of a glbl atom.
1693 unsigned size = avio_rb32(pb);
1694 unsigned type = avio_rl32(pb);
1695 avio_seek(pb, -8, SEEK_CUR);
1696 if (type == MKTAG('f','i','e','l') && size == atom.size)
1697 return mov_read_default(c, pb, atom);
1699 if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
1700 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1703 av_freep(&st->codecpar->extradata);
1704 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1711 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1714 uint8_t profile_level;
1717 if (c->fc->nb_streams < 1)
1719 st = c->fc->streams[c->fc->nb_streams-1];
1721 if (atom.size >= (1<<28) || atom.size < 7)
1722 return AVERROR_INVALIDDATA;
1724 profile_level = avio_r8(pb);
1725 if ((profile_level & 0xf0) != 0xc0)
1728 avio_seek(pb, 6, SEEK_CUR);
1729 av_freep(&st->codecpar->extradata);
1730 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
1738 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1739 * but can have extradata appended at the end after the 40 bytes belonging
1742 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1747 if (c->fc->nb_streams < 1)
1749 if (atom.size <= 40)
1751 st = c->fc->streams[c->fc->nb_streams-1];
1753 if ((uint64_t)atom.size > (1<<30))
1754 return AVERROR_INVALIDDATA;
1757 av_freep(&st->codecpar->extradata);
1758 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
1765 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1768 MOVStreamContext *sc;
1769 unsigned int i, entries;
1771 if (c->fc->nb_streams < 1)
1773 st = c->fc->streams[c->fc->nb_streams-1];
1776 avio_r8(pb); /* version */
1777 avio_rb24(pb); /* flags */
1779 entries = avio_rb32(pb);
1784 if (sc->chunk_offsets)
1785 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1786 av_free(sc->chunk_offsets);
1787 sc->chunk_count = 0;
1788 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1789 if (!sc->chunk_offsets)
1790 return AVERROR(ENOMEM);
1791 sc->chunk_count = entries;
1793 if (atom.type == MKTAG('s','t','c','o'))
1794 for (i = 0; i < entries && !pb->eof_reached; i++)
1795 sc->chunk_offsets[i] = avio_rb32(pb);
1796 else if (atom.type == MKTAG('c','o','6','4'))
1797 for (i = 0; i < entries && !pb->eof_reached; i++)
1798 sc->chunk_offsets[i] = avio_rb64(pb);
1800 return AVERROR_INVALIDDATA;
1802 sc->chunk_count = i;
1804 if (pb->eof_reached)
1811 * Compute codec id for 'lpcm' tag.
1812 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1814 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1821 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1824 static int mov_codec_id(AVStream *st, uint32_t format)
1826 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1829 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1830 (format & 0xFFFF) == 'T' + ('S' << 8)))
1831 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1833 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1834 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1835 } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
1836 /* skip old ASF MPEG-4 tag */
1837 format && format != MKTAG('m','p','4','s')) {
1838 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1840 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1842 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
1843 else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
1844 (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1845 st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
1846 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1848 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
1852 st->codecpar->codec_tag = format;
1857 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1858 AVStream *st, MOVStreamContext *sc)
1860 uint8_t codec_name[32] = { 0 };
1864 /* The first 16 bytes of the video sample description are already
1865 * read in ff_mov_read_stsd_entries() */
1866 stsd_start = avio_tell(pb) - 16;
1868 avio_rb16(pb); /* version */
1869 avio_rb16(pb); /* revision level */
1870 avio_rb32(pb); /* vendor */
1871 avio_rb32(pb); /* temporal quality */
1872 avio_rb32(pb); /* spatial quality */
1874 st->codecpar->width = avio_rb16(pb); /* width */
1875 st->codecpar->height = avio_rb16(pb); /* height */
1877 avio_rb32(pb); /* horiz resolution */
1878 avio_rb32(pb); /* vert resolution */
1879 avio_rb32(pb); /* data size, always 0 */
1880 avio_rb16(pb); /* frames per samples */
1882 len = avio_r8(pb); /* codec name, pascal string */
1885 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1887 avio_skip(pb, 31 - len);
1890 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1892 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1893 if (!strncmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1894 st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
1895 st->codecpar->width &= ~1;
1896 st->codecpar->height &= ~1;
1898 /* Flash Media Server uses tag H.263 with Sorenson Spark */
1899 if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
1900 !strncmp(codec_name, "Sorenson H263", 13))
1901 st->codecpar->codec_id = AV_CODEC_ID_FLV1;
1903 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
1905 avio_seek(pb, stsd_start, SEEK_SET);
1907 if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
1908 st->codecpar->bits_per_coded_sample &= 0x1F;
1909 sc->has_palette = 1;
1913 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1914 AVStream *st, MOVStreamContext *sc)
1916 int bits_per_sample, flags;
1917 uint16_t version = avio_rb16(pb);
1918 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1920 avio_rb16(pb); /* revision level */
1921 avio_rb32(pb); /* vendor */
1923 st->codecpar->channels = avio_rb16(pb); /* channel count */
1924 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1925 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
1927 sc->audio_cid = avio_rb16(pb);
1928 avio_rb16(pb); /* packet size = 0 */
1930 st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
1932 // Read QT version 1 fields. In version 0 these do not exist.
1933 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1935 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1938 sc->samples_per_frame = avio_rb32(pb);
1939 avio_rb32(pb); /* bytes per packet */
1940 sc->bytes_per_frame = avio_rb32(pb);
1941 avio_rb32(pb); /* bytes per sample */
1942 } else if (version == 2) {
1943 avio_rb32(pb); /* sizeof struct only */
1944 st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
1945 st->codecpar->channels = avio_rb32(pb);
1946 avio_rb32(pb); /* always 0x7F000000 */
1947 st->codecpar->bits_per_coded_sample = avio_rb32(pb);
1949 flags = avio_rb32(pb); /* lpcm format specific flag */
1950 sc->bytes_per_frame = avio_rb32(pb);
1951 sc->samples_per_frame = avio_rb32(pb);
1952 if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
1953 st->codecpar->codec_id =
1954 ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
1957 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1958 /* can't correctly handle variable sized packet as audio unit */
1959 switch (st->codecpar->codec_id) {
1960 case AV_CODEC_ID_MP2:
1961 case AV_CODEC_ID_MP3:
1962 st->need_parsing = AVSTREAM_PARSE_FULL;
1968 if (sc->format == 0) {
1969 if (st->codecpar->bits_per_coded_sample == 8)
1970 st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
1971 else if (st->codecpar->bits_per_coded_sample == 16)
1972 st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
1975 switch (st->codecpar->codec_id) {
1976 case AV_CODEC_ID_PCM_S8:
1977 case AV_CODEC_ID_PCM_U8:
1978 if (st->codecpar->bits_per_coded_sample == 16)
1979 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
1981 case AV_CODEC_ID_PCM_S16LE:
1982 case AV_CODEC_ID_PCM_S16BE:
1983 if (st->codecpar->bits_per_coded_sample == 8)
1984 st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
1985 else if (st->codecpar->bits_per_coded_sample == 24)
1986 st->codecpar->codec_id =
1987 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
1988 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1989 else if (st->codecpar->bits_per_coded_sample == 32)
1990 st->codecpar->codec_id =
1991 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
1992 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1994 /* set values for old format before stsd version 1 appeared */
1995 case AV_CODEC_ID_MACE3:
1996 sc->samples_per_frame = 6;
1997 sc->bytes_per_frame = 2 * st->codecpar->channels;
1999 case AV_CODEC_ID_MACE6:
2000 sc->samples_per_frame = 6;
2001 sc->bytes_per_frame = 1 * st->codecpar->channels;
2003 case AV_CODEC_ID_ADPCM_IMA_QT:
2004 sc->samples_per_frame = 64;
2005 sc->bytes_per_frame = 34 * st->codecpar->channels;
2007 case AV_CODEC_ID_GSM:
2008 sc->samples_per_frame = 160;
2009 sc->bytes_per_frame = 33;
2015 bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
2016 if (bits_per_sample) {
2017 st->codecpar->bits_per_coded_sample = bits_per_sample;
2018 sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
2022 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
2023 AVStream *st, MOVStreamContext *sc,
2026 // ttxt stsd contains display flags, justification, background
2027 // color, fonts, and default styles, so fake an atom to read it
2028 MOVAtom fake_atom = { .size = size };
2029 // mp4s contains a regular esds atom
2030 if (st->codecpar->codec_tag != AV_RL32("mp4s"))
2031 mov_read_glbl(c, pb, fake_atom);
2032 st->codecpar->width = sc->width;
2033 st->codecpar->height = sc->height;
2036 static uint32_t yuv_to_rgba(uint32_t ycbcr)
2041 y = (ycbcr >> 16) & 0xFF;
2042 cr = (ycbcr >> 8) & 0xFF;
2045 b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
2046 g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
2047 r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
2049 return (r << 16) | (g << 8) | b;
2052 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
2054 char buf[256] = {0};
2055 uint8_t *src = st->codecpar->extradata;
2058 if (st->codecpar->extradata_size != 64)
2061 if (st->codecpar->width > 0 && st->codecpar->height > 0)
2062 snprintf(buf, sizeof(buf), "size: %dx%d\n",
2063 st->codecpar->width, st->codecpar->height);
2064 av_strlcat(buf, "palette: ", sizeof(buf));
2066 for (i = 0; i < 16; i++) {
2067 uint32_t yuv = AV_RB32(src + i * 4);
2068 uint32_t rgba = yuv_to_rgba(yuv);
2070 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2073 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2076 av_freep(&st->codecpar->extradata);
2077 st->codecpar->extradata_size = 0;
2078 st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
2079 if (!st->codecpar->extradata)
2080 return AVERROR(ENOMEM);
2081 st->codecpar->extradata_size = strlen(buf);
2082 memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
2087 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2088 AVStream *st, MOVStreamContext *sc,
2093 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
2094 if ((int)size != size)
2095 return AVERROR(ENOMEM);
2097 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
2101 MOVStreamContext *tmcd_ctx = st->priv_data;
2103 val = AV_RB32(st->codecpar->extradata + 4);
2104 tmcd_ctx->tmcd_flags = val;
2105 st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
2106 st->avg_frame_rate.den = 1;
2107 #if FF_API_LAVF_AVCTX
2108 FF_DISABLE_DEPRECATION_WARNINGS
2109 st->codec->time_base = av_inv_q(st->avg_frame_rate);
2110 FF_ENABLE_DEPRECATION_WARNINGS
2112 /* adjust for per frame dur in counter mode */
2113 if (tmcd_ctx->tmcd_flags & 0x0008) {
2114 int timescale = AV_RB32(st->codecpar->extradata + 8);
2115 int framedur = AV_RB32(st->codecpar->extradata + 12);
2116 st->avg_frame_rate.num *= timescale;
2117 st->avg_frame_rate.den *= framedur;
2118 #if FF_API_LAVF_AVCTX
2119 FF_DISABLE_DEPRECATION_WARNINGS
2120 st->codec->time_base.den *= timescale;
2121 st->codec->time_base.num *= framedur;
2122 FF_ENABLE_DEPRECATION_WARNINGS
2126 uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
2127 uint32_t format = AV_RB32(st->codecpar->extradata + 22);
2128 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2129 uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
2130 if (str_size > 0 && size >= (int)str_size + 26) {
2131 char *reel_name = av_malloc(str_size + 1);
2133 return AVERROR(ENOMEM);
2134 memcpy(reel_name, st->codecpar->extradata + 30, str_size);
2135 reel_name[str_size] = 0; /* Add null terminator */
2136 /* don't add reel_name if emtpy string */
2137 if (*reel_name == 0) {
2140 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2147 /* other codec type, just skip (rtp, mp4s ...) */
2148 avio_skip(pb, size);
2153 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2154 AVStream *st, MOVStreamContext *sc)
2156 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2157 !st->codecpar->sample_rate && sc->time_scale > 1)
2158 st->codecpar->sample_rate = sc->time_scale;
2160 /* special codec parameters handling */
2161 switch (st->codecpar->codec_id) {
2162 #if CONFIG_DV_DEMUXER
2163 case AV_CODEC_ID_DVAUDIO:
2164 c->dv_fctx = avformat_alloc_context();
2166 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2167 return AVERROR(ENOMEM);
2169 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2171 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2172 return AVERROR(ENOMEM);
2174 sc->dv_audio_container = 1;
2175 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
2178 /* no ifdef since parameters are always those */
2179 case AV_CODEC_ID_QCELP:
2180 st->codecpar->channels = 1;
2181 // force sample rate for qcelp when not stored in mov
2182 if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
2183 st->codecpar->sample_rate = 8000;
2184 // FIXME: Why is the following needed for some files?
2185 sc->samples_per_frame = 160;
2186 if (!sc->bytes_per_frame)
2187 sc->bytes_per_frame = 35;
2189 case AV_CODEC_ID_AMR_NB:
2190 st->codecpar->channels = 1;
2191 /* force sample rate for amr, stsd in 3gp does not store sample rate */
2192 st->codecpar->sample_rate = 8000;
2194 case AV_CODEC_ID_AMR_WB:
2195 st->codecpar->channels = 1;
2196 st->codecpar->sample_rate = 16000;
2198 case AV_CODEC_ID_MP2:
2199 case AV_CODEC_ID_MP3:
2200 /* force type after stsd for m1a hdlr */
2201 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2203 case AV_CODEC_ID_GSM:
2204 case AV_CODEC_ID_ADPCM_MS:
2205 case AV_CODEC_ID_ADPCM_IMA_WAV:
2206 case AV_CODEC_ID_ILBC:
2207 case AV_CODEC_ID_MACE3:
2208 case AV_CODEC_ID_MACE6:
2209 case AV_CODEC_ID_QDM2:
2210 st->codecpar->block_align = sc->bytes_per_frame;
2212 case AV_CODEC_ID_ALAC:
2213 if (st->codecpar->extradata_size == 36) {
2214 st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
2215 st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
2218 case AV_CODEC_ID_AC3:
2219 case AV_CODEC_ID_EAC3:
2220 case AV_CODEC_ID_MPEG1VIDEO:
2221 case AV_CODEC_ID_VC1:
2222 case AV_CODEC_ID_VP9:
2223 st->need_parsing = AVSTREAM_PARSE_FULL;
2231 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2232 int codec_tag, int format,
2235 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2238 (codec_tag != format &&
2239 // AVID 1:1 samples with differing data format and codec tag exist
2240 (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
2241 // prores is allowed to have differing data format and codec tag
2242 codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
2244 codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
2245 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2246 : codec_tag != MKTAG('j','p','e','g')))) {
2247 /* Multiple fourcc, we skip JPEG. This is not correct, we should
2248 * export it as a separate AVStream but this needs a few changes
2249 * in the MOV demuxer, patch welcome. */
2251 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2252 avio_skip(pb, size);
2259 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2262 MOVStreamContext *sc;
2263 int pseudo_stream_id;
2265 if (c->fc->nb_streams < 1)
2267 st = c->fc->streams[c->fc->nb_streams-1];
2270 for (pseudo_stream_id = 0;
2271 pseudo_stream_id < entries && !pb->eof_reached;
2272 pseudo_stream_id++) {
2273 //Parsing Sample description table
2275 int ret, dref_id = 1;
2276 MOVAtom a = { AV_RL32("stsd") };
2277 int64_t start_pos = avio_tell(pb);
2278 int64_t size = avio_rb32(pb); /* size */
2279 uint32_t format = avio_rl32(pb); /* data format */
2282 avio_rb32(pb); /* reserved */
2283 avio_rb16(pb); /* reserved */
2284 dref_id = avio_rb16(pb);
2285 } else if (size <= 7) {
2286 av_log(c->fc, AV_LOG_ERROR,
2287 "invalid size %"PRId64" in stsd\n", size);
2288 return AVERROR_INVALIDDATA;
2291 if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
2292 size - (avio_tell(pb) - start_pos)))
2295 sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
2296 sc->dref_id= dref_id;
2297 sc->format = format;
2299 id = mov_codec_id(st, format);
2301 av_log(c->fc, AV_LOG_TRACE,
2302 "size=%"PRId64" 4CC=%s codec_type=%d\n", size,
2303 av_fourcc2str(format), st->codecpar->codec_type);
2305 if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
2306 st->codecpar->codec_id = id;
2307 mov_parse_stsd_video(c, pb, st, sc);
2308 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
2309 st->codecpar->codec_id = id;
2310 mov_parse_stsd_audio(c, pb, st, sc);
2311 if (st->codecpar->sample_rate < 0) {
2312 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
2313 return AVERROR_INVALIDDATA;
2315 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
2316 st->codecpar->codec_id = id;
2317 mov_parse_stsd_subtitle(c, pb, st, sc,
2318 size - (avio_tell(pb) - start_pos));
2320 ret = mov_parse_stsd_data(c, pb, st, sc,
2321 size - (avio_tell(pb) - start_pos));
2325 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2326 a.size = size - (avio_tell(pb) - start_pos);
2328 if ((ret = mov_read_default(c, pb, a)) < 0)
2330 } else if (a.size > 0)
2331 avio_skip(pb, a.size);
2333 if (sc->extradata && st->codecpar->extradata) {
2334 int extra_size = st->codecpar->extradata_size;
2336 /* Move the current stream extradata to the stream context one. */
2337 sc->extradata_size[pseudo_stream_id] = extra_size;
2338 sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
2339 if (!sc->extradata[pseudo_stream_id])
2340 return AVERROR(ENOMEM);
2341 memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
2342 av_freep(&st->codecpar->extradata);
2343 st->codecpar->extradata_size = 0;
2347 if (pb->eof_reached)
2353 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2356 MOVStreamContext *sc;
2359 if (c->fc->nb_streams < 1)
2361 st = c->fc->streams[c->fc->nb_streams - 1];
2364 avio_r8(pb); /* version */
2365 avio_rb24(pb); /* flags */
2366 entries = avio_rb32(pb);
2369 av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
2370 return AVERROR_INVALIDDATA;
2373 if (sc->extradata) {
2374 av_log(c->fc, AV_LOG_ERROR,
2375 "Duplicate stsd found in this track.\n");
2376 return AVERROR_INVALIDDATA;
2379 /* Prepare space for hosting multiple extradata. */
2380 sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
2381 sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
2382 if (!sc->extradata_size || !sc->extradata) {
2383 ret = AVERROR(ENOMEM);
2387 ret = ff_mov_read_stsd_entries(c, pb, entries);
2391 sc->stsd_count = entries;
2393 /* Restore back the primary extradata. */
2394 av_freep(&st->codecpar->extradata);
2395 st->codecpar->extradata_size = sc->extradata_size[0];
2396 if (sc->extradata_size[0]) {
2397 st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
2398 if (!st->codecpar->extradata)
2399 return AVERROR(ENOMEM);
2400 memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
2403 return mov_finalize_stsd_codec(c, pb, st, sc);
2405 av_freep(&sc->extradata);
2406 av_freep(&sc->extradata_size);
2410 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2413 MOVStreamContext *sc;
2414 unsigned int i, entries;
2416 if (c->fc->nb_streams < 1)
2418 st = c->fc->streams[c->fc->nb_streams-1];
2421 avio_r8(pb); /* version */
2422 avio_rb24(pb); /* flags */
2424 entries = avio_rb32(pb);
2426 av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
2431 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2432 av_free(sc->stsc_data);
2434 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2436 return AVERROR(ENOMEM);
2438 for (i = 0; i < entries && !pb->eof_reached; i++) {
2439 sc->stsc_data[i].first = avio_rb32(pb);
2440 sc->stsc_data[i].count = avio_rb32(pb);
2441 sc->stsc_data[i].id = avio_rb32(pb);
2446 if (pb->eof_reached)
2452 static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
2454 return index < count - 1;
2457 /* Compute the samples value for the stsc entry at the given index. */
2458 static inline int mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
2462 if (mov_stsc_index_valid(index, sc->stsc_count))
2463 chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
2465 chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
2467 return sc->stsc_data[index].count * chunk_count;
2470 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2473 MOVStreamContext *sc;
2474 unsigned i, entries;
2476 if (c->fc->nb_streams < 1)
2478 st = c->fc->streams[c->fc->nb_streams-1];
2481 avio_rb32(pb); // version + flags
2483 entries = avio_rb32(pb);
2485 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2486 av_free(sc->stps_data);
2488 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2490 return AVERROR(ENOMEM);
2492 for (i = 0; i < entries && !pb->eof_reached; i++) {
2493 sc->stps_data[i] = avio_rb32(pb);
2498 if (pb->eof_reached)
2504 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2507 MOVStreamContext *sc;
2508 unsigned int i, entries;
2510 if (c->fc->nb_streams < 1)
2512 st = c->fc->streams[c->fc->nb_streams-1];
2515 avio_r8(pb); /* version */
2516 avio_rb24(pb); /* flags */
2518 entries = avio_rb32(pb);
2520 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
2524 sc->keyframe_absent = 1;
2525 if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2526 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2530 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2531 if (entries >= UINT_MAX / sizeof(int))
2532 return AVERROR_INVALIDDATA;
2533 av_freep(&sc->keyframes);
2534 sc->keyframe_count = 0;
2535 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2537 return AVERROR(ENOMEM);
2539 for (i = 0; i < entries && !pb->eof_reached; i++) {
2540 sc->keyframes[i] = avio_rb32(pb);
2543 sc->keyframe_count = i;
2545 if (pb->eof_reached)
2551 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2554 MOVStreamContext *sc;
2555 unsigned int i, entries, sample_size, field_size, num_bytes;
2560 if (c->fc->nb_streams < 1)
2562 st = c->fc->streams[c->fc->nb_streams-1];
2565 avio_r8(pb); /* version */
2566 avio_rb24(pb); /* flags */
2568 if (atom.type == MKTAG('s','t','s','z')) {
2569 sample_size = avio_rb32(pb);
2570 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2571 sc->sample_size = sample_size;
2572 sc->stsz_sample_size = sample_size;
2576 avio_rb24(pb); /* reserved */
2577 field_size = avio_r8(pb);
2579 entries = avio_rb32(pb);
2581 av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
2583 sc->sample_count = entries;
2587 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2588 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
2589 return AVERROR_INVALIDDATA;
2594 if (entries >= (UINT_MAX - 4) / field_size)
2595 return AVERROR_INVALIDDATA;
2596 if (sc->sample_sizes)
2597 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2598 av_free(sc->sample_sizes);
2599 sc->sample_count = 0;
2600 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2601 if (!sc->sample_sizes)
2602 return AVERROR(ENOMEM);
2604 num_bytes = (entries*field_size+4)>>3;
2606 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2608 av_freep(&sc->sample_sizes);
2609 return AVERROR(ENOMEM);
2612 ret = ffio_read_size(pb, buf, num_bytes);
2614 av_freep(&sc->sample_sizes);
2619 init_get_bits(&gb, buf, 8*num_bytes);
2621 for (i = 0; i < entries && !pb->eof_reached; i++) {
2622 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2623 sc->data_size += sc->sample_sizes[i];
2626 sc->sample_count = i;
2630 if (pb->eof_reached)
2636 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2639 MOVStreamContext *sc;
2640 unsigned int i, entries;
2642 int64_t total_sample_count=0;
2644 if (c->fc->nb_streams < 1)
2646 st = c->fc->streams[c->fc->nb_streams-1];
2649 avio_r8(pb); /* version */
2650 avio_rb24(pb); /* flags */
2651 entries = avio_rb32(pb);
2653 av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
2654 c->fc->nb_streams-1, entries);
2657 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2658 av_free(sc->stts_data);
2660 sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2662 return AVERROR(ENOMEM);
2664 for (i = 0; i < entries && !pb->eof_reached; i++) {
2665 int sample_duration;
2668 sample_count=avio_rb32(pb);
2669 sample_duration = avio_rb32(pb);
2671 if (sample_count < 0) {
2672 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2673 return AVERROR_INVALIDDATA;
2675 sc->stts_data[i].count= sample_count;
2676 sc->stts_data[i].duration= sample_duration;
2678 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2679 sample_count, sample_duration);
2683 && sample_count == 1
2684 && total_sample_count > 100
2685 && sample_duration/10 > duration / total_sample_count)
2686 sample_duration = duration / total_sample_count;
2687 duration+=(int64_t)sample_duration*sample_count;
2688 total_sample_count+=sample_count;
2693 sc->duration_for_fps += duration;
2694 sc->nb_frames_for_fps += total_sample_count;
2696 if (pb->eof_reached)
2699 st->nb_frames= total_sample_count;
2701 st->duration= duration;
2702 sc->track_end = duration;
2706 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2709 if (duration == INT_MIN) {
2710 av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2713 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2717 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2720 MOVStreamContext *sc;
2721 unsigned int i, j, entries, ctts_count = 0;
2723 if (c->fc->nb_streams < 1)
2725 st = c->fc->streams[c->fc->nb_streams-1];
2728 avio_r8(pb); /* version */
2729 avio_rb24(pb); /* flags */
2730 entries = avio_rb32(pb);
2732 av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
2736 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2737 return AVERROR_INVALIDDATA;
2738 av_freep(&sc->ctts_data);
2739 sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
2741 return AVERROR(ENOMEM);
2743 for (i = 0; i < entries && !pb->eof_reached; i++) {
2744 int count =avio_rb32(pb);
2745 int duration =avio_rb32(pb);
2748 av_log(c->fc, AV_LOG_TRACE,
2749 "ignoring CTTS entry with count=%d duration=%d\n",
2754 /* Expand entries such that we have a 1-1 mapping with samples. */
2755 for (j = 0; j < count; j++)
2756 add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size, 1, duration);
2758 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2761 if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2762 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2763 av_freep(&sc->ctts_data);
2769 mov_update_dts_shift(sc, duration);
2772 sc->ctts_count = ctts_count;
2774 if (pb->eof_reached)
2777 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2782 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2785 MOVStreamContext *sc;
2786 unsigned int i, entries;
2788 uint32_t grouping_type;
2790 if (c->fc->nb_streams < 1)
2792 st = c->fc->streams[c->fc->nb_streams-1];
2795 version = avio_r8(pb); /* version */
2796 avio_rb24(pb); /* flags */
2797 grouping_type = avio_rl32(pb);
2798 if (grouping_type != MKTAG( 'r','a','p',' '))
2799 return 0; /* only support 'rap ' grouping */
2801 avio_rb32(pb); /* grouping_type_parameter */
2803 entries = avio_rb32(pb);
2807 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2808 av_free(sc->rap_group);
2809 sc->rap_group_count = 0;
2810 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2812 return AVERROR(ENOMEM);
2814 for (i = 0; i < entries && !pb->eof_reached; i++) {
2815 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2816 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2819 sc->rap_group_count = i;
2821 return pb->eof_reached ? AVERROR_EOF : 0;
2825 * Get ith edit list entry (media time, duration).
2827 static int get_edit_list_entry(MOVContext *mov,
2828 const MOVStreamContext *msc,
2829 unsigned int edit_list_index,
2830 int64_t *edit_list_media_time,
2831 int64_t *edit_list_duration,
2832 int64_t global_timescale)
2834 if (edit_list_index == msc->elst_count) {
2837 *edit_list_media_time = msc->elst_data[edit_list_index].time;
2838 *edit_list_duration = msc->elst_data[edit_list_index].duration;
2840 /* duration is in global timescale units;convert to msc timescale */
2841 if (global_timescale == 0) {
2842 avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
2845 *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
2851 * Find the closest previous frame to the timestamp, in e_old index
2852 * entries. Searching for just any frame / just key frames can be controlled by
2853 * last argument 'flag'.
2854 * Returns the index of the entry in st->index_entries if successful,
2857 static int64_t find_prev_closest_index(AVStream *st,
2858 AVIndexEntry *e_old,
2863 AVIndexEntry *e_keep = st->index_entries;
2864 int nb_keep = st->nb_index_entries;
2868 st->index_entries = e_old;
2869 st->nb_index_entries = nb_old;
2870 found = av_index_search_timestamp(st, timestamp, flag | AVSEEK_FLAG_BACKWARD);
2872 // Keep going backwards in the index entries until the timestamp is the same.
2874 for (i = found; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
2876 if ((flag & AVSEEK_FLAG_ANY) ||
2877 (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
2883 /* restore AVStream state*/
2884 st->index_entries = e_keep;
2885 st->nb_index_entries = nb_keep;
2890 * Add index entry with the given values, to the end of st->index_entries.
2891 * Returns the new size st->index_entries if successful, else returns -1.
2893 * This function is similar to ff_add_index_entry in libavformat/utils.c
2894 * except that here we are always unconditionally adding an index entry to
2895 * the end, instead of searching the entries list and skipping the add if
2896 * there is an existing entry with the same timestamp.
2897 * This is needed because the mov_fix_index calls this func with the same
2898 * unincremented timestamp for successive discarded frames.
2900 static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
2901 int size, int distance, int flags)
2903 AVIndexEntry *entries, *ie;
2905 const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
2907 // Double the allocation each time, to lower memory fragmentation.
2908 // Another difference from ff_add_index_entry function.
2909 const size_t requested_size =
2910 min_size_needed > st->index_entries_allocated_size ?
2911 FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
2914 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
2917 entries = av_fast_realloc(st->index_entries,
2918 &st->index_entries_allocated_size,
2923 st->index_entries= entries;
2925 index= st->nb_index_entries++;
2926 ie= &entries[index];
2929 ie->timestamp = timestamp;
2930 ie->min_distance= distance;
2937 * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
2938 * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
2940 static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
2941 int64_t* frame_duration_buffer,
2942 int frame_duration_buffer_size) {
2944 av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
2945 for (i = 0; i < frame_duration_buffer_size; i++) {
2946 end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
2947 st->index_entries[end_index - 1 - i].timestamp = end_ts;
2952 * Append a new ctts entry to ctts_data.
2953 * Returns the new ctts_count if successful, else returns -1.
2955 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
2956 int count, int duration)
2958 MOVStts *ctts_buf_new;
2959 const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
2960 const size_t requested_size =
2961 min_size_needed > *allocated_size ?
2962 FFMAX(min_size_needed, 2 * (*allocated_size)) :
2965 if((unsigned)(*ctts_count) + 1 >= UINT_MAX / sizeof(MOVStts))
2968 ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
2973 *ctts_data = ctts_buf_new;
2975 ctts_buf_new[*ctts_count].count = count;
2976 ctts_buf_new[*ctts_count].duration = duration;
2978 *ctts_count = (*ctts_count) + 1;
2982 static void mov_current_sample_inc(MOVStreamContext *sc)
2984 sc->current_sample++;
2985 sc->current_index++;
2986 if (sc->index_ranges &&
2987 sc->current_index >= sc->current_index_range->end &&
2988 sc->current_index_range->end) {
2989 sc->current_index_range++;
2990 sc->current_index = sc->current_index_range->start;
2994 static void mov_current_sample_dec(MOVStreamContext *sc)
2996 sc->current_sample--;
2997 sc->current_index--;
2998 if (sc->index_ranges &&
2999 sc->current_index < sc->current_index_range->start &&
3000 sc->current_index_range > sc->index_ranges) {
3001 sc->current_index_range--;
3002 sc->current_index = sc->current_index_range->end - 1;
3006 static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
3010 sc->current_sample = current_sample;
3011 sc->current_index = current_sample;
3012 if (!sc->index_ranges) {
3016 for (sc->current_index_range = sc->index_ranges;
3017 sc->current_index_range->end;
3018 sc->current_index_range++) {
3019 range_size = sc->current_index_range->end - sc->current_index_range->start;
3020 if (range_size > current_sample) {
3021 sc->current_index = sc->current_index_range->start + current_sample;
3024 current_sample -= range_size;
3029 * Fix st->index_entries, so that it contains only the entries (and the entries
3030 * which are needed to decode them) that fall in the edit list time ranges.
3031 * Also fixes the timestamps of the index entries to match the timeline
3032 * specified the edit lists.
3034 static void mov_fix_index(MOVContext *mov, AVStream *st)
3036 MOVStreamContext *msc = st->priv_data;
3037 AVIndexEntry *e_old = st->index_entries;
3038 int nb_old = st->nb_index_entries;
3039 const AVIndexEntry *e_old_end = e_old + nb_old;
3040 const AVIndexEntry *current = NULL;
3041 MOVStts *ctts_data_old = msc->ctts_data;
3042 int64_t ctts_index_old = 0;
3043 int64_t ctts_sample_old = 0;
3044 int64_t ctts_count_old = msc->ctts_count;
3045 int64_t edit_list_media_time = 0;
3046 int64_t edit_list_duration = 0;
3047 int64_t frame_duration = 0;
3048 int64_t edit_list_dts_counter = 0;
3049 int64_t edit_list_dts_entry_end = 0;
3050 int64_t edit_list_start_ctts_sample = 0;
3052 int64_t curr_ctts = 0;
3053 int64_t min_corrected_pts = -1;
3054 int64_t empty_edits_sum_duration = 0;
3055 int64_t edit_list_index = 0;
3057 int64_t index_ctts_count;
3059 int64_t start_dts = 0;
3060 int64_t edit_list_media_time_dts = 0;
3061 int64_t edit_list_start_encountered = 0;
3062 int64_t search_timestamp = 0;
3063 int64_t* frame_duration_buffer = NULL;
3064 int num_discarded_begin = 0;
3065 int first_non_zero_audio_edit = -1;
3066 int packet_skip_samples = 0;
3067 MOVIndexRange *current_index_range;
3070 if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
3074 // allocate the index ranges array
3075 msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
3076 if (!msc->index_ranges) {
3077 av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
3080 msc->current_index_range = msc->index_ranges;
3081 current_index_range = msc->index_ranges - 1;
3083 // Clean AVStream from traces of old index
3084 st->index_entries = NULL;
3085 st->index_entries_allocated_size = 0;
3086 st->nb_index_entries = 0;
3088 // Clean ctts fields of MOVStreamContext
3089 msc->ctts_data = NULL;
3090 msc->ctts_count = 0;
3091 msc->ctts_index = 0;
3092 msc->ctts_sample = 0;
3093 msc->ctts_allocated_size = 0;
3095 // If the dts_shift is positive (in case of negative ctts values in mov),
3096 // then negate the DTS by dts_shift
3097 if (msc->dts_shift > 0) {
3098 edit_list_dts_entry_end -= msc->dts_shift;
3099 av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
3102 start_dts = edit_list_dts_entry_end;
3104 while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
3105 &edit_list_duration, mov->time_scale)) {
3106 av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
3107 st->index, edit_list_index, edit_list_media_time, edit_list_duration);
3109 edit_list_dts_counter = edit_list_dts_entry_end;
3110 edit_list_dts_entry_end += edit_list_duration;
3111 num_discarded_begin = 0;
3112 if (edit_list_media_time == -1) {
3113 empty_edits_sum_duration += edit_list_duration;
3117 // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
3118 // according to the edit list below.
3119 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3120 if (first_non_zero_audio_edit < 0) {
3121 first_non_zero_audio_edit = 1;
3123 first_non_zero_audio_edit = 0;
3126 if (first_non_zero_audio_edit > 0)
3127 st->skip_samples = msc->start_pad = 0;
3130 //find closest previous key frame
3131 edit_list_media_time_dts = edit_list_media_time;
3132 if (msc->dts_shift > 0) {
3133 edit_list_media_time_dts -= msc->dts_shift;
3136 // While reordering frame index according to edit list we must handle properly
3137 // the scenario when edit list entry starts from none key frame.
3138 // We find closest previous key frame and preserve it and consequent frames in index.
3139 // All frames which are outside edit list entry time boundaries will be dropped after decoding.
3140 search_timestamp = edit_list_media_time_dts;
3141 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3142 // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
3143 // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
3144 // edit_list_media_time to cover the decoder delay.
3145 search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
3148 index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, 0);
3150 av_log(mov->fc, AV_LOG_WARNING,
3151 "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
3152 st->index, edit_list_index, search_timestamp);
3153 index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, AVSEEK_FLAG_ANY);
3156 av_log(mov->fc, AV_LOG_WARNING,
3157 "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n"
3158 "Rounding edit list media time to zero.\n",
3159 st->index, edit_list_index, search_timestamp);
3161 edit_list_media_time = 0;
3164 current = e_old + index;
3167 ctts_sample_old = 0;
3169 // set ctts_index properly for the found key frame
3170 for (index_ctts_count = 0; index_ctts_count < index; index_ctts_count++) {
3171 if (ctts_data_old && ctts_index_old < ctts_count_old) {
3173 if (ctts_data_old[ctts_index_old].count == ctts_sample_old) {
3175 ctts_sample_old = 0;
3180 edit_list_start_ctts_sample = ctts_sample_old;
3182 // Iterate over index and arrange it according to edit list
3183 edit_list_start_encountered = 0;
3184 for (; current < e_old_end; current++, index++) {
3185 // check if frame outside edit list mark it for discard
3186 frame_duration = (current + 1 < e_old_end) ?
3187 ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
3189 flags = current->flags;
3191 // frames (pts) before or after edit list
3192 curr_cts = current->timestamp + msc->dts_shift;
3195 if (ctts_data_old && ctts_index_old < ctts_count_old) {
3196 curr_ctts = ctts_data_old[ctts_index_old].duration;
3197 av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",
3198 curr_cts, curr_ctts, ctts_index_old, ctts_count_old);
3199 curr_cts += curr_ctts;
3201 if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
3202 if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3203 &msc->ctts_allocated_size,
3204 ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3205 ctts_data_old[ctts_index_old].duration) == -1) {
3206 av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3208 ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3209 ctts_data_old[ctts_index_old].duration);
3213 ctts_sample_old = 0;
3214 edit_list_start_ctts_sample = 0;
3218 if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
3219 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
3220 curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
3221 first_non_zero_audio_edit > 0) {
3222 packet_skip_samples = edit_list_media_time - curr_cts;
3223 st->skip_samples += packet_skip_samples;
3225 // Shift the index entry timestamp by packet_skip_samples to be correct.
3226 edit_list_dts_counter -= packet_skip_samples;
3227 if (edit_list_start_encountered == 0) {
3228 edit_list_start_encountered = 1;
3229 // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3230 // discarded packets.
3231 if (frame_duration_buffer) {
3232 fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3233 frame_duration_buffer, num_discarded_begin);
3234 av_freep(&frame_duration_buffer);
3238 av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
3240 flags |= AVINDEX_DISCARD_FRAME;
3241 av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
3243 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
3244 num_discarded_begin++;
3245 frame_duration_buffer = av_realloc(frame_duration_buffer,
3246 num_discarded_begin * sizeof(int64_t));
3247 if (!frame_duration_buffer) {
3248 av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
3251 frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
3253 // Increment skip_samples for the first non-zero audio edit list
3254 if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
3255 st->skip_samples += frame_duration;
3256 msc->start_pad = st->skip_samples;
3261 if (min_corrected_pts < 0) {
3262 min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
3264 min_corrected_pts = FFMIN(min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
3266 if (edit_list_start_encountered == 0) {
3267 edit_list_start_encountered = 1;
3268 // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3269 // discarded packets.
3270 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
3271 fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3272 frame_duration_buffer, num_discarded_begin);
3273 av_freep(&frame_duration_buffer);
3278 if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
3279 current->min_distance, flags) == -1) {
3280 av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
3284 // Update the index ranges array
3285 if (current_index_range < msc->index_ranges || index != current_index_range->end) {
3286 current_index_range++;
3287 current_index_range->start = index;
3289 current_index_range->end = index + 1;
3291 // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
3292 if (edit_list_start_encountered > 0) {
3293 edit_list_dts_counter = edit_list_dts_counter + frame_duration;
3296 // Break when found first key frame after edit entry completion
3297 if (((curr_cts + frame_duration) >= (edit_list_duration + edit_list_media_time)) &&
3298 ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
3300 if (ctts_data_old && ctts_sample_old != 0) {
3301 if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3302 &msc->ctts_allocated_size,
3303 ctts_sample_old - edit_list_start_ctts_sample,
3304 ctts_data_old[ctts_index_old].duration) == -1) {
3305 av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3306 ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
3307 ctts_data_old[ctts_index_old].duration);
3315 // If there are empty edits, then min_corrected_pts might be positive intentionally. So we subtract the
3316 // sum duration of emtpy edits here.
3317 min_corrected_pts -= empty_edits_sum_duration;
3319 // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
3320 // dts by that amount to make the first pts zero.
3321 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && min_corrected_pts > 0) {
3322 av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", min_corrected_pts);
3323 for (i = 0; i < st->nb_index_entries; ++i) {
3324 st->index_entries[i].timestamp -= min_corrected_pts;
3328 // Update av stream length
3329 st->duration = edit_list_dts_entry_end - start_dts;
3331 // Free the old index and the old CTTS structures
3333 av_free(ctts_data_old);
3335 // Null terminate the index ranges array
3336 current_index_range++;
3337 current_index_range->start = 0;
3338 current_index_range->end = 0;
3339 msc->current_index = msc->index_ranges[0].start;
3342 static void mov_build_index(MOVContext *mov, AVStream *st)
3344 MOVStreamContext *sc = st->priv_data;
3345 int64_t current_offset;
3346 int64_t current_dts = 0;
3347 unsigned int stts_index = 0;
3348 unsigned int stsc_index = 0;
3349 unsigned int stss_index = 0;
3350 unsigned int stps_index = 0;
3352 uint64_t stream_size = 0;
3354 if (sc->elst_count) {
3355 int i, edit_start_index = 0, multiple_edits = 0;
3356 int64_t empty_duration = 0; // empty duration of the first edit list entry
3357 int64_t start_time = 0; // start time of the media
3359 for (i = 0; i < sc->elst_count; i++) {
3360 const MOVElst *e = &sc->elst_data[i];
3361 if (i == 0 && e->time == -1) {
3362 /* if empty, the first entry is the start time of the stream
3363 * relative to the presentation itself */
3364 empty_duration = e->duration;
3365 edit_start_index = 1;
3366 } else if (i == edit_start_index && e->time >= 0) {
3367 start_time = e->time;
3373 if (multiple_edits && !mov->advanced_editlist)
3374 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
3375 "Use -advanced_editlist to correctly decode otherwise "
3376 "a/v desync might occur\n");
3378 /* adjust first dts according to edit list */
3379 if ((empty_duration || start_time) && mov->time_scale > 0) {
3381 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
3382 sc->time_offset = start_time - empty_duration;
3383 if (!mov->advanced_editlist)
3384 current_dts = -sc->time_offset;
3387 if (!multiple_edits && !mov->advanced_editlist &&
3388 st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
3389 sc->start_pad = start_time;
3392 /* only use old uncompressed audio chunk demuxing when stts specifies it */
3393 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
3394 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
3395 unsigned int current_sample = 0;
3396 unsigned int stts_sample = 0;
3397 unsigned int sample_size;
3398 unsigned int distance = 0;
3399 unsigned int rap_group_index = 0;
3400 unsigned int rap_group_sample = 0;
3401 int64_t last_dts = 0;
3402 int64_t dts_correction = 0;
3403 int rap_group_present = sc->rap_group_count && sc->rap_group;
3404 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
3406 current_dts -= sc->dts_shift;
3407 last_dts = current_dts;
3409 if (!sc->sample_count || st->nb_index_entries)
3411 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3413 if (av_reallocp_array(&st->index_entries,
3414 st->nb_index_entries + sc->sample_count,
3415 sizeof(*st->index_entries)) < 0) {
3416 st->nb_index_entries = 0;
3419 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
3421 for (i = 0; i < sc->chunk_count; i++) {
3422 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
3423 current_offset = sc->chunk_offsets[i];
3424 while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3425 i + 1 == sc->stsc_data[stsc_index + 1].first)
3428 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
3429 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
3430 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
3431 sc->stsz_sample_size = sc->sample_size;
3433 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
3434 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
3435 sc->stsz_sample_size = sc->sample_size;
3438 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
3440 if (current_sample >= sc->sample_count) {
3441 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
3445 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
3447 if (stss_index + 1 < sc->keyframe_count)
3449 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
3451 if (stps_index + 1 < sc->stps_count)
3454 if (rap_group_present && rap_group_index < sc->rap_group_count) {
3455 if (sc->rap_group[rap_group_index].index > 0)
3457 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
3458 rap_group_sample = 0;
3462 if (sc->keyframe_absent
3464 && !rap_group_present
3465 && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
3469 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
3470 if (sc->pseudo_stream_id == -1 ||
3471 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
3473 if (sample_size > 0x3FFFFFFF) {
3474 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
3477 e = &st->index_entries[st->nb_index_entries++];
3478 e->pos = current_offset;
3479 e->timestamp = current_dts;
3480 e->size = sample_size;
3481 e->min_distance = distance;
3482 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
3483 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
3484 "size %u, distance %u, keyframe %d\n", st->index, current_sample,
3485 current_offset, current_dts, sample_size, distance, keyframe);
3486 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
3487 ff_rfps_add_frame(mov->fc, st, current_dts);
3490 current_offset += sample_size;
3491 stream_size += sample_size;
3493 /* A negative sample duration is invalid based on the spec,
3494 * but some samples need it to correct the DTS. */
3495 if (sc->stts_data[stts_index].duration < 0) {
3496 av_log(mov->fc, AV_LOG_WARNING,
3497 "Invalid SampleDelta %d in STTS, at %d st:%d\n",
3498 sc->stts_data[stts_index].duration, stts_index,
3500 dts_correction += sc->stts_data[stts_index].duration - 1;
3501 sc->stts_data[stts_index].duration = 1;
3503 current_dts += sc->stts_data[stts_index].duration;
3504 if (!dts_correction || current_dts + dts_correction > last_dts) {
3505 current_dts += dts_correction;
3508 /* Avoid creating non-monotonous DTS */
3509 dts_correction += current_dts - last_dts - 1;
3510 current_dts = last_dts + 1;
3512 last_dts = current_dts;
3516 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
3522 if (st->duration > 0)
3523 st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
3525 unsigned chunk_samples, total = 0;
3527 // compute total chunk count
3528 for (i = 0; i < sc->stsc_count; i++) {
3529 unsigned count, chunk_count;
3531 chunk_samples = sc->stsc_data[i].count;
3532 if (i != sc->stsc_count - 1 &&
3533 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
3534 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
3538 if (sc->samples_per_frame >= 160) { // gsm
3539 count = chunk_samples / sc->samples_per_frame;
3540 } else if (sc->samples_per_frame > 1) {
3541 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
3542 count = (chunk_samples+samples-1) / samples;
3544 count = (chunk_samples+1023) / 1024;
3547 if (mov_stsc_index_valid(i, sc->stsc_count))
3548 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
3550 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
3551 total += chunk_count * count;
3554 av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
3555 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3557 if (av_reallocp_array(&st->index_entries,
3558 st->nb_index_entries + total,
3559 sizeof(*st->index_entries)) < 0) {
3560 st->nb_index_entries = 0;
3563 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
3566 for (i = 0; i < sc->chunk_count; i++) {
3567 current_offset = sc->chunk_offsets[i];
3568 if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3569 i + 1 == sc->stsc_data[stsc_index + 1].first)
3571 chunk_samples = sc->stsc_data[stsc_index].count;
3573 while (chunk_samples > 0) {
3575 unsigned size, samples;
3577 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
3578 avpriv_request_sample(mov->fc,
3579 "Zero bytes per frame, but %d samples per frame",
3580 sc->samples_per_frame);
3584 if (sc->samples_per_frame >= 160) { // gsm
3585 samples = sc->samples_per_frame;
3586 size = sc->bytes_per_frame;
3588 if (sc->samples_per_frame > 1) {
3589 samples = FFMIN((1024 / sc->samples_per_frame)*
3590 sc->samples_per_frame, chunk_samples);
3591 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
3593 samples = FFMIN(1024, chunk_samples);
3594 size = samples * sc->sample_size;
3598 if (st->nb_index_entries >= total) {
3599 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
3602 if (size > 0x3FFFFFFF) {
3603 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
3606 e = &st->index_entries[st->nb_index_entries++];
3607 e->pos = current_offset;
3608 e->timestamp = current_dts;
3610 e->min_distance = 0;
3611 e->flags = AVINDEX_KEYFRAME;
3612 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
3613 "size %u, duration %u\n", st->index, i, current_offset, current_dts,
3616 current_offset += size;
3617 current_dts += samples;
3618 chunk_samples -= samples;
3623 if (!mov->ignore_editlist && mov->advanced_editlist) {
3624 // Fix index according to edit lists.
3625 mov_fix_index(mov, st);
3629 static int test_same_origin(const char *src, const char *ref) {
3639 av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
3640 av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
3642 if (strlen(src) == 0) {
3644 } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
3645 strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
3646 strlen(src_host) + 1 >= sizeof(src_host) ||
3647 strlen(ref_host) + 1 >= sizeof(ref_host)) {
3649 } else if (strcmp(src_proto, ref_proto) ||
3650 strcmp(src_auth, ref_auth) ||
3651 strcmp(src_host, ref_host) ||
3652 src_port != ref_port) {
3658 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
3660 /* try relative path, we do not try the absolute because it can leak information about our
3661 system to an attacker */
3662 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
3663 char filename[1025];
3664 const char *src_path;
3667 /* find a source dir */
3668 src_path = strrchr(src, '/');
3674 /* find a next level down to target */
3675 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
3676 if (ref->path[l] == '/') {
3677 if (i == ref->nlvl_to - 1)
3683 /* compose filename if next level down to target was found */
3684 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
3685 memcpy(filename, src, src_path - src);
3686 filename[src_path - src] = 0;
3688 for (i = 1; i < ref->nlvl_from; i++)
3689 av_strlcat(filename, "../", sizeof(filename));
3691 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
3692 if (!c->use_absolute_path) {
3693 int same_origin = test_same_origin(src, filename);
3696 av_log(c->fc, AV_LOG_ERROR,
3697 "Reference with mismatching origin, %s not tried for security reasons, "
3698 "set demuxer option use_absolute_path to allow it anyway\n",
3700 return AVERROR(ENOENT);
3703 if(strstr(ref->path + l + 1, "..") ||
3704 strstr(ref->path + l + 1, ":") ||
3705 (ref->nlvl_from > 1 && same_origin < 0) ||
3706 (filename[0] == '/' && src_path == src))
3707 return AVERROR(ENOENT);
3710 if (strlen(filename) + 1 == sizeof(filename))
3711 return AVERROR(ENOENT);
3712 if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
3715 } else if (c->use_absolute_path) {
3716 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
3717 "this is a possible security issue\n");
3718 if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
3721 av_log(c->fc, AV_LOG_ERROR,
3722 "Absolute path %s not tried for security reasons, "
3723 "set demuxer option use_absolute_path to allow absolute paths\n",
3727 return AVERROR(ENOENT);
3730 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
3732 if (sc->time_scale <= 0) {
3733 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
3734 sc->time_scale = c->time_scale;
3735 if (sc->time_scale <= 0)
3740 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3743 MOVStreamContext *sc;
3746 st = avformat_new_stream(c->fc, NULL);
3747 if (!st) return AVERROR(ENOMEM);
3748 st->id = c->fc->nb_streams;
3749 sc = av_mallocz(sizeof(MOVStreamContext));
3750 if (!sc) return AVERROR(ENOMEM);
3753 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
3754 sc->ffindex = st->index;
3755 c->trak_index = st->index;
3757 if ((ret = mov_read_default(c, pb, atom)) < 0)
3763 if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
3764 (!sc->sample_size && !sc->sample_count))) ||
3765 (!sc->chunk_count && sc->sample_count)) {
3766 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
3771 fix_timescale(c, sc);
3773 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
3775 mov_build_index(c, st);
3777 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
3778 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
3779 if (c->enable_drefs) {
3780 if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
3781 av_log(c->fc, AV_LOG_ERROR,
3782 "stream %d, error opening alias: path='%s', dir='%s', "
3783 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
3784 st->index, dref->path, dref->dir, dref->filename,
3785 dref->volume, dref->nlvl_from, dref->nlvl_to);
3787 av_log(c->fc, AV_LOG_WARNING,
3788 "Skipped opening external track: "
3789 "stream %d, alias: path='%s', dir='%s', "
3790 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
3791 "Set enable_drefs to allow this.\n",
3792 st->index, dref->path, dref->dir, dref->filename,
3793 dref->volume, dref->nlvl_from, dref->nlvl_to);
3797 sc->pb_is_copied = 1;
3800 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3801 if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
3802 sc->height && sc->width &&
3803 (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
3804 st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
3805 ((double)st->codecpar->width * sc->height), INT_MAX);
3808 #if FF_API_R_FRAME_RATE
3809 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
3810 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
3811 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
3815 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3816 if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
3817 TAG_IS_AVCI(st->codecpar->codec_tag)) {
3818 ret = ff_generate_avci_extradata(st);
3823 switch (st->codecpar->codec_id) {
3824 #if CONFIG_H261_DECODER
3825 case AV_CODEC_ID_H261:
3827 #if CONFIG_H263_DECODER
3828 case AV_CODEC_ID_H263:
3830 #if CONFIG_MPEG4_DECODER
3831 case AV_CODEC_ID_MPEG4:
3833 st->codecpar->width = 0; /* let decoder init width/height */
3834 st->codecpar->height= 0;
3838 // If the duration of the mp3 packets is not constant, then they could need a parser
3839 if (st->codecpar->codec_id == AV_CODEC_ID_MP3
3840 && sc->stts_count > 3
3841 && sc->stts_count*10 > st->nb_frames
3842 && sc->time_scale == st->codecpar->sample_rate) {
3843 st->need_parsing = AVSTREAM_PARSE_FULL;
3845 /* Do not need those anymore. */
3846 av_freep(&sc->chunk_offsets);
3847 av_freep(&sc->sample_sizes);
3848 av_freep(&sc->keyframes);
3849 av_freep(&sc->stts_data);
3850 av_freep(&sc->stps_data);
3851 av_freep(&sc->elst_data);
3852 av_freep(&sc->rap_group);
3857 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3860 c->itunes_metadata = 1;
3861 ret = mov_read_default(c, pb, atom);
3862 c->itunes_metadata = 0;
3866 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3875 count = avio_rb32(pb);
3876 if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
3877 av_log(c->fc, AV_LOG_ERROR,
3878 "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
3879 return AVERROR_INVALIDDATA;
3882 c->meta_keys_count = count + 1;
3883 c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
3885 return AVERROR(ENOMEM);
3887 for (i = 1; i <= count; ++i) {
3888 uint32_t key_size = avio_rb32(pb);
3889 uint32_t type = avio_rl32(pb);
3891 av_log(c->fc, AV_LOG_ERROR,
3892 "The key# %"PRIu32" in meta has invalid size:"
3893 "%"PRIu32"\n", i, key_size);
3894 return AVERROR_INVALIDDATA;
3897 if (type != MKTAG('m','d','t','a')) {
3898 avio_skip(pb, key_size);
3900 c->meta_keys[i] = av_mallocz(key_size + 1);
3901 if (!c->meta_keys[i])
3902 return AVERROR(ENOMEM);
3903 avio_read(pb, c->meta_keys[i], key_size);
3909 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3911 int64_t end = avio_tell(pb) + atom.size;
3912 uint8_t *key = NULL, *val = NULL, *mean = NULL;
3916 MOVStreamContext *sc;
3918 if (c->fc->nb_streams < 1)
3920 st = c->fc->streams[c->fc->nb_streams-1];
3923 for (i = 0; i < 3; i++) {
3927 if (end - avio_tell(pb) <= 12)
3930 len = avio_rb32(pb);
3931 tag = avio_rl32(pb);
3932 avio_skip(pb, 4); // flags
3934 if (len < 12 || len - 12 > end - avio_tell(pb))
3938 if (tag == MKTAG('m', 'e', 'a', 'n'))
3940 else if (tag == MKTAG('n', 'a', 'm', 'e'))
3942 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
3949 *p = av_malloc(len + 1);
3952 ret = ffio_read_size(pb, *p, len);
3960 if (mean && key && val) {
3961 if (strcmp(key, "iTunSMPB") == 0) {
3962 int priming, remainder, samples;
3963 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
3964 if(priming>0 && priming<16384)
3965 sc->start_pad = priming;
3968 if (strcmp(key, "cdec") != 0) {
3969 av_dict_set(&c->fc->metadata, key, val,
3970 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
3974 av_log(c->fc, AV_LOG_VERBOSE,
3975 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
3978 avio_seek(pb, end, SEEK_SET);
3985 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3987 while (atom.size > 8) {
3988 uint32_t tag = avio_rl32(pb);
3990 if (tag == MKTAG('h','d','l','r')) {
3991 avio_seek(pb, -8, SEEK_CUR);
3993 return mov_read_default(c, pb, atom);
3999 // return 1 when matrix is identity, 0 otherwise
4000 #define IS_MATRIX_IDENT(matrix) \
4001 ( (matrix)[0][0] == (1 << 16) && \
4002 (matrix)[1][1] == (1 << 16) && \
4003 (matrix)[2][2] == (1 << 30) && \
4004 !(matrix)[0][1] && !(matrix)[0][2] && \
4005 !(matrix)[1][0] && !(matrix)[1][2] && \
4006 !(matrix)[2][0] && !(matrix)[2][1])
4008 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4013 int display_matrix[3][3];
4014 int res_display_matrix[3][3] = { { 0 } };
4016 MOVStreamContext *sc;
4020 if (c->fc->nb_streams < 1)
4022 st = c->fc->streams[c->fc->nb_streams-1];
4025 version = avio_r8(pb);
4026 flags = avio_rb24(pb);
4027 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
4033 avio_rb32(pb); /* creation time */
4034 avio_rb32(pb); /* modification time */
4036 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
4037 avio_rb32(pb); /* reserved */
4039 /* highlevel (considering edits) duration in movie timebase */
4040 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
4041 avio_rb32(pb); /* reserved */
4042 avio_rb32(pb); /* reserved */
4044 avio_rb16(pb); /* layer */
4045 avio_rb16(pb); /* alternate group */
4046 avio_rb16(pb); /* volume */
4047 avio_rb16(pb); /* reserved */
4049 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
4050 // they're kept in fixed point format through all calculations
4051 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
4052 // side data, but the scale factor is not needed to calculate aspect ratio
4053 for (i = 0; i < 3; i++) {
4054 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
4055 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
4056 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
4059 width = avio_rb32(pb); // 16.16 fixed point track width
4060 height = avio_rb32(pb); // 16.16 fixed point track height
4061 sc->width = width >> 16;
4062 sc->height = height >> 16;
4064 // apply the moov display matrix (after the tkhd one)
4065 for (i = 0; i < 3; i++) {
4066 const int sh[3] = { 16, 16, 30 };
4067 for (j = 0; j < 3; j++) {
4068 for (e = 0; e < 3; e++) {
4069 res_display_matrix[i][j] +=
4070 ((int64_t) display_matrix[i][e] *
4071 c->movie_display_matrix[e][j]) >> sh[e];
4076 // save the matrix when it is not the default identity
4077 if (!IS_MATRIX_IDENT(res_display_matrix)) {
4080 av_freep(&sc->display_matrix);
4081 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
4082 if (!sc->display_matrix)
4083 return AVERROR(ENOMEM);
4085 for (i = 0; i < 3; i++)
4086 for (j = 0; j < 3; j++)
4087 sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
4089 #if FF_API_OLD_ROTATE_API
4090 rotate = av_display_rotation_get(sc->display_matrix);
4091 if (!isnan(rotate)) {
4092 char rotate_buf[64];
4094 if (rotate < 0) // for backward compatibility
4096 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
4097 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
4102 // transform the display width/height according to the matrix
4103 // to keep the same scale, use [width height 1<<16]
4104 if (width && height && sc->display_matrix) {
4105 double disp_transform[2];
4107 for (i = 0; i < 2; i++)
4108 disp_transform[i] = hypot(sc->display_matrix[0 + i],
4109 sc->display_matrix[3 + i]);
4111 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
4112 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
4113 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
4114 st->sample_aspect_ratio = av_d2q(
4115 disp_transform[0] / disp_transform[1],
4121 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4123 MOVFragment *frag = &c->fragment;
4124 MOVTrackExt *trex = NULL;
4125 MOVFragmentIndex* index = NULL;
4126 int flags, track_id, i, found = 0;
4128 avio_r8(pb); /* version */
4129 flags = avio_rb24(pb);
4131 track_id = avio_rb32(pb);
4133 return AVERROR_INVALIDDATA;
4134 frag->track_id = track_id;
4135 for (i = 0; i < c->trex_count; i++)
4136 if (c->trex_data[i].track_id == frag->track_id) {
4137 trex = &c->trex_data[i];
4141 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
4142 return AVERROR_INVALIDDATA;
4145 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
4146 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
4147 frag->moof_offset : frag->implicit_offset;
4148 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
4150 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
4151 avio_rb32(pb) : trex->duration;
4152 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
4153 avio_rb32(pb) : trex->size;
4154 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
4155 avio_rb32(pb) : trex->flags;
4156 frag->time = AV_NOPTS_VALUE;
4157 for (i = 0; i < c->fragment_index_count; i++) {
4159 MOVFragmentIndex* candidate = c->fragment_index_data[i];
4160 if (candidate->track_id == frag->track_id) {
4161 av_log(c->fc, AV_LOG_DEBUG,
4162 "found fragment index for track %u\n", frag->track_id);
4164 for (j = index->current_item; j < index->item_count; j++) {
4165 if (frag->implicit_offset == index->items[j].moof_offset) {
4166 av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
4167 "for track %u and moof_offset %"PRId64"\n",
4168 frag->track_id, index->items[j].moof_offset);
4169 frag->time = index->items[j].time;
4170 index->current_item = j + 1;
4179 if (index && !found) {
4180 av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
4181 "it doesn't have an (in-order) entry for moof_offset "
4182 "%"PRId64"\n", frag->track_id, frag->implicit_offset);
4184 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
4188 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4193 num = atom.size / 4;
4194 if (!(new_tracks = av_malloc_array(num, sizeof(int))))
4195 return AVERROR(ENOMEM);
4197 av_free(c->chapter_tracks);
4198 c->chapter_tracks = new_tracks;
4199 c->nb_chapter_tracks = num;
4201 for (i = 0; i < num && !pb->eof_reached; i++)
4202 c->chapter_tracks[i] = avio_rb32(pb);
4207 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4212 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
4213 return AVERROR_INVALIDDATA;
4214 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
4215 sizeof(*c->trex_data))) < 0) {
4220 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
4222 trex = &c->trex_data[c->trex_count++];
4223 avio_r8(pb); /* version */
4224 avio_rb24(pb); /* flags */
4225 trex->track_id = avio_rb32(pb);
4226 trex->stsd_id = avio_rb32(pb);
4227 trex->duration = avio_rb32(pb);
4228 trex->size = avio_rb32(pb);
4229 trex->flags = avio_rb32(pb);
4233 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4235 MOVFragment *frag = &c->fragment;
4236 AVStream *st = NULL;
4237 MOVStreamContext *sc;
4240 for (i = 0; i < c->fc->nb_streams; i++) {
4241 if (c->fc->streams[i]->id == frag->track_id) {
4242 st = c->fc->streams[i];
4247 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4248 return AVERROR_INVALIDDATA;
4251 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
4253 version = avio_r8(pb);
4254 avio_rb24(pb); /* flags */
4256 sc->track_end = avio_rb64(pb);
4258 sc->track_end = avio_rb32(pb);
4263 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4265 MOVFragment *frag = &c->fragment;
4266 AVStream *st = NULL;
4267 MOVStreamContext *sc;
4271 int data_offset = 0;
4272 unsigned entries, first_sample_flags = frag->flags;
4273 int flags, distance, i;
4275 for (i = 0; i < c->fc->nb_streams; i++) {
4276 if (c->fc->streams[i]->id == frag->track_id) {
4277 st = c->fc->streams[i];
4282 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4283 return AVERROR_INVALIDDATA;
4286 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
4288 avio_r8(pb); /* version */
4289 flags = avio_rb24(pb);
4290 entries = avio_rb32(pb);
4291 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
4293 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
4294 return AVERROR_INVALIDDATA;
4295 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
4296 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
4297 dts = sc->track_end - sc->time_offset;
4298 offset = frag->base_data_offset + data_offset;
4300 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
4301 for (i = 0; i < entries && !pb->eof_reached; i++) {
4302 unsigned sample_size = frag->size;
4303 int sample_flags = i ? frag->flags : first_sample_flags;
4304 unsigned sample_duration = frag->duration;
4305 unsigned ctts_duration = 0;
4308 int old_nb_index_entries = st->nb_index_entries;
4310 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
4311 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
4312 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
4313 if (flags & MOV_TRUN_SAMPLE_CTS) ctts_duration = avio_rb32(pb);
4315 mov_update_dts_shift(sc, ctts_duration);
4316 if (frag->time != AV_NOPTS_VALUE) {
4317 if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
4318 int64_t pts = frag->time;
4319 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
4320 " sc->dts_shift %d ctts.duration %d"
4321 " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
4322 sc->dts_shift, ctts_duration,
4323 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
4324 dts = pts - sc->dts_shift;
4325 if (flags & MOV_TRUN_SAMPLE_CTS) {
4326 dts -= ctts_duration;
4328 dts -= sc->time_offset;
4330 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
4332 dts = frag->time - sc->time_offset;
4333 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
4334 ", using it for dts\n", dts);
4336 frag->time = AV_NOPTS_VALUE;
4339 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4343 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
4344 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
4347 ctts_index = av_add_index_entry(st, offset, dts, sample_size, distance,
4348 keyframe ? AVINDEX_KEYFRAME : 0);
4349 if (ctts_index >= 0 && old_nb_index_entries < st->nb_index_entries) {
4350 unsigned int size_needed = st->nb_index_entries * sizeof(*sc->ctts_data);
4351 unsigned int request_size = size_needed > sc->ctts_allocated_size ?
4352 FFMAX(size_needed, 2 * sc->ctts_allocated_size) : size_needed;
4353 unsigned int old_ctts_size = sc->ctts_allocated_size;
4354 ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size, request_size);
4356 av_freep(&sc->ctts_data);
4357 return AVERROR(ENOMEM);
4359 sc->ctts_data = ctts_data;
4361 // In case there were samples without ctts entries, ensure they get
4362 // zero valued entries. This ensures clips which mix boxes with and
4363 // without ctts entries don't pickup uninitialized data.
4364 memset((uint8_t*)(sc->ctts_data) + old_ctts_size, 0, sc->ctts_allocated_size - old_ctts_size);
4366 if (ctts_index != old_nb_index_entries) {
4367 memmove(sc->ctts_data + ctts_index + 1, sc->ctts_data + ctts_index,
4368 sizeof(*sc->ctts_data) * (sc->ctts_count - ctts_index));
4369 if (ctts_index <= sc->current_sample) {
4370 // if we inserted a new item before the current sample, move the
4371 // counter ahead so it is still pointing to the same sample.
4372 sc->current_sample++;
4376 sc->ctts_data[ctts_index].count = 1;
4377 sc->ctts_data[ctts_index].duration = ctts_duration;
4380 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
4383 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
4384 "size %u, distance %d, keyframe %d\n", st->index, ctts_index,
4385 offset, dts, sample_size, distance, keyframe);
4387 dts += sample_duration;
4388 offset += sample_size;
4389 sc->data_size += sample_size;
4390 sc->duration_for_fps += sample_duration;
4391 sc->nb_frames_for_fps ++;
4394 if (pb->eof_reached)
4397 frag->implicit_offset = offset;
4399 sc->track_end = dts + sc->time_offset;
4400 if (st->duration < sc->track_end)
4401 st->duration = sc->track_end;
4406 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4408 int64_t offset = avio_tell(pb) + atom.size, pts;
4410 unsigned i, track_id;
4411 AVStream *st = NULL;
4412 AVStream *ref_st = NULL;
4413 MOVStreamContext *sc, *ref_sc = NULL;
4414 MOVFragmentIndex *index = NULL;
4415 MOVFragmentIndex **tmp;
4416 AVRational timescale;
4418 version = avio_r8(pb);
4420 avpriv_request_sample(c->fc, "sidx version %u", version);
4424 avio_rb24(pb); // flags
4426 track_id = avio_rb32(pb); // Reference ID
4427 for (i = 0; i < c->fc->nb_streams; i++) {
4428 if (c->fc->streams[i]->id == track_id) {
4429 st = c->fc->streams[i];
4434 av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
4440 timescale = av_make_q(1, avio_rb32(pb));
4442 if (timescale.den <= 0) {
4443 av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
4444 return AVERROR_INVALIDDATA;
4448 pts = avio_rb32(pb);
4449 offset += avio_rb32(pb);
4451 pts = avio_rb64(pb);
4452 offset += avio_rb64(pb);
4455 avio_rb16(pb); // reserved
4457 index = av_mallocz(sizeof(MOVFragmentIndex));
4459 return AVERROR(ENOMEM);
4461 index->track_id = track_id;
4463 index->item_count = avio_rb16(pb);
4464 index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
4466 if (!index->items) {
4468 return AVERROR(ENOMEM);
4471 for (i = 0; i < index->item_count; i++) {
4472 uint32_t size = avio_rb32(pb);
4473 uint32_t duration = avio_rb32(pb);
4474 if (size & 0x80000000) {
4475 avpriv_request_sample(c->fc, "sidx reference_type 1");
4476 av_freep(&index->items);
4478 return AVERROR_PATCHWELCOME;
4480 avio_rb32(pb); // sap_flags
4481 index->items[i].moof_offset = offset;
4482 index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
4487 st->duration = sc->track_end = pts;
4489 tmp = av_realloc_array(c->fragment_index_data,
4490 c->fragment_index_count + 1,
4491 sizeof(MOVFragmentIndex*));
4493 av_freep(&index->items);
4495 return AVERROR(ENOMEM);
4498 c->fragment_index_data = tmp;
4499 c->fragment_index_data[c->fragment_index_count++] = index;
4502 if (offset == avio_size(pb)) {
4503 for (i = 0; i < c->fc->nb_streams; i++) {
4504 if (c->fc->streams[i]->id == c->fragment_index_data[0]->track_id) {
4505 ref_st = c->fc->streams[i];
4506 ref_sc = ref_st->priv_data;
4510 for (i = 0; i < c->fc->nb_streams; i++) {
4511 st = c->fc->streams[i];
4513 if (!sc->has_sidx) {
4514 st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
4518 c->fragment_index_complete = 1;
4524 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
4525 /* like the files created with Adobe Premiere 5.0, for samples see */
4526 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
4527 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4532 return 0; /* continue */
4533 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
4534 avio_skip(pb, atom.size - 4);
4537 atom.type = avio_rl32(pb);
4539 if (atom.type != MKTAG('m','d','a','t')) {
4540 avio_skip(pb, atom.size);
4543 err = mov_read_mdat(c, pb, atom);
4547 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4552 uint8_t *moov_data; /* uncompressed data */
4553 long cmov_len, moov_len;
4556 avio_rb32(pb); /* dcom atom */
4557 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
4558 return AVERROR_INVALIDDATA;
4559 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
4560 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
4561 return AVERROR_INVALIDDATA;
4563 avio_rb32(pb); /* cmvd atom */
4564 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
4565 return AVERROR_INVALIDDATA;
4566 moov_len = avio_rb32(pb); /* uncompressed size */
4567 cmov_len = atom.size - 6 * 4;
4569 cmov_data = av_malloc(cmov_len);
4571 return AVERROR(ENOMEM);
4572 moov_data = av_malloc(moov_len);
4575 return AVERROR(ENOMEM);
4577 ret = ffio_read_size(pb, cmov_data, cmov_len);
4579 goto free_and_return;
4581 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
4582 goto free_and_return;
4583 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
4584 goto free_and_return;
4585 ctx.seekable = AVIO_SEEKABLE_NORMAL;
4586 atom.type = MKTAG('m','o','o','v');
4587 atom.size = moov_len;
4588 ret = mov_read_default(c, &ctx, atom);
4594 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
4595 return AVERROR(ENOSYS);
4599 /* edit list atom */
4600 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4602 MOVStreamContext *sc;
4603 int i, edit_count, version;
4605 if (c->fc->nb_streams < 1 || c->ignore_editlist)
4607 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
4609 version = avio_r8(pb); /* version */
4610 avio_rb24(pb); /* flags */
4611 edit_count = avio_rb32(pb); /* entries */
4616 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
4617 av_free(sc->elst_data);
4619 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
4621 return AVERROR(ENOMEM);
4623 av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
4624 for (i = 0; i < edit_count && !pb->eof_reached; i++) {
4625 MOVElst *e = &sc->elst_data[i];
4628 e->duration = avio_rb64(pb);
4629 e->time = avio_rb64(pb);
4631 e->duration = avio_rb32(pb); /* segment duration */
4632 e->time = (int32_t)avio_rb32(pb); /* media time */
4634 e->rate = avio_rb32(pb) / 65536.0;
4635 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
4636 e->duration, e->time, e->rate);
4638 if (e->time < 0 && e->time != -1 &&
4639 c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
4640 av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
4641 c->fc->nb_streams-1, i, e->time);
4642 return AVERROR_INVALIDDATA;
4650 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4652 MOVStreamContext *sc;
4654 if (c->fc->nb_streams < 1)
4655 return AVERROR_INVALIDDATA;
4656 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
4657 sc->timecode_track = avio_rb32(pb);
4661 static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4664 int version, color_range, color_primaries, color_trc, color_space;
4666 if (c->fc->nb_streams < 1)
4668 st = c->fc->streams[c->fc->nb_streams - 1];
4670 if (atom.size < 5) {
4671 av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
4672 return AVERROR_INVALIDDATA;
4675 version = avio_r8(pb);
4677 av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
4680 avio_skip(pb, 3); /* flags */
4682 avio_skip(pb, 2); /* profile + level */
4683 color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
4684 color_primaries = avio_r8(pb);
4685 color_trc = avio_r8(pb);
4686 color_space = avio_r8(pb);
4687 if (avio_rb16(pb)) /* codecIntializationDataSize */
4688 return AVERROR_INVALIDDATA;
4690 if (!av_color_primaries_name(color_primaries))
4691 color_primaries = AVCOL_PRI_UNSPECIFIED;
4692 if (!av_color_transfer_name(color_trc))
4693 color_trc = AVCOL_TRC_UNSPECIFIED;
4694 if (!av_color_space_name(color_space))
4695 color_space = AVCOL_SPC_UNSPECIFIED;
4697 st->codecpar->color_range = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
4698 st->codecpar->color_primaries = color_primaries;
4699 st->codecpar->color_trc = color_trc;
4700 st->codecpar->color_space = color_space;
4705 static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4707 MOVStreamContext *sc;
4708 const int chroma_den = 50000;
4709 const int luma_den = 10000;
4712 if (c->fc->nb_streams < 1)
4713 return AVERROR_INVALIDDATA;
4715 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
4717 if (atom.size < 5) {
4718 av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
4719 return AVERROR_INVALIDDATA;
4722 version = avio_r8(pb);
4724 av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
4727 avio_skip(pb, 3); /* flags */
4729 sc->mastering = av_mastering_display_metadata_alloc();
4731 return AVERROR(ENOMEM);
4733 for (i = 0; i < 3; i++)
4734 for (j = 0; j < 2; j++)
4735 sc->mastering->display_primaries[i][j] =
4736 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
4737 for (i = 0; i < 2; i++)
4738 sc->mastering->white_point[i] =
4739 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
4740 sc->mastering->max_luminance =
4741 av_make_q(lrint(((double)avio_rb32(pb) / (1 << 8)) * luma_den), luma_den);
4742 sc->mastering->min_luminance =
4743 av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den);
4745 sc->mastering->has_primaries = 1;
4746 sc->mastering->has_luminance = 1;
4751 static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4753 MOVStreamContext *sc;
4756 if (c->fc->nb_streams < 1)
4757 return AVERROR_INVALIDDATA;
4759 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
4761 if (atom.size < 5) {
4762 av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
4763 return AVERROR_INVALIDDATA;
4766 version = avio_r8(pb);
4768 av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
4771 avio_skip(pb, 3); /* flags */
4773 sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
4775 return AVERROR(ENOMEM);
4777 sc->coll->MaxCLL = avio_rb16(pb);
4778 sc->coll->MaxFALL = avio_rb16(pb);
4783 static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4786 MOVStreamContext *sc;
4787 enum AVStereo3DType type;
4790 if (c->fc->nb_streams < 1)
4793 st = c->fc->streams[c->fc->nb_streams - 1];
4796 if (atom.size < 5) {
4797 av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
4798 return AVERROR_INVALIDDATA;
4800 avio_skip(pb, 4); /* version + flags */
4805 type = AV_STEREO3D_2D;
4808 type = AV_STEREO3D_TOPBOTTOM;
4811 type = AV_STEREO3D_SIDEBYSIDE;
4814 av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
4818 sc->stereo3d = av_stereo3d_alloc();
4820 return AVERROR(ENOMEM);
4822 sc->stereo3d->type = type;
4826 static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4829 MOVStreamContext *sc;
4831 int32_t yaw, pitch, roll;
4832 uint32_t l = 0, t = 0, r = 0, b = 0;
4833 uint32_t tag, padding = 0;
4834 enum AVSphericalProjection projection;
4836 if (c->fc->nb_streams < 1)
4839 st = c->fc->streams[c->fc->nb_streams - 1];
4842 if (atom.size < 8) {
4843 av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
4844 return AVERROR_INVALIDDATA;
4847 size = avio_rb32(pb);
4848 if (size <= 12 || size > atom.size)
4849 return AVERROR_INVALIDDATA;
4851 tag = avio_rl32(pb);
4852 if (tag != MKTAG('s','v','h','d')) {
4853 av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
4856 avio_skip(pb, 4); /* version + flags */
4857 avio_skip(pb, size - 12); /* metadata_source */
4859 size = avio_rb32(pb);
4860 if (size > atom.size)
4861 return AVERROR_INVALIDDATA;
4863 tag = avio_rl32(pb);
4864 if (tag != MKTAG('p','r','o','j')) {
4865 av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
4869 size = avio_rb32(pb);
4870 if (size > atom.size)
4871 return AVERROR_INVALIDDATA;
4873 tag = avio_rl32(pb);
4874 if (tag != MKTAG('p','r','h','d')) {
4875 av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
4878 avio_skip(pb, 4); /* version + flags */
4880 /* 16.16 fixed point */
4881 yaw = avio_rb32(pb);
4882 pitch = avio_rb32(pb);
4883 roll = avio_rb32(pb);
4885 size = avio_rb32(pb);
4886 if (size > atom.size)
4887 return AVERROR_INVALIDDATA;
4889 tag = avio_rl32(pb);
4890 avio_skip(pb, 4); /* version + flags */
4892 case MKTAG('c','b','m','p'):
4893 layout = avio_rb32(pb);
4895 av_log(c->fc, AV_LOG_WARNING,
4896 "Unsupported cubemap layout %d\n", layout);
4899 projection = AV_SPHERICAL_CUBEMAP;
4900 padding = avio_rb32(pb);
4902 case MKTAG('e','q','u','i'):
4908 if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
4909 av_log(c->fc, AV_LOG_ERROR,
4910 "Invalid bounding rectangle coordinates "
4911 "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
4912 return AVERROR_INVALIDDATA;
4915 if (l || t || r || b)
4916 projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
4918 projection = AV_SPHERICAL_EQUIRECTANGULAR;
4921 av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n");
4925 sc->spherical = av_spherical_alloc(&sc->spherical_size);
4927 return AVERROR(ENOMEM);
4929 sc->spherical->projection = projection;
4931 sc->spherical->yaw = yaw;
4932 sc->spherical->pitch = pitch;
4933 sc->spherical->roll = roll;
4935 sc->spherical->padding = padding;
4937 sc->spherical->bound_left = l;
4938 sc->spherical->bound_top = t;
4939 sc->spherical->bound_right = r;
4940 sc->spherical->bound_bottom = b;
4945 static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
4948 uint8_t *buffer = av_malloc(len + 1);
4952 return AVERROR(ENOMEM);
4955 ret = ffio_read_size(pb, buffer, len);
4959 /* Check for mandatory keys and values, try to support XML as best-effort */
4960 if (av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
4961 (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
4962 av_stristr(val, "true") &&
4963 (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
4964 av_stristr(val, "true") &&
4965 (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
4966 av_stristr(val, "equirectangular")) {
4967 sc->spherical = av_spherical_alloc(&sc->spherical_size);
4971 sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
4973 if (av_stristr(buffer, "<GSpherical:StereoMode>")) {
4974 enum AVStereo3DType mode;
4976 if (av_stristr(buffer, "left-right"))
4977 mode = AV_STEREO3D_SIDEBYSIDE;
4978 else if (av_stristr(buffer, "top-bottom"))
4979 mode = AV_STEREO3D_TOPBOTTOM;
4981 mode = AV_STEREO3D_2D;
4983 sc->stereo3d = av_stereo3d_alloc();
4987 sc->stereo3d->type = mode;
4991 val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
4993 sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
4994 val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
4996 sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
4997 val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
4999 sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
5007 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5010 MOVStreamContext *sc;
5013 static const uint8_t uuid_isml_manifest[] = {
5014 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
5015 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
5017 static const uint8_t uuid_xmp[] = {
5018 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
5019 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
5021 static const uint8_t uuid_spherical[] = {
5022 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
5023 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
5026 if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
5027 return AVERROR_INVALIDDATA;
5029 if (c->fc->nb_streams < 1)
5031 st = c->fc->streams[c->fc->nb_streams - 1];
5034 ret = avio_read(pb, uuid, sizeof(uuid));
5037 } else if (ret != sizeof(uuid)) {
5038 return AVERROR_INVALIDDATA;
5040 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
5041 uint8_t *buffer, *ptr;
5043 size_t len = atom.size - sizeof(uuid);
5046 return AVERROR_INVALIDDATA;
5048 ret = avio_skip(pb, 4); // zeroes
5051 buffer = av_mallocz(len + 1);
5053 return AVERROR(ENOMEM);
5055 ret = avio_read(pb, buffer, len);
5059 } else if (ret != len) {
5061 return AVERROR_INVALIDDATA;
5065 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
5066 ptr += sizeof("systemBitrate=\"") - 1;
5067 c->bitrates_count++;
5068 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
5070 c->bitrates_count = 0;
5072 return AVERROR(ENOMEM);
5075 ret = strtol(ptr, &endptr, 10);
5076 if (ret < 0 || errno || *endptr != '"') {
5077 c->bitrates[c->bitrates_count - 1] = 0;
5079 c->bitrates[c->bitrates_count - 1] = ret;
5084 } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
5086 size_t len = atom.size - sizeof(uuid);
5087 if (c->export_xmp) {
5088 buffer = av_mallocz(len + 1);
5090 return AVERROR(ENOMEM);
5092 ret = avio_read(pb, buffer, len);
5096 } else if (ret != len) {
5098 return AVERROR_INVALIDDATA;
5101 av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
5104 // skip all uuid atom, which makes it fast for long uuid-xmp file
5105 ret = avio_skip(pb, len);
5109 } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
5110 size_t len = atom.size - sizeof(uuid);
5111 ret = mov_parse_uuid_spherical(sc, pb, len);
5115 av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n"); }
5120 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5123 uint8_t content[16];
5128 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
5134 && !memcmp(content, "Anevia\x1A\x1A", 8)
5135 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
5136 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
5142 static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5144 uint32_t format = avio_rl32(pb);
5145 MOVStreamContext *sc;
5149 if (c->fc->nb_streams < 1)
5151 st = c->fc->streams[c->fc->nb_streams - 1];
5156 case MKTAG('e','n','c','v'): // encrypted video
5157 case MKTAG('e','n','c','a'): // encrypted audio
5158 id = mov_codec_id(st, format);
5159 if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
5160 st->codecpar->codec_id != id) {
5161 av_log(c->fc, AV_LOG_WARNING,
5162 "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
5163 (char*)&format, st->codecpar->codec_id);
5167 st->codecpar->codec_id = id;
5168 sc->format = format;
5172 if (format != sc->format) {
5173 av_log(c->fc, AV_LOG_WARNING,
5174 "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
5175 (char*)&format, (char*)&sc->format);
5183 static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5186 MOVStreamContext *sc;
5187 size_t auxiliary_info_size;
5189 if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5192 st = c->fc->streams[c->fc->nb_streams - 1];
5195 if (sc->cenc.aes_ctr) {
5196 av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
5197 return AVERROR_INVALIDDATA;
5200 avio_r8(pb); /* version */
5201 sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
5203 avio_rb32(pb); /* entries */
5205 if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5206 av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size);
5207 return AVERROR_INVALIDDATA;
5210 /* save the auxiliary info as is */
5211 auxiliary_info_size = atom.size - 8;
5213 sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
5214 if (!sc->cenc.auxiliary_info) {
5215 return AVERROR(ENOMEM);
5218 sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
5219 sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
5220 sc->cenc.auxiliary_info_index = 0;
5222 if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
5223 av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
5224 return AVERROR_INVALIDDATA;
5227 /* initialize the cipher */
5228 sc->cenc.aes_ctr = av_aes_ctr_alloc();
5229 if (!sc->cenc.aes_ctr) {
5230 return AVERROR(ENOMEM);
5233 return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
5236 static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5239 MOVStreamContext *sc;
5241 int atom_header_size;
5244 if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5247 st = c->fc->streams[c->fc->nb_streams - 1];
5250 if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
5251 av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
5252 return AVERROR_INVALIDDATA;
5255 atom_header_size = 9;
5257 avio_r8(pb); /* version */
5258 flags = avio_rb24(pb);
5260 if ((flags & 0x01) != 0) {
5261 atom_header_size += 8;
5263 avio_rb32(pb); /* info type */
5264 avio_rb32(pb); /* info type param */
5267 sc->cenc.auxiliary_info_default_size = avio_r8(pb);
5268 avio_rb32(pb); /* entries */
5270 if (atom.size <= atom_header_size) {
5274 if (atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5275 av_log(c->fc, AV_LOG_ERROR, "saiz atom auxiliary_info_sizes size %"PRId64" invalid\n", atom.size);
5276 return AVERROR_INVALIDDATA;
5279 /* save the auxiliary info sizes as is */
5280 data_size = atom.size - atom_header_size;
5282 sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
5283 if (!sc->cenc.auxiliary_info_sizes) {
5284 return AVERROR(ENOMEM);
5287 sc->cenc.auxiliary_info_sizes_count = data_size;
5289 if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
5290 av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
5291 return AVERROR_INVALIDDATA;
5297 static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5300 int last, type, size, ret;
5303 if (c->fc->nb_streams < 1)
5305 st = c->fc->streams[c->fc->nb_streams-1];
5307 if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
5308 return AVERROR_INVALIDDATA;
5310 /* Check FlacSpecificBox version. */
5311 if (avio_r8(pb) != 0)
5312 return AVERROR_INVALIDDATA;
5314 avio_rb24(pb); /* Flags */
5316 avio_read(pb, buf, sizeof(buf));
5317 flac_parse_block_header(buf, &last, &type, &size);
5319 if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
5320 av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
5321 return AVERROR_INVALIDDATA;
5324 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
5329 av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
5334 static int mov_seek_auxiliary_info(MOVContext *c, MOVStreamContext *sc, int64_t index)
5336 size_t auxiliary_info_seek_offset = 0;
5339 if (sc->cenc.auxiliary_info_default_size) {
5340 auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * index;
5341 } else if (sc->cenc.auxiliary_info_sizes) {
5342 if (index > sc->cenc.auxiliary_info_sizes_count) {
5343 av_log(c, AV_LOG_ERROR, "current sample %"PRId64" greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
5344 index, sc->cenc.auxiliary_info_sizes_count);
5345 return AVERROR_INVALIDDATA;
5348 for (i = 0; i < index; i++) {
5349 auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
5353 if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
5354 av_log(c, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
5355 auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
5356 return AVERROR_INVALIDDATA;
5359 sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
5360 sc->cenc.auxiliary_info_index = index;
5364 static int cenc_filter(MOVContext *c, MOVStreamContext *sc, int64_t index, uint8_t *input, int size)
5366 uint32_t encrypted_bytes;
5367 uint16_t subsample_count;
5368 uint16_t clear_bytes;
5369 uint8_t* input_end = input + size;
5372 if (index != sc->cenc.auxiliary_info_index) {
5373 ret = mov_seek_auxiliary_info(c, sc, index);
5380 if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5381 av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
5382 return AVERROR_INVALIDDATA;
5385 av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
5386 sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
5388 if (!sc->cenc.use_subsamples)
5390 /* decrypt the whole packet */
5391 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
5395 /* read the subsample count */
5396 if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5397 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
5398 return AVERROR_INVALIDDATA;
5401 subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
5402 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5404 for (; subsample_count > 0; subsample_count--)
5406 if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5407 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
5408 return AVERROR_INVALIDDATA;
5411 /* read the number of clear / encrypted bytes */
5412 clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
5413 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5414 encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
5415 sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
5417 if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
5418 av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
5419 return AVERROR_INVALIDDATA;
5422 /* skip the clear bytes */
5423 input += clear_bytes;
5425 /* decrypt the encrypted bytes */
5426 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
5427 input += encrypted_bytes;
5430 if (input < input_end) {
5431 av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
5432 return AVERROR_INVALIDDATA;
5435 sc->cenc.auxiliary_info_index++;
5439 static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5441 const int OPUS_SEEK_PREROLL_MS = 80;
5446 if (c->fc->nb_streams < 1)
5448 st = c->fc->streams[c->fc->nb_streams-1];
5450 if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
5451 return AVERROR_INVALIDDATA;
5453 /* Check OpusSpecificBox version. */
5454 if (avio_r8(pb) != 0) {
5455 av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
5456 return AVERROR_INVALIDDATA;
5459 /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
5460 size = atom.size + 8;
5462 if (ff_alloc_extradata(st->codecpar, size))
5463 return AVERROR(ENOMEM);
5465 AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
5466 AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
5467 AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
5468 avio_read(pb, st->codecpar->extradata + 9, size - 9);
5470 /* OpusSpecificBox is stored in big-endian, but OpusHead is
5471 little-endian; aside from the preceeding magic and version they're
5472 otherwise currently identical. Data after output gain at offset 16
5473 doesn't need to be bytewapped. */
5474 pre_skip = AV_RB16(st->codecpar->extradata + 10);
5475 AV_WL16(st->codecpar->extradata + 10, pre_skip);
5476 AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
5477 AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
5479 st->codecpar->initial_padding = pre_skip;
5480 st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
5481 (AVRational){1, 1000},
5482 (AVRational){1, 48000});
5487 static const MOVParseTableEntry mov_default_parse_table[] = {
5488 { MKTAG('A','C','L','R'), mov_read_aclr },
5489 { MKTAG('A','P','R','G'), mov_read_avid },
5490 { MKTAG('A','A','L','P'), mov_read_avid },
5491 { MKTAG('A','R','E','S'), mov_read_ares },
5492 { MKTAG('a','v','s','s'), mov_read_avss },
5493 { MKTAG('c','h','p','l'), mov_read_chpl },
5494 { MKTAG('c','o','6','4'), mov_read_stco },
5495 { MKTAG('c','o','l','r'), mov_read_colr },
5496 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
5497 { MKTAG('d','i','n','f'), mov_read_default },
5498 { MKTAG('D','p','x','E'), mov_read_dpxe },
5499 { MKTAG('d','r','e','f'), mov_read_dref },
5500 { MKTAG('e','d','t','s'), mov_read_default },
5501 { MKTAG('e','l','s','t'), mov_read_elst },
5502 { MKTAG('e','n','d','a'), mov_read_enda },
5503 { MKTAG('f','i','e','l'), mov_read_fiel },
5504 { MKTAG('a','d','r','m'), mov_read_adrm },
5505 { MKTAG('f','t','y','p'), mov_read_ftyp },
5506 { MKTAG('g','l','b','l'), mov_read_glbl },
5507 { MKTAG('h','d','l','r'), mov_read_hdlr },
5508 { MKTAG('i','l','s','t'), mov_read_ilst },
5509 { MKTAG('j','p','2','h'), mov_read_jp2h },
5510 { MKTAG('m','d','a','t'), mov_read_mdat },
5511 { MKTAG('m','d','h','d'), mov_read_mdhd },
5512 { MKTAG('m','d','i','a'), mov_read_default },
5513 { MKTAG('m','e','t','a'), mov_read_meta },
5514 { MKTAG('m','i','n','f'), mov_read_default },
5515 { MKTAG('m','o','o','f'), mov_read_moof },
5516 { MKTAG('m','o','o','v'), mov_read_moov },
5517 { MKTAG('m','v','e','x'), mov_read_default },
5518 { MKTAG('m','v','h','d'), mov_read_mvhd },
5519 { MKTAG('S','M','I',' '), mov_read_svq3 },
5520 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
5521 { MKTAG('a','v','c','C'), mov_read_glbl },
5522 { MKTAG('p','a','s','p'), mov_read_pasp },
5523 { MKTAG('s','i','d','x'), mov_read_sidx },
5524 { MKTAG('s','t','b','l'), mov_read_default },
5525 { MKTAG('s','t','c','o'), mov_read_stco },
5526 { MKTAG('s','t','p','s'), mov_read_stps },
5527 { MKTAG('s','t','r','f'), mov_read_strf },
5528 { MKTAG('s','t','s','c'), mov_read_stsc },
5529 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
5530 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
5531 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
5532 { MKTAG('s','t','t','s'), mov_read_stts },
5533 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
5534 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
5535 { MKTAG('t','f','d','t'), mov_read_tfdt },
5536 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
5537 { MKTAG('t','r','a','k'), mov_read_trak },
5538 { MKTAG('t','r','a','f'), mov_read_default },
5539 { MKTAG('t','r','e','f'), mov_read_default },
5540 { MKTAG('t','m','c','d'), mov_read_tmcd },
5541 { MKTAG('c','h','a','p'), mov_read_chap },
5542 { MKTAG('t','r','e','x'), mov_read_trex },
5543 { MKTAG('t','r','u','n'), mov_read_trun },
5544 { MKTAG('u','d','t','a'), mov_read_default },
5545 { MKTAG('w','a','v','e'), mov_read_wave },
5546 { MKTAG('e','s','d','s'), mov_read_esds },
5547 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
5548 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
5549 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
5550 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
5551 { MKTAG('w','f','e','x'), mov_read_wfex },
5552 { MKTAG('c','m','o','v'), mov_read_cmov },
5553 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
5554 { MKTAG('d','v','c','1'), mov_read_dvc1 },
5555 { MKTAG('s','b','g','p'), mov_read_sbgp },
5556 { MKTAG('h','v','c','C'), mov_read_glbl },
5557 { MKTAG('u','u','i','d'), mov_read_uuid },
5558 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
5559 { MKTAG('f','r','e','e'), mov_read_free },
5560 { MKTAG('-','-','-','-'), mov_read_custom },
5561 { MKTAG('s','i','n','f'), mov_read_default },
5562 { MKTAG('f','r','m','a'), mov_read_frma },
5563 { MKTAG('s','e','n','c'), mov_read_senc },
5564 { MKTAG('s','a','i','z'), mov_read_saiz },
5565 { MKTAG('d','f','L','a'), mov_read_dfla },
5566 { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
5567 { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
5568 { MKTAG('d','O','p','s'), mov_read_dops },
5569 { MKTAG('S','m','D','m'), mov_read_smdm },
5570 { MKTAG('C','o','L','L'), mov_read_coll },
5571 { MKTAG('v','p','c','C'), mov_read_vpcc },
5575 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5577 int64_t total_size = 0;
5581 if (c->atom_depth > 10) {
5582 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
5583 return AVERROR_INVALIDDATA;
5588 atom.size = INT64_MAX;
5589 while (total_size <= atom.size - 8 && !avio_feof(pb)) {
5590 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
5593 if (atom.size >= 8) {
5594 a.size = avio_rb32(pb);
5595 a.type = avio_rl32(pb);
5596 if (a.type == MKTAG('f','r','e','e') &&
5598 c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
5601 uint32_t *type = (uint32_t *)buf + 1;
5602 if (avio_read(pb, buf, 8) != 8)
5603 return AVERROR_INVALIDDATA;
5604 avio_seek(pb, -8, SEEK_CUR);
5605 if (*type == MKTAG('m','v','h','d') ||
5606 *type == MKTAG('c','m','o','v')) {
5607 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
5608 a.type = MKTAG('m','o','o','v');
5611 if (atom.type != MKTAG('r','o','o','t') &&
5612 atom.type != MKTAG('m','o','o','v'))
5614 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
5616 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
5623 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
5624 a.size = avio_rb64(pb) - 8;
5628 av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
5629 av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
5631 a.size = atom.size - total_size + 8;
5636 a.size = FFMIN(a.size, atom.size - total_size);
5638 for (i = 0; mov_default_parse_table[i].type; i++)
5639 if (mov_default_parse_table[i].type == a.type) {
5640 parse = mov_default_parse_table[i].parse;
5644 // container is user data
5645 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
5646 atom.type == MKTAG('i','l','s','t')))
5647 parse = mov_read_udta_string;
5649 // Supports parsing the QuickTime Metadata Keys.
5650 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
5651 if (!parse && c->found_hdlr_mdta &&
5652 atom.type == MKTAG('m','e','t','a') &&
5653 a.type == MKTAG('k','e','y','s')) {
5654 parse = mov_read_keys;
5657 if (!parse) { /* skip leaf atoms data */
5658 avio_skip(pb, a.size);
5660 int64_t start_pos = avio_tell(pb);
5662 int err = parse(c, pb, a);
5667 if (c->found_moov && c->found_mdat &&
5668 ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
5669 start_pos + a.size == avio_size(pb))) {
5670 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
5671 c->next_root_atom = start_pos + a.size;
5675 left = a.size - avio_tell(pb) + start_pos;
5676 if (left > 0) /* skip garbage at atom end */
5677 avio_skip(pb, left);
5678 else if (left < 0) {
5679 av_log(c->fc, AV_LOG_WARNING,
5680 "overread end of atom '%.4s' by %"PRId64" bytes\n",
5681 (char*)&a.type, -left);
5682 avio_seek(pb, left, SEEK_CUR);
5686 total_size += a.size;
5689 if (total_size < atom.size && atom.size < 0x7ffff)
5690 avio_skip(pb, atom.size - total_size);
5696 static int mov_probe(AVProbeData *p)
5701 int moov_offset = -1;
5703 /* check file header */
5706 /* ignore invalid offset */
5707 if ((offset + 8) > (unsigned int)p->buf_size)
5709 tag = AV_RL32(p->buf + offset + 4);
5711 /* check for obvious tags */
5712 case MKTAG('m','o','o','v'):
5713 moov_offset = offset + 4;
5714 case MKTAG('m','d','a','t'):
5715 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
5716 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
5717 case MKTAG('f','t','y','p'):
5718 if (AV_RB32(p->buf+offset) < 8 &&
5719 (AV_RB32(p->buf+offset) != 1 ||
5720 offset + 12 > (unsigned int)p->buf_size ||
5721 AV_RB64(p->buf+offset + 8) == 0)) {
5722 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
5723 } else if (tag == MKTAG('f','t','y','p') &&
5724 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
5725 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
5727 score = FFMAX(score, 5);
5729 score = AVPROBE_SCORE_MAX;
5731 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
5733 /* those are more common words, so rate then a bit less */
5734 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
5735 case MKTAG('w','i','d','e'):
5736 case MKTAG('f','r','e','e'):
5737 case MKTAG('j','u','n','k'):
5738 case MKTAG('p','i','c','t'):
5739 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
5740 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
5742 case MKTAG(0x82,0x82,0x7f,0x7d):
5743 case MKTAG('s','k','i','p'):
5744 case MKTAG('u','u','i','d'):
5745 case MKTAG('p','r','f','l'):
5746 /* if we only find those cause probedata is too small at least rate them */
5747 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
5748 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
5751 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
5754 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
5755 /* moov atom in the header - we should make sure that this is not a
5756 * MOV-packed MPEG-PS */
5757 offset = moov_offset;
5759 while(offset < (p->buf_size - 16)){ /* Sufficient space */
5760 /* We found an actual hdlr atom */
5761 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
5762 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
5763 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
5764 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
5765 /* We found a media handler reference atom describing an
5766 * MPEG-PS-in-MOV, return a
5767 * low score to force expanding the probe window until
5768 * mpegps_probe finds what it needs */
5779 // must be done after parsing all trak because there's no order requirement
5780 static void mov_read_chapters(AVFormatContext *s)
5782 MOVContext *mov = s->priv_data;
5784 MOVStreamContext *sc;
5789 for (j = 0; j < mov->nb_chapter_tracks; j++) {
5790 chapter_track = mov->chapter_tracks[j];
5792 for (i = 0; i < s->nb_streams; i++)
5793 if (s->streams[i]->id == chapter_track) {
5798 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
5803 cur_pos = avio_tell(sc->pb);
5805 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5806 st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
5807 if (st->nb_index_entries) {
5808 // Retrieve the first frame, if possible
5810 AVIndexEntry *sample = &st->index_entries[0];
5811 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
5812 av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
5816 if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
5819 st->attached_pic = pkt;
5820 st->attached_pic.stream_index = st->index;
5821 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
5824 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
5825 st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
5826 st->discard = AVDISCARD_ALL;
5827 for (i = 0; i < st->nb_index_entries; i++) {
5828 AVIndexEntry *sample = &st->index_entries[i];
5829 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
5834 if (end < sample->timestamp) {
5835 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
5836 end = AV_NOPTS_VALUE;
5839 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
5840 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
5844 // the first two bytes are the length of the title
5845 len = avio_rb16(sc->pb);
5846 if (len > sample->size-2)
5848 title_len = 2*len + 1;
5849 if (!(title = av_mallocz(title_len)))
5852 // The samples could theoretically be in any encoding if there's an encd
5853 // atom following, but in practice are only utf-8 or utf-16, distinguished
5854 // instead by the presence of a BOM
5858 ch = avio_rb16(sc->pb);
5860 avio_get_str16be(sc->pb, len, title, title_len);
5861 else if (ch == 0xfffe)
5862 avio_get_str16le(sc->pb, len, title, title_len);
5865 if (len == 1 || len == 2)
5868 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
5872 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
5877 avio_seek(sc->pb, cur_pos, SEEK_SET);
5881 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
5882 uint32_t value, int flags)
5885 char buf[AV_TIMECODE_STR_SIZE];
5886 AVRational rate = st->avg_frame_rate;
5887 int ret = av_timecode_init(&tc, rate, flags, 0, s);
5890 av_dict_set(&st->metadata, "timecode",
5891 av_timecode_make_string(&tc, buf, value), 0);
5895 static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
5897 MOVStreamContext *sc = st->priv_data;
5898 char buf[AV_TIMECODE_STR_SIZE];
5899 int64_t cur_pos = avio_tell(sc->pb);
5900 int hh, mm, ss, ff, drop;
5902 if (!st->nb_index_entries)
5905 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
5906 avio_skip(s->pb, 13);
5907 hh = avio_r8(s->pb);
5908 mm = avio_r8(s->pb);
5909 ss = avio_r8(s->pb);
5910 drop = avio_r8(s->pb);
5911 ff = avio_r8(s->pb);
5912 snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
5913 hh, mm, ss, drop ? ';' : ':', ff);
5914 av_dict_set(&st->metadata, "timecode", buf, 0);
5916 avio_seek(sc->pb, cur_pos, SEEK_SET);
5920 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
5922 MOVStreamContext *sc = st->priv_data;
5924 int64_t cur_pos = avio_tell(sc->pb);
5927 if (!st->nb_index_entries)
5930 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
5931 value = avio_rb32(s->pb);
5933 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
5934 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
5935 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
5937 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
5938 * not the case) and thus assume "frame number format" instead of QT one.
5939 * No sample with tmcd track can be found with a QT timecode at the moment,
5940 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
5942 parse_timecode_in_framenum_format(s, st, value, flags);
5944 avio_seek(sc->pb, cur_pos, SEEK_SET);
5948 static int mov_read_close(AVFormatContext *s)
5950 MOVContext *mov = s->priv_data;
5953 for (i = 0; i < s->nb_streams; i++) {
5954 AVStream *st = s->streams[i];
5955 MOVStreamContext *sc = st->priv_data;
5960 av_freep(&sc->ctts_data);
5961 for (j = 0; j < sc->drefs_count; j++) {
5962 av_freep(&sc->drefs[j].path);
5963 av_freep(&sc->drefs[j].dir);
5965 av_freep(&sc->drefs);
5967 sc->drefs_count = 0;
5969 if (!sc->pb_is_copied)
5970 ff_format_io_close(s, &sc->pb);
5973 av_freep(&sc->chunk_offsets);
5974 av_freep(&sc->stsc_data);
5975 av_freep(&sc->sample_sizes);
5976 av_freep(&sc->keyframes);
5977 av_freep(&sc->stts_data);
5978 av_freep(&sc->stps_data);
5979 av_freep(&sc->elst_data);
5980 av_freep(&sc->rap_group);
5981 av_freep(&sc->display_matrix);
5982 av_freep(&sc->index_ranges);
5985 for (j = 0; j < sc->stsd_count; j++)
5986 av_free(sc->extradata[j]);
5987 av_freep(&sc->extradata);
5988 av_freep(&sc->extradata_size);
5990 av_freep(&sc->cenc.auxiliary_info);
5991 av_freep(&sc->cenc.auxiliary_info_sizes);
5992 av_aes_ctr_free(sc->cenc.aes_ctr);
5994 av_freep(&sc->stereo3d);
5995 av_freep(&sc->spherical);
5996 av_freep(&sc->mastering);
5997 av_freep(&sc->coll);
6000 if (mov->dv_demux) {
6001 avformat_free_context(mov->dv_fctx);
6002 mov->dv_fctx = NULL;
6005 if (mov->meta_keys) {
6006 for (i = 1; i < mov->meta_keys_count; i++) {
6007 av_freep(&mov->meta_keys[i]);
6009 av_freep(&mov->meta_keys);
6012 av_freep(&mov->trex_data);
6013 av_freep(&mov->bitrates);
6015 for (i = 0; i < mov->fragment_index_count; i++) {
6016 MOVFragmentIndex* index = mov->fragment_index_data[i];
6017 av_freep(&index->items);
6018 av_freep(&mov->fragment_index_data[i]);
6020 av_freep(&mov->fragment_index_data);
6022 av_freep(&mov->aes_decrypt);
6023 av_freep(&mov->chapter_tracks);
6028 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
6032 for (i = 0; i < s->nb_streams; i++) {
6033 AVStream *st = s->streams[i];
6034 MOVStreamContext *sc = st->priv_data;
6036 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6037 sc->timecode_track == tmcd_id)
6043 /* look for a tmcd track not referenced by any video track, and export it globally */
6044 static void export_orphan_timecode(AVFormatContext *s)
6048 for (i = 0; i < s->nb_streams; i++) {
6049 AVStream *st = s->streams[i];
6051 if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
6052 !tmcd_is_referenced(s, i + 1)) {
6053 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
6055 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
6062 static int read_tfra(MOVContext *mov, AVIOContext *f)
6064 MOVFragmentIndex* index = NULL;
6065 int version, fieldlength, i, j;
6066 int64_t pos = avio_tell(f);
6067 uint32_t size = avio_rb32(f);
6070 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
6073 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
6074 index = av_mallocz(sizeof(MOVFragmentIndex));
6076 return AVERROR(ENOMEM);
6079 tmp = av_realloc_array(mov->fragment_index_data,
6080 mov->fragment_index_count + 1,
6081 sizeof(MOVFragmentIndex*));
6084 return AVERROR(ENOMEM);
6086 mov->fragment_index_data = tmp;
6087 mov->fragment_index_data[mov->fragment_index_count++] = index;
6089 version = avio_r8(f);
6091 index->track_id = avio_rb32(f);
6092 fieldlength = avio_rb32(f);
6093 index->item_count = avio_rb32(f);
6094 index->items = av_mallocz_array(
6095 index->item_count, sizeof(MOVFragmentIndexItem));
6096 if (!index->items) {
6097 index->item_count = 0;
6098 return AVERROR(ENOMEM);
6100 for (i = 0; i < index->item_count; i++) {
6101 int64_t time, offset;
6104 index->item_count = 0;
6105 av_freep(&index->items);
6106 return AVERROR_INVALIDDATA;
6110 time = avio_rb64(f);
6111 offset = avio_rb64(f);
6113 time = avio_rb32(f);
6114 offset = avio_rb32(f);
6116 index->items[i].time = time;
6117 index->items[i].moof_offset = offset;
6118 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
6120 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
6122 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
6126 avio_seek(f, pos + size, SEEK_SET);
6130 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
6132 int64_t stream_size = avio_size(f);
6133 int64_t original_pos = avio_tell(f);
6137 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
6141 mfra_size = avio_rb32(f);
6142 if (mfra_size < 0 || mfra_size > stream_size) {
6143 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
6146 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
6150 if (avio_rb32(f) != mfra_size) {
6151 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
6154 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
6155 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
6158 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
6160 ret = read_tfra(c, f);
6166 seek_ret = avio_seek(f, original_pos, SEEK_SET);
6168 av_log(c->fc, AV_LOG_ERROR,
6169 "failed to seek back after looking for mfra\n");
6175 static int mov_read_header(AVFormatContext *s)
6177 MOVContext *mov = s->priv_data;
6178 AVIOContext *pb = s->pb;
6180 MOVAtom atom = { AV_RL32("root") };
6183 if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
6184 av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
6185 mov->decryption_key_len, AES_CTR_KEY_SIZE);
6186 return AVERROR(EINVAL);
6190 mov->trak_index = -1;
6191 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
6192 if (pb->seekable & AVIO_SEEKABLE_NORMAL)
6193 atom.size = avio_size(pb);
6195 atom.size = INT64_MAX;
6197 /* check MOV header */
6199 if (mov->moov_retry)
6200 avio_seek(pb, 0, SEEK_SET);
6201 if ((err = mov_read_default(mov, pb, atom)) < 0) {
6202 av_log(s, AV_LOG_ERROR, "error reading header\n");
6206 } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
6207 if (!mov->found_moov) {
6208 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
6210 return AVERROR_INVALIDDATA;
6212 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
6214 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
6215 if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
6216 mov_read_chapters(s);
6217 for (i = 0; i < s->nb_streams; i++)
6218 if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
6219 mov_read_timecode_track(s, s->streams[i]);
6220 } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
6221 mov_read_rtmd_track(s, s->streams[i]);
6225 /* copy timecode metadata from tmcd tracks to the related video streams */
6226 for (i = 0; i < s->nb_streams; i++) {
6227 AVStream *st = s->streams[i];
6228 MOVStreamContext *sc = st->priv_data;
6229 if (sc->timecode_track > 0) {
6230 AVDictionaryEntry *tcr;
6231 int tmcd_st_id = -1;
6233 for (j = 0; j < s->nb_streams; j++)
6234 if (s->streams[j]->id == sc->timecode_track)
6237 if (tmcd_st_id < 0 || tmcd_st_id == i)
6239 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
6241 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
6244 export_orphan_timecode(s);
6246 for (i = 0; i < s->nb_streams; i++) {
6247 AVStream *st = s->streams[i];
6248 MOVStreamContext *sc = st->priv_data;
6249 fix_timescale(mov, sc);
6250 if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6251 st->skip_samples = sc->start_pad;
6253 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
6254 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
6255 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
6256 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6257 if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
6258 st->codecpar->width = sc->width;
6259 st->codecpar->height = sc->height;
6261 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
6262 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
6266 if (mov->handbrake_version &&
6267 mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
6268 st->codecpar->codec_id == AV_CODEC_ID_MP3
6270 av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
6271 st->need_parsing = AVSTREAM_PARSE_FULL;
6275 if (mov->trex_data) {
6276 for (i = 0; i < s->nb_streams; i++) {
6277 AVStream *st = s->streams[i];
6278 MOVStreamContext *sc = st->priv_data;
6279 if (st->duration > 0) {
6280 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6281 av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6282 sc->data_size, sc->time_scale);
6284 return AVERROR_INVALIDDATA;
6286 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
6291 if (mov->use_mfra_for > 0) {
6292 for (i = 0; i < s->nb_streams; i++) {
6293 AVStream *st = s->streams[i];
6294 MOVStreamContext *sc = st->priv_data;
6295 if (sc->duration_for_fps > 0) {
6296 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6297 av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6298 sc->data_size, sc->time_scale);
6300 return AVERROR_INVALIDDATA;
6302 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
6303 sc->duration_for_fps;
6308 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
6309 if (mov->bitrates[i]) {
6310 s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
6314 ff_rfps_calculate(s);
6316 for (i = 0; i < s->nb_streams; i++) {
6317 AVStream *st = s->streams[i];
6318 MOVStreamContext *sc = st->priv_data;
6320 switch (st->codecpar->codec_type) {
6321 case AVMEDIA_TYPE_AUDIO:
6322 err = ff_replaygain_export(st, s->metadata);
6328 case AVMEDIA_TYPE_VIDEO:
6329 if (sc->display_matrix) {
6330 err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix,
6331 sizeof(int32_t) * 9);
6335 sc->display_matrix = NULL;
6338 err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
6339 (uint8_t *)sc->stereo3d,
6340 sizeof(*sc->stereo3d));
6344 sc->stereo3d = NULL;
6346 if (sc->spherical) {
6347 err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
6348 (uint8_t *)sc->spherical,
6349 sc->spherical_size);
6353 sc->spherical = NULL;
6355 if (sc->mastering) {
6356 err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
6357 (uint8_t *)sc->mastering,
6358 sizeof(*sc->mastering));
6362 sc->mastering = NULL;
6365 err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
6366 (uint8_t *)sc->coll,
6376 ff_configure_buffers_for_index(s, AV_TIME_BASE);
6378 for (i = 0; i < mov->fragment_index_count; i++) {
6379 MOVFragmentIndex *idx = mov->fragment_index_data[i];
6380 for (j = 0; j < idx->item_count; j++)
6381 if (idx->items[j].moof_offset <= mov->fragment.moof_offset)
6382 idx->items[j].headers_read = 1;
6388 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
6390 AVIndexEntry *sample = NULL;
6391 int64_t best_dts = INT64_MAX;
6393 for (i = 0; i < s->nb_streams; i++) {
6394 AVStream *avst = s->streams[i];
6395 MOVStreamContext *msc = avst->priv_data;
6396 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
6397 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
6398 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
6399 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
6400 if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
6401 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6402 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
6403 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
6404 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
6405 sample = current_sample;
6414 static int should_retry(AVIOContext *pb, int error_code) {
6415 if (error_code == AVERROR_EOF || avio_feof(pb))
6421 static int mov_switch_root(AVFormatContext *s, int64_t target)
6423 MOVContext *mov = s->priv_data;
6425 int already_read = 0;
6427 if (avio_seek(s->pb, target, SEEK_SET) != target) {
6428 av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
6429 return AVERROR_INVALIDDATA;
6432 mov->next_root_atom = 0;
6434 for (i = 0; i < mov->fragment_index_count; i++) {
6435 MOVFragmentIndex *index = mov->fragment_index_data[i];
6437 for (j = 0; j < index->item_count; j++) {
6438 MOVFragmentIndexItem *item = &index->items[j];
6440 mov->next_root_atom = item->moof_offset;
6441 break; // Advance to next index in outer loop
6442 } else if (item->moof_offset == target) {
6443 index->current_item = FFMIN(j, index->current_item);
6444 if (item->headers_read)
6446 item->headers_read = 1;
6451 index->current_item = 0;
6457 mov->found_mdat = 0;
6459 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
6462 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
6467 static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
6469 uint8_t *side, *extradata;
6472 /* Save the current index. */
6473 sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
6475 /* Notify the decoder that extradata changed. */
6476 extradata_size = sc->extradata_size[sc->last_stsd_index];
6477 extradata = sc->extradata[sc->last_stsd_index];
6478 if (extradata_size > 0 && extradata) {
6479 side = av_packet_new_side_data(pkt,
6480 AV_PKT_DATA_NEW_EXTRADATA,
6483 return AVERROR(ENOMEM);
6484 memcpy(side, extradata, extradata_size);
6490 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
6492 MOVContext *mov = s->priv_data;
6493 MOVStreamContext *sc;
6494 AVIndexEntry *sample;
6495 AVStream *st = NULL;
6496 int64_t current_index;
6500 sample = mov_find_next_sample(s, &st);
6501 if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
6502 if (!mov->next_root_atom)
6504 if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
6509 /* must be done just before reading, to avoid infinite loop on sample */
6510 current_index = sc->current_index;
6511 mov_current_sample_inc(sc);
6513 if (mov->next_root_atom) {
6514 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
6515 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
6518 if (st->discard != AVDISCARD_ALL) {
6519 int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
6520 if (ret64 != sample->pos) {
6521 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
6522 sc->ffindex, sample->pos);
6523 if (should_retry(sc->pb, ret64)) {
6524 mov_current_sample_dec(sc);
6526 return AVERROR_INVALIDDATA;
6529 if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
6530 av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
6534 ret = av_get_packet(sc->pb, pkt, sample->size);
6536 if (should_retry(sc->pb, ret)) {
6537 mov_current_sample_dec(sc);
6541 if (sc->has_palette) {
6544 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
6546 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
6548 memcpy(pal, sc->palette, AVPALETTE_SIZE);
6549 sc->has_palette = 0;
6552 #if CONFIG_DV_DEMUXER
6553 if (mov->dv_demux && sc->dv_audio_container) {
6554 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
6555 av_freep(&pkt->data);
6557 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
6562 if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
6563 if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
6564 st->need_parsing = AVSTREAM_PARSE_FULL;
6568 pkt->stream_index = sc->ffindex;
6569 pkt->dts = sample->timestamp;
6570 if (sample->flags & AVINDEX_DISCARD_FRAME) {
6571 pkt->flags |= AV_PKT_FLAG_DISCARD;
6573 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
6574 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
6575 /* update ctts context */
6577 if (sc->ctts_index < sc->ctts_count &&
6578 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
6580 sc->ctts_sample = 0;
6583 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
6584 st->index_entries[sc->current_sample].timestamp : st->duration;
6585 pkt->duration = next_dts - pkt->dts;
6586 pkt->pts = pkt->dts;
6588 if (st->discard == AVDISCARD_ALL)
6590 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
6591 pkt->pos = sample->pos;
6593 /* Multiple stsd handling. */
6594 if (sc->stsc_data) {
6595 /* Keep track of the stsc index for the given sample, then check
6596 * if the stsd index is different from the last used one. */
6598 if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
6599 mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
6601 sc->stsc_sample = 0;
6602 /* Do not check indexes after a switch. */
6603 } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
6604 sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
6605 sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
6606 ret = mov_change_extradata(sc, pkt);
6613 aax_filter(pkt->data, pkt->size, mov);
6615 if (sc->cenc.aes_ctr) {
6616 ret = cenc_filter(mov, sc, current_index, pkt->data, pkt->size);
6625 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
6627 MOVContext *mov = s->priv_data;
6628 MOVStreamContext *sc = st->priv_data;
6631 if (!mov->fragment_index_complete)
6634 for (i = 0; i < mov->fragment_index_count; i++) {
6635 if (mov->fragment_index_data[i]->track_id == st->id || !sc->has_sidx) {
6636 MOVFragmentIndex *index = mov->fragment_index_data[i];
6637 for (j = index->item_count - 1; j >= 0; j--) {
6638 if (index->items[j].time <= timestamp) {
6639 if (index->items[j].headers_read)
6642 return mov_switch_root(s, index->items[j].moof_offset);
6651 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
6653 MOVStreamContext *sc = st->priv_data;
6654 int sample, time_sample;
6657 int ret = mov_seek_fragment(s, st, timestamp);
6661 sample = av_index_search_timestamp(st, timestamp, flags);
6662 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
6663 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
6665 if (sample < 0) /* not sure what to do */
6666 return AVERROR_INVALIDDATA;
6667 mov_current_sample_set(sc, sample);
6668 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
6669 /* adjust ctts index */
6670 if (sc->ctts_data) {
6672 for (i = 0; i < sc->ctts_count; i++) {
6673 int next = time_sample + sc->ctts_data[i].count;
6674 if (next > sc->current_sample) {
6676 sc->ctts_sample = sc->current_sample - time_sample;
6683 /* adjust stsd index */
6685 for (i = 0; i < sc->stsc_count; i++) {
6686 int next = time_sample + mov_get_stsc_samples(sc, i);
6687 if (next > sc->current_sample) {
6689 sc->stsc_sample = sc->current_sample - time_sample;
6698 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
6700 MOVContext *mc = s->priv_data;
6705 if (stream_index >= s->nb_streams)
6706 return AVERROR_INVALIDDATA;
6708 st = s->streams[stream_index];
6709 sample = mov_seek_stream(s, st, sample_time, flags);
6713 if (mc->seek_individually) {
6714 /* adjust seek timestamp to found sample timestamp */
6715 int64_t seek_timestamp = st->index_entries[sample].timestamp;
6717 for (i = 0; i < s->nb_streams; i++) {
6719 MOVStreamContext *sc = s->streams[i]->priv_data;
6721 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
6723 if (stream_index == i)
6726 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
6727 mov_seek_stream(s, st, timestamp, flags);
6730 for (i = 0; i < s->nb_streams; i++) {
6731 MOVStreamContext *sc;
6734 mov_current_sample_set(sc, 0);
6737 MOVStreamContext *sc;
6738 AVIndexEntry *entry = mov_find_next_sample(s, &st);
6740 return AVERROR_INVALIDDATA;
6742 if (sc->ffindex == stream_index && sc->current_sample == sample)
6744 mov_current_sample_inc(sc);
6750 #define OFFSET(x) offsetof(MOVContext, x)
6751 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
6752 static const AVOption mov_options[] = {
6753 {"use_absolute_path",
6754 "allow using absolute path when opening alias, this is a possible security issue",
6755 OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
6757 {"seek_streams_individually",
6758 "Seek each stream individually to the to the closest point",
6759 OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
6761 {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
6763 {"advanced_editlist",
6764 "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
6765 OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
6767 {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
6770 "use mfra for fragment timestamps",
6771 OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
6772 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
6774 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
6775 FLAGS, "use_mfra_for" },
6776 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
6777 FLAGS, "use_mfra_for" },
6778 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
6779 FLAGS, "use_mfra_for" },
6780 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
6781 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
6782 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
6783 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
6784 { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
6785 AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
6786 { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
6787 "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
6788 AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
6789 .flags = AV_OPT_FLAG_DECODING_PARAM },
6790 { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
6791 { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
6792 {.i64 = 0}, 0, 1, FLAGS },
6797 static const AVClass mov_class = {
6798 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
6799 .item_name = av_default_item_name,
6800 .option = mov_options,
6801 .version = LIBAVUTIL_VERSION_INT,
6804 AVInputFormat ff_mov_demuxer = {
6805 .name = "mov,mp4,m4a,3gp,3g2,mj2",
6806 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
6807 .priv_class = &mov_class,
6808 .priv_data_size = sizeof(MOVContext),
6809 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
6810 .read_probe = mov_probe,
6811 .read_header = mov_read_header,
6812 .read_packet = mov_read_packet,
6813 .read_close = mov_read_close,
6814 .read_seek = mov_read_seek,
6815 .flags = AVFMT_NO_BYTE_SEEK,