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( 'm','a','n','u'): key = "make"; break;
340 case MKTAG( 'm','o','d','l'): key = "model"; break;
341 case MKTAG( 'p','c','s','t'): key = "podcast";
342 parse = mov_metadata_int8_no_padding; break;
343 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
344 parse = mov_metadata_int8_no_padding; break;
345 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
346 case MKTAG( 'r','t','n','g'): key = "rating";
347 parse = mov_metadata_int8_no_padding; break;
348 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
349 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
350 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
351 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
352 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
353 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
354 case MKTAG( 's','t','i','k'): key = "media_type";
355 parse = mov_metadata_int8_no_padding; break;
356 case MKTAG( 't','r','k','n'): key = "track";
357 parse = mov_metadata_track_or_disc_number; break;
358 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
359 case MKTAG( 't','v','e','s'): key = "episode_sort";
360 parse = mov_metadata_int8_bypass_padding; break;
361 case MKTAG( 't','v','n','n'): key = "network"; break;
362 case MKTAG( 't','v','s','h'): key = "show"; break;
363 case MKTAG( 't','v','s','n'): key = "season_number";
364 parse = mov_metadata_int8_bypass_padding; break;
365 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
366 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
367 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
368 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
369 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
370 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
371 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
372 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
373 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
374 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
375 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
376 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
377 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
378 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
379 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
380 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
381 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
382 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
383 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
384 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
385 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
386 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
387 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
388 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
389 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
390 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
391 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
392 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
393 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
394 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
395 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
396 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
397 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
398 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
399 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
402 if (c->itunes_metadata && atom.size > 8) {
403 int data_size = avio_rb32(pb);
404 int tag = avio_rl32(pb);
405 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
406 data_type = avio_rb32(pb); // type
407 avio_rb32(pb); // unknown
408 str_size = data_size - 16;
411 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
412 int ret = mov_read_covr(c, pb, data_type, str_size);
414 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
417 } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
418 uint32_t index = AV_RB32(&atom.type);
419 if (index < c->meta_keys_count && index > 0) {
420 key = c->meta_keys[index];
422 av_log(c->fc, AV_LOG_WARNING,
423 "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n",
424 index, c->meta_keys_count);
428 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
429 str_size = avio_rb16(pb); // string length
430 if (str_size > atom.size) {
432 avio_seek(pb, -2, SEEK_CUR);
433 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
436 langcode = avio_rb16(pb);
437 ff_mov_lang_to_iso639(langcode, language);
440 str_size = atom.size;
442 if (c->export_all && !key) {
443 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
449 if (atom.size < 0 || str_size >= INT_MAX/2)
450 return AVERROR_INVALIDDATA;
452 // Allocates enough space if data_type is a int32 or float32 number, otherwise
453 // worst-case requirement for output string in case of utf8 coded input
454 num = (data_type >= 21 && data_type <= 23);
455 str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
456 str = av_mallocz(str_size_alloc);
458 return AVERROR(ENOMEM);
461 parse(c, pb, str_size, key);
463 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
464 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
465 } else if (data_type == 21) { // BE signed integer, variable size
468 val = (int8_t)avio_r8(pb);
469 else if (str_size == 2)
470 val = (int16_t)avio_rb16(pb);
471 else if (str_size == 3)
472 val = ((int32_t)(avio_rb24(pb)<<8))>>8;
473 else if (str_size == 4)
474 val = (int32_t)avio_rb32(pb);
475 if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
476 av_log(c->fc, AV_LOG_ERROR,
477 "Failed to store the number (%d) in string.\n", val);
479 return AVERROR_INVALIDDATA;
481 } else if (data_type == 22) { // BE unsigned integer, variable size
482 unsigned int val = 0;
485 else if (str_size == 2)
487 else if (str_size == 3)
489 else if (str_size == 4)
491 if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
492 av_log(c->fc, AV_LOG_ERROR,
493 "Failed to store the number (%u) in string.\n", val);
495 return AVERROR_INVALIDDATA;
497 } else if (data_type == 23 && str_size >= 4) { // BE float32
498 float val = av_int2float(avio_rb32(pb));
499 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
500 av_log(c->fc, AV_LOG_ERROR,
501 "Failed to store the float32 number (%f) in string.\n", val);
503 return AVERROR_INVALIDDATA;
506 int ret = ffio_read_size(pb, str, str_size);
513 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
514 av_dict_set(&c->fc->metadata, key, str, 0);
515 if (*language && strcmp(language, "und")) {
516 snprintf(key2, sizeof(key2), "%s-%s", key, language);
517 av_dict_set(&c->fc->metadata, key2, str, 0);
519 if (!strcmp(key, "encoder")) {
520 int major, minor, micro;
521 if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, µ) == 3) {
522 c->handbrake_version = 1000000*major + 1000*minor + micro;
531 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
534 int i, nb_chapters, str_len, version;
538 if (c->ignore_chapters)
541 if ((atom.size -= 5) < 0)
544 version = avio_r8(pb);
547 avio_rb32(pb); // ???
548 nb_chapters = avio_r8(pb);
550 for (i = 0; i < nb_chapters; i++) {
554 start = avio_rb64(pb);
555 str_len = avio_r8(pb);
557 if ((atom.size -= 9+str_len) < 0)
560 ret = ffio_read_size(pb, str, str_len);
564 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
569 #define MIN_DATA_ENTRY_BOX_SIZE 12
570 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
573 MOVStreamContext *sc;
576 if (c->fc->nb_streams < 1)
578 st = c->fc->streams[c->fc->nb_streams-1];
581 avio_rb32(pb); // version + flags
582 entries = avio_rb32(pb);
584 entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
585 entries >= UINT_MAX / sizeof(*sc->drefs))
586 return AVERROR_INVALIDDATA;
590 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
592 return AVERROR(ENOMEM);
593 sc->drefs_count = entries;
595 for (i = 0; i < entries; i++) {
596 MOVDref *dref = &sc->drefs[i];
597 uint32_t size = avio_rb32(pb);
598 int64_t next = avio_tell(pb) + size - 4;
601 return AVERROR_INVALIDDATA;
603 dref->type = avio_rl32(pb);
604 avio_rb32(pb); // version + flags
606 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
607 /* macintosh alias record */
608 uint16_t volume_len, len;
614 volume_len = avio_r8(pb);
615 volume_len = FFMIN(volume_len, 27);
616 ret = ffio_read_size(pb, dref->volume, 27);
619 dref->volume[volume_len] = 0;
620 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
625 len = FFMIN(len, 63);
626 ret = ffio_read_size(pb, dref->filename, 63);
629 dref->filename[len] = 0;
630 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
634 /* read next level up_from_alias/down_to_target */
635 dref->nlvl_from = avio_rb16(pb);
636 dref->nlvl_to = avio_rb16(pb);
637 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
638 dref->nlvl_from, dref->nlvl_to);
642 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
645 type = avio_rb16(pb);
647 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
650 if (type == 2) { // absolute path
652 dref->path = av_mallocz(len+1);
654 return AVERROR(ENOMEM);
656 ret = ffio_read_size(pb, dref->path, len);
658 av_freep(&dref->path);
661 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
663 memmove(dref->path, dref->path+volume_len, len);
666 // trim string of any ending zeros
667 for (j = len - 1; j >= 0; j--) {
668 if (dref->path[j] == 0)
673 for (j = 0; j < len; j++)
674 if (dref->path[j] == ':' || dref->path[j] == 0)
676 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
677 } else if (type == 0) { // directory name
679 dref->dir = av_malloc(len+1);
681 return AVERROR(ENOMEM);
683 ret = ffio_read_size(pb, dref->dir, len);
685 av_freep(&dref->dir);
689 for (j = 0; j < len; j++)
690 if (dref->dir[j] == ':')
692 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
697 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n",
702 avio_seek(pb, next, SEEK_SET);
707 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
716 avio_r8(pb); /* version */
717 avio_rb24(pb); /* flags */
720 ctype = avio_rl32(pb);
721 type = avio_rl32(pb); /* component subtype */
723 av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype));
724 av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type));
726 if (c->trak_index < 0) { // meta not inside a trak
727 if (type == MKTAG('m','d','t','a')) {
728 c->found_hdlr_mdta = 1;
733 st = c->fc->streams[c->fc->nb_streams-1];
735 if (type == MKTAG('v','i','d','e'))
736 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
737 else if (type == MKTAG('s','o','u','n'))
738 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
739 else if (type == MKTAG('m','1','a',' '))
740 st->codecpar->codec_id = AV_CODEC_ID_MP2;
741 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
742 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
744 avio_rb32(pb); /* component manufacture */
745 avio_rb32(pb); /* component flags */
746 avio_rb32(pb); /* component flags mask */
748 title_size = atom.size - 24;
749 if (title_size > 0) {
750 if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
751 return AVERROR_INVALIDDATA;
752 title_str = av_malloc(title_size + 1); /* Add null terminator */
754 return AVERROR(ENOMEM);
756 ret = ffio_read_size(pb, title_str, title_size);
758 av_freep(&title_str);
761 title_str[title_size] = 0;
763 int off = (!c->isom && title_str[0] == title_size - 1);
764 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
766 av_freep(&title_str);
772 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
774 return ff_mov_read_esds(c->fc, pb);
777 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
780 enum AVAudioServiceType *ast;
781 int ac3info, acmod, lfeon, bsmod;
783 if (c->fc->nb_streams < 1)
785 st = c->fc->streams[c->fc->nb_streams-1];
787 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
790 return AVERROR(ENOMEM);
792 ac3info = avio_rb24(pb);
793 bsmod = (ac3info >> 14) & 0x7;
794 acmod = (ac3info >> 11) & 0x7;
795 lfeon = (ac3info >> 10) & 0x1;
796 st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
797 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
799 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
801 if (st->codecpar->channels > 1 && bsmod == 0x7)
802 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
804 #if FF_API_LAVF_AVCTX
805 FF_DISABLE_DEPRECATION_WARNINGS
806 st->codec->audio_service_type = *ast;
807 FF_ENABLE_DEPRECATION_WARNINGS
813 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
816 enum AVAudioServiceType *ast;
817 int eac3info, acmod, lfeon, bsmod;
819 if (c->fc->nb_streams < 1)
821 st = c->fc->streams[c->fc->nb_streams-1];
823 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
826 return AVERROR(ENOMEM);
828 /* No need to parse fields for additional independent substreams and its
829 * associated dependent substreams since libavcodec's E-AC-3 decoder
830 * does not support them yet. */
831 avio_rb16(pb); /* data_rate and num_ind_sub */
832 eac3info = avio_rb24(pb);
833 bsmod = (eac3info >> 12) & 0x1f;
834 acmod = (eac3info >> 9) & 0x7;
835 lfeon = (eac3info >> 8) & 0x1;
836 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
838 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
839 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
841 if (st->codecpar->channels > 1 && bsmod == 0x7)
842 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
844 #if FF_API_LAVF_AVCTX
845 FF_DISABLE_DEPRECATION_WARNINGS
846 st->codec->audio_service_type = *ast;
847 FF_ENABLE_DEPRECATION_WARNINGS
853 static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
855 const uint32_t ddts_size = 20;
858 uint32_t frame_duration_code = 0;
859 uint32_t channel_layout_code = 0;
862 buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE);
864 return AVERROR(ENOMEM);
866 if (avio_read(pb, buf, ddts_size) < ddts_size) {
868 return AVERROR_INVALIDDATA;
871 init_get_bits(&gb, buf, 8*ddts_size);
873 if (c->fc->nb_streams < 1) {
877 st = c->fc->streams[c->fc->nb_streams-1];
879 st->codecpar->sample_rate = get_bits_long(&gb, 32);
880 if (st->codecpar->sample_rate <= 0) {
881 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
883 return AVERROR_INVALIDDATA;
885 skip_bits_long(&gb, 32); /* max bitrate */
886 st->codecpar->bit_rate = get_bits_long(&gb, 32);
887 st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
888 frame_duration_code = get_bits(&gb, 2);
889 skip_bits(&gb, 30); /* various fields */
890 channel_layout_code = get_bits(&gb, 16);
892 st->codecpar->frame_size =
893 (frame_duration_code == 0) ? 512 :
894 (frame_duration_code == 1) ? 1024 :
895 (frame_duration_code == 2) ? 2048 :
896 (frame_duration_code == 3) ? 4096 : 0;
898 if (channel_layout_code > 0xff) {
899 av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
901 st->codecpar->channel_layout =
902 ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
903 ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
904 ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
905 ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
906 ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
907 ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
909 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
915 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
919 if (c->fc->nb_streams < 1)
921 st = c->fc->streams[c->fc->nb_streams-1];
926 /* skip version and flags */
929 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
934 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
939 if (c->fc->nb_streams < 1)
941 st = c->fc->streams[c->fc->nb_streams-1];
943 if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
944 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
949 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
951 const int num = avio_rb32(pb);
952 const int den = avio_rb32(pb);
955 if (c->fc->nb_streams < 1)
957 st = c->fc->streams[c->fc->nb_streams-1];
959 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
960 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
961 av_log(c->fc, AV_LOG_WARNING,
962 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
963 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
965 } else if (den != 0) {
966 av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
972 /* this atom contains actual media data */
973 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
975 if (atom.size == 0) /* wrong one (MP4) */
978 return 0; /* now go for moov */
981 #define DRM_BLOB_SIZE 56
983 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
985 uint8_t intermediate_key[20];
986 uint8_t intermediate_iv[20];
989 uint8_t file_checksum[20];
990 uint8_t calculated_checksum[20];
994 uint8_t *activation_bytes = c->activation_bytes;
995 uint8_t *fixed_key = c->audible_fixed_key;
999 sha = av_sha_alloc();
1001 return AVERROR(ENOMEM);
1002 c->aes_decrypt = av_aes_alloc();
1003 if (!c->aes_decrypt) {
1004 ret = AVERROR(ENOMEM);
1008 /* drm blob processing */
1009 avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
1010 avio_read(pb, input, DRM_BLOB_SIZE);
1011 avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
1012 avio_read(pb, file_checksum, 20);
1014 av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
1015 for (i = 0; i < 20; i++)
1016 av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
1017 av_log(c->fc, AV_LOG_INFO, "\n");
1019 /* verify activation data */
1020 if (!activation_bytes) {
1021 av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
1022 ret = 0; /* allow ffprobe to continue working on .aax files */
1025 if (c->activation_bytes_size != 4) {
1026 av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
1027 ret = AVERROR(EINVAL);
1031 /* verify fixed key */
1032 if (c->audible_fixed_key_size != 16) {
1033 av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
1034 ret = AVERROR(EINVAL);
1038 /* AAX (and AAX+) key derivation */
1039 av_sha_init(sha, 160);
1040 av_sha_update(sha, fixed_key, 16);
1041 av_sha_update(sha, activation_bytes, 4);
1042 av_sha_final(sha, intermediate_key);
1043 av_sha_init(sha, 160);
1044 av_sha_update(sha, fixed_key, 16);
1045 av_sha_update(sha, intermediate_key, 20);
1046 av_sha_update(sha, activation_bytes, 4);
1047 av_sha_final(sha, intermediate_iv);
1048 av_sha_init(sha, 160);
1049 av_sha_update(sha, intermediate_key, 16);
1050 av_sha_update(sha, intermediate_iv, 16);
1051 av_sha_final(sha, calculated_checksum);
1052 if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
1053 av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
1054 ret = AVERROR_INVALIDDATA;
1057 av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
1058 av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
1059 for (i = 0; i < 4; i++) {
1060 // file data (in output) is stored in big-endian mode
1061 if (activation_bytes[i] != output[3 - i]) { // critical error
1062 av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
1063 ret = AVERROR_INVALIDDATA;
1067 memcpy(c->file_key, output + 8, 16);
1068 memcpy(input, output + 26, 16);
1069 av_sha_init(sha, 160);
1070 av_sha_update(sha, input, 16);
1071 av_sha_update(sha, c->file_key, 16);
1072 av_sha_update(sha, fixed_key, 16);
1073 av_sha_final(sha, c->file_iv);
1081 // Audible AAX (and AAX+) bytestream decryption
1082 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1085 unsigned char iv[16];
1087 memcpy(iv, c->file_iv, 16); // iv is overwritten
1088 blocks = size >> 4; // trailing bytes are not encrypted!
1089 av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1090 av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1095 /* read major brand, minor version and compatible brands and store them as metadata */
1096 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1099 int comp_brand_size;
1100 char* comp_brands_str;
1101 uint8_t type[5] = {0};
1102 int ret = ffio_read_size(pb, type, 4);
1106 if (strcmp(type, "qt "))
1108 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1109 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1110 minor_ver = avio_rb32(pb); /* minor version */
1111 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1113 comp_brand_size = atom.size - 8;
1114 if (comp_brand_size < 0)
1115 return AVERROR_INVALIDDATA;
1116 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1117 if (!comp_brands_str)
1118 return AVERROR(ENOMEM);
1120 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1122 av_freep(&comp_brands_str);
1125 comp_brands_str[comp_brand_size] = 0;
1126 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1127 av_freep(&comp_brands_str);
1132 /* this atom should contain all header atoms */
1133 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1137 if (c->found_moov) {
1138 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1139 avio_skip(pb, atom.size);
1143 if ((ret = mov_read_default(c, pb, atom)) < 0)
1145 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1146 /* so we don't parse the whole file if over a network */
1148 return 0; /* now go for mdat */
1151 static MOVFragmentStreamInfo * get_frag_stream_info(
1152 MOVFragmentIndex *frag_index,
1157 MOVFragmentIndexItem * item;
1159 if (index < 0 || index >= frag_index->nb_items)
1161 item = &frag_index->item[index];
1162 for (i = 0; i < item->nb_stream_info; i++)
1163 if (item->stream_info[i].id == id)
1164 return &item->stream_info[i];
1166 // This shouldn't happen
1170 static void set_frag_stream(MOVFragmentIndex *frag_index, int id)
1173 MOVFragmentIndexItem * item;
1175 if (frag_index->current < 0 ||
1176 frag_index->current >= frag_index->nb_items)
1179 item = &frag_index->item[frag_index->current];
1180 for (i = 0; i < item->nb_stream_info; i++)
1181 if (item->stream_info[i].id == id) {
1186 // id not found. This shouldn't happen.
1190 static MOVFragmentStreamInfo * get_current_frag_stream_info(
1191 MOVFragmentIndex *frag_index)
1193 MOVFragmentIndexItem *item;
1194 if (frag_index->current < 0 ||
1195 frag_index->current >= frag_index->nb_items)
1198 item = &frag_index->item[frag_index->current];
1199 if (item->current >= 0 && item->current < item->nb_stream_info)
1200 return &item->stream_info[item->current];
1202 // This shouldn't happen
1206 static int search_frag_moof_offset(MOVFragmentIndex *frag_index, int64_t offset)
1209 int64_t moof_offset;
1211 // Optimize for appending new entries
1212 if (!frag_index->nb_items ||
1213 frag_index->item[frag_index->nb_items - 1].moof_offset < offset)
1214 return frag_index->nb_items;
1217 b = frag_index->nb_items;
1221 moof_offset = frag_index->item[m].moof_offset;
1222 if (moof_offset >= offset)
1224 if (moof_offset <= offset)
1230 static int64_t get_stream_info_time(MOVFragmentStreamInfo * frag_stream_info)
1233 if (frag_stream_info) {
1234 if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE)
1235 return frag_stream_info->sidx_pts;
1236 if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE)
1237 return frag_stream_info->first_tfra_pts;
1238 if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE)
1239 return frag_stream_info->tfdt_dts;
1241 return AV_NOPTS_VALUE;
1244 static int64_t get_frag_time(MOVFragmentIndex *frag_index,
1245 int index, int track_id)
1247 MOVFragmentStreamInfo * frag_stream_info;
1251 if (track_id >= 0) {
1252 frag_stream_info = get_frag_stream_info(frag_index, index, track_id);
1253 return frag_stream_info->sidx_pts;
1256 for (i = 0; i < frag_index->item[index].nb_stream_info; i++) {
1257 frag_stream_info = &frag_index->item[index].stream_info[i];
1258 timestamp = get_stream_info_time(frag_stream_info);
1259 if (timestamp != AV_NOPTS_VALUE)
1262 return AV_NOPTS_VALUE;
1265 static int search_frag_timestamp(MOVFragmentIndex *frag_index,
1266 AVStream *st, int64_t timestamp)
1273 // If the stream is referenced by any sidx, limit the search
1274 // to fragments that referenced this stream in the sidx
1275 MOVStreamContext *sc = st->priv_data;
1281 b = frag_index->nb_items;
1285 frag_time = get_frag_time(frag_index, m, id);
1286 if (frag_time != AV_NOPTS_VALUE) {
1287 if (frag_time >= timestamp)
1289 if (frag_time <= timestamp)
1296 static int update_frag_index(MOVContext *c, int64_t offset)
1299 MOVFragmentIndexItem * item;
1300 MOVFragmentStreamInfo * frag_stream_info;
1302 // If moof_offset already exists in frag_index, return index to it
1303 index = search_frag_moof_offset(&c->frag_index, offset);
1304 if (index < c->frag_index.nb_items &&
1305 c->frag_index.item[index].moof_offset == offset)
1308 // offset is not yet in frag index.
1309 // Insert new item at index (sorted by moof offset)
1310 item = av_fast_realloc(c->frag_index.item,
1311 &c->frag_index.allocated_size,
1312 (c->frag_index.nb_items + 1) *
1313 sizeof(*c->frag_index.item));
1316 c->frag_index.item = item;
1318 frag_stream_info = av_realloc_array(NULL, c->fc->nb_streams,
1319 sizeof(*item->stream_info));
1320 if (!frag_stream_info)
1323 for (i = 0; i < c->fc->nb_streams; i++) {
1324 frag_stream_info[i].id = c->fc->streams[i]->id;
1325 frag_stream_info[i].sidx_pts = AV_NOPTS_VALUE;
1326 frag_stream_info[i].tfdt_dts = AV_NOPTS_VALUE;
1327 frag_stream_info[i].first_tfra_pts = AV_NOPTS_VALUE;
1328 frag_stream_info[i].index_entry = -1;
1331 if (index < c->frag_index.nb_items)
1332 memmove(c->frag_index.item + index + 1, c->frag_index.item + index,
1333 (c->frag_index.nb_items - index) * sizeof(*c->frag_index.item));
1335 item = &c->frag_index.item[index];
1336 item->headers_read = 0;
1338 item->nb_stream_info = c->fc->nb_streams;
1339 item->moof_offset = offset;
1340 item->stream_info = frag_stream_info;
1341 c->frag_index.nb_items++;
1346 static void fix_frag_index_entries(MOVFragmentIndex *frag_index, int index,
1347 int id, int entries)
1350 MOVFragmentStreamInfo * frag_stream_info;
1354 for (i = index; i < frag_index->nb_items; i++) {
1355 frag_stream_info = get_frag_stream_info(frag_index, i, id);
1356 if (frag_stream_info && frag_stream_info->index_entry >= 0)
1357 frag_stream_info->index_entry += entries;
1361 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1363 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1364 c->has_looked_for_mfra = 1;
1365 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
1367 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1369 if ((ret = mov_read_mfra(c, pb)) < 0) {
1370 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1371 "read the mfra (may be a live ismv)\n");
1374 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1375 "seekable, can not look for mfra\n");
1378 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
1379 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1380 c->frag_index.current = update_frag_index(c, c->fragment.moof_offset);
1381 return mov_read_default(c, pb, atom);
1384 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1387 if(time >= 2082844800)
1388 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1390 if ((int64_t)(time * 1000000ULL) / 1000000 != time) {
1391 av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n");
1395 avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
1399 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1402 MOVStreamContext *sc;
1404 char language[4] = {0};
1406 int64_t creation_time;
1408 if (c->fc->nb_streams < 1)
1410 st = c->fc->streams[c->fc->nb_streams-1];
1413 if (sc->time_scale) {
1414 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1415 return AVERROR_INVALIDDATA;
1418 version = avio_r8(pb);
1420 avpriv_request_sample(c->fc, "Version %d", version);
1421 return AVERROR_PATCHWELCOME;
1423 avio_rb24(pb); /* flags */
1425 creation_time = avio_rb64(pb);
1428 creation_time = avio_rb32(pb);
1429 avio_rb32(pb); /* modification time */
1431 mov_metadata_creation_time(&st->metadata, creation_time);
1433 sc->time_scale = avio_rb32(pb);
1434 if (sc->time_scale <= 0) {
1435 av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale);
1438 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1440 lang = avio_rb16(pb); /* language */
1441 if (ff_mov_lang_to_iso639(lang, language))
1442 av_dict_set(&st->metadata, "language", language, 0);
1443 avio_rb16(pb); /* quality */
1448 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1451 int64_t creation_time;
1452 int version = avio_r8(pb); /* version */
1453 avio_rb24(pb); /* flags */
1456 creation_time = avio_rb64(pb);
1459 creation_time = avio_rb32(pb);
1460 avio_rb32(pb); /* modification time */
1462 mov_metadata_creation_time(&c->fc->metadata, creation_time);
1463 c->time_scale = avio_rb32(pb); /* time scale */
1464 if (c->time_scale <= 0) {
1465 av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale);
1468 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1470 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1471 // set the AVCodecContext duration because the duration of individual tracks
1472 // may be inaccurate
1473 if (c->time_scale > 0 && !c->trex_data)
1474 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1475 avio_rb32(pb); /* preferred scale */
1477 avio_rb16(pb); /* preferred volume */
1479 avio_skip(pb, 10); /* reserved */
1481 /* movie display matrix, store it in main context and use it later on */
1482 for (i = 0; i < 3; i++) {
1483 c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
1484 c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
1485 c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
1488 avio_rb32(pb); /* preview time */
1489 avio_rb32(pb); /* preview duration */
1490 avio_rb32(pb); /* poster time */
1491 avio_rb32(pb); /* selection time */
1492 avio_rb32(pb); /* selection duration */
1493 avio_rb32(pb); /* current time */
1494 avio_rb32(pb); /* next track ID */
1499 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1504 if (c->fc->nb_streams < 1)
1506 st = c->fc->streams[c->fc->nb_streams-1];
1508 little_endian = avio_rb16(pb) & 0xFF;
1509 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1510 if (little_endian == 1) {
1511 switch (st->codecpar->codec_id) {
1512 case AV_CODEC_ID_PCM_S24BE:
1513 st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
1515 case AV_CODEC_ID_PCM_S32BE:
1516 st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
1518 case AV_CODEC_ID_PCM_F32BE:
1519 st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
1521 case AV_CODEC_ID_PCM_F64BE:
1522 st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
1531 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1534 char color_parameter_type[5] = { 0 };
1535 uint16_t color_primaries, color_trc, color_matrix;
1538 if (c->fc->nb_streams < 1)
1540 st = c->fc->streams[c->fc->nb_streams - 1];
1542 ret = ffio_read_size(pb, color_parameter_type, 4);
1545 if (strncmp(color_parameter_type, "nclx", 4) &&
1546 strncmp(color_parameter_type, "nclc", 4)) {
1547 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1548 color_parameter_type);
1552 color_primaries = avio_rb16(pb);
1553 color_trc = avio_rb16(pb);
1554 color_matrix = avio_rb16(pb);
1556 av_log(c->fc, AV_LOG_TRACE,
1557 "%s: pri %d trc %d matrix %d",
1558 color_parameter_type, color_primaries, color_trc, color_matrix);
1560 if (!strncmp(color_parameter_type, "nclx", 4)) {
1561 uint8_t color_range = avio_r8(pb) >> 7;
1562 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1564 st->codecpar->color_range = AVCOL_RANGE_JPEG;
1566 st->codecpar->color_range = AVCOL_RANGE_MPEG;
1569 if (!av_color_primaries_name(color_primaries))
1570 color_primaries = AVCOL_PRI_UNSPECIFIED;
1571 if (!av_color_transfer_name(color_trc))
1572 color_trc = AVCOL_TRC_UNSPECIFIED;
1573 if (!av_color_space_name(color_matrix))
1574 color_matrix = AVCOL_SPC_UNSPECIFIED;
1576 st->codecpar->color_primaries = color_primaries;
1577 st->codecpar->color_trc = color_trc;
1578 st->codecpar->color_space = color_matrix;
1579 av_log(c->fc, AV_LOG_TRACE, "\n");
1584 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1587 unsigned mov_field_order;
1588 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1590 if (c->fc->nb_streams < 1) // will happen with jp2 files
1592 st = c->fc->streams[c->fc->nb_streams-1];
1594 return AVERROR_INVALIDDATA;
1595 mov_field_order = avio_rb16(pb);
1596 if ((mov_field_order & 0xFF00) == 0x0100)
1597 decoded_field_order = AV_FIELD_PROGRESSIVE;
1598 else if ((mov_field_order & 0xFF00) == 0x0200) {
1599 switch (mov_field_order & 0xFF) {
1600 case 0x01: decoded_field_order = AV_FIELD_TT;
1602 case 0x06: decoded_field_order = AV_FIELD_BB;
1604 case 0x09: decoded_field_order = AV_FIELD_TB;
1606 case 0x0E: decoded_field_order = AV_FIELD_BT;
1610 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1611 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1613 st->codecpar->field_order = decoded_field_order;
1618 static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
1621 uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1622 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1623 return AVERROR_INVALIDDATA;
1624 if ((err = av_reallocp(&par->extradata, size)) < 0) {
1625 par->extradata_size = 0;
1628 par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1632 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1633 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1634 AVCodecParameters *par, uint8_t *buf)
1636 int64_t result = atom.size;
1639 AV_WB32(buf , atom.size + 8);
1640 AV_WL32(buf + 4, atom.type);
1641 err = ffio_read_size(pb, buf + 8, atom.size);
1643 par->extradata_size -= atom.size;
1645 } else if (err < atom.size) {
1646 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1647 par->extradata_size -= atom.size - err;
1650 memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1654 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1655 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1656 enum AVCodecID codec_id)
1659 uint64_t original_size;
1662 if (c->fc->nb_streams < 1) // will happen with jp2 files
1664 st = c->fc->streams[c->fc->nb_streams-1];
1666 if (st->codecpar->codec_id != codec_id)
1667 return 0; /* unexpected codec_id - don't mess with extradata */
1669 original_size = st->codecpar->extradata_size;
1670 err = mov_realloc_extradata(st->codecpar, atom);
1674 err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
1677 return 0; // Note: this is the original behavior to ignore truncation.
1680 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1681 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1683 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1686 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1688 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1691 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1693 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1696 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1698 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1701 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1703 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1705 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1709 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1711 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1713 if (!ret && c->fc->nb_streams >= 1) {
1714 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1715 if (par->extradata_size >= 40) {
1716 par->height = AV_RB16(&par->extradata[36]);
1717 par->width = AV_RB16(&par->extradata[38]);
1723 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1725 if (c->fc->nb_streams >= 1) {
1726 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1727 if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1728 par->codec_id == AV_CODEC_ID_H264 &&
1732 cid = avio_rb16(pb);
1733 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1734 if (cid == 0xd4d || cid == 0xd4e)
1737 } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
1738 par->codec_tag == MKTAG('A', 'V', 'j', '2') ||
1739 par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
1743 num = avio_rb32(pb);
1744 den = avio_rb32(pb);
1745 if (num <= 0 || den <= 0)
1747 switch (avio_rb32(pb)) {
1749 if (den >= INT_MAX / 2)
1753 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1754 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1761 return mov_read_avid(c, pb, atom);
1764 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1768 uint64_t original_size;
1769 if (c->fc->nb_streams >= 1) {
1770 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1771 if (par->codec_id == AV_CODEC_ID_H264)
1773 if (atom.size == 16) {
1774 original_size = par->extradata_size;
1775 ret = mov_realloc_extradata(par, atom);
1777 length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
1778 if (length == atom.size) {
1779 const uint8_t range_value = par->extradata[original_size + 19];
1780 switch (range_value) {
1782 par->color_range = AVCOL_RANGE_MPEG;
1785 par->color_range = AVCOL_RANGE_JPEG;
1788 av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1791 ff_dlog(c, "color_range: %d\n", par->color_range);
1793 /* For some reason the whole atom was not added to the extradata */
1794 av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1797 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1800 av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1807 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1809 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1812 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1817 if (c->fc->nb_streams < 1)
1819 st = c->fc->streams[c->fc->nb_streams-1];
1821 if ((uint64_t)atom.size > (1<<30))
1822 return AVERROR_INVALIDDATA;
1824 if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
1825 st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
1826 st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
1827 // pass all frma atom to codec, needed at least for QDMC and QDM2
1828 av_freep(&st->codecpar->extradata);
1829 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1832 } else if (atom.size > 8) { /* to read frma, esds atoms */
1833 if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1835 ret = ffio_ensure_seekback(pb, 8);
1838 buffer = avio_rb64(pb);
1840 if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1841 && buffer >> 32 <= atom.size
1842 && buffer >> 32 >= 8) {
1845 } else if (!st->codecpar->extradata_size) {
1846 #define ALAC_EXTRADATA_SIZE 36
1847 st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1848 if (!st->codecpar->extradata)
1849 return AVERROR(ENOMEM);
1850 st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
1851 AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE);
1852 AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
1853 AV_WB64(st->codecpar->extradata + 12, buffer);
1854 avio_read(pb, st->codecpar->extradata + 20, 16);
1855 avio_skip(pb, atom.size - 24);
1859 if ((ret = mov_read_default(c, pb, atom)) < 0)
1862 avio_skip(pb, atom.size);
1867 * This function reads atom content and puts data in extradata without tag
1868 * nor size unlike mov_read_extradata.
1870 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1875 if (c->fc->nb_streams < 1)
1877 st = c->fc->streams[c->fc->nb_streams-1];
1879 if ((uint64_t)atom.size > (1<<30))
1880 return AVERROR_INVALIDDATA;
1882 if (atom.size >= 10) {
1883 // Broken files created by legacy versions of libavformat will
1884 // wrap a whole fiel atom inside of a glbl atom.
1885 unsigned size = avio_rb32(pb);
1886 unsigned type = avio_rl32(pb);
1887 avio_seek(pb, -8, SEEK_CUR);
1888 if (type == MKTAG('f','i','e','l') && size == atom.size)
1889 return mov_read_default(c, pb, atom);
1891 if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
1892 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1895 av_freep(&st->codecpar->extradata);
1896 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1903 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1906 uint8_t profile_level;
1909 if (c->fc->nb_streams < 1)
1911 st = c->fc->streams[c->fc->nb_streams-1];
1913 if (atom.size >= (1<<28) || atom.size < 7)
1914 return AVERROR_INVALIDDATA;
1916 profile_level = avio_r8(pb);
1917 if ((profile_level & 0xf0) != 0xc0)
1920 avio_seek(pb, 6, SEEK_CUR);
1921 av_freep(&st->codecpar->extradata);
1922 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
1930 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1931 * but can have extradata appended at the end after the 40 bytes belonging
1934 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1939 if (c->fc->nb_streams < 1)
1941 if (atom.size <= 40)
1943 st = c->fc->streams[c->fc->nb_streams-1];
1945 if ((uint64_t)atom.size > (1<<30))
1946 return AVERROR_INVALIDDATA;
1949 av_freep(&st->codecpar->extradata);
1950 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
1957 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1960 MOVStreamContext *sc;
1961 unsigned int i, entries;
1963 if (c->fc->nb_streams < 1)
1965 st = c->fc->streams[c->fc->nb_streams-1];
1968 avio_r8(pb); /* version */
1969 avio_rb24(pb); /* flags */
1971 entries = avio_rb32(pb);
1976 if (sc->chunk_offsets)
1977 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1978 av_free(sc->chunk_offsets);
1979 sc->chunk_count = 0;
1980 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1981 if (!sc->chunk_offsets)
1982 return AVERROR(ENOMEM);
1983 sc->chunk_count = entries;
1985 if (atom.type == MKTAG('s','t','c','o'))
1986 for (i = 0; i < entries && !pb->eof_reached; i++)
1987 sc->chunk_offsets[i] = avio_rb32(pb);
1988 else if (atom.type == MKTAG('c','o','6','4'))
1989 for (i = 0; i < entries && !pb->eof_reached; i++)
1990 sc->chunk_offsets[i] = avio_rb64(pb);
1992 return AVERROR_INVALIDDATA;
1994 sc->chunk_count = i;
1996 if (pb->eof_reached) {
1997 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STCO atom\n");
2004 static int mov_codec_id(AVStream *st, uint32_t format)
2006 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
2009 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
2010 (format & 0xFFFF) == 'T' + ('S' << 8)))
2011 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
2013 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
2014 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2015 } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
2016 /* skip old ASF MPEG-4 tag */
2017 format && format != MKTAG('m','p','4','s')) {
2018 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2020 id = ff_codec_get_id(ff_codec_bmp_tags, format);
2022 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2023 else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
2024 (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
2025 st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
2026 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
2028 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2032 st->codecpar->codec_tag = format;
2037 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
2038 AVStream *st, MOVStreamContext *sc)
2040 uint8_t codec_name[32] = { 0 };
2044 /* The first 16 bytes of the video sample description are already
2045 * read in ff_mov_read_stsd_entries() */
2046 stsd_start = avio_tell(pb) - 16;
2048 avio_rb16(pb); /* version */
2049 avio_rb16(pb); /* revision level */
2050 avio_rb32(pb); /* vendor */
2051 avio_rb32(pb); /* temporal quality */
2052 avio_rb32(pb); /* spatial quality */
2054 st->codecpar->width = avio_rb16(pb); /* width */
2055 st->codecpar->height = avio_rb16(pb); /* height */
2057 avio_rb32(pb); /* horiz resolution */
2058 avio_rb32(pb); /* vert resolution */
2059 avio_rb32(pb); /* data size, always 0 */
2060 avio_rb16(pb); /* frames per samples */
2062 len = avio_r8(pb); /* codec name, pascal string */
2065 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
2067 avio_skip(pb, 31 - len);
2070 av_dict_set(&st->metadata, "encoder", codec_name, 0);
2072 /* codec_tag YV12 triggers an UV swap in rawdec.c */
2073 if (!strncmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
2074 st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
2075 st->codecpar->width &= ~1;
2076 st->codecpar->height &= ~1;
2078 /* Flash Media Server uses tag H.263 with Sorenson Spark */
2079 if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
2080 !strncmp(codec_name, "Sorenson H263", 13))
2081 st->codecpar->codec_id = AV_CODEC_ID_FLV1;
2083 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
2085 avio_seek(pb, stsd_start, SEEK_SET);
2087 if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
2088 st->codecpar->bits_per_coded_sample &= 0x1F;
2089 sc->has_palette = 1;
2093 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
2094 AVStream *st, MOVStreamContext *sc)
2096 int bits_per_sample, flags;
2097 uint16_t version = avio_rb16(pb);
2098 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
2100 avio_rb16(pb); /* revision level */
2101 avio_rb32(pb); /* vendor */
2103 st->codecpar->channels = avio_rb16(pb); /* channel count */
2104 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
2105 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
2107 sc->audio_cid = avio_rb16(pb);
2108 avio_rb16(pb); /* packet size = 0 */
2110 st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
2112 // Read QT version 1 fields. In version 0 these do not exist.
2113 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
2115 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
2118 sc->samples_per_frame = avio_rb32(pb);
2119 avio_rb32(pb); /* bytes per packet */
2120 sc->bytes_per_frame = avio_rb32(pb);
2121 avio_rb32(pb); /* bytes per sample */
2122 } else if (version == 2) {
2123 avio_rb32(pb); /* sizeof struct only */
2124 st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
2125 st->codecpar->channels = avio_rb32(pb);
2126 avio_rb32(pb); /* always 0x7F000000 */
2127 st->codecpar->bits_per_coded_sample = avio_rb32(pb);
2129 flags = avio_rb32(pb); /* lpcm format specific flag */
2130 sc->bytes_per_frame = avio_rb32(pb);
2131 sc->samples_per_frame = avio_rb32(pb);
2132 if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
2133 st->codecpar->codec_id =
2134 ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
2137 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
2138 /* can't correctly handle variable sized packet as audio unit */
2139 switch (st->codecpar->codec_id) {
2140 case AV_CODEC_ID_MP2:
2141 case AV_CODEC_ID_MP3:
2142 st->need_parsing = AVSTREAM_PARSE_FULL;
2148 if (sc->format == 0) {
2149 if (st->codecpar->bits_per_coded_sample == 8)
2150 st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
2151 else if (st->codecpar->bits_per_coded_sample == 16)
2152 st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
2155 switch (st->codecpar->codec_id) {
2156 case AV_CODEC_ID_PCM_S8:
2157 case AV_CODEC_ID_PCM_U8:
2158 if (st->codecpar->bits_per_coded_sample == 16)
2159 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
2161 case AV_CODEC_ID_PCM_S16LE:
2162 case AV_CODEC_ID_PCM_S16BE:
2163 if (st->codecpar->bits_per_coded_sample == 8)
2164 st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
2165 else if (st->codecpar->bits_per_coded_sample == 24)
2166 st->codecpar->codec_id =
2167 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
2168 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2169 else if (st->codecpar->bits_per_coded_sample == 32)
2170 st->codecpar->codec_id =
2171 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
2172 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2174 /* set values for old format before stsd version 1 appeared */
2175 case AV_CODEC_ID_MACE3:
2176 sc->samples_per_frame = 6;
2177 sc->bytes_per_frame = 2 * st->codecpar->channels;
2179 case AV_CODEC_ID_MACE6:
2180 sc->samples_per_frame = 6;
2181 sc->bytes_per_frame = 1 * st->codecpar->channels;
2183 case AV_CODEC_ID_ADPCM_IMA_QT:
2184 sc->samples_per_frame = 64;
2185 sc->bytes_per_frame = 34 * st->codecpar->channels;
2187 case AV_CODEC_ID_GSM:
2188 sc->samples_per_frame = 160;
2189 sc->bytes_per_frame = 33;
2195 bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
2196 if (bits_per_sample) {
2197 st->codecpar->bits_per_coded_sample = bits_per_sample;
2198 sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
2202 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
2203 AVStream *st, MOVStreamContext *sc,
2206 // ttxt stsd contains display flags, justification, background
2207 // color, fonts, and default styles, so fake an atom to read it
2208 MOVAtom fake_atom = { .size = size };
2209 // mp4s contains a regular esds atom
2210 if (st->codecpar->codec_tag != AV_RL32("mp4s"))
2211 mov_read_glbl(c, pb, fake_atom);
2212 st->codecpar->width = sc->width;
2213 st->codecpar->height = sc->height;
2216 static uint32_t yuv_to_rgba(uint32_t ycbcr)
2221 y = (ycbcr >> 16) & 0xFF;
2222 cr = (ycbcr >> 8) & 0xFF;
2225 b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
2226 g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
2227 r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
2229 return (r << 16) | (g << 8) | b;
2232 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
2234 char buf[256] = {0};
2235 uint8_t *src = st->codecpar->extradata;
2238 if (st->codecpar->extradata_size != 64)
2241 if (st->codecpar->width > 0 && st->codecpar->height > 0)
2242 snprintf(buf, sizeof(buf), "size: %dx%d\n",
2243 st->codecpar->width, st->codecpar->height);
2244 av_strlcat(buf, "palette: ", sizeof(buf));
2246 for (i = 0; i < 16; i++) {
2247 uint32_t yuv = AV_RB32(src + i * 4);
2248 uint32_t rgba = yuv_to_rgba(yuv);
2250 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2253 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2256 av_freep(&st->codecpar->extradata);
2257 st->codecpar->extradata_size = 0;
2258 st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
2259 if (!st->codecpar->extradata)
2260 return AVERROR(ENOMEM);
2261 st->codecpar->extradata_size = strlen(buf);
2262 memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
2267 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2268 AVStream *st, MOVStreamContext *sc,
2273 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
2274 if ((int)size != size)
2275 return AVERROR(ENOMEM);
2277 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
2281 MOVStreamContext *tmcd_ctx = st->priv_data;
2283 val = AV_RB32(st->codecpar->extradata + 4);
2284 tmcd_ctx->tmcd_flags = val;
2285 st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
2286 st->avg_frame_rate.den = 1;
2287 #if FF_API_LAVF_AVCTX
2288 FF_DISABLE_DEPRECATION_WARNINGS
2289 st->codec->time_base = av_inv_q(st->avg_frame_rate);
2290 FF_ENABLE_DEPRECATION_WARNINGS
2292 /* adjust for per frame dur in counter mode */
2293 if (tmcd_ctx->tmcd_flags & 0x0008) {
2294 int timescale = AV_RB32(st->codecpar->extradata + 8);
2295 int framedur = AV_RB32(st->codecpar->extradata + 12);
2296 st->avg_frame_rate.num *= timescale;
2297 st->avg_frame_rate.den *= framedur;
2298 #if FF_API_LAVF_AVCTX
2299 FF_DISABLE_DEPRECATION_WARNINGS
2300 st->codec->time_base.den *= timescale;
2301 st->codec->time_base.num *= framedur;
2302 FF_ENABLE_DEPRECATION_WARNINGS
2306 uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
2307 uint32_t format = AV_RB32(st->codecpar->extradata + 22);
2308 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2309 uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
2310 if (str_size > 0 && size >= (int)str_size + 26) {
2311 char *reel_name = av_malloc(str_size + 1);
2313 return AVERROR(ENOMEM);
2314 memcpy(reel_name, st->codecpar->extradata + 30, str_size);
2315 reel_name[str_size] = 0; /* Add null terminator */
2316 /* don't add reel_name if emtpy string */
2317 if (*reel_name == 0) {
2320 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2327 /* other codec type, just skip (rtp, mp4s ...) */
2328 avio_skip(pb, size);
2333 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2334 AVStream *st, MOVStreamContext *sc)
2336 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2337 !st->codecpar->sample_rate && sc->time_scale > 1)
2338 st->codecpar->sample_rate = sc->time_scale;
2340 /* special codec parameters handling */
2341 switch (st->codecpar->codec_id) {
2342 #if CONFIG_DV_DEMUXER
2343 case AV_CODEC_ID_DVAUDIO:
2344 c->dv_fctx = avformat_alloc_context();
2346 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2347 return AVERROR(ENOMEM);
2349 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2351 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2352 return AVERROR(ENOMEM);
2354 sc->dv_audio_container = 1;
2355 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
2358 /* no ifdef since parameters are always those */
2359 case AV_CODEC_ID_QCELP:
2360 st->codecpar->channels = 1;
2361 // force sample rate for qcelp when not stored in mov
2362 if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
2363 st->codecpar->sample_rate = 8000;
2364 // FIXME: Why is the following needed for some files?
2365 sc->samples_per_frame = 160;
2366 if (!sc->bytes_per_frame)
2367 sc->bytes_per_frame = 35;
2369 case AV_CODEC_ID_AMR_NB:
2370 st->codecpar->channels = 1;
2371 /* force sample rate for amr, stsd in 3gp does not store sample rate */
2372 st->codecpar->sample_rate = 8000;
2374 case AV_CODEC_ID_AMR_WB:
2375 st->codecpar->channels = 1;
2376 st->codecpar->sample_rate = 16000;
2378 case AV_CODEC_ID_MP2:
2379 case AV_CODEC_ID_MP3:
2380 /* force type after stsd for m1a hdlr */
2381 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2383 case AV_CODEC_ID_GSM:
2384 case AV_CODEC_ID_ADPCM_MS:
2385 case AV_CODEC_ID_ADPCM_IMA_WAV:
2386 case AV_CODEC_ID_ILBC:
2387 case AV_CODEC_ID_MACE3:
2388 case AV_CODEC_ID_MACE6:
2389 case AV_CODEC_ID_QDM2:
2390 st->codecpar->block_align = sc->bytes_per_frame;
2392 case AV_CODEC_ID_ALAC:
2393 if (st->codecpar->extradata_size == 36) {
2394 st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
2395 st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
2398 case AV_CODEC_ID_AC3:
2399 case AV_CODEC_ID_EAC3:
2400 case AV_CODEC_ID_MPEG1VIDEO:
2401 case AV_CODEC_ID_VC1:
2402 case AV_CODEC_ID_VP8:
2403 case AV_CODEC_ID_VP9:
2404 st->need_parsing = AVSTREAM_PARSE_FULL;
2412 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2413 int codec_tag, int format,
2416 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2419 (codec_tag != format &&
2420 // AVID 1:1 samples with differing data format and codec tag exist
2421 (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
2422 // prores is allowed to have differing data format and codec tag
2423 codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
2425 codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
2426 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2427 : codec_tag != MKTAG('j','p','e','g')))) {
2428 /* Multiple fourcc, we skip JPEG. This is not correct, we should
2429 * export it as a separate AVStream but this needs a few changes
2430 * in the MOV demuxer, patch welcome. */
2432 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2433 avio_skip(pb, size);
2440 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2443 MOVStreamContext *sc;
2444 int pseudo_stream_id;
2446 av_assert0 (c->fc->nb_streams >= 1);
2447 st = c->fc->streams[c->fc->nb_streams-1];
2450 for (pseudo_stream_id = 0;
2451 pseudo_stream_id < entries && !pb->eof_reached;
2452 pseudo_stream_id++) {
2453 //Parsing Sample description table
2455 int ret, dref_id = 1;
2456 MOVAtom a = { AV_RL32("stsd") };
2457 int64_t start_pos = avio_tell(pb);
2458 int64_t size = avio_rb32(pb); /* size */
2459 uint32_t format = avio_rl32(pb); /* data format */
2462 avio_rb32(pb); /* reserved */
2463 avio_rb16(pb); /* reserved */
2464 dref_id = avio_rb16(pb);
2465 } else if (size <= 7) {
2466 av_log(c->fc, AV_LOG_ERROR,
2467 "invalid size %"PRId64" in stsd\n", size);
2468 return AVERROR_INVALIDDATA;
2471 if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
2472 size - (avio_tell(pb) - start_pos))) {
2477 sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
2478 sc->dref_id= dref_id;
2479 sc->format = format;
2481 id = mov_codec_id(st, format);
2483 av_log(c->fc, AV_LOG_TRACE,
2484 "size=%"PRId64" 4CC=%s codec_type=%d\n", size,
2485 av_fourcc2str(format), st->codecpar->codec_type);
2487 if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
2488 st->codecpar->codec_id = id;
2489 mov_parse_stsd_video(c, pb, st, sc);
2490 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
2491 st->codecpar->codec_id = id;
2492 mov_parse_stsd_audio(c, pb, st, sc);
2493 if (st->codecpar->sample_rate < 0) {
2494 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
2495 return AVERROR_INVALIDDATA;
2497 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
2498 st->codecpar->codec_id = id;
2499 mov_parse_stsd_subtitle(c, pb, st, sc,
2500 size - (avio_tell(pb) - start_pos));
2502 ret = mov_parse_stsd_data(c, pb, st, sc,
2503 size - (avio_tell(pb) - start_pos));
2507 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2508 a.size = size - (avio_tell(pb) - start_pos);
2510 if ((ret = mov_read_default(c, pb, a)) < 0)
2512 } else if (a.size > 0)
2513 avio_skip(pb, a.size);
2515 if (sc->extradata && st->codecpar->extradata) {
2516 int extra_size = st->codecpar->extradata_size;
2518 /* Move the current stream extradata to the stream context one. */
2519 sc->extradata_size[pseudo_stream_id] = extra_size;
2520 sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
2521 if (!sc->extradata[pseudo_stream_id])
2522 return AVERROR(ENOMEM);
2523 memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
2524 av_freep(&st->codecpar->extradata);
2525 st->codecpar->extradata_size = 0;
2530 if (pb->eof_reached) {
2531 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSD atom\n");
2538 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2541 MOVStreamContext *sc;
2544 if (c->fc->nb_streams < 1)
2546 st = c->fc->streams[c->fc->nb_streams - 1];
2549 avio_r8(pb); /* version */
2550 avio_rb24(pb); /* flags */
2551 entries = avio_rb32(pb);
2554 av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
2555 return AVERROR_INVALIDDATA;
2558 if (sc->extradata) {
2559 av_log(c->fc, AV_LOG_ERROR,
2560 "Duplicate stsd found in this track.\n");
2561 return AVERROR_INVALIDDATA;
2564 /* Prepare space for hosting multiple extradata. */
2565 sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
2567 return AVERROR(ENOMEM);
2569 sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
2570 if (!sc->extradata_size) {
2571 ret = AVERROR(ENOMEM);
2575 ret = ff_mov_read_stsd_entries(c, pb, entries);
2579 /* Restore back the primary extradata. */
2580 av_freep(&st->codecpar->extradata);
2581 st->codecpar->extradata_size = sc->extradata_size[0];
2582 if (sc->extradata_size[0]) {
2583 st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
2584 if (!st->codecpar->extradata)
2585 return AVERROR(ENOMEM);
2586 memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
2589 return mov_finalize_stsd_codec(c, pb, st, sc);
2591 av_freep(&sc->extradata);
2592 av_freep(&sc->extradata_size);
2596 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2599 MOVStreamContext *sc;
2600 unsigned int i, entries;
2602 if (c->fc->nb_streams < 1)
2604 st = c->fc->streams[c->fc->nb_streams-1];
2607 avio_r8(pb); /* version */
2608 avio_rb24(pb); /* flags */
2610 entries = avio_rb32(pb);
2611 if ((uint64_t)entries * 12 + 4 > atom.size)
2612 return AVERROR_INVALIDDATA;
2614 av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
2619 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2620 av_free(sc->stsc_data);
2622 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2624 return AVERROR(ENOMEM);
2626 for (i = 0; i < entries && !pb->eof_reached; i++) {
2627 sc->stsc_data[i].first = avio_rb32(pb);
2628 sc->stsc_data[i].count = avio_rb32(pb);
2629 sc->stsc_data[i].id = avio_rb32(pb);
2633 for (i = sc->stsc_count - 1; i < UINT_MAX; i--) {
2634 if ((i+1 < sc->stsc_count && sc->stsc_data[i].first >= sc->stsc_data[i+1].first) ||
2635 (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first) ||
2636 sc->stsc_data[i].first < 1 ||
2637 sc->stsc_data[i].count < 1 ||
2638 sc->stsc_data[i].id < 1) {
2639 av_log(c->fc, AV_LOG_WARNING, "STSC entry %d is invalid (first=%d count=%d id=%d)\n", i, sc->stsc_data[i].first, sc->stsc_data[i].count, sc->stsc_data[i].id);
2640 if (i+1 >= sc->stsc_count || sc->stsc_data[i+1].first < 2)
2641 return AVERROR_INVALIDDATA;
2642 // We replace this entry by the next valid
2643 sc->stsc_data[i].first = sc->stsc_data[i+1].first - 1;
2644 sc->stsc_data[i].count = sc->stsc_data[i+1].count;
2645 sc->stsc_data[i].id = sc->stsc_data[i+1].id;
2649 if (pb->eof_reached) {
2650 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSC atom\n");
2657 static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
2659 return index < count - 1;
2662 /* Compute the samples value for the stsc entry at the given index. */
2663 static inline int64_t mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
2667 if (mov_stsc_index_valid(index, sc->stsc_count))
2668 chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
2670 chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
2672 return sc->stsc_data[index].count * (int64_t)chunk_count;
2675 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2678 MOVStreamContext *sc;
2679 unsigned i, entries;
2681 if (c->fc->nb_streams < 1)
2683 st = c->fc->streams[c->fc->nb_streams-1];
2686 avio_rb32(pb); // version + flags
2688 entries = avio_rb32(pb);
2690 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2691 av_free(sc->stps_data);
2693 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2695 return AVERROR(ENOMEM);
2697 for (i = 0; i < entries && !pb->eof_reached; i++) {
2698 sc->stps_data[i] = avio_rb32(pb);
2703 if (pb->eof_reached) {
2704 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STPS atom\n");
2711 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2714 MOVStreamContext *sc;
2715 unsigned int i, entries;
2717 if (c->fc->nb_streams < 1)
2719 st = c->fc->streams[c->fc->nb_streams-1];
2722 avio_r8(pb); /* version */
2723 avio_rb24(pb); /* flags */
2725 entries = avio_rb32(pb);
2727 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
2731 sc->keyframe_absent = 1;
2732 if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2733 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2737 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2738 if (entries >= UINT_MAX / sizeof(int))
2739 return AVERROR_INVALIDDATA;
2740 av_freep(&sc->keyframes);
2741 sc->keyframe_count = 0;
2742 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2744 return AVERROR(ENOMEM);
2746 for (i = 0; i < entries && !pb->eof_reached; i++) {
2747 sc->keyframes[i] = avio_rb32(pb);
2750 sc->keyframe_count = i;
2752 if (pb->eof_reached) {
2753 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSS atom\n");
2760 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2763 MOVStreamContext *sc;
2764 unsigned int i, entries, sample_size, field_size, num_bytes;
2769 if (c->fc->nb_streams < 1)
2771 st = c->fc->streams[c->fc->nb_streams-1];
2774 avio_r8(pb); /* version */
2775 avio_rb24(pb); /* flags */
2777 if (atom.type == MKTAG('s','t','s','z')) {
2778 sample_size = avio_rb32(pb);
2779 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2780 sc->sample_size = sample_size;
2781 sc->stsz_sample_size = sample_size;
2785 avio_rb24(pb); /* reserved */
2786 field_size = avio_r8(pb);
2788 entries = avio_rb32(pb);
2790 av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
2792 sc->sample_count = entries;
2796 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2797 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
2798 return AVERROR_INVALIDDATA;
2803 if (entries >= (UINT_MAX - 4) / field_size)
2804 return AVERROR_INVALIDDATA;
2805 if (sc->sample_sizes)
2806 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2807 av_free(sc->sample_sizes);
2808 sc->sample_count = 0;
2809 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2810 if (!sc->sample_sizes)
2811 return AVERROR(ENOMEM);
2813 num_bytes = (entries*field_size+4)>>3;
2815 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2817 av_freep(&sc->sample_sizes);
2818 return AVERROR(ENOMEM);
2821 ret = ffio_read_size(pb, buf, num_bytes);
2823 av_freep(&sc->sample_sizes);
2828 init_get_bits(&gb, buf, 8*num_bytes);
2830 for (i = 0; i < entries && !pb->eof_reached; i++) {
2831 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2832 sc->data_size += sc->sample_sizes[i];
2835 sc->sample_count = i;
2839 if (pb->eof_reached) {
2840 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSZ atom\n");
2847 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2850 MOVStreamContext *sc;
2851 unsigned int i, entries, alloc_size = 0;
2853 int64_t total_sample_count=0;
2855 if (c->fc->nb_streams < 1)
2857 st = c->fc->streams[c->fc->nb_streams-1];
2860 avio_r8(pb); /* version */
2861 avio_rb24(pb); /* flags */
2862 entries = avio_rb32(pb);
2864 av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
2865 c->fc->nb_streams-1, entries);
2868 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2869 av_freep(&sc->stts_data);
2871 if (entries >= INT_MAX / sizeof(*sc->stts_data))
2872 return AVERROR(ENOMEM);
2874 for (i = 0; i < entries && !pb->eof_reached; i++) {
2875 int sample_duration;
2876 unsigned int sample_count;
2877 unsigned int min_entries = FFMIN(FFMAX(i + 1, 1024 * 1024), entries);
2878 MOVStts *stts_data = av_fast_realloc(sc->stts_data, &alloc_size,
2879 min_entries * sizeof(*sc->stts_data));
2881 av_freep(&sc->stts_data);
2883 return AVERROR(ENOMEM);
2885 sc->stts_count = min_entries;
2886 sc->stts_data = stts_data;
2888 sample_count=avio_rb32(pb);
2889 sample_duration = avio_rb32(pb);
2891 sc->stts_data[i].count= sample_count;
2892 sc->stts_data[i].duration= sample_duration;
2894 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2895 sample_count, sample_duration);
2899 && sample_count == 1
2900 && total_sample_count > 100
2901 && sample_duration/10 > duration / total_sample_count)
2902 sample_duration = duration / total_sample_count;
2903 duration+=(int64_t)sample_duration*(uint64_t)sample_count;
2904 total_sample_count+=sample_count;
2910 duration <= INT64_MAX - sc->duration_for_fps &&
2911 total_sample_count <= INT64_MAX - sc->nb_frames_for_fps
2913 sc->duration_for_fps += duration;
2914 sc->nb_frames_for_fps += total_sample_count;
2917 if (pb->eof_reached) {
2918 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STTS atom\n");
2922 st->nb_frames= total_sample_count;
2924 st->duration= duration;
2925 sc->track_end = duration;
2929 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2932 if (duration == INT_MIN) {
2933 av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2936 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2940 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2943 MOVStreamContext *sc;
2944 unsigned int i, entries, ctts_count = 0;
2946 if (c->fc->nb_streams < 1)
2948 st = c->fc->streams[c->fc->nb_streams-1];
2951 avio_r8(pb); /* version */
2952 avio_rb24(pb); /* flags */
2953 entries = avio_rb32(pb);
2955 av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
2959 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2960 return AVERROR_INVALIDDATA;
2961 av_freep(&sc->ctts_data);
2962 sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
2964 return AVERROR(ENOMEM);
2966 for (i = 0; i < entries && !pb->eof_reached; i++) {
2967 int count =avio_rb32(pb);
2968 int duration =avio_rb32(pb);
2971 av_log(c->fc, AV_LOG_TRACE,
2972 "ignoring CTTS entry with count=%d duration=%d\n",
2977 add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size,
2980 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2983 if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2984 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2985 av_freep(&sc->ctts_data);
2991 mov_update_dts_shift(sc, duration);
2994 sc->ctts_count = ctts_count;
2996 if (pb->eof_reached) {
2997 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted CTTS atom\n");
3001 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
3006 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3009 MOVStreamContext *sc;
3010 unsigned int i, entries;
3012 uint32_t grouping_type;
3014 if (c->fc->nb_streams < 1)
3016 st = c->fc->streams[c->fc->nb_streams-1];
3019 version = avio_r8(pb); /* version */
3020 avio_rb24(pb); /* flags */
3021 grouping_type = avio_rl32(pb);
3022 if (grouping_type != MKTAG( 'r','a','p',' '))
3023 return 0; /* only support 'rap ' grouping */
3025 avio_rb32(pb); /* grouping_type_parameter */
3027 entries = avio_rb32(pb);
3031 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
3032 av_free(sc->rap_group);
3033 sc->rap_group_count = 0;
3034 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
3036 return AVERROR(ENOMEM);
3038 for (i = 0; i < entries && !pb->eof_reached; i++) {
3039 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
3040 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
3043 sc->rap_group_count = i;
3045 if (pb->eof_reached) {
3046 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted SBGP atom\n");
3054 * Get ith edit list entry (media time, duration).
3056 static int get_edit_list_entry(MOVContext *mov,
3057 const MOVStreamContext *msc,
3058 unsigned int edit_list_index,
3059 int64_t *edit_list_media_time,
3060 int64_t *edit_list_duration,
3061 int64_t global_timescale)
3063 if (edit_list_index == msc->elst_count) {
3066 *edit_list_media_time = msc->elst_data[edit_list_index].time;
3067 *edit_list_duration = msc->elst_data[edit_list_index].duration;
3069 /* duration is in global timescale units;convert to msc timescale */
3070 if (global_timescale == 0) {
3071 avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
3074 *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
3080 * Find the closest previous frame to the timestamp_pts, in e_old index
3081 * entries. Searching for just any frame / just key frames can be controlled by
3082 * last argument 'flag'.
3083 * Note that if ctts_data is not NULL, we will always search for a key frame
3084 * irrespective of the value of 'flag'. If we don't find any keyframe, we will
3085 * return the first frame of the video.
3087 * Here the timestamp_pts is considered to be a presentation timestamp and
3088 * the timestamp of index entries are considered to be decoding timestamps.
3090 * Returns 0 if successful in finding a frame, else returns -1.
3091 * Places the found index corresponding output arg.
3093 * If ctts_old is not NULL, then refines the searched entry by searching
3094 * backwards from the found timestamp, to find the frame with correct PTS.
3096 * Places the found ctts_index and ctts_sample in corresponding output args.
3098 static int find_prev_closest_index(AVStream *st,
3099 AVIndexEntry *e_old,
3103 int64_t timestamp_pts,
3106 int64_t* ctts_index,
3107 int64_t* ctts_sample)
3109 MOVStreamContext *msc = st->priv_data;
3110 AVIndexEntry *e_keep = st->index_entries;
3111 int nb_keep = st->nb_index_entries;
3113 int64_t index_ctts_count;
3117 // If dts_shift > 0, then all the index timestamps will have to be offset by
3118 // at least dts_shift amount to obtain PTS.
3119 // Hence we decrement the searched timestamp_pts by dts_shift to find the closest index element.
3120 if (msc->dts_shift > 0) {
3121 timestamp_pts -= msc->dts_shift;
3124 st->index_entries = e_old;
3125 st->nb_index_entries = nb_old;
3126 *index = av_index_search_timestamp(st, timestamp_pts, flag | AVSEEK_FLAG_BACKWARD);
3128 // Keep going backwards in the index entries until the timestamp is the same.
3130 for (i = *index; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
3132 if ((flag & AVSEEK_FLAG_ANY) ||
3133 (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
3139 // If we have CTTS then refine the search, by searching backwards over PTS
3140 // computed by adding corresponding CTTS durations to index timestamps.
3141 if (ctts_data && *index >= 0) {
3142 av_assert0(ctts_index);
3143 av_assert0(ctts_sample);
3144 // Find out the ctts_index for the found frame.
3147 for (index_ctts_count = 0; index_ctts_count < *index; index_ctts_count++) {
3148 if (*ctts_index < ctts_count) {
3150 if (ctts_data[*ctts_index].count == *ctts_sample) {
3157 while (*index >= 0 && (*ctts_index) >= 0 && (*ctts_index) < ctts_count) {
3158 // Find a "key frame" with PTS <= timestamp_pts (So that we can decode B-frames correctly).
3159 // No need to add dts_shift to the timestamp here becase timestamp_pts has already been
3160 // compensated by dts_shift above.
3161 if ((e_old[*index].timestamp + ctts_data[*ctts_index].duration) <= timestamp_pts &&
3162 (e_old[*index].flags & AVINDEX_KEYFRAME)) {
3167 if (*ctts_sample == 0) {
3169 if (*ctts_index >= 0)
3170 *ctts_sample = ctts_data[*ctts_index].count - 1;
3177 /* restore AVStream state*/
3178 st->index_entries = e_keep;
3179 st->nb_index_entries = nb_keep;
3180 return *index >= 0 ? 0 : -1;
3184 * Add index entry with the given values, to the end of st->index_entries.
3185 * Returns the new size st->index_entries if successful, else returns -1.
3187 * This function is similar to ff_add_index_entry in libavformat/utils.c
3188 * except that here we are always unconditionally adding an index entry to
3189 * the end, instead of searching the entries list and skipping the add if
3190 * there is an existing entry with the same timestamp.
3191 * This is needed because the mov_fix_index calls this func with the same
3192 * unincremented timestamp for successive discarded frames.
3194 static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
3195 int size, int distance, int flags)
3197 AVIndexEntry *entries, *ie;
3199 const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
3201 // Double the allocation each time, to lower memory fragmentation.
3202 // Another difference from ff_add_index_entry function.
3203 const size_t requested_size =
3204 min_size_needed > st->index_entries_allocated_size ?
3205 FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
3208 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
3211 entries = av_fast_realloc(st->index_entries,
3212 &st->index_entries_allocated_size,
3217 st->index_entries= entries;
3219 index= st->nb_index_entries++;
3220 ie= &entries[index];
3223 ie->timestamp = timestamp;
3224 ie->min_distance= distance;
3231 * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
3232 * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
3234 static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
3235 int64_t* frame_duration_buffer,
3236 int frame_duration_buffer_size) {
3238 av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
3239 for (i = 0; i < frame_duration_buffer_size; i++) {
3240 end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
3241 st->index_entries[end_index - 1 - i].timestamp = end_ts;
3246 * Append a new ctts entry to ctts_data.
3247 * Returns the new ctts_count if successful, else returns -1.
3249 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
3250 int count, int duration)
3252 MOVStts *ctts_buf_new;
3253 const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
3254 const size_t requested_size =
3255 min_size_needed > *allocated_size ?
3256 FFMAX(min_size_needed, 2 * (*allocated_size)) :
3259 if((unsigned)(*ctts_count) >= UINT_MAX / sizeof(MOVStts) - 1)
3262 ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
3267 *ctts_data = ctts_buf_new;
3269 ctts_buf_new[*ctts_count].count = count;
3270 ctts_buf_new[*ctts_count].duration = duration;
3272 *ctts_count = (*ctts_count) + 1;
3276 #define MAX_REORDER_DELAY 16
3277 static void mov_estimate_video_delay(MOVContext *c, AVStream* st) {
3278 MOVStreamContext *msc = st->priv_data;
3281 int ctts_sample = 0;
3282 int64_t pts_buf[MAX_REORDER_DELAY + 1]; // Circular buffer to sort pts.
3285 int j, r, num_swaps;
3287 if (st->codecpar->video_delay <= 0 && msc->ctts_data &&
3288 st->codecpar->codec_id == AV_CODEC_ID_H264) {
3289 st->codecpar->video_delay = 0;
3290 for(ind = 0; ind < st->nb_index_entries && ctts_ind < msc->ctts_count; ++ind) {
3291 if (buf_size == (MAX_REORDER_DELAY + 1)) {
3292 // If circular buffer is full, then move the first element forward.
3293 buf_start = (buf_start + 1) % buf_size;
3298 // Point j to the last elem of the buffer and insert the current pts there.
3299 j = (buf_start + buf_size - 1) % buf_size;
3300 pts_buf[j] = st->index_entries[ind].timestamp + msc->ctts_data[ctts_ind].duration;
3302 // The timestamps that are already in the sorted buffer, and are greater than the
3303 // current pts, are exactly the timestamps that need to be buffered to output PTS
3304 // in correct sorted order.
3305 // Hence the video delay (which is the buffer size used to sort DTS and output PTS),
3306 // can be computed as the maximum no. of swaps any particular timestamp needs to
3307 // go through, to keep this buffer in sorted order.
3309 while (j != buf_start) {
3310 r = (j - 1 + buf_size) % buf_size;
3311 if (pts_buf[j] < pts_buf[r]) {
3312 FFSWAP(int64_t, pts_buf[j], pts_buf[r]);
3317 st->codecpar->video_delay = FFMAX(st->codecpar->video_delay, num_swaps);
3320 if (ctts_sample == msc->ctts_data[ctts_ind].count) {
3325 av_log(c->fc, AV_LOG_DEBUG, "Setting codecpar->delay to %d for stream st: %d\n",
3326 st->codecpar->video_delay, st->index);
3330 static void mov_current_sample_inc(MOVStreamContext *sc)
3332 sc->current_sample++;
3333 sc->current_index++;
3334 if (sc->index_ranges &&
3335 sc->current_index >= sc->current_index_range->end &&
3336 sc->current_index_range->end) {
3337 sc->current_index_range++;
3338 sc->current_index = sc->current_index_range->start;
3342 static void mov_current_sample_dec(MOVStreamContext *sc)
3344 sc->current_sample--;
3345 sc->current_index--;
3346 if (sc->index_ranges &&
3347 sc->current_index < sc->current_index_range->start &&
3348 sc->current_index_range > sc->index_ranges) {
3349 sc->current_index_range--;
3350 sc->current_index = sc->current_index_range->end - 1;
3354 static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
3358 sc->current_sample = current_sample;
3359 sc->current_index = current_sample;
3360 if (!sc->index_ranges) {
3364 for (sc->current_index_range = sc->index_ranges;
3365 sc->current_index_range->end;
3366 sc->current_index_range++) {
3367 range_size = sc->current_index_range->end - sc->current_index_range->start;
3368 if (range_size > current_sample) {
3369 sc->current_index = sc->current_index_range->start + current_sample;
3372 current_sample -= range_size;
3377 * Fix st->index_entries, so that it contains only the entries (and the entries
3378 * which are needed to decode them) that fall in the edit list time ranges.
3379 * Also fixes the timestamps of the index entries to match the timeline
3380 * specified the edit lists.
3382 static void mov_fix_index(MOVContext *mov, AVStream *st)
3384 MOVStreamContext *msc = st->priv_data;
3385 AVIndexEntry *e_old = st->index_entries;
3386 int nb_old = st->nb_index_entries;
3387 const AVIndexEntry *e_old_end = e_old + nb_old;
3388 const AVIndexEntry *current = NULL;
3389 MOVStts *ctts_data_old = msc->ctts_data;
3390 int64_t ctts_index_old = 0;
3391 int64_t ctts_sample_old = 0;
3392 int64_t ctts_count_old = msc->ctts_count;
3393 int64_t edit_list_media_time = 0;
3394 int64_t edit_list_duration = 0;
3395 int64_t frame_duration = 0;
3396 int64_t edit_list_dts_counter = 0;
3397 int64_t edit_list_dts_entry_end = 0;
3398 int64_t edit_list_start_ctts_sample = 0;
3400 int64_t curr_ctts = 0;
3401 int64_t empty_edits_sum_duration = 0;
3402 int64_t edit_list_index = 0;
3405 int64_t start_dts = 0;
3406 int64_t edit_list_start_encountered = 0;
3407 int64_t search_timestamp = 0;
3408 int64_t* frame_duration_buffer = NULL;
3409 int num_discarded_begin = 0;
3410 int first_non_zero_audio_edit = -1;
3411 int packet_skip_samples = 0;
3412 MOVIndexRange *current_index_range;
3414 int found_keyframe_after_edit = 0;
3416 if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
3420 // allocate the index ranges array
3421 msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
3422 if (!msc->index_ranges) {
3423 av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
3426 msc->current_index_range = msc->index_ranges;
3427 current_index_range = msc->index_ranges - 1;
3429 // Clean AVStream from traces of old index
3430 st->index_entries = NULL;
3431 st->index_entries_allocated_size = 0;
3432 st->nb_index_entries = 0;
3434 // Clean ctts fields of MOVStreamContext
3435 msc->ctts_data = NULL;
3436 msc->ctts_count = 0;
3437 msc->ctts_index = 0;
3438 msc->ctts_sample = 0;
3439 msc->ctts_allocated_size = 0;
3441 // Reinitialize min_corrected_pts so that it can be computed again.
3442 msc->min_corrected_pts = -1;
3444 // If the dts_shift is positive (in case of negative ctts values in mov),
3445 // then negate the DTS by dts_shift
3446 if (msc->dts_shift > 0) {
3447 edit_list_dts_entry_end -= msc->dts_shift;
3448 av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
3451 start_dts = edit_list_dts_entry_end;
3453 while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
3454 &edit_list_duration, mov->time_scale)) {
3455 av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
3456 st->index, edit_list_index, edit_list_media_time, edit_list_duration);
3458 edit_list_dts_counter = edit_list_dts_entry_end;
3459 edit_list_dts_entry_end += edit_list_duration;
3460 num_discarded_begin = 0;
3461 if (edit_list_media_time == -1) {
3462 empty_edits_sum_duration += edit_list_duration;
3466 // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
3467 // according to the edit list below.
3468 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3469 if (first_non_zero_audio_edit < 0) {
3470 first_non_zero_audio_edit = 1;
3472 first_non_zero_audio_edit = 0;
3475 if (first_non_zero_audio_edit > 0)
3476 st->skip_samples = msc->start_pad = 0;
3479 // While reordering frame index according to edit list we must handle properly
3480 // the scenario when edit list entry starts from none key frame.
3481 // We find closest previous key frame and preserve it and consequent frames in index.
3482 // All frames which are outside edit list entry time boundaries will be dropped after decoding.
3483 search_timestamp = edit_list_media_time;
3484 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3485 // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
3486 // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
3487 // edit_list_media_time to cover the decoder delay.
3488 search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
3491 if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, 0,
3492 &index, &ctts_index_old, &ctts_sample_old) < 0) {
3493 av_log(mov->fc, AV_LOG_WARNING,
3494 "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
3495 st->index, edit_list_index, search_timestamp);
3496 if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, AVSEEK_FLAG_ANY,
3497 &index, &ctts_index_old, &ctts_sample_old) < 0) {
3498 av_log(mov->fc, AV_LOG_WARNING,
3499 "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n",
3500 st->index, edit_list_index, search_timestamp);
3503 ctts_sample_old = 0;
3506 current = e_old + index;
3507 edit_list_start_ctts_sample = ctts_sample_old;
3509 // Iterate over index and arrange it according to edit list
3510 edit_list_start_encountered = 0;
3511 found_keyframe_after_edit = 0;
3512 for (; current < e_old_end; current++, index++) {
3513 // check if frame outside edit list mark it for discard
3514 frame_duration = (current + 1 < e_old_end) ?
3515 ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
3517 flags = current->flags;
3519 // frames (pts) before or after edit list
3520 curr_cts = current->timestamp + msc->dts_shift;
3523 if (ctts_data_old && ctts_index_old < ctts_count_old) {
3524 curr_ctts = ctts_data_old[ctts_index_old].duration;
3525 av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",
3526 curr_cts, curr_ctts, ctts_index_old, ctts_count_old);
3527 curr_cts += curr_ctts;
3529 if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
3530 if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3531 &msc->ctts_allocated_size,
3532 ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3533 ctts_data_old[ctts_index_old].duration) == -1) {
3534 av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3536 ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3537 ctts_data_old[ctts_index_old].duration);
3541 ctts_sample_old = 0;
3542 edit_list_start_ctts_sample = 0;
3546 if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
3547 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
3548 curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
3549 first_non_zero_audio_edit > 0) {
3550 packet_skip_samples = edit_list_media_time - curr_cts;
3551 st->skip_samples += packet_skip_samples;
3553 // Shift the index entry timestamp by packet_skip_samples to be correct.
3554 edit_list_dts_counter -= packet_skip_samples;
3555 if (edit_list_start_encountered == 0) {
3556 edit_list_start_encountered = 1;
3557 // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3558 // discarded packets.
3559 if (frame_duration_buffer) {
3560 fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3561 frame_duration_buffer, num_discarded_begin);
3562 av_freep(&frame_duration_buffer);
3566 av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
3568 flags |= AVINDEX_DISCARD_FRAME;
3569 av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
3571 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
3572 num_discarded_begin++;
3573 frame_duration_buffer = av_realloc(frame_duration_buffer,
3574 num_discarded_begin * sizeof(int64_t));
3575 if (!frame_duration_buffer) {
3576 av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
3579 frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
3581 // Increment skip_samples for the first non-zero audio edit list
3582 if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
3583 st->skip_samples += frame_duration;
3588 if (msc->min_corrected_pts < 0) {
3589 msc->min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
3591 msc->min_corrected_pts = FFMIN(msc->min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
3593 if (edit_list_start_encountered == 0) {
3594 edit_list_start_encountered = 1;
3595 // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3596 // discarded packets.
3597 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
3598 fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3599 frame_duration_buffer, num_discarded_begin);
3600 av_freep(&frame_duration_buffer);
3605 if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
3606 current->min_distance, flags) == -1) {
3607 av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
3611 // Update the index ranges array
3612 if (current_index_range < msc->index_ranges || index != current_index_range->end) {
3613 current_index_range++;
3614 current_index_range->start = index;
3616 current_index_range->end = index + 1;
3618 // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
3619 if (edit_list_start_encountered > 0) {
3620 edit_list_dts_counter = edit_list_dts_counter + frame_duration;
3623 // Break when found first key frame after edit entry completion
3624 if ((curr_cts + frame_duration >= (edit_list_duration + edit_list_media_time)) &&
3625 ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
3626 if (ctts_data_old) {
3627 // If we have CTTS and this is the first keyframe after edit elist,
3628 // wait for one more, because there might be trailing B-frames after this I-frame
3629 // that do belong to the edit.
3630 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && found_keyframe_after_edit == 0) {
3631 found_keyframe_after_edit = 1;
3634 if (ctts_sample_old != 0) {
3635 if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3636 &msc->ctts_allocated_size,
3637 ctts_sample_old - edit_list_start_ctts_sample,
3638 ctts_data_old[ctts_index_old].duration) == -1) {
3639 av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3640 ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
3641 ctts_data_old[ctts_index_old].duration);
3650 // If there are empty edits, then msc->min_corrected_pts might be positive
3651 // intentionally. So we subtract the sum duration of emtpy edits here.
3652 msc->min_corrected_pts -= empty_edits_sum_duration;
3654 // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
3655 // dts by that amount to make the first pts zero.
3656 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && msc->min_corrected_pts > 0) {
3657 av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", msc->min_corrected_pts);
3658 for (i = 0; i < st->nb_index_entries; ++i) {
3659 st->index_entries[i].timestamp -= msc->min_corrected_pts;
3663 // Update av stream length
3664 st->duration = edit_list_dts_entry_end - start_dts;
3665 msc->start_pad = st->skip_samples;
3667 // Free the old index and the old CTTS structures
3669 av_free(ctts_data_old);
3670 av_freep(&frame_duration_buffer);
3672 // Null terminate the index ranges array
3673 current_index_range++;
3674 current_index_range->start = 0;
3675 current_index_range->end = 0;
3676 msc->current_index = msc->index_ranges[0].start;
3679 static void mov_build_index(MOVContext *mov, AVStream *st)
3681 MOVStreamContext *sc = st->priv_data;
3682 int64_t current_offset;
3683 int64_t current_dts = 0;
3684 unsigned int stts_index = 0;
3685 unsigned int stsc_index = 0;
3686 unsigned int stss_index = 0;
3687 unsigned int stps_index = 0;
3689 uint64_t stream_size = 0;
3690 MOVStts *ctts_data_old = sc->ctts_data;
3691 unsigned int ctts_count_old = sc->ctts_count;
3693 if (sc->elst_count) {
3694 int i, edit_start_index = 0, multiple_edits = 0;
3695 int64_t empty_duration = 0; // empty duration of the first edit list entry
3696 int64_t start_time = 0; // start time of the media
3698 for (i = 0; i < sc->elst_count; i++) {
3699 const MOVElst *e = &sc->elst_data[i];
3700 if (i == 0 && e->time == -1) {
3701 /* if empty, the first entry is the start time of the stream
3702 * relative to the presentation itself */
3703 empty_duration = e->duration;
3704 edit_start_index = 1;
3705 } else if (i == edit_start_index && e->time >= 0) {
3706 start_time = e->time;
3712 if (multiple_edits && !mov->advanced_editlist)
3713 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
3714 "Use -advanced_editlist to correctly decode otherwise "
3715 "a/v desync might occur\n");
3717 /* adjust first dts according to edit list */
3718 if ((empty_duration || start_time) && mov->time_scale > 0) {
3720 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
3721 sc->time_offset = start_time - empty_duration;
3722 sc->min_corrected_pts = start_time;
3723 if (!mov->advanced_editlist)
3724 current_dts = -sc->time_offset;
3727 if (!multiple_edits && !mov->advanced_editlist &&
3728 st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
3729 sc->start_pad = start_time;
3732 /* only use old uncompressed audio chunk demuxing when stts specifies it */
3733 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
3734 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
3735 unsigned int current_sample = 0;
3736 unsigned int stts_sample = 0;
3737 unsigned int sample_size;
3738 unsigned int distance = 0;
3739 unsigned int rap_group_index = 0;
3740 unsigned int rap_group_sample = 0;
3741 int64_t last_dts = 0;
3742 int64_t dts_correction = 0;
3743 int rap_group_present = sc->rap_group_count && sc->rap_group;
3744 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
3746 current_dts -= sc->dts_shift;
3747 last_dts = current_dts;
3749 if (!sc->sample_count || st->nb_index_entries)
3751 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3753 if (av_reallocp_array(&st->index_entries,
3754 st->nb_index_entries + sc->sample_count,
3755 sizeof(*st->index_entries)) < 0) {
3756 st->nb_index_entries = 0;
3759 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
3761 if (ctts_data_old) {
3762 // Expand ctts entries such that we have a 1-1 mapping with samples
3763 if (sc->sample_count >= UINT_MAX / sizeof(*sc->ctts_data))
3766 sc->ctts_allocated_size = 0;
3767 sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size,
3768 sc->sample_count * sizeof(*sc->ctts_data));
3769 if (!sc->ctts_data) {
3770 av_free(ctts_data_old);
3774 memset((uint8_t*)(sc->ctts_data), 0, sc->ctts_allocated_size);
3776 for (i = 0; i < ctts_count_old &&
3777 sc->ctts_count < sc->sample_count; i++)
3778 for (j = 0; j < ctts_data_old[i].count &&
3779 sc->ctts_count < sc->sample_count; j++)
3780 add_ctts_entry(&sc->ctts_data, &sc->ctts_count,
3781 &sc->ctts_allocated_size, 1,
3782 ctts_data_old[i].duration);
3783 av_free(ctts_data_old);
3786 for (i = 0; i < sc->chunk_count; i++) {
3787 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
3788 current_offset = sc->chunk_offsets[i];
3789 while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3790 i + 1 == sc->stsc_data[stsc_index + 1].first)
3793 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
3794 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
3795 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
3796 sc->stsz_sample_size = sc->sample_size;
3798 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
3799 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
3800 sc->stsz_sample_size = sc->sample_size;
3803 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
3805 if (current_sample >= sc->sample_count) {
3806 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
3810 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
3812 if (stss_index + 1 < sc->keyframe_count)
3814 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
3816 if (stps_index + 1 < sc->stps_count)
3819 if (rap_group_present && rap_group_index < sc->rap_group_count) {
3820 if (sc->rap_group[rap_group_index].index > 0)
3822 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
3823 rap_group_sample = 0;
3827 if (sc->keyframe_absent
3829 && !rap_group_present
3830 && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
3834 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
3835 if (sc->pseudo_stream_id == -1 ||
3836 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
3838 if (sample_size > 0x3FFFFFFF) {
3839 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
3842 e = &st->index_entries[st->nb_index_entries++];
3843 e->pos = current_offset;
3844 e->timestamp = current_dts;
3845 e->size = sample_size;
3846 e->min_distance = distance;
3847 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
3848 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
3849 "size %u, distance %u, keyframe %d\n", st->index, current_sample,
3850 current_offset, current_dts, sample_size, distance, keyframe);
3851 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
3852 ff_rfps_add_frame(mov->fc, st, current_dts);
3855 current_offset += sample_size;
3856 stream_size += sample_size;
3858 /* A negative sample duration is invalid based on the spec,
3859 * but some samples need it to correct the DTS. */
3860 if (sc->stts_data[stts_index].duration < 0) {
3861 av_log(mov->fc, AV_LOG_WARNING,
3862 "Invalid SampleDelta %d in STTS, at %d st:%d\n",
3863 sc->stts_data[stts_index].duration, stts_index,
3865 dts_correction += sc->stts_data[stts_index].duration - 1;
3866 sc->stts_data[stts_index].duration = 1;
3868 current_dts += sc->stts_data[stts_index].duration;
3869 if (!dts_correction || current_dts + dts_correction > last_dts) {
3870 current_dts += dts_correction;
3873 /* Avoid creating non-monotonous DTS */
3874 dts_correction += current_dts - last_dts - 1;
3875 current_dts = last_dts + 1;
3877 last_dts = current_dts;
3881 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
3887 if (st->duration > 0)
3888 st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
3890 unsigned chunk_samples, total = 0;
3892 // compute total chunk count
3893 for (i = 0; i < sc->stsc_count; i++) {
3894 unsigned count, chunk_count;
3896 chunk_samples = sc->stsc_data[i].count;
3897 if (i != sc->stsc_count - 1 &&
3898 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
3899 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
3903 if (sc->samples_per_frame >= 160) { // gsm
3904 count = chunk_samples / sc->samples_per_frame;
3905 } else if (sc->samples_per_frame > 1) {
3906 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
3907 count = (chunk_samples+samples-1) / samples;
3909 count = (chunk_samples+1023) / 1024;
3912 if (mov_stsc_index_valid(i, sc->stsc_count))
3913 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
3915 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
3916 total += chunk_count * count;
3919 av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
3920 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3922 if (av_reallocp_array(&st->index_entries,
3923 st->nb_index_entries + total,
3924 sizeof(*st->index_entries)) < 0) {
3925 st->nb_index_entries = 0;
3928 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
3931 for (i = 0; i < sc->chunk_count; i++) {
3932 current_offset = sc->chunk_offsets[i];
3933 if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3934 i + 1 == sc->stsc_data[stsc_index + 1].first)
3936 chunk_samples = sc->stsc_data[stsc_index].count;
3938 while (chunk_samples > 0) {
3940 unsigned size, samples;
3942 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
3943 avpriv_request_sample(mov->fc,
3944 "Zero bytes per frame, but %d samples per frame",
3945 sc->samples_per_frame);
3949 if (sc->samples_per_frame >= 160) { // gsm
3950 samples = sc->samples_per_frame;
3951 size = sc->bytes_per_frame;
3953 if (sc->samples_per_frame > 1) {
3954 samples = FFMIN((1024 / sc->samples_per_frame)*
3955 sc->samples_per_frame, chunk_samples);
3956 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
3958 samples = FFMIN(1024, chunk_samples);
3959 size = samples * sc->sample_size;
3963 if (st->nb_index_entries >= total) {
3964 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
3967 if (size > 0x3FFFFFFF) {
3968 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
3971 e = &st->index_entries[st->nb_index_entries++];
3972 e->pos = current_offset;
3973 e->timestamp = current_dts;
3975 e->min_distance = 0;
3976 e->flags = AVINDEX_KEYFRAME;
3977 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
3978 "size %u, duration %u\n", st->index, i, current_offset, current_dts,
3981 current_offset += size;
3982 current_dts += samples;
3983 chunk_samples -= samples;
3988 if (!mov->ignore_editlist && mov->advanced_editlist) {
3989 // Fix index according to edit lists.
3990 mov_fix_index(mov, st);
3993 mov_estimate_video_delay(mov, st);
3996 static int test_same_origin(const char *src, const char *ref) {
4006 av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
4007 av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
4009 if (strlen(src) == 0) {
4011 } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
4012 strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
4013 strlen(src_host) + 1 >= sizeof(src_host) ||
4014 strlen(ref_host) + 1 >= sizeof(ref_host)) {
4016 } else if (strcmp(src_proto, ref_proto) ||
4017 strcmp(src_auth, ref_auth) ||
4018 strcmp(src_host, ref_host) ||
4019 src_port != ref_port) {
4025 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
4027 /* try relative path, we do not try the absolute because it can leak information about our
4028 system to an attacker */
4029 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
4030 char filename[1025];
4031 const char *src_path;
4034 /* find a source dir */
4035 src_path = strrchr(src, '/');
4041 /* find a next level down to target */
4042 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
4043 if (ref->path[l] == '/') {
4044 if (i == ref->nlvl_to - 1)
4050 /* compose filename if next level down to target was found */
4051 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
4052 memcpy(filename, src, src_path - src);
4053 filename[src_path - src] = 0;
4055 for (i = 1; i < ref->nlvl_from; i++)
4056 av_strlcat(filename, "../", sizeof(filename));
4058 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
4059 if (!c->use_absolute_path) {
4060 int same_origin = test_same_origin(src, filename);
4063 av_log(c->fc, AV_LOG_ERROR,
4064 "Reference with mismatching origin, %s not tried for security reasons, "
4065 "set demuxer option use_absolute_path to allow it anyway\n",
4067 return AVERROR(ENOENT);
4070 if(strstr(ref->path + l + 1, "..") ||
4071 strstr(ref->path + l + 1, ":") ||
4072 (ref->nlvl_from > 1 && same_origin < 0) ||
4073 (filename[0] == '/' && src_path == src))
4074 return AVERROR(ENOENT);
4077 if (strlen(filename) + 1 == sizeof(filename))
4078 return AVERROR(ENOENT);
4079 if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
4082 } else if (c->use_absolute_path) {
4083 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
4084 "this is a possible security issue\n");
4085 if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
4088 av_log(c->fc, AV_LOG_ERROR,
4089 "Absolute path %s not tried for security reasons, "
4090 "set demuxer option use_absolute_path to allow absolute paths\n",
4094 return AVERROR(ENOENT);
4097 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
4099 if (sc->time_scale <= 0) {
4100 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
4101 sc->time_scale = c->time_scale;
4102 if (sc->time_scale <= 0)
4107 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4110 MOVStreamContext *sc;
4113 st = avformat_new_stream(c->fc, NULL);
4114 if (!st) return AVERROR(ENOMEM);
4115 st->id = c->fc->nb_streams;
4116 sc = av_mallocz(sizeof(MOVStreamContext));
4117 if (!sc) return AVERROR(ENOMEM);
4120 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
4121 sc->ffindex = st->index;
4122 c->trak_index = st->index;
4124 if ((ret = mov_read_default(c, pb, atom)) < 0)
4130 if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
4131 (!sc->sample_size && !sc->sample_count))) ||
4132 (!sc->chunk_count && sc->sample_count)) {
4133 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
4137 if (sc->stsc_count && sc->stsc_data[ sc->stsc_count - 1 ].first > sc->chunk_count) {
4138 av_log(c->fc, AV_LOG_ERROR, "stream %d, contradictionary STSC and STCO\n",
4140 return AVERROR_INVALIDDATA;
4143 fix_timescale(c, sc);
4145 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
4147 mov_build_index(c, st);
4149 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
4150 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
4151 if (c->enable_drefs) {
4152 if (mov_open_dref(c, &sc->pb, c->fc->url, dref) < 0)
4153 av_log(c->fc, AV_LOG_ERROR,
4154 "stream %d, error opening alias: path='%s', dir='%s', "
4155 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
4156 st->index, dref->path, dref->dir, dref->filename,
4157 dref->volume, dref->nlvl_from, dref->nlvl_to);
4159 av_log(c->fc, AV_LOG_WARNING,
4160 "Skipped opening external track: "
4161 "stream %d, alias: path='%s', dir='%s', "
4162 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
4163 "Set enable_drefs to allow this.\n",
4164 st->index, dref->path, dref->dir, dref->filename,
4165 dref->volume, dref->nlvl_from, dref->nlvl_to);
4169 sc->pb_is_copied = 1;
4172 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
4173 if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
4174 sc->height && sc->width &&
4175 (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
4176 st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
4177 ((double)st->codecpar->width * sc->height), INT_MAX);
4180 #if FF_API_R_FRAME_RATE
4181 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
4182 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
4183 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
4187 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
4188 if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
4189 TAG_IS_AVCI(st->codecpar->codec_tag)) {
4190 ret = ff_generate_avci_extradata(st);
4195 switch (st->codecpar->codec_id) {
4196 #if CONFIG_H261_DECODER
4197 case AV_CODEC_ID_H261:
4199 #if CONFIG_H263_DECODER
4200 case AV_CODEC_ID_H263:
4202 #if CONFIG_MPEG4_DECODER
4203 case AV_CODEC_ID_MPEG4:
4205 st->codecpar->width = 0; /* let decoder init width/height */
4206 st->codecpar->height= 0;
4210 // If the duration of the mp3 packets is not constant, then they could need a parser
4211 if (st->codecpar->codec_id == AV_CODEC_ID_MP3
4212 && sc->stts_count > 3
4213 && sc->stts_count*10 > st->nb_frames
4214 && sc->time_scale == st->codecpar->sample_rate) {
4215 st->need_parsing = AVSTREAM_PARSE_FULL;
4217 /* Do not need those anymore. */
4218 av_freep(&sc->chunk_offsets);
4219 av_freep(&sc->sample_sizes);
4220 av_freep(&sc->keyframes);
4221 av_freep(&sc->stts_data);
4222 av_freep(&sc->stps_data);
4223 av_freep(&sc->elst_data);
4224 av_freep(&sc->rap_group);
4229 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4232 c->itunes_metadata = 1;
4233 ret = mov_read_default(c, pb, atom);
4234 c->itunes_metadata = 0;
4238 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4247 count = avio_rb32(pb);
4248 if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
4249 av_log(c->fc, AV_LOG_ERROR,
4250 "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
4251 return AVERROR_INVALIDDATA;
4254 c->meta_keys_count = count + 1;
4255 c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
4257 return AVERROR(ENOMEM);
4259 for (i = 1; i <= count; ++i) {
4260 uint32_t key_size = avio_rb32(pb);
4261 uint32_t type = avio_rl32(pb);
4263 av_log(c->fc, AV_LOG_ERROR,
4264 "The key# %"PRIu32" in meta has invalid size:"
4265 "%"PRIu32"\n", i, key_size);
4266 return AVERROR_INVALIDDATA;
4269 if (type != MKTAG('m','d','t','a')) {
4270 avio_skip(pb, key_size);
4272 c->meta_keys[i] = av_mallocz(key_size + 1);
4273 if (!c->meta_keys[i])
4274 return AVERROR(ENOMEM);
4275 avio_read(pb, c->meta_keys[i], key_size);
4281 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4283 int64_t end = avio_tell(pb) + atom.size;
4284 uint8_t *key = NULL, *val = NULL, *mean = NULL;
4288 MOVStreamContext *sc;
4290 if (c->fc->nb_streams < 1)
4292 st = c->fc->streams[c->fc->nb_streams-1];
4295 for (i = 0; i < 3; i++) {
4299 if (end - avio_tell(pb) <= 12)
4302 len = avio_rb32(pb);
4303 tag = avio_rl32(pb);
4304 avio_skip(pb, 4); // flags
4306 if (len < 12 || len - 12 > end - avio_tell(pb))
4310 if (tag == MKTAG('m', 'e', 'a', 'n'))
4312 else if (tag == MKTAG('n', 'a', 'm', 'e'))
4314 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
4321 *p = av_malloc(len + 1);
4323 ret = AVERROR(ENOMEM);
4326 ret = ffio_read_size(pb, *p, len);
4334 if (mean && key && val) {
4335 if (strcmp(key, "iTunSMPB") == 0) {
4336 int priming, remainder, samples;
4337 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
4338 if(priming>0 && priming<16384)
4339 sc->start_pad = priming;
4342 if (strcmp(key, "cdec") != 0) {
4343 av_dict_set(&c->fc->metadata, key, val,
4344 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
4348 av_log(c->fc, AV_LOG_VERBOSE,
4349 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
4352 avio_seek(pb, end, SEEK_SET);
4359 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4361 while (atom.size > 8) {
4362 uint32_t tag = avio_rl32(pb);
4364 if (tag == MKTAG('h','d','l','r')) {
4365 avio_seek(pb, -8, SEEK_CUR);
4367 return mov_read_default(c, pb, atom);
4373 // return 1 when matrix is identity, 0 otherwise
4374 #define IS_MATRIX_IDENT(matrix) \
4375 ( (matrix)[0][0] == (1 << 16) && \
4376 (matrix)[1][1] == (1 << 16) && \
4377 (matrix)[2][2] == (1 << 30) && \
4378 !(matrix)[0][1] && !(matrix)[0][2] && \
4379 !(matrix)[1][0] && !(matrix)[1][2] && \
4380 !(matrix)[2][0] && !(matrix)[2][1])
4382 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4387 int display_matrix[3][3];
4388 int res_display_matrix[3][3] = { { 0 } };
4390 MOVStreamContext *sc;
4394 if (c->fc->nb_streams < 1)
4396 st = c->fc->streams[c->fc->nb_streams-1];
4399 version = avio_r8(pb);
4400 flags = avio_rb24(pb);
4401 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
4407 avio_rb32(pb); /* creation time */
4408 avio_rb32(pb); /* modification time */
4410 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
4411 avio_rb32(pb); /* reserved */
4413 /* highlevel (considering edits) duration in movie timebase */
4414 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
4415 avio_rb32(pb); /* reserved */
4416 avio_rb32(pb); /* reserved */
4418 avio_rb16(pb); /* layer */
4419 avio_rb16(pb); /* alternate group */
4420 avio_rb16(pb); /* volume */
4421 avio_rb16(pb); /* reserved */
4423 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
4424 // they're kept in fixed point format through all calculations
4425 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
4426 // side data, but the scale factor is not needed to calculate aspect ratio
4427 for (i = 0; i < 3; i++) {
4428 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
4429 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
4430 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
4433 width = avio_rb32(pb); // 16.16 fixed point track width
4434 height = avio_rb32(pb); // 16.16 fixed point track height
4435 sc->width = width >> 16;
4436 sc->height = height >> 16;
4438 // apply the moov display matrix (after the tkhd one)
4439 for (i = 0; i < 3; i++) {
4440 const int sh[3] = { 16, 16, 30 };
4441 for (j = 0; j < 3; j++) {
4442 for (e = 0; e < 3; e++) {
4443 res_display_matrix[i][j] +=
4444 ((int64_t) display_matrix[i][e] *
4445 c->movie_display_matrix[e][j]) >> sh[e];
4450 // save the matrix when it is not the default identity
4451 if (!IS_MATRIX_IDENT(res_display_matrix)) {
4454 av_freep(&sc->display_matrix);
4455 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
4456 if (!sc->display_matrix)
4457 return AVERROR(ENOMEM);
4459 for (i = 0; i < 3; i++)
4460 for (j = 0; j < 3; j++)
4461 sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
4463 #if FF_API_OLD_ROTATE_API
4464 rotate = av_display_rotation_get(sc->display_matrix);
4465 if (!isnan(rotate)) {
4466 char rotate_buf[64];
4468 if (rotate < 0) // for backward compatibility
4470 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
4471 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
4476 // transform the display width/height according to the matrix
4477 // to keep the same scale, use [width height 1<<16]
4478 if (width && height && sc->display_matrix) {
4479 double disp_transform[2];
4481 for (i = 0; i < 2; i++)
4482 disp_transform[i] = hypot(sc->display_matrix[0 + i],
4483 sc->display_matrix[3 + i]);
4485 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
4486 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
4487 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
4488 st->sample_aspect_ratio = av_d2q(
4489 disp_transform[0] / disp_transform[1],
4495 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4497 MOVFragment *frag = &c->fragment;
4498 MOVTrackExt *trex = NULL;
4499 int flags, track_id, i;
4501 avio_r8(pb); /* version */
4502 flags = avio_rb24(pb);
4504 track_id = avio_rb32(pb);
4506 return AVERROR_INVALIDDATA;
4507 frag->track_id = track_id;
4508 set_frag_stream(&c->frag_index, track_id);
4509 for (i = 0; i < c->trex_count; i++)
4510 if (c->trex_data[i].track_id == frag->track_id) {
4511 trex = &c->trex_data[i];
4515 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
4516 return AVERROR_INVALIDDATA;
4519 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
4520 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
4521 frag->moof_offset : frag->implicit_offset;
4522 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
4524 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
4525 avio_rb32(pb) : trex->duration;
4526 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
4527 avio_rb32(pb) : trex->size;
4528 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
4529 avio_rb32(pb) : trex->flags;
4530 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
4535 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4540 num = atom.size / 4;
4541 if (!(new_tracks = av_malloc_array(num, sizeof(int))))
4542 return AVERROR(ENOMEM);
4544 av_free(c->chapter_tracks);
4545 c->chapter_tracks = new_tracks;
4546 c->nb_chapter_tracks = num;
4548 for (i = 0; i < num && !pb->eof_reached; i++)
4549 c->chapter_tracks[i] = avio_rb32(pb);
4554 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4559 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
4560 return AVERROR_INVALIDDATA;
4561 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
4562 sizeof(*c->trex_data))) < 0) {
4567 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
4569 trex = &c->trex_data[c->trex_count++];
4570 avio_r8(pb); /* version */
4571 avio_rb24(pb); /* flags */
4572 trex->track_id = avio_rb32(pb);
4573 trex->stsd_id = avio_rb32(pb);
4574 trex->duration = avio_rb32(pb);
4575 trex->size = avio_rb32(pb);
4576 trex->flags = avio_rb32(pb);
4580 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4582 MOVFragment *frag = &c->fragment;
4583 AVStream *st = NULL;
4584 MOVStreamContext *sc;
4586 MOVFragmentStreamInfo * frag_stream_info;
4587 int64_t base_media_decode_time;
4589 for (i = 0; i < c->fc->nb_streams; i++) {
4590 if (c->fc->streams[i]->id == frag->track_id) {
4591 st = c->fc->streams[i];
4596 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4597 return AVERROR_INVALIDDATA;
4600 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
4602 version = avio_r8(pb);
4603 avio_rb24(pb); /* flags */
4605 base_media_decode_time = avio_rb64(pb);
4607 base_media_decode_time = avio_rb32(pb);
4610 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4611 if (frag_stream_info)
4612 frag_stream_info->tfdt_dts = base_media_decode_time;
4613 sc->track_end = base_media_decode_time;
4618 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4620 MOVFragment *frag = &c->fragment;
4621 AVStream *st = NULL;
4622 MOVStreamContext *sc;
4625 int64_t dts, pts = AV_NOPTS_VALUE;
4626 int data_offset = 0;
4627 unsigned entries, first_sample_flags = frag->flags;
4628 int flags, distance, i;
4629 int64_t prev_dts = AV_NOPTS_VALUE;
4630 int next_frag_index = -1, index_entry_pos;
4631 size_t requested_size;
4632 size_t old_ctts_allocated_size;
4633 AVIndexEntry *new_entries;
4634 MOVFragmentStreamInfo * frag_stream_info;
4636 for (i = 0; i < c->fc->nb_streams; i++) {
4637 if (c->fc->streams[i]->id == frag->track_id) {
4638 st = c->fc->streams[i];
4643 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4644 return AVERROR_INVALIDDATA;
4647 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
4650 // Find the next frag_index index that has a valid index_entry for
4651 // the current track_id.
4653 // A valid index_entry means the trun for the fragment was read
4654 // and it's samples are in index_entries at the given position.
4655 // New index entries will be inserted before the index_entry found.
4656 index_entry_pos = st->nb_index_entries;
4657 for (i = c->frag_index.current + 1; i < c->frag_index.nb_items; i++) {
4658 frag_stream_info = get_frag_stream_info(&c->frag_index, i, frag->track_id);
4659 if (frag_stream_info && frag_stream_info->index_entry >= 0) {
4660 next_frag_index = i;
4661 index_entry_pos = frag_stream_info->index_entry;
4666 avio_r8(pb); /* version */
4667 flags = avio_rb24(pb);
4668 entries = avio_rb32(pb);
4669 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
4671 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
4672 return AVERROR_INVALIDDATA;
4673 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
4674 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
4676 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4677 if (frag_stream_info)
4679 if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE &&
4680 c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
4681 pts = frag_stream_info->first_tfra_pts;
4682 av_log(c->fc, AV_LOG_DEBUG, "found mfra time %"PRId64
4683 ", using it for pts\n", pts);
4684 } else if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE) {
4685 // FIXME: sidx earliest_presentation_time is *PTS*, s.b.
4686 // pts = frag_stream_info->sidx_pts;
4687 dts = frag_stream_info->sidx_pts - sc->time_offset;
4688 av_log(c->fc, AV_LOG_DEBUG, "found sidx time %"PRId64
4689 ", using it for pts\n", pts);
4690 } else if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE) {
4691 dts = frag_stream_info->tfdt_dts - sc->time_offset;
4692 av_log(c->fc, AV_LOG_DEBUG, "found tfdt time %"PRId64
4693 ", using it for dts\n", dts);
4695 dts = sc->track_end - sc->time_offset;
4696 av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4697 ", using it for dts\n", dts);
4700 dts = sc->track_end - sc->time_offset;
4701 av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4702 ", using it for dts\n", dts);
4704 offset = frag->base_data_offset + data_offset;
4706 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
4708 // realloc space for new index entries
4709 if((unsigned)st->nb_index_entries + entries >= UINT_MAX / sizeof(AVIndexEntry)) {
4710 entries = UINT_MAX / sizeof(AVIndexEntry) - st->nb_index_entries;
4711 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
4716 requested_size = (st->nb_index_entries + entries) * sizeof(AVIndexEntry);
4717 new_entries = av_fast_realloc(st->index_entries,
4718 &st->index_entries_allocated_size,
4721 return AVERROR(ENOMEM);
4722 st->index_entries= new_entries;
4724 requested_size = (st->nb_index_entries + entries) * sizeof(*sc->ctts_data);
4725 old_ctts_allocated_size = sc->ctts_allocated_size;
4726 ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size,
4729 return AVERROR(ENOMEM);
4730 sc->ctts_data = ctts_data;
4732 // In case there were samples without ctts entries, ensure they get
4733 // zero valued entries. This ensures clips which mix boxes with and
4734 // without ctts entries don't pickup uninitialized data.
4735 memset((uint8_t*)(sc->ctts_data) + old_ctts_allocated_size, 0,
4736 sc->ctts_allocated_size - old_ctts_allocated_size);
4738 if (index_entry_pos < st->nb_index_entries) {
4739 // Make hole in index_entries and ctts_data for new samples
4740 memmove(st->index_entries + index_entry_pos + entries,
4741 st->index_entries + index_entry_pos,
4742 sizeof(*st->index_entries) *
4743 (st->nb_index_entries - index_entry_pos));
4744 memmove(sc->ctts_data + index_entry_pos + entries,
4745 sc->ctts_data + index_entry_pos,
4746 sizeof(*sc->ctts_data) * (sc->ctts_count - index_entry_pos));
4747 if (index_entry_pos < sc->current_sample) {
4748 sc->current_sample += entries;
4752 st->nb_index_entries += entries;
4753 sc->ctts_count = st->nb_index_entries;
4755 // Record the index_entry position in frag_index of this fragment
4756 if (frag_stream_info)
4757 frag_stream_info->index_entry = index_entry_pos;
4759 if (index_entry_pos > 0)
4760 prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4762 for (i = 0; i < entries && !pb->eof_reached; i++) {
4763 unsigned sample_size = frag->size;
4764 int sample_flags = i ? frag->flags : first_sample_flags;
4765 unsigned sample_duration = frag->duration;
4766 unsigned ctts_duration = 0;
4768 int index_entry_flags = 0;
4770 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
4771 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
4772 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
4773 if (flags & MOV_TRUN_SAMPLE_CTS) ctts_duration = avio_rb32(pb);
4775 mov_update_dts_shift(sc, ctts_duration);
4776 if (pts != AV_NOPTS_VALUE) {
4777 dts = pts - sc->dts_shift;
4778 if (flags & MOV_TRUN_SAMPLE_CTS) {
4779 dts -= ctts_duration;
4781 dts -= sc->time_offset;
4783 av_log(c->fc, AV_LOG_DEBUG,
4784 "pts %"PRId64" calculated dts %"PRId64
4785 " sc->dts_shift %d ctts.duration %d"
4786 " sc->time_offset %"PRId64
4787 " flags & MOV_TRUN_SAMPLE_CTS %d\n",
4789 sc->dts_shift, ctts_duration,
4790 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
4791 pts = AV_NOPTS_VALUE;
4794 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4798 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
4799 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
4802 index_entry_flags |= AVINDEX_KEYFRAME;
4804 // Fragments can overlap in time. Discard overlapping frames after
4806 if (prev_dts >= dts)
4807 index_entry_flags |= AVINDEX_DISCARD_FRAME;
4809 st->index_entries[index_entry_pos].pos = offset;
4810 st->index_entries[index_entry_pos].timestamp = dts;
4811 st->index_entries[index_entry_pos].size= sample_size;
4812 st->index_entries[index_entry_pos].min_distance= distance;
4813 st->index_entries[index_entry_pos].flags = index_entry_flags;
4815 sc->ctts_data[index_entry_pos].count = 1;
4816 sc->ctts_data[index_entry_pos].duration = ctts_duration;
4819 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
4820 "size %u, distance %d, keyframe %d\n", st->index,
4821 index_entry_pos, offset, dts, sample_size, distance, keyframe);
4823 dts += sample_duration;
4824 offset += sample_size;
4825 sc->data_size += sample_size;
4827 if (sample_duration <= INT64_MAX - sc->duration_for_fps &&
4828 1 <= INT64_MAX - sc->nb_frames_for_fps
4830 sc->duration_for_fps += sample_duration;
4831 sc->nb_frames_for_fps ++;
4835 // EOF found before reading all entries. Fix the hole this would
4836 // leave in index_entries and ctts_data
4837 int gap = entries - i;
4838 memmove(st->index_entries + index_entry_pos,
4839 st->index_entries + index_entry_pos + gap,
4840 sizeof(*st->index_entries) *
4841 (st->nb_index_entries - (index_entry_pos + gap)));
4842 memmove(sc->ctts_data + index_entry_pos,
4843 sc->ctts_data + index_entry_pos + gap,
4844 sizeof(*sc->ctts_data) *
4845 (sc->ctts_count - (index_entry_pos + gap)));
4847 st->nb_index_entries -= gap;
4848 sc->ctts_count -= gap;
4849 if (index_entry_pos < sc->current_sample) {
4850 sc->current_sample -= gap;
4855 // The end of this new fragment may overlap in time with the start
4856 // of the next fragment in index_entries. Mark the samples in the next
4857 // fragment that overlap with AVINDEX_DISCARD_FRAME
4858 prev_dts = AV_NOPTS_VALUE;
4859 if (index_entry_pos > 0)
4860 prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4861 for (i = index_entry_pos; i < st->nb_index_entries; i++) {
4862 if (prev_dts < st->index_entries[i].timestamp)
4864 st->index_entries[i].flags |= AVINDEX_DISCARD_FRAME;
4867 // If a hole was created to insert the new index_entries into,
4868 // the index_entry recorded for all subsequent moof must
4869 // be incremented by the number of entries inserted.
4870 fix_frag_index_entries(&c->frag_index, next_frag_index,
4871 frag->track_id, entries);
4873 if (pb->eof_reached) {
4874 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted TRUN atom\n");
4878 frag->implicit_offset = offset;
4880 sc->track_end = dts + sc->time_offset;
4881 if (st->duration < sc->track_end)
4882 st->duration = sc->track_end;
4887 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4889 int64_t offset = avio_tell(pb) + atom.size, pts, timestamp;
4891 unsigned i, j, track_id, item_count;
4892 AVStream *st = NULL;
4893 AVStream *ref_st = NULL;
4894 MOVStreamContext *sc, *ref_sc = NULL;
4895 AVRational timescale;
4897 version = avio_r8(pb);
4899 avpriv_request_sample(c->fc, "sidx version %u", version);
4903 avio_rb24(pb); // flags
4905 track_id = avio_rb32(pb); // Reference ID
4906 for (i = 0; i < c->fc->nb_streams; i++) {
4907 if (c->fc->streams[i]->id == track_id) {
4908 st = c->fc->streams[i];
4913 av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
4919 timescale = av_make_q(1, avio_rb32(pb));
4921 if (timescale.den <= 0) {
4922 av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
4923 return AVERROR_INVALIDDATA;
4927 pts = avio_rb32(pb);
4928 offset += avio_rb32(pb);
4930 pts = avio_rb64(pb);
4931 offset += avio_rb64(pb);
4934 avio_rb16(pb); // reserved
4936 item_count = avio_rb16(pb);
4938 for (i = 0; i < item_count; i++) {
4940 MOVFragmentStreamInfo * frag_stream_info;
4941 uint32_t size = avio_rb32(pb);
4942 uint32_t duration = avio_rb32(pb);
4943 if (size & 0x80000000) {
4944 avpriv_request_sample(c->fc, "sidx reference_type 1");
4945 return AVERROR_PATCHWELCOME;
4947 avio_rb32(pb); // sap_flags
4948 timestamp = av_rescale_q(pts, st->time_base, timescale);
4950 index = update_frag_index(c, offset);
4951 frag_stream_info = get_frag_stream_info(&c->frag_index, index, track_id);
4952 if (frag_stream_info)
4953 frag_stream_info->sidx_pts = timestamp;
4959 st->duration = sc->track_end = pts;
4963 if (offset == avio_size(pb)) {
4964 // Find first entry in fragment index that came from an sidx.
4965 // This will pretty much always be the first entry.
4966 for (i = 0; i < c->frag_index.nb_items; i++) {
4967 MOVFragmentIndexItem * item = &c->frag_index.item[i];
4968 for (j = 0; ref_st == NULL && j < item->nb_stream_info; j++) {
4969 MOVFragmentStreamInfo * si;
4970 si = &item->stream_info[j];
4971 if (si->sidx_pts != AV_NOPTS_VALUE) {
4972 ref_st = c->fc->streams[j];
4973 ref_sc = ref_st->priv_data;
4978 for (i = 0; i < c->fc->nb_streams; i++) {
4979 st = c->fc->streams[i];
4981 if (!sc->has_sidx) {
4982 st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
4986 c->frag_index.complete = 1;
4992 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
4993 /* like the files created with Adobe Premiere 5.0, for samples see */
4994 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
4995 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5000 return 0; /* continue */
5001 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
5002 avio_skip(pb, atom.size - 4);
5005 atom.type = avio_rl32(pb);
5007 if (atom.type != MKTAG('m','d','a','t')) {
5008 avio_skip(pb, atom.size);
5011 err = mov_read_mdat(c, pb, atom);
5015 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5020 uint8_t *moov_data; /* uncompressed data */
5021 long cmov_len, moov_len;
5024 avio_rb32(pb); /* dcom atom */
5025 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
5026 return AVERROR_INVALIDDATA;
5027 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
5028 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
5029 return AVERROR_INVALIDDATA;
5031 avio_rb32(pb); /* cmvd atom */
5032 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
5033 return AVERROR_INVALIDDATA;
5034 moov_len = avio_rb32(pb); /* uncompressed size */
5035 cmov_len = atom.size - 6 * 4;
5037 cmov_data = av_malloc(cmov_len);
5039 return AVERROR(ENOMEM);
5040 moov_data = av_malloc(moov_len);
5043 return AVERROR(ENOMEM);
5045 ret = ffio_read_size(pb, cmov_data, cmov_len);
5047 goto free_and_return;
5049 ret = AVERROR_INVALIDDATA;
5050 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
5051 goto free_and_return;
5052 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
5053 goto free_and_return;
5054 ctx.seekable = AVIO_SEEKABLE_NORMAL;
5055 atom.type = MKTAG('m','o','o','v');
5056 atom.size = moov_len;
5057 ret = mov_read_default(c, &ctx, atom);
5063 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
5064 return AVERROR(ENOSYS);
5068 /* edit list atom */
5069 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5071 MOVStreamContext *sc;
5072 int i, edit_count, version;
5073 int64_t elst_entry_size;
5075 if (c->fc->nb_streams < 1 || c->ignore_editlist)
5077 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
5079 version = avio_r8(pb); /* version */
5080 avio_rb24(pb); /* flags */
5081 edit_count = avio_rb32(pb); /* entries */
5084 elst_entry_size = version == 1 ? 20 : 12;
5085 if (atom.size != edit_count * elst_entry_size) {
5086 if (c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
5087 av_log(c->fc, AV_LOG_ERROR, "Invalid edit list entry_count: %d for elst atom of size: %"PRId64" bytes.\n",
5088 edit_count, atom.size + 8);
5089 return AVERROR_INVALIDDATA;
5091 edit_count = atom.size / elst_entry_size;
5092 if (edit_count * elst_entry_size != atom.size) {
5093 av_log(c->fc, AV_LOG_WARNING, "ELST atom of %"PRId64" bytes, bigger than %d entries.", atom.size, edit_count);
5101 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
5102 av_free(sc->elst_data);
5104 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
5106 return AVERROR(ENOMEM);
5108 av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
5109 for (i = 0; i < edit_count && atom.size > 0 && !pb->eof_reached; i++) {
5110 MOVElst *e = &sc->elst_data[i];
5113 e->duration = avio_rb64(pb);
5114 e->time = avio_rb64(pb);
5117 e->duration = avio_rb32(pb); /* segment duration */
5118 e->time = (int32_t)avio_rb32(pb); /* media time */
5121 e->rate = avio_rb32(pb) / 65536.0;
5123 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
5124 e->duration, e->time, e->rate);
5126 if (e->time < 0 && e->time != -1 &&
5127 c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
5128 av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
5129 c->fc->nb_streams-1, i, e->time);
5130 return AVERROR_INVALIDDATA;
5138 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5140 MOVStreamContext *sc;
5142 if (c->fc->nb_streams < 1)
5143 return AVERROR_INVALIDDATA;
5144 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5145 sc->timecode_track = avio_rb32(pb);
5149 static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5152 int version, color_range, color_primaries, color_trc, color_space;
5154 if (c->fc->nb_streams < 1)
5156 st = c->fc->streams[c->fc->nb_streams - 1];
5158 if (atom.size < 5) {
5159 av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
5160 return AVERROR_INVALIDDATA;
5163 version = avio_r8(pb);
5165 av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
5168 avio_skip(pb, 3); /* flags */
5170 avio_skip(pb, 2); /* profile + level */
5171 color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
5172 color_primaries = avio_r8(pb);
5173 color_trc = avio_r8(pb);
5174 color_space = avio_r8(pb);
5175 if (avio_rb16(pb)) /* codecIntializationDataSize */
5176 return AVERROR_INVALIDDATA;
5178 if (!av_color_primaries_name(color_primaries))
5179 color_primaries = AVCOL_PRI_UNSPECIFIED;
5180 if (!av_color_transfer_name(color_trc))
5181 color_trc = AVCOL_TRC_UNSPECIFIED;
5182 if (!av_color_space_name(color_space))
5183 color_space = AVCOL_SPC_UNSPECIFIED;
5185 st->codecpar->color_range = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
5186 st->codecpar->color_primaries = color_primaries;
5187 st->codecpar->color_trc = color_trc;
5188 st->codecpar->color_space = color_space;
5193 static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5195 MOVStreamContext *sc;
5196 const int chroma_den = 50000;
5197 const int luma_den = 10000;
5200 if (c->fc->nb_streams < 1)
5201 return AVERROR_INVALIDDATA;
5203 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5205 if (atom.size < 5) {
5206 av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
5207 return AVERROR_INVALIDDATA;
5210 version = avio_r8(pb);
5212 av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
5215 avio_skip(pb, 3); /* flags */
5217 sc->mastering = av_mastering_display_metadata_alloc();
5219 return AVERROR(ENOMEM);
5221 for (i = 0; i < 3; i++)
5222 for (j = 0; j < 2; j++)
5223 sc->mastering->display_primaries[i][j] =
5224 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5225 for (i = 0; i < 2; i++)
5226 sc->mastering->white_point[i] =
5227 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5228 sc->mastering->max_luminance =
5229 av_make_q(lrint(((double)avio_rb32(pb) / (1 << 8)) * luma_den), luma_den);
5230 sc->mastering->min_luminance =
5231 av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den);
5233 sc->mastering->has_primaries = 1;
5234 sc->mastering->has_luminance = 1;
5239 static int mov_read_mdcv(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5241 MOVStreamContext *sc;
5242 const int mapping[3] = {1, 2, 0};
5243 const int chroma_den = 50000;
5244 const int luma_den = 10000;
5247 if (c->fc->nb_streams < 1)
5248 return AVERROR_INVALIDDATA;
5250 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5252 if (atom.size < 24) {
5253 av_log(c->fc, AV_LOG_ERROR, "Invalid Mastering Display Color Volume box\n");
5254 return AVERROR_INVALIDDATA;
5257 sc->mastering = av_mastering_display_metadata_alloc();
5259 return AVERROR(ENOMEM);
5261 for (i = 0; i < 3; i++) {
5262 const int j = mapping[i];
5263 sc->mastering->display_primaries[j][0] = av_make_q(avio_rb16(pb), chroma_den);
5264 sc->mastering->display_primaries[j][1] = av_make_q(avio_rb16(pb), chroma_den);
5266 sc->mastering->white_point[0] = av_make_q(avio_rb16(pb), chroma_den);
5267 sc->mastering->white_point[1] = av_make_q(avio_rb16(pb), chroma_den);
5269 sc->mastering->max_luminance = av_make_q(avio_rb32(pb), luma_den);
5270 sc->mastering->min_luminance = av_make_q(avio_rb32(pb), luma_den);
5272 sc->mastering->has_luminance = 1;
5273 sc->mastering->has_primaries = 1;
5278 static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5280 MOVStreamContext *sc;
5283 if (c->fc->nb_streams < 1)
5284 return AVERROR_INVALIDDATA;
5286 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5288 if (atom.size < 5) {
5289 av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
5290 return AVERROR_INVALIDDATA;
5293 version = avio_r8(pb);
5295 av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
5298 avio_skip(pb, 3); /* flags */
5300 sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
5302 return AVERROR(ENOMEM);
5304 sc->coll->MaxCLL = avio_rb16(pb);
5305 sc->coll->MaxFALL = avio_rb16(pb);
5310 static int mov_read_clli(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5312 MOVStreamContext *sc;
5314 if (c->fc->nb_streams < 1)
5315 return AVERROR_INVALIDDATA;
5317 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5319 if (atom.size < 4) {
5320 av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level Info box\n");
5321 return AVERROR_INVALIDDATA;
5324 sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
5326 return AVERROR(ENOMEM);
5328 sc->coll->MaxCLL = avio_rb16(pb);
5329 sc->coll->MaxFALL = avio_rb16(pb);
5334 static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5337 MOVStreamContext *sc;
5338 enum AVStereo3DType type;
5341 if (c->fc->nb_streams < 1)
5344 st = c->fc->streams[c->fc->nb_streams - 1];
5347 if (atom.size < 5) {
5348 av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
5349 return AVERROR_INVALIDDATA;
5351 avio_skip(pb, 4); /* version + flags */
5356 type = AV_STEREO3D_2D;
5359 type = AV_STEREO3D_TOPBOTTOM;
5362 type = AV_STEREO3D_SIDEBYSIDE;
5365 av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
5369 sc->stereo3d = av_stereo3d_alloc();
5371 return AVERROR(ENOMEM);
5373 sc->stereo3d->type = type;
5377 static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5380 MOVStreamContext *sc;
5381 int size, version, layout;
5382 int32_t yaw, pitch, roll;
5383 uint32_t l = 0, t = 0, r = 0, b = 0;
5384 uint32_t tag, padding = 0;
5385 enum AVSphericalProjection projection;
5387 if (c->fc->nb_streams < 1)
5390 st = c->fc->streams[c->fc->nb_streams - 1];
5393 if (atom.size < 8) {
5394 av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
5395 return AVERROR_INVALIDDATA;
5398 size = avio_rb32(pb);
5399 if (size <= 12 || size > atom.size)
5400 return AVERROR_INVALIDDATA;
5402 tag = avio_rl32(pb);
5403 if (tag != MKTAG('s','v','h','d')) {
5404 av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
5407 version = avio_r8(pb);
5409 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5413 avio_skip(pb, 3); /* flags */
5414 avio_skip(pb, size - 12); /* metadata_source */
5416 size = avio_rb32(pb);
5417 if (size > atom.size)
5418 return AVERROR_INVALIDDATA;
5420 tag = avio_rl32(pb);
5421 if (tag != MKTAG('p','r','o','j')) {
5422 av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
5426 size = avio_rb32(pb);
5427 if (size > atom.size)
5428 return AVERROR_INVALIDDATA;
5430 tag = avio_rl32(pb);
5431 if (tag != MKTAG('p','r','h','d')) {
5432 av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
5435 version = avio_r8(pb);
5437 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5441 avio_skip(pb, 3); /* flags */
5443 /* 16.16 fixed point */
5444 yaw = avio_rb32(pb);
5445 pitch = avio_rb32(pb);
5446 roll = avio_rb32(pb);
5448 size = avio_rb32(pb);
5449 if (size > atom.size)
5450 return AVERROR_INVALIDDATA;
5452 tag = avio_rl32(pb);
5453 version = avio_r8(pb);
5455 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5459 avio_skip(pb, 3); /* flags */
5461 case MKTAG('c','b','m','p'):
5462 layout = avio_rb32(pb);
5464 av_log(c->fc, AV_LOG_WARNING,
5465 "Unsupported cubemap layout %d\n", layout);
5468 projection = AV_SPHERICAL_CUBEMAP;
5469 padding = avio_rb32(pb);
5471 case MKTAG('e','q','u','i'):
5477 if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
5478 av_log(c->fc, AV_LOG_ERROR,
5479 "Invalid bounding rectangle coordinates "
5480 "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
5481 return AVERROR_INVALIDDATA;
5484 if (l || t || r || b)
5485 projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
5487 projection = AV_SPHERICAL_EQUIRECTANGULAR;
5490 av_log(c->fc, AV_LOG_ERROR, "Unknown projection type: %s\n", av_fourcc2str(tag));
5494 sc->spherical = av_spherical_alloc(&sc->spherical_size);
5496 return AVERROR(ENOMEM);
5498 sc->spherical->projection = projection;
5500 sc->spherical->yaw = yaw;
5501 sc->spherical->pitch = pitch;
5502 sc->spherical->roll = roll;
5504 sc->spherical->padding = padding;
5506 sc->spherical->bound_left = l;
5507 sc->spherical->bound_top = t;
5508 sc->spherical->bound_right = r;
5509 sc->spherical->bound_bottom = b;
5514 static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
5517 uint8_t *buffer = av_malloc(len + 1);
5521 return AVERROR(ENOMEM);
5524 ret = ffio_read_size(pb, buffer, len);
5528 /* Check for mandatory keys and values, try to support XML as best-effort */
5529 if (!sc->spherical &&
5530 av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
5531 (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
5532 av_stristr(val, "true") &&
5533 (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
5534 av_stristr(val, "true") &&
5535 (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
5536 av_stristr(val, "equirectangular")) {
5537 sc->spherical = av_spherical_alloc(&sc->spherical_size);
5541 sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
5543 if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
5544 enum AVStereo3DType mode;
5546 if (av_stristr(buffer, "left-right"))
5547 mode = AV_STEREO3D_SIDEBYSIDE;
5548 else if (av_stristr(buffer, "top-bottom"))
5549 mode = AV_STEREO3D_TOPBOTTOM;
5551 mode = AV_STEREO3D_2D;
5553 sc->stereo3d = av_stereo3d_alloc();
5557 sc->stereo3d->type = mode;
5561 val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
5563 sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
5564 val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
5566 sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
5567 val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
5569 sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
5577 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5580 MOVStreamContext *sc;
5583 static const uint8_t uuid_isml_manifest[] = {
5584 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
5585 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
5587 static const uint8_t uuid_xmp[] = {
5588 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
5589 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
5591 static const uint8_t uuid_spherical[] = {
5592 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
5593 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
5596 if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
5597 return AVERROR_INVALIDDATA;
5599 if (c->fc->nb_streams < 1)
5601 st = c->fc->streams[c->fc->nb_streams - 1];
5604 ret = avio_read(pb, uuid, sizeof(uuid));
5607 } else if (ret != sizeof(uuid)) {
5608 return AVERROR_INVALIDDATA;
5610 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
5611 uint8_t *buffer, *ptr;
5613 size_t len = atom.size - sizeof(uuid);
5616 return AVERROR_INVALIDDATA;
5618 ret = avio_skip(pb, 4); // zeroes
5621 buffer = av_mallocz(len + 1);
5623 return AVERROR(ENOMEM);
5625 ret = avio_read(pb, buffer, len);
5629 } else if (ret != len) {
5631 return AVERROR_INVALIDDATA;
5635 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
5636 ptr += sizeof("systemBitrate=\"") - 1;
5637 c->bitrates_count++;
5638 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
5640 c->bitrates_count = 0;
5642 return AVERROR(ENOMEM);
5645 ret = strtol(ptr, &endptr, 10);
5646 if (ret < 0 || errno || *endptr != '"') {
5647 c->bitrates[c->bitrates_count - 1] = 0;
5649 c->bitrates[c->bitrates_count - 1] = ret;
5654 } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
5656 size_t len = atom.size - sizeof(uuid);
5657 if (c->export_xmp) {
5658 buffer = av_mallocz(len + 1);
5660 return AVERROR(ENOMEM);
5662 ret = avio_read(pb, buffer, len);
5666 } else if (ret != len) {
5668 return AVERROR_INVALIDDATA;
5671 av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
5674 // skip all uuid atom, which makes it fast for long uuid-xmp file
5675 ret = avio_skip(pb, len);
5679 } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
5680 size_t len = atom.size - sizeof(uuid);
5681 ret = mov_parse_uuid_spherical(sc, pb, len);
5685 av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
5691 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5694 uint8_t content[16];
5699 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
5705 && !memcmp(content, "Anevia\x1A\x1A", 8)
5706 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
5707 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
5713 static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5715 uint32_t format = avio_rl32(pb);
5716 MOVStreamContext *sc;
5720 if (c->fc->nb_streams < 1)
5722 st = c->fc->streams[c->fc->nb_streams - 1];
5727 case MKTAG('e','n','c','v'): // encrypted video
5728 case MKTAG('e','n','c','a'): // encrypted audio
5729 id = mov_codec_id(st, format);
5730 if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
5731 st->codecpar->codec_id != id) {
5732 av_log(c->fc, AV_LOG_WARNING,
5733 "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
5734 (char*)&format, st->codecpar->codec_id);
5738 st->codecpar->codec_id = id;
5739 sc->format = format;
5743 if (format != sc->format) {
5744 av_log(c->fc, AV_LOG_WARNING,
5745 "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
5746 (char*)&format, (char*)&sc->format);
5754 static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5757 MOVStreamContext *sc;
5758 size_t auxiliary_info_size;
5760 if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5763 st = c->fc->streams[c->fc->nb_streams - 1];
5766 if (sc->cenc.aes_ctr) {
5767 av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
5768 return AVERROR_INVALIDDATA;
5771 avio_r8(pb); /* version */
5772 sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
5774 avio_rb32(pb); /* entries */
5776 if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5777 av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size);
5778 return AVERROR_INVALIDDATA;
5781 /* save the auxiliary info as is */
5782 auxiliary_info_size = atom.size - 8;
5784 sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
5785 if (!sc->cenc.auxiliary_info) {
5786 return AVERROR(ENOMEM);
5789 sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
5790 sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
5791 sc->cenc.auxiliary_info_index = 0;
5793 if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
5794 av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
5795 return AVERROR_INVALIDDATA;
5798 /* initialize the cipher */
5799 sc->cenc.aes_ctr = av_aes_ctr_alloc();
5800 if (!sc->cenc.aes_ctr) {
5801 return AVERROR(ENOMEM);
5804 return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
5807 static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5810 MOVStreamContext *sc;
5812 int atom_header_size;
5815 if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5818 st = c->fc->streams[c->fc->nb_streams - 1];
5821 if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
5822 av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
5823 return AVERROR_INVALIDDATA;
5826 atom_header_size = 9;
5828 avio_r8(pb); /* version */
5829 flags = avio_rb24(pb);
5831 if ((flags & 0x01) != 0) {
5832 atom_header_size += 8;
5834 avio_rb32(pb); /* info type */
5835 avio_rb32(pb); /* info type param */
5838 sc->cenc.auxiliary_info_default_size = avio_r8(pb);
5839 avio_rb32(pb); /* entries */
5841 if (atom.size <= atom_header_size) {
5845 if (atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5846 av_log(c->fc, AV_LOG_ERROR, "saiz atom auxiliary_info_sizes size %"PRId64" invalid\n", atom.size);
5847 return AVERROR_INVALIDDATA;
5850 /* save the auxiliary info sizes as is */
5851 data_size = atom.size - atom_header_size;
5853 sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
5854 if (!sc->cenc.auxiliary_info_sizes) {
5855 return AVERROR(ENOMEM);
5858 sc->cenc.auxiliary_info_sizes_count = data_size;
5860 if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
5861 av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
5862 return AVERROR_INVALIDDATA;
5868 static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5871 int last, type, size, ret;
5874 if (c->fc->nb_streams < 1)
5876 st = c->fc->streams[c->fc->nb_streams-1];
5878 if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
5879 return AVERROR_INVALIDDATA;
5881 /* Check FlacSpecificBox version. */
5882 if (avio_r8(pb) != 0)
5883 return AVERROR_INVALIDDATA;
5885 avio_rb24(pb); /* Flags */
5887 avio_read(pb, buf, sizeof(buf));
5888 flac_parse_block_header(buf, &last, &type, &size);
5890 if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
5891 av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
5892 return AVERROR_INVALIDDATA;
5895 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
5900 av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
5905 static int mov_seek_auxiliary_info(MOVContext *c, MOVStreamContext *sc, int64_t index)
5907 size_t auxiliary_info_seek_offset = 0;
5910 if (sc->cenc.auxiliary_info_default_size) {
5911 auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * index;
5912 } else if (sc->cenc.auxiliary_info_sizes) {
5913 if (index > sc->cenc.auxiliary_info_sizes_count) {
5914 av_log(c, AV_LOG_ERROR, "current sample %"PRId64" greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
5915 index, sc->cenc.auxiliary_info_sizes_count);
5916 return AVERROR_INVALIDDATA;
5919 for (i = 0; i < index; i++) {
5920 auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
5924 if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
5925 av_log(c, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
5926 auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
5927 return AVERROR_INVALIDDATA;
5930 sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
5931 sc->cenc.auxiliary_info_index = index;
5935 static int cenc_filter(MOVContext *c, MOVStreamContext *sc, int64_t index, uint8_t *input, int size)
5937 uint32_t encrypted_bytes;
5938 uint16_t subsample_count;
5939 uint16_t clear_bytes;
5940 uint8_t* input_end = input + size;
5943 if (index != sc->cenc.auxiliary_info_index) {
5944 ret = mov_seek_auxiliary_info(c, sc, index);
5951 if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5952 av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
5953 return AVERROR_INVALIDDATA;
5956 av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
5957 sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
5959 if (!sc->cenc.use_subsamples)
5961 /* decrypt the whole packet */
5962 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
5966 /* read the subsample count */
5967 if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5968 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
5969 return AVERROR_INVALIDDATA;
5972 subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
5973 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5975 for (; subsample_count > 0; subsample_count--)
5977 if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5978 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
5979 return AVERROR_INVALIDDATA;
5982 /* read the number of clear / encrypted bytes */
5983 clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
5984 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5985 encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
5986 sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
5988 if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
5989 av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
5990 return AVERROR_INVALIDDATA;
5993 /* skip the clear bytes */
5994 input += clear_bytes;
5996 /* decrypt the encrypted bytes */
5997 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
5998 input += encrypted_bytes;
6001 if (input < input_end) {
6002 av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
6003 return AVERROR_INVALIDDATA;
6006 sc->cenc.auxiliary_info_index++;
6010 static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6012 const int OPUS_SEEK_PREROLL_MS = 80;
6017 if (c->fc->nb_streams < 1)
6019 st = c->fc->streams[c->fc->nb_streams-1];
6021 if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
6022 return AVERROR_INVALIDDATA;
6024 /* Check OpusSpecificBox version. */
6025 if (avio_r8(pb) != 0) {
6026 av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
6027 return AVERROR_INVALIDDATA;
6030 /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
6031 size = atom.size + 8;
6033 if (ff_alloc_extradata(st->codecpar, size))
6034 return AVERROR(ENOMEM);
6036 AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
6037 AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
6038 AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
6039 avio_read(pb, st->codecpar->extradata + 9, size - 9);
6041 /* OpusSpecificBox is stored in big-endian, but OpusHead is
6042 little-endian; aside from the preceeding magic and version they're
6043 otherwise currently identical. Data after output gain at offset 16
6044 doesn't need to be bytewapped. */
6045 pre_skip = AV_RB16(st->codecpar->extradata + 10);
6046 AV_WL16(st->codecpar->extradata + 10, pre_skip);
6047 AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
6048 AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
6050 st->codecpar->initial_padding = pre_skip;
6051 st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
6052 (AVRational){1, 1000},
6053 (AVRational){1, 48000});
6058 static const MOVParseTableEntry mov_default_parse_table[] = {
6059 { MKTAG('A','C','L','R'), mov_read_aclr },
6060 { MKTAG('A','P','R','G'), mov_read_avid },
6061 { MKTAG('A','A','L','P'), mov_read_avid },
6062 { MKTAG('A','R','E','S'), mov_read_ares },
6063 { MKTAG('a','v','s','s'), mov_read_avss },
6064 { MKTAG('c','h','p','l'), mov_read_chpl },
6065 { MKTAG('c','o','6','4'), mov_read_stco },
6066 { MKTAG('c','o','l','r'), mov_read_colr },
6067 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
6068 { MKTAG('d','i','n','f'), mov_read_default },
6069 { MKTAG('D','p','x','E'), mov_read_dpxe },
6070 { MKTAG('d','r','e','f'), mov_read_dref },
6071 { MKTAG('e','d','t','s'), mov_read_default },
6072 { MKTAG('e','l','s','t'), mov_read_elst },
6073 { MKTAG('e','n','d','a'), mov_read_enda },
6074 { MKTAG('f','i','e','l'), mov_read_fiel },
6075 { MKTAG('a','d','r','m'), mov_read_adrm },
6076 { MKTAG('f','t','y','p'), mov_read_ftyp },
6077 { MKTAG('g','l','b','l'), mov_read_glbl },
6078 { MKTAG('h','d','l','r'), mov_read_hdlr },
6079 { MKTAG('i','l','s','t'), mov_read_ilst },
6080 { MKTAG('j','p','2','h'), mov_read_jp2h },
6081 { MKTAG('m','d','a','t'), mov_read_mdat },
6082 { MKTAG('m','d','h','d'), mov_read_mdhd },
6083 { MKTAG('m','d','i','a'), mov_read_default },
6084 { MKTAG('m','e','t','a'), mov_read_meta },
6085 { MKTAG('m','i','n','f'), mov_read_default },
6086 { MKTAG('m','o','o','f'), mov_read_moof },
6087 { MKTAG('m','o','o','v'), mov_read_moov },
6088 { MKTAG('m','v','e','x'), mov_read_default },
6089 { MKTAG('m','v','h','d'), mov_read_mvhd },
6090 { MKTAG('S','M','I',' '), mov_read_svq3 },
6091 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
6092 { MKTAG('a','v','c','C'), mov_read_glbl },
6093 { MKTAG('p','a','s','p'), mov_read_pasp },
6094 { MKTAG('s','i','d','x'), mov_read_sidx },
6095 { MKTAG('s','t','b','l'), mov_read_default },
6096 { MKTAG('s','t','c','o'), mov_read_stco },
6097 { MKTAG('s','t','p','s'), mov_read_stps },
6098 { MKTAG('s','t','r','f'), mov_read_strf },
6099 { MKTAG('s','t','s','c'), mov_read_stsc },
6100 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
6101 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
6102 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
6103 { MKTAG('s','t','t','s'), mov_read_stts },
6104 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
6105 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
6106 { MKTAG('t','f','d','t'), mov_read_tfdt },
6107 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
6108 { MKTAG('t','r','a','k'), mov_read_trak },
6109 { MKTAG('t','r','a','f'), mov_read_default },
6110 { MKTAG('t','r','e','f'), mov_read_default },
6111 { MKTAG('t','m','c','d'), mov_read_tmcd },
6112 { MKTAG('c','h','a','p'), mov_read_chap },
6113 { MKTAG('t','r','e','x'), mov_read_trex },
6114 { MKTAG('t','r','u','n'), mov_read_trun },
6115 { MKTAG('u','d','t','a'), mov_read_default },
6116 { MKTAG('w','a','v','e'), mov_read_wave },
6117 { MKTAG('e','s','d','s'), mov_read_esds },
6118 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
6119 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
6120 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
6121 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
6122 { MKTAG('w','f','e','x'), mov_read_wfex },
6123 { MKTAG('c','m','o','v'), mov_read_cmov },
6124 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
6125 { MKTAG('d','v','c','1'), mov_read_dvc1 },
6126 { MKTAG('s','b','g','p'), mov_read_sbgp },
6127 { MKTAG('h','v','c','C'), mov_read_glbl },
6128 { MKTAG('u','u','i','d'), mov_read_uuid },
6129 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
6130 { MKTAG('f','r','e','e'), mov_read_free },
6131 { MKTAG('-','-','-','-'), mov_read_custom },
6132 { MKTAG('s','i','n','f'), mov_read_default },
6133 { MKTAG('f','r','m','a'), mov_read_frma },
6134 { MKTAG('s','e','n','c'), mov_read_senc },
6135 { MKTAG('s','a','i','z'), mov_read_saiz },
6136 { MKTAG('d','f','L','a'), mov_read_dfla },
6137 { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
6138 { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
6139 { MKTAG('d','O','p','s'), mov_read_dops },
6140 { MKTAG('S','m','D','m'), mov_read_smdm },
6141 { MKTAG('C','o','L','L'), mov_read_coll },
6142 { MKTAG('v','p','c','C'), mov_read_vpcc },
6143 { MKTAG('m','d','c','v'), mov_read_mdcv },
6144 { MKTAG('c','l','l','i'), mov_read_clli },
6148 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6150 int64_t total_size = 0;
6154 if (c->atom_depth > 10) {
6155 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
6156 return AVERROR_INVALIDDATA;
6161 atom.size = INT64_MAX;
6162 while (total_size <= atom.size - 8 && !avio_feof(pb)) {
6163 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
6166 if (atom.size >= 8) {
6167 a.size = avio_rb32(pb);
6168 a.type = avio_rl32(pb);
6169 if (a.type == MKTAG('f','r','e','e') &&
6171 c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
6174 uint32_t *type = (uint32_t *)buf + 1;
6175 if (avio_read(pb, buf, 8) != 8)
6176 return AVERROR_INVALIDDATA;
6177 avio_seek(pb, -8, SEEK_CUR);
6178 if (*type == MKTAG('m','v','h','d') ||
6179 *type == MKTAG('c','m','o','v')) {
6180 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
6181 a.type = MKTAG('m','o','o','v');
6184 if (atom.type != MKTAG('r','o','o','t') &&
6185 atom.type != MKTAG('m','o','o','v'))
6187 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
6189 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
6196 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
6197 a.size = avio_rb64(pb) - 8;
6201 av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
6202 av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
6204 a.size = atom.size - total_size + 8;
6209 a.size = FFMIN(a.size, atom.size - total_size);
6211 for (i = 0; mov_default_parse_table[i].type; i++)
6212 if (mov_default_parse_table[i].type == a.type) {
6213 parse = mov_default_parse_table[i].parse;
6217 // container is user data
6218 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
6219 atom.type == MKTAG('i','l','s','t')))
6220 parse = mov_read_udta_string;
6222 // Supports parsing the QuickTime Metadata Keys.
6223 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
6224 if (!parse && c->found_hdlr_mdta &&
6225 atom.type == MKTAG('m','e','t','a') &&
6226 a.type == MKTAG('k','e','y','s')) {
6227 parse = mov_read_keys;
6230 if (!parse) { /* skip leaf atoms data */
6231 avio_skip(pb, a.size);
6233 int64_t start_pos = avio_tell(pb);
6235 int err = parse(c, pb, a);
6240 if (c->found_moov && c->found_mdat &&
6241 ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete) ||
6242 start_pos + a.size == avio_size(pb))) {
6243 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete)
6244 c->next_root_atom = start_pos + a.size;
6248 left = a.size - avio_tell(pb) + start_pos;
6249 if (left > 0) /* skip garbage at atom end */
6250 avio_skip(pb, left);
6251 else if (left < 0) {
6252 av_log(c->fc, AV_LOG_WARNING,
6253 "overread end of atom '%.4s' by %"PRId64" bytes\n",
6254 (char*)&a.type, -left);
6255 avio_seek(pb, left, SEEK_CUR);
6259 total_size += a.size;
6262 if (total_size < atom.size && atom.size < 0x7ffff)
6263 avio_skip(pb, atom.size - total_size);
6269 static int mov_probe(AVProbeData *p)
6274 int moov_offset = -1;
6276 /* check file header */
6279 /* ignore invalid offset */
6280 if ((offset + 8) > (unsigned int)p->buf_size)
6282 tag = AV_RL32(p->buf + offset + 4);
6284 /* check for obvious tags */
6285 case MKTAG('m','o','o','v'):
6286 moov_offset = offset + 4;
6287 case MKTAG('m','d','a','t'):
6288 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
6289 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
6290 case MKTAG('f','t','y','p'):
6291 if (AV_RB32(p->buf+offset) < 8 &&
6292 (AV_RB32(p->buf+offset) != 1 ||
6293 offset + 12 > (unsigned int)p->buf_size ||
6294 AV_RB64(p->buf+offset + 8) == 0)) {
6295 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6296 } else if (tag == MKTAG('f','t','y','p') &&
6297 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
6298 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
6300 score = FFMAX(score, 5);
6302 score = AVPROBE_SCORE_MAX;
6304 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6306 /* those are more common words, so rate then a bit less */
6307 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
6308 case MKTAG('w','i','d','e'):
6309 case MKTAG('f','r','e','e'):
6310 case MKTAG('j','u','n','k'):
6311 case MKTAG('p','i','c','t'):
6312 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
6313 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6315 case MKTAG(0x82,0x82,0x7f,0x7d):
6316 case MKTAG('s','k','i','p'):
6317 case MKTAG('u','u','i','d'):
6318 case MKTAG('p','r','f','l'):
6319 /* if we only find those cause probedata is too small at least rate them */
6320 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6321 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6324 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6327 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
6328 /* moov atom in the header - we should make sure that this is not a
6329 * MOV-packed MPEG-PS */
6330 offset = moov_offset;
6332 while(offset < (p->buf_size - 16)){ /* Sufficient space */
6333 /* We found an actual hdlr atom */
6334 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
6335 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
6336 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
6337 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
6338 /* We found a media handler reference atom describing an
6339 * MPEG-PS-in-MOV, return a
6340 * low score to force expanding the probe window until
6341 * mpegps_probe finds what it needs */
6352 // must be done after parsing all trak because there's no order requirement
6353 static void mov_read_chapters(AVFormatContext *s)
6355 MOVContext *mov = s->priv_data;
6357 MOVStreamContext *sc;
6362 for (j = 0; j < mov->nb_chapter_tracks; j++) {
6363 chapter_track = mov->chapter_tracks[j];
6365 for (i = 0; i < s->nb_streams; i++)
6366 if (s->streams[i]->id == chapter_track) {
6371 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
6376 cur_pos = avio_tell(sc->pb);
6378 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6379 st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
6380 if (st->nb_index_entries) {
6381 // Retrieve the first frame, if possible
6383 AVIndexEntry *sample = &st->index_entries[0];
6384 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6385 av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
6389 if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
6392 st->attached_pic = pkt;
6393 st->attached_pic.stream_index = st->index;
6394 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
6397 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
6398 st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
6399 st->discard = AVDISCARD_ALL;
6400 for (i = 0; i < st->nb_index_entries; i++) {
6401 AVIndexEntry *sample = &st->index_entries[i];
6402 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
6407 if (end < sample->timestamp) {
6408 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
6409 end = AV_NOPTS_VALUE;
6412 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6413 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
6417 // the first two bytes are the length of the title
6418 len = avio_rb16(sc->pb);
6419 if (len > sample->size-2)
6421 title_len = 2*len + 1;
6422 if (!(title = av_mallocz(title_len)))
6425 // The samples could theoretically be in any encoding if there's an encd
6426 // atom following, but in practice are only utf-8 or utf-16, distinguished
6427 // instead by the presence of a BOM
6431 ch = avio_rb16(sc->pb);
6433 avio_get_str16be(sc->pb, len, title, title_len);
6434 else if (ch == 0xfffe)
6435 avio_get_str16le(sc->pb, len, title, title_len);
6438 if (len == 1 || len == 2)
6441 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
6445 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
6450 avio_seek(sc->pb, cur_pos, SEEK_SET);
6454 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
6455 uint32_t value, int flags)
6458 char buf[AV_TIMECODE_STR_SIZE];
6459 AVRational rate = st->avg_frame_rate;
6460 int ret = av_timecode_init(&tc, rate, flags, 0, s);
6463 av_dict_set(&st->metadata, "timecode",
6464 av_timecode_make_string(&tc, buf, value), 0);
6468 static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
6470 MOVStreamContext *sc = st->priv_data;
6471 char buf[AV_TIMECODE_STR_SIZE];
6472 int64_t cur_pos = avio_tell(sc->pb);
6473 int hh, mm, ss, ff, drop;
6475 if (!st->nb_index_entries)
6478 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6479 avio_skip(s->pb, 13);
6480 hh = avio_r8(s->pb);
6481 mm = avio_r8(s->pb);
6482 ss = avio_r8(s->pb);
6483 drop = avio_r8(s->pb);
6484 ff = avio_r8(s->pb);
6485 snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
6486 hh, mm, ss, drop ? ';' : ':', ff);
6487 av_dict_set(&st->metadata, "timecode", buf, 0);
6489 avio_seek(sc->pb, cur_pos, SEEK_SET);
6493 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
6495 MOVStreamContext *sc = st->priv_data;
6497 int64_t cur_pos = avio_tell(sc->pb);
6500 if (!st->nb_index_entries)
6503 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6504 value = avio_rb32(s->pb);
6506 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
6507 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
6508 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
6510 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
6511 * not the case) and thus assume "frame number format" instead of QT one.
6512 * No sample with tmcd track can be found with a QT timecode at the moment,
6513 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
6515 parse_timecode_in_framenum_format(s, st, value, flags);
6517 avio_seek(sc->pb, cur_pos, SEEK_SET);
6521 static int mov_read_close(AVFormatContext *s)
6523 MOVContext *mov = s->priv_data;
6526 for (i = 0; i < s->nb_streams; i++) {
6527 AVStream *st = s->streams[i];
6528 MOVStreamContext *sc = st->priv_data;
6533 av_freep(&sc->ctts_data);
6534 for (j = 0; j < sc->drefs_count; j++) {
6535 av_freep(&sc->drefs[j].path);
6536 av_freep(&sc->drefs[j].dir);
6538 av_freep(&sc->drefs);
6540 sc->drefs_count = 0;
6542 if (!sc->pb_is_copied)
6543 ff_format_io_close(s, &sc->pb);
6546 av_freep(&sc->chunk_offsets);
6547 av_freep(&sc->stsc_data);
6548 av_freep(&sc->sample_sizes);
6549 av_freep(&sc->keyframes);
6550 av_freep(&sc->stts_data);
6551 av_freep(&sc->stps_data);
6552 av_freep(&sc->elst_data);
6553 av_freep(&sc->rap_group);
6554 av_freep(&sc->display_matrix);
6555 av_freep(&sc->index_ranges);
6558 for (j = 0; j < sc->stsd_count; j++)
6559 av_free(sc->extradata[j]);
6560 av_freep(&sc->extradata);
6561 av_freep(&sc->extradata_size);
6563 av_freep(&sc->cenc.auxiliary_info);
6564 av_freep(&sc->cenc.auxiliary_info_sizes);
6565 av_aes_ctr_free(sc->cenc.aes_ctr);
6567 av_freep(&sc->stereo3d);
6568 av_freep(&sc->spherical);
6569 av_freep(&sc->mastering);
6570 av_freep(&sc->coll);
6573 if (mov->dv_demux) {
6574 avformat_free_context(mov->dv_fctx);
6575 mov->dv_fctx = NULL;
6578 if (mov->meta_keys) {
6579 for (i = 1; i < mov->meta_keys_count; i++) {
6580 av_freep(&mov->meta_keys[i]);
6582 av_freep(&mov->meta_keys);
6585 av_freep(&mov->trex_data);
6586 av_freep(&mov->bitrates);
6588 for (i = 0; i < mov->frag_index.nb_items; i++) {
6589 av_freep(&mov->frag_index.item[i].stream_info);
6591 av_freep(&mov->frag_index.item);
6593 av_freep(&mov->aes_decrypt);
6594 av_freep(&mov->chapter_tracks);
6599 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
6603 for (i = 0; i < s->nb_streams; i++) {
6604 AVStream *st = s->streams[i];
6605 MOVStreamContext *sc = st->priv_data;
6607 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6608 sc->timecode_track == tmcd_id)
6614 /* look for a tmcd track not referenced by any video track, and export it globally */
6615 static void export_orphan_timecode(AVFormatContext *s)
6619 for (i = 0; i < s->nb_streams; i++) {
6620 AVStream *st = s->streams[i];
6622 if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
6623 !tmcd_is_referenced(s, i + 1)) {
6624 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
6626 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
6633 static int read_tfra(MOVContext *mov, AVIOContext *f)
6635 int version, fieldlength, i, j;
6636 int64_t pos = avio_tell(f);
6637 uint32_t size = avio_rb32(f);
6638 unsigned track_id, item_count;
6640 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
6643 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
6645 version = avio_r8(f);
6647 track_id = avio_rb32(f);
6648 fieldlength = avio_rb32(f);
6649 item_count = avio_rb32(f);
6650 for (i = 0; i < item_count; i++) {
6651 int64_t time, offset;
6653 MOVFragmentStreamInfo * frag_stream_info;
6656 return AVERROR_INVALIDDATA;
6660 time = avio_rb64(f);
6661 offset = avio_rb64(f);
6663 time = avio_rb32(f);
6664 offset = avio_rb32(f);
6667 // The first sample of each stream in a fragment is always a random
6668 // access sample. So it's entry in the tfra can be used as the
6669 // initial PTS of the fragment.
6670 index = update_frag_index(mov, offset);
6671 frag_stream_info = get_frag_stream_info(&mov->frag_index, index, track_id);
6672 if (frag_stream_info &&
6673 frag_stream_info->first_tfra_pts == AV_NOPTS_VALUE)
6674 frag_stream_info->first_tfra_pts = time;
6676 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
6678 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
6680 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
6684 avio_seek(f, pos + size, SEEK_SET);
6688 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
6690 int64_t stream_size = avio_size(f);
6691 int64_t original_pos = avio_tell(f);
6695 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
6699 mfra_size = avio_rb32(f);
6700 if (mfra_size < 0 || mfra_size > stream_size) {
6701 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
6704 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
6708 if (avio_rb32(f) != mfra_size) {
6709 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
6712 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
6713 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
6716 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
6718 ret = read_tfra(c, f);
6724 seek_ret = avio_seek(f, original_pos, SEEK_SET);
6726 av_log(c->fc, AV_LOG_ERROR,
6727 "failed to seek back after looking for mfra\n");
6733 static int mov_read_header(AVFormatContext *s)
6735 MOVContext *mov = s->priv_data;
6736 AVIOContext *pb = s->pb;
6738 MOVAtom atom = { AV_RL32("root") };
6741 if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
6742 av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
6743 mov->decryption_key_len, AES_CTR_KEY_SIZE);
6744 return AVERROR(EINVAL);
6748 mov->trak_index = -1;
6749 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
6750 if (pb->seekable & AVIO_SEEKABLE_NORMAL)
6751 atom.size = avio_size(pb);
6753 atom.size = INT64_MAX;
6755 /* check MOV header */
6757 if (mov->moov_retry)
6758 avio_seek(pb, 0, SEEK_SET);
6759 if ((err = mov_read_default(mov, pb, atom)) < 0) {
6760 av_log(s, AV_LOG_ERROR, "error reading header\n");
6764 } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
6765 if (!mov->found_moov) {
6766 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
6768 return AVERROR_INVALIDDATA;
6770 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
6772 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
6773 if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
6774 mov_read_chapters(s);
6775 for (i = 0; i < s->nb_streams; i++)
6776 if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
6777 mov_read_timecode_track(s, s->streams[i]);
6778 } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
6779 mov_read_rtmd_track(s, s->streams[i]);
6783 /* copy timecode metadata from tmcd tracks to the related video streams */
6784 for (i = 0; i < s->nb_streams; i++) {
6785 AVStream *st = s->streams[i];
6786 MOVStreamContext *sc = st->priv_data;
6787 if (sc->timecode_track > 0) {
6788 AVDictionaryEntry *tcr;
6789 int tmcd_st_id = -1;
6791 for (j = 0; j < s->nb_streams; j++)
6792 if (s->streams[j]->id == sc->timecode_track)
6795 if (tmcd_st_id < 0 || tmcd_st_id == i)
6797 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
6799 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
6802 export_orphan_timecode(s);
6804 for (i = 0; i < s->nb_streams; i++) {
6805 AVStream *st = s->streams[i];
6806 MOVStreamContext *sc = st->priv_data;
6807 fix_timescale(mov, sc);
6808 if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6809 st->skip_samples = sc->start_pad;
6811 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
6812 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
6813 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
6814 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6815 if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
6816 st->codecpar->width = sc->width;
6817 st->codecpar->height = sc->height;
6819 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
6820 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
6824 if (mov->handbrake_version &&
6825 mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
6826 st->codecpar->codec_id == AV_CODEC_ID_MP3
6828 av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
6829 st->need_parsing = AVSTREAM_PARSE_FULL;
6833 if (mov->trex_data) {
6834 for (i = 0; i < s->nb_streams; i++) {
6835 AVStream *st = s->streams[i];
6836 MOVStreamContext *sc = st->priv_data;
6837 if (st->duration > 0) {
6838 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6839 av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6840 sc->data_size, sc->time_scale);
6842 return AVERROR_INVALIDDATA;
6844 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
6849 if (mov->use_mfra_for > 0) {
6850 for (i = 0; i < s->nb_streams; i++) {
6851 AVStream *st = s->streams[i];
6852 MOVStreamContext *sc = st->priv_data;
6853 if (sc->duration_for_fps > 0) {
6854 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6855 av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6856 sc->data_size, sc->time_scale);
6858 return AVERROR_INVALIDDATA;
6860 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
6861 sc->duration_for_fps;
6866 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
6867 if (mov->bitrates[i]) {
6868 s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
6872 ff_rfps_calculate(s);
6874 for (i = 0; i < s->nb_streams; i++) {
6875 AVStream *st = s->streams[i];
6876 MOVStreamContext *sc = st->priv_data;
6878 switch (st->codecpar->codec_type) {
6879 case AVMEDIA_TYPE_AUDIO:
6880 err = ff_replaygain_export(st, s->metadata);
6886 case AVMEDIA_TYPE_VIDEO:
6887 if (sc->display_matrix) {
6888 err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix,
6889 sizeof(int32_t) * 9);
6893 sc->display_matrix = NULL;
6896 err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
6897 (uint8_t *)sc->stereo3d,
6898 sizeof(*sc->stereo3d));
6902 sc->stereo3d = NULL;
6904 if (sc->spherical) {
6905 err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
6906 (uint8_t *)sc->spherical,
6907 sc->spherical_size);
6911 sc->spherical = NULL;
6913 if (sc->mastering) {
6914 err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
6915 (uint8_t *)sc->mastering,
6916 sizeof(*sc->mastering));
6920 sc->mastering = NULL;
6923 err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
6924 (uint8_t *)sc->coll,
6934 ff_configure_buffers_for_index(s, AV_TIME_BASE);
6936 for (i = 0; i < mov->frag_index.nb_items; i++)
6937 if (mov->frag_index.item[i].moof_offset <= mov->fragment.moof_offset)
6938 mov->frag_index.item[i].headers_read = 1;
6943 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
6945 AVIndexEntry *sample = NULL;
6946 int64_t best_dts = INT64_MAX;
6948 for (i = 0; i < s->nb_streams; i++) {
6949 AVStream *avst = s->streams[i];
6950 MOVStreamContext *msc = avst->priv_data;
6951 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
6952 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
6953 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
6954 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
6955 if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
6956 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6957 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
6958 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
6959 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
6960 sample = current_sample;
6969 static int should_retry(AVIOContext *pb, int error_code) {
6970 if (error_code == AVERROR_EOF || avio_feof(pb))
6976 static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
6979 MOVContext *mov = s->priv_data;
6981 if (index >= 0 && index < mov->frag_index.nb_items)
6982 target = mov->frag_index.item[index].moof_offset;
6983 if (avio_seek(s->pb, target, SEEK_SET) != target) {
6984 av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
6985 return AVERROR_INVALIDDATA;
6988 mov->next_root_atom = 0;
6989 if (index < 0 || index >= mov->frag_index.nb_items)
6990 index = search_frag_moof_offset(&mov->frag_index, target);
6991 if (index < mov->frag_index.nb_items) {
6992 if (index + 1 < mov->frag_index.nb_items)
6993 mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
6994 if (mov->frag_index.item[index].headers_read)
6996 mov->frag_index.item[index].headers_read = 1;
6999 mov->found_mdat = 0;
7001 ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
7004 if (avio_feof(s->pb))
7006 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
7011 static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
7013 uint8_t *side, *extradata;
7016 /* Save the current index. */
7017 sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
7019 /* Notify the decoder that extradata changed. */
7020 extradata_size = sc->extradata_size[sc->last_stsd_index];
7021 extradata = sc->extradata[sc->last_stsd_index];
7022 if (extradata_size > 0 && extradata) {
7023 side = av_packet_new_side_data(pkt,
7024 AV_PKT_DATA_NEW_EXTRADATA,
7027 return AVERROR(ENOMEM);
7028 memcpy(side, extradata, extradata_size);
7034 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
7036 MOVContext *mov = s->priv_data;
7037 MOVStreamContext *sc;
7038 AVIndexEntry *sample;
7039 AVStream *st = NULL;
7040 int64_t current_index;
7044 sample = mov_find_next_sample(s, &st);
7045 if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
7046 if (!mov->next_root_atom)
7048 if ((ret = mov_switch_root(s, mov->next_root_atom, -1)) < 0)
7053 /* must be done just before reading, to avoid infinite loop on sample */
7054 current_index = sc->current_index;
7055 mov_current_sample_inc(sc);
7057 if (mov->next_root_atom) {
7058 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
7059 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
7062 if (st->discard != AVDISCARD_ALL) {
7063 int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
7064 if (ret64 != sample->pos) {
7065 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
7066 sc->ffindex, sample->pos);
7067 if (should_retry(sc->pb, ret64)) {
7068 mov_current_sample_dec(sc);
7070 return AVERROR_INVALIDDATA;
7073 if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
7074 av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
7078 ret = av_get_packet(sc->pb, pkt, sample->size);
7080 if (should_retry(sc->pb, ret)) {
7081 mov_current_sample_dec(sc);
7085 if (sc->has_palette) {
7088 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
7090 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
7092 memcpy(pal, sc->palette, AVPALETTE_SIZE);
7093 sc->has_palette = 0;
7096 #if CONFIG_DV_DEMUXER
7097 if (mov->dv_demux && sc->dv_audio_container) {
7098 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
7099 av_freep(&pkt->data);
7101 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
7106 if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
7107 if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
7108 st->need_parsing = AVSTREAM_PARSE_FULL;
7112 pkt->stream_index = sc->ffindex;
7113 pkt->dts = sample->timestamp;
7114 if (sample->flags & AVINDEX_DISCARD_FRAME) {
7115 pkt->flags |= AV_PKT_FLAG_DISCARD;
7117 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
7118 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
7119 /* update ctts context */
7121 if (sc->ctts_index < sc->ctts_count &&
7122 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
7124 sc->ctts_sample = 0;
7127 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
7128 st->index_entries[sc->current_sample].timestamp : st->duration;
7129 pkt->duration = next_dts - pkt->dts;
7130 pkt->pts = pkt->dts;
7132 if (st->discard == AVDISCARD_ALL)
7134 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
7135 pkt->pos = sample->pos;
7137 /* Multiple stsd handling. */
7138 if (sc->stsc_data) {
7139 /* Keep track of the stsc index for the given sample, then check
7140 * if the stsd index is different from the last used one. */
7142 if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
7143 mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
7145 sc->stsc_sample = 0;
7146 /* Do not check indexes after a switch. */
7147 } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
7148 sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
7149 sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
7150 ret = mov_change_extradata(sc, pkt);
7157 aax_filter(pkt->data, pkt->size, mov);
7159 if (sc->cenc.aes_ctr) {
7160 ret = cenc_filter(mov, sc, current_index, pkt->data, pkt->size);
7169 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
7171 MOVContext *mov = s->priv_data;
7174 if (!mov->frag_index.complete)
7177 index = search_frag_timestamp(&mov->frag_index, st, timestamp);
7180 if (!mov->frag_index.item[index].headers_read)
7181 return mov_switch_root(s, -1, index);
7182 if (index + 1 < mov->frag_index.nb_items)
7183 mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
7188 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
7190 MOVStreamContext *sc = st->priv_data;
7191 int sample, time_sample, ret;
7194 // Here we consider timestamp to be PTS, hence try to offset it so that we
7195 // can search over the DTS timeline.
7196 timestamp -= (sc->min_corrected_pts + sc->dts_shift);
7198 ret = mov_seek_fragment(s, st, timestamp);
7202 sample = av_index_search_timestamp(st, timestamp, flags);
7203 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
7204 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
7206 if (sample < 0) /* not sure what to do */
7207 return AVERROR_INVALIDDATA;
7208 mov_current_sample_set(sc, sample);
7209 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
7210 /* adjust ctts index */
7211 if (sc->ctts_data) {
7213 for (i = 0; i < sc->ctts_count; i++) {
7214 int next = time_sample + sc->ctts_data[i].count;
7215 if (next > sc->current_sample) {
7217 sc->ctts_sample = sc->current_sample - time_sample;
7224 /* adjust stsd index */
7226 for (i = 0; i < sc->stsc_count; i++) {
7227 int64_t next = time_sample + mov_get_stsc_samples(sc, i);
7228 if (next > sc->current_sample) {
7230 sc->stsc_sample = sc->current_sample - time_sample;
7233 av_assert0(next == (int)next);
7240 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
7242 MOVContext *mc = s->priv_data;
7247 if (stream_index >= s->nb_streams)
7248 return AVERROR_INVALIDDATA;
7250 st = s->streams[stream_index];
7251 sample = mov_seek_stream(s, st, sample_time, flags);
7255 if (mc->seek_individually) {
7256 /* adjust seek timestamp to found sample timestamp */
7257 int64_t seek_timestamp = st->index_entries[sample].timestamp;
7259 for (i = 0; i < s->nb_streams; i++) {
7261 MOVStreamContext *sc = s->streams[i]->priv_data;
7263 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
7265 if (stream_index == i)
7268 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
7269 mov_seek_stream(s, st, timestamp, flags);
7272 for (i = 0; i < s->nb_streams; i++) {
7273 MOVStreamContext *sc;
7276 mov_current_sample_set(sc, 0);
7279 MOVStreamContext *sc;
7280 AVIndexEntry *entry = mov_find_next_sample(s, &st);
7282 return AVERROR_INVALIDDATA;
7284 if (sc->ffindex == stream_index && sc->current_sample == sample)
7286 mov_current_sample_inc(sc);
7292 #define OFFSET(x) offsetof(MOVContext, x)
7293 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
7294 static const AVOption mov_options[] = {
7295 {"use_absolute_path",
7296 "allow using absolute path when opening alias, this is a possible security issue",
7297 OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
7299 {"seek_streams_individually",
7300 "Seek each stream individually to the to the closest point",
7301 OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
7303 {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
7305 {"advanced_editlist",
7306 "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
7307 OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
7309 {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
7312 "use mfra for fragment timestamps",
7313 OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
7314 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
7316 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
7317 FLAGS, "use_mfra_for" },
7318 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
7319 FLAGS, "use_mfra_for" },
7320 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
7321 FLAGS, "use_mfra_for" },
7322 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
7323 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7324 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
7325 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7326 { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
7327 AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7328 { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
7329 "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
7330 AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
7331 .flags = AV_OPT_FLAG_DECODING_PARAM },
7332 { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7333 { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
7334 {.i64 = 0}, 0, 1, FLAGS },
7339 static const AVClass mov_class = {
7340 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
7341 .item_name = av_default_item_name,
7342 .option = mov_options,
7343 .version = LIBAVUTIL_VERSION_INT,
7346 AVInputFormat ff_mov_demuxer = {
7347 .name = "mov,mp4,m4a,3gp,3g2,mj2",
7348 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
7349 .priv_class = &mov_class,
7350 .priv_data_size = sizeof(MOVContext),
7351 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
7352 .read_probe = mov_probe,
7353 .read_header = mov_read_header,
7354 .read_packet = mov_read_packet,
7355 .read_close = mov_read_close,
7356 .read_seek = mov_read_seek,
7357 .flags = AVFMT_NO_BYTE_SEEK,