3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * first version by Francois Revol <revol@free.fr>
7 * seek function by Gael Chardon <gael.dev@4now.net>
9 * This file is part of FFmpeg.
11 * FFmpeg is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * FFmpeg is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with FFmpeg; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include "libavutil/attributes.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/intfloat.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/time_internal.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/display.h"
41 #include "libavutil/opt.h"
42 #include "libavutil/aes.h"
43 #include "libavutil/aes_ctr.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/sha.h"
46 #include "libavutil/spherical.h"
47 #include "libavutil/stereo3d.h"
48 #include "libavutil/timecode.h"
49 #include "libavcodec/ac3tab.h"
50 #include "libavcodec/flac.h"
51 #include "libavcodec/mpegaudiodecheader.h"
54 #include "avio_internal.h"
57 #include "libavcodec/get_bits.h"
60 #include "replaygain.h"
66 #include "qtpalette.h"
68 /* those functions parse an atom */
69 /* links atom IDs to parse functions */
70 typedef struct MOVParseTableEntry {
72 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
75 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
76 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
77 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
78 int count, int duration);
80 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
81 unsigned len, const char *key)
85 short current, total = 0;
86 avio_rb16(pb); // unknown
87 current = avio_rb16(pb);
89 total = avio_rb16(pb);
91 snprintf(buf, sizeof(buf), "%d", current);
93 snprintf(buf, sizeof(buf), "%d/%d", current, total);
94 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
95 av_dict_set(&c->fc->metadata, key, buf, 0);
100 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
101 unsigned len, const char *key)
103 /* bypass padding bytes */
108 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
109 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
114 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
115 unsigned len, const char *key)
117 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
118 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
123 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
124 unsigned len, const char *key)
128 avio_r8(pb); // unknown
131 if (genre < 1 || genre > ID3v1_GENRE_MAX)
133 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
134 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
139 static const uint32_t mac_to_unicode[128] = {
140 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
141 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
142 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
143 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
144 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
145 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
146 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
147 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
148 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
149 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
150 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
151 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
152 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
153 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
154 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
155 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
158 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
159 char *dst, int dstlen)
162 char *end = dst+dstlen-1;
165 for (i = 0; i < len; i++) {
166 uint8_t t, c = avio_r8(pb);
174 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
180 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
184 MOVStreamContext *sc;
189 case 0xd: id = AV_CODEC_ID_MJPEG; break;
190 case 0xe: id = AV_CODEC_ID_PNG; break;
191 case 0x1b: id = AV_CODEC_ID_BMP; break;
193 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
198 st = avformat_new_stream(c->fc, NULL);
200 return AVERROR(ENOMEM);
201 sc = av_mallocz(sizeof(*sc));
203 return AVERROR(ENOMEM);
206 ret = av_get_packet(pb, &pkt, len);
210 if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
211 if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
212 id = AV_CODEC_ID_PNG;
214 id = AV_CODEC_ID_MJPEG;
218 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
220 st->attached_pic = pkt;
221 st->attached_pic.stream_index = st->index;
222 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
224 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
225 st->codecpar->codec_id = id;
231 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
233 char language[4] = { 0 };
234 char buf[200], place[100];
235 uint16_t langcode = 0;
236 double longitude, latitude, altitude;
237 const char *key = "location";
239 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
240 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
241 return AVERROR_INVALIDDATA;
244 avio_skip(pb, 4); // version+flags
245 langcode = avio_rb16(pb);
246 ff_mov_lang_to_iso639(langcode, language);
249 len -= avio_get_str(pb, len, place, sizeof(place));
251 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
252 return AVERROR_INVALIDDATA;
254 avio_skip(pb, 1); // role
258 av_log(c->fc, AV_LOG_ERROR,
259 "loci too short (%u bytes left, need at least %d)\n", len, 12);
260 return AVERROR_INVALIDDATA;
262 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
263 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
264 altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
266 // Try to output in the same format as the ?xyz field
267 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
269 av_strlcatf(buf, sizeof(buf), "%+f", altitude);
270 av_strlcatf(buf, sizeof(buf), "/%s", place);
272 if (*language && strcmp(language, "und")) {
274 snprintf(key2, sizeof(key2), "%s-%s", key, language);
275 av_dict_set(&c->fc->metadata, key2, buf, 0);
277 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
278 return av_dict_set(&c->fc->metadata, key, buf, 0);
281 static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
287 if (c->ignore_chapters)
290 n_hmmt = avio_rb32(pb);
291 for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
292 int moment_time = avio_rb32(pb);
293 avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
298 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
301 char key2[32], language[4] = {0};
303 const char *key = NULL;
304 uint16_t langcode = 0;
305 uint32_t data_type = 0, str_size, str_size_alloc;
306 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
311 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
312 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
313 case MKTAG( 'X','M','P','_'):
314 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
315 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
316 case MKTAG( 'a','k','I','D'): key = "account_type";
317 parse = mov_metadata_int8_no_padding; break;
318 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
319 case MKTAG( 'c','a','t','g'): key = "category"; break;
320 case MKTAG( 'c','p','i','l'): key = "compilation";
321 parse = mov_metadata_int8_no_padding; break;
322 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
323 case MKTAG( 'd','e','s','c'): key = "description"; break;
324 case MKTAG( 'd','i','s','k'): key = "disc";
325 parse = mov_metadata_track_or_disc_number; break;
326 case MKTAG( 'e','g','i','d'): key = "episode_uid";
327 parse = mov_metadata_int8_no_padding; break;
328 case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
329 case MKTAG( 'g','n','r','e'): key = "genre";
330 parse = mov_metadata_gnre; break;
331 case MKTAG( 'h','d','v','d'): key = "hd_video";
332 parse = mov_metadata_int8_no_padding; break;
333 case MKTAG( 'H','M','M','T'):
334 return mov_metadata_hmmt(c, pb, atom.size);
335 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
336 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
337 case MKTAG( 'l','o','c','i'):
338 return mov_metadata_loci(c, pb, atom.size);
339 case MKTAG( 'p','c','s','t'): key = "podcast";
340 parse = mov_metadata_int8_no_padding; break;
341 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
342 parse = mov_metadata_int8_no_padding; break;
343 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
344 case MKTAG( 'r','t','n','g'): key = "rating";
345 parse = mov_metadata_int8_no_padding; break;
346 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
347 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
348 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
349 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
350 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
351 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
352 case MKTAG( 's','t','i','k'): key = "media_type";
353 parse = mov_metadata_int8_no_padding; break;
354 case MKTAG( 't','r','k','n'): key = "track";
355 parse = mov_metadata_track_or_disc_number; break;
356 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
357 case MKTAG( 't','v','e','s'): key = "episode_sort";
358 parse = mov_metadata_int8_bypass_padding; break;
359 case MKTAG( 't','v','n','n'): key = "network"; break;
360 case MKTAG( 't','v','s','h'): key = "show"; break;
361 case MKTAG( 't','v','s','n'): key = "season_number";
362 parse = mov_metadata_int8_bypass_padding; break;
363 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
364 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
365 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
366 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
367 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
368 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
369 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
370 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
371 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
372 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
373 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
374 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
375 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
376 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
377 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
378 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
379 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
380 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
381 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
382 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
383 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
384 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
385 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
386 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
387 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
388 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
389 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
390 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
391 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
392 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
393 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
394 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
395 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
396 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
397 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
400 if (c->itunes_metadata && atom.size > 8) {
401 int data_size = avio_rb32(pb);
402 int tag = avio_rl32(pb);
403 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
404 data_type = avio_rb32(pb); // type
405 avio_rb32(pb); // unknown
406 str_size = data_size - 16;
409 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
410 int ret = mov_read_covr(c, pb, data_type, str_size);
412 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
415 } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
416 uint32_t index = AV_RB32(&atom.type);
417 if (index < c->meta_keys_count && index > 0) {
418 key = c->meta_keys[index];
420 av_log(c->fc, AV_LOG_WARNING,
421 "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n",
422 index, c->meta_keys_count);
426 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
427 str_size = avio_rb16(pb); // string length
428 if (str_size > atom.size) {
430 avio_seek(pb, -2, SEEK_CUR);
431 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
434 langcode = avio_rb16(pb);
435 ff_mov_lang_to_iso639(langcode, language);
438 str_size = atom.size;
440 if (c->export_all && !key) {
441 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
447 if (atom.size < 0 || str_size >= INT_MAX/2)
448 return AVERROR_INVALIDDATA;
450 // Allocates enough space if data_type is a int32 or float32 number, otherwise
451 // worst-case requirement for output string in case of utf8 coded input
452 num = (data_type >= 21 && data_type <= 23);
453 str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
454 str = av_mallocz(str_size_alloc);
456 return AVERROR(ENOMEM);
459 parse(c, pb, str_size, key);
461 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
462 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
463 } else if (data_type == 21) { // BE signed integer, variable size
466 val = (int8_t)avio_r8(pb);
467 else if (str_size == 2)
468 val = (int16_t)avio_rb16(pb);
469 else if (str_size == 3)
470 val = ((int32_t)(avio_rb24(pb)<<8))>>8;
471 else if (str_size == 4)
472 val = (int32_t)avio_rb32(pb);
473 if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
474 av_log(c->fc, AV_LOG_ERROR,
475 "Failed to store the number (%d) in string.\n", val);
477 return AVERROR_INVALIDDATA;
479 } else if (data_type == 22) { // BE unsigned integer, variable size
480 unsigned int val = 0;
483 else if (str_size == 2)
485 else if (str_size == 3)
487 else if (str_size == 4)
489 if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
490 av_log(c->fc, AV_LOG_ERROR,
491 "Failed to store the number (%u) in string.\n", val);
493 return AVERROR_INVALIDDATA;
495 } else if (data_type == 23 && str_size >= 4) { // BE float32
496 float val = av_int2float(avio_rb32(pb));
497 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
498 av_log(c->fc, AV_LOG_ERROR,
499 "Failed to store the float32 number (%f) in string.\n", val);
501 return AVERROR_INVALIDDATA;
504 int ret = ffio_read_size(pb, str, str_size);
511 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
512 av_dict_set(&c->fc->metadata, key, str, 0);
513 if (*language && strcmp(language, "und")) {
514 snprintf(key2, sizeof(key2), "%s-%s", key, language);
515 av_dict_set(&c->fc->metadata, key2, str, 0);
517 if (!strcmp(key, "encoder")) {
518 int major, minor, micro;
519 if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, µ) == 3) {
520 c->handbrake_version = 1000000*major + 1000*minor + micro;
529 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
532 int i, nb_chapters, str_len, version;
536 if (c->ignore_chapters)
539 if ((atom.size -= 5) < 0)
542 version = avio_r8(pb);
545 avio_rb32(pb); // ???
546 nb_chapters = avio_r8(pb);
548 for (i = 0; i < nb_chapters; i++) {
552 start = avio_rb64(pb);
553 str_len = avio_r8(pb);
555 if ((atom.size -= 9+str_len) < 0)
558 ret = ffio_read_size(pb, str, str_len);
562 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
567 #define MIN_DATA_ENTRY_BOX_SIZE 12
568 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
571 MOVStreamContext *sc;
574 if (c->fc->nb_streams < 1)
576 st = c->fc->streams[c->fc->nb_streams-1];
579 avio_rb32(pb); // version + flags
580 entries = avio_rb32(pb);
582 entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
583 entries >= UINT_MAX / sizeof(*sc->drefs))
584 return AVERROR_INVALIDDATA;
588 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
590 return AVERROR(ENOMEM);
591 sc->drefs_count = entries;
593 for (i = 0; i < entries; i++) {
594 MOVDref *dref = &sc->drefs[i];
595 uint32_t size = avio_rb32(pb);
596 int64_t next = avio_tell(pb) + size - 4;
599 return AVERROR_INVALIDDATA;
601 dref->type = avio_rl32(pb);
602 avio_rb32(pb); // version + flags
604 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
605 /* macintosh alias record */
606 uint16_t volume_len, len;
612 volume_len = avio_r8(pb);
613 volume_len = FFMIN(volume_len, 27);
614 ret = ffio_read_size(pb, dref->volume, 27);
617 dref->volume[volume_len] = 0;
618 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
623 len = FFMIN(len, 63);
624 ret = ffio_read_size(pb, dref->filename, 63);
627 dref->filename[len] = 0;
628 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
632 /* read next level up_from_alias/down_to_target */
633 dref->nlvl_from = avio_rb16(pb);
634 dref->nlvl_to = avio_rb16(pb);
635 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
636 dref->nlvl_from, dref->nlvl_to);
640 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
643 type = avio_rb16(pb);
645 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
648 if (type == 2) { // absolute path
650 dref->path = av_mallocz(len+1);
652 return AVERROR(ENOMEM);
654 ret = ffio_read_size(pb, dref->path, len);
656 av_freep(&dref->path);
659 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
661 memmove(dref->path, dref->path+volume_len, len);
664 // trim string of any ending zeros
665 for (j = len - 1; j >= 0; j--) {
666 if (dref->path[j] == 0)
671 for (j = 0; j < len; j++)
672 if (dref->path[j] == ':' || dref->path[j] == 0)
674 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
675 } else if (type == 0) { // directory name
677 dref->dir = av_malloc(len+1);
679 return AVERROR(ENOMEM);
681 ret = ffio_read_size(pb, dref->dir, len);
683 av_freep(&dref->dir);
687 for (j = 0; j < len; j++)
688 if (dref->dir[j] == ':')
690 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
695 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n",
700 avio_seek(pb, next, SEEK_SET);
705 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
714 avio_r8(pb); /* version */
715 avio_rb24(pb); /* flags */
718 ctype = avio_rl32(pb);
719 type = avio_rl32(pb); /* component subtype */
721 av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype));
722 av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type));
724 if (c->trak_index < 0) { // meta not inside a trak
725 if (type == MKTAG('m','d','t','a')) {
726 c->found_hdlr_mdta = 1;
731 st = c->fc->streams[c->fc->nb_streams-1];
733 if (type == MKTAG('v','i','d','e'))
734 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
735 else if (type == MKTAG('s','o','u','n'))
736 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
737 else if (type == MKTAG('m','1','a',' '))
738 st->codecpar->codec_id = AV_CODEC_ID_MP2;
739 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
740 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
742 avio_rb32(pb); /* component manufacture */
743 avio_rb32(pb); /* component flags */
744 avio_rb32(pb); /* component flags mask */
746 title_size = atom.size - 24;
747 if (title_size > 0) {
748 if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
749 return AVERROR_INVALIDDATA;
750 title_str = av_malloc(title_size + 1); /* Add null terminator */
752 return AVERROR(ENOMEM);
754 ret = ffio_read_size(pb, title_str, title_size);
756 av_freep(&title_str);
759 title_str[title_size] = 0;
761 int off = (!c->isom && title_str[0] == title_size - 1);
762 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
764 av_freep(&title_str);
770 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
772 return ff_mov_read_esds(c->fc, pb);
775 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
778 enum AVAudioServiceType *ast;
779 int ac3info, acmod, lfeon, bsmod;
781 if (c->fc->nb_streams < 1)
783 st = c->fc->streams[c->fc->nb_streams-1];
785 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
788 return AVERROR(ENOMEM);
790 ac3info = avio_rb24(pb);
791 bsmod = (ac3info >> 14) & 0x7;
792 acmod = (ac3info >> 11) & 0x7;
793 lfeon = (ac3info >> 10) & 0x1;
794 st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
795 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
797 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
799 if (st->codecpar->channels > 1 && bsmod == 0x7)
800 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
802 #if FF_API_LAVF_AVCTX
803 FF_DISABLE_DEPRECATION_WARNINGS
804 st->codec->audio_service_type = *ast;
805 FF_ENABLE_DEPRECATION_WARNINGS
811 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
814 enum AVAudioServiceType *ast;
815 int eac3info, acmod, lfeon, bsmod;
817 if (c->fc->nb_streams < 1)
819 st = c->fc->streams[c->fc->nb_streams-1];
821 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
824 return AVERROR(ENOMEM);
826 /* No need to parse fields for additional independent substreams and its
827 * associated dependent substreams since libavcodec's E-AC-3 decoder
828 * does not support them yet. */
829 avio_rb16(pb); /* data_rate and num_ind_sub */
830 eac3info = avio_rb24(pb);
831 bsmod = (eac3info >> 12) & 0x1f;
832 acmod = (eac3info >> 9) & 0x7;
833 lfeon = (eac3info >> 8) & 0x1;
834 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
836 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
837 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
839 if (st->codecpar->channels > 1 && bsmod == 0x7)
840 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
842 #if FF_API_LAVF_AVCTX
843 FF_DISABLE_DEPRECATION_WARNINGS
844 st->codec->audio_service_type = *ast;
845 FF_ENABLE_DEPRECATION_WARNINGS
851 static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
853 const uint32_t ddts_size = 20;
856 uint32_t frame_duration_code = 0;
857 uint32_t channel_layout_code = 0;
860 buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE);
862 return AVERROR(ENOMEM);
864 if (avio_read(pb, buf, ddts_size) < ddts_size) {
866 return AVERROR_INVALIDDATA;
869 init_get_bits(&gb, buf, 8*ddts_size);
871 if (c->fc->nb_streams < 1) {
875 st = c->fc->streams[c->fc->nb_streams-1];
877 st->codecpar->sample_rate = get_bits_long(&gb, 32);
878 if (st->codecpar->sample_rate <= 0) {
879 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
881 return AVERROR_INVALIDDATA;
883 skip_bits_long(&gb, 32); /* max bitrate */
884 st->codecpar->bit_rate = get_bits_long(&gb, 32);
885 st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
886 frame_duration_code = get_bits(&gb, 2);
887 skip_bits(&gb, 30); /* various fields */
888 channel_layout_code = get_bits(&gb, 16);
890 st->codecpar->frame_size =
891 (frame_duration_code == 0) ? 512 :
892 (frame_duration_code == 1) ? 1024 :
893 (frame_duration_code == 2) ? 2048 :
894 (frame_duration_code == 3) ? 4096 : 0;
896 if (channel_layout_code > 0xff) {
897 av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
899 st->codecpar->channel_layout =
900 ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
901 ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
902 ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
903 ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
904 ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
905 ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
907 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
913 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
917 if (c->fc->nb_streams < 1)
919 st = c->fc->streams[c->fc->nb_streams-1];
924 /* skip version and flags */
927 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
932 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
937 if (c->fc->nb_streams < 1)
939 st = c->fc->streams[c->fc->nb_streams-1];
941 if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
942 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
947 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
949 const int num = avio_rb32(pb);
950 const int den = avio_rb32(pb);
953 if (c->fc->nb_streams < 1)
955 st = c->fc->streams[c->fc->nb_streams-1];
957 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
958 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
959 av_log(c->fc, AV_LOG_WARNING,
960 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
961 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
963 } else if (den != 0) {
964 av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
970 /* this atom contains actual media data */
971 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
973 if (atom.size == 0) /* wrong one (MP4) */
976 return 0; /* now go for moov */
979 #define DRM_BLOB_SIZE 56
981 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
983 uint8_t intermediate_key[20];
984 uint8_t intermediate_iv[20];
987 uint8_t file_checksum[20];
988 uint8_t calculated_checksum[20];
992 uint8_t *activation_bytes = c->activation_bytes;
993 uint8_t *fixed_key = c->audible_fixed_key;
997 sha = av_sha_alloc();
999 return AVERROR(ENOMEM);
1000 c->aes_decrypt = av_aes_alloc();
1001 if (!c->aes_decrypt) {
1002 ret = AVERROR(ENOMEM);
1006 /* drm blob processing */
1007 avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
1008 avio_read(pb, input, DRM_BLOB_SIZE);
1009 avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
1010 avio_read(pb, file_checksum, 20);
1012 av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
1013 for (i = 0; i < 20; i++)
1014 av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
1015 av_log(c->fc, AV_LOG_INFO, "\n");
1017 /* verify activation data */
1018 if (!activation_bytes) {
1019 av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
1020 ret = 0; /* allow ffprobe to continue working on .aax files */
1023 if (c->activation_bytes_size != 4) {
1024 av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
1025 ret = AVERROR(EINVAL);
1029 /* verify fixed key */
1030 if (c->audible_fixed_key_size != 16) {
1031 av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
1032 ret = AVERROR(EINVAL);
1036 /* AAX (and AAX+) key derivation */
1037 av_sha_init(sha, 160);
1038 av_sha_update(sha, fixed_key, 16);
1039 av_sha_update(sha, activation_bytes, 4);
1040 av_sha_final(sha, intermediate_key);
1041 av_sha_init(sha, 160);
1042 av_sha_update(sha, fixed_key, 16);
1043 av_sha_update(sha, intermediate_key, 20);
1044 av_sha_update(sha, activation_bytes, 4);
1045 av_sha_final(sha, intermediate_iv);
1046 av_sha_init(sha, 160);
1047 av_sha_update(sha, intermediate_key, 16);
1048 av_sha_update(sha, intermediate_iv, 16);
1049 av_sha_final(sha, calculated_checksum);
1050 if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
1051 av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
1052 ret = AVERROR_INVALIDDATA;
1055 av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
1056 av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
1057 for (i = 0; i < 4; i++) {
1058 // file data (in output) is stored in big-endian mode
1059 if (activation_bytes[i] != output[3 - i]) { // critical error
1060 av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
1061 ret = AVERROR_INVALIDDATA;
1065 memcpy(c->file_key, output + 8, 16);
1066 memcpy(input, output + 26, 16);
1067 av_sha_init(sha, 160);
1068 av_sha_update(sha, input, 16);
1069 av_sha_update(sha, c->file_key, 16);
1070 av_sha_update(sha, fixed_key, 16);
1071 av_sha_final(sha, c->file_iv);
1079 // Audible AAX (and AAX+) bytestream decryption
1080 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1083 unsigned char iv[16];
1085 memcpy(iv, c->file_iv, 16); // iv is overwritten
1086 blocks = size >> 4; // trailing bytes are not encrypted!
1087 av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1088 av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1093 /* read major brand, minor version and compatible brands and store them as metadata */
1094 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1097 int comp_brand_size;
1098 char* comp_brands_str;
1099 uint8_t type[5] = {0};
1100 int ret = ffio_read_size(pb, type, 4);
1104 if (strcmp(type, "qt "))
1106 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1107 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1108 minor_ver = avio_rb32(pb); /* minor version */
1109 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1111 comp_brand_size = atom.size - 8;
1112 if (comp_brand_size < 0)
1113 return AVERROR_INVALIDDATA;
1114 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1115 if (!comp_brands_str)
1116 return AVERROR(ENOMEM);
1118 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1120 av_freep(&comp_brands_str);
1123 comp_brands_str[comp_brand_size] = 0;
1124 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1125 av_freep(&comp_brands_str);
1130 /* this atom should contain all header atoms */
1131 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1135 if (c->found_moov) {
1136 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1137 avio_skip(pb, atom.size);
1141 if ((ret = mov_read_default(c, pb, atom)) < 0)
1143 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1144 /* so we don't parse the whole file if over a network */
1146 return 0; /* now go for mdat */
1149 static MOVFragmentStreamInfo * get_frag_stream_info(
1150 MOVFragmentIndex *frag_index,
1155 MOVFragmentIndexItem * item;
1157 if (index < 0 || index >= frag_index->nb_items)
1159 item = &frag_index->item[index];
1160 for (i = 0; i < item->nb_stream_info; i++)
1161 if (item->stream_info[i].id == id)
1162 return &item->stream_info[i];
1164 // This shouldn't happen
1168 static void set_frag_stream(MOVFragmentIndex *frag_index, int id)
1171 MOVFragmentIndexItem * item;
1173 if (frag_index->current < 0 ||
1174 frag_index->current >= frag_index->nb_items)
1177 item = &frag_index->item[frag_index->current];
1178 for (i = 0; i < item->nb_stream_info; i++)
1179 if (item->stream_info[i].id == id) {
1184 // id not found. This shouldn't happen.
1188 static MOVFragmentStreamInfo * get_current_frag_stream_info(
1189 MOVFragmentIndex *frag_index)
1191 MOVFragmentIndexItem *item;
1192 if (frag_index->current < 0 ||
1193 frag_index->current >= frag_index->nb_items)
1196 item = &frag_index->item[frag_index->current];
1197 if (item->current >= 0 && item->current < item->nb_stream_info)
1198 return &item->stream_info[item->current];
1200 // This shouldn't happen
1204 static int search_frag_moof_offset(MOVFragmentIndex *frag_index, int64_t offset)
1207 int64_t moof_offset;
1209 // Optimize for appending new entries
1210 if (!frag_index->nb_items ||
1211 frag_index->item[frag_index->nb_items - 1].moof_offset < offset)
1212 return frag_index->nb_items;
1215 b = frag_index->nb_items;
1219 moof_offset = frag_index->item[m].moof_offset;
1220 if (moof_offset >= offset)
1222 if (moof_offset <= offset)
1228 static int64_t get_stream_info_time(MOVFragmentStreamInfo * frag_stream_info)
1231 if (frag_stream_info) {
1232 if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE)
1233 return frag_stream_info->sidx_pts;
1234 if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE)
1235 return frag_stream_info->first_tfra_pts;
1236 if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE)
1237 return frag_stream_info->tfdt_dts;
1239 return AV_NOPTS_VALUE;
1242 static int64_t get_frag_time(MOVFragmentIndex *frag_index,
1243 int index, int track_id)
1245 MOVFragmentStreamInfo * frag_stream_info;
1249 if (track_id >= 0) {
1250 frag_stream_info = get_frag_stream_info(frag_index, index, track_id);
1251 return frag_stream_info->sidx_pts;
1254 for (i = 0; i < frag_index->item[index].nb_stream_info; i++) {
1255 frag_stream_info = &frag_index->item[index].stream_info[i];
1256 timestamp = get_stream_info_time(frag_stream_info);
1257 if (timestamp != AV_NOPTS_VALUE)
1260 return AV_NOPTS_VALUE;
1263 static int search_frag_timestamp(MOVFragmentIndex *frag_index,
1264 AVStream *st, int64_t timestamp)
1271 // If the stream is referenced by any sidx, limit the search
1272 // to fragments that referenced this stream in the sidx
1273 MOVStreamContext *sc = st->priv_data;
1279 b = frag_index->nb_items;
1283 frag_time = get_frag_time(frag_index, m, id);
1284 if (frag_time != AV_NOPTS_VALUE) {
1285 if (frag_time >= timestamp)
1287 if (frag_time <= timestamp)
1294 static int update_frag_index(MOVContext *c, int64_t offset)
1297 MOVFragmentIndexItem * item;
1298 MOVFragmentStreamInfo * frag_stream_info;
1300 // If moof_offset already exists in frag_index, return index to it
1301 index = search_frag_moof_offset(&c->frag_index, offset);
1302 if (index < c->frag_index.nb_items &&
1303 c->frag_index.item[index].moof_offset == offset)
1306 // offset is not yet in frag index.
1307 // Insert new item at index (sorted by moof offset)
1308 item = av_fast_realloc(c->frag_index.item,
1309 &c->frag_index.allocated_size,
1310 (c->frag_index.nb_items + 1) *
1311 sizeof(*c->frag_index.item));
1314 c->frag_index.item = item;
1316 frag_stream_info = av_realloc_array(NULL, c->fc->nb_streams,
1317 sizeof(*item->stream_info));
1318 if (!frag_stream_info)
1321 for (i = 0; i < c->fc->nb_streams; i++) {
1322 frag_stream_info[i].id = c->fc->streams[i]->id;
1323 frag_stream_info[i].sidx_pts = AV_NOPTS_VALUE;
1324 frag_stream_info[i].tfdt_dts = AV_NOPTS_VALUE;
1325 frag_stream_info[i].first_tfra_pts = AV_NOPTS_VALUE;
1326 frag_stream_info[i].index_entry = -1;
1329 if (index < c->frag_index.nb_items)
1330 memmove(c->frag_index.item + index + 1, c->frag_index.item + index,
1331 (c->frag_index.nb_items - index) * sizeof(*c->frag_index.item));
1333 item = &c->frag_index.item[index];
1334 item->headers_read = 0;
1336 item->nb_stream_info = c->fc->nb_streams;
1337 item->moof_offset = offset;
1338 item->stream_info = frag_stream_info;
1339 c->frag_index.nb_items++;
1344 static void fix_frag_index_entries(MOVFragmentIndex *frag_index, int index,
1345 int id, int entries)
1348 MOVFragmentStreamInfo * frag_stream_info;
1352 for (i = index; i < frag_index->nb_items; i++) {
1353 frag_stream_info = get_frag_stream_info(frag_index, i, id);
1354 if (frag_stream_info && frag_stream_info->index_entry >= 0)
1355 frag_stream_info->index_entry += entries;
1359 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1361 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1362 c->has_looked_for_mfra = 1;
1363 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
1365 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1367 if ((ret = mov_read_mfra(c, pb)) < 0) {
1368 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1369 "read the mfra (may be a live ismv)\n");
1372 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1373 "seekable, can not look for mfra\n");
1376 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
1377 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1378 c->frag_index.current = update_frag_index(c, c->fragment.moof_offset);
1379 return mov_read_default(c, pb, atom);
1382 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1385 if(time >= 2082844800)
1386 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1388 if ((int64_t)(time * 1000000ULL) / 1000000 != time) {
1389 av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n");
1393 avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
1397 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1400 MOVStreamContext *sc;
1402 char language[4] = {0};
1404 int64_t creation_time;
1406 if (c->fc->nb_streams < 1)
1408 st = c->fc->streams[c->fc->nb_streams-1];
1411 if (sc->time_scale) {
1412 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1413 return AVERROR_INVALIDDATA;
1416 version = avio_r8(pb);
1418 avpriv_request_sample(c->fc, "Version %d", version);
1419 return AVERROR_PATCHWELCOME;
1421 avio_rb24(pb); /* flags */
1423 creation_time = avio_rb64(pb);
1426 creation_time = avio_rb32(pb);
1427 avio_rb32(pb); /* modification time */
1429 mov_metadata_creation_time(&st->metadata, creation_time);
1431 sc->time_scale = avio_rb32(pb);
1432 if (sc->time_scale <= 0) {
1433 av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale);
1436 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1438 lang = avio_rb16(pb); /* language */
1439 if (ff_mov_lang_to_iso639(lang, language))
1440 av_dict_set(&st->metadata, "language", language, 0);
1441 avio_rb16(pb); /* quality */
1446 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1449 int64_t creation_time;
1450 int version = avio_r8(pb); /* version */
1451 avio_rb24(pb); /* flags */
1454 creation_time = avio_rb64(pb);
1457 creation_time = avio_rb32(pb);
1458 avio_rb32(pb); /* modification time */
1460 mov_metadata_creation_time(&c->fc->metadata, creation_time);
1461 c->time_scale = avio_rb32(pb); /* time scale */
1462 if (c->time_scale <= 0) {
1463 av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale);
1466 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1468 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1469 // set the AVCodecContext duration because the duration of individual tracks
1470 // may be inaccurate
1471 if (c->time_scale > 0 && !c->trex_data)
1472 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1473 avio_rb32(pb); /* preferred scale */
1475 avio_rb16(pb); /* preferred volume */
1477 avio_skip(pb, 10); /* reserved */
1479 /* movie display matrix, store it in main context and use it later on */
1480 for (i = 0; i < 3; i++) {
1481 c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
1482 c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
1483 c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
1486 avio_rb32(pb); /* preview time */
1487 avio_rb32(pb); /* preview duration */
1488 avio_rb32(pb); /* poster time */
1489 avio_rb32(pb); /* selection time */
1490 avio_rb32(pb); /* selection duration */
1491 avio_rb32(pb); /* current time */
1492 avio_rb32(pb); /* next track ID */
1497 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1502 if (c->fc->nb_streams < 1)
1504 st = c->fc->streams[c->fc->nb_streams-1];
1506 little_endian = avio_rb16(pb) & 0xFF;
1507 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1508 if (little_endian == 1) {
1509 switch (st->codecpar->codec_id) {
1510 case AV_CODEC_ID_PCM_S24BE:
1511 st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
1513 case AV_CODEC_ID_PCM_S32BE:
1514 st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
1516 case AV_CODEC_ID_PCM_F32BE:
1517 st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
1519 case AV_CODEC_ID_PCM_F64BE:
1520 st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
1529 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1532 char color_parameter_type[5] = { 0 };
1533 uint16_t color_primaries, color_trc, color_matrix;
1536 if (c->fc->nb_streams < 1)
1538 st = c->fc->streams[c->fc->nb_streams - 1];
1540 ret = ffio_read_size(pb, color_parameter_type, 4);
1543 if (strncmp(color_parameter_type, "nclx", 4) &&
1544 strncmp(color_parameter_type, "nclc", 4)) {
1545 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1546 color_parameter_type);
1550 color_primaries = avio_rb16(pb);
1551 color_trc = avio_rb16(pb);
1552 color_matrix = avio_rb16(pb);
1554 av_log(c->fc, AV_LOG_TRACE,
1555 "%s: pri %d trc %d matrix %d",
1556 color_parameter_type, color_primaries, color_trc, color_matrix);
1558 if (!strncmp(color_parameter_type, "nclx", 4)) {
1559 uint8_t color_range = avio_r8(pb) >> 7;
1560 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1562 st->codecpar->color_range = AVCOL_RANGE_JPEG;
1564 st->codecpar->color_range = AVCOL_RANGE_MPEG;
1567 if (!av_color_primaries_name(color_primaries))
1568 color_primaries = AVCOL_PRI_UNSPECIFIED;
1569 if (!av_color_transfer_name(color_trc))
1570 color_trc = AVCOL_TRC_UNSPECIFIED;
1571 if (!av_color_space_name(color_matrix))
1572 color_matrix = AVCOL_SPC_UNSPECIFIED;
1574 st->codecpar->color_primaries = color_primaries;
1575 st->codecpar->color_trc = color_trc;
1576 st->codecpar->color_space = color_matrix;
1577 av_log(c->fc, AV_LOG_TRACE, "\n");
1582 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1585 unsigned mov_field_order;
1586 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1588 if (c->fc->nb_streams < 1) // will happen with jp2 files
1590 st = c->fc->streams[c->fc->nb_streams-1];
1592 return AVERROR_INVALIDDATA;
1593 mov_field_order = avio_rb16(pb);
1594 if ((mov_field_order & 0xFF00) == 0x0100)
1595 decoded_field_order = AV_FIELD_PROGRESSIVE;
1596 else if ((mov_field_order & 0xFF00) == 0x0200) {
1597 switch (mov_field_order & 0xFF) {
1598 case 0x01: decoded_field_order = AV_FIELD_TT;
1600 case 0x06: decoded_field_order = AV_FIELD_BB;
1602 case 0x09: decoded_field_order = AV_FIELD_TB;
1604 case 0x0E: decoded_field_order = AV_FIELD_BT;
1608 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1609 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1611 st->codecpar->field_order = decoded_field_order;
1616 static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
1619 uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1620 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1621 return AVERROR_INVALIDDATA;
1622 if ((err = av_reallocp(&par->extradata, size)) < 0) {
1623 par->extradata_size = 0;
1626 par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1630 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1631 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1632 AVCodecParameters *par, uint8_t *buf)
1634 int64_t result = atom.size;
1637 AV_WB32(buf , atom.size + 8);
1638 AV_WL32(buf + 4, atom.type);
1639 err = ffio_read_size(pb, buf + 8, atom.size);
1641 par->extradata_size -= atom.size;
1643 } else if (err < atom.size) {
1644 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1645 par->extradata_size -= atom.size - err;
1648 memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1652 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1653 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1654 enum AVCodecID codec_id)
1657 uint64_t original_size;
1660 if (c->fc->nb_streams < 1) // will happen with jp2 files
1662 st = c->fc->streams[c->fc->nb_streams-1];
1664 if (st->codecpar->codec_id != codec_id)
1665 return 0; /* unexpected codec_id - don't mess with extradata */
1667 original_size = st->codecpar->extradata_size;
1668 err = mov_realloc_extradata(st->codecpar, atom);
1672 err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
1675 return 0; // Note: this is the original behavior to ignore truncation.
1678 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1679 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1681 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1684 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1686 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1689 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1691 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1694 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1696 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1699 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1701 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1703 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1707 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1709 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1711 if (!ret && c->fc->nb_streams >= 1) {
1712 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1713 if (par->extradata_size >= 40) {
1714 par->height = AV_RB16(&par->extradata[36]);
1715 par->width = AV_RB16(&par->extradata[38]);
1721 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1723 if (c->fc->nb_streams >= 1) {
1724 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1725 if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1726 par->codec_id == AV_CODEC_ID_H264 &&
1730 cid = avio_rb16(pb);
1731 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1732 if (cid == 0xd4d || cid == 0xd4e)
1735 } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
1736 par->codec_tag == MKTAG('A', 'V', 'j', '2') ||
1737 par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
1741 num = avio_rb32(pb);
1742 den = avio_rb32(pb);
1743 if (num <= 0 || den <= 0)
1745 switch (avio_rb32(pb)) {
1747 if (den >= INT_MAX / 2)
1751 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1752 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1759 return mov_read_avid(c, pb, atom);
1762 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1766 uint64_t original_size;
1767 if (c->fc->nb_streams >= 1) {
1768 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1769 if (par->codec_id == AV_CODEC_ID_H264)
1771 if (atom.size == 16) {
1772 original_size = par->extradata_size;
1773 ret = mov_realloc_extradata(par, atom);
1775 length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
1776 if (length == atom.size) {
1777 const uint8_t range_value = par->extradata[original_size + 19];
1778 switch (range_value) {
1780 par->color_range = AVCOL_RANGE_MPEG;
1783 par->color_range = AVCOL_RANGE_JPEG;
1786 av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1789 ff_dlog(c, "color_range: %d\n", par->color_range);
1791 /* For some reason the whole atom was not added to the extradata */
1792 av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1795 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1798 av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1805 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1807 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1810 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1815 if (c->fc->nb_streams < 1)
1817 st = c->fc->streams[c->fc->nb_streams-1];
1819 if ((uint64_t)atom.size > (1<<30))
1820 return AVERROR_INVALIDDATA;
1822 if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
1823 st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
1824 st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
1825 // pass all frma atom to codec, needed at least for QDMC and QDM2
1826 av_freep(&st->codecpar->extradata);
1827 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1830 } else if (atom.size > 8) { /* to read frma, esds atoms */
1831 if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1833 ret = ffio_ensure_seekback(pb, 8);
1836 buffer = avio_rb64(pb);
1838 if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1839 && buffer >> 32 <= atom.size
1840 && buffer >> 32 >= 8) {
1843 } else if (!st->codecpar->extradata_size) {
1844 #define ALAC_EXTRADATA_SIZE 36
1845 st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1846 if (!st->codecpar->extradata)
1847 return AVERROR(ENOMEM);
1848 st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
1849 AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE);
1850 AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
1851 AV_WB64(st->codecpar->extradata + 12, buffer);
1852 avio_read(pb, st->codecpar->extradata + 20, 16);
1853 avio_skip(pb, atom.size - 24);
1857 if ((ret = mov_read_default(c, pb, atom)) < 0)
1860 avio_skip(pb, atom.size);
1865 * This function reads atom content and puts data in extradata without tag
1866 * nor size unlike mov_read_extradata.
1868 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1873 if (c->fc->nb_streams < 1)
1875 st = c->fc->streams[c->fc->nb_streams-1];
1877 if ((uint64_t)atom.size > (1<<30))
1878 return AVERROR_INVALIDDATA;
1880 if (atom.size >= 10) {
1881 // Broken files created by legacy versions of libavformat will
1882 // wrap a whole fiel atom inside of a glbl atom.
1883 unsigned size = avio_rb32(pb);
1884 unsigned type = avio_rl32(pb);
1885 avio_seek(pb, -8, SEEK_CUR);
1886 if (type == MKTAG('f','i','e','l') && size == atom.size)
1887 return mov_read_default(c, pb, atom);
1889 if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
1890 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1893 av_freep(&st->codecpar->extradata);
1894 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1901 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1904 uint8_t profile_level;
1907 if (c->fc->nb_streams < 1)
1909 st = c->fc->streams[c->fc->nb_streams-1];
1911 if (atom.size >= (1<<28) || atom.size < 7)
1912 return AVERROR_INVALIDDATA;
1914 profile_level = avio_r8(pb);
1915 if ((profile_level & 0xf0) != 0xc0)
1918 avio_seek(pb, 6, SEEK_CUR);
1919 av_freep(&st->codecpar->extradata);
1920 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
1928 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1929 * but can have extradata appended at the end after the 40 bytes belonging
1932 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1937 if (c->fc->nb_streams < 1)
1939 if (atom.size <= 40)
1941 st = c->fc->streams[c->fc->nb_streams-1];
1943 if ((uint64_t)atom.size > (1<<30))
1944 return AVERROR_INVALIDDATA;
1947 av_freep(&st->codecpar->extradata);
1948 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
1955 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1958 MOVStreamContext *sc;
1959 unsigned int i, entries;
1961 if (c->fc->nb_streams < 1)
1963 st = c->fc->streams[c->fc->nb_streams-1];
1966 avio_r8(pb); /* version */
1967 avio_rb24(pb); /* flags */
1969 entries = avio_rb32(pb);
1974 if (sc->chunk_offsets)
1975 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1976 av_free(sc->chunk_offsets);
1977 sc->chunk_count = 0;
1978 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1979 if (!sc->chunk_offsets)
1980 return AVERROR(ENOMEM);
1981 sc->chunk_count = entries;
1983 if (atom.type == MKTAG('s','t','c','o'))
1984 for (i = 0; i < entries && !pb->eof_reached; i++)
1985 sc->chunk_offsets[i] = avio_rb32(pb);
1986 else if (atom.type == MKTAG('c','o','6','4'))
1987 for (i = 0; i < entries && !pb->eof_reached; i++)
1988 sc->chunk_offsets[i] = avio_rb64(pb);
1990 return AVERROR_INVALIDDATA;
1992 sc->chunk_count = i;
1994 if (pb->eof_reached) {
1995 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STCO atom\n");
2002 static int mov_codec_id(AVStream *st, uint32_t format)
2004 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
2007 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
2008 (format & 0xFFFF) == 'T' + ('S' << 8)))
2009 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
2011 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
2012 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2013 } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
2014 /* skip old ASF MPEG-4 tag */
2015 format && format != MKTAG('m','p','4','s')) {
2016 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2018 id = ff_codec_get_id(ff_codec_bmp_tags, format);
2020 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2021 else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
2022 (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
2023 st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
2024 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
2026 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2030 st->codecpar->codec_tag = format;
2035 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
2036 AVStream *st, MOVStreamContext *sc)
2038 uint8_t codec_name[32] = { 0 };
2042 /* The first 16 bytes of the video sample description are already
2043 * read in ff_mov_read_stsd_entries() */
2044 stsd_start = avio_tell(pb) - 16;
2046 avio_rb16(pb); /* version */
2047 avio_rb16(pb); /* revision level */
2048 avio_rb32(pb); /* vendor */
2049 avio_rb32(pb); /* temporal quality */
2050 avio_rb32(pb); /* spatial quality */
2052 st->codecpar->width = avio_rb16(pb); /* width */
2053 st->codecpar->height = avio_rb16(pb); /* height */
2055 avio_rb32(pb); /* horiz resolution */
2056 avio_rb32(pb); /* vert resolution */
2057 avio_rb32(pb); /* data size, always 0 */
2058 avio_rb16(pb); /* frames per samples */
2060 len = avio_r8(pb); /* codec name, pascal string */
2063 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
2065 avio_skip(pb, 31 - len);
2068 av_dict_set(&st->metadata, "encoder", codec_name, 0);
2070 /* codec_tag YV12 triggers an UV swap in rawdec.c */
2071 if (!strncmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
2072 st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
2073 st->codecpar->width &= ~1;
2074 st->codecpar->height &= ~1;
2076 /* Flash Media Server uses tag H.263 with Sorenson Spark */
2077 if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
2078 !strncmp(codec_name, "Sorenson H263", 13))
2079 st->codecpar->codec_id = AV_CODEC_ID_FLV1;
2081 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
2083 avio_seek(pb, stsd_start, SEEK_SET);
2085 if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
2086 st->codecpar->bits_per_coded_sample &= 0x1F;
2087 sc->has_palette = 1;
2091 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
2092 AVStream *st, MOVStreamContext *sc)
2094 int bits_per_sample, flags;
2095 uint16_t version = avio_rb16(pb);
2096 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
2098 avio_rb16(pb); /* revision level */
2099 avio_rb32(pb); /* vendor */
2101 st->codecpar->channels = avio_rb16(pb); /* channel count */
2102 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
2103 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
2105 sc->audio_cid = avio_rb16(pb);
2106 avio_rb16(pb); /* packet size = 0 */
2108 st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
2110 // Read QT version 1 fields. In version 0 these do not exist.
2111 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
2113 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
2116 sc->samples_per_frame = avio_rb32(pb);
2117 avio_rb32(pb); /* bytes per packet */
2118 sc->bytes_per_frame = avio_rb32(pb);
2119 avio_rb32(pb); /* bytes per sample */
2120 } else if (version == 2) {
2121 avio_rb32(pb); /* sizeof struct only */
2122 st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
2123 st->codecpar->channels = avio_rb32(pb);
2124 avio_rb32(pb); /* always 0x7F000000 */
2125 st->codecpar->bits_per_coded_sample = avio_rb32(pb);
2127 flags = avio_rb32(pb); /* lpcm format specific flag */
2128 sc->bytes_per_frame = avio_rb32(pb);
2129 sc->samples_per_frame = avio_rb32(pb);
2130 if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
2131 st->codecpar->codec_id =
2132 ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
2135 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
2136 /* can't correctly handle variable sized packet as audio unit */
2137 switch (st->codecpar->codec_id) {
2138 case AV_CODEC_ID_MP2:
2139 case AV_CODEC_ID_MP3:
2140 st->need_parsing = AVSTREAM_PARSE_FULL;
2146 if (sc->format == 0) {
2147 if (st->codecpar->bits_per_coded_sample == 8)
2148 st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
2149 else if (st->codecpar->bits_per_coded_sample == 16)
2150 st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
2153 switch (st->codecpar->codec_id) {
2154 case AV_CODEC_ID_PCM_S8:
2155 case AV_CODEC_ID_PCM_U8:
2156 if (st->codecpar->bits_per_coded_sample == 16)
2157 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
2159 case AV_CODEC_ID_PCM_S16LE:
2160 case AV_CODEC_ID_PCM_S16BE:
2161 if (st->codecpar->bits_per_coded_sample == 8)
2162 st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
2163 else if (st->codecpar->bits_per_coded_sample == 24)
2164 st->codecpar->codec_id =
2165 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
2166 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2167 else if (st->codecpar->bits_per_coded_sample == 32)
2168 st->codecpar->codec_id =
2169 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
2170 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2172 /* set values for old format before stsd version 1 appeared */
2173 case AV_CODEC_ID_MACE3:
2174 sc->samples_per_frame = 6;
2175 sc->bytes_per_frame = 2 * st->codecpar->channels;
2177 case AV_CODEC_ID_MACE6:
2178 sc->samples_per_frame = 6;
2179 sc->bytes_per_frame = 1 * st->codecpar->channels;
2181 case AV_CODEC_ID_ADPCM_IMA_QT:
2182 sc->samples_per_frame = 64;
2183 sc->bytes_per_frame = 34 * st->codecpar->channels;
2185 case AV_CODEC_ID_GSM:
2186 sc->samples_per_frame = 160;
2187 sc->bytes_per_frame = 33;
2193 bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
2194 if (bits_per_sample) {
2195 st->codecpar->bits_per_coded_sample = bits_per_sample;
2196 sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
2200 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
2201 AVStream *st, MOVStreamContext *sc,
2204 // ttxt stsd contains display flags, justification, background
2205 // color, fonts, and default styles, so fake an atom to read it
2206 MOVAtom fake_atom = { .size = size };
2207 // mp4s contains a regular esds atom
2208 if (st->codecpar->codec_tag != AV_RL32("mp4s"))
2209 mov_read_glbl(c, pb, fake_atom);
2210 st->codecpar->width = sc->width;
2211 st->codecpar->height = sc->height;
2214 static uint32_t yuv_to_rgba(uint32_t ycbcr)
2219 y = (ycbcr >> 16) & 0xFF;
2220 cr = (ycbcr >> 8) & 0xFF;
2223 b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
2224 g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
2225 r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
2227 return (r << 16) | (g << 8) | b;
2230 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
2232 char buf[256] = {0};
2233 uint8_t *src = st->codecpar->extradata;
2236 if (st->codecpar->extradata_size != 64)
2239 if (st->codecpar->width > 0 && st->codecpar->height > 0)
2240 snprintf(buf, sizeof(buf), "size: %dx%d\n",
2241 st->codecpar->width, st->codecpar->height);
2242 av_strlcat(buf, "palette: ", sizeof(buf));
2244 for (i = 0; i < 16; i++) {
2245 uint32_t yuv = AV_RB32(src + i * 4);
2246 uint32_t rgba = yuv_to_rgba(yuv);
2248 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2251 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2254 av_freep(&st->codecpar->extradata);
2255 st->codecpar->extradata_size = 0;
2256 st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
2257 if (!st->codecpar->extradata)
2258 return AVERROR(ENOMEM);
2259 st->codecpar->extradata_size = strlen(buf);
2260 memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
2265 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2266 AVStream *st, MOVStreamContext *sc,
2271 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
2272 if ((int)size != size)
2273 return AVERROR(ENOMEM);
2275 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
2279 MOVStreamContext *tmcd_ctx = st->priv_data;
2281 val = AV_RB32(st->codecpar->extradata + 4);
2282 tmcd_ctx->tmcd_flags = val;
2283 st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
2284 st->avg_frame_rate.den = 1;
2285 #if FF_API_LAVF_AVCTX
2286 FF_DISABLE_DEPRECATION_WARNINGS
2287 st->codec->time_base = av_inv_q(st->avg_frame_rate);
2288 FF_ENABLE_DEPRECATION_WARNINGS
2290 /* adjust for per frame dur in counter mode */
2291 if (tmcd_ctx->tmcd_flags & 0x0008) {
2292 int timescale = AV_RB32(st->codecpar->extradata + 8);
2293 int framedur = AV_RB32(st->codecpar->extradata + 12);
2294 st->avg_frame_rate.num *= timescale;
2295 st->avg_frame_rate.den *= framedur;
2296 #if FF_API_LAVF_AVCTX
2297 FF_DISABLE_DEPRECATION_WARNINGS
2298 st->codec->time_base.den *= timescale;
2299 st->codec->time_base.num *= framedur;
2300 FF_ENABLE_DEPRECATION_WARNINGS
2304 uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
2305 uint32_t format = AV_RB32(st->codecpar->extradata + 22);
2306 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2307 uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
2308 if (str_size > 0 && size >= (int)str_size + 26) {
2309 char *reel_name = av_malloc(str_size + 1);
2311 return AVERROR(ENOMEM);
2312 memcpy(reel_name, st->codecpar->extradata + 30, str_size);
2313 reel_name[str_size] = 0; /* Add null terminator */
2314 /* don't add reel_name if emtpy string */
2315 if (*reel_name == 0) {
2318 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2325 /* other codec type, just skip (rtp, mp4s ...) */
2326 avio_skip(pb, size);
2331 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2332 AVStream *st, MOVStreamContext *sc)
2334 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2335 !st->codecpar->sample_rate && sc->time_scale > 1)
2336 st->codecpar->sample_rate = sc->time_scale;
2338 /* special codec parameters handling */
2339 switch (st->codecpar->codec_id) {
2340 #if CONFIG_DV_DEMUXER
2341 case AV_CODEC_ID_DVAUDIO:
2342 c->dv_fctx = avformat_alloc_context();
2344 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2345 return AVERROR(ENOMEM);
2347 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2349 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2350 return AVERROR(ENOMEM);
2352 sc->dv_audio_container = 1;
2353 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
2356 /* no ifdef since parameters are always those */
2357 case AV_CODEC_ID_QCELP:
2358 st->codecpar->channels = 1;
2359 // force sample rate for qcelp when not stored in mov
2360 if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
2361 st->codecpar->sample_rate = 8000;
2362 // FIXME: Why is the following needed for some files?
2363 sc->samples_per_frame = 160;
2364 if (!sc->bytes_per_frame)
2365 sc->bytes_per_frame = 35;
2367 case AV_CODEC_ID_AMR_NB:
2368 st->codecpar->channels = 1;
2369 /* force sample rate for amr, stsd in 3gp does not store sample rate */
2370 st->codecpar->sample_rate = 8000;
2372 case AV_CODEC_ID_AMR_WB:
2373 st->codecpar->channels = 1;
2374 st->codecpar->sample_rate = 16000;
2376 case AV_CODEC_ID_MP2:
2377 case AV_CODEC_ID_MP3:
2378 /* force type after stsd for m1a hdlr */
2379 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2381 case AV_CODEC_ID_GSM:
2382 case AV_CODEC_ID_ADPCM_MS:
2383 case AV_CODEC_ID_ADPCM_IMA_WAV:
2384 case AV_CODEC_ID_ILBC:
2385 case AV_CODEC_ID_MACE3:
2386 case AV_CODEC_ID_MACE6:
2387 case AV_CODEC_ID_QDM2:
2388 st->codecpar->block_align = sc->bytes_per_frame;
2390 case AV_CODEC_ID_ALAC:
2391 if (st->codecpar->extradata_size == 36) {
2392 st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
2393 st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
2396 case AV_CODEC_ID_AC3:
2397 case AV_CODEC_ID_EAC3:
2398 case AV_CODEC_ID_MPEG1VIDEO:
2399 case AV_CODEC_ID_VC1:
2400 case AV_CODEC_ID_VP9:
2401 st->need_parsing = AVSTREAM_PARSE_FULL;
2409 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2410 int codec_tag, int format,
2413 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2416 (codec_tag != format &&
2417 // AVID 1:1 samples with differing data format and codec tag exist
2418 (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
2419 // prores is allowed to have differing data format and codec tag
2420 codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
2422 codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
2423 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2424 : codec_tag != MKTAG('j','p','e','g')))) {
2425 /* Multiple fourcc, we skip JPEG. This is not correct, we should
2426 * export it as a separate AVStream but this needs a few changes
2427 * in the MOV demuxer, patch welcome. */
2429 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2430 avio_skip(pb, size);
2437 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2440 MOVStreamContext *sc;
2441 int pseudo_stream_id;
2443 av_assert0 (c->fc->nb_streams >= 1);
2444 st = c->fc->streams[c->fc->nb_streams-1];
2447 for (pseudo_stream_id = 0;
2448 pseudo_stream_id < entries && !pb->eof_reached;
2449 pseudo_stream_id++) {
2450 //Parsing Sample description table
2452 int ret, dref_id = 1;
2453 MOVAtom a = { AV_RL32("stsd") };
2454 int64_t start_pos = avio_tell(pb);
2455 int64_t size = avio_rb32(pb); /* size */
2456 uint32_t format = avio_rl32(pb); /* data format */
2459 avio_rb32(pb); /* reserved */
2460 avio_rb16(pb); /* reserved */
2461 dref_id = avio_rb16(pb);
2462 } else if (size <= 7) {
2463 av_log(c->fc, AV_LOG_ERROR,
2464 "invalid size %"PRId64" in stsd\n", size);
2465 return AVERROR_INVALIDDATA;
2468 if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
2469 size - (avio_tell(pb) - start_pos))) {
2474 sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
2475 sc->dref_id= dref_id;
2476 sc->format = format;
2478 id = mov_codec_id(st, format);
2480 av_log(c->fc, AV_LOG_TRACE,
2481 "size=%"PRId64" 4CC=%s codec_type=%d\n", size,
2482 av_fourcc2str(format), st->codecpar->codec_type);
2484 if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
2485 st->codecpar->codec_id = id;
2486 mov_parse_stsd_video(c, pb, st, sc);
2487 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
2488 st->codecpar->codec_id = id;
2489 mov_parse_stsd_audio(c, pb, st, sc);
2490 if (st->codecpar->sample_rate < 0) {
2491 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
2492 return AVERROR_INVALIDDATA;
2494 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
2495 st->codecpar->codec_id = id;
2496 mov_parse_stsd_subtitle(c, pb, st, sc,
2497 size - (avio_tell(pb) - start_pos));
2499 ret = mov_parse_stsd_data(c, pb, st, sc,
2500 size - (avio_tell(pb) - start_pos));
2504 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2505 a.size = size - (avio_tell(pb) - start_pos);
2507 if ((ret = mov_read_default(c, pb, a)) < 0)
2509 } else if (a.size > 0)
2510 avio_skip(pb, a.size);
2512 if (sc->extradata && st->codecpar->extradata) {
2513 int extra_size = st->codecpar->extradata_size;
2515 /* Move the current stream extradata to the stream context one. */
2516 sc->extradata_size[pseudo_stream_id] = extra_size;
2517 sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
2518 if (!sc->extradata[pseudo_stream_id])
2519 return AVERROR(ENOMEM);
2520 memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
2521 av_freep(&st->codecpar->extradata);
2522 st->codecpar->extradata_size = 0;
2527 if (pb->eof_reached) {
2528 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSD atom\n");
2535 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2538 MOVStreamContext *sc;
2541 if (c->fc->nb_streams < 1)
2543 st = c->fc->streams[c->fc->nb_streams - 1];
2546 avio_r8(pb); /* version */
2547 avio_rb24(pb); /* flags */
2548 entries = avio_rb32(pb);
2551 av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
2552 return AVERROR_INVALIDDATA;
2555 if (sc->extradata) {
2556 av_log(c->fc, AV_LOG_ERROR,
2557 "Duplicate stsd found in this track.\n");
2558 return AVERROR_INVALIDDATA;
2561 /* Prepare space for hosting multiple extradata. */
2562 sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
2564 return AVERROR(ENOMEM);
2566 sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
2567 if (!sc->extradata_size) {
2568 ret = AVERROR(ENOMEM);
2572 ret = ff_mov_read_stsd_entries(c, pb, entries);
2576 /* Restore back the primary extradata. */
2577 av_freep(&st->codecpar->extradata);
2578 st->codecpar->extradata_size = sc->extradata_size[0];
2579 if (sc->extradata_size[0]) {
2580 st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
2581 if (!st->codecpar->extradata)
2582 return AVERROR(ENOMEM);
2583 memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
2586 return mov_finalize_stsd_codec(c, pb, st, sc);
2588 av_freep(&sc->extradata);
2589 av_freep(&sc->extradata_size);
2593 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2596 MOVStreamContext *sc;
2597 unsigned int i, entries;
2599 if (c->fc->nb_streams < 1)
2601 st = c->fc->streams[c->fc->nb_streams-1];
2604 avio_r8(pb); /* version */
2605 avio_rb24(pb); /* flags */
2607 entries = avio_rb32(pb);
2608 if ((uint64_t)entries * 12 + 4 > atom.size)
2609 return AVERROR_INVALIDDATA;
2611 av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
2616 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2617 av_free(sc->stsc_data);
2619 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2621 return AVERROR(ENOMEM);
2623 for (i = 0; i < entries && !pb->eof_reached; i++) {
2624 sc->stsc_data[i].first = avio_rb32(pb);
2625 sc->stsc_data[i].count = avio_rb32(pb);
2626 sc->stsc_data[i].id = avio_rb32(pb);
2631 if (pb->eof_reached) {
2632 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSC atom\n");
2639 static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
2641 return index < count - 1;
2644 /* Compute the samples value for the stsc entry at the given index. */
2645 static inline int mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
2649 if (mov_stsc_index_valid(index, sc->stsc_count))
2650 chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
2652 chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
2654 return sc->stsc_data[index].count * chunk_count;
2657 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2660 MOVStreamContext *sc;
2661 unsigned i, entries;
2663 if (c->fc->nb_streams < 1)
2665 st = c->fc->streams[c->fc->nb_streams-1];
2668 avio_rb32(pb); // version + flags
2670 entries = avio_rb32(pb);
2672 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2673 av_free(sc->stps_data);
2675 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2677 return AVERROR(ENOMEM);
2679 for (i = 0; i < entries && !pb->eof_reached; i++) {
2680 sc->stps_data[i] = avio_rb32(pb);
2685 if (pb->eof_reached) {
2686 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STPS atom\n");
2693 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2696 MOVStreamContext *sc;
2697 unsigned int i, entries;
2699 if (c->fc->nb_streams < 1)
2701 st = c->fc->streams[c->fc->nb_streams-1];
2704 avio_r8(pb); /* version */
2705 avio_rb24(pb); /* flags */
2707 entries = avio_rb32(pb);
2709 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
2713 sc->keyframe_absent = 1;
2714 if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2715 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2719 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2720 if (entries >= UINT_MAX / sizeof(int))
2721 return AVERROR_INVALIDDATA;
2722 av_freep(&sc->keyframes);
2723 sc->keyframe_count = 0;
2724 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2726 return AVERROR(ENOMEM);
2728 for (i = 0; i < entries && !pb->eof_reached; i++) {
2729 sc->keyframes[i] = avio_rb32(pb);
2732 sc->keyframe_count = i;
2734 if (pb->eof_reached) {
2735 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSS atom\n");
2742 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2745 MOVStreamContext *sc;
2746 unsigned int i, entries, sample_size, field_size, num_bytes;
2751 if (c->fc->nb_streams < 1)
2753 st = c->fc->streams[c->fc->nb_streams-1];
2756 avio_r8(pb); /* version */
2757 avio_rb24(pb); /* flags */
2759 if (atom.type == MKTAG('s','t','s','z')) {
2760 sample_size = avio_rb32(pb);
2761 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2762 sc->sample_size = sample_size;
2763 sc->stsz_sample_size = sample_size;
2767 avio_rb24(pb); /* reserved */
2768 field_size = avio_r8(pb);
2770 entries = avio_rb32(pb);
2772 av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
2774 sc->sample_count = entries;
2778 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2779 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
2780 return AVERROR_INVALIDDATA;
2785 if (entries >= (UINT_MAX - 4) / field_size)
2786 return AVERROR_INVALIDDATA;
2787 if (sc->sample_sizes)
2788 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2789 av_free(sc->sample_sizes);
2790 sc->sample_count = 0;
2791 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2792 if (!sc->sample_sizes)
2793 return AVERROR(ENOMEM);
2795 num_bytes = (entries*field_size+4)>>3;
2797 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2799 av_freep(&sc->sample_sizes);
2800 return AVERROR(ENOMEM);
2803 ret = ffio_read_size(pb, buf, num_bytes);
2805 av_freep(&sc->sample_sizes);
2810 init_get_bits(&gb, buf, 8*num_bytes);
2812 for (i = 0; i < entries && !pb->eof_reached; i++) {
2813 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2814 sc->data_size += sc->sample_sizes[i];
2817 sc->sample_count = i;
2821 if (pb->eof_reached) {
2822 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSZ atom\n");
2829 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2832 MOVStreamContext *sc;
2833 unsigned int i, entries, alloc_size = 0;
2835 int64_t total_sample_count=0;
2837 if (c->fc->nb_streams < 1)
2839 st = c->fc->streams[c->fc->nb_streams-1];
2842 avio_r8(pb); /* version */
2843 avio_rb24(pb); /* flags */
2844 entries = avio_rb32(pb);
2846 av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
2847 c->fc->nb_streams-1, entries);
2850 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2851 av_freep(&sc->stts_data);
2853 if (entries >= INT_MAX / sizeof(*sc->stts_data))
2854 return AVERROR(ENOMEM);
2856 for (i = 0; i < entries && !pb->eof_reached; i++) {
2857 int sample_duration;
2858 unsigned int sample_count;
2859 unsigned min_entries = FFMIN(FFMAX(i, 1024 * 1024), entries);
2860 MOVStts *stts_data = av_fast_realloc(sc->stts_data, &alloc_size,
2861 min_entries * sizeof(*sc->stts_data));
2863 av_freep(&sc->stts_data);
2865 return AVERROR(ENOMEM);
2867 sc->stts_count = min_entries;
2868 sc->stts_data = stts_data;
2870 sample_count=avio_rb32(pb);
2871 sample_duration = avio_rb32(pb);
2873 sc->stts_data[i].count= sample_count;
2874 sc->stts_data[i].duration= sample_duration;
2876 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2877 sample_count, sample_duration);
2881 && sample_count == 1
2882 && total_sample_count > 100
2883 && sample_duration/10 > duration / total_sample_count)
2884 sample_duration = duration / total_sample_count;
2885 duration+=(int64_t)sample_duration*sample_count;
2886 total_sample_count+=sample_count;
2891 sc->duration_for_fps += duration;
2892 sc->nb_frames_for_fps += total_sample_count;
2894 if (pb->eof_reached) {
2895 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STTS atom\n");
2899 st->nb_frames= total_sample_count;
2901 st->duration= duration;
2902 sc->track_end = duration;
2906 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2909 if (duration == INT_MIN) {
2910 av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2913 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2917 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2920 MOVStreamContext *sc;
2921 unsigned int i, entries, ctts_count = 0;
2923 if (c->fc->nb_streams < 1)
2925 st = c->fc->streams[c->fc->nb_streams-1];
2928 avio_r8(pb); /* version */
2929 avio_rb24(pb); /* flags */
2930 entries = avio_rb32(pb);
2932 av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
2936 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2937 return AVERROR_INVALIDDATA;
2938 av_freep(&sc->ctts_data);
2939 sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
2941 return AVERROR(ENOMEM);
2943 for (i = 0; i < entries && !pb->eof_reached; i++) {
2944 int count =avio_rb32(pb);
2945 int duration =avio_rb32(pb);
2948 av_log(c->fc, AV_LOG_TRACE,
2949 "ignoring CTTS entry with count=%d duration=%d\n",
2954 add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size,
2957 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2960 if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2961 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2962 av_freep(&sc->ctts_data);
2968 mov_update_dts_shift(sc, duration);
2971 sc->ctts_count = ctts_count;
2973 if (pb->eof_reached) {
2974 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted CTTS atom\n");
2978 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2983 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2986 MOVStreamContext *sc;
2987 unsigned int i, entries;
2989 uint32_t grouping_type;
2991 if (c->fc->nb_streams < 1)
2993 st = c->fc->streams[c->fc->nb_streams-1];
2996 version = avio_r8(pb); /* version */
2997 avio_rb24(pb); /* flags */
2998 grouping_type = avio_rl32(pb);
2999 if (grouping_type != MKTAG( 'r','a','p',' '))
3000 return 0; /* only support 'rap ' grouping */
3002 avio_rb32(pb); /* grouping_type_parameter */
3004 entries = avio_rb32(pb);
3008 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
3009 av_free(sc->rap_group);
3010 sc->rap_group_count = 0;
3011 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
3013 return AVERROR(ENOMEM);
3015 for (i = 0; i < entries && !pb->eof_reached; i++) {
3016 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
3017 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
3020 sc->rap_group_count = i;
3022 if (pb->eof_reached) {
3023 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted SBGP atom\n");
3031 * Get ith edit list entry (media time, duration).
3033 static int get_edit_list_entry(MOVContext *mov,
3034 const MOVStreamContext *msc,
3035 unsigned int edit_list_index,
3036 int64_t *edit_list_media_time,
3037 int64_t *edit_list_duration,
3038 int64_t global_timescale)
3040 if (edit_list_index == msc->elst_count) {
3043 *edit_list_media_time = msc->elst_data[edit_list_index].time;
3044 *edit_list_duration = msc->elst_data[edit_list_index].duration;
3046 /* duration is in global timescale units;convert to msc timescale */
3047 if (global_timescale == 0) {
3048 avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
3051 *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
3057 * Find the closest previous frame to the timestamp_pts, in e_old index
3058 * entries. Searching for just any frame / just key frames can be controlled by
3059 * last argument 'flag'.
3060 * Note that if ctts_data is not NULL, we will always search for a key frame
3061 * irrespective of the value of 'flag'. If we don't find any keyframe, we will
3062 * return the first frame of the video.
3064 * Here the timestamp_pts is considered to be a presentation timestamp and
3065 * the timestamp of index entries are considered to be decoding timestamps.
3067 * Returns 0 if successful in finding a frame, else returns -1.
3068 * Places the found index corresponding output arg.
3070 * If ctts_old is not NULL, then refines the searched entry by searching
3071 * backwards from the found timestamp, to find the frame with correct PTS.
3073 * Places the found ctts_index and ctts_sample in corresponding output args.
3075 static int find_prev_closest_index(AVStream *st,
3076 AVIndexEntry *e_old,
3080 int64_t timestamp_pts,
3083 int64_t* ctts_index,
3084 int64_t* ctts_sample)
3086 MOVStreamContext *msc = st->priv_data;
3087 AVIndexEntry *e_keep = st->index_entries;
3088 int nb_keep = st->nb_index_entries;
3090 int64_t index_ctts_count;
3094 // If dts_shift > 0, then all the index timestamps will have to be offset by
3095 // at least dts_shift amount to obtain PTS.
3096 // Hence we decrement the searched timestamp_pts by dts_shift to find the closest index element.
3097 if (msc->dts_shift > 0) {
3098 timestamp_pts -= msc->dts_shift;
3101 st->index_entries = e_old;
3102 st->nb_index_entries = nb_old;
3103 *index = av_index_search_timestamp(st, timestamp_pts, flag | AVSEEK_FLAG_BACKWARD);
3105 // Keep going backwards in the index entries until the timestamp is the same.
3107 for (i = *index; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
3109 if ((flag & AVSEEK_FLAG_ANY) ||
3110 (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
3116 // If we have CTTS then refine the search, by searching backwards over PTS
3117 // computed by adding corresponding CTTS durations to index timestamps.
3118 if (ctts_data && *index >= 0) {
3119 av_assert0(ctts_index);
3120 av_assert0(ctts_sample);
3121 // Find out the ctts_index for the found frame.
3124 for (index_ctts_count = 0; index_ctts_count < *index; index_ctts_count++) {
3125 if (*ctts_index < ctts_count) {
3127 if (ctts_data[*ctts_index].count == *ctts_sample) {
3134 while (*index >= 0 && (*ctts_index) >= 0) {
3135 // Find a "key frame" with PTS <= timestamp_pts (So that we can decode B-frames correctly).
3136 // No need to add dts_shift to the timestamp here becase timestamp_pts has already been
3137 // compensated by dts_shift above.
3138 if ((e_old[*index].timestamp + ctts_data[*ctts_index].duration) <= timestamp_pts &&
3139 (e_old[*index].flags & AVINDEX_KEYFRAME)) {
3144 if (*ctts_sample == 0) {
3146 if (*ctts_index >= 0)
3147 *ctts_sample = ctts_data[*ctts_index].count - 1;
3154 /* restore AVStream state*/
3155 st->index_entries = e_keep;
3156 st->nb_index_entries = nb_keep;
3157 return *index >= 0 ? 0 : -1;
3161 * Add index entry with the given values, to the end of st->index_entries.
3162 * Returns the new size st->index_entries if successful, else returns -1.
3164 * This function is similar to ff_add_index_entry in libavformat/utils.c
3165 * except that here we are always unconditionally adding an index entry to
3166 * the end, instead of searching the entries list and skipping the add if
3167 * there is an existing entry with the same timestamp.
3168 * This is needed because the mov_fix_index calls this func with the same
3169 * unincremented timestamp for successive discarded frames.
3171 static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
3172 int size, int distance, int flags)
3174 AVIndexEntry *entries, *ie;
3176 const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
3178 // Double the allocation each time, to lower memory fragmentation.
3179 // Another difference from ff_add_index_entry function.
3180 const size_t requested_size =
3181 min_size_needed > st->index_entries_allocated_size ?
3182 FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
3185 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
3188 entries = av_fast_realloc(st->index_entries,
3189 &st->index_entries_allocated_size,
3194 st->index_entries= entries;
3196 index= st->nb_index_entries++;
3197 ie= &entries[index];
3200 ie->timestamp = timestamp;
3201 ie->min_distance= distance;
3208 * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
3209 * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
3211 static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
3212 int64_t* frame_duration_buffer,
3213 int frame_duration_buffer_size) {
3215 av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
3216 for (i = 0; i < frame_duration_buffer_size; i++) {
3217 end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
3218 st->index_entries[end_index - 1 - i].timestamp = end_ts;
3223 * Append a new ctts entry to ctts_data.
3224 * Returns the new ctts_count if successful, else returns -1.
3226 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
3227 int count, int duration)
3229 MOVStts *ctts_buf_new;
3230 const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
3231 const size_t requested_size =
3232 min_size_needed > *allocated_size ?
3233 FFMAX(min_size_needed, 2 * (*allocated_size)) :
3236 if((unsigned)(*ctts_count) + 1 >= UINT_MAX / sizeof(MOVStts))
3239 ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
3244 *ctts_data = ctts_buf_new;
3246 ctts_buf_new[*ctts_count].count = count;
3247 ctts_buf_new[*ctts_count].duration = duration;
3249 *ctts_count = (*ctts_count) + 1;
3253 #define MAX_REORDER_DELAY 16
3254 static void mov_estimate_video_delay(MOVContext *c, AVStream* st) {
3255 MOVStreamContext *msc = st->priv_data;
3258 int ctts_sample = 0;
3259 int64_t pts_buf[MAX_REORDER_DELAY + 1]; // Circular buffer to sort pts.
3262 int j, r, num_swaps;
3264 if (st->codecpar->video_delay <= 0 && msc->ctts_data &&
3265 st->codecpar->codec_id == AV_CODEC_ID_H264) {
3266 st->codecpar->video_delay = 0;
3267 for(ind = 0; ind < st->nb_index_entries && ctts_ind < msc->ctts_count; ++ind) {
3268 if (buf_size == (MAX_REORDER_DELAY + 1)) {
3269 // If circular buffer is full, then move the first element forward.
3270 buf_start = (buf_start + 1) % buf_size;
3275 // Point j to the last elem of the buffer and insert the current pts there.
3276 j = (buf_start + buf_size - 1) % buf_size;
3277 pts_buf[j] = st->index_entries[ind].timestamp + msc->ctts_data[ctts_ind].duration;
3279 // The timestamps that are already in the sorted buffer, and are greater than the
3280 // current pts, are exactly the timestamps that need to be buffered to output PTS
3281 // in correct sorted order.
3282 // Hence the video delay (which is the buffer size used to sort DTS and output PTS),
3283 // can be computed as the maximum no. of swaps any particular timestamp needs to
3284 // go through, to keep this buffer in sorted order.
3286 while (j != buf_start) {
3287 r = (j - 1 + buf_size) % buf_size;
3288 if (pts_buf[j] < pts_buf[r]) {
3289 FFSWAP(int64_t, pts_buf[j], pts_buf[r]);
3294 st->codecpar->video_delay = FFMAX(st->codecpar->video_delay, num_swaps);
3297 if (ctts_sample == msc->ctts_data[ctts_ind].count) {
3302 av_log(c->fc, AV_LOG_DEBUG, "Setting codecpar->delay to %d for stream st: %d\n",
3303 st->codecpar->video_delay, st->index);
3307 static void mov_current_sample_inc(MOVStreamContext *sc)
3309 sc->current_sample++;
3310 sc->current_index++;
3311 if (sc->index_ranges &&
3312 sc->current_index >= sc->current_index_range->end &&
3313 sc->current_index_range->end) {
3314 sc->current_index_range++;
3315 sc->current_index = sc->current_index_range->start;
3319 static void mov_current_sample_dec(MOVStreamContext *sc)
3321 sc->current_sample--;
3322 sc->current_index--;
3323 if (sc->index_ranges &&
3324 sc->current_index < sc->current_index_range->start &&
3325 sc->current_index_range > sc->index_ranges) {
3326 sc->current_index_range--;
3327 sc->current_index = sc->current_index_range->end - 1;
3331 static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
3335 sc->current_sample = current_sample;
3336 sc->current_index = current_sample;
3337 if (!sc->index_ranges) {
3341 for (sc->current_index_range = sc->index_ranges;
3342 sc->current_index_range->end;
3343 sc->current_index_range++) {
3344 range_size = sc->current_index_range->end - sc->current_index_range->start;
3345 if (range_size > current_sample) {
3346 sc->current_index = sc->current_index_range->start + current_sample;
3349 current_sample -= range_size;
3354 * Fix st->index_entries, so that it contains only the entries (and the entries
3355 * which are needed to decode them) that fall in the edit list time ranges.
3356 * Also fixes the timestamps of the index entries to match the timeline
3357 * specified the edit lists.
3359 static void mov_fix_index(MOVContext *mov, AVStream *st)
3361 MOVStreamContext *msc = st->priv_data;
3362 AVIndexEntry *e_old = st->index_entries;
3363 int nb_old = st->nb_index_entries;
3364 const AVIndexEntry *e_old_end = e_old + nb_old;
3365 const AVIndexEntry *current = NULL;
3366 MOVStts *ctts_data_old = msc->ctts_data;
3367 int64_t ctts_index_old = 0;
3368 int64_t ctts_sample_old = 0;
3369 int64_t ctts_count_old = msc->ctts_count;
3370 int64_t edit_list_media_time = 0;
3371 int64_t edit_list_duration = 0;
3372 int64_t frame_duration = 0;
3373 int64_t edit_list_dts_counter = 0;
3374 int64_t edit_list_dts_entry_end = 0;
3375 int64_t edit_list_start_ctts_sample = 0;
3377 int64_t curr_ctts = 0;
3378 int64_t min_corrected_pts = -1;
3379 int64_t empty_edits_sum_duration = 0;
3380 int64_t edit_list_index = 0;
3383 int64_t start_dts = 0;
3384 int64_t edit_list_start_encountered = 0;
3385 int64_t search_timestamp = 0;
3386 int64_t* frame_duration_buffer = NULL;
3387 int num_discarded_begin = 0;
3388 int first_non_zero_audio_edit = -1;
3389 int packet_skip_samples = 0;
3390 MOVIndexRange *current_index_range;
3392 int found_keyframe_after_edit = 0;
3394 if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
3398 // allocate the index ranges array
3399 msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
3400 if (!msc->index_ranges) {
3401 av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
3404 msc->current_index_range = msc->index_ranges;
3405 current_index_range = msc->index_ranges - 1;
3407 // Clean AVStream from traces of old index
3408 st->index_entries = NULL;
3409 st->index_entries_allocated_size = 0;
3410 st->nb_index_entries = 0;
3412 // Clean ctts fields of MOVStreamContext
3413 msc->ctts_data = NULL;
3414 msc->ctts_count = 0;
3415 msc->ctts_index = 0;
3416 msc->ctts_sample = 0;
3417 msc->ctts_allocated_size = 0;
3419 // If the dts_shift is positive (in case of negative ctts values in mov),
3420 // then negate the DTS by dts_shift
3421 if (msc->dts_shift > 0) {
3422 edit_list_dts_entry_end -= msc->dts_shift;
3423 av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
3426 start_dts = edit_list_dts_entry_end;
3428 while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
3429 &edit_list_duration, mov->time_scale)) {
3430 av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
3431 st->index, edit_list_index, edit_list_media_time, edit_list_duration);
3433 edit_list_dts_counter = edit_list_dts_entry_end;
3434 edit_list_dts_entry_end += edit_list_duration;
3435 num_discarded_begin = 0;
3436 if (edit_list_media_time == -1) {
3437 empty_edits_sum_duration += edit_list_duration;
3441 // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
3442 // according to the edit list below.
3443 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3444 if (first_non_zero_audio_edit < 0) {
3445 first_non_zero_audio_edit = 1;
3447 first_non_zero_audio_edit = 0;
3450 if (first_non_zero_audio_edit > 0)
3451 st->skip_samples = msc->start_pad = 0;
3454 // While reordering frame index according to edit list we must handle properly
3455 // the scenario when edit list entry starts from none key frame.
3456 // We find closest previous key frame and preserve it and consequent frames in index.
3457 // All frames which are outside edit list entry time boundaries will be dropped after decoding.
3458 search_timestamp = edit_list_media_time;
3459 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3460 // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
3461 // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
3462 // edit_list_media_time to cover the decoder delay.
3463 search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
3466 if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, 0,
3467 &index, &ctts_index_old, &ctts_sample_old) < 0) {
3468 av_log(mov->fc, AV_LOG_WARNING,
3469 "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
3470 st->index, edit_list_index, search_timestamp);
3471 if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, AVSEEK_FLAG_ANY,
3472 &index, &ctts_index_old, &ctts_sample_old) < 0) {
3473 av_log(mov->fc, AV_LOG_WARNING,
3474 "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n",
3475 st->index, edit_list_index, search_timestamp);
3478 ctts_sample_old = 0;
3481 current = e_old + index;
3482 edit_list_start_ctts_sample = ctts_sample_old;
3484 // Iterate over index and arrange it according to edit list
3485 edit_list_start_encountered = 0;
3486 found_keyframe_after_edit = 0;
3487 for (; current < e_old_end; current++, index++) {
3488 // check if frame outside edit list mark it for discard
3489 frame_duration = (current + 1 < e_old_end) ?
3490 ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
3492 flags = current->flags;
3494 // frames (pts) before or after edit list
3495 curr_cts = current->timestamp + msc->dts_shift;
3498 if (ctts_data_old && ctts_index_old < ctts_count_old) {
3499 curr_ctts = ctts_data_old[ctts_index_old].duration;
3500 av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",
3501 curr_cts, curr_ctts, ctts_index_old, ctts_count_old);
3502 curr_cts += curr_ctts;
3504 if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
3505 if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3506 &msc->ctts_allocated_size,
3507 ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3508 ctts_data_old[ctts_index_old].duration) == -1) {
3509 av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3511 ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3512 ctts_data_old[ctts_index_old].duration);
3516 ctts_sample_old = 0;
3517 edit_list_start_ctts_sample = 0;
3521 if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
3522 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
3523 curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
3524 first_non_zero_audio_edit > 0) {
3525 packet_skip_samples = edit_list_media_time - curr_cts;
3526 st->skip_samples += packet_skip_samples;
3528 // Shift the index entry timestamp by packet_skip_samples to be correct.
3529 edit_list_dts_counter -= packet_skip_samples;
3530 if (edit_list_start_encountered == 0) {
3531 edit_list_start_encountered = 1;
3532 // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3533 // discarded packets.
3534 if (frame_duration_buffer) {
3535 fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3536 frame_duration_buffer, num_discarded_begin);
3537 av_freep(&frame_duration_buffer);
3541 av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
3543 flags |= AVINDEX_DISCARD_FRAME;
3544 av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
3546 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
3547 num_discarded_begin++;
3548 frame_duration_buffer = av_realloc(frame_duration_buffer,
3549 num_discarded_begin * sizeof(int64_t));
3550 if (!frame_duration_buffer) {
3551 av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
3554 frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
3556 // Increment skip_samples for the first non-zero audio edit list
3557 if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
3558 st->skip_samples += frame_duration;
3563 if (min_corrected_pts < 0) {
3564 min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
3566 min_corrected_pts = FFMIN(min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
3568 if (edit_list_start_encountered == 0) {
3569 edit_list_start_encountered = 1;
3570 // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3571 // discarded packets.
3572 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
3573 fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3574 frame_duration_buffer, num_discarded_begin);
3575 av_freep(&frame_duration_buffer);
3580 if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
3581 current->min_distance, flags) == -1) {
3582 av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
3586 // Update the index ranges array
3587 if (current_index_range < msc->index_ranges || index != current_index_range->end) {
3588 current_index_range++;
3589 current_index_range->start = index;
3591 current_index_range->end = index + 1;
3593 // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
3594 if (edit_list_start_encountered > 0) {
3595 edit_list_dts_counter = edit_list_dts_counter + frame_duration;
3598 // Break when found first key frame after edit entry completion
3599 if ((curr_cts + frame_duration >= (edit_list_duration + edit_list_media_time)) &&
3600 ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
3601 if (ctts_data_old) {
3602 // If we have CTTS and this is the first keyframe after edit elist,
3603 // wait for one more, because there might be trailing B-frames after this I-frame
3604 // that do belong to the edit.
3605 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && found_keyframe_after_edit == 0) {
3606 found_keyframe_after_edit = 1;
3609 if (ctts_sample_old != 0) {
3610 if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3611 &msc->ctts_allocated_size,
3612 ctts_sample_old - edit_list_start_ctts_sample,
3613 ctts_data_old[ctts_index_old].duration) == -1) {
3614 av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3615 ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
3616 ctts_data_old[ctts_index_old].duration);
3625 // If there are empty edits, then min_corrected_pts might be positive intentionally. So we subtract the
3626 // sum duration of emtpy edits here.
3627 min_corrected_pts -= empty_edits_sum_duration;
3629 // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
3630 // dts by that amount to make the first pts zero.
3631 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && min_corrected_pts > 0) {
3632 av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", min_corrected_pts);
3633 for (i = 0; i < st->nb_index_entries; ++i) {
3634 st->index_entries[i].timestamp -= min_corrected_pts;
3638 // Update av stream length
3639 st->duration = edit_list_dts_entry_end - start_dts;
3640 msc->start_pad = st->skip_samples;
3642 // Free the old index and the old CTTS structures
3644 av_free(ctts_data_old);
3645 av_freep(&frame_duration_buffer);
3647 // Null terminate the index ranges array
3648 current_index_range++;
3649 current_index_range->start = 0;
3650 current_index_range->end = 0;
3651 msc->current_index = msc->index_ranges[0].start;
3654 static void mov_build_index(MOVContext *mov, AVStream *st)
3656 MOVStreamContext *sc = st->priv_data;
3657 int64_t current_offset;
3658 int64_t current_dts = 0;
3659 unsigned int stts_index = 0;
3660 unsigned int stsc_index = 0;
3661 unsigned int stss_index = 0;
3662 unsigned int stps_index = 0;
3664 uint64_t stream_size = 0;
3665 MOVStts *ctts_data_old = sc->ctts_data;
3666 unsigned int ctts_count_old = sc->ctts_count;
3668 if (sc->elst_count) {
3669 int i, edit_start_index = 0, multiple_edits = 0;
3670 int64_t empty_duration = 0; // empty duration of the first edit list entry
3671 int64_t start_time = 0; // start time of the media
3673 for (i = 0; i < sc->elst_count; i++) {
3674 const MOVElst *e = &sc->elst_data[i];
3675 if (i == 0 && e->time == -1) {
3676 /* if empty, the first entry is the start time of the stream
3677 * relative to the presentation itself */
3678 empty_duration = e->duration;
3679 edit_start_index = 1;
3680 } else if (i == edit_start_index && e->time >= 0) {
3681 start_time = e->time;
3687 if (multiple_edits && !mov->advanced_editlist)
3688 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
3689 "Use -advanced_editlist to correctly decode otherwise "
3690 "a/v desync might occur\n");
3692 /* adjust first dts according to edit list */
3693 if ((empty_duration || start_time) && mov->time_scale > 0) {
3695 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
3696 sc->time_offset = start_time - empty_duration;
3697 if (!mov->advanced_editlist)
3698 current_dts = -sc->time_offset;
3701 if (!multiple_edits && !mov->advanced_editlist &&
3702 st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
3703 sc->start_pad = start_time;
3706 /* only use old uncompressed audio chunk demuxing when stts specifies it */
3707 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
3708 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
3709 unsigned int current_sample = 0;
3710 unsigned int stts_sample = 0;
3711 unsigned int sample_size;
3712 unsigned int distance = 0;
3713 unsigned int rap_group_index = 0;
3714 unsigned int rap_group_sample = 0;
3715 int64_t last_dts = 0;
3716 int64_t dts_correction = 0;
3717 int rap_group_present = sc->rap_group_count && sc->rap_group;
3718 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
3720 current_dts -= sc->dts_shift;
3721 last_dts = current_dts;
3723 if (!sc->sample_count || st->nb_index_entries)
3725 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3727 if (av_reallocp_array(&st->index_entries,
3728 st->nb_index_entries + sc->sample_count,
3729 sizeof(*st->index_entries)) < 0) {
3730 st->nb_index_entries = 0;
3733 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
3735 if (ctts_data_old) {
3736 // Expand ctts entries such that we have a 1-1 mapping with samples
3737 if (sc->sample_count >= UINT_MAX / sizeof(*sc->ctts_data))
3740 sc->ctts_allocated_size = 0;
3741 sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size,
3742 sc->sample_count * sizeof(*sc->ctts_data));
3743 if (!sc->ctts_data) {
3744 av_free(ctts_data_old);
3747 for (i = 0; i < ctts_count_old &&
3748 sc->ctts_count < sc->sample_count; i++)
3749 for (j = 0; j < ctts_data_old[i].count &&
3750 sc->ctts_count < sc->sample_count; j++)
3751 add_ctts_entry(&sc->ctts_data, &sc->ctts_count,
3752 &sc->ctts_allocated_size, 1,
3753 ctts_data_old[i].duration);
3754 av_free(ctts_data_old);
3757 for (i = 0; i < sc->chunk_count; i++) {
3758 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
3759 current_offset = sc->chunk_offsets[i];
3760 while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3761 i + 1 == sc->stsc_data[stsc_index + 1].first)
3764 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
3765 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
3766 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
3767 sc->stsz_sample_size = sc->sample_size;
3769 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
3770 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
3771 sc->stsz_sample_size = sc->sample_size;
3774 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
3776 if (current_sample >= sc->sample_count) {
3777 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
3781 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
3783 if (stss_index + 1 < sc->keyframe_count)
3785 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
3787 if (stps_index + 1 < sc->stps_count)
3790 if (rap_group_present && rap_group_index < sc->rap_group_count) {
3791 if (sc->rap_group[rap_group_index].index > 0)
3793 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
3794 rap_group_sample = 0;
3798 if (sc->keyframe_absent
3800 && !rap_group_present
3801 && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
3805 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
3806 if (sc->pseudo_stream_id == -1 ||
3807 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
3809 if (sample_size > 0x3FFFFFFF) {
3810 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
3813 e = &st->index_entries[st->nb_index_entries++];
3814 e->pos = current_offset;
3815 e->timestamp = current_dts;
3816 e->size = sample_size;
3817 e->min_distance = distance;
3818 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
3819 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
3820 "size %u, distance %u, keyframe %d\n", st->index, current_sample,
3821 current_offset, current_dts, sample_size, distance, keyframe);
3822 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
3823 ff_rfps_add_frame(mov->fc, st, current_dts);
3826 current_offset += sample_size;
3827 stream_size += sample_size;
3829 /* A negative sample duration is invalid based on the spec,
3830 * but some samples need it to correct the DTS. */
3831 if (sc->stts_data[stts_index].duration < 0) {
3832 av_log(mov->fc, AV_LOG_WARNING,
3833 "Invalid SampleDelta %d in STTS, at %d st:%d\n",
3834 sc->stts_data[stts_index].duration, stts_index,
3836 dts_correction += sc->stts_data[stts_index].duration - 1;
3837 sc->stts_data[stts_index].duration = 1;
3839 current_dts += sc->stts_data[stts_index].duration;
3840 if (!dts_correction || current_dts + dts_correction > last_dts) {
3841 current_dts += dts_correction;
3844 /* Avoid creating non-monotonous DTS */
3845 dts_correction += current_dts - last_dts - 1;
3846 current_dts = last_dts + 1;
3848 last_dts = current_dts;
3852 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
3858 if (st->duration > 0)
3859 st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
3861 unsigned chunk_samples, total = 0;
3863 // compute total chunk count
3864 for (i = 0; i < sc->stsc_count; i++) {
3865 unsigned count, chunk_count;
3867 chunk_samples = sc->stsc_data[i].count;
3868 if (i != sc->stsc_count - 1 &&
3869 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
3870 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
3874 if (sc->samples_per_frame >= 160) { // gsm
3875 count = chunk_samples / sc->samples_per_frame;
3876 } else if (sc->samples_per_frame > 1) {
3877 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
3878 count = (chunk_samples+samples-1) / samples;
3880 count = (chunk_samples+1023) / 1024;
3883 if (mov_stsc_index_valid(i, sc->stsc_count))
3884 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
3886 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
3887 total += chunk_count * count;
3890 av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
3891 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3893 if (av_reallocp_array(&st->index_entries,
3894 st->nb_index_entries + total,
3895 sizeof(*st->index_entries)) < 0) {
3896 st->nb_index_entries = 0;
3899 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
3902 for (i = 0; i < sc->chunk_count; i++) {
3903 current_offset = sc->chunk_offsets[i];
3904 if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3905 i + 1 == sc->stsc_data[stsc_index + 1].first)
3907 chunk_samples = sc->stsc_data[stsc_index].count;
3909 while (chunk_samples > 0) {
3911 unsigned size, samples;
3913 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
3914 avpriv_request_sample(mov->fc,
3915 "Zero bytes per frame, but %d samples per frame",
3916 sc->samples_per_frame);
3920 if (sc->samples_per_frame >= 160) { // gsm
3921 samples = sc->samples_per_frame;
3922 size = sc->bytes_per_frame;
3924 if (sc->samples_per_frame > 1) {
3925 samples = FFMIN((1024 / sc->samples_per_frame)*
3926 sc->samples_per_frame, chunk_samples);
3927 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
3929 samples = FFMIN(1024, chunk_samples);
3930 size = samples * sc->sample_size;
3934 if (st->nb_index_entries >= total) {
3935 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
3938 if (size > 0x3FFFFFFF) {
3939 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
3942 e = &st->index_entries[st->nb_index_entries++];
3943 e->pos = current_offset;
3944 e->timestamp = current_dts;
3946 e->min_distance = 0;
3947 e->flags = AVINDEX_KEYFRAME;
3948 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
3949 "size %u, duration %u\n", st->index, i, current_offset, current_dts,
3952 current_offset += size;
3953 current_dts += samples;
3954 chunk_samples -= samples;
3959 if (!mov->ignore_editlist && mov->advanced_editlist) {
3960 // Fix index according to edit lists.
3961 mov_fix_index(mov, st);
3964 mov_estimate_video_delay(mov, st);
3967 static int test_same_origin(const char *src, const char *ref) {
3977 av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
3978 av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
3980 if (strlen(src) == 0) {
3982 } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
3983 strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
3984 strlen(src_host) + 1 >= sizeof(src_host) ||
3985 strlen(ref_host) + 1 >= sizeof(ref_host)) {
3987 } else if (strcmp(src_proto, ref_proto) ||
3988 strcmp(src_auth, ref_auth) ||
3989 strcmp(src_host, ref_host) ||
3990 src_port != ref_port) {
3996 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
3998 /* try relative path, we do not try the absolute because it can leak information about our
3999 system to an attacker */
4000 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
4001 char filename[1025];
4002 const char *src_path;
4005 /* find a source dir */
4006 src_path = strrchr(src, '/');
4012 /* find a next level down to target */
4013 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
4014 if (ref->path[l] == '/') {
4015 if (i == ref->nlvl_to - 1)
4021 /* compose filename if next level down to target was found */
4022 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
4023 memcpy(filename, src, src_path - src);
4024 filename[src_path - src] = 0;
4026 for (i = 1; i < ref->nlvl_from; i++)
4027 av_strlcat(filename, "../", sizeof(filename));
4029 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
4030 if (!c->use_absolute_path) {
4031 int same_origin = test_same_origin(src, filename);
4034 av_log(c->fc, AV_LOG_ERROR,
4035 "Reference with mismatching origin, %s not tried for security reasons, "
4036 "set demuxer option use_absolute_path to allow it anyway\n",
4038 return AVERROR(ENOENT);
4041 if(strstr(ref->path + l + 1, "..") ||
4042 strstr(ref->path + l + 1, ":") ||
4043 (ref->nlvl_from > 1 && same_origin < 0) ||
4044 (filename[0] == '/' && src_path == src))
4045 return AVERROR(ENOENT);
4048 if (strlen(filename) + 1 == sizeof(filename))
4049 return AVERROR(ENOENT);
4050 if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
4053 } else if (c->use_absolute_path) {
4054 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
4055 "this is a possible security issue\n");
4056 if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
4059 av_log(c->fc, AV_LOG_ERROR,
4060 "Absolute path %s not tried for security reasons, "
4061 "set demuxer option use_absolute_path to allow absolute paths\n",
4065 return AVERROR(ENOENT);
4068 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
4070 if (sc->time_scale <= 0) {
4071 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
4072 sc->time_scale = c->time_scale;
4073 if (sc->time_scale <= 0)
4078 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4081 MOVStreamContext *sc;
4084 st = avformat_new_stream(c->fc, NULL);
4085 if (!st) return AVERROR(ENOMEM);
4086 st->id = c->fc->nb_streams;
4087 sc = av_mallocz(sizeof(MOVStreamContext));
4088 if (!sc) return AVERROR(ENOMEM);
4091 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
4092 sc->ffindex = st->index;
4093 c->trak_index = st->index;
4095 if ((ret = mov_read_default(c, pb, atom)) < 0)
4101 if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
4102 (!sc->sample_size && !sc->sample_count))) ||
4103 (!sc->chunk_count && sc->sample_count)) {
4104 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
4109 fix_timescale(c, sc);
4111 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
4113 mov_build_index(c, st);
4115 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
4116 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
4117 if (c->enable_drefs) {
4118 if (mov_open_dref(c, &sc->pb, c->fc->url, dref) < 0)
4119 av_log(c->fc, AV_LOG_ERROR,
4120 "stream %d, error opening alias: path='%s', dir='%s', "
4121 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
4122 st->index, dref->path, dref->dir, dref->filename,
4123 dref->volume, dref->nlvl_from, dref->nlvl_to);
4125 av_log(c->fc, AV_LOG_WARNING,
4126 "Skipped opening external track: "
4127 "stream %d, alias: path='%s', dir='%s', "
4128 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
4129 "Set enable_drefs to allow this.\n",
4130 st->index, dref->path, dref->dir, dref->filename,
4131 dref->volume, dref->nlvl_from, dref->nlvl_to);
4135 sc->pb_is_copied = 1;
4138 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
4139 if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
4140 sc->height && sc->width &&
4141 (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
4142 st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
4143 ((double)st->codecpar->width * sc->height), INT_MAX);
4146 #if FF_API_R_FRAME_RATE
4147 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
4148 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
4149 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
4153 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
4154 if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
4155 TAG_IS_AVCI(st->codecpar->codec_tag)) {
4156 ret = ff_generate_avci_extradata(st);
4161 switch (st->codecpar->codec_id) {
4162 #if CONFIG_H261_DECODER
4163 case AV_CODEC_ID_H261:
4165 #if CONFIG_H263_DECODER
4166 case AV_CODEC_ID_H263:
4168 #if CONFIG_MPEG4_DECODER
4169 case AV_CODEC_ID_MPEG4:
4171 st->codecpar->width = 0; /* let decoder init width/height */
4172 st->codecpar->height= 0;
4176 // If the duration of the mp3 packets is not constant, then they could need a parser
4177 if (st->codecpar->codec_id == AV_CODEC_ID_MP3
4178 && sc->stts_count > 3
4179 && sc->stts_count*10 > st->nb_frames
4180 && sc->time_scale == st->codecpar->sample_rate) {
4181 st->need_parsing = AVSTREAM_PARSE_FULL;
4183 /* Do not need those anymore. */
4184 av_freep(&sc->chunk_offsets);
4185 av_freep(&sc->sample_sizes);
4186 av_freep(&sc->keyframes);
4187 av_freep(&sc->stts_data);
4188 av_freep(&sc->stps_data);
4189 av_freep(&sc->elst_data);
4190 av_freep(&sc->rap_group);
4195 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4198 c->itunes_metadata = 1;
4199 ret = mov_read_default(c, pb, atom);
4200 c->itunes_metadata = 0;
4204 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4213 count = avio_rb32(pb);
4214 if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
4215 av_log(c->fc, AV_LOG_ERROR,
4216 "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
4217 return AVERROR_INVALIDDATA;
4220 c->meta_keys_count = count + 1;
4221 c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
4223 return AVERROR(ENOMEM);
4225 for (i = 1; i <= count; ++i) {
4226 uint32_t key_size = avio_rb32(pb);
4227 uint32_t type = avio_rl32(pb);
4229 av_log(c->fc, AV_LOG_ERROR,
4230 "The key# %"PRIu32" in meta has invalid size:"
4231 "%"PRIu32"\n", i, key_size);
4232 return AVERROR_INVALIDDATA;
4235 if (type != MKTAG('m','d','t','a')) {
4236 avio_skip(pb, key_size);
4238 c->meta_keys[i] = av_mallocz(key_size + 1);
4239 if (!c->meta_keys[i])
4240 return AVERROR(ENOMEM);
4241 avio_read(pb, c->meta_keys[i], key_size);
4247 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4249 int64_t end = avio_tell(pb) + atom.size;
4250 uint8_t *key = NULL, *val = NULL, *mean = NULL;
4254 MOVStreamContext *sc;
4256 if (c->fc->nb_streams < 1)
4258 st = c->fc->streams[c->fc->nb_streams-1];
4261 for (i = 0; i < 3; i++) {
4265 if (end - avio_tell(pb) <= 12)
4268 len = avio_rb32(pb);
4269 tag = avio_rl32(pb);
4270 avio_skip(pb, 4); // flags
4272 if (len < 12 || len - 12 > end - avio_tell(pb))
4276 if (tag == MKTAG('m', 'e', 'a', 'n'))
4278 else if (tag == MKTAG('n', 'a', 'm', 'e'))
4280 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
4287 *p = av_malloc(len + 1);
4289 ret = AVERROR(ENOMEM);
4292 ret = ffio_read_size(pb, *p, len);
4300 if (mean && key && val) {
4301 if (strcmp(key, "iTunSMPB") == 0) {
4302 int priming, remainder, samples;
4303 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
4304 if(priming>0 && priming<16384)
4305 sc->start_pad = priming;
4308 if (strcmp(key, "cdec") != 0) {
4309 av_dict_set(&c->fc->metadata, key, val,
4310 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
4314 av_log(c->fc, AV_LOG_VERBOSE,
4315 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
4318 avio_seek(pb, end, SEEK_SET);
4325 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4327 while (atom.size > 8) {
4328 uint32_t tag = avio_rl32(pb);
4330 if (tag == MKTAG('h','d','l','r')) {
4331 avio_seek(pb, -8, SEEK_CUR);
4333 return mov_read_default(c, pb, atom);
4339 // return 1 when matrix is identity, 0 otherwise
4340 #define IS_MATRIX_IDENT(matrix) \
4341 ( (matrix)[0][0] == (1 << 16) && \
4342 (matrix)[1][1] == (1 << 16) && \
4343 (matrix)[2][2] == (1 << 30) && \
4344 !(matrix)[0][1] && !(matrix)[0][2] && \
4345 !(matrix)[1][0] && !(matrix)[1][2] && \
4346 !(matrix)[2][0] && !(matrix)[2][1])
4348 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4353 int display_matrix[3][3];
4354 int res_display_matrix[3][3] = { { 0 } };
4356 MOVStreamContext *sc;
4360 if (c->fc->nb_streams < 1)
4362 st = c->fc->streams[c->fc->nb_streams-1];
4365 version = avio_r8(pb);
4366 flags = avio_rb24(pb);
4367 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
4373 avio_rb32(pb); /* creation time */
4374 avio_rb32(pb); /* modification time */
4376 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
4377 avio_rb32(pb); /* reserved */
4379 /* highlevel (considering edits) duration in movie timebase */
4380 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
4381 avio_rb32(pb); /* reserved */
4382 avio_rb32(pb); /* reserved */
4384 avio_rb16(pb); /* layer */
4385 avio_rb16(pb); /* alternate group */
4386 avio_rb16(pb); /* volume */
4387 avio_rb16(pb); /* reserved */
4389 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
4390 // they're kept in fixed point format through all calculations
4391 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
4392 // side data, but the scale factor is not needed to calculate aspect ratio
4393 for (i = 0; i < 3; i++) {
4394 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
4395 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
4396 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
4399 width = avio_rb32(pb); // 16.16 fixed point track width
4400 height = avio_rb32(pb); // 16.16 fixed point track height
4401 sc->width = width >> 16;
4402 sc->height = height >> 16;
4404 // apply the moov display matrix (after the tkhd one)
4405 for (i = 0; i < 3; i++) {
4406 const int sh[3] = { 16, 16, 30 };
4407 for (j = 0; j < 3; j++) {
4408 for (e = 0; e < 3; e++) {
4409 res_display_matrix[i][j] +=
4410 ((int64_t) display_matrix[i][e] *
4411 c->movie_display_matrix[e][j]) >> sh[e];
4416 // save the matrix when it is not the default identity
4417 if (!IS_MATRIX_IDENT(res_display_matrix)) {
4420 av_freep(&sc->display_matrix);
4421 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
4422 if (!sc->display_matrix)
4423 return AVERROR(ENOMEM);
4425 for (i = 0; i < 3; i++)
4426 for (j = 0; j < 3; j++)
4427 sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
4429 #if FF_API_OLD_ROTATE_API
4430 rotate = av_display_rotation_get(sc->display_matrix);
4431 if (!isnan(rotate)) {
4432 char rotate_buf[64];
4434 if (rotate < 0) // for backward compatibility
4436 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
4437 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
4442 // transform the display width/height according to the matrix
4443 // to keep the same scale, use [width height 1<<16]
4444 if (width && height && sc->display_matrix) {
4445 double disp_transform[2];
4447 for (i = 0; i < 2; i++)
4448 disp_transform[i] = hypot(sc->display_matrix[0 + i],
4449 sc->display_matrix[3 + i]);
4451 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
4452 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
4453 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
4454 st->sample_aspect_ratio = av_d2q(
4455 disp_transform[0] / disp_transform[1],
4461 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4463 MOVFragment *frag = &c->fragment;
4464 MOVTrackExt *trex = NULL;
4465 int flags, track_id, i;
4467 avio_r8(pb); /* version */
4468 flags = avio_rb24(pb);
4470 track_id = avio_rb32(pb);
4472 return AVERROR_INVALIDDATA;
4473 frag->track_id = track_id;
4474 set_frag_stream(&c->frag_index, track_id);
4475 for (i = 0; i < c->trex_count; i++)
4476 if (c->trex_data[i].track_id == frag->track_id) {
4477 trex = &c->trex_data[i];
4481 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
4482 return AVERROR_INVALIDDATA;
4485 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
4486 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
4487 frag->moof_offset : frag->implicit_offset;
4488 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
4490 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
4491 avio_rb32(pb) : trex->duration;
4492 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
4493 avio_rb32(pb) : trex->size;
4494 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
4495 avio_rb32(pb) : trex->flags;
4496 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
4501 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4506 num = atom.size / 4;
4507 if (!(new_tracks = av_malloc_array(num, sizeof(int))))
4508 return AVERROR(ENOMEM);
4510 av_free(c->chapter_tracks);
4511 c->chapter_tracks = new_tracks;
4512 c->nb_chapter_tracks = num;
4514 for (i = 0; i < num && !pb->eof_reached; i++)
4515 c->chapter_tracks[i] = avio_rb32(pb);
4520 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4525 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
4526 return AVERROR_INVALIDDATA;
4527 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
4528 sizeof(*c->trex_data))) < 0) {
4533 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
4535 trex = &c->trex_data[c->trex_count++];
4536 avio_r8(pb); /* version */
4537 avio_rb24(pb); /* flags */
4538 trex->track_id = avio_rb32(pb);
4539 trex->stsd_id = avio_rb32(pb);
4540 trex->duration = avio_rb32(pb);
4541 trex->size = avio_rb32(pb);
4542 trex->flags = avio_rb32(pb);
4546 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4548 MOVFragment *frag = &c->fragment;
4549 AVStream *st = NULL;
4550 MOVStreamContext *sc;
4552 MOVFragmentStreamInfo * frag_stream_info;
4553 int64_t base_media_decode_time;
4555 for (i = 0; i < c->fc->nb_streams; i++) {
4556 if (c->fc->streams[i]->id == frag->track_id) {
4557 st = c->fc->streams[i];
4562 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4563 return AVERROR_INVALIDDATA;
4566 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
4568 version = avio_r8(pb);
4569 avio_rb24(pb); /* flags */
4571 base_media_decode_time = avio_rb64(pb);
4573 base_media_decode_time = avio_rb32(pb);
4576 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4577 if (frag_stream_info)
4578 frag_stream_info->tfdt_dts = base_media_decode_time;
4579 sc->track_end = base_media_decode_time;
4584 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4586 MOVFragment *frag = &c->fragment;
4587 AVStream *st = NULL;
4588 MOVStreamContext *sc;
4591 int64_t dts, pts = AV_NOPTS_VALUE;
4592 int data_offset = 0;
4593 unsigned entries, first_sample_flags = frag->flags;
4594 int flags, distance, i;
4595 int64_t prev_dts = AV_NOPTS_VALUE;
4596 int next_frag_index = -1, index_entry_pos;
4597 size_t requested_size;
4598 AVIndexEntry *new_entries;
4599 MOVFragmentStreamInfo * frag_stream_info;
4601 for (i = 0; i < c->fc->nb_streams; i++) {
4602 if (c->fc->streams[i]->id == frag->track_id) {
4603 st = c->fc->streams[i];
4608 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4609 return AVERROR_INVALIDDATA;
4612 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
4615 // Find the next frag_index index that has a valid index_entry for
4616 // the current track_id.
4618 // A valid index_entry means the trun for the fragment was read
4619 // and it's samples are in index_entries at the given position.
4620 // New index entries will be inserted before the index_entry found.
4621 index_entry_pos = st->nb_index_entries;
4622 for (i = c->frag_index.current + 1; i < c->frag_index.nb_items; i++) {
4623 frag_stream_info = get_frag_stream_info(&c->frag_index, i, frag->track_id);
4624 if (frag_stream_info && frag_stream_info->index_entry >= 0) {
4625 next_frag_index = i;
4626 index_entry_pos = frag_stream_info->index_entry;
4631 avio_r8(pb); /* version */
4632 flags = avio_rb24(pb);
4633 entries = avio_rb32(pb);
4634 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
4636 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
4637 return AVERROR_INVALIDDATA;
4638 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
4639 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
4641 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4642 if (frag_stream_info)
4644 if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE &&
4645 c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
4646 pts = frag_stream_info->first_tfra_pts;
4647 av_log(c->fc, AV_LOG_DEBUG, "found mfra time %"PRId64
4648 ", using it for pts\n", pts);
4649 } else if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE) {
4650 // FIXME: sidx earliest_presentation_time is *PTS*, s.b.
4651 // pts = frag_stream_info->sidx_pts;
4652 dts = frag_stream_info->sidx_pts - sc->time_offset;
4653 av_log(c->fc, AV_LOG_DEBUG, "found sidx time %"PRId64
4654 ", using it for pts\n", pts);
4655 } else if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE) {
4656 dts = frag_stream_info->tfdt_dts - sc->time_offset;
4657 av_log(c->fc, AV_LOG_DEBUG, "found tfdt time %"PRId64
4658 ", using it for dts\n", dts);
4660 dts = sc->track_end - sc->time_offset;
4661 av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4662 ", using it for dts\n", dts);
4665 dts = sc->track_end - sc->time_offset;
4666 av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4667 ", using it for dts\n", dts);
4669 offset = frag->base_data_offset + data_offset;
4671 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
4673 // realloc space for new index entries
4674 if((unsigned)st->nb_index_entries + entries >= UINT_MAX / sizeof(AVIndexEntry)) {
4675 entries = UINT_MAX / sizeof(AVIndexEntry) - st->nb_index_entries;
4676 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
4681 requested_size = (st->nb_index_entries + entries) * sizeof(AVIndexEntry);
4682 new_entries = av_fast_realloc(st->index_entries,
4683 &st->index_entries_allocated_size,
4686 return AVERROR(ENOMEM);
4687 st->index_entries= new_entries;
4689 requested_size = (st->nb_index_entries + entries) * sizeof(*sc->ctts_data);
4690 ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size,
4693 return AVERROR(ENOMEM);
4694 sc->ctts_data = ctts_data;
4696 // In case there were samples without ctts entries, ensure they get
4697 // zero valued entries. This ensures clips which mix boxes with and
4698 // without ctts entries don't pickup uninitialized data.
4699 memset(sc->ctts_data + sc->ctts_count, 0,
4700 (st->nb_index_entries - sc->ctts_count) * sizeof(*sc->ctts_data));
4702 if (index_entry_pos < st->nb_index_entries) {
4703 // Make hole in index_entries and ctts_data for new samples
4704 memmove(st->index_entries + index_entry_pos + entries,
4705 st->index_entries + index_entry_pos,
4706 sizeof(*st->index_entries) *
4707 (st->nb_index_entries - index_entry_pos));
4708 memmove(sc->ctts_data + index_entry_pos + entries,
4709 sc->ctts_data + index_entry_pos,
4710 sizeof(*sc->ctts_data) * (sc->ctts_count - index_entry_pos));
4711 if (index_entry_pos < sc->current_sample) {
4712 sc->current_sample += entries;
4716 st->nb_index_entries += entries;
4717 sc->ctts_count = st->nb_index_entries;
4719 // Record the index_entry position in frag_index of this fragment
4720 if (frag_stream_info)
4721 frag_stream_info->index_entry = index_entry_pos;
4723 if (index_entry_pos > 0)
4724 prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4726 for (i = 0; i < entries && !pb->eof_reached; i++) {
4727 unsigned sample_size = frag->size;
4728 int sample_flags = i ? frag->flags : first_sample_flags;
4729 unsigned sample_duration = frag->duration;
4730 unsigned ctts_duration = 0;
4732 int index_entry_flags = 0;
4734 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
4735 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
4736 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
4737 if (flags & MOV_TRUN_SAMPLE_CTS) ctts_duration = avio_rb32(pb);
4739 mov_update_dts_shift(sc, ctts_duration);
4740 if (pts != AV_NOPTS_VALUE) {
4741 dts = pts - sc->dts_shift;
4742 if (flags & MOV_TRUN_SAMPLE_CTS) {
4743 dts -= ctts_duration;
4745 dts -= sc->time_offset;
4747 av_log(c->fc, AV_LOG_DEBUG,
4748 "pts %"PRId64" calculated dts %"PRId64
4749 " sc->dts_shift %d ctts.duration %d"
4750 " sc->time_offset %"PRId64
4751 " flags & MOV_TRUN_SAMPLE_CTS %d\n",
4753 sc->dts_shift, ctts_duration,
4754 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
4755 pts = AV_NOPTS_VALUE;
4758 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4762 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
4763 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
4766 index_entry_flags |= AVINDEX_KEYFRAME;
4768 // Fragments can overlap in time. Discard overlapping frames after
4770 if (prev_dts >= dts)
4771 index_entry_flags |= AVINDEX_DISCARD_FRAME;
4773 st->index_entries[index_entry_pos].pos = offset;
4774 st->index_entries[index_entry_pos].timestamp = dts;
4775 st->index_entries[index_entry_pos].size= sample_size;
4776 st->index_entries[index_entry_pos].min_distance= distance;
4777 st->index_entries[index_entry_pos].flags = index_entry_flags;
4779 sc->ctts_data[index_entry_pos].count = 1;
4780 sc->ctts_data[index_entry_pos].duration = ctts_duration;
4783 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
4784 "size %u, distance %d, keyframe %d\n", st->index,
4785 index_entry_pos, offset, dts, sample_size, distance, keyframe);
4787 dts += sample_duration;
4788 offset += sample_size;
4789 sc->data_size += sample_size;
4790 sc->duration_for_fps += sample_duration;
4791 sc->nb_frames_for_fps ++;
4794 // EOF found before reading all entries. Fix the hole this would
4795 // leave in index_entries and ctts_data
4796 int gap = entries - i;
4797 memmove(st->index_entries + index_entry_pos,
4798 st->index_entries + index_entry_pos + gap,
4799 sizeof(*st->index_entries) *
4800 (st->nb_index_entries - (index_entry_pos + gap)));
4801 memmove(sc->ctts_data + index_entry_pos,
4802 sc->ctts_data + index_entry_pos + gap,
4803 sizeof(*sc->ctts_data) *
4804 (sc->ctts_count - (index_entry_pos + gap)));
4806 st->nb_index_entries -= gap;
4807 sc->ctts_count -= gap;
4808 if (index_entry_pos < sc->current_sample) {
4809 sc->current_sample -= gap;
4814 // The end of this new fragment may overlap in time with the start
4815 // of the next fragment in index_entries. Mark the samples in the next
4816 // fragment that overlap with AVINDEX_DISCARD_FRAME
4817 prev_dts = AV_NOPTS_VALUE;
4818 if (index_entry_pos > 0)
4819 prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4820 for (i = index_entry_pos; i < st->nb_index_entries; i++) {
4821 if (prev_dts < st->index_entries[i].timestamp)
4823 st->index_entries[i].flags |= AVINDEX_DISCARD_FRAME;
4826 // If a hole was created to insert the new index_entries into,
4827 // the index_entry recorded for all subsequent moof must
4828 // be incremented by the number of entries inserted.
4829 fix_frag_index_entries(&c->frag_index, next_frag_index,
4830 frag->track_id, entries);
4832 if (pb->eof_reached) {
4833 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted TRUN atom\n");
4837 frag->implicit_offset = offset;
4839 sc->track_end = dts + sc->time_offset;
4840 if (st->duration < sc->track_end)
4841 st->duration = sc->track_end;
4846 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4848 int64_t offset = avio_tell(pb) + atom.size, pts, timestamp;
4850 unsigned i, j, track_id, item_count;
4851 AVStream *st = NULL;
4852 AVStream *ref_st = NULL;
4853 MOVStreamContext *sc, *ref_sc = NULL;
4854 AVRational timescale;
4856 version = avio_r8(pb);
4858 avpriv_request_sample(c->fc, "sidx version %u", version);
4862 avio_rb24(pb); // flags
4864 track_id = avio_rb32(pb); // Reference ID
4865 for (i = 0; i < c->fc->nb_streams; i++) {
4866 if (c->fc->streams[i]->id == track_id) {
4867 st = c->fc->streams[i];
4872 av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
4878 timescale = av_make_q(1, avio_rb32(pb));
4880 if (timescale.den <= 0) {
4881 av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
4882 return AVERROR_INVALIDDATA;
4886 pts = avio_rb32(pb);
4887 offset += avio_rb32(pb);
4889 pts = avio_rb64(pb);
4890 offset += avio_rb64(pb);
4893 avio_rb16(pb); // reserved
4895 item_count = avio_rb16(pb);
4897 for (i = 0; i < item_count; i++) {
4899 MOVFragmentStreamInfo * frag_stream_info;
4900 uint32_t size = avio_rb32(pb);
4901 uint32_t duration = avio_rb32(pb);
4902 if (size & 0x80000000) {
4903 avpriv_request_sample(c->fc, "sidx reference_type 1");
4904 return AVERROR_PATCHWELCOME;
4906 avio_rb32(pb); // sap_flags
4907 timestamp = av_rescale_q(pts, st->time_base, timescale);
4909 index = update_frag_index(c, offset);
4910 frag_stream_info = get_frag_stream_info(&c->frag_index, index, track_id);
4911 if (frag_stream_info)
4912 frag_stream_info->sidx_pts = timestamp;
4918 st->duration = sc->track_end = pts;
4922 if (offset == avio_size(pb)) {
4923 // Find first entry in fragment index that came from an sidx.
4924 // This will pretty much always be the first entry.
4925 for (i = 0; i < c->frag_index.nb_items; i++) {
4926 MOVFragmentIndexItem * item = &c->frag_index.item[i];
4927 for (j = 0; ref_st == NULL && j < item->nb_stream_info; j++) {
4928 MOVFragmentStreamInfo * si;
4929 si = &item->stream_info[j];
4930 if (si->sidx_pts != AV_NOPTS_VALUE) {
4931 ref_st = c->fc->streams[j];
4932 ref_sc = ref_st->priv_data;
4937 for (i = 0; i < c->fc->nb_streams; i++) {
4938 st = c->fc->streams[i];
4940 if (!sc->has_sidx) {
4941 st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
4945 c->frag_index.complete = 1;
4951 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
4952 /* like the files created with Adobe Premiere 5.0, for samples see */
4953 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
4954 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4959 return 0; /* continue */
4960 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
4961 avio_skip(pb, atom.size - 4);
4964 atom.type = avio_rl32(pb);
4966 if (atom.type != MKTAG('m','d','a','t')) {
4967 avio_skip(pb, atom.size);
4970 err = mov_read_mdat(c, pb, atom);
4974 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4979 uint8_t *moov_data; /* uncompressed data */
4980 long cmov_len, moov_len;
4983 avio_rb32(pb); /* dcom atom */
4984 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
4985 return AVERROR_INVALIDDATA;
4986 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
4987 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
4988 return AVERROR_INVALIDDATA;
4990 avio_rb32(pb); /* cmvd atom */
4991 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
4992 return AVERROR_INVALIDDATA;
4993 moov_len = avio_rb32(pb); /* uncompressed size */
4994 cmov_len = atom.size - 6 * 4;
4996 cmov_data = av_malloc(cmov_len);
4998 return AVERROR(ENOMEM);
4999 moov_data = av_malloc(moov_len);
5002 return AVERROR(ENOMEM);
5004 ret = ffio_read_size(pb, cmov_data, cmov_len);
5006 goto free_and_return;
5008 ret = AVERROR_INVALIDDATA;
5009 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
5010 goto free_and_return;
5011 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
5012 goto free_and_return;
5013 ctx.seekable = AVIO_SEEKABLE_NORMAL;
5014 atom.type = MKTAG('m','o','o','v');
5015 atom.size = moov_len;
5016 ret = mov_read_default(c, &ctx, atom);
5022 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
5023 return AVERROR(ENOSYS);
5027 /* edit list atom */
5028 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5030 MOVStreamContext *sc;
5031 int i, edit_count, version;
5032 int64_t elst_entry_size;
5034 if (c->fc->nb_streams < 1 || c->ignore_editlist)
5036 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
5038 version = avio_r8(pb); /* version */
5039 avio_rb24(pb); /* flags */
5040 edit_count = avio_rb32(pb); /* entries */
5043 elst_entry_size = version == 1 ? 20 : 12;
5044 if (atom.size != edit_count * elst_entry_size) {
5045 if (c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
5046 av_log(c->fc, AV_LOG_ERROR, "Invalid edit list entry_count: %d for elst atom of size: %"PRId64" bytes.\n",
5047 edit_count, atom.size + 8);
5048 return AVERROR_INVALIDDATA;
5050 edit_count = atom.size / elst_entry_size;
5051 if (edit_count * elst_entry_size != atom.size) {
5052 av_log(c->fc, AV_LOG_WARNING, "ELST atom of %"PRId64" bytes, bigger than %d entries.", atom.size, edit_count);
5060 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
5061 av_free(sc->elst_data);
5063 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
5065 return AVERROR(ENOMEM);
5067 av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
5068 for (i = 0; i < edit_count && atom.size > 0 && !pb->eof_reached; i++) {
5069 MOVElst *e = &sc->elst_data[i];
5072 e->duration = avio_rb64(pb);
5073 e->time = avio_rb64(pb);
5076 e->duration = avio_rb32(pb); /* segment duration */
5077 e->time = (int32_t)avio_rb32(pb); /* media time */
5080 e->rate = avio_rb32(pb) / 65536.0;
5082 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
5083 e->duration, e->time, e->rate);
5085 if (e->time < 0 && e->time != -1 &&
5086 c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
5087 av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
5088 c->fc->nb_streams-1, i, e->time);
5089 return AVERROR_INVALIDDATA;
5097 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5099 MOVStreamContext *sc;
5101 if (c->fc->nb_streams < 1)
5102 return AVERROR_INVALIDDATA;
5103 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5104 sc->timecode_track = avio_rb32(pb);
5108 static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5111 int version, color_range, color_primaries, color_trc, color_space;
5113 if (c->fc->nb_streams < 1)
5115 st = c->fc->streams[c->fc->nb_streams - 1];
5117 if (atom.size < 5) {
5118 av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
5119 return AVERROR_INVALIDDATA;
5122 version = avio_r8(pb);
5124 av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
5127 avio_skip(pb, 3); /* flags */
5129 avio_skip(pb, 2); /* profile + level */
5130 color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
5131 color_primaries = avio_r8(pb);
5132 color_trc = avio_r8(pb);
5133 color_space = avio_r8(pb);
5134 if (avio_rb16(pb)) /* codecIntializationDataSize */
5135 return AVERROR_INVALIDDATA;
5137 if (!av_color_primaries_name(color_primaries))
5138 color_primaries = AVCOL_PRI_UNSPECIFIED;
5139 if (!av_color_transfer_name(color_trc))
5140 color_trc = AVCOL_TRC_UNSPECIFIED;
5141 if (!av_color_space_name(color_space))
5142 color_space = AVCOL_SPC_UNSPECIFIED;
5144 st->codecpar->color_range = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
5145 st->codecpar->color_primaries = color_primaries;
5146 st->codecpar->color_trc = color_trc;
5147 st->codecpar->color_space = color_space;
5152 static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5154 MOVStreamContext *sc;
5155 const int chroma_den = 50000;
5156 const int luma_den = 10000;
5159 if (c->fc->nb_streams < 1)
5160 return AVERROR_INVALIDDATA;
5162 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5164 if (atom.size < 5) {
5165 av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
5166 return AVERROR_INVALIDDATA;
5169 version = avio_r8(pb);
5171 av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
5174 avio_skip(pb, 3); /* flags */
5176 sc->mastering = av_mastering_display_metadata_alloc();
5178 return AVERROR(ENOMEM);
5180 for (i = 0; i < 3; i++)
5181 for (j = 0; j < 2; j++)
5182 sc->mastering->display_primaries[i][j] =
5183 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5184 for (i = 0; i < 2; i++)
5185 sc->mastering->white_point[i] =
5186 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5187 sc->mastering->max_luminance =
5188 av_make_q(lrint(((double)avio_rb32(pb) / (1 << 8)) * luma_den), luma_den);
5189 sc->mastering->min_luminance =
5190 av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den);
5192 sc->mastering->has_primaries = 1;
5193 sc->mastering->has_luminance = 1;
5198 static int mov_read_mdcv(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5200 MOVStreamContext *sc;
5201 const int mapping[3] = {1, 2, 0};
5202 const int chroma_den = 50000;
5203 const int luma_den = 10000;
5206 if (c->fc->nb_streams < 1)
5207 return AVERROR_INVALIDDATA;
5209 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5211 if (atom.size < 24) {
5212 av_log(c->fc, AV_LOG_ERROR, "Invalid Mastering Display Color Volume box\n");
5213 return AVERROR_INVALIDDATA;
5216 sc->mastering = av_mastering_display_metadata_alloc();
5218 return AVERROR(ENOMEM);
5220 for (i = 0; i < 3; i++) {
5221 const int j = mapping[i];
5222 sc->mastering->display_primaries[j][0] = av_make_q(avio_rb16(pb), chroma_den);
5223 sc->mastering->display_primaries[j][1] = av_make_q(avio_rb16(pb), chroma_den);
5225 sc->mastering->white_point[0] = av_make_q(avio_rb16(pb), chroma_den);
5226 sc->mastering->white_point[1] = av_make_q(avio_rb16(pb), chroma_den);
5228 sc->mastering->max_luminance = av_make_q(avio_rb32(pb), luma_den);
5229 sc->mastering->min_luminance = av_make_q(avio_rb32(pb), luma_den);
5231 sc->mastering->has_luminance = 1;
5232 sc->mastering->has_primaries = 1;
5237 static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5239 MOVStreamContext *sc;
5242 if (c->fc->nb_streams < 1)
5243 return AVERROR_INVALIDDATA;
5245 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5247 if (atom.size < 5) {
5248 av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
5249 return AVERROR_INVALIDDATA;
5252 version = avio_r8(pb);
5254 av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
5257 avio_skip(pb, 3); /* flags */
5259 sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
5261 return AVERROR(ENOMEM);
5263 sc->coll->MaxCLL = avio_rb16(pb);
5264 sc->coll->MaxFALL = avio_rb16(pb);
5269 static int mov_read_clli(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5271 MOVStreamContext *sc;
5273 if (c->fc->nb_streams < 1)
5274 return AVERROR_INVALIDDATA;
5276 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5278 if (atom.size < 4) {
5279 av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level Info box\n");
5280 return AVERROR_INVALIDDATA;
5283 sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
5285 return AVERROR(ENOMEM);
5287 sc->coll->MaxCLL = avio_rb16(pb);
5288 sc->coll->MaxFALL = avio_rb16(pb);
5293 static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5296 MOVStreamContext *sc;
5297 enum AVStereo3DType type;
5300 if (c->fc->nb_streams < 1)
5303 st = c->fc->streams[c->fc->nb_streams - 1];
5306 if (atom.size < 5) {
5307 av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
5308 return AVERROR_INVALIDDATA;
5310 avio_skip(pb, 4); /* version + flags */
5315 type = AV_STEREO3D_2D;
5318 type = AV_STEREO3D_TOPBOTTOM;
5321 type = AV_STEREO3D_SIDEBYSIDE;
5324 av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
5328 sc->stereo3d = av_stereo3d_alloc();
5330 return AVERROR(ENOMEM);
5332 sc->stereo3d->type = type;
5336 static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5339 MOVStreamContext *sc;
5340 int size, version, layout;
5341 int32_t yaw, pitch, roll;
5342 uint32_t l = 0, t = 0, r = 0, b = 0;
5343 uint32_t tag, padding = 0;
5344 enum AVSphericalProjection projection;
5346 if (c->fc->nb_streams < 1)
5349 st = c->fc->streams[c->fc->nb_streams - 1];
5352 if (atom.size < 8) {
5353 av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
5354 return AVERROR_INVALIDDATA;
5357 size = avio_rb32(pb);
5358 if (size <= 12 || size > atom.size)
5359 return AVERROR_INVALIDDATA;
5361 tag = avio_rl32(pb);
5362 if (tag != MKTAG('s','v','h','d')) {
5363 av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
5366 version = avio_r8(pb);
5368 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5372 avio_skip(pb, 3); /* flags */
5373 avio_skip(pb, size - 12); /* metadata_source */
5375 size = avio_rb32(pb);
5376 if (size > atom.size)
5377 return AVERROR_INVALIDDATA;
5379 tag = avio_rl32(pb);
5380 if (tag != MKTAG('p','r','o','j')) {
5381 av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
5385 size = avio_rb32(pb);
5386 if (size > atom.size)
5387 return AVERROR_INVALIDDATA;
5389 tag = avio_rl32(pb);
5390 if (tag != MKTAG('p','r','h','d')) {
5391 av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
5394 version = avio_r8(pb);
5396 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5400 avio_skip(pb, 3); /* flags */
5402 /* 16.16 fixed point */
5403 yaw = avio_rb32(pb);
5404 pitch = avio_rb32(pb);
5405 roll = avio_rb32(pb);
5407 size = avio_rb32(pb);
5408 if (size > atom.size)
5409 return AVERROR_INVALIDDATA;
5411 tag = avio_rl32(pb);
5412 version = avio_r8(pb);
5414 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5418 avio_skip(pb, 3); /* flags */
5420 case MKTAG('c','b','m','p'):
5421 layout = avio_rb32(pb);
5423 av_log(c->fc, AV_LOG_WARNING,
5424 "Unsupported cubemap layout %d\n", layout);
5427 projection = AV_SPHERICAL_CUBEMAP;
5428 padding = avio_rb32(pb);
5430 case MKTAG('e','q','u','i'):
5436 if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
5437 av_log(c->fc, AV_LOG_ERROR,
5438 "Invalid bounding rectangle coordinates "
5439 "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
5440 return AVERROR_INVALIDDATA;
5443 if (l || t || r || b)
5444 projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
5446 projection = AV_SPHERICAL_EQUIRECTANGULAR;
5449 av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n");
5453 sc->spherical = av_spherical_alloc(&sc->spherical_size);
5455 return AVERROR(ENOMEM);
5457 sc->spherical->projection = projection;
5459 sc->spherical->yaw = yaw;
5460 sc->spherical->pitch = pitch;
5461 sc->spherical->roll = roll;
5463 sc->spherical->padding = padding;
5465 sc->spherical->bound_left = l;
5466 sc->spherical->bound_top = t;
5467 sc->spherical->bound_right = r;
5468 sc->spherical->bound_bottom = b;
5473 static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
5476 uint8_t *buffer = av_malloc(len + 1);
5480 return AVERROR(ENOMEM);
5483 ret = ffio_read_size(pb, buffer, len);
5487 /* Check for mandatory keys and values, try to support XML as best-effort */
5488 if (!sc->spherical &&
5489 av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
5490 (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
5491 av_stristr(val, "true") &&
5492 (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
5493 av_stristr(val, "true") &&
5494 (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
5495 av_stristr(val, "equirectangular")) {
5496 sc->spherical = av_spherical_alloc(&sc->spherical_size);
5500 sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
5502 if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
5503 enum AVStereo3DType mode;
5505 if (av_stristr(buffer, "left-right"))
5506 mode = AV_STEREO3D_SIDEBYSIDE;
5507 else if (av_stristr(buffer, "top-bottom"))
5508 mode = AV_STEREO3D_TOPBOTTOM;
5510 mode = AV_STEREO3D_2D;
5512 sc->stereo3d = av_stereo3d_alloc();
5516 sc->stereo3d->type = mode;
5520 val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
5522 sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
5523 val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
5525 sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
5526 val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
5528 sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
5536 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5539 MOVStreamContext *sc;
5542 static const uint8_t uuid_isml_manifest[] = {
5543 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
5544 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
5546 static const uint8_t uuid_xmp[] = {
5547 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
5548 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
5550 static const uint8_t uuid_spherical[] = {
5551 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
5552 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
5555 if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
5556 return AVERROR_INVALIDDATA;
5558 if (c->fc->nb_streams < 1)
5560 st = c->fc->streams[c->fc->nb_streams - 1];
5563 ret = avio_read(pb, uuid, sizeof(uuid));
5566 } else if (ret != sizeof(uuid)) {
5567 return AVERROR_INVALIDDATA;
5569 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
5570 uint8_t *buffer, *ptr;
5572 size_t len = atom.size - sizeof(uuid);
5575 return AVERROR_INVALIDDATA;
5577 ret = avio_skip(pb, 4); // zeroes
5580 buffer = av_mallocz(len + 1);
5582 return AVERROR(ENOMEM);
5584 ret = avio_read(pb, buffer, len);
5588 } else if (ret != len) {
5590 return AVERROR_INVALIDDATA;
5594 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
5595 ptr += sizeof("systemBitrate=\"") - 1;
5596 c->bitrates_count++;
5597 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
5599 c->bitrates_count = 0;
5601 return AVERROR(ENOMEM);
5604 ret = strtol(ptr, &endptr, 10);
5605 if (ret < 0 || errno || *endptr != '"') {
5606 c->bitrates[c->bitrates_count - 1] = 0;
5608 c->bitrates[c->bitrates_count - 1] = ret;
5613 } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
5615 size_t len = atom.size - sizeof(uuid);
5616 if (c->export_xmp) {
5617 buffer = av_mallocz(len + 1);
5619 return AVERROR(ENOMEM);
5621 ret = avio_read(pb, buffer, len);
5625 } else if (ret != len) {
5627 return AVERROR_INVALIDDATA;
5630 av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
5633 // skip all uuid atom, which makes it fast for long uuid-xmp file
5634 ret = avio_skip(pb, len);
5638 } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
5639 size_t len = atom.size - sizeof(uuid);
5640 ret = mov_parse_uuid_spherical(sc, pb, len);
5644 av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
5650 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5653 uint8_t content[16];
5658 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
5664 && !memcmp(content, "Anevia\x1A\x1A", 8)
5665 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
5666 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
5672 static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5674 uint32_t format = avio_rl32(pb);
5675 MOVStreamContext *sc;
5679 if (c->fc->nb_streams < 1)
5681 st = c->fc->streams[c->fc->nb_streams - 1];
5686 case MKTAG('e','n','c','v'): // encrypted video
5687 case MKTAG('e','n','c','a'): // encrypted audio
5688 id = mov_codec_id(st, format);
5689 if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
5690 st->codecpar->codec_id != id) {
5691 av_log(c->fc, AV_LOG_WARNING,
5692 "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
5693 (char*)&format, st->codecpar->codec_id);
5697 st->codecpar->codec_id = id;
5698 sc->format = format;
5702 if (format != sc->format) {
5703 av_log(c->fc, AV_LOG_WARNING,
5704 "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
5705 (char*)&format, (char*)&sc->format);
5713 static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5716 MOVStreamContext *sc;
5717 size_t auxiliary_info_size;
5719 if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5722 st = c->fc->streams[c->fc->nb_streams - 1];
5725 if (sc->cenc.aes_ctr) {
5726 av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
5727 return AVERROR_INVALIDDATA;
5730 avio_r8(pb); /* version */
5731 sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
5733 avio_rb32(pb); /* entries */
5735 if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5736 av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size);
5737 return AVERROR_INVALIDDATA;
5740 /* save the auxiliary info as is */
5741 auxiliary_info_size = atom.size - 8;
5743 sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
5744 if (!sc->cenc.auxiliary_info) {
5745 return AVERROR(ENOMEM);
5748 sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
5749 sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
5750 sc->cenc.auxiliary_info_index = 0;
5752 if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
5753 av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
5754 return AVERROR_INVALIDDATA;
5757 /* initialize the cipher */
5758 sc->cenc.aes_ctr = av_aes_ctr_alloc();
5759 if (!sc->cenc.aes_ctr) {
5760 return AVERROR(ENOMEM);
5763 return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
5766 static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5769 MOVStreamContext *sc;
5771 int atom_header_size;
5774 if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5777 st = c->fc->streams[c->fc->nb_streams - 1];
5780 if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
5781 av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
5782 return AVERROR_INVALIDDATA;
5785 atom_header_size = 9;
5787 avio_r8(pb); /* version */
5788 flags = avio_rb24(pb);
5790 if ((flags & 0x01) != 0) {
5791 atom_header_size += 8;
5793 avio_rb32(pb); /* info type */
5794 avio_rb32(pb); /* info type param */
5797 sc->cenc.auxiliary_info_default_size = avio_r8(pb);
5798 avio_rb32(pb); /* entries */
5800 if (atom.size <= atom_header_size) {
5804 if (atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5805 av_log(c->fc, AV_LOG_ERROR, "saiz atom auxiliary_info_sizes size %"PRId64" invalid\n", atom.size);
5806 return AVERROR_INVALIDDATA;
5809 /* save the auxiliary info sizes as is */
5810 data_size = atom.size - atom_header_size;
5812 sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
5813 if (!sc->cenc.auxiliary_info_sizes) {
5814 return AVERROR(ENOMEM);
5817 sc->cenc.auxiliary_info_sizes_count = data_size;
5819 if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
5820 av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
5821 return AVERROR_INVALIDDATA;
5827 static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5830 int last, type, size, ret;
5833 if (c->fc->nb_streams < 1)
5835 st = c->fc->streams[c->fc->nb_streams-1];
5837 if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
5838 return AVERROR_INVALIDDATA;
5840 /* Check FlacSpecificBox version. */
5841 if (avio_r8(pb) != 0)
5842 return AVERROR_INVALIDDATA;
5844 avio_rb24(pb); /* Flags */
5846 avio_read(pb, buf, sizeof(buf));
5847 flac_parse_block_header(buf, &last, &type, &size);
5849 if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
5850 av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
5851 return AVERROR_INVALIDDATA;
5854 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
5859 av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
5864 static int mov_seek_auxiliary_info(MOVContext *c, MOVStreamContext *sc, int64_t index)
5866 size_t auxiliary_info_seek_offset = 0;
5869 if (sc->cenc.auxiliary_info_default_size) {
5870 auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * index;
5871 } else if (sc->cenc.auxiliary_info_sizes) {
5872 if (index > sc->cenc.auxiliary_info_sizes_count) {
5873 av_log(c, AV_LOG_ERROR, "current sample %"PRId64" greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
5874 index, sc->cenc.auxiliary_info_sizes_count);
5875 return AVERROR_INVALIDDATA;
5878 for (i = 0; i < index; i++) {
5879 auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
5883 if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
5884 av_log(c, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
5885 auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
5886 return AVERROR_INVALIDDATA;
5889 sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
5890 sc->cenc.auxiliary_info_index = index;
5894 static int cenc_filter(MOVContext *c, MOVStreamContext *sc, int64_t index, uint8_t *input, int size)
5896 uint32_t encrypted_bytes;
5897 uint16_t subsample_count;
5898 uint16_t clear_bytes;
5899 uint8_t* input_end = input + size;
5902 if (index != sc->cenc.auxiliary_info_index) {
5903 ret = mov_seek_auxiliary_info(c, sc, index);
5910 if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5911 av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
5912 return AVERROR_INVALIDDATA;
5915 av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
5916 sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
5918 if (!sc->cenc.use_subsamples)
5920 /* decrypt the whole packet */
5921 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
5925 /* read the subsample count */
5926 if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5927 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
5928 return AVERROR_INVALIDDATA;
5931 subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
5932 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5934 for (; subsample_count > 0; subsample_count--)
5936 if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5937 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
5938 return AVERROR_INVALIDDATA;
5941 /* read the number of clear / encrypted bytes */
5942 clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
5943 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5944 encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
5945 sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
5947 if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
5948 av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
5949 return AVERROR_INVALIDDATA;
5952 /* skip the clear bytes */
5953 input += clear_bytes;
5955 /* decrypt the encrypted bytes */
5956 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
5957 input += encrypted_bytes;
5960 if (input < input_end) {
5961 av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
5962 return AVERROR_INVALIDDATA;
5965 sc->cenc.auxiliary_info_index++;
5969 static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5971 const int OPUS_SEEK_PREROLL_MS = 80;
5976 if (c->fc->nb_streams < 1)
5978 st = c->fc->streams[c->fc->nb_streams-1];
5980 if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
5981 return AVERROR_INVALIDDATA;
5983 /* Check OpusSpecificBox version. */
5984 if (avio_r8(pb) != 0) {
5985 av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
5986 return AVERROR_INVALIDDATA;
5989 /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
5990 size = atom.size + 8;
5992 if (ff_alloc_extradata(st->codecpar, size))
5993 return AVERROR(ENOMEM);
5995 AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
5996 AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
5997 AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
5998 avio_read(pb, st->codecpar->extradata + 9, size - 9);
6000 /* OpusSpecificBox is stored in big-endian, but OpusHead is
6001 little-endian; aside from the preceeding magic and version they're
6002 otherwise currently identical. Data after output gain at offset 16
6003 doesn't need to be bytewapped. */
6004 pre_skip = AV_RB16(st->codecpar->extradata + 10);
6005 AV_WL16(st->codecpar->extradata + 10, pre_skip);
6006 AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
6007 AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
6009 st->codecpar->initial_padding = pre_skip;
6010 st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
6011 (AVRational){1, 1000},
6012 (AVRational){1, 48000});
6017 static const MOVParseTableEntry mov_default_parse_table[] = {
6018 { MKTAG('A','C','L','R'), mov_read_aclr },
6019 { MKTAG('A','P','R','G'), mov_read_avid },
6020 { MKTAG('A','A','L','P'), mov_read_avid },
6021 { MKTAG('A','R','E','S'), mov_read_ares },
6022 { MKTAG('a','v','s','s'), mov_read_avss },
6023 { MKTAG('c','h','p','l'), mov_read_chpl },
6024 { MKTAG('c','o','6','4'), mov_read_stco },
6025 { MKTAG('c','o','l','r'), mov_read_colr },
6026 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
6027 { MKTAG('d','i','n','f'), mov_read_default },
6028 { MKTAG('D','p','x','E'), mov_read_dpxe },
6029 { MKTAG('d','r','e','f'), mov_read_dref },
6030 { MKTAG('e','d','t','s'), mov_read_default },
6031 { MKTAG('e','l','s','t'), mov_read_elst },
6032 { MKTAG('e','n','d','a'), mov_read_enda },
6033 { MKTAG('f','i','e','l'), mov_read_fiel },
6034 { MKTAG('a','d','r','m'), mov_read_adrm },
6035 { MKTAG('f','t','y','p'), mov_read_ftyp },
6036 { MKTAG('g','l','b','l'), mov_read_glbl },
6037 { MKTAG('h','d','l','r'), mov_read_hdlr },
6038 { MKTAG('i','l','s','t'), mov_read_ilst },
6039 { MKTAG('j','p','2','h'), mov_read_jp2h },
6040 { MKTAG('m','d','a','t'), mov_read_mdat },
6041 { MKTAG('m','d','h','d'), mov_read_mdhd },
6042 { MKTAG('m','d','i','a'), mov_read_default },
6043 { MKTAG('m','e','t','a'), mov_read_meta },
6044 { MKTAG('m','i','n','f'), mov_read_default },
6045 { MKTAG('m','o','o','f'), mov_read_moof },
6046 { MKTAG('m','o','o','v'), mov_read_moov },
6047 { MKTAG('m','v','e','x'), mov_read_default },
6048 { MKTAG('m','v','h','d'), mov_read_mvhd },
6049 { MKTAG('S','M','I',' '), mov_read_svq3 },
6050 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
6051 { MKTAG('a','v','c','C'), mov_read_glbl },
6052 { MKTAG('p','a','s','p'), mov_read_pasp },
6053 { MKTAG('s','i','d','x'), mov_read_sidx },
6054 { MKTAG('s','t','b','l'), mov_read_default },
6055 { MKTAG('s','t','c','o'), mov_read_stco },
6056 { MKTAG('s','t','p','s'), mov_read_stps },
6057 { MKTAG('s','t','r','f'), mov_read_strf },
6058 { MKTAG('s','t','s','c'), mov_read_stsc },
6059 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
6060 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
6061 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
6062 { MKTAG('s','t','t','s'), mov_read_stts },
6063 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
6064 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
6065 { MKTAG('t','f','d','t'), mov_read_tfdt },
6066 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
6067 { MKTAG('t','r','a','k'), mov_read_trak },
6068 { MKTAG('t','r','a','f'), mov_read_default },
6069 { MKTAG('t','r','e','f'), mov_read_default },
6070 { MKTAG('t','m','c','d'), mov_read_tmcd },
6071 { MKTAG('c','h','a','p'), mov_read_chap },
6072 { MKTAG('t','r','e','x'), mov_read_trex },
6073 { MKTAG('t','r','u','n'), mov_read_trun },
6074 { MKTAG('u','d','t','a'), mov_read_default },
6075 { MKTAG('w','a','v','e'), mov_read_wave },
6076 { MKTAG('e','s','d','s'), mov_read_esds },
6077 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
6078 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
6079 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
6080 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
6081 { MKTAG('w','f','e','x'), mov_read_wfex },
6082 { MKTAG('c','m','o','v'), mov_read_cmov },
6083 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
6084 { MKTAG('d','v','c','1'), mov_read_dvc1 },
6085 { MKTAG('s','b','g','p'), mov_read_sbgp },
6086 { MKTAG('h','v','c','C'), mov_read_glbl },
6087 { MKTAG('u','u','i','d'), mov_read_uuid },
6088 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
6089 { MKTAG('f','r','e','e'), mov_read_free },
6090 { MKTAG('-','-','-','-'), mov_read_custom },
6091 { MKTAG('s','i','n','f'), mov_read_default },
6092 { MKTAG('f','r','m','a'), mov_read_frma },
6093 { MKTAG('s','e','n','c'), mov_read_senc },
6094 { MKTAG('s','a','i','z'), mov_read_saiz },
6095 { MKTAG('d','f','L','a'), mov_read_dfla },
6096 { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
6097 { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
6098 { MKTAG('d','O','p','s'), mov_read_dops },
6099 { MKTAG('S','m','D','m'), mov_read_smdm },
6100 { MKTAG('C','o','L','L'), mov_read_coll },
6101 { MKTAG('v','p','c','C'), mov_read_vpcc },
6102 { MKTAG('m','d','c','v'), mov_read_mdcv },
6103 { MKTAG('c','l','l','i'), mov_read_clli },
6107 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6109 int64_t total_size = 0;
6113 if (c->atom_depth > 10) {
6114 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
6115 return AVERROR_INVALIDDATA;
6120 atom.size = INT64_MAX;
6121 while (total_size <= atom.size - 8 && !avio_feof(pb)) {
6122 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
6125 if (atom.size >= 8) {
6126 a.size = avio_rb32(pb);
6127 a.type = avio_rl32(pb);
6128 if (a.type == MKTAG('f','r','e','e') &&
6130 c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
6133 uint32_t *type = (uint32_t *)buf + 1;
6134 if (avio_read(pb, buf, 8) != 8)
6135 return AVERROR_INVALIDDATA;
6136 avio_seek(pb, -8, SEEK_CUR);
6137 if (*type == MKTAG('m','v','h','d') ||
6138 *type == MKTAG('c','m','o','v')) {
6139 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
6140 a.type = MKTAG('m','o','o','v');
6143 if (atom.type != MKTAG('r','o','o','t') &&
6144 atom.type != MKTAG('m','o','o','v'))
6146 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
6148 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
6155 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
6156 a.size = avio_rb64(pb) - 8;
6160 av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
6161 av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
6163 a.size = atom.size - total_size + 8;
6168 a.size = FFMIN(a.size, atom.size - total_size);
6170 for (i = 0; mov_default_parse_table[i].type; i++)
6171 if (mov_default_parse_table[i].type == a.type) {
6172 parse = mov_default_parse_table[i].parse;
6176 // container is user data
6177 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
6178 atom.type == MKTAG('i','l','s','t')))
6179 parse = mov_read_udta_string;
6181 // Supports parsing the QuickTime Metadata Keys.
6182 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
6183 if (!parse && c->found_hdlr_mdta &&
6184 atom.type == MKTAG('m','e','t','a') &&
6185 a.type == MKTAG('k','e','y','s')) {
6186 parse = mov_read_keys;
6189 if (!parse) { /* skip leaf atoms data */
6190 avio_skip(pb, a.size);
6192 int64_t start_pos = avio_tell(pb);
6194 int err = parse(c, pb, a);
6199 if (c->found_moov && c->found_mdat &&
6200 ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete) ||
6201 start_pos + a.size == avio_size(pb))) {
6202 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete)
6203 c->next_root_atom = start_pos + a.size;
6207 left = a.size - avio_tell(pb) + start_pos;
6208 if (left > 0) /* skip garbage at atom end */
6209 avio_skip(pb, left);
6210 else if (left < 0) {
6211 av_log(c->fc, AV_LOG_WARNING,
6212 "overread end of atom '%.4s' by %"PRId64" bytes\n",
6213 (char*)&a.type, -left);
6214 avio_seek(pb, left, SEEK_CUR);
6218 total_size += a.size;
6221 if (total_size < atom.size && atom.size < 0x7ffff)
6222 avio_skip(pb, atom.size - total_size);
6228 static int mov_probe(AVProbeData *p)
6233 int moov_offset = -1;
6235 /* check file header */
6238 /* ignore invalid offset */
6239 if ((offset + 8) > (unsigned int)p->buf_size)
6241 tag = AV_RL32(p->buf + offset + 4);
6243 /* check for obvious tags */
6244 case MKTAG('m','o','o','v'):
6245 moov_offset = offset + 4;
6246 case MKTAG('m','d','a','t'):
6247 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
6248 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
6249 case MKTAG('f','t','y','p'):
6250 if (AV_RB32(p->buf+offset) < 8 &&
6251 (AV_RB32(p->buf+offset) != 1 ||
6252 offset + 12 > (unsigned int)p->buf_size ||
6253 AV_RB64(p->buf+offset + 8) == 0)) {
6254 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6255 } else if (tag == MKTAG('f','t','y','p') &&
6256 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
6257 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
6259 score = FFMAX(score, 5);
6261 score = AVPROBE_SCORE_MAX;
6263 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6265 /* those are more common words, so rate then a bit less */
6266 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
6267 case MKTAG('w','i','d','e'):
6268 case MKTAG('f','r','e','e'):
6269 case MKTAG('j','u','n','k'):
6270 case MKTAG('p','i','c','t'):
6271 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
6272 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6274 case MKTAG(0x82,0x82,0x7f,0x7d):
6275 case MKTAG('s','k','i','p'):
6276 case MKTAG('u','u','i','d'):
6277 case MKTAG('p','r','f','l'):
6278 /* if we only find those cause probedata is too small at least rate them */
6279 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6280 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6283 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6286 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
6287 /* moov atom in the header - we should make sure that this is not a
6288 * MOV-packed MPEG-PS */
6289 offset = moov_offset;
6291 while(offset < (p->buf_size - 16)){ /* Sufficient space */
6292 /* We found an actual hdlr atom */
6293 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
6294 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
6295 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
6296 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
6297 /* We found a media handler reference atom describing an
6298 * MPEG-PS-in-MOV, return a
6299 * low score to force expanding the probe window until
6300 * mpegps_probe finds what it needs */
6311 // must be done after parsing all trak because there's no order requirement
6312 static void mov_read_chapters(AVFormatContext *s)
6314 MOVContext *mov = s->priv_data;
6316 MOVStreamContext *sc;
6321 for (j = 0; j < mov->nb_chapter_tracks; j++) {
6322 chapter_track = mov->chapter_tracks[j];
6324 for (i = 0; i < s->nb_streams; i++)
6325 if (s->streams[i]->id == chapter_track) {
6330 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
6335 cur_pos = avio_tell(sc->pb);
6337 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6338 st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
6339 if (st->nb_index_entries) {
6340 // Retrieve the first frame, if possible
6342 AVIndexEntry *sample = &st->index_entries[0];
6343 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6344 av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
6348 if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
6351 st->attached_pic = pkt;
6352 st->attached_pic.stream_index = st->index;
6353 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
6356 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
6357 st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
6358 st->discard = AVDISCARD_ALL;
6359 for (i = 0; i < st->nb_index_entries; i++) {
6360 AVIndexEntry *sample = &st->index_entries[i];
6361 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
6366 if (end < sample->timestamp) {
6367 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
6368 end = AV_NOPTS_VALUE;
6371 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6372 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
6376 // the first two bytes are the length of the title
6377 len = avio_rb16(sc->pb);
6378 if (len > sample->size-2)
6380 title_len = 2*len + 1;
6381 if (!(title = av_mallocz(title_len)))
6384 // The samples could theoretically be in any encoding if there's an encd
6385 // atom following, but in practice are only utf-8 or utf-16, distinguished
6386 // instead by the presence of a BOM
6390 ch = avio_rb16(sc->pb);
6392 avio_get_str16be(sc->pb, len, title, title_len);
6393 else if (ch == 0xfffe)
6394 avio_get_str16le(sc->pb, len, title, title_len);
6397 if (len == 1 || len == 2)
6400 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
6404 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
6409 avio_seek(sc->pb, cur_pos, SEEK_SET);
6413 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
6414 uint32_t value, int flags)
6417 char buf[AV_TIMECODE_STR_SIZE];
6418 AVRational rate = st->avg_frame_rate;
6419 int ret = av_timecode_init(&tc, rate, flags, 0, s);
6422 av_dict_set(&st->metadata, "timecode",
6423 av_timecode_make_string(&tc, buf, value), 0);
6427 static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
6429 MOVStreamContext *sc = st->priv_data;
6430 char buf[AV_TIMECODE_STR_SIZE];
6431 int64_t cur_pos = avio_tell(sc->pb);
6432 int hh, mm, ss, ff, drop;
6434 if (!st->nb_index_entries)
6437 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6438 avio_skip(s->pb, 13);
6439 hh = avio_r8(s->pb);
6440 mm = avio_r8(s->pb);
6441 ss = avio_r8(s->pb);
6442 drop = avio_r8(s->pb);
6443 ff = avio_r8(s->pb);
6444 snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
6445 hh, mm, ss, drop ? ';' : ':', ff);
6446 av_dict_set(&st->metadata, "timecode", buf, 0);
6448 avio_seek(sc->pb, cur_pos, SEEK_SET);
6452 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
6454 MOVStreamContext *sc = st->priv_data;
6456 int64_t cur_pos = avio_tell(sc->pb);
6459 if (!st->nb_index_entries)
6462 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6463 value = avio_rb32(s->pb);
6465 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
6466 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
6467 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
6469 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
6470 * not the case) and thus assume "frame number format" instead of QT one.
6471 * No sample with tmcd track can be found with a QT timecode at the moment,
6472 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
6474 parse_timecode_in_framenum_format(s, st, value, flags);
6476 avio_seek(sc->pb, cur_pos, SEEK_SET);
6480 static int mov_read_close(AVFormatContext *s)
6482 MOVContext *mov = s->priv_data;
6485 for (i = 0; i < s->nb_streams; i++) {
6486 AVStream *st = s->streams[i];
6487 MOVStreamContext *sc = st->priv_data;
6492 av_freep(&sc->ctts_data);
6493 for (j = 0; j < sc->drefs_count; j++) {
6494 av_freep(&sc->drefs[j].path);
6495 av_freep(&sc->drefs[j].dir);
6497 av_freep(&sc->drefs);
6499 sc->drefs_count = 0;
6501 if (!sc->pb_is_copied)
6502 ff_format_io_close(s, &sc->pb);
6505 av_freep(&sc->chunk_offsets);
6506 av_freep(&sc->stsc_data);
6507 av_freep(&sc->sample_sizes);
6508 av_freep(&sc->keyframes);
6509 av_freep(&sc->stts_data);
6510 av_freep(&sc->stps_data);
6511 av_freep(&sc->elst_data);
6512 av_freep(&sc->rap_group);
6513 av_freep(&sc->display_matrix);
6514 av_freep(&sc->index_ranges);
6517 for (j = 0; j < sc->stsd_count; j++)
6518 av_free(sc->extradata[j]);
6519 av_freep(&sc->extradata);
6520 av_freep(&sc->extradata_size);
6522 av_freep(&sc->cenc.auxiliary_info);
6523 av_freep(&sc->cenc.auxiliary_info_sizes);
6524 av_aes_ctr_free(sc->cenc.aes_ctr);
6526 av_freep(&sc->stereo3d);
6527 av_freep(&sc->spherical);
6528 av_freep(&sc->mastering);
6529 av_freep(&sc->coll);
6532 if (mov->dv_demux) {
6533 avformat_free_context(mov->dv_fctx);
6534 mov->dv_fctx = NULL;
6537 if (mov->meta_keys) {
6538 for (i = 1; i < mov->meta_keys_count; i++) {
6539 av_freep(&mov->meta_keys[i]);
6541 av_freep(&mov->meta_keys);
6544 av_freep(&mov->trex_data);
6545 av_freep(&mov->bitrates);
6547 for (i = 0; i < mov->frag_index.nb_items; i++) {
6548 av_freep(&mov->frag_index.item[i].stream_info);
6550 av_freep(&mov->frag_index.item);
6552 av_freep(&mov->aes_decrypt);
6553 av_freep(&mov->chapter_tracks);
6558 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
6562 for (i = 0; i < s->nb_streams; i++) {
6563 AVStream *st = s->streams[i];
6564 MOVStreamContext *sc = st->priv_data;
6566 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6567 sc->timecode_track == tmcd_id)
6573 /* look for a tmcd track not referenced by any video track, and export it globally */
6574 static void export_orphan_timecode(AVFormatContext *s)
6578 for (i = 0; i < s->nb_streams; i++) {
6579 AVStream *st = s->streams[i];
6581 if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
6582 !tmcd_is_referenced(s, i + 1)) {
6583 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
6585 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
6592 static int read_tfra(MOVContext *mov, AVIOContext *f)
6594 int version, fieldlength, i, j;
6595 int64_t pos = avio_tell(f);
6596 uint32_t size = avio_rb32(f);
6597 unsigned track_id, item_count;
6599 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
6602 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
6604 version = avio_r8(f);
6606 track_id = avio_rb32(f);
6607 fieldlength = avio_rb32(f);
6608 item_count = avio_rb32(f);
6609 for (i = 0; i < item_count; i++) {
6610 int64_t time, offset;
6612 MOVFragmentStreamInfo * frag_stream_info;
6615 return AVERROR_INVALIDDATA;
6619 time = avio_rb64(f);
6620 offset = avio_rb64(f);
6622 time = avio_rb32(f);
6623 offset = avio_rb32(f);
6626 // The first sample of each stream in a fragment is always a random
6627 // access sample. So it's entry in the tfra can be used as the
6628 // initial PTS of the fragment.
6629 index = update_frag_index(mov, offset);
6630 frag_stream_info = get_frag_stream_info(&mov->frag_index, index, track_id);
6631 if (frag_stream_info &&
6632 frag_stream_info->first_tfra_pts == AV_NOPTS_VALUE)
6633 frag_stream_info->first_tfra_pts = time;
6635 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
6637 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
6639 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
6643 avio_seek(f, pos + size, SEEK_SET);
6647 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
6649 int64_t stream_size = avio_size(f);
6650 int64_t original_pos = avio_tell(f);
6654 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
6658 mfra_size = avio_rb32(f);
6659 if (mfra_size < 0 || mfra_size > stream_size) {
6660 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
6663 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
6667 if (avio_rb32(f) != mfra_size) {
6668 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
6671 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
6672 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
6675 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
6677 ret = read_tfra(c, f);
6683 seek_ret = avio_seek(f, original_pos, SEEK_SET);
6685 av_log(c->fc, AV_LOG_ERROR,
6686 "failed to seek back after looking for mfra\n");
6692 static int mov_read_header(AVFormatContext *s)
6694 MOVContext *mov = s->priv_data;
6695 AVIOContext *pb = s->pb;
6697 MOVAtom atom = { AV_RL32("root") };
6700 if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
6701 av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
6702 mov->decryption_key_len, AES_CTR_KEY_SIZE);
6703 return AVERROR(EINVAL);
6707 mov->trak_index = -1;
6708 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
6709 if (pb->seekable & AVIO_SEEKABLE_NORMAL)
6710 atom.size = avio_size(pb);
6712 atom.size = INT64_MAX;
6714 /* check MOV header */
6716 if (mov->moov_retry)
6717 avio_seek(pb, 0, SEEK_SET);
6718 if ((err = mov_read_default(mov, pb, atom)) < 0) {
6719 av_log(s, AV_LOG_ERROR, "error reading header\n");
6723 } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
6724 if (!mov->found_moov) {
6725 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
6727 return AVERROR_INVALIDDATA;
6729 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
6731 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
6732 if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
6733 mov_read_chapters(s);
6734 for (i = 0; i < s->nb_streams; i++)
6735 if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
6736 mov_read_timecode_track(s, s->streams[i]);
6737 } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
6738 mov_read_rtmd_track(s, s->streams[i]);
6742 /* copy timecode metadata from tmcd tracks to the related video streams */
6743 for (i = 0; i < s->nb_streams; i++) {
6744 AVStream *st = s->streams[i];
6745 MOVStreamContext *sc = st->priv_data;
6746 if (sc->timecode_track > 0) {
6747 AVDictionaryEntry *tcr;
6748 int tmcd_st_id = -1;
6750 for (j = 0; j < s->nb_streams; j++)
6751 if (s->streams[j]->id == sc->timecode_track)
6754 if (tmcd_st_id < 0 || tmcd_st_id == i)
6756 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
6758 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
6761 export_orphan_timecode(s);
6763 for (i = 0; i < s->nb_streams; i++) {
6764 AVStream *st = s->streams[i];
6765 MOVStreamContext *sc = st->priv_data;
6766 fix_timescale(mov, sc);
6767 if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6768 st->skip_samples = sc->start_pad;
6770 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
6771 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
6772 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
6773 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6774 if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
6775 st->codecpar->width = sc->width;
6776 st->codecpar->height = sc->height;
6778 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
6779 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
6783 if (mov->handbrake_version &&
6784 mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
6785 st->codecpar->codec_id == AV_CODEC_ID_MP3
6787 av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
6788 st->need_parsing = AVSTREAM_PARSE_FULL;
6792 if (mov->trex_data) {
6793 for (i = 0; i < s->nb_streams; i++) {
6794 AVStream *st = s->streams[i];
6795 MOVStreamContext *sc = st->priv_data;
6796 if (st->duration > 0) {
6797 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6798 av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6799 sc->data_size, sc->time_scale);
6801 return AVERROR_INVALIDDATA;
6803 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
6808 if (mov->use_mfra_for > 0) {
6809 for (i = 0; i < s->nb_streams; i++) {
6810 AVStream *st = s->streams[i];
6811 MOVStreamContext *sc = st->priv_data;
6812 if (sc->duration_for_fps > 0) {
6813 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6814 av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6815 sc->data_size, sc->time_scale);
6817 return AVERROR_INVALIDDATA;
6819 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
6820 sc->duration_for_fps;
6825 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
6826 if (mov->bitrates[i]) {
6827 s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
6831 ff_rfps_calculate(s);
6833 for (i = 0; i < s->nb_streams; i++) {
6834 AVStream *st = s->streams[i];
6835 MOVStreamContext *sc = st->priv_data;
6837 switch (st->codecpar->codec_type) {
6838 case AVMEDIA_TYPE_AUDIO:
6839 err = ff_replaygain_export(st, s->metadata);
6845 case AVMEDIA_TYPE_VIDEO:
6846 if (sc->display_matrix) {
6847 err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix,
6848 sizeof(int32_t) * 9);
6852 sc->display_matrix = NULL;
6855 err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
6856 (uint8_t *)sc->stereo3d,
6857 sizeof(*sc->stereo3d));
6861 sc->stereo3d = NULL;
6863 if (sc->spherical) {
6864 err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
6865 (uint8_t *)sc->spherical,
6866 sc->spherical_size);
6870 sc->spherical = NULL;
6872 if (sc->mastering) {
6873 err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
6874 (uint8_t *)sc->mastering,
6875 sizeof(*sc->mastering));
6879 sc->mastering = NULL;
6882 err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
6883 (uint8_t *)sc->coll,
6893 ff_configure_buffers_for_index(s, AV_TIME_BASE);
6895 for (i = 0; i < mov->frag_index.nb_items; i++)
6896 if (mov->frag_index.item[i].moof_offset <= mov->fragment.moof_offset)
6897 mov->frag_index.item[i].headers_read = 1;
6902 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
6904 AVIndexEntry *sample = NULL;
6905 int64_t best_dts = INT64_MAX;
6907 for (i = 0; i < s->nb_streams; i++) {
6908 AVStream *avst = s->streams[i];
6909 MOVStreamContext *msc = avst->priv_data;
6910 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
6911 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
6912 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
6913 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
6914 if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
6915 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6916 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
6917 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
6918 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
6919 sample = current_sample;
6928 static int should_retry(AVIOContext *pb, int error_code) {
6929 if (error_code == AVERROR_EOF || avio_feof(pb))
6935 static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
6938 MOVContext *mov = s->priv_data;
6940 if (index >= 0 && index < mov->frag_index.nb_items)
6941 target = mov->frag_index.item[index].moof_offset;
6942 if (avio_seek(s->pb, target, SEEK_SET) != target) {
6943 av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
6944 return AVERROR_INVALIDDATA;
6947 mov->next_root_atom = 0;
6948 if (index < 0 || index >= mov->frag_index.nb_items)
6949 index = search_frag_moof_offset(&mov->frag_index, target);
6950 if (index < mov->frag_index.nb_items) {
6951 if (index + 1 < mov->frag_index.nb_items)
6952 mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
6953 if (mov->frag_index.item[index].headers_read)
6955 mov->frag_index.item[index].headers_read = 1;
6958 mov->found_mdat = 0;
6960 ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
6963 if (avio_feof(s->pb))
6965 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
6970 static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
6972 uint8_t *side, *extradata;
6975 /* Save the current index. */
6976 sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
6978 /* Notify the decoder that extradata changed. */
6979 extradata_size = sc->extradata_size[sc->last_stsd_index];
6980 extradata = sc->extradata[sc->last_stsd_index];
6981 if (extradata_size > 0 && extradata) {
6982 side = av_packet_new_side_data(pkt,
6983 AV_PKT_DATA_NEW_EXTRADATA,
6986 return AVERROR(ENOMEM);
6987 memcpy(side, extradata, extradata_size);
6993 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
6995 MOVContext *mov = s->priv_data;
6996 MOVStreamContext *sc;
6997 AVIndexEntry *sample;
6998 AVStream *st = NULL;
6999 int64_t current_index;
7003 sample = mov_find_next_sample(s, &st);
7004 if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
7005 if (!mov->next_root_atom)
7007 if ((ret = mov_switch_root(s, mov->next_root_atom, -1)) < 0)
7012 /* must be done just before reading, to avoid infinite loop on sample */
7013 current_index = sc->current_index;
7014 mov_current_sample_inc(sc);
7016 if (mov->next_root_atom) {
7017 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
7018 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
7021 if (st->discard != AVDISCARD_ALL) {
7022 int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
7023 if (ret64 != sample->pos) {
7024 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
7025 sc->ffindex, sample->pos);
7026 if (should_retry(sc->pb, ret64)) {
7027 mov_current_sample_dec(sc);
7029 return AVERROR_INVALIDDATA;
7032 if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
7033 av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
7037 ret = av_get_packet(sc->pb, pkt, sample->size);
7039 if (should_retry(sc->pb, ret)) {
7040 mov_current_sample_dec(sc);
7044 if (sc->has_palette) {
7047 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
7049 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
7051 memcpy(pal, sc->palette, AVPALETTE_SIZE);
7052 sc->has_palette = 0;
7055 #if CONFIG_DV_DEMUXER
7056 if (mov->dv_demux && sc->dv_audio_container) {
7057 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
7058 av_freep(&pkt->data);
7060 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
7065 if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
7066 if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
7067 st->need_parsing = AVSTREAM_PARSE_FULL;
7071 pkt->stream_index = sc->ffindex;
7072 pkt->dts = sample->timestamp;
7073 if (sample->flags & AVINDEX_DISCARD_FRAME) {
7074 pkt->flags |= AV_PKT_FLAG_DISCARD;
7076 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
7077 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
7078 /* update ctts context */
7080 if (sc->ctts_index < sc->ctts_count &&
7081 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
7083 sc->ctts_sample = 0;
7086 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
7087 st->index_entries[sc->current_sample].timestamp : st->duration;
7088 pkt->duration = next_dts - pkt->dts;
7089 pkt->pts = pkt->dts;
7091 if (st->discard == AVDISCARD_ALL)
7093 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
7094 pkt->pos = sample->pos;
7096 /* Multiple stsd handling. */
7097 if (sc->stsc_data) {
7098 /* Keep track of the stsc index for the given sample, then check
7099 * if the stsd index is different from the last used one. */
7101 if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
7102 mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
7104 sc->stsc_sample = 0;
7105 /* Do not check indexes after a switch. */
7106 } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
7107 sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
7108 sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
7109 ret = mov_change_extradata(sc, pkt);
7116 aax_filter(pkt->data, pkt->size, mov);
7118 if (sc->cenc.aes_ctr) {
7119 ret = cenc_filter(mov, sc, current_index, pkt->data, pkt->size);
7128 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
7130 MOVContext *mov = s->priv_data;
7133 if (!mov->frag_index.complete)
7136 index = search_frag_timestamp(&mov->frag_index, st, timestamp);
7139 if (!mov->frag_index.item[index].headers_read)
7140 return mov_switch_root(s, -1, index);
7141 if (index + 1 < mov->frag_index.nb_items)
7142 mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
7147 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
7149 MOVStreamContext *sc = st->priv_data;
7150 int sample, time_sample, ret;
7153 timestamp -= sc->time_offset;
7155 ret = mov_seek_fragment(s, st, timestamp);
7159 sample = av_index_search_timestamp(st, timestamp, flags);
7160 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
7161 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
7163 if (sample < 0) /* not sure what to do */
7164 return AVERROR_INVALIDDATA;
7165 mov_current_sample_set(sc, sample);
7166 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
7167 /* adjust ctts index */
7168 if (sc->ctts_data) {
7170 for (i = 0; i < sc->ctts_count; i++) {
7171 int next = time_sample + sc->ctts_data[i].count;
7172 if (next > sc->current_sample) {
7174 sc->ctts_sample = sc->current_sample - time_sample;
7181 /* adjust stsd index */
7183 for (i = 0; i < sc->stsc_count; i++) {
7184 int next = time_sample + mov_get_stsc_samples(sc, i);
7185 if (next > sc->current_sample) {
7187 sc->stsc_sample = sc->current_sample - time_sample;
7196 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
7198 MOVContext *mc = s->priv_data;
7203 if (stream_index >= s->nb_streams)
7204 return AVERROR_INVALIDDATA;
7206 st = s->streams[stream_index];
7207 sample = mov_seek_stream(s, st, sample_time, flags);
7211 if (mc->seek_individually) {
7212 /* adjust seek timestamp to found sample timestamp */
7213 int64_t seek_timestamp = st->index_entries[sample].timestamp;
7215 for (i = 0; i < s->nb_streams; i++) {
7217 MOVStreamContext *sc = s->streams[i]->priv_data;
7219 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
7221 if (stream_index == i)
7224 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
7225 mov_seek_stream(s, st, timestamp, flags);
7228 for (i = 0; i < s->nb_streams; i++) {
7229 MOVStreamContext *sc;
7232 mov_current_sample_set(sc, 0);
7235 MOVStreamContext *sc;
7236 AVIndexEntry *entry = mov_find_next_sample(s, &st);
7238 return AVERROR_INVALIDDATA;
7240 if (sc->ffindex == stream_index && sc->current_sample == sample)
7242 mov_current_sample_inc(sc);
7248 #define OFFSET(x) offsetof(MOVContext, x)
7249 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
7250 static const AVOption mov_options[] = {
7251 {"use_absolute_path",
7252 "allow using absolute path when opening alias, this is a possible security issue",
7253 OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
7255 {"seek_streams_individually",
7256 "Seek each stream individually to the to the closest point",
7257 OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
7259 {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
7261 {"advanced_editlist",
7262 "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
7263 OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
7265 {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
7268 "use mfra for fragment timestamps",
7269 OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
7270 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
7272 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
7273 FLAGS, "use_mfra_for" },
7274 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
7275 FLAGS, "use_mfra_for" },
7276 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
7277 FLAGS, "use_mfra_for" },
7278 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
7279 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7280 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
7281 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7282 { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
7283 AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7284 { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
7285 "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
7286 AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
7287 .flags = AV_OPT_FLAG_DECODING_PARAM },
7288 { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7289 { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
7290 {.i64 = 0}, 0, 1, FLAGS },
7295 static const AVClass mov_class = {
7296 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
7297 .item_name = av_default_item_name,
7298 .option = mov_options,
7299 .version = LIBAVUTIL_VERSION_INT,
7302 AVInputFormat ff_mov_demuxer = {
7303 .name = "mov,mp4,m4a,3gp,3g2,mj2",
7304 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
7305 .priv_class = &mov_class,
7306 .priv_data_size = sizeof(MOVContext),
7307 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
7308 .read_probe = mov_probe,
7309 .read_header = mov_read_header,
7310 .read_packet = mov_read_packet,
7311 .read_close = mov_read_close,
7312 .read_seek = mov_read_seek,
7313 .flags = AVFMT_NO_BYTE_SEEK,