3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * first version by Francois Revol <revol@free.fr>
7 * seek function by Gael Chardon <gael.dev@4now.net>
9 * This file is part of FFmpeg.
11 * FFmpeg is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * FFmpeg is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with FFmpeg; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include "libavutil/attributes.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/intfloat.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/time_internal.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/display.h"
41 #include "libavutil/opt.h"
42 #include "libavutil/aes.h"
43 #include "libavutil/aes_ctr.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/sha.h"
46 #include "libavutil/spherical.h"
47 #include "libavutil/stereo3d.h"
48 #include "libavutil/timecode.h"
49 #include "libavcodec/ac3tab.h"
50 #include "libavcodec/flac.h"
51 #include "libavcodec/mpegaudiodecheader.h"
54 #include "avio_internal.h"
57 #include "libavcodec/get_bits.h"
60 #include "replaygain.h"
66 #include "qtpalette.h"
68 /* those functions parse an atom */
69 /* links atom IDs to parse functions */
70 typedef struct MOVParseTableEntry {
72 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
75 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
76 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
77 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
78 int count, int duration);
80 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
81 unsigned len, const char *key)
85 short current, total = 0;
86 avio_rb16(pb); // unknown
87 current = avio_rb16(pb);
89 total = avio_rb16(pb);
91 snprintf(buf, sizeof(buf), "%d", current);
93 snprintf(buf, sizeof(buf), "%d/%d", current, total);
94 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
95 av_dict_set(&c->fc->metadata, key, buf, 0);
100 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
101 unsigned len, const char *key)
103 /* bypass padding bytes */
108 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
109 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
114 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
115 unsigned len, const char *key)
117 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
118 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
123 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
124 unsigned len, const char *key)
128 avio_r8(pb); // unknown
131 if (genre < 1 || genre > ID3v1_GENRE_MAX)
133 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
134 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
139 static const uint32_t mac_to_unicode[128] = {
140 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
141 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
142 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
143 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
144 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
145 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
146 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
147 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
148 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
149 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
150 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
151 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
152 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
153 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
154 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
155 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
158 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
159 char *dst, int dstlen)
162 char *end = dst+dstlen-1;
165 for (i = 0; i < len; i++) {
166 uint8_t t, c = avio_r8(pb);
174 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
180 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
184 MOVStreamContext *sc;
189 case 0xd: id = AV_CODEC_ID_MJPEG; break;
190 case 0xe: id = AV_CODEC_ID_PNG; break;
191 case 0x1b: id = AV_CODEC_ID_BMP; break;
193 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
198 st = avformat_new_stream(c->fc, NULL);
200 return AVERROR(ENOMEM);
201 sc = av_mallocz(sizeof(*sc));
203 return AVERROR(ENOMEM);
206 ret = av_get_packet(pb, &pkt, len);
210 if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
211 if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
212 id = AV_CODEC_ID_PNG;
214 id = AV_CODEC_ID_MJPEG;
218 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
220 st->attached_pic = pkt;
221 st->attached_pic.stream_index = st->index;
222 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
224 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
225 st->codecpar->codec_id = id;
231 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
233 char language[4] = { 0 };
234 char buf[200], place[100];
235 uint16_t langcode = 0;
236 double longitude, latitude, altitude;
237 const char *key = "location";
239 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
240 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
241 return AVERROR_INVALIDDATA;
244 avio_skip(pb, 4); // version+flags
245 langcode = avio_rb16(pb);
246 ff_mov_lang_to_iso639(langcode, language);
249 len -= avio_get_str(pb, len, place, sizeof(place));
251 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
252 return AVERROR_INVALIDDATA;
254 avio_skip(pb, 1); // role
258 av_log(c->fc, AV_LOG_ERROR,
259 "loci too short (%u bytes left, need at least %d)\n", len, 12);
260 return AVERROR_INVALIDDATA;
262 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
263 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
264 altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
266 // Try to output in the same format as the ?xyz field
267 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
269 av_strlcatf(buf, sizeof(buf), "%+f", altitude);
270 av_strlcatf(buf, sizeof(buf), "/%s", place);
272 if (*language && strcmp(language, "und")) {
274 snprintf(key2, sizeof(key2), "%s-%s", key, language);
275 av_dict_set(&c->fc->metadata, key2, buf, 0);
277 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
278 return av_dict_set(&c->fc->metadata, key, buf, 0);
281 static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
287 if (c->ignore_chapters)
290 n_hmmt = avio_rb32(pb);
291 for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
292 int moment_time = avio_rb32(pb);
293 avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
298 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
301 char key2[32], language[4] = {0};
303 const char *key = NULL;
304 uint16_t langcode = 0;
305 uint32_t data_type = 0, str_size, str_size_alloc;
306 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
311 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
312 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
313 case MKTAG( 'X','M','P','_'):
314 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
315 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
316 case MKTAG( 'a','k','I','D'): key = "account_type";
317 parse = mov_metadata_int8_no_padding; break;
318 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
319 case MKTAG( 'c','a','t','g'): key = "category"; break;
320 case MKTAG( 'c','p','i','l'): key = "compilation";
321 parse = mov_metadata_int8_no_padding; break;
322 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
323 case MKTAG( 'd','e','s','c'): key = "description"; break;
324 case MKTAG( 'd','i','s','k'): key = "disc";
325 parse = mov_metadata_track_or_disc_number; break;
326 case MKTAG( 'e','g','i','d'): key = "episode_uid";
327 parse = mov_metadata_int8_no_padding; break;
328 case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
329 case MKTAG( 'g','n','r','e'): key = "genre";
330 parse = mov_metadata_gnre; break;
331 case MKTAG( 'h','d','v','d'): key = "hd_video";
332 parse = mov_metadata_int8_no_padding; break;
333 case MKTAG( 'H','M','M','T'):
334 return mov_metadata_hmmt(c, pb, atom.size);
335 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
336 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
337 case MKTAG( 'l','o','c','i'):
338 return mov_metadata_loci(c, pb, atom.size);
339 case MKTAG( 'p','c','s','t'): key = "podcast";
340 parse = mov_metadata_int8_no_padding; break;
341 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
342 parse = mov_metadata_int8_no_padding; break;
343 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
344 case MKTAG( 'r','t','n','g'): key = "rating";
345 parse = mov_metadata_int8_no_padding; break;
346 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
347 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
348 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
349 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
350 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
351 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
352 case MKTAG( 's','t','i','k'): key = "media_type";
353 parse = mov_metadata_int8_no_padding; break;
354 case MKTAG( 't','r','k','n'): key = "track";
355 parse = mov_metadata_track_or_disc_number; break;
356 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
357 case MKTAG( 't','v','e','s'): key = "episode_sort";
358 parse = mov_metadata_int8_bypass_padding; break;
359 case MKTAG( 't','v','n','n'): key = "network"; break;
360 case MKTAG( 't','v','s','h'): key = "show"; break;
361 case MKTAG( 't','v','s','n'): key = "season_number";
362 parse = mov_metadata_int8_bypass_padding; break;
363 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
364 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
365 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
366 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
367 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
368 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
369 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
370 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
371 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
372 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
373 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
374 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
375 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
376 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
377 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
378 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
379 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
380 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
381 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
382 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
383 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
384 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
385 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
386 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
387 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
388 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
389 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
390 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
391 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
392 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
393 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
394 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
395 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
396 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
397 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
400 if (c->itunes_metadata && atom.size > 8) {
401 int data_size = avio_rb32(pb);
402 int tag = avio_rl32(pb);
403 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
404 data_type = avio_rb32(pb); // type
405 avio_rb32(pb); // unknown
406 str_size = data_size - 16;
409 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
410 int ret = mov_read_covr(c, pb, data_type, str_size);
412 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
415 } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
416 uint32_t index = AV_RB32(&atom.type);
417 if (index < c->meta_keys_count && index > 0) {
418 key = c->meta_keys[index];
420 av_log(c->fc, AV_LOG_WARNING,
421 "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n",
422 index, c->meta_keys_count);
426 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
427 str_size = avio_rb16(pb); // string length
428 if (str_size > atom.size) {
430 avio_seek(pb, -2, SEEK_CUR);
431 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
434 langcode = avio_rb16(pb);
435 ff_mov_lang_to_iso639(langcode, language);
438 str_size = atom.size;
440 if (c->export_all && !key) {
441 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
447 if (atom.size < 0 || str_size >= INT_MAX/2)
448 return AVERROR_INVALIDDATA;
450 // Allocates enough space if data_type is a int32 or float32 number, otherwise
451 // worst-case requirement for output string in case of utf8 coded input
452 num = (data_type >= 21 && data_type <= 23);
453 str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
454 str = av_mallocz(str_size_alloc);
456 return AVERROR(ENOMEM);
459 parse(c, pb, str_size, key);
461 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
462 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
463 } else if (data_type == 21) { // BE signed integer, variable size
466 val = (int8_t)avio_r8(pb);
467 else if (str_size == 2)
468 val = (int16_t)avio_rb16(pb);
469 else if (str_size == 3)
470 val = ((int32_t)(avio_rb24(pb)<<8))>>8;
471 else if (str_size == 4)
472 val = (int32_t)avio_rb32(pb);
473 if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
474 av_log(c->fc, AV_LOG_ERROR,
475 "Failed to store the number (%d) in string.\n", val);
477 return AVERROR_INVALIDDATA;
479 } else if (data_type == 22) { // BE unsigned integer, variable size
480 unsigned int val = 0;
483 else if (str_size == 2)
485 else if (str_size == 3)
487 else if (str_size == 4)
489 if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
490 av_log(c->fc, AV_LOG_ERROR,
491 "Failed to store the number (%u) in string.\n", val);
493 return AVERROR_INVALIDDATA;
495 } else if (data_type == 23 && str_size >= 4) { // BE float32
496 float val = av_int2float(avio_rb32(pb));
497 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
498 av_log(c->fc, AV_LOG_ERROR,
499 "Failed to store the float32 number (%f) in string.\n", val);
501 return AVERROR_INVALIDDATA;
504 int ret = ffio_read_size(pb, str, str_size);
511 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
512 av_dict_set(&c->fc->metadata, key, str, 0);
513 if (*language && strcmp(language, "und")) {
514 snprintf(key2, sizeof(key2), "%s-%s", key, language);
515 av_dict_set(&c->fc->metadata, key2, str, 0);
517 if (!strcmp(key, "encoder")) {
518 int major, minor, micro;
519 if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, µ) == 3) {
520 c->handbrake_version = 1000000*major + 1000*minor + micro;
529 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
532 int i, nb_chapters, str_len, version;
536 if (c->ignore_chapters)
539 if ((atom.size -= 5) < 0)
542 version = avio_r8(pb);
545 avio_rb32(pb); // ???
546 nb_chapters = avio_r8(pb);
548 for (i = 0; i < nb_chapters; i++) {
552 start = avio_rb64(pb);
553 str_len = avio_r8(pb);
555 if ((atom.size -= 9+str_len) < 0)
558 ret = ffio_read_size(pb, str, str_len);
562 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
567 #define MIN_DATA_ENTRY_BOX_SIZE 12
568 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
571 MOVStreamContext *sc;
574 if (c->fc->nb_streams < 1)
576 st = c->fc->streams[c->fc->nb_streams-1];
579 avio_rb32(pb); // version + flags
580 entries = avio_rb32(pb);
582 entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
583 entries >= UINT_MAX / sizeof(*sc->drefs))
584 return AVERROR_INVALIDDATA;
588 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
590 return AVERROR(ENOMEM);
591 sc->drefs_count = entries;
593 for (i = 0; i < entries; i++) {
594 MOVDref *dref = &sc->drefs[i];
595 uint32_t size = avio_rb32(pb);
596 int64_t next = avio_tell(pb) + size - 4;
599 return AVERROR_INVALIDDATA;
601 dref->type = avio_rl32(pb);
602 avio_rb32(pb); // version + flags
604 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
605 /* macintosh alias record */
606 uint16_t volume_len, len;
612 volume_len = avio_r8(pb);
613 volume_len = FFMIN(volume_len, 27);
614 ret = ffio_read_size(pb, dref->volume, 27);
617 dref->volume[volume_len] = 0;
618 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
623 len = FFMIN(len, 63);
624 ret = ffio_read_size(pb, dref->filename, 63);
627 dref->filename[len] = 0;
628 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
632 /* read next level up_from_alias/down_to_target */
633 dref->nlvl_from = avio_rb16(pb);
634 dref->nlvl_to = avio_rb16(pb);
635 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
636 dref->nlvl_from, dref->nlvl_to);
640 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
643 type = avio_rb16(pb);
645 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
648 if (type == 2) { // absolute path
650 dref->path = av_mallocz(len+1);
652 return AVERROR(ENOMEM);
654 ret = ffio_read_size(pb, dref->path, len);
656 av_freep(&dref->path);
659 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
661 memmove(dref->path, dref->path+volume_len, len);
664 // trim string of any ending zeros
665 for (j = len - 1; j >= 0; j--) {
666 if (dref->path[j] == 0)
671 for (j = 0; j < len; j++)
672 if (dref->path[j] == ':' || dref->path[j] == 0)
674 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
675 } else if (type == 0) { // directory name
677 dref->dir = av_malloc(len+1);
679 return AVERROR(ENOMEM);
681 ret = ffio_read_size(pb, dref->dir, len);
683 av_freep(&dref->dir);
687 for (j = 0; j < len; j++)
688 if (dref->dir[j] == ':')
690 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
695 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n",
700 avio_seek(pb, next, SEEK_SET);
705 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
714 avio_r8(pb); /* version */
715 avio_rb24(pb); /* flags */
718 ctype = avio_rl32(pb);
719 type = avio_rl32(pb); /* component subtype */
721 av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype));
722 av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type));
724 if (c->trak_index < 0) { // meta not inside a trak
725 if (type == MKTAG('m','d','t','a')) {
726 c->found_hdlr_mdta = 1;
731 st = c->fc->streams[c->fc->nb_streams-1];
733 if (type == MKTAG('v','i','d','e'))
734 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
735 else if (type == MKTAG('s','o','u','n'))
736 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
737 else if (type == MKTAG('m','1','a',' '))
738 st->codecpar->codec_id = AV_CODEC_ID_MP2;
739 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
740 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
742 avio_rb32(pb); /* component manufacture */
743 avio_rb32(pb); /* component flags */
744 avio_rb32(pb); /* component flags mask */
746 title_size = atom.size - 24;
747 if (title_size > 0) {
748 if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
749 return AVERROR_INVALIDDATA;
750 title_str = av_malloc(title_size + 1); /* Add null terminator */
752 return AVERROR(ENOMEM);
754 ret = ffio_read_size(pb, title_str, title_size);
756 av_freep(&title_str);
759 title_str[title_size] = 0;
761 int off = (!c->isom && title_str[0] == title_size - 1);
762 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
764 av_freep(&title_str);
770 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
775 if (fc->nb_streams < 1)
777 st = fc->streams[fc->nb_streams-1];
779 avio_rb32(pb); /* version + flags */
780 ff_mp4_read_descr(fc, pb, &tag);
781 if (tag == MP4ESDescrTag) {
782 ff_mp4_parse_es_descr(pb, NULL);
784 avio_rb16(pb); /* ID */
786 ff_mp4_read_descr(fc, pb, &tag);
787 if (tag == MP4DecConfigDescrTag)
788 ff_mp4_read_dec_config_descr(fc, st, pb);
792 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
794 return ff_mov_read_esds(c->fc, pb);
797 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
800 enum AVAudioServiceType *ast;
801 int ac3info, acmod, lfeon, bsmod;
803 if (c->fc->nb_streams < 1)
805 st = c->fc->streams[c->fc->nb_streams-1];
807 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
810 return AVERROR(ENOMEM);
812 ac3info = avio_rb24(pb);
813 bsmod = (ac3info >> 14) & 0x7;
814 acmod = (ac3info >> 11) & 0x7;
815 lfeon = (ac3info >> 10) & 0x1;
816 st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
817 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
819 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
821 if (st->codecpar->channels > 1 && bsmod == 0x7)
822 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
824 #if FF_API_LAVF_AVCTX
825 FF_DISABLE_DEPRECATION_WARNINGS
826 st->codec->audio_service_type = *ast;
827 FF_ENABLE_DEPRECATION_WARNINGS
833 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
836 enum AVAudioServiceType *ast;
837 int eac3info, acmod, lfeon, bsmod;
839 if (c->fc->nb_streams < 1)
841 st = c->fc->streams[c->fc->nb_streams-1];
843 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
846 return AVERROR(ENOMEM);
848 /* No need to parse fields for additional independent substreams and its
849 * associated dependent substreams since libavcodec's E-AC-3 decoder
850 * does not support them yet. */
851 avio_rb16(pb); /* data_rate and num_ind_sub */
852 eac3info = avio_rb24(pb);
853 bsmod = (eac3info >> 12) & 0x1f;
854 acmod = (eac3info >> 9) & 0x7;
855 lfeon = (eac3info >> 8) & 0x1;
856 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
858 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
859 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
861 if (st->codecpar->channels > 1 && bsmod == 0x7)
862 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
864 #if FF_API_LAVF_AVCTX
865 FF_DISABLE_DEPRECATION_WARNINGS
866 st->codec->audio_service_type = *ast;
867 FF_ENABLE_DEPRECATION_WARNINGS
873 static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
875 const uint32_t ddts_size = 20;
878 uint32_t frame_duration_code = 0;
879 uint32_t channel_layout_code = 0;
882 buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE);
884 return AVERROR(ENOMEM);
886 if (avio_read(pb, buf, ddts_size) < ddts_size) {
888 return AVERROR_INVALIDDATA;
891 init_get_bits(&gb, buf, 8*ddts_size);
893 if (c->fc->nb_streams < 1) {
897 st = c->fc->streams[c->fc->nb_streams-1];
899 st->codecpar->sample_rate = get_bits_long(&gb, 32);
900 if (st->codecpar->sample_rate <= 0) {
901 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
903 return AVERROR_INVALIDDATA;
905 skip_bits_long(&gb, 32); /* max bitrate */
906 st->codecpar->bit_rate = get_bits_long(&gb, 32);
907 st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
908 frame_duration_code = get_bits(&gb, 2);
909 skip_bits(&gb, 30); /* various fields */
910 channel_layout_code = get_bits(&gb, 16);
912 st->codecpar->frame_size =
913 (frame_duration_code == 0) ? 512 :
914 (frame_duration_code == 1) ? 1024 :
915 (frame_duration_code == 2) ? 2048 :
916 (frame_duration_code == 3) ? 4096 : 0;
918 if (channel_layout_code > 0xff) {
919 av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
921 st->codecpar->channel_layout =
922 ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
923 ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
924 ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
925 ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
926 ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
927 ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
929 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
935 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
939 if (c->fc->nb_streams < 1)
941 st = c->fc->streams[c->fc->nb_streams-1];
946 /* skip version and flags */
949 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
954 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
959 if (c->fc->nb_streams < 1)
961 st = c->fc->streams[c->fc->nb_streams-1];
963 if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
964 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
969 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
971 const int num = avio_rb32(pb);
972 const int den = avio_rb32(pb);
975 if (c->fc->nb_streams < 1)
977 st = c->fc->streams[c->fc->nb_streams-1];
979 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
980 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
981 av_log(c->fc, AV_LOG_WARNING,
982 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
983 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
985 } else if (den != 0) {
986 av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
992 /* this atom contains actual media data */
993 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
995 if (atom.size == 0) /* wrong one (MP4) */
998 return 0; /* now go for moov */
1001 #define DRM_BLOB_SIZE 56
1003 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1005 uint8_t intermediate_key[20];
1006 uint8_t intermediate_iv[20];
1009 uint8_t file_checksum[20];
1010 uint8_t calculated_checksum[20];
1014 uint8_t *activation_bytes = c->activation_bytes;
1015 uint8_t *fixed_key = c->audible_fixed_key;
1019 sha = av_sha_alloc();
1021 return AVERROR(ENOMEM);
1022 c->aes_decrypt = av_aes_alloc();
1023 if (!c->aes_decrypt) {
1024 ret = AVERROR(ENOMEM);
1028 /* drm blob processing */
1029 avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
1030 avio_read(pb, input, DRM_BLOB_SIZE);
1031 avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
1032 avio_read(pb, file_checksum, 20);
1034 av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
1035 for (i = 0; i < 20; i++)
1036 av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
1037 av_log(c->fc, AV_LOG_INFO, "\n");
1039 /* verify activation data */
1040 if (!activation_bytes) {
1041 av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
1042 ret = 0; /* allow ffprobe to continue working on .aax files */
1045 if (c->activation_bytes_size != 4) {
1046 av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
1047 ret = AVERROR(EINVAL);
1051 /* verify fixed key */
1052 if (c->audible_fixed_key_size != 16) {
1053 av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
1054 ret = AVERROR(EINVAL);
1058 /* AAX (and AAX+) key derivation */
1059 av_sha_init(sha, 160);
1060 av_sha_update(sha, fixed_key, 16);
1061 av_sha_update(sha, activation_bytes, 4);
1062 av_sha_final(sha, intermediate_key);
1063 av_sha_init(sha, 160);
1064 av_sha_update(sha, fixed_key, 16);
1065 av_sha_update(sha, intermediate_key, 20);
1066 av_sha_update(sha, activation_bytes, 4);
1067 av_sha_final(sha, intermediate_iv);
1068 av_sha_init(sha, 160);
1069 av_sha_update(sha, intermediate_key, 16);
1070 av_sha_update(sha, intermediate_iv, 16);
1071 av_sha_final(sha, calculated_checksum);
1072 if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
1073 av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
1074 ret = AVERROR_INVALIDDATA;
1077 av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
1078 av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
1079 for (i = 0; i < 4; i++) {
1080 // file data (in output) is stored in big-endian mode
1081 if (activation_bytes[i] != output[3 - i]) { // critical error
1082 av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
1083 ret = AVERROR_INVALIDDATA;
1087 memcpy(c->file_key, output + 8, 16);
1088 memcpy(input, output + 26, 16);
1089 av_sha_init(sha, 160);
1090 av_sha_update(sha, input, 16);
1091 av_sha_update(sha, c->file_key, 16);
1092 av_sha_update(sha, fixed_key, 16);
1093 av_sha_final(sha, c->file_iv);
1101 // Audible AAX (and AAX+) bytestream decryption
1102 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1105 unsigned char iv[16];
1107 memcpy(iv, c->file_iv, 16); // iv is overwritten
1108 blocks = size >> 4; // trailing bytes are not encrypted!
1109 av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1110 av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1115 /* read major brand, minor version and compatible brands and store them as metadata */
1116 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1119 int comp_brand_size;
1120 char* comp_brands_str;
1121 uint8_t type[5] = {0};
1122 int ret = ffio_read_size(pb, type, 4);
1126 if (strcmp(type, "qt "))
1128 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1129 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1130 minor_ver = avio_rb32(pb); /* minor version */
1131 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1133 comp_brand_size = atom.size - 8;
1134 if (comp_brand_size < 0)
1135 return AVERROR_INVALIDDATA;
1136 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1137 if (!comp_brands_str)
1138 return AVERROR(ENOMEM);
1140 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1142 av_freep(&comp_brands_str);
1145 comp_brands_str[comp_brand_size] = 0;
1146 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1147 av_freep(&comp_brands_str);
1152 /* this atom should contain all header atoms */
1153 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1157 if (c->found_moov) {
1158 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1159 avio_skip(pb, atom.size);
1163 if ((ret = mov_read_default(c, pb, atom)) < 0)
1165 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1166 /* so we don't parse the whole file if over a network */
1168 return 0; /* now go for mdat */
1171 static MOVFragmentStreamInfo * get_frag_stream_info(
1172 MOVFragmentIndex *frag_index,
1177 MOVFragmentIndexItem * item;
1179 if (index < 0 || index >= frag_index->nb_items)
1181 item = &frag_index->item[index];
1182 for (i = 0; i < item->nb_stream_info; i++)
1183 if (item->stream_info[i].id == id)
1184 return &item->stream_info[i];
1186 // This shouldn't happen
1190 static void set_frag_stream(MOVFragmentIndex *frag_index, int id)
1193 MOVFragmentIndexItem * item;
1195 if (frag_index->current < 0 ||
1196 frag_index->current >= frag_index->nb_items)
1199 item = &frag_index->item[frag_index->current];
1200 for (i = 0; i < item->nb_stream_info; i++)
1201 if (item->stream_info[i].id == id) {
1206 // id not found. This shouldn't happen.
1210 static MOVFragmentStreamInfo * get_current_frag_stream_info(
1211 MOVFragmentIndex *frag_index)
1213 MOVFragmentIndexItem * item = &frag_index->item[frag_index->current];
1214 if (item->current >= 0 && item->current < item->nb_stream_info)
1215 return &item->stream_info[item->current];
1217 // This shouldn't happen
1221 static int search_frag_moof_offset(MOVFragmentIndex *frag_index, int64_t offset)
1224 int64_t moof_offset;
1226 // Optimize for appending new entries
1227 if (!frag_index->nb_items ||
1228 frag_index->item[frag_index->nb_items - 1].moof_offset < offset)
1229 return frag_index->nb_items;
1232 b = frag_index->nb_items;
1236 moof_offset = frag_index->item[m].moof_offset;
1237 if (moof_offset >= offset)
1239 if (moof_offset <= offset)
1245 static int64_t get_stream_info_time(MOVFragmentStreamInfo * frag_stream_info)
1248 if (frag_stream_info) {
1249 if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE)
1250 return frag_stream_info->sidx_pts;
1251 if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE)
1252 return frag_stream_info->first_tfra_pts;
1253 if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE)
1254 return frag_stream_info->tfdt_dts;
1256 return AV_NOPTS_VALUE;
1259 static int64_t get_frag_time(MOVFragmentIndex *frag_index,
1260 int index, int track_id)
1262 MOVFragmentStreamInfo * frag_stream_info;
1266 if (track_id >= 0) {
1267 frag_stream_info = get_frag_stream_info(frag_index, index, track_id);
1268 return frag_stream_info->sidx_pts;
1271 for (i = 0; i < frag_index->item[index].nb_stream_info; i++) {
1272 frag_stream_info = &frag_index->item[index].stream_info[i];
1273 timestamp = get_stream_info_time(frag_stream_info);
1274 if (timestamp != AV_NOPTS_VALUE)
1277 return AV_NOPTS_VALUE;
1280 static int search_frag_timestamp(MOVFragmentIndex *frag_index,
1281 AVStream *st, int64_t timestamp)
1288 // If the stream is referenced by any sidx, limit the search
1289 // to fragments that referenced this stream in the sidx
1290 MOVStreamContext *sc = st->priv_data;
1296 b = frag_index->nb_items;
1300 frag_time = get_frag_time(frag_index, m, id);
1301 if (frag_time != AV_NOPTS_VALUE) {
1302 if (frag_time >= timestamp)
1304 if (frag_time <= timestamp)
1311 static int update_frag_index(MOVContext *c, int64_t offset)
1314 MOVFragmentIndexItem * item;
1315 MOVFragmentStreamInfo * frag_stream_info;
1317 // If moof_offset already exists in frag_index, return index to it
1318 index = search_frag_moof_offset(&c->frag_index, offset);
1319 if (index < c->frag_index.nb_items &&
1320 c->frag_index.item[index].moof_offset == offset)
1323 // offset is not yet in frag index.
1324 // Insert new item at index (sorted by moof offset)
1325 item = av_fast_realloc(c->frag_index.item,
1326 &c->frag_index.allocated_size,
1327 (c->frag_index.nb_items + 1) *
1328 sizeof(*c->frag_index.item));
1331 c->frag_index.item = item;
1333 frag_stream_info = av_realloc_array(NULL, c->fc->nb_streams,
1334 sizeof(*item->stream_info));
1335 if (!frag_stream_info)
1338 for (i = 0; i < c->fc->nb_streams; i++) {
1339 frag_stream_info[i].id = c->fc->streams[i]->id;
1340 frag_stream_info[i].sidx_pts = AV_NOPTS_VALUE;
1341 frag_stream_info[i].tfdt_dts = AV_NOPTS_VALUE;
1342 frag_stream_info[i].first_tfra_pts = AV_NOPTS_VALUE;
1343 frag_stream_info[i].index_entry = -1;
1346 if (index < c->frag_index.nb_items)
1347 memmove(c->frag_index.item + index + 1, c->frag_index.item + index,
1348 (c->frag_index.nb_items - index) * sizeof(*c->frag_index.item));
1350 item = &c->frag_index.item[index];
1351 item->headers_read = 0;
1353 item->nb_stream_info = c->fc->nb_streams;
1354 item->moof_offset = offset;
1355 item->stream_info = frag_stream_info;
1356 c->frag_index.nb_items++;
1361 static void fix_frag_index_entries(MOVFragmentIndex *frag_index, int index,
1362 int id, int entries)
1365 MOVFragmentStreamInfo * frag_stream_info;
1369 for (i = index; i < frag_index->nb_items; i++) {
1370 frag_stream_info = get_frag_stream_info(frag_index, i, id);
1371 if (frag_stream_info && frag_stream_info->index_entry >= 0)
1372 frag_stream_info->index_entry += entries;
1376 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1378 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1379 c->has_looked_for_mfra = 1;
1380 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
1382 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1384 if ((ret = mov_read_mfra(c, pb)) < 0) {
1385 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1386 "read the mfra (may be a live ismv)\n");
1389 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1390 "seekable, can not look for mfra\n");
1393 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
1394 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1395 c->frag_index.current = update_frag_index(c, c->fragment.moof_offset);
1396 return mov_read_default(c, pb, atom);
1399 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1402 if(time >= 2082844800)
1403 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1405 if ((int64_t)(time * 1000000ULL) / 1000000 != time) {
1406 av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n");
1410 avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
1414 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1417 MOVStreamContext *sc;
1419 char language[4] = {0};
1421 int64_t creation_time;
1423 if (c->fc->nb_streams < 1)
1425 st = c->fc->streams[c->fc->nb_streams-1];
1428 if (sc->time_scale) {
1429 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1430 return AVERROR_INVALIDDATA;
1433 version = avio_r8(pb);
1435 avpriv_request_sample(c->fc, "Version %d", version);
1436 return AVERROR_PATCHWELCOME;
1438 avio_rb24(pb); /* flags */
1440 creation_time = avio_rb64(pb);
1443 creation_time = avio_rb32(pb);
1444 avio_rb32(pb); /* modification time */
1446 mov_metadata_creation_time(&st->metadata, creation_time);
1448 sc->time_scale = avio_rb32(pb);
1449 if (sc->time_scale <= 0) {
1450 av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale);
1453 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1455 lang = avio_rb16(pb); /* language */
1456 if (ff_mov_lang_to_iso639(lang, language))
1457 av_dict_set(&st->metadata, "language", language, 0);
1458 avio_rb16(pb); /* quality */
1463 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1466 int64_t creation_time;
1467 int version = avio_r8(pb); /* version */
1468 avio_rb24(pb); /* flags */
1471 creation_time = avio_rb64(pb);
1474 creation_time = avio_rb32(pb);
1475 avio_rb32(pb); /* modification time */
1477 mov_metadata_creation_time(&c->fc->metadata, creation_time);
1478 c->time_scale = avio_rb32(pb); /* time scale */
1479 if (c->time_scale <= 0) {
1480 av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale);
1483 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1485 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1486 // set the AVCodecContext duration because the duration of individual tracks
1487 // may be inaccurate
1488 if (c->time_scale > 0 && !c->trex_data)
1489 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1490 avio_rb32(pb); /* preferred scale */
1492 avio_rb16(pb); /* preferred volume */
1494 avio_skip(pb, 10); /* reserved */
1496 /* movie display matrix, store it in main context and use it later on */
1497 for (i = 0; i < 3; i++) {
1498 c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
1499 c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
1500 c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
1503 avio_rb32(pb); /* preview time */
1504 avio_rb32(pb); /* preview duration */
1505 avio_rb32(pb); /* poster time */
1506 avio_rb32(pb); /* selection time */
1507 avio_rb32(pb); /* selection duration */
1508 avio_rb32(pb); /* current time */
1509 avio_rb32(pb); /* next track ID */
1514 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1519 if (c->fc->nb_streams < 1)
1521 st = c->fc->streams[c->fc->nb_streams-1];
1523 little_endian = avio_rb16(pb) & 0xFF;
1524 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1525 if (little_endian == 1) {
1526 switch (st->codecpar->codec_id) {
1527 case AV_CODEC_ID_PCM_S24BE:
1528 st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
1530 case AV_CODEC_ID_PCM_S32BE:
1531 st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
1533 case AV_CODEC_ID_PCM_F32BE:
1534 st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
1536 case AV_CODEC_ID_PCM_F64BE:
1537 st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
1546 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1549 char color_parameter_type[5] = { 0 };
1550 uint16_t color_primaries, color_trc, color_matrix;
1553 if (c->fc->nb_streams < 1)
1555 st = c->fc->streams[c->fc->nb_streams - 1];
1557 ret = ffio_read_size(pb, color_parameter_type, 4);
1560 if (strncmp(color_parameter_type, "nclx", 4) &&
1561 strncmp(color_parameter_type, "nclc", 4)) {
1562 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1563 color_parameter_type);
1567 color_primaries = avio_rb16(pb);
1568 color_trc = avio_rb16(pb);
1569 color_matrix = avio_rb16(pb);
1571 av_log(c->fc, AV_LOG_TRACE,
1572 "%s: pri %d trc %d matrix %d",
1573 color_parameter_type, color_primaries, color_trc, color_matrix);
1575 if (!strncmp(color_parameter_type, "nclx", 4)) {
1576 uint8_t color_range = avio_r8(pb) >> 7;
1577 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1579 st->codecpar->color_range = AVCOL_RANGE_JPEG;
1581 st->codecpar->color_range = AVCOL_RANGE_MPEG;
1584 if (!av_color_primaries_name(color_primaries))
1585 color_primaries = AVCOL_PRI_UNSPECIFIED;
1586 if (!av_color_transfer_name(color_trc))
1587 color_trc = AVCOL_TRC_UNSPECIFIED;
1588 if (!av_color_space_name(color_matrix))
1589 color_matrix = AVCOL_SPC_UNSPECIFIED;
1591 st->codecpar->color_primaries = color_primaries;
1592 st->codecpar->color_trc = color_trc;
1593 st->codecpar->color_space = color_matrix;
1594 av_log(c->fc, AV_LOG_TRACE, "\n");
1599 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1602 unsigned mov_field_order;
1603 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1605 if (c->fc->nb_streams < 1) // will happen with jp2 files
1607 st = c->fc->streams[c->fc->nb_streams-1];
1609 return AVERROR_INVALIDDATA;
1610 mov_field_order = avio_rb16(pb);
1611 if ((mov_field_order & 0xFF00) == 0x0100)
1612 decoded_field_order = AV_FIELD_PROGRESSIVE;
1613 else if ((mov_field_order & 0xFF00) == 0x0200) {
1614 switch (mov_field_order & 0xFF) {
1615 case 0x01: decoded_field_order = AV_FIELD_TT;
1617 case 0x06: decoded_field_order = AV_FIELD_BB;
1619 case 0x09: decoded_field_order = AV_FIELD_TB;
1621 case 0x0E: decoded_field_order = AV_FIELD_BT;
1625 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1626 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1628 st->codecpar->field_order = decoded_field_order;
1633 static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
1636 uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1637 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1638 return AVERROR_INVALIDDATA;
1639 if ((err = av_reallocp(&par->extradata, size)) < 0) {
1640 par->extradata_size = 0;
1643 par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1647 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1648 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1649 AVCodecParameters *par, uint8_t *buf)
1651 int64_t result = atom.size;
1654 AV_WB32(buf , atom.size + 8);
1655 AV_WL32(buf + 4, atom.type);
1656 err = ffio_read_size(pb, buf + 8, atom.size);
1658 par->extradata_size -= atom.size;
1660 } else if (err < atom.size) {
1661 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1662 par->extradata_size -= atom.size - err;
1665 memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1669 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1670 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1671 enum AVCodecID codec_id)
1674 uint64_t original_size;
1677 if (c->fc->nb_streams < 1) // will happen with jp2 files
1679 st = c->fc->streams[c->fc->nb_streams-1];
1681 if (st->codecpar->codec_id != codec_id)
1682 return 0; /* unexpected codec_id - don't mess with extradata */
1684 original_size = st->codecpar->extradata_size;
1685 err = mov_realloc_extradata(st->codecpar, atom);
1689 err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
1692 return 0; // Note: this is the original behavior to ignore truncation.
1695 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1696 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1698 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1701 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1703 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1706 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1708 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1711 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1713 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1716 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1718 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1720 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1724 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1726 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1728 if (!ret && c->fc->nb_streams >= 1) {
1729 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1730 if (par->extradata_size >= 40) {
1731 par->height = AV_RB16(&par->extradata[36]);
1732 par->width = AV_RB16(&par->extradata[38]);
1738 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1740 if (c->fc->nb_streams >= 1) {
1741 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1742 if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1743 par->codec_id == AV_CODEC_ID_H264 &&
1747 cid = avio_rb16(pb);
1748 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1749 if (cid == 0xd4d || cid == 0xd4e)
1752 } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
1753 par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
1757 num = avio_rb32(pb);
1758 den = avio_rb32(pb);
1759 if (num <= 0 || den <= 0)
1761 switch (avio_rb32(pb)) {
1763 if (den >= INT_MAX / 2)
1767 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1768 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1775 return mov_read_avid(c, pb, atom);
1778 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1782 uint64_t original_size;
1783 if (c->fc->nb_streams >= 1) {
1784 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1785 if (par->codec_id == AV_CODEC_ID_H264)
1787 if (atom.size == 16) {
1788 original_size = par->extradata_size;
1789 ret = mov_realloc_extradata(par, atom);
1791 length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
1792 if (length == atom.size) {
1793 const uint8_t range_value = par->extradata[original_size + 19];
1794 switch (range_value) {
1796 par->color_range = AVCOL_RANGE_MPEG;
1799 par->color_range = AVCOL_RANGE_JPEG;
1802 av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1805 ff_dlog(c, "color_range: %d\n", par->color_range);
1807 /* For some reason the whole atom was not added to the extradata */
1808 av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1811 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1814 av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1821 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1823 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1826 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1831 if (c->fc->nb_streams < 1)
1833 st = c->fc->streams[c->fc->nb_streams-1];
1835 if ((uint64_t)atom.size > (1<<30))
1836 return AVERROR_INVALIDDATA;
1838 if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
1839 st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
1840 st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
1841 // pass all frma atom to codec, needed at least for QDMC and QDM2
1842 av_freep(&st->codecpar->extradata);
1843 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1846 } else if (atom.size > 8) { /* to read frma, esds atoms */
1847 if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1849 ret = ffio_ensure_seekback(pb, 8);
1852 buffer = avio_rb64(pb);
1854 if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1855 && buffer >> 32 <= atom.size
1856 && buffer >> 32 >= 8) {
1859 } else if (!st->codecpar->extradata_size) {
1860 #define ALAC_EXTRADATA_SIZE 36
1861 st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1862 if (!st->codecpar->extradata)
1863 return AVERROR(ENOMEM);
1864 st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
1865 AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE);
1866 AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
1867 AV_WB64(st->codecpar->extradata + 12, buffer);
1868 avio_read(pb, st->codecpar->extradata + 20, 16);
1869 avio_skip(pb, atom.size - 24);
1873 if ((ret = mov_read_default(c, pb, atom)) < 0)
1876 avio_skip(pb, atom.size);
1881 * This function reads atom content and puts data in extradata without tag
1882 * nor size unlike mov_read_extradata.
1884 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1889 if (c->fc->nb_streams < 1)
1891 st = c->fc->streams[c->fc->nb_streams-1];
1893 if ((uint64_t)atom.size > (1<<30))
1894 return AVERROR_INVALIDDATA;
1896 if (atom.size >= 10) {
1897 // Broken files created by legacy versions of libavformat will
1898 // wrap a whole fiel atom inside of a glbl atom.
1899 unsigned size = avio_rb32(pb);
1900 unsigned type = avio_rl32(pb);
1901 avio_seek(pb, -8, SEEK_CUR);
1902 if (type == MKTAG('f','i','e','l') && size == atom.size)
1903 return mov_read_default(c, pb, atom);
1905 if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
1906 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1909 av_freep(&st->codecpar->extradata);
1910 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1917 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1920 uint8_t profile_level;
1923 if (c->fc->nb_streams < 1)
1925 st = c->fc->streams[c->fc->nb_streams-1];
1927 if (atom.size >= (1<<28) || atom.size < 7)
1928 return AVERROR_INVALIDDATA;
1930 profile_level = avio_r8(pb);
1931 if ((profile_level & 0xf0) != 0xc0)
1934 avio_seek(pb, 6, SEEK_CUR);
1935 av_freep(&st->codecpar->extradata);
1936 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
1944 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1945 * but can have extradata appended at the end after the 40 bytes belonging
1948 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1953 if (c->fc->nb_streams < 1)
1955 if (atom.size <= 40)
1957 st = c->fc->streams[c->fc->nb_streams-1];
1959 if ((uint64_t)atom.size > (1<<30))
1960 return AVERROR_INVALIDDATA;
1963 av_freep(&st->codecpar->extradata);
1964 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
1971 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1974 MOVStreamContext *sc;
1975 unsigned int i, entries;
1977 if (c->fc->nb_streams < 1)
1979 st = c->fc->streams[c->fc->nb_streams-1];
1982 avio_r8(pb); /* version */
1983 avio_rb24(pb); /* flags */
1985 entries = avio_rb32(pb);
1990 if (sc->chunk_offsets)
1991 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1992 av_free(sc->chunk_offsets);
1993 sc->chunk_count = 0;
1994 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1995 if (!sc->chunk_offsets)
1996 return AVERROR(ENOMEM);
1997 sc->chunk_count = entries;
1999 if (atom.type == MKTAG('s','t','c','o'))
2000 for (i = 0; i < entries && !pb->eof_reached; i++)
2001 sc->chunk_offsets[i] = avio_rb32(pb);
2002 else if (atom.type == MKTAG('c','o','6','4'))
2003 for (i = 0; i < entries && !pb->eof_reached; i++)
2004 sc->chunk_offsets[i] = avio_rb64(pb);
2006 return AVERROR_INVALIDDATA;
2008 sc->chunk_count = i;
2010 if (pb->eof_reached)
2017 * Compute codec id for 'lpcm' tag.
2018 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
2020 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
2027 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
2030 static int mov_codec_id(AVStream *st, uint32_t format)
2032 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
2035 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
2036 (format & 0xFFFF) == 'T' + ('S' << 8)))
2037 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
2039 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
2040 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2041 } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
2042 /* skip old ASF MPEG-4 tag */
2043 format && format != MKTAG('m','p','4','s')) {
2044 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2046 id = ff_codec_get_id(ff_codec_bmp_tags, format);
2048 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2049 else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
2050 (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
2051 st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
2052 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
2054 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2058 st->codecpar->codec_tag = format;
2063 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
2064 AVStream *st, MOVStreamContext *sc)
2066 uint8_t codec_name[32] = { 0 };
2070 /* The first 16 bytes of the video sample description are already
2071 * read in ff_mov_read_stsd_entries() */
2072 stsd_start = avio_tell(pb) - 16;
2074 avio_rb16(pb); /* version */
2075 avio_rb16(pb); /* revision level */
2076 avio_rb32(pb); /* vendor */
2077 avio_rb32(pb); /* temporal quality */
2078 avio_rb32(pb); /* spatial quality */
2080 st->codecpar->width = avio_rb16(pb); /* width */
2081 st->codecpar->height = avio_rb16(pb); /* height */
2083 avio_rb32(pb); /* horiz resolution */
2084 avio_rb32(pb); /* vert resolution */
2085 avio_rb32(pb); /* data size, always 0 */
2086 avio_rb16(pb); /* frames per samples */
2088 len = avio_r8(pb); /* codec name, pascal string */
2091 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
2093 avio_skip(pb, 31 - len);
2096 av_dict_set(&st->metadata, "encoder", codec_name, 0);
2098 /* codec_tag YV12 triggers an UV swap in rawdec.c */
2099 if (!strncmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
2100 st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
2101 st->codecpar->width &= ~1;
2102 st->codecpar->height &= ~1;
2104 /* Flash Media Server uses tag H.263 with Sorenson Spark */
2105 if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
2106 !strncmp(codec_name, "Sorenson H263", 13))
2107 st->codecpar->codec_id = AV_CODEC_ID_FLV1;
2109 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
2111 avio_seek(pb, stsd_start, SEEK_SET);
2113 if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
2114 st->codecpar->bits_per_coded_sample &= 0x1F;
2115 sc->has_palette = 1;
2119 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
2120 AVStream *st, MOVStreamContext *sc)
2122 int bits_per_sample, flags;
2123 uint16_t version = avio_rb16(pb);
2124 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
2126 avio_rb16(pb); /* revision level */
2127 avio_rb32(pb); /* vendor */
2129 st->codecpar->channels = avio_rb16(pb); /* channel count */
2130 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
2131 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
2133 sc->audio_cid = avio_rb16(pb);
2134 avio_rb16(pb); /* packet size = 0 */
2136 st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
2138 // Read QT version 1 fields. In version 0 these do not exist.
2139 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
2141 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
2144 sc->samples_per_frame = avio_rb32(pb);
2145 avio_rb32(pb); /* bytes per packet */
2146 sc->bytes_per_frame = avio_rb32(pb);
2147 avio_rb32(pb); /* bytes per sample */
2148 } else if (version == 2) {
2149 avio_rb32(pb); /* sizeof struct only */
2150 st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
2151 st->codecpar->channels = avio_rb32(pb);
2152 avio_rb32(pb); /* always 0x7F000000 */
2153 st->codecpar->bits_per_coded_sample = avio_rb32(pb);
2155 flags = avio_rb32(pb); /* lpcm format specific flag */
2156 sc->bytes_per_frame = avio_rb32(pb);
2157 sc->samples_per_frame = avio_rb32(pb);
2158 if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
2159 st->codecpar->codec_id =
2160 ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
2163 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
2164 /* can't correctly handle variable sized packet as audio unit */
2165 switch (st->codecpar->codec_id) {
2166 case AV_CODEC_ID_MP2:
2167 case AV_CODEC_ID_MP3:
2168 st->need_parsing = AVSTREAM_PARSE_FULL;
2174 if (sc->format == 0) {
2175 if (st->codecpar->bits_per_coded_sample == 8)
2176 st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
2177 else if (st->codecpar->bits_per_coded_sample == 16)
2178 st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
2181 switch (st->codecpar->codec_id) {
2182 case AV_CODEC_ID_PCM_S8:
2183 case AV_CODEC_ID_PCM_U8:
2184 if (st->codecpar->bits_per_coded_sample == 16)
2185 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
2187 case AV_CODEC_ID_PCM_S16LE:
2188 case AV_CODEC_ID_PCM_S16BE:
2189 if (st->codecpar->bits_per_coded_sample == 8)
2190 st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
2191 else if (st->codecpar->bits_per_coded_sample == 24)
2192 st->codecpar->codec_id =
2193 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
2194 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2195 else if (st->codecpar->bits_per_coded_sample == 32)
2196 st->codecpar->codec_id =
2197 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
2198 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2200 /* set values for old format before stsd version 1 appeared */
2201 case AV_CODEC_ID_MACE3:
2202 sc->samples_per_frame = 6;
2203 sc->bytes_per_frame = 2 * st->codecpar->channels;
2205 case AV_CODEC_ID_MACE6:
2206 sc->samples_per_frame = 6;
2207 sc->bytes_per_frame = 1 * st->codecpar->channels;
2209 case AV_CODEC_ID_ADPCM_IMA_QT:
2210 sc->samples_per_frame = 64;
2211 sc->bytes_per_frame = 34 * st->codecpar->channels;
2213 case AV_CODEC_ID_GSM:
2214 sc->samples_per_frame = 160;
2215 sc->bytes_per_frame = 33;
2221 bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
2222 if (bits_per_sample) {
2223 st->codecpar->bits_per_coded_sample = bits_per_sample;
2224 sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
2228 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
2229 AVStream *st, MOVStreamContext *sc,
2232 // ttxt stsd contains display flags, justification, background
2233 // color, fonts, and default styles, so fake an atom to read it
2234 MOVAtom fake_atom = { .size = size };
2235 // mp4s contains a regular esds atom
2236 if (st->codecpar->codec_tag != AV_RL32("mp4s"))
2237 mov_read_glbl(c, pb, fake_atom);
2238 st->codecpar->width = sc->width;
2239 st->codecpar->height = sc->height;
2242 static uint32_t yuv_to_rgba(uint32_t ycbcr)
2247 y = (ycbcr >> 16) & 0xFF;
2248 cr = (ycbcr >> 8) & 0xFF;
2251 b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
2252 g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
2253 r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
2255 return (r << 16) | (g << 8) | b;
2258 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
2260 char buf[256] = {0};
2261 uint8_t *src = st->codecpar->extradata;
2264 if (st->codecpar->extradata_size != 64)
2267 if (st->codecpar->width > 0 && st->codecpar->height > 0)
2268 snprintf(buf, sizeof(buf), "size: %dx%d\n",
2269 st->codecpar->width, st->codecpar->height);
2270 av_strlcat(buf, "palette: ", sizeof(buf));
2272 for (i = 0; i < 16; i++) {
2273 uint32_t yuv = AV_RB32(src + i * 4);
2274 uint32_t rgba = yuv_to_rgba(yuv);
2276 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2279 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2282 av_freep(&st->codecpar->extradata);
2283 st->codecpar->extradata_size = 0;
2284 st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
2285 if (!st->codecpar->extradata)
2286 return AVERROR(ENOMEM);
2287 st->codecpar->extradata_size = strlen(buf);
2288 memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
2293 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2294 AVStream *st, MOVStreamContext *sc,
2299 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
2300 if ((int)size != size)
2301 return AVERROR(ENOMEM);
2303 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
2307 MOVStreamContext *tmcd_ctx = st->priv_data;
2309 val = AV_RB32(st->codecpar->extradata + 4);
2310 tmcd_ctx->tmcd_flags = val;
2311 st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
2312 st->avg_frame_rate.den = 1;
2313 #if FF_API_LAVF_AVCTX
2314 FF_DISABLE_DEPRECATION_WARNINGS
2315 st->codec->time_base = av_inv_q(st->avg_frame_rate);
2316 FF_ENABLE_DEPRECATION_WARNINGS
2318 /* adjust for per frame dur in counter mode */
2319 if (tmcd_ctx->tmcd_flags & 0x0008) {
2320 int timescale = AV_RB32(st->codecpar->extradata + 8);
2321 int framedur = AV_RB32(st->codecpar->extradata + 12);
2322 st->avg_frame_rate.num *= timescale;
2323 st->avg_frame_rate.den *= framedur;
2324 #if FF_API_LAVF_AVCTX
2325 FF_DISABLE_DEPRECATION_WARNINGS
2326 st->codec->time_base.den *= timescale;
2327 st->codec->time_base.num *= framedur;
2328 FF_ENABLE_DEPRECATION_WARNINGS
2332 uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
2333 uint32_t format = AV_RB32(st->codecpar->extradata + 22);
2334 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2335 uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
2336 if (str_size > 0 && size >= (int)str_size + 26) {
2337 char *reel_name = av_malloc(str_size + 1);
2339 return AVERROR(ENOMEM);
2340 memcpy(reel_name, st->codecpar->extradata + 30, str_size);
2341 reel_name[str_size] = 0; /* Add null terminator */
2342 /* don't add reel_name if emtpy string */
2343 if (*reel_name == 0) {
2346 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2353 /* other codec type, just skip (rtp, mp4s ...) */
2354 avio_skip(pb, size);
2359 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2360 AVStream *st, MOVStreamContext *sc)
2362 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2363 !st->codecpar->sample_rate && sc->time_scale > 1)
2364 st->codecpar->sample_rate = sc->time_scale;
2366 /* special codec parameters handling */
2367 switch (st->codecpar->codec_id) {
2368 #if CONFIG_DV_DEMUXER
2369 case AV_CODEC_ID_DVAUDIO:
2370 c->dv_fctx = avformat_alloc_context();
2372 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2373 return AVERROR(ENOMEM);
2375 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2377 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2378 return AVERROR(ENOMEM);
2380 sc->dv_audio_container = 1;
2381 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
2384 /* no ifdef since parameters are always those */
2385 case AV_CODEC_ID_QCELP:
2386 st->codecpar->channels = 1;
2387 // force sample rate for qcelp when not stored in mov
2388 if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
2389 st->codecpar->sample_rate = 8000;
2390 // FIXME: Why is the following needed for some files?
2391 sc->samples_per_frame = 160;
2392 if (!sc->bytes_per_frame)
2393 sc->bytes_per_frame = 35;
2395 case AV_CODEC_ID_AMR_NB:
2396 st->codecpar->channels = 1;
2397 /* force sample rate for amr, stsd in 3gp does not store sample rate */
2398 st->codecpar->sample_rate = 8000;
2400 case AV_CODEC_ID_AMR_WB:
2401 st->codecpar->channels = 1;
2402 st->codecpar->sample_rate = 16000;
2404 case AV_CODEC_ID_MP2:
2405 case AV_CODEC_ID_MP3:
2406 /* force type after stsd for m1a hdlr */
2407 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2409 case AV_CODEC_ID_GSM:
2410 case AV_CODEC_ID_ADPCM_MS:
2411 case AV_CODEC_ID_ADPCM_IMA_WAV:
2412 case AV_CODEC_ID_ILBC:
2413 case AV_CODEC_ID_MACE3:
2414 case AV_CODEC_ID_MACE6:
2415 case AV_CODEC_ID_QDM2:
2416 st->codecpar->block_align = sc->bytes_per_frame;
2418 case AV_CODEC_ID_ALAC:
2419 if (st->codecpar->extradata_size == 36) {
2420 st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
2421 st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
2424 case AV_CODEC_ID_AC3:
2425 case AV_CODEC_ID_EAC3:
2426 case AV_CODEC_ID_MPEG1VIDEO:
2427 case AV_CODEC_ID_VC1:
2428 case AV_CODEC_ID_VP9:
2429 st->need_parsing = AVSTREAM_PARSE_FULL;
2437 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2438 int codec_tag, int format,
2441 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2444 (codec_tag != format &&
2445 // AVID 1:1 samples with differing data format and codec tag exist
2446 (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
2447 // prores is allowed to have differing data format and codec tag
2448 codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
2450 codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
2451 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2452 : codec_tag != MKTAG('j','p','e','g')))) {
2453 /* Multiple fourcc, we skip JPEG. This is not correct, we should
2454 * export it as a separate AVStream but this needs a few changes
2455 * in the MOV demuxer, patch welcome. */
2457 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2458 avio_skip(pb, size);
2465 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2468 MOVStreamContext *sc;
2469 int pseudo_stream_id;
2471 if (c->fc->nb_streams < 1)
2473 st = c->fc->streams[c->fc->nb_streams-1];
2476 for (pseudo_stream_id = 0;
2477 pseudo_stream_id < entries && !pb->eof_reached;
2478 pseudo_stream_id++) {
2479 //Parsing Sample description table
2481 int ret, dref_id = 1;
2482 MOVAtom a = { AV_RL32("stsd") };
2483 int64_t start_pos = avio_tell(pb);
2484 int64_t size = avio_rb32(pb); /* size */
2485 uint32_t format = avio_rl32(pb); /* data format */
2488 avio_rb32(pb); /* reserved */
2489 avio_rb16(pb); /* reserved */
2490 dref_id = avio_rb16(pb);
2491 } else if (size <= 7) {
2492 av_log(c->fc, AV_LOG_ERROR,
2493 "invalid size %"PRId64" in stsd\n", size);
2494 return AVERROR_INVALIDDATA;
2497 if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
2498 size - (avio_tell(pb) - start_pos)))
2501 sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
2502 sc->dref_id= dref_id;
2503 sc->format = format;
2505 id = mov_codec_id(st, format);
2507 av_log(c->fc, AV_LOG_TRACE,
2508 "size=%"PRId64" 4CC=%s codec_type=%d\n", size,
2509 av_fourcc2str(format), st->codecpar->codec_type);
2511 if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
2512 st->codecpar->codec_id = id;
2513 mov_parse_stsd_video(c, pb, st, sc);
2514 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
2515 st->codecpar->codec_id = id;
2516 mov_parse_stsd_audio(c, pb, st, sc);
2517 if (st->codecpar->sample_rate < 0) {
2518 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
2519 return AVERROR_INVALIDDATA;
2521 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
2522 st->codecpar->codec_id = id;
2523 mov_parse_stsd_subtitle(c, pb, st, sc,
2524 size - (avio_tell(pb) - start_pos));
2526 ret = mov_parse_stsd_data(c, pb, st, sc,
2527 size - (avio_tell(pb) - start_pos));
2531 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2532 a.size = size - (avio_tell(pb) - start_pos);
2534 if ((ret = mov_read_default(c, pb, a)) < 0)
2536 } else if (a.size > 0)
2537 avio_skip(pb, a.size);
2539 if (sc->extradata && st->codecpar->extradata) {
2540 int extra_size = st->codecpar->extradata_size;
2542 /* Move the current stream extradata to the stream context one. */
2543 sc->extradata_size[pseudo_stream_id] = extra_size;
2544 sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
2545 if (!sc->extradata[pseudo_stream_id])
2546 return AVERROR(ENOMEM);
2547 memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
2548 av_freep(&st->codecpar->extradata);
2549 st->codecpar->extradata_size = 0;
2553 if (pb->eof_reached)
2559 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2562 MOVStreamContext *sc;
2565 if (c->fc->nb_streams < 1)
2567 st = c->fc->streams[c->fc->nb_streams - 1];
2570 avio_r8(pb); /* version */
2571 avio_rb24(pb); /* flags */
2572 entries = avio_rb32(pb);
2575 av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
2576 return AVERROR_INVALIDDATA;
2579 if (sc->extradata) {
2580 av_log(c->fc, AV_LOG_ERROR,
2581 "Duplicate stsd found in this track.\n");
2582 return AVERROR_INVALIDDATA;
2585 /* Prepare space for hosting multiple extradata. */
2586 sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
2587 sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
2588 if (!sc->extradata_size || !sc->extradata) {
2589 ret = AVERROR(ENOMEM);
2593 ret = ff_mov_read_stsd_entries(c, pb, entries);
2597 sc->stsd_count = entries;
2599 /* Restore back the primary extradata. */
2600 av_freep(&st->codecpar->extradata);
2601 st->codecpar->extradata_size = sc->extradata_size[0];
2602 if (sc->extradata_size[0]) {
2603 st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
2604 if (!st->codecpar->extradata)
2605 return AVERROR(ENOMEM);
2606 memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
2609 return mov_finalize_stsd_codec(c, pb, st, sc);
2611 av_freep(&sc->extradata);
2612 av_freep(&sc->extradata_size);
2616 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2619 MOVStreamContext *sc;
2620 unsigned int i, entries;
2622 if (c->fc->nb_streams < 1)
2624 st = c->fc->streams[c->fc->nb_streams-1];
2627 avio_r8(pb); /* version */
2628 avio_rb24(pb); /* flags */
2630 entries = avio_rb32(pb);
2632 av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
2637 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2638 av_free(sc->stsc_data);
2640 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2642 return AVERROR(ENOMEM);
2644 for (i = 0; i < entries && !pb->eof_reached; i++) {
2645 sc->stsc_data[i].first = avio_rb32(pb);
2646 sc->stsc_data[i].count = avio_rb32(pb);
2647 sc->stsc_data[i].id = avio_rb32(pb);
2652 if (pb->eof_reached)
2658 static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
2660 return index < count - 1;
2663 /* Compute the samples value for the stsc entry at the given index. */
2664 static inline int mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
2668 if (mov_stsc_index_valid(index, sc->stsc_count))
2669 chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
2671 chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
2673 return sc->stsc_data[index].count * chunk_count;
2676 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2679 MOVStreamContext *sc;
2680 unsigned i, entries;
2682 if (c->fc->nb_streams < 1)
2684 st = c->fc->streams[c->fc->nb_streams-1];
2687 avio_rb32(pb); // version + flags
2689 entries = avio_rb32(pb);
2691 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2692 av_free(sc->stps_data);
2694 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2696 return AVERROR(ENOMEM);
2698 for (i = 0; i < entries && !pb->eof_reached; i++) {
2699 sc->stps_data[i] = avio_rb32(pb);
2704 if (pb->eof_reached)
2710 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2713 MOVStreamContext *sc;
2714 unsigned int i, entries;
2716 if (c->fc->nb_streams < 1)
2718 st = c->fc->streams[c->fc->nb_streams-1];
2721 avio_r8(pb); /* version */
2722 avio_rb24(pb); /* flags */
2724 entries = avio_rb32(pb);
2726 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
2730 sc->keyframe_absent = 1;
2731 if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2732 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2736 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2737 if (entries >= UINT_MAX / sizeof(int))
2738 return AVERROR_INVALIDDATA;
2739 av_freep(&sc->keyframes);
2740 sc->keyframe_count = 0;
2741 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2743 return AVERROR(ENOMEM);
2745 for (i = 0; i < entries && !pb->eof_reached; i++) {
2746 sc->keyframes[i] = avio_rb32(pb);
2749 sc->keyframe_count = i;
2751 if (pb->eof_reached)
2757 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2760 MOVStreamContext *sc;
2761 unsigned int i, entries, sample_size, field_size, num_bytes;
2766 if (c->fc->nb_streams < 1)
2768 st = c->fc->streams[c->fc->nb_streams-1];
2771 avio_r8(pb); /* version */
2772 avio_rb24(pb); /* flags */
2774 if (atom.type == MKTAG('s','t','s','z')) {
2775 sample_size = avio_rb32(pb);
2776 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2777 sc->sample_size = sample_size;
2778 sc->stsz_sample_size = sample_size;
2782 avio_rb24(pb); /* reserved */
2783 field_size = avio_r8(pb);
2785 entries = avio_rb32(pb);
2787 av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
2789 sc->sample_count = entries;
2793 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2794 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
2795 return AVERROR_INVALIDDATA;
2800 if (entries >= (UINT_MAX - 4) / field_size)
2801 return AVERROR_INVALIDDATA;
2802 if (sc->sample_sizes)
2803 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2804 av_free(sc->sample_sizes);
2805 sc->sample_count = 0;
2806 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2807 if (!sc->sample_sizes)
2808 return AVERROR(ENOMEM);
2810 num_bytes = (entries*field_size+4)>>3;
2812 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2814 av_freep(&sc->sample_sizes);
2815 return AVERROR(ENOMEM);
2818 ret = ffio_read_size(pb, buf, num_bytes);
2820 av_freep(&sc->sample_sizes);
2825 init_get_bits(&gb, buf, 8*num_bytes);
2827 for (i = 0; i < entries && !pb->eof_reached; i++) {
2828 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2829 sc->data_size += sc->sample_sizes[i];
2832 sc->sample_count = i;
2836 if (pb->eof_reached)
2842 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2845 MOVStreamContext *sc;
2846 unsigned int i, entries;
2848 int64_t total_sample_count=0;
2850 if (c->fc->nb_streams < 1)
2852 st = c->fc->streams[c->fc->nb_streams-1];
2855 avio_r8(pb); /* version */
2856 avio_rb24(pb); /* flags */
2857 entries = avio_rb32(pb);
2859 av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
2860 c->fc->nb_streams-1, entries);
2863 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2864 av_free(sc->stts_data);
2866 sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2868 return AVERROR(ENOMEM);
2870 for (i = 0; i < entries && !pb->eof_reached; i++) {
2871 int sample_duration;
2872 unsigned int sample_count;
2874 sample_count=avio_rb32(pb);
2875 sample_duration = avio_rb32(pb);
2877 sc->stts_data[i].count= sample_count;
2878 sc->stts_data[i].duration= sample_duration;
2880 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2881 sample_count, sample_duration);
2885 && sample_count == 1
2886 && total_sample_count > 100
2887 && sample_duration/10 > duration / total_sample_count)
2888 sample_duration = duration / total_sample_count;
2889 duration+=(int64_t)sample_duration*sample_count;
2890 total_sample_count+=sample_count;
2895 sc->duration_for_fps += duration;
2896 sc->nb_frames_for_fps += total_sample_count;
2898 if (pb->eof_reached)
2901 st->nb_frames= total_sample_count;
2903 st->duration= duration;
2904 sc->track_end = duration;
2908 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2911 if (duration == INT_MIN) {
2912 av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2915 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2919 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2922 MOVStreamContext *sc;
2923 unsigned int i, j, entries, ctts_count = 0;
2925 if (c->fc->nb_streams < 1)
2927 st = c->fc->streams[c->fc->nb_streams-1];
2930 avio_r8(pb); /* version */
2931 avio_rb24(pb); /* flags */
2932 entries = avio_rb32(pb);
2934 av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
2938 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2939 return AVERROR_INVALIDDATA;
2940 av_freep(&sc->ctts_data);
2941 sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
2943 return AVERROR(ENOMEM);
2945 for (i = 0; i < entries && !pb->eof_reached; i++) {
2946 int count =avio_rb32(pb);
2947 int duration =avio_rb32(pb);
2950 av_log(c->fc, AV_LOG_TRACE,
2951 "ignoring CTTS entry with count=%d duration=%d\n",
2956 /* Expand entries such that we have a 1-1 mapping with samples. */
2957 for (j = 0; j < count; j++)
2958 add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size, 1, duration);
2960 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2963 if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2964 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2965 av_freep(&sc->ctts_data);
2971 mov_update_dts_shift(sc, duration);
2974 sc->ctts_count = ctts_count;
2976 if (pb->eof_reached)
2979 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2984 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2987 MOVStreamContext *sc;
2988 unsigned int i, entries;
2990 uint32_t grouping_type;
2992 if (c->fc->nb_streams < 1)
2994 st = c->fc->streams[c->fc->nb_streams-1];
2997 version = avio_r8(pb); /* version */
2998 avio_rb24(pb); /* flags */
2999 grouping_type = avio_rl32(pb);
3000 if (grouping_type != MKTAG( 'r','a','p',' '))
3001 return 0; /* only support 'rap ' grouping */
3003 avio_rb32(pb); /* grouping_type_parameter */
3005 entries = avio_rb32(pb);
3009 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
3010 av_free(sc->rap_group);
3011 sc->rap_group_count = 0;
3012 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
3014 return AVERROR(ENOMEM);
3016 for (i = 0; i < entries && !pb->eof_reached; i++) {
3017 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
3018 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
3021 sc->rap_group_count = i;
3023 return pb->eof_reached ? AVERROR_EOF : 0;
3027 * Get ith edit list entry (media time, duration).
3029 static int get_edit_list_entry(MOVContext *mov,
3030 const MOVStreamContext *msc,
3031 unsigned int edit_list_index,
3032 int64_t *edit_list_media_time,
3033 int64_t *edit_list_duration,
3034 int64_t global_timescale)
3036 if (edit_list_index == msc->elst_count) {
3039 *edit_list_media_time = msc->elst_data[edit_list_index].time;
3040 *edit_list_duration = msc->elst_data[edit_list_index].duration;
3042 /* duration is in global timescale units;convert to msc timescale */
3043 if (global_timescale == 0) {
3044 avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
3047 *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
3053 * Find the closest previous frame to the timestamp, in e_old index
3054 * entries. Searching for just any frame / just key frames can be controlled by
3055 * last argument 'flag'.
3056 * Returns the index of the entry in st->index_entries if successful,
3059 static int64_t find_prev_closest_index(AVStream *st,
3060 AVIndexEntry *e_old,
3065 AVIndexEntry *e_keep = st->index_entries;
3066 int nb_keep = st->nb_index_entries;
3070 st->index_entries = e_old;
3071 st->nb_index_entries = nb_old;
3072 found = av_index_search_timestamp(st, timestamp, flag | AVSEEK_FLAG_BACKWARD);
3074 // Keep going backwards in the index entries until the timestamp is the same.
3076 for (i = found; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
3078 if ((flag & AVSEEK_FLAG_ANY) ||
3079 (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
3085 /* restore AVStream state*/
3086 st->index_entries = e_keep;
3087 st->nb_index_entries = nb_keep;
3092 * Add index entry with the given values, to the end of st->index_entries.
3093 * Returns the new size st->index_entries if successful, else returns -1.
3095 * This function is similar to ff_add_index_entry in libavformat/utils.c
3096 * except that here we are always unconditionally adding an index entry to
3097 * the end, instead of searching the entries list and skipping the add if
3098 * there is an existing entry with the same timestamp.
3099 * This is needed because the mov_fix_index calls this func with the same
3100 * unincremented timestamp for successive discarded frames.
3102 static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
3103 int size, int distance, int flags)
3105 AVIndexEntry *entries, *ie;
3107 const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
3109 // Double the allocation each time, to lower memory fragmentation.
3110 // Another difference from ff_add_index_entry function.
3111 const size_t requested_size =
3112 min_size_needed > st->index_entries_allocated_size ?
3113 FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
3116 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
3119 entries = av_fast_realloc(st->index_entries,
3120 &st->index_entries_allocated_size,
3125 st->index_entries= entries;
3127 index= st->nb_index_entries++;
3128 ie= &entries[index];
3131 ie->timestamp = timestamp;
3132 ie->min_distance= distance;
3139 * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
3140 * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
3142 static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
3143 int64_t* frame_duration_buffer,
3144 int frame_duration_buffer_size) {
3146 av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
3147 for (i = 0; i < frame_duration_buffer_size; i++) {
3148 end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
3149 st->index_entries[end_index - 1 - i].timestamp = end_ts;
3154 * Append a new ctts entry to ctts_data.
3155 * Returns the new ctts_count if successful, else returns -1.
3157 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
3158 int count, int duration)
3160 MOVStts *ctts_buf_new;
3161 const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
3162 const size_t requested_size =
3163 min_size_needed > *allocated_size ?
3164 FFMAX(min_size_needed, 2 * (*allocated_size)) :
3167 if((unsigned)(*ctts_count) + 1 >= UINT_MAX / sizeof(MOVStts))
3170 ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
3175 *ctts_data = ctts_buf_new;
3177 ctts_buf_new[*ctts_count].count = count;
3178 ctts_buf_new[*ctts_count].duration = duration;
3180 *ctts_count = (*ctts_count) + 1;
3184 static void mov_current_sample_inc(MOVStreamContext *sc)
3186 sc->current_sample++;
3187 sc->current_index++;
3188 if (sc->index_ranges &&
3189 sc->current_index >= sc->current_index_range->end &&
3190 sc->current_index_range->end) {
3191 sc->current_index_range++;
3192 sc->current_index = sc->current_index_range->start;
3196 static void mov_current_sample_dec(MOVStreamContext *sc)
3198 sc->current_sample--;
3199 sc->current_index--;
3200 if (sc->index_ranges &&
3201 sc->current_index < sc->current_index_range->start &&
3202 sc->current_index_range > sc->index_ranges) {
3203 sc->current_index_range--;
3204 sc->current_index = sc->current_index_range->end - 1;
3208 static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
3212 sc->current_sample = current_sample;
3213 sc->current_index = current_sample;
3214 if (!sc->index_ranges) {
3218 for (sc->current_index_range = sc->index_ranges;
3219 sc->current_index_range->end;
3220 sc->current_index_range++) {
3221 range_size = sc->current_index_range->end - sc->current_index_range->start;
3222 if (range_size > current_sample) {
3223 sc->current_index = sc->current_index_range->start + current_sample;
3226 current_sample -= range_size;
3231 * Fix st->index_entries, so that it contains only the entries (and the entries
3232 * which are needed to decode them) that fall in the edit list time ranges.
3233 * Also fixes the timestamps of the index entries to match the timeline
3234 * specified the edit lists.
3236 static void mov_fix_index(MOVContext *mov, AVStream *st)
3238 MOVStreamContext *msc = st->priv_data;
3239 AVIndexEntry *e_old = st->index_entries;
3240 int nb_old = st->nb_index_entries;
3241 const AVIndexEntry *e_old_end = e_old + nb_old;
3242 const AVIndexEntry *current = NULL;
3243 MOVStts *ctts_data_old = msc->ctts_data;
3244 int64_t ctts_index_old = 0;
3245 int64_t ctts_sample_old = 0;
3246 int64_t ctts_count_old = msc->ctts_count;
3247 int64_t edit_list_media_time = 0;
3248 int64_t edit_list_duration = 0;
3249 int64_t frame_duration = 0;
3250 int64_t edit_list_dts_counter = 0;
3251 int64_t edit_list_dts_entry_end = 0;
3252 int64_t edit_list_start_ctts_sample = 0;
3254 int64_t curr_ctts = 0;
3255 int64_t min_corrected_pts = -1;
3256 int64_t empty_edits_sum_duration = 0;
3257 int64_t edit_list_index = 0;
3259 int64_t index_ctts_count;
3261 int64_t start_dts = 0;
3262 int64_t edit_list_media_time_dts = 0;
3263 int64_t edit_list_start_encountered = 0;
3264 int64_t search_timestamp = 0;
3265 int64_t* frame_duration_buffer = NULL;
3266 int num_discarded_begin = 0;
3267 int first_non_zero_audio_edit = -1;
3268 int packet_skip_samples = 0;
3269 MOVIndexRange *current_index_range;
3272 if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
3276 // allocate the index ranges array
3277 msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
3278 if (!msc->index_ranges) {
3279 av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
3282 msc->current_index_range = msc->index_ranges;
3283 current_index_range = msc->index_ranges - 1;
3285 // Clean AVStream from traces of old index
3286 st->index_entries = NULL;
3287 st->index_entries_allocated_size = 0;
3288 st->nb_index_entries = 0;
3290 // Clean ctts fields of MOVStreamContext
3291 msc->ctts_data = NULL;
3292 msc->ctts_count = 0;
3293 msc->ctts_index = 0;
3294 msc->ctts_sample = 0;
3295 msc->ctts_allocated_size = 0;
3297 // If the dts_shift is positive (in case of negative ctts values in mov),
3298 // then negate the DTS by dts_shift
3299 if (msc->dts_shift > 0) {
3300 edit_list_dts_entry_end -= msc->dts_shift;
3301 av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
3304 start_dts = edit_list_dts_entry_end;
3306 while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
3307 &edit_list_duration, mov->time_scale)) {
3308 av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
3309 st->index, edit_list_index, edit_list_media_time, edit_list_duration);
3311 edit_list_dts_counter = edit_list_dts_entry_end;
3312 edit_list_dts_entry_end += edit_list_duration;
3313 num_discarded_begin = 0;
3314 if (edit_list_media_time == -1) {
3315 empty_edits_sum_duration += edit_list_duration;
3319 // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
3320 // according to the edit list below.
3321 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3322 if (first_non_zero_audio_edit < 0) {
3323 first_non_zero_audio_edit = 1;
3325 first_non_zero_audio_edit = 0;
3328 if (first_non_zero_audio_edit > 0)
3329 st->skip_samples = msc->start_pad = 0;
3332 //find closest previous key frame
3333 edit_list_media_time_dts = edit_list_media_time;
3334 if (msc->dts_shift > 0) {
3335 edit_list_media_time_dts -= msc->dts_shift;
3338 // While reordering frame index according to edit list we must handle properly
3339 // the scenario when edit list entry starts from none key frame.
3340 // We find closest previous key frame and preserve it and consequent frames in index.
3341 // All frames which are outside edit list entry time boundaries will be dropped after decoding.
3342 search_timestamp = edit_list_media_time_dts;
3343 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3344 // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
3345 // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
3346 // edit_list_media_time to cover the decoder delay.
3347 search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
3350 index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, 0);
3352 av_log(mov->fc, AV_LOG_WARNING,
3353 "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
3354 st->index, edit_list_index, search_timestamp);
3355 index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, AVSEEK_FLAG_ANY);
3358 av_log(mov->fc, AV_LOG_WARNING,
3359 "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n"
3360 "Rounding edit list media time to zero.\n",
3361 st->index, edit_list_index, search_timestamp);
3363 edit_list_media_time = 0;
3366 current = e_old + index;
3369 ctts_sample_old = 0;
3371 // set ctts_index properly for the found key frame
3372 for (index_ctts_count = 0; index_ctts_count < index; index_ctts_count++) {
3373 if (ctts_data_old && ctts_index_old < ctts_count_old) {
3375 if (ctts_data_old[ctts_index_old].count == ctts_sample_old) {
3377 ctts_sample_old = 0;
3382 edit_list_start_ctts_sample = ctts_sample_old;
3384 // Iterate over index and arrange it according to edit list
3385 edit_list_start_encountered = 0;
3386 for (; current < e_old_end; current++, index++) {
3387 // check if frame outside edit list mark it for discard
3388 frame_duration = (current + 1 < e_old_end) ?
3389 ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
3391 flags = current->flags;
3393 // frames (pts) before or after edit list
3394 curr_cts = current->timestamp + msc->dts_shift;
3397 if (ctts_data_old && ctts_index_old < ctts_count_old) {
3398 curr_ctts = ctts_data_old[ctts_index_old].duration;
3399 av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",
3400 curr_cts, curr_ctts, ctts_index_old, ctts_count_old);
3401 curr_cts += curr_ctts;
3403 if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
3404 if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3405 &msc->ctts_allocated_size,
3406 ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3407 ctts_data_old[ctts_index_old].duration) == -1) {
3408 av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3410 ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3411 ctts_data_old[ctts_index_old].duration);
3415 ctts_sample_old = 0;
3416 edit_list_start_ctts_sample = 0;
3420 if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
3421 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
3422 curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
3423 first_non_zero_audio_edit > 0) {
3424 packet_skip_samples = edit_list_media_time - curr_cts;
3425 st->skip_samples += packet_skip_samples;
3427 // Shift the index entry timestamp by packet_skip_samples to be correct.
3428 edit_list_dts_counter -= packet_skip_samples;
3429 if (edit_list_start_encountered == 0) {
3430 edit_list_start_encountered = 1;
3431 // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3432 // discarded packets.
3433 if (frame_duration_buffer) {
3434 fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3435 frame_duration_buffer, num_discarded_begin);
3436 av_freep(&frame_duration_buffer);
3440 av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
3442 flags |= AVINDEX_DISCARD_FRAME;
3443 av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
3445 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
3446 num_discarded_begin++;
3447 frame_duration_buffer = av_realloc(frame_duration_buffer,
3448 num_discarded_begin * sizeof(int64_t));
3449 if (!frame_duration_buffer) {
3450 av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
3453 frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
3455 // Increment skip_samples for the first non-zero audio edit list
3456 if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
3457 st->skip_samples += frame_duration;
3462 if (min_corrected_pts < 0) {
3463 min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
3465 min_corrected_pts = FFMIN(min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
3467 if (edit_list_start_encountered == 0) {
3468 edit_list_start_encountered = 1;
3469 // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3470 // discarded packets.
3471 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
3472 fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3473 frame_duration_buffer, num_discarded_begin);
3474 av_freep(&frame_duration_buffer);
3479 if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
3480 current->min_distance, flags) == -1) {
3481 av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
3485 // Update the index ranges array
3486 if (current_index_range < msc->index_ranges || index != current_index_range->end) {
3487 current_index_range++;
3488 current_index_range->start = index;
3490 current_index_range->end = index + 1;
3492 // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
3493 if (edit_list_start_encountered > 0) {
3494 edit_list_dts_counter = edit_list_dts_counter + frame_duration;
3497 // Break when found first key frame after edit entry completion
3498 if (((curr_cts + frame_duration) >= (edit_list_duration + edit_list_media_time)) &&
3499 ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
3501 if (ctts_data_old && ctts_sample_old != 0) {
3502 if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3503 &msc->ctts_allocated_size,
3504 ctts_sample_old - edit_list_start_ctts_sample,
3505 ctts_data_old[ctts_index_old].duration) == -1) {
3506 av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3507 ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
3508 ctts_data_old[ctts_index_old].duration);
3516 // If there are empty edits, then min_corrected_pts might be positive intentionally. So we subtract the
3517 // sum duration of emtpy edits here.
3518 min_corrected_pts -= empty_edits_sum_duration;
3520 // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
3521 // dts by that amount to make the first pts zero.
3522 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && min_corrected_pts > 0) {
3523 av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", min_corrected_pts);
3524 for (i = 0; i < st->nb_index_entries; ++i) {
3525 st->index_entries[i].timestamp -= min_corrected_pts;
3529 // Update av stream length
3530 st->duration = edit_list_dts_entry_end - start_dts;
3531 msc->start_pad = st->skip_samples;
3533 // Free the old index and the old CTTS structures
3535 av_free(ctts_data_old);
3537 // Null terminate the index ranges array
3538 current_index_range++;
3539 current_index_range->start = 0;
3540 current_index_range->end = 0;
3541 msc->current_index = msc->index_ranges[0].start;
3544 static void mov_build_index(MOVContext *mov, AVStream *st)
3546 MOVStreamContext *sc = st->priv_data;
3547 int64_t current_offset;
3548 int64_t current_dts = 0;
3549 unsigned int stts_index = 0;
3550 unsigned int stsc_index = 0;
3551 unsigned int stss_index = 0;
3552 unsigned int stps_index = 0;
3554 uint64_t stream_size = 0;
3556 if (sc->elst_count) {
3557 int i, edit_start_index = 0, multiple_edits = 0;
3558 int64_t empty_duration = 0; // empty duration of the first edit list entry
3559 int64_t start_time = 0; // start time of the media
3561 for (i = 0; i < sc->elst_count; i++) {
3562 const MOVElst *e = &sc->elst_data[i];
3563 if (i == 0 && e->time == -1) {
3564 /* if empty, the first entry is the start time of the stream
3565 * relative to the presentation itself */
3566 empty_duration = e->duration;
3567 edit_start_index = 1;
3568 } else if (i == edit_start_index && e->time >= 0) {
3569 start_time = e->time;
3575 if (multiple_edits && !mov->advanced_editlist)
3576 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
3577 "Use -advanced_editlist to correctly decode otherwise "
3578 "a/v desync might occur\n");
3580 /* adjust first dts according to edit list */
3581 if ((empty_duration || start_time) && mov->time_scale > 0) {
3583 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
3584 sc->time_offset = start_time - empty_duration;
3585 if (!mov->advanced_editlist)
3586 current_dts = -sc->time_offset;
3589 if (!multiple_edits && !mov->advanced_editlist &&
3590 st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
3591 sc->start_pad = start_time;
3594 /* only use old uncompressed audio chunk demuxing when stts specifies it */
3595 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
3596 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
3597 unsigned int current_sample = 0;
3598 unsigned int stts_sample = 0;
3599 unsigned int sample_size;
3600 unsigned int distance = 0;
3601 unsigned int rap_group_index = 0;
3602 unsigned int rap_group_sample = 0;
3603 int64_t last_dts = 0;
3604 int64_t dts_correction = 0;
3605 int rap_group_present = sc->rap_group_count && sc->rap_group;
3606 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
3608 current_dts -= sc->dts_shift;
3609 last_dts = current_dts;
3611 if (!sc->sample_count || st->nb_index_entries)
3613 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3615 if (av_reallocp_array(&st->index_entries,
3616 st->nb_index_entries + sc->sample_count,
3617 sizeof(*st->index_entries)) < 0) {
3618 st->nb_index_entries = 0;
3621 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
3623 for (i = 0; i < sc->chunk_count; i++) {
3624 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
3625 current_offset = sc->chunk_offsets[i];
3626 while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3627 i + 1 == sc->stsc_data[stsc_index + 1].first)
3630 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
3631 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
3632 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
3633 sc->stsz_sample_size = sc->sample_size;
3635 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
3636 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
3637 sc->stsz_sample_size = sc->sample_size;
3640 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
3642 if (current_sample >= sc->sample_count) {
3643 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
3647 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
3649 if (stss_index + 1 < sc->keyframe_count)
3651 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
3653 if (stps_index + 1 < sc->stps_count)
3656 if (rap_group_present && rap_group_index < sc->rap_group_count) {
3657 if (sc->rap_group[rap_group_index].index > 0)
3659 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
3660 rap_group_sample = 0;
3664 if (sc->keyframe_absent
3666 && !rap_group_present
3667 && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
3671 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
3672 if (sc->pseudo_stream_id == -1 ||
3673 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
3675 if (sample_size > 0x3FFFFFFF) {
3676 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
3679 e = &st->index_entries[st->nb_index_entries++];
3680 e->pos = current_offset;
3681 e->timestamp = current_dts;
3682 e->size = sample_size;
3683 e->min_distance = distance;
3684 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
3685 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
3686 "size %u, distance %u, keyframe %d\n", st->index, current_sample,
3687 current_offset, current_dts, sample_size, distance, keyframe);
3688 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
3689 ff_rfps_add_frame(mov->fc, st, current_dts);
3692 current_offset += sample_size;
3693 stream_size += sample_size;
3695 /* A negative sample duration is invalid based on the spec,
3696 * but some samples need it to correct the DTS. */
3697 if (sc->stts_data[stts_index].duration < 0) {
3698 av_log(mov->fc, AV_LOG_WARNING,
3699 "Invalid SampleDelta %d in STTS, at %d st:%d\n",
3700 sc->stts_data[stts_index].duration, stts_index,
3702 dts_correction += sc->stts_data[stts_index].duration - 1;
3703 sc->stts_data[stts_index].duration = 1;
3705 current_dts += sc->stts_data[stts_index].duration;
3706 if (!dts_correction || current_dts + dts_correction > last_dts) {
3707 current_dts += dts_correction;
3710 /* Avoid creating non-monotonous DTS */
3711 dts_correction += current_dts - last_dts - 1;
3712 current_dts = last_dts + 1;
3714 last_dts = current_dts;
3718 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
3724 if (st->duration > 0)
3725 st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
3727 unsigned chunk_samples, total = 0;
3729 // compute total chunk count
3730 for (i = 0; i < sc->stsc_count; i++) {
3731 unsigned count, chunk_count;
3733 chunk_samples = sc->stsc_data[i].count;
3734 if (i != sc->stsc_count - 1 &&
3735 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
3736 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
3740 if (sc->samples_per_frame >= 160) { // gsm
3741 count = chunk_samples / sc->samples_per_frame;
3742 } else if (sc->samples_per_frame > 1) {
3743 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
3744 count = (chunk_samples+samples-1) / samples;
3746 count = (chunk_samples+1023) / 1024;
3749 if (mov_stsc_index_valid(i, sc->stsc_count))
3750 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
3752 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
3753 total += chunk_count * count;
3756 av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
3757 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3759 if (av_reallocp_array(&st->index_entries,
3760 st->nb_index_entries + total,
3761 sizeof(*st->index_entries)) < 0) {
3762 st->nb_index_entries = 0;
3765 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
3768 for (i = 0; i < sc->chunk_count; i++) {
3769 current_offset = sc->chunk_offsets[i];
3770 if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3771 i + 1 == sc->stsc_data[stsc_index + 1].first)
3773 chunk_samples = sc->stsc_data[stsc_index].count;
3775 while (chunk_samples > 0) {
3777 unsigned size, samples;
3779 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
3780 avpriv_request_sample(mov->fc,
3781 "Zero bytes per frame, but %d samples per frame",
3782 sc->samples_per_frame);
3786 if (sc->samples_per_frame >= 160) { // gsm
3787 samples = sc->samples_per_frame;
3788 size = sc->bytes_per_frame;
3790 if (sc->samples_per_frame > 1) {
3791 samples = FFMIN((1024 / sc->samples_per_frame)*
3792 sc->samples_per_frame, chunk_samples);
3793 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
3795 samples = FFMIN(1024, chunk_samples);
3796 size = samples * sc->sample_size;
3800 if (st->nb_index_entries >= total) {
3801 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
3804 if (size > 0x3FFFFFFF) {
3805 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
3808 e = &st->index_entries[st->nb_index_entries++];
3809 e->pos = current_offset;
3810 e->timestamp = current_dts;
3812 e->min_distance = 0;
3813 e->flags = AVINDEX_KEYFRAME;
3814 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
3815 "size %u, duration %u\n", st->index, i, current_offset, current_dts,
3818 current_offset += size;
3819 current_dts += samples;
3820 chunk_samples -= samples;
3825 if (!mov->ignore_editlist && mov->advanced_editlist) {
3826 // Fix index according to edit lists.
3827 mov_fix_index(mov, st);
3831 static int test_same_origin(const char *src, const char *ref) {
3841 av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
3842 av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
3844 if (strlen(src) == 0) {
3846 } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
3847 strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
3848 strlen(src_host) + 1 >= sizeof(src_host) ||
3849 strlen(ref_host) + 1 >= sizeof(ref_host)) {
3851 } else if (strcmp(src_proto, ref_proto) ||
3852 strcmp(src_auth, ref_auth) ||
3853 strcmp(src_host, ref_host) ||
3854 src_port != ref_port) {
3860 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
3862 /* try relative path, we do not try the absolute because it can leak information about our
3863 system to an attacker */
3864 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
3865 char filename[1025];
3866 const char *src_path;
3869 /* find a source dir */
3870 src_path = strrchr(src, '/');
3876 /* find a next level down to target */
3877 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
3878 if (ref->path[l] == '/') {
3879 if (i == ref->nlvl_to - 1)
3885 /* compose filename if next level down to target was found */
3886 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
3887 memcpy(filename, src, src_path - src);
3888 filename[src_path - src] = 0;
3890 for (i = 1; i < ref->nlvl_from; i++)
3891 av_strlcat(filename, "../", sizeof(filename));
3893 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
3894 if (!c->use_absolute_path) {
3895 int same_origin = test_same_origin(src, filename);
3898 av_log(c->fc, AV_LOG_ERROR,
3899 "Reference with mismatching origin, %s not tried for security reasons, "
3900 "set demuxer option use_absolute_path to allow it anyway\n",
3902 return AVERROR(ENOENT);
3905 if(strstr(ref->path + l + 1, "..") ||
3906 strstr(ref->path + l + 1, ":") ||
3907 (ref->nlvl_from > 1 && same_origin < 0) ||
3908 (filename[0] == '/' && src_path == src))
3909 return AVERROR(ENOENT);
3912 if (strlen(filename) + 1 == sizeof(filename))
3913 return AVERROR(ENOENT);
3914 if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
3917 } else if (c->use_absolute_path) {
3918 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
3919 "this is a possible security issue\n");
3920 if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
3923 av_log(c->fc, AV_LOG_ERROR,
3924 "Absolute path %s not tried for security reasons, "
3925 "set demuxer option use_absolute_path to allow absolute paths\n",
3929 return AVERROR(ENOENT);
3932 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
3934 if (sc->time_scale <= 0) {
3935 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
3936 sc->time_scale = c->time_scale;
3937 if (sc->time_scale <= 0)
3942 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3945 MOVStreamContext *sc;
3948 st = avformat_new_stream(c->fc, NULL);
3949 if (!st) return AVERROR(ENOMEM);
3950 st->id = c->fc->nb_streams;
3951 sc = av_mallocz(sizeof(MOVStreamContext));
3952 if (!sc) return AVERROR(ENOMEM);
3955 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
3956 sc->ffindex = st->index;
3957 c->trak_index = st->index;
3959 if ((ret = mov_read_default(c, pb, atom)) < 0)
3965 if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
3966 (!sc->sample_size && !sc->sample_count))) ||
3967 (!sc->chunk_count && sc->sample_count)) {
3968 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
3973 fix_timescale(c, sc);
3975 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
3977 mov_build_index(c, st);
3979 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
3980 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
3981 if (c->enable_drefs) {
3982 if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
3983 av_log(c->fc, AV_LOG_ERROR,
3984 "stream %d, error opening alias: path='%s', dir='%s', "
3985 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
3986 st->index, dref->path, dref->dir, dref->filename,
3987 dref->volume, dref->nlvl_from, dref->nlvl_to);
3989 av_log(c->fc, AV_LOG_WARNING,
3990 "Skipped opening external track: "
3991 "stream %d, alias: path='%s', dir='%s', "
3992 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
3993 "Set enable_drefs to allow this.\n",
3994 st->index, dref->path, dref->dir, dref->filename,
3995 dref->volume, dref->nlvl_from, dref->nlvl_to);
3999 sc->pb_is_copied = 1;
4002 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
4003 if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
4004 sc->height && sc->width &&
4005 (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
4006 st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
4007 ((double)st->codecpar->width * sc->height), INT_MAX);
4010 #if FF_API_R_FRAME_RATE
4011 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
4012 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
4013 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
4017 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
4018 if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
4019 TAG_IS_AVCI(st->codecpar->codec_tag)) {
4020 ret = ff_generate_avci_extradata(st);
4025 switch (st->codecpar->codec_id) {
4026 #if CONFIG_H261_DECODER
4027 case AV_CODEC_ID_H261:
4029 #if CONFIG_H263_DECODER
4030 case AV_CODEC_ID_H263:
4032 #if CONFIG_MPEG4_DECODER
4033 case AV_CODEC_ID_MPEG4:
4035 st->codecpar->width = 0; /* let decoder init width/height */
4036 st->codecpar->height= 0;
4040 // If the duration of the mp3 packets is not constant, then they could need a parser
4041 if (st->codecpar->codec_id == AV_CODEC_ID_MP3
4042 && sc->stts_count > 3
4043 && sc->stts_count*10 > st->nb_frames
4044 && sc->time_scale == st->codecpar->sample_rate) {
4045 st->need_parsing = AVSTREAM_PARSE_FULL;
4047 /* Do not need those anymore. */
4048 av_freep(&sc->chunk_offsets);
4049 av_freep(&sc->sample_sizes);
4050 av_freep(&sc->keyframes);
4051 av_freep(&sc->stts_data);
4052 av_freep(&sc->stps_data);
4053 av_freep(&sc->elst_data);
4054 av_freep(&sc->rap_group);
4059 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4062 c->itunes_metadata = 1;
4063 ret = mov_read_default(c, pb, atom);
4064 c->itunes_metadata = 0;
4068 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4077 count = avio_rb32(pb);
4078 if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
4079 av_log(c->fc, AV_LOG_ERROR,
4080 "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
4081 return AVERROR_INVALIDDATA;
4084 c->meta_keys_count = count + 1;
4085 c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
4087 return AVERROR(ENOMEM);
4089 for (i = 1; i <= count; ++i) {
4090 uint32_t key_size = avio_rb32(pb);
4091 uint32_t type = avio_rl32(pb);
4093 av_log(c->fc, AV_LOG_ERROR,
4094 "The key# %"PRIu32" in meta has invalid size:"
4095 "%"PRIu32"\n", i, key_size);
4096 return AVERROR_INVALIDDATA;
4099 if (type != MKTAG('m','d','t','a')) {
4100 avio_skip(pb, key_size);
4102 c->meta_keys[i] = av_mallocz(key_size + 1);
4103 if (!c->meta_keys[i])
4104 return AVERROR(ENOMEM);
4105 avio_read(pb, c->meta_keys[i], key_size);
4111 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4113 int64_t end = avio_tell(pb) + atom.size;
4114 uint8_t *key = NULL, *val = NULL, *mean = NULL;
4118 MOVStreamContext *sc;
4120 if (c->fc->nb_streams < 1)
4122 st = c->fc->streams[c->fc->nb_streams-1];
4125 for (i = 0; i < 3; i++) {
4129 if (end - avio_tell(pb) <= 12)
4132 len = avio_rb32(pb);
4133 tag = avio_rl32(pb);
4134 avio_skip(pb, 4); // flags
4136 if (len < 12 || len - 12 > end - avio_tell(pb))
4140 if (tag == MKTAG('m', 'e', 'a', 'n'))
4142 else if (tag == MKTAG('n', 'a', 'm', 'e'))
4144 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
4151 *p = av_malloc(len + 1);
4154 ret = ffio_read_size(pb, *p, len);
4162 if (mean && key && val) {
4163 if (strcmp(key, "iTunSMPB") == 0) {
4164 int priming, remainder, samples;
4165 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
4166 if(priming>0 && priming<16384)
4167 sc->start_pad = priming;
4170 if (strcmp(key, "cdec") != 0) {
4171 av_dict_set(&c->fc->metadata, key, val,
4172 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
4176 av_log(c->fc, AV_LOG_VERBOSE,
4177 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
4180 avio_seek(pb, end, SEEK_SET);
4187 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4189 while (atom.size > 8) {
4190 uint32_t tag = avio_rl32(pb);
4192 if (tag == MKTAG('h','d','l','r')) {
4193 avio_seek(pb, -8, SEEK_CUR);
4195 return mov_read_default(c, pb, atom);
4201 // return 1 when matrix is identity, 0 otherwise
4202 #define IS_MATRIX_IDENT(matrix) \
4203 ( (matrix)[0][0] == (1 << 16) && \
4204 (matrix)[1][1] == (1 << 16) && \
4205 (matrix)[2][2] == (1 << 30) && \
4206 !(matrix)[0][1] && !(matrix)[0][2] && \
4207 !(matrix)[1][0] && !(matrix)[1][2] && \
4208 !(matrix)[2][0] && !(matrix)[2][1])
4210 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4215 int display_matrix[3][3];
4216 int res_display_matrix[3][3] = { { 0 } };
4218 MOVStreamContext *sc;
4222 if (c->fc->nb_streams < 1)
4224 st = c->fc->streams[c->fc->nb_streams-1];
4227 version = avio_r8(pb);
4228 flags = avio_rb24(pb);
4229 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
4235 avio_rb32(pb); /* creation time */
4236 avio_rb32(pb); /* modification time */
4238 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
4239 avio_rb32(pb); /* reserved */
4241 /* highlevel (considering edits) duration in movie timebase */
4242 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
4243 avio_rb32(pb); /* reserved */
4244 avio_rb32(pb); /* reserved */
4246 avio_rb16(pb); /* layer */
4247 avio_rb16(pb); /* alternate group */
4248 avio_rb16(pb); /* volume */
4249 avio_rb16(pb); /* reserved */
4251 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
4252 // they're kept in fixed point format through all calculations
4253 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
4254 // side data, but the scale factor is not needed to calculate aspect ratio
4255 for (i = 0; i < 3; i++) {
4256 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
4257 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
4258 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
4261 width = avio_rb32(pb); // 16.16 fixed point track width
4262 height = avio_rb32(pb); // 16.16 fixed point track height
4263 sc->width = width >> 16;
4264 sc->height = height >> 16;
4266 // apply the moov display matrix (after the tkhd one)
4267 for (i = 0; i < 3; i++) {
4268 const int sh[3] = { 16, 16, 30 };
4269 for (j = 0; j < 3; j++) {
4270 for (e = 0; e < 3; e++) {
4271 res_display_matrix[i][j] +=
4272 ((int64_t) display_matrix[i][e] *
4273 c->movie_display_matrix[e][j]) >> sh[e];
4278 // save the matrix when it is not the default identity
4279 if (!IS_MATRIX_IDENT(res_display_matrix)) {
4282 av_freep(&sc->display_matrix);
4283 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
4284 if (!sc->display_matrix)
4285 return AVERROR(ENOMEM);
4287 for (i = 0; i < 3; i++)
4288 for (j = 0; j < 3; j++)
4289 sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
4291 #if FF_API_OLD_ROTATE_API
4292 rotate = av_display_rotation_get(sc->display_matrix);
4293 if (!isnan(rotate)) {
4294 char rotate_buf[64];
4296 if (rotate < 0) // for backward compatibility
4298 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
4299 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
4304 // transform the display width/height according to the matrix
4305 // to keep the same scale, use [width height 1<<16]
4306 if (width && height && sc->display_matrix) {
4307 double disp_transform[2];
4309 for (i = 0; i < 2; i++)
4310 disp_transform[i] = hypot(sc->display_matrix[0 + i],
4311 sc->display_matrix[3 + i]);
4313 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
4314 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
4315 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
4316 st->sample_aspect_ratio = av_d2q(
4317 disp_transform[0] / disp_transform[1],
4323 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4325 MOVFragment *frag = &c->fragment;
4326 MOVTrackExt *trex = NULL;
4327 int flags, track_id, i;
4329 avio_r8(pb); /* version */
4330 flags = avio_rb24(pb);
4332 track_id = avio_rb32(pb);
4334 return AVERROR_INVALIDDATA;
4335 frag->track_id = track_id;
4336 set_frag_stream(&c->frag_index, track_id);
4337 for (i = 0; i < c->trex_count; i++)
4338 if (c->trex_data[i].track_id == frag->track_id) {
4339 trex = &c->trex_data[i];
4343 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
4344 return AVERROR_INVALIDDATA;
4347 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
4348 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
4349 frag->moof_offset : frag->implicit_offset;
4350 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
4352 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
4353 avio_rb32(pb) : trex->duration;
4354 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
4355 avio_rb32(pb) : trex->size;
4356 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
4357 avio_rb32(pb) : trex->flags;
4358 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
4363 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4368 num = atom.size / 4;
4369 if (!(new_tracks = av_malloc_array(num, sizeof(int))))
4370 return AVERROR(ENOMEM);
4372 av_free(c->chapter_tracks);
4373 c->chapter_tracks = new_tracks;
4374 c->nb_chapter_tracks = num;
4376 for (i = 0; i < num && !pb->eof_reached; i++)
4377 c->chapter_tracks[i] = avio_rb32(pb);
4382 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4387 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
4388 return AVERROR_INVALIDDATA;
4389 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
4390 sizeof(*c->trex_data))) < 0) {
4395 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
4397 trex = &c->trex_data[c->trex_count++];
4398 avio_r8(pb); /* version */
4399 avio_rb24(pb); /* flags */
4400 trex->track_id = avio_rb32(pb);
4401 trex->stsd_id = avio_rb32(pb);
4402 trex->duration = avio_rb32(pb);
4403 trex->size = avio_rb32(pb);
4404 trex->flags = avio_rb32(pb);
4408 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4410 MOVFragment *frag = &c->fragment;
4411 AVStream *st = NULL;
4412 MOVStreamContext *sc;
4414 MOVFragmentStreamInfo * frag_stream_info;
4415 int64_t base_media_decode_time;
4417 for (i = 0; i < c->fc->nb_streams; i++) {
4418 if (c->fc->streams[i]->id == frag->track_id) {
4419 st = c->fc->streams[i];
4424 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4425 return AVERROR_INVALIDDATA;
4428 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
4430 version = avio_r8(pb);
4431 avio_rb24(pb); /* flags */
4433 base_media_decode_time = avio_rb64(pb);
4435 base_media_decode_time = avio_rb32(pb);
4438 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4439 if (frag_stream_info)
4440 frag_stream_info->tfdt_dts = base_media_decode_time;
4441 sc->track_end = base_media_decode_time;
4446 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4448 MOVFragment *frag = &c->fragment;
4449 AVStream *st = NULL;
4450 MOVStreamContext *sc;
4453 int64_t dts, pts = AV_NOPTS_VALUE;
4454 int data_offset = 0;
4455 unsigned entries, first_sample_flags = frag->flags;
4456 int flags, distance, i;
4457 int64_t prev_dts = AV_NOPTS_VALUE;
4458 int next_frag_index = -1, index_entry_pos;
4459 size_t requested_size;
4460 AVIndexEntry *new_entries;
4461 MOVFragmentStreamInfo * frag_stream_info;
4463 for (i = 0; i < c->fc->nb_streams; i++) {
4464 if (c->fc->streams[i]->id == frag->track_id) {
4465 st = c->fc->streams[i];
4470 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4471 return AVERROR_INVALIDDATA;
4474 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
4477 // Find the next frag_index index that has a valid index_entry for
4478 // the current track_id.
4480 // A valid index_entry means the trun for the fragment was read
4481 // and it's samples are in index_entries at the given position.
4482 // New index entries will be inserted before the index_entry found.
4483 index_entry_pos = st->nb_index_entries;
4484 for (i = c->frag_index.current + 1; i < c->frag_index.nb_items; i++) {
4485 frag_stream_info = get_frag_stream_info(&c->frag_index, i, frag->track_id);
4486 if (frag_stream_info && frag_stream_info->index_entry >= 0) {
4487 next_frag_index = i;
4488 index_entry_pos = frag_stream_info->index_entry;
4493 avio_r8(pb); /* version */
4494 flags = avio_rb24(pb);
4495 entries = avio_rb32(pb);
4496 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
4498 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
4499 return AVERROR_INVALIDDATA;
4500 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
4501 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
4503 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4504 if (frag_stream_info)
4506 if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE &&
4507 c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
4508 pts = frag_stream_info->first_tfra_pts;
4509 av_log(c->fc, AV_LOG_DEBUG, "found mfra time %"PRId64
4510 ", using it for pts\n", pts);
4511 } else if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE) {
4512 // FIXME: sidx earliest_presentation_time is *PTS*, s.b.
4513 // pts = frag_stream_info->sidx_pts;
4514 dts = frag_stream_info->sidx_pts - sc->time_offset;
4515 av_log(c->fc, AV_LOG_DEBUG, "found sidx time %"PRId64
4516 ", using it for pts\n", pts);
4517 } else if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE) {
4518 dts = frag_stream_info->tfdt_dts - sc->time_offset;
4519 av_log(c->fc, AV_LOG_DEBUG, "found tfdt time %"PRId64
4520 ", using it for dts\n", dts);
4522 dts = sc->track_end - sc->time_offset;
4523 av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4524 ", using it for dts\n", dts);
4527 dts = sc->track_end - sc->time_offset;
4528 av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4529 ", using it for dts\n", dts);
4531 offset = frag->base_data_offset + data_offset;
4533 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
4535 // realloc space for new index entries
4536 if((unsigned)st->nb_index_entries + entries >= UINT_MAX / sizeof(AVIndexEntry)) {
4537 entries = UINT_MAX / sizeof(AVIndexEntry) - st->nb_index_entries;
4538 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
4543 requested_size = (st->nb_index_entries + entries) * sizeof(AVIndexEntry);
4544 new_entries = av_fast_realloc(st->index_entries,
4545 &st->index_entries_allocated_size,
4548 return AVERROR(ENOMEM);
4549 st->index_entries= new_entries;
4551 requested_size = (st->nb_index_entries + entries) * sizeof(*sc->ctts_data);
4552 ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size,
4555 return AVERROR(ENOMEM);
4556 sc->ctts_data = ctts_data;
4558 // In case there were samples without ctts entries, ensure they get
4559 // zero valued entries. This ensures clips which mix boxes with and
4560 // without ctts entries don't pickup uninitialized data.
4561 memset(sc->ctts_data + sc->ctts_count, 0,
4562 (st->nb_index_entries - sc->ctts_count) * sizeof(*sc->ctts_data));
4564 if (index_entry_pos < st->nb_index_entries) {
4565 // Make hole in index_entries and ctts_data for new samples
4566 memmove(st->index_entries + index_entry_pos + entries,
4567 st->index_entries + index_entry_pos,
4568 sizeof(*st->index_entries) *
4569 (st->nb_index_entries - index_entry_pos));
4570 memmove(sc->ctts_data + index_entry_pos + entries,
4571 sc->ctts_data + index_entry_pos,
4572 sizeof(*sc->ctts_data) * (sc->ctts_count - index_entry_pos));
4573 if (index_entry_pos < sc->current_sample) {
4574 sc->current_sample += entries;
4578 st->nb_index_entries += entries;
4579 sc->ctts_count = st->nb_index_entries;
4581 // Record the index_entry position in frag_index of this fragment
4582 if (frag_stream_info)
4583 frag_stream_info->index_entry = index_entry_pos;
4585 if (index_entry_pos > 0)
4586 prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4588 for (i = 0; i < entries && !pb->eof_reached; i++) {
4589 unsigned sample_size = frag->size;
4590 int sample_flags = i ? frag->flags : first_sample_flags;
4591 unsigned sample_duration = frag->duration;
4592 unsigned ctts_duration = 0;
4594 int index_entry_flags = 0;
4596 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
4597 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
4598 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
4599 if (flags & MOV_TRUN_SAMPLE_CTS) ctts_duration = avio_rb32(pb);
4601 mov_update_dts_shift(sc, ctts_duration);
4602 if (pts != AV_NOPTS_VALUE) {
4603 dts = pts - sc->dts_shift;
4604 if (flags & MOV_TRUN_SAMPLE_CTS) {
4605 dts -= ctts_duration;
4607 dts -= sc->time_offset;
4609 av_log(c->fc, AV_LOG_DEBUG,
4610 "pts %"PRId64" calculated dts %"PRId64
4611 " sc->dts_shift %d ctts.duration %d"
4612 " sc->time_offset %"PRId64
4613 " flags & MOV_TRUN_SAMPLE_CTS %d\n",
4615 sc->dts_shift, ctts_duration,
4616 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
4617 pts = AV_NOPTS_VALUE;
4620 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4624 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
4625 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
4628 index_entry_flags |= AVINDEX_KEYFRAME;
4630 // Fragments can overlap in time. Discard overlapping frames after
4632 if (prev_dts >= dts)
4633 index_entry_flags |= AVINDEX_DISCARD_FRAME;
4635 st->index_entries[index_entry_pos].pos = offset;
4636 st->index_entries[index_entry_pos].timestamp = dts;
4637 st->index_entries[index_entry_pos].size= sample_size;
4638 st->index_entries[index_entry_pos].min_distance= distance;
4639 st->index_entries[index_entry_pos].flags = index_entry_flags;
4641 sc->ctts_data[index_entry_pos].count = 1;
4642 sc->ctts_data[index_entry_pos].duration = ctts_duration;
4645 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
4646 "size %u, distance %d, keyframe %d\n", st->index,
4647 index_entry_pos, offset, dts, sample_size, distance, keyframe);
4649 dts += sample_duration;
4650 offset += sample_size;
4651 sc->data_size += sample_size;
4652 sc->duration_for_fps += sample_duration;
4653 sc->nb_frames_for_fps ++;
4656 // EOF found before reading all entries. Fix the hole this would
4657 // leave in index_entries and ctts_data
4658 int gap = entries - i;
4659 memmove(st->index_entries + index_entry_pos,
4660 st->index_entries + index_entry_pos + gap,
4661 sizeof(*st->index_entries) *
4662 (st->nb_index_entries - (index_entry_pos + gap)));
4663 memmove(sc->ctts_data + index_entry_pos,
4664 sc->ctts_data + index_entry_pos + gap,
4665 sizeof(*sc->ctts_data) *
4666 (sc->ctts_count - (index_entry_pos + gap)));
4668 st->nb_index_entries -= gap;
4669 sc->ctts_count -= gap;
4670 if (index_entry_pos < sc->current_sample) {
4671 sc->current_sample -= gap;
4676 // The end of this new fragment may overlap in time with the start
4677 // of the next fragment in index_entries. Mark the samples in the next
4678 // fragment that overlap with AVINDEX_DISCARD_FRAME
4679 prev_dts = AV_NOPTS_VALUE;
4680 if (index_entry_pos > 0)
4681 prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4682 for (i = index_entry_pos; i < st->nb_index_entries; i++) {
4683 if (prev_dts < st->index_entries[i].timestamp)
4685 st->index_entries[i].flags |= AVINDEX_DISCARD_FRAME;
4688 // If a hole was created to insert the new index_entries into,
4689 // the index_entry recorded for all subsequent moof must
4690 // be incremented by the number of entries inserted.
4691 fix_frag_index_entries(&c->frag_index, next_frag_index,
4692 frag->track_id, entries);
4694 if (pb->eof_reached)
4697 frag->implicit_offset = offset;
4699 sc->track_end = dts + sc->time_offset;
4700 if (st->duration < sc->track_end)
4701 st->duration = sc->track_end;
4706 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4708 int64_t offset = avio_tell(pb) + atom.size, pts, timestamp;
4710 unsigned i, j, track_id, item_count;
4711 AVStream *st = NULL;
4712 AVStream *ref_st = NULL;
4713 MOVStreamContext *sc, *ref_sc = NULL;
4714 AVRational timescale;
4716 version = avio_r8(pb);
4718 avpriv_request_sample(c->fc, "sidx version %u", version);
4722 avio_rb24(pb); // flags
4724 track_id = avio_rb32(pb); // Reference ID
4725 for (i = 0; i < c->fc->nb_streams; i++) {
4726 if (c->fc->streams[i]->id == track_id) {
4727 st = c->fc->streams[i];
4732 av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
4738 timescale = av_make_q(1, avio_rb32(pb));
4740 if (timescale.den <= 0) {
4741 av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
4742 return AVERROR_INVALIDDATA;
4746 pts = avio_rb32(pb);
4747 offset += avio_rb32(pb);
4749 pts = avio_rb64(pb);
4750 offset += avio_rb64(pb);
4753 avio_rb16(pb); // reserved
4755 item_count = avio_rb16(pb);
4757 for (i = 0; i < item_count; i++) {
4759 MOVFragmentStreamInfo * frag_stream_info;
4760 uint32_t size = avio_rb32(pb);
4761 uint32_t duration = avio_rb32(pb);
4762 if (size & 0x80000000) {
4763 avpriv_request_sample(c->fc, "sidx reference_type 1");
4764 return AVERROR_PATCHWELCOME;
4766 avio_rb32(pb); // sap_flags
4767 timestamp = av_rescale_q(pts, st->time_base, timescale);
4769 index = update_frag_index(c, offset);
4770 frag_stream_info = get_frag_stream_info(&c->frag_index, index, track_id);
4771 if (frag_stream_info)
4772 frag_stream_info->sidx_pts = timestamp;
4778 st->duration = sc->track_end = pts;
4782 if (offset == avio_size(pb)) {
4783 // Find first entry in fragment index that came from an sidx.
4784 // This will pretty much always be the first entry.
4785 for (i = 0; i < c->frag_index.nb_items; i++) {
4786 MOVFragmentIndexItem * item = &c->frag_index.item[i];
4787 for (j = 0; ref_st == NULL && j < item->nb_stream_info; j++) {
4788 MOVFragmentStreamInfo * si;
4789 si = &item->stream_info[j];
4790 if (si->sidx_pts != AV_NOPTS_VALUE) {
4791 ref_st = c->fc->streams[i];
4792 ref_sc = ref_st->priv_data;
4797 for (i = 0; i < c->fc->nb_streams; i++) {
4798 st = c->fc->streams[i];
4800 if (!sc->has_sidx) {
4801 st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
4805 c->frag_index.complete = 1;
4811 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
4812 /* like the files created with Adobe Premiere 5.0, for samples see */
4813 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
4814 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4819 return 0; /* continue */
4820 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
4821 avio_skip(pb, atom.size - 4);
4824 atom.type = avio_rl32(pb);
4826 if (atom.type != MKTAG('m','d','a','t')) {
4827 avio_skip(pb, atom.size);
4830 err = mov_read_mdat(c, pb, atom);
4834 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4839 uint8_t *moov_data; /* uncompressed data */
4840 long cmov_len, moov_len;
4843 avio_rb32(pb); /* dcom atom */
4844 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
4845 return AVERROR_INVALIDDATA;
4846 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
4847 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
4848 return AVERROR_INVALIDDATA;
4850 avio_rb32(pb); /* cmvd atom */
4851 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
4852 return AVERROR_INVALIDDATA;
4853 moov_len = avio_rb32(pb); /* uncompressed size */
4854 cmov_len = atom.size - 6 * 4;
4856 cmov_data = av_malloc(cmov_len);
4858 return AVERROR(ENOMEM);
4859 moov_data = av_malloc(moov_len);
4862 return AVERROR(ENOMEM);
4864 ret = ffio_read_size(pb, cmov_data, cmov_len);
4866 goto free_and_return;
4868 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
4869 goto free_and_return;
4870 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
4871 goto free_and_return;
4872 ctx.seekable = AVIO_SEEKABLE_NORMAL;
4873 atom.type = MKTAG('m','o','o','v');
4874 atom.size = moov_len;
4875 ret = mov_read_default(c, &ctx, atom);
4881 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
4882 return AVERROR(ENOSYS);
4886 /* edit list atom */
4887 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4889 MOVStreamContext *sc;
4890 int i, edit_count, version;
4892 if (c->fc->nb_streams < 1 || c->ignore_editlist)
4894 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
4896 version = avio_r8(pb); /* version */
4897 avio_rb24(pb); /* flags */
4898 edit_count = avio_rb32(pb); /* entries */
4903 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
4904 av_free(sc->elst_data);
4906 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
4908 return AVERROR(ENOMEM);
4910 av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
4911 for (i = 0; i < edit_count && !pb->eof_reached; i++) {
4912 MOVElst *e = &sc->elst_data[i];
4915 e->duration = avio_rb64(pb);
4916 e->time = avio_rb64(pb);
4918 e->duration = avio_rb32(pb); /* segment duration */
4919 e->time = (int32_t)avio_rb32(pb); /* media time */
4921 e->rate = avio_rb32(pb) / 65536.0;
4922 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
4923 e->duration, e->time, e->rate);
4925 if (e->time < 0 && e->time != -1 &&
4926 c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
4927 av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
4928 c->fc->nb_streams-1, i, e->time);
4929 return AVERROR_INVALIDDATA;
4937 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4939 MOVStreamContext *sc;
4941 if (c->fc->nb_streams < 1)
4942 return AVERROR_INVALIDDATA;
4943 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
4944 sc->timecode_track = avio_rb32(pb);
4948 static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4951 int version, color_range, color_primaries, color_trc, color_space;
4953 if (c->fc->nb_streams < 1)
4955 st = c->fc->streams[c->fc->nb_streams - 1];
4957 if (atom.size < 5) {
4958 av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
4959 return AVERROR_INVALIDDATA;
4962 version = avio_r8(pb);
4964 av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
4967 avio_skip(pb, 3); /* flags */
4969 avio_skip(pb, 2); /* profile + level */
4970 color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
4971 color_primaries = avio_r8(pb);
4972 color_trc = avio_r8(pb);
4973 color_space = avio_r8(pb);
4974 if (avio_rb16(pb)) /* codecIntializationDataSize */
4975 return AVERROR_INVALIDDATA;
4977 if (!av_color_primaries_name(color_primaries))
4978 color_primaries = AVCOL_PRI_UNSPECIFIED;
4979 if (!av_color_transfer_name(color_trc))
4980 color_trc = AVCOL_TRC_UNSPECIFIED;
4981 if (!av_color_space_name(color_space))
4982 color_space = AVCOL_SPC_UNSPECIFIED;
4984 st->codecpar->color_range = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
4985 st->codecpar->color_primaries = color_primaries;
4986 st->codecpar->color_trc = color_trc;
4987 st->codecpar->color_space = color_space;
4992 static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4994 MOVStreamContext *sc;
4995 const int chroma_den = 50000;
4996 const int luma_den = 10000;
4999 if (c->fc->nb_streams < 1)
5000 return AVERROR_INVALIDDATA;
5002 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5004 if (atom.size < 5) {
5005 av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
5006 return AVERROR_INVALIDDATA;
5009 version = avio_r8(pb);
5011 av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
5014 avio_skip(pb, 3); /* flags */
5016 sc->mastering = av_mastering_display_metadata_alloc();
5018 return AVERROR(ENOMEM);
5020 for (i = 0; i < 3; i++)
5021 for (j = 0; j < 2; j++)
5022 sc->mastering->display_primaries[i][j] =
5023 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5024 for (i = 0; i < 2; i++)
5025 sc->mastering->white_point[i] =
5026 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5027 sc->mastering->max_luminance =
5028 av_make_q(lrint(((double)avio_rb32(pb) / (1 << 8)) * luma_den), luma_den);
5029 sc->mastering->min_luminance =
5030 av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den);
5032 sc->mastering->has_primaries = 1;
5033 sc->mastering->has_luminance = 1;
5038 static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5040 MOVStreamContext *sc;
5043 if (c->fc->nb_streams < 1)
5044 return AVERROR_INVALIDDATA;
5046 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5048 if (atom.size < 5) {
5049 av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
5050 return AVERROR_INVALIDDATA;
5053 version = avio_r8(pb);
5055 av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
5058 avio_skip(pb, 3); /* flags */
5060 sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
5062 return AVERROR(ENOMEM);
5064 sc->coll->MaxCLL = avio_rb16(pb);
5065 sc->coll->MaxFALL = avio_rb16(pb);
5070 static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5073 MOVStreamContext *sc;
5074 enum AVStereo3DType type;
5077 if (c->fc->nb_streams < 1)
5080 st = c->fc->streams[c->fc->nb_streams - 1];
5083 if (atom.size < 5) {
5084 av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
5085 return AVERROR_INVALIDDATA;
5087 avio_skip(pb, 4); /* version + flags */
5092 type = AV_STEREO3D_2D;
5095 type = AV_STEREO3D_TOPBOTTOM;
5098 type = AV_STEREO3D_SIDEBYSIDE;
5101 av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
5105 sc->stereo3d = av_stereo3d_alloc();
5107 return AVERROR(ENOMEM);
5109 sc->stereo3d->type = type;
5113 static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5116 MOVStreamContext *sc;
5117 int size, version, layout;
5118 int32_t yaw, pitch, roll;
5119 uint32_t l = 0, t = 0, r = 0, b = 0;
5120 uint32_t tag, padding = 0;
5121 enum AVSphericalProjection projection;
5123 if (c->fc->nb_streams < 1)
5126 st = c->fc->streams[c->fc->nb_streams - 1];
5129 if (atom.size < 8) {
5130 av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
5131 return AVERROR_INVALIDDATA;
5134 size = avio_rb32(pb);
5135 if (size <= 12 || size > atom.size)
5136 return AVERROR_INVALIDDATA;
5138 tag = avio_rl32(pb);
5139 if (tag != MKTAG('s','v','h','d')) {
5140 av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
5143 version = avio_r8(pb);
5145 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5149 avio_skip(pb, 3); /* flags */
5150 avio_skip(pb, size - 12); /* metadata_source */
5152 size = avio_rb32(pb);
5153 if (size > atom.size)
5154 return AVERROR_INVALIDDATA;
5156 tag = avio_rl32(pb);
5157 if (tag != MKTAG('p','r','o','j')) {
5158 av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
5162 size = avio_rb32(pb);
5163 if (size > atom.size)
5164 return AVERROR_INVALIDDATA;
5166 tag = avio_rl32(pb);
5167 if (tag != MKTAG('p','r','h','d')) {
5168 av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
5171 version = avio_r8(pb);
5173 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5177 avio_skip(pb, 3); /* flags */
5179 /* 16.16 fixed point */
5180 yaw = avio_rb32(pb);
5181 pitch = avio_rb32(pb);
5182 roll = avio_rb32(pb);
5184 size = avio_rb32(pb);
5185 if (size > atom.size)
5186 return AVERROR_INVALIDDATA;
5188 tag = avio_rl32(pb);
5189 version = avio_r8(pb);
5191 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5195 avio_skip(pb, 3); /* flags */
5197 case MKTAG('c','b','m','p'):
5198 layout = avio_rb32(pb);
5200 av_log(c->fc, AV_LOG_WARNING,
5201 "Unsupported cubemap layout %d\n", layout);
5204 projection = AV_SPHERICAL_CUBEMAP;
5205 padding = avio_rb32(pb);
5207 case MKTAG('e','q','u','i'):
5213 if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
5214 av_log(c->fc, AV_LOG_ERROR,
5215 "Invalid bounding rectangle coordinates "
5216 "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
5217 return AVERROR_INVALIDDATA;
5220 if (l || t || r || b)
5221 projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
5223 projection = AV_SPHERICAL_EQUIRECTANGULAR;
5226 av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n");
5230 sc->spherical = av_spherical_alloc(&sc->spherical_size);
5232 return AVERROR(ENOMEM);
5234 sc->spherical->projection = projection;
5236 sc->spherical->yaw = yaw;
5237 sc->spherical->pitch = pitch;
5238 sc->spherical->roll = roll;
5240 sc->spherical->padding = padding;
5242 sc->spherical->bound_left = l;
5243 sc->spherical->bound_top = t;
5244 sc->spherical->bound_right = r;
5245 sc->spherical->bound_bottom = b;
5250 static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
5253 uint8_t *buffer = av_malloc(len + 1);
5257 return AVERROR(ENOMEM);
5260 ret = ffio_read_size(pb, buffer, len);
5264 /* Check for mandatory keys and values, try to support XML as best-effort */
5265 if (!sc->spherical &&
5266 av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
5267 (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
5268 av_stristr(val, "true") &&
5269 (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
5270 av_stristr(val, "true") &&
5271 (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
5272 av_stristr(val, "equirectangular")) {
5273 sc->spherical = av_spherical_alloc(&sc->spherical_size);
5277 sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
5279 if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
5280 enum AVStereo3DType mode;
5282 if (av_stristr(buffer, "left-right"))
5283 mode = AV_STEREO3D_SIDEBYSIDE;
5284 else if (av_stristr(buffer, "top-bottom"))
5285 mode = AV_STEREO3D_TOPBOTTOM;
5287 mode = AV_STEREO3D_2D;
5289 sc->stereo3d = av_stereo3d_alloc();
5293 sc->stereo3d->type = mode;
5297 val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
5299 sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
5300 val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
5302 sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
5303 val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
5305 sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
5313 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5316 MOVStreamContext *sc;
5319 static const uint8_t uuid_isml_manifest[] = {
5320 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
5321 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
5323 static const uint8_t uuid_xmp[] = {
5324 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
5325 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
5327 static const uint8_t uuid_spherical[] = {
5328 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
5329 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
5332 if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
5333 return AVERROR_INVALIDDATA;
5335 if (c->fc->nb_streams < 1)
5337 st = c->fc->streams[c->fc->nb_streams - 1];
5340 ret = avio_read(pb, uuid, sizeof(uuid));
5343 } else if (ret != sizeof(uuid)) {
5344 return AVERROR_INVALIDDATA;
5346 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
5347 uint8_t *buffer, *ptr;
5349 size_t len = atom.size - sizeof(uuid);
5352 return AVERROR_INVALIDDATA;
5354 ret = avio_skip(pb, 4); // zeroes
5357 buffer = av_mallocz(len + 1);
5359 return AVERROR(ENOMEM);
5361 ret = avio_read(pb, buffer, len);
5365 } else if (ret != len) {
5367 return AVERROR_INVALIDDATA;
5371 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
5372 ptr += sizeof("systemBitrate=\"") - 1;
5373 c->bitrates_count++;
5374 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
5376 c->bitrates_count = 0;
5378 return AVERROR(ENOMEM);
5381 ret = strtol(ptr, &endptr, 10);
5382 if (ret < 0 || errno || *endptr != '"') {
5383 c->bitrates[c->bitrates_count - 1] = 0;
5385 c->bitrates[c->bitrates_count - 1] = ret;
5390 } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
5392 size_t len = atom.size - sizeof(uuid);
5393 if (c->export_xmp) {
5394 buffer = av_mallocz(len + 1);
5396 return AVERROR(ENOMEM);
5398 ret = avio_read(pb, buffer, len);
5402 } else if (ret != len) {
5404 return AVERROR_INVALIDDATA;
5407 av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
5410 // skip all uuid atom, which makes it fast for long uuid-xmp file
5411 ret = avio_skip(pb, len);
5415 } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
5416 size_t len = atom.size - sizeof(uuid);
5417 ret = mov_parse_uuid_spherical(sc, pb, len);
5421 av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n"); }
5426 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5429 uint8_t content[16];
5434 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
5440 && !memcmp(content, "Anevia\x1A\x1A", 8)
5441 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
5442 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
5448 static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5450 uint32_t format = avio_rl32(pb);
5451 MOVStreamContext *sc;
5455 if (c->fc->nb_streams < 1)
5457 st = c->fc->streams[c->fc->nb_streams - 1];
5462 case MKTAG('e','n','c','v'): // encrypted video
5463 case MKTAG('e','n','c','a'): // encrypted audio
5464 id = mov_codec_id(st, format);
5465 if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
5466 st->codecpar->codec_id != id) {
5467 av_log(c->fc, AV_LOG_WARNING,
5468 "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
5469 (char*)&format, st->codecpar->codec_id);
5473 st->codecpar->codec_id = id;
5474 sc->format = format;
5478 if (format != sc->format) {
5479 av_log(c->fc, AV_LOG_WARNING,
5480 "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
5481 (char*)&format, (char*)&sc->format);
5489 static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5492 MOVStreamContext *sc;
5493 size_t auxiliary_info_size;
5495 if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5498 st = c->fc->streams[c->fc->nb_streams - 1];
5501 if (sc->cenc.aes_ctr) {
5502 av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
5503 return AVERROR_INVALIDDATA;
5506 avio_r8(pb); /* version */
5507 sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
5509 avio_rb32(pb); /* entries */
5511 if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5512 av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size);
5513 return AVERROR_INVALIDDATA;
5516 /* save the auxiliary info as is */
5517 auxiliary_info_size = atom.size - 8;
5519 sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
5520 if (!sc->cenc.auxiliary_info) {
5521 return AVERROR(ENOMEM);
5524 sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
5525 sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
5526 sc->cenc.auxiliary_info_index = 0;
5528 if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
5529 av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
5530 return AVERROR_INVALIDDATA;
5533 /* initialize the cipher */
5534 sc->cenc.aes_ctr = av_aes_ctr_alloc();
5535 if (!sc->cenc.aes_ctr) {
5536 return AVERROR(ENOMEM);
5539 return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
5542 static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5545 MOVStreamContext *sc;
5547 int atom_header_size;
5550 if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5553 st = c->fc->streams[c->fc->nb_streams - 1];
5556 if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
5557 av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
5558 return AVERROR_INVALIDDATA;
5561 atom_header_size = 9;
5563 avio_r8(pb); /* version */
5564 flags = avio_rb24(pb);
5566 if ((flags & 0x01) != 0) {
5567 atom_header_size += 8;
5569 avio_rb32(pb); /* info type */
5570 avio_rb32(pb); /* info type param */
5573 sc->cenc.auxiliary_info_default_size = avio_r8(pb);
5574 avio_rb32(pb); /* entries */
5576 if (atom.size <= atom_header_size) {
5580 if (atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5581 av_log(c->fc, AV_LOG_ERROR, "saiz atom auxiliary_info_sizes size %"PRId64" invalid\n", atom.size);
5582 return AVERROR_INVALIDDATA;
5585 /* save the auxiliary info sizes as is */
5586 data_size = atom.size - atom_header_size;
5588 sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
5589 if (!sc->cenc.auxiliary_info_sizes) {
5590 return AVERROR(ENOMEM);
5593 sc->cenc.auxiliary_info_sizes_count = data_size;
5595 if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
5596 av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
5597 return AVERROR_INVALIDDATA;
5603 static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5606 int last, type, size, ret;
5609 if (c->fc->nb_streams < 1)
5611 st = c->fc->streams[c->fc->nb_streams-1];
5613 if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
5614 return AVERROR_INVALIDDATA;
5616 /* Check FlacSpecificBox version. */
5617 if (avio_r8(pb) != 0)
5618 return AVERROR_INVALIDDATA;
5620 avio_rb24(pb); /* Flags */
5622 avio_read(pb, buf, sizeof(buf));
5623 flac_parse_block_header(buf, &last, &type, &size);
5625 if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
5626 av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
5627 return AVERROR_INVALIDDATA;
5630 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
5635 av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
5640 static int mov_seek_auxiliary_info(MOVContext *c, MOVStreamContext *sc, int64_t index)
5642 size_t auxiliary_info_seek_offset = 0;
5645 if (sc->cenc.auxiliary_info_default_size) {
5646 auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * index;
5647 } else if (sc->cenc.auxiliary_info_sizes) {
5648 if (index > sc->cenc.auxiliary_info_sizes_count) {
5649 av_log(c, AV_LOG_ERROR, "current sample %"PRId64" greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
5650 index, sc->cenc.auxiliary_info_sizes_count);
5651 return AVERROR_INVALIDDATA;
5654 for (i = 0; i < index; i++) {
5655 auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
5659 if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
5660 av_log(c, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
5661 auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
5662 return AVERROR_INVALIDDATA;
5665 sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
5666 sc->cenc.auxiliary_info_index = index;
5670 static int cenc_filter(MOVContext *c, MOVStreamContext *sc, int64_t index, uint8_t *input, int size)
5672 uint32_t encrypted_bytes;
5673 uint16_t subsample_count;
5674 uint16_t clear_bytes;
5675 uint8_t* input_end = input + size;
5678 if (index != sc->cenc.auxiliary_info_index) {
5679 ret = mov_seek_auxiliary_info(c, sc, index);
5686 if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5687 av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
5688 return AVERROR_INVALIDDATA;
5691 av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
5692 sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
5694 if (!sc->cenc.use_subsamples)
5696 /* decrypt the whole packet */
5697 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
5701 /* read the subsample count */
5702 if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5703 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
5704 return AVERROR_INVALIDDATA;
5707 subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
5708 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5710 for (; subsample_count > 0; subsample_count--)
5712 if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5713 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
5714 return AVERROR_INVALIDDATA;
5717 /* read the number of clear / encrypted bytes */
5718 clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
5719 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5720 encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
5721 sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
5723 if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
5724 av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
5725 return AVERROR_INVALIDDATA;
5728 /* skip the clear bytes */
5729 input += clear_bytes;
5731 /* decrypt the encrypted bytes */
5732 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
5733 input += encrypted_bytes;
5736 if (input < input_end) {
5737 av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
5738 return AVERROR_INVALIDDATA;
5741 sc->cenc.auxiliary_info_index++;
5745 static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5747 const int OPUS_SEEK_PREROLL_MS = 80;
5752 if (c->fc->nb_streams < 1)
5754 st = c->fc->streams[c->fc->nb_streams-1];
5756 if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
5757 return AVERROR_INVALIDDATA;
5759 /* Check OpusSpecificBox version. */
5760 if (avio_r8(pb) != 0) {
5761 av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
5762 return AVERROR_INVALIDDATA;
5765 /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
5766 size = atom.size + 8;
5768 if (ff_alloc_extradata(st->codecpar, size))
5769 return AVERROR(ENOMEM);
5771 AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
5772 AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
5773 AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
5774 avio_read(pb, st->codecpar->extradata + 9, size - 9);
5776 /* OpusSpecificBox is stored in big-endian, but OpusHead is
5777 little-endian; aside from the preceeding magic and version they're
5778 otherwise currently identical. Data after output gain at offset 16
5779 doesn't need to be bytewapped. */
5780 pre_skip = AV_RB16(st->codecpar->extradata + 10);
5781 AV_WL16(st->codecpar->extradata + 10, pre_skip);
5782 AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
5783 AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
5785 st->codecpar->initial_padding = pre_skip;
5786 st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
5787 (AVRational){1, 1000},
5788 (AVRational){1, 48000});
5793 static const MOVParseTableEntry mov_default_parse_table[] = {
5794 { MKTAG('A','C','L','R'), mov_read_aclr },
5795 { MKTAG('A','P','R','G'), mov_read_avid },
5796 { MKTAG('A','A','L','P'), mov_read_avid },
5797 { MKTAG('A','R','E','S'), mov_read_ares },
5798 { MKTAG('a','v','s','s'), mov_read_avss },
5799 { MKTAG('c','h','p','l'), mov_read_chpl },
5800 { MKTAG('c','o','6','4'), mov_read_stco },
5801 { MKTAG('c','o','l','r'), mov_read_colr },
5802 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
5803 { MKTAG('d','i','n','f'), mov_read_default },
5804 { MKTAG('D','p','x','E'), mov_read_dpxe },
5805 { MKTAG('d','r','e','f'), mov_read_dref },
5806 { MKTAG('e','d','t','s'), mov_read_default },
5807 { MKTAG('e','l','s','t'), mov_read_elst },
5808 { MKTAG('e','n','d','a'), mov_read_enda },
5809 { MKTAG('f','i','e','l'), mov_read_fiel },
5810 { MKTAG('a','d','r','m'), mov_read_adrm },
5811 { MKTAG('f','t','y','p'), mov_read_ftyp },
5812 { MKTAG('g','l','b','l'), mov_read_glbl },
5813 { MKTAG('h','d','l','r'), mov_read_hdlr },
5814 { MKTAG('i','l','s','t'), mov_read_ilst },
5815 { MKTAG('j','p','2','h'), mov_read_jp2h },
5816 { MKTAG('m','d','a','t'), mov_read_mdat },
5817 { MKTAG('m','d','h','d'), mov_read_mdhd },
5818 { MKTAG('m','d','i','a'), mov_read_default },
5819 { MKTAG('m','e','t','a'), mov_read_meta },
5820 { MKTAG('m','i','n','f'), mov_read_default },
5821 { MKTAG('m','o','o','f'), mov_read_moof },
5822 { MKTAG('m','o','o','v'), mov_read_moov },
5823 { MKTAG('m','v','e','x'), mov_read_default },
5824 { MKTAG('m','v','h','d'), mov_read_mvhd },
5825 { MKTAG('S','M','I',' '), mov_read_svq3 },
5826 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
5827 { MKTAG('a','v','c','C'), mov_read_glbl },
5828 { MKTAG('p','a','s','p'), mov_read_pasp },
5829 { MKTAG('s','i','d','x'), mov_read_sidx },
5830 { MKTAG('s','t','b','l'), mov_read_default },
5831 { MKTAG('s','t','c','o'), mov_read_stco },
5832 { MKTAG('s','t','p','s'), mov_read_stps },
5833 { MKTAG('s','t','r','f'), mov_read_strf },
5834 { MKTAG('s','t','s','c'), mov_read_stsc },
5835 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
5836 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
5837 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
5838 { MKTAG('s','t','t','s'), mov_read_stts },
5839 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
5840 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
5841 { MKTAG('t','f','d','t'), mov_read_tfdt },
5842 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
5843 { MKTAG('t','r','a','k'), mov_read_trak },
5844 { MKTAG('t','r','a','f'), mov_read_default },
5845 { MKTAG('t','r','e','f'), mov_read_default },
5846 { MKTAG('t','m','c','d'), mov_read_tmcd },
5847 { MKTAG('c','h','a','p'), mov_read_chap },
5848 { MKTAG('t','r','e','x'), mov_read_trex },
5849 { MKTAG('t','r','u','n'), mov_read_trun },
5850 { MKTAG('u','d','t','a'), mov_read_default },
5851 { MKTAG('w','a','v','e'), mov_read_wave },
5852 { MKTAG('e','s','d','s'), mov_read_esds },
5853 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
5854 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
5855 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
5856 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
5857 { MKTAG('w','f','e','x'), mov_read_wfex },
5858 { MKTAG('c','m','o','v'), mov_read_cmov },
5859 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
5860 { MKTAG('d','v','c','1'), mov_read_dvc1 },
5861 { MKTAG('s','b','g','p'), mov_read_sbgp },
5862 { MKTAG('h','v','c','C'), mov_read_glbl },
5863 { MKTAG('u','u','i','d'), mov_read_uuid },
5864 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
5865 { MKTAG('f','r','e','e'), mov_read_free },
5866 { MKTAG('-','-','-','-'), mov_read_custom },
5867 { MKTAG('s','i','n','f'), mov_read_default },
5868 { MKTAG('f','r','m','a'), mov_read_frma },
5869 { MKTAG('s','e','n','c'), mov_read_senc },
5870 { MKTAG('s','a','i','z'), mov_read_saiz },
5871 { MKTAG('d','f','L','a'), mov_read_dfla },
5872 { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
5873 { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
5874 { MKTAG('d','O','p','s'), mov_read_dops },
5875 { MKTAG('S','m','D','m'), mov_read_smdm },
5876 { MKTAG('C','o','L','L'), mov_read_coll },
5877 { MKTAG('v','p','c','C'), mov_read_vpcc },
5881 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5883 int64_t total_size = 0;
5887 if (c->atom_depth > 10) {
5888 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
5889 return AVERROR_INVALIDDATA;
5894 atom.size = INT64_MAX;
5895 while (total_size <= atom.size - 8 && !avio_feof(pb)) {
5896 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
5899 if (atom.size >= 8) {
5900 a.size = avio_rb32(pb);
5901 a.type = avio_rl32(pb);
5902 if (a.type == MKTAG('f','r','e','e') &&
5904 c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
5907 uint32_t *type = (uint32_t *)buf + 1;
5908 if (avio_read(pb, buf, 8) != 8)
5909 return AVERROR_INVALIDDATA;
5910 avio_seek(pb, -8, SEEK_CUR);
5911 if (*type == MKTAG('m','v','h','d') ||
5912 *type == MKTAG('c','m','o','v')) {
5913 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
5914 a.type = MKTAG('m','o','o','v');
5917 if (atom.type != MKTAG('r','o','o','t') &&
5918 atom.type != MKTAG('m','o','o','v'))
5920 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
5922 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
5929 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
5930 a.size = avio_rb64(pb) - 8;
5934 av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
5935 av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
5937 a.size = atom.size - total_size + 8;
5942 a.size = FFMIN(a.size, atom.size - total_size);
5944 for (i = 0; mov_default_parse_table[i].type; i++)
5945 if (mov_default_parse_table[i].type == a.type) {
5946 parse = mov_default_parse_table[i].parse;
5950 // container is user data
5951 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
5952 atom.type == MKTAG('i','l','s','t')))
5953 parse = mov_read_udta_string;
5955 // Supports parsing the QuickTime Metadata Keys.
5956 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
5957 if (!parse && c->found_hdlr_mdta &&
5958 atom.type == MKTAG('m','e','t','a') &&
5959 a.type == MKTAG('k','e','y','s')) {
5960 parse = mov_read_keys;
5963 if (!parse) { /* skip leaf atoms data */
5964 avio_skip(pb, a.size);
5966 int64_t start_pos = avio_tell(pb);
5968 int err = parse(c, pb, a);
5973 if (c->found_moov && c->found_mdat &&
5974 ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete) ||
5975 start_pos + a.size == avio_size(pb))) {
5976 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete)
5977 c->next_root_atom = start_pos + a.size;
5981 left = a.size - avio_tell(pb) + start_pos;
5982 if (left > 0) /* skip garbage at atom end */
5983 avio_skip(pb, left);
5984 else if (left < 0) {
5985 av_log(c->fc, AV_LOG_WARNING,
5986 "overread end of atom '%.4s' by %"PRId64" bytes\n",
5987 (char*)&a.type, -left);
5988 avio_seek(pb, left, SEEK_CUR);
5992 total_size += a.size;
5995 if (total_size < atom.size && atom.size < 0x7ffff)
5996 avio_skip(pb, atom.size - total_size);
6002 static int mov_probe(AVProbeData *p)
6007 int moov_offset = -1;
6009 /* check file header */
6012 /* ignore invalid offset */
6013 if ((offset + 8) > (unsigned int)p->buf_size)
6015 tag = AV_RL32(p->buf + offset + 4);
6017 /* check for obvious tags */
6018 case MKTAG('m','o','o','v'):
6019 moov_offset = offset + 4;
6020 case MKTAG('m','d','a','t'):
6021 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
6022 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
6023 case MKTAG('f','t','y','p'):
6024 if (AV_RB32(p->buf+offset) < 8 &&
6025 (AV_RB32(p->buf+offset) != 1 ||
6026 offset + 12 > (unsigned int)p->buf_size ||
6027 AV_RB64(p->buf+offset + 8) == 0)) {
6028 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6029 } else if (tag == MKTAG('f','t','y','p') &&
6030 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
6031 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
6033 score = FFMAX(score, 5);
6035 score = AVPROBE_SCORE_MAX;
6037 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6039 /* those are more common words, so rate then a bit less */
6040 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
6041 case MKTAG('w','i','d','e'):
6042 case MKTAG('f','r','e','e'):
6043 case MKTAG('j','u','n','k'):
6044 case MKTAG('p','i','c','t'):
6045 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
6046 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6048 case MKTAG(0x82,0x82,0x7f,0x7d):
6049 case MKTAG('s','k','i','p'):
6050 case MKTAG('u','u','i','d'):
6051 case MKTAG('p','r','f','l'):
6052 /* if we only find those cause probedata is too small at least rate them */
6053 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6054 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6057 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6060 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
6061 /* moov atom in the header - we should make sure that this is not a
6062 * MOV-packed MPEG-PS */
6063 offset = moov_offset;
6065 while(offset < (p->buf_size - 16)){ /* Sufficient space */
6066 /* We found an actual hdlr atom */
6067 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
6068 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
6069 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
6070 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
6071 /* We found a media handler reference atom describing an
6072 * MPEG-PS-in-MOV, return a
6073 * low score to force expanding the probe window until
6074 * mpegps_probe finds what it needs */
6085 // must be done after parsing all trak because there's no order requirement
6086 static void mov_read_chapters(AVFormatContext *s)
6088 MOVContext *mov = s->priv_data;
6090 MOVStreamContext *sc;
6095 for (j = 0; j < mov->nb_chapter_tracks; j++) {
6096 chapter_track = mov->chapter_tracks[j];
6098 for (i = 0; i < s->nb_streams; i++)
6099 if (s->streams[i]->id == chapter_track) {
6104 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
6109 cur_pos = avio_tell(sc->pb);
6111 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6112 st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
6113 if (st->nb_index_entries) {
6114 // Retrieve the first frame, if possible
6116 AVIndexEntry *sample = &st->index_entries[0];
6117 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6118 av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
6122 if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
6125 st->attached_pic = pkt;
6126 st->attached_pic.stream_index = st->index;
6127 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
6130 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
6131 st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
6132 st->discard = AVDISCARD_ALL;
6133 for (i = 0; i < st->nb_index_entries; i++) {
6134 AVIndexEntry *sample = &st->index_entries[i];
6135 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
6140 if (end < sample->timestamp) {
6141 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
6142 end = AV_NOPTS_VALUE;
6145 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6146 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
6150 // the first two bytes are the length of the title
6151 len = avio_rb16(sc->pb);
6152 if (len > sample->size-2)
6154 title_len = 2*len + 1;
6155 if (!(title = av_mallocz(title_len)))
6158 // The samples could theoretically be in any encoding if there's an encd
6159 // atom following, but in practice are only utf-8 or utf-16, distinguished
6160 // instead by the presence of a BOM
6164 ch = avio_rb16(sc->pb);
6166 avio_get_str16be(sc->pb, len, title, title_len);
6167 else if (ch == 0xfffe)
6168 avio_get_str16le(sc->pb, len, title, title_len);
6171 if (len == 1 || len == 2)
6174 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
6178 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
6183 avio_seek(sc->pb, cur_pos, SEEK_SET);
6187 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
6188 uint32_t value, int flags)
6191 char buf[AV_TIMECODE_STR_SIZE];
6192 AVRational rate = st->avg_frame_rate;
6193 int ret = av_timecode_init(&tc, rate, flags, 0, s);
6196 av_dict_set(&st->metadata, "timecode",
6197 av_timecode_make_string(&tc, buf, value), 0);
6201 static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
6203 MOVStreamContext *sc = st->priv_data;
6204 char buf[AV_TIMECODE_STR_SIZE];
6205 int64_t cur_pos = avio_tell(sc->pb);
6206 int hh, mm, ss, ff, drop;
6208 if (!st->nb_index_entries)
6211 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6212 avio_skip(s->pb, 13);
6213 hh = avio_r8(s->pb);
6214 mm = avio_r8(s->pb);
6215 ss = avio_r8(s->pb);
6216 drop = avio_r8(s->pb);
6217 ff = avio_r8(s->pb);
6218 snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
6219 hh, mm, ss, drop ? ';' : ':', ff);
6220 av_dict_set(&st->metadata, "timecode", buf, 0);
6222 avio_seek(sc->pb, cur_pos, SEEK_SET);
6226 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
6228 MOVStreamContext *sc = st->priv_data;
6230 int64_t cur_pos = avio_tell(sc->pb);
6233 if (!st->nb_index_entries)
6236 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6237 value = avio_rb32(s->pb);
6239 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
6240 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
6241 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
6243 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
6244 * not the case) and thus assume "frame number format" instead of QT one.
6245 * No sample with tmcd track can be found with a QT timecode at the moment,
6246 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
6248 parse_timecode_in_framenum_format(s, st, value, flags);
6250 avio_seek(sc->pb, cur_pos, SEEK_SET);
6254 static int mov_read_close(AVFormatContext *s)
6256 MOVContext *mov = s->priv_data;
6259 for (i = 0; i < s->nb_streams; i++) {
6260 AVStream *st = s->streams[i];
6261 MOVStreamContext *sc = st->priv_data;
6266 av_freep(&sc->ctts_data);
6267 for (j = 0; j < sc->drefs_count; j++) {
6268 av_freep(&sc->drefs[j].path);
6269 av_freep(&sc->drefs[j].dir);
6271 av_freep(&sc->drefs);
6273 sc->drefs_count = 0;
6275 if (!sc->pb_is_copied)
6276 ff_format_io_close(s, &sc->pb);
6279 av_freep(&sc->chunk_offsets);
6280 av_freep(&sc->stsc_data);
6281 av_freep(&sc->sample_sizes);
6282 av_freep(&sc->keyframes);
6283 av_freep(&sc->stts_data);
6284 av_freep(&sc->stps_data);
6285 av_freep(&sc->elst_data);
6286 av_freep(&sc->rap_group);
6287 av_freep(&sc->display_matrix);
6288 av_freep(&sc->index_ranges);
6291 for (j = 0; j < sc->stsd_count; j++)
6292 av_free(sc->extradata[j]);
6293 av_freep(&sc->extradata);
6294 av_freep(&sc->extradata_size);
6296 av_freep(&sc->cenc.auxiliary_info);
6297 av_freep(&sc->cenc.auxiliary_info_sizes);
6298 av_aes_ctr_free(sc->cenc.aes_ctr);
6300 av_freep(&sc->stereo3d);
6301 av_freep(&sc->spherical);
6302 av_freep(&sc->mastering);
6303 av_freep(&sc->coll);
6306 if (mov->dv_demux) {
6307 avformat_free_context(mov->dv_fctx);
6308 mov->dv_fctx = NULL;
6311 if (mov->meta_keys) {
6312 for (i = 1; i < mov->meta_keys_count; i++) {
6313 av_freep(&mov->meta_keys[i]);
6315 av_freep(&mov->meta_keys);
6318 av_freep(&mov->trex_data);
6319 av_freep(&mov->bitrates);
6321 for (i = 0; i < mov->frag_index.nb_items; i++) {
6322 av_freep(&mov->frag_index.item[i].stream_info);
6324 av_freep(&mov->frag_index.item);
6326 av_freep(&mov->aes_decrypt);
6327 av_freep(&mov->chapter_tracks);
6332 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
6336 for (i = 0; i < s->nb_streams; i++) {
6337 AVStream *st = s->streams[i];
6338 MOVStreamContext *sc = st->priv_data;
6340 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6341 sc->timecode_track == tmcd_id)
6347 /* look for a tmcd track not referenced by any video track, and export it globally */
6348 static void export_orphan_timecode(AVFormatContext *s)
6352 for (i = 0; i < s->nb_streams; i++) {
6353 AVStream *st = s->streams[i];
6355 if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
6356 !tmcd_is_referenced(s, i + 1)) {
6357 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
6359 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
6366 static int read_tfra(MOVContext *mov, AVIOContext *f)
6368 int version, fieldlength, i, j;
6369 int64_t pos = avio_tell(f);
6370 uint32_t size = avio_rb32(f);
6371 unsigned track_id, item_count;
6373 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
6376 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
6378 version = avio_r8(f);
6380 track_id = avio_rb32(f);
6381 fieldlength = avio_rb32(f);
6382 item_count = avio_rb32(f);
6383 for (i = 0; i < item_count; i++) {
6384 int64_t time, offset;
6386 MOVFragmentStreamInfo * frag_stream_info;
6389 return AVERROR_INVALIDDATA;
6393 time = avio_rb64(f);
6394 offset = avio_rb64(f);
6396 time = avio_rb32(f);
6397 offset = avio_rb32(f);
6400 // The first sample of each stream in a fragment is always a random
6401 // access sample. So it's entry in the tfra can be used as the
6402 // initial PTS of the fragment.
6403 index = update_frag_index(mov, offset);
6404 frag_stream_info = get_frag_stream_info(&mov->frag_index, index, track_id);
6405 if (frag_stream_info &&
6406 frag_stream_info->first_tfra_pts == AV_NOPTS_VALUE)
6407 frag_stream_info->first_tfra_pts = time;
6409 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
6411 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
6413 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
6417 avio_seek(f, pos + size, SEEK_SET);
6421 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
6423 int64_t stream_size = avio_size(f);
6424 int64_t original_pos = avio_tell(f);
6428 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
6432 mfra_size = avio_rb32(f);
6433 if (mfra_size < 0 || mfra_size > stream_size) {
6434 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
6437 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
6441 if (avio_rb32(f) != mfra_size) {
6442 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
6445 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
6446 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
6449 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
6451 ret = read_tfra(c, f);
6457 seek_ret = avio_seek(f, original_pos, SEEK_SET);
6459 av_log(c->fc, AV_LOG_ERROR,
6460 "failed to seek back after looking for mfra\n");
6466 static int mov_read_header(AVFormatContext *s)
6468 MOVContext *mov = s->priv_data;
6469 AVIOContext *pb = s->pb;
6471 MOVAtom atom = { AV_RL32("root") };
6474 if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
6475 av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
6476 mov->decryption_key_len, AES_CTR_KEY_SIZE);
6477 return AVERROR(EINVAL);
6481 mov->trak_index = -1;
6482 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
6483 if (pb->seekable & AVIO_SEEKABLE_NORMAL)
6484 atom.size = avio_size(pb);
6486 atom.size = INT64_MAX;
6488 /* check MOV header */
6490 if (mov->moov_retry)
6491 avio_seek(pb, 0, SEEK_SET);
6492 if ((err = mov_read_default(mov, pb, atom)) < 0) {
6493 av_log(s, AV_LOG_ERROR, "error reading header\n");
6497 } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
6498 if (!mov->found_moov) {
6499 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
6501 return AVERROR_INVALIDDATA;
6503 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
6505 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
6506 if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
6507 mov_read_chapters(s);
6508 for (i = 0; i < s->nb_streams; i++)
6509 if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
6510 mov_read_timecode_track(s, s->streams[i]);
6511 } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
6512 mov_read_rtmd_track(s, s->streams[i]);
6516 /* copy timecode metadata from tmcd tracks to the related video streams */
6517 for (i = 0; i < s->nb_streams; i++) {
6518 AVStream *st = s->streams[i];
6519 MOVStreamContext *sc = st->priv_data;
6520 if (sc->timecode_track > 0) {
6521 AVDictionaryEntry *tcr;
6522 int tmcd_st_id = -1;
6524 for (j = 0; j < s->nb_streams; j++)
6525 if (s->streams[j]->id == sc->timecode_track)
6528 if (tmcd_st_id < 0 || tmcd_st_id == i)
6530 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
6532 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
6535 export_orphan_timecode(s);
6537 for (i = 0; i < s->nb_streams; i++) {
6538 AVStream *st = s->streams[i];
6539 MOVStreamContext *sc = st->priv_data;
6540 fix_timescale(mov, sc);
6541 if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6542 st->skip_samples = sc->start_pad;
6544 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
6545 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
6546 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
6547 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6548 if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
6549 st->codecpar->width = sc->width;
6550 st->codecpar->height = sc->height;
6552 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
6553 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
6557 if (mov->handbrake_version &&
6558 mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
6559 st->codecpar->codec_id == AV_CODEC_ID_MP3
6561 av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
6562 st->need_parsing = AVSTREAM_PARSE_FULL;
6566 if (mov->trex_data) {
6567 for (i = 0; i < s->nb_streams; i++) {
6568 AVStream *st = s->streams[i];
6569 MOVStreamContext *sc = st->priv_data;
6570 if (st->duration > 0) {
6571 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6572 av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6573 sc->data_size, sc->time_scale);
6575 return AVERROR_INVALIDDATA;
6577 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
6582 if (mov->use_mfra_for > 0) {
6583 for (i = 0; i < s->nb_streams; i++) {
6584 AVStream *st = s->streams[i];
6585 MOVStreamContext *sc = st->priv_data;
6586 if (sc->duration_for_fps > 0) {
6587 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6588 av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6589 sc->data_size, sc->time_scale);
6591 return AVERROR_INVALIDDATA;
6593 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
6594 sc->duration_for_fps;
6599 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
6600 if (mov->bitrates[i]) {
6601 s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
6605 ff_rfps_calculate(s);
6607 for (i = 0; i < s->nb_streams; i++) {
6608 AVStream *st = s->streams[i];
6609 MOVStreamContext *sc = st->priv_data;
6611 switch (st->codecpar->codec_type) {
6612 case AVMEDIA_TYPE_AUDIO:
6613 err = ff_replaygain_export(st, s->metadata);
6619 case AVMEDIA_TYPE_VIDEO:
6620 if (sc->display_matrix) {
6621 err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix,
6622 sizeof(int32_t) * 9);
6626 sc->display_matrix = NULL;
6629 err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
6630 (uint8_t *)sc->stereo3d,
6631 sizeof(*sc->stereo3d));
6635 sc->stereo3d = NULL;
6637 if (sc->spherical) {
6638 err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
6639 (uint8_t *)sc->spherical,
6640 sc->spherical_size);
6644 sc->spherical = NULL;
6646 if (sc->mastering) {
6647 err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
6648 (uint8_t *)sc->mastering,
6649 sizeof(*sc->mastering));
6653 sc->mastering = NULL;
6656 err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
6657 (uint8_t *)sc->coll,
6667 ff_configure_buffers_for_index(s, AV_TIME_BASE);
6669 for (i = 0; i < mov->frag_index.nb_items; i++)
6670 if (mov->frag_index.item[i].moof_offset <= mov->fragment.moof_offset)
6671 mov->frag_index.item[i].headers_read = 1;
6676 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
6678 AVIndexEntry *sample = NULL;
6679 int64_t best_dts = INT64_MAX;
6681 for (i = 0; i < s->nb_streams; i++) {
6682 AVStream *avst = s->streams[i];
6683 MOVStreamContext *msc = avst->priv_data;
6684 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
6685 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
6686 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
6687 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
6688 if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
6689 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6690 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
6691 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
6692 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
6693 sample = current_sample;
6702 static int should_retry(AVIOContext *pb, int error_code) {
6703 if (error_code == AVERROR_EOF || avio_feof(pb))
6709 static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
6711 MOVContext *mov = s->priv_data;
6713 if (index >= 0 && index < mov->frag_index.nb_items)
6714 target = mov->frag_index.item[index].moof_offset;
6715 if (avio_seek(s->pb, target, SEEK_SET) != target) {
6716 av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
6717 return AVERROR_INVALIDDATA;
6720 mov->next_root_atom = 0;
6721 if (index < 0 || index >= mov->frag_index.nb_items)
6722 index = search_frag_moof_offset(&mov->frag_index, target);
6723 if (index < mov->frag_index.nb_items) {
6724 if (index + 1 < mov->frag_index.nb_items)
6725 mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
6726 if (mov->frag_index.item[index].headers_read)
6728 mov->frag_index.item[index].headers_read = 1;
6731 mov->found_mdat = 0;
6733 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
6736 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
6741 static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
6743 uint8_t *side, *extradata;
6746 /* Save the current index. */
6747 sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
6749 /* Notify the decoder that extradata changed. */
6750 extradata_size = sc->extradata_size[sc->last_stsd_index];
6751 extradata = sc->extradata[sc->last_stsd_index];
6752 if (extradata_size > 0 && extradata) {
6753 side = av_packet_new_side_data(pkt,
6754 AV_PKT_DATA_NEW_EXTRADATA,
6757 return AVERROR(ENOMEM);
6758 memcpy(side, extradata, extradata_size);
6764 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
6766 MOVContext *mov = s->priv_data;
6767 MOVStreamContext *sc;
6768 AVIndexEntry *sample;
6769 AVStream *st = NULL;
6770 int64_t current_index;
6774 sample = mov_find_next_sample(s, &st);
6775 if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
6776 if (!mov->next_root_atom)
6778 if ((ret = mov_switch_root(s, mov->next_root_atom, -1)) < 0)
6783 /* must be done just before reading, to avoid infinite loop on sample */
6784 current_index = sc->current_index;
6785 mov_current_sample_inc(sc);
6787 if (mov->next_root_atom) {
6788 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
6789 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
6792 if (st->discard != AVDISCARD_ALL) {
6793 int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
6794 if (ret64 != sample->pos) {
6795 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
6796 sc->ffindex, sample->pos);
6797 if (should_retry(sc->pb, ret64)) {
6798 mov_current_sample_dec(sc);
6800 return AVERROR_INVALIDDATA;
6803 if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
6804 av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
6808 ret = av_get_packet(sc->pb, pkt, sample->size);
6810 if (should_retry(sc->pb, ret)) {
6811 mov_current_sample_dec(sc);
6815 if (sc->has_palette) {
6818 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
6820 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
6822 memcpy(pal, sc->palette, AVPALETTE_SIZE);
6823 sc->has_palette = 0;
6826 #if CONFIG_DV_DEMUXER
6827 if (mov->dv_demux && sc->dv_audio_container) {
6828 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
6829 av_freep(&pkt->data);
6831 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
6836 if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
6837 if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
6838 st->need_parsing = AVSTREAM_PARSE_FULL;
6842 pkt->stream_index = sc->ffindex;
6843 pkt->dts = sample->timestamp;
6844 if (sample->flags & AVINDEX_DISCARD_FRAME) {
6845 pkt->flags |= AV_PKT_FLAG_DISCARD;
6847 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
6848 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
6849 /* update ctts context */
6851 if (sc->ctts_index < sc->ctts_count &&
6852 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
6854 sc->ctts_sample = 0;
6857 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
6858 st->index_entries[sc->current_sample].timestamp : st->duration;
6859 pkt->duration = next_dts - pkt->dts;
6860 pkt->pts = pkt->dts;
6862 if (st->discard == AVDISCARD_ALL)
6864 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
6865 pkt->pos = sample->pos;
6867 /* Multiple stsd handling. */
6868 if (sc->stsc_data) {
6869 /* Keep track of the stsc index for the given sample, then check
6870 * if the stsd index is different from the last used one. */
6872 if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
6873 mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
6875 sc->stsc_sample = 0;
6876 /* Do not check indexes after a switch. */
6877 } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
6878 sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
6879 sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
6880 ret = mov_change_extradata(sc, pkt);
6887 aax_filter(pkt->data, pkt->size, mov);
6889 if (sc->cenc.aes_ctr) {
6890 ret = cenc_filter(mov, sc, current_index, pkt->data, pkt->size);
6899 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
6901 MOVContext *mov = s->priv_data;
6904 if (!mov->frag_index.complete)
6907 index = search_frag_timestamp(&mov->frag_index, st, timestamp);
6910 if (!mov->frag_index.item[index].headers_read)
6911 return mov_switch_root(s, -1, index);
6912 if (index + 1 < mov->frag_index.nb_items)
6913 mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
6918 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
6920 MOVStreamContext *sc = st->priv_data;
6921 int sample, time_sample;
6924 int ret = mov_seek_fragment(s, st, timestamp);
6928 sample = av_index_search_timestamp(st, timestamp, flags);
6929 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
6930 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
6932 if (sample < 0) /* not sure what to do */
6933 return AVERROR_INVALIDDATA;
6934 mov_current_sample_set(sc, sample);
6935 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
6936 /* adjust ctts index */
6937 if (sc->ctts_data) {
6939 for (i = 0; i < sc->ctts_count; i++) {
6940 int next = time_sample + sc->ctts_data[i].count;
6941 if (next > sc->current_sample) {
6943 sc->ctts_sample = sc->current_sample - time_sample;
6950 /* adjust stsd index */
6952 for (i = 0; i < sc->stsc_count; i++) {
6953 int next = time_sample + mov_get_stsc_samples(sc, i);
6954 if (next > sc->current_sample) {
6956 sc->stsc_sample = sc->current_sample - time_sample;
6965 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
6967 MOVContext *mc = s->priv_data;
6972 if (stream_index >= s->nb_streams)
6973 return AVERROR_INVALIDDATA;
6975 st = s->streams[stream_index];
6976 sample = mov_seek_stream(s, st, sample_time, flags);
6980 if (mc->seek_individually) {
6981 /* adjust seek timestamp to found sample timestamp */
6982 int64_t seek_timestamp = st->index_entries[sample].timestamp;
6984 for (i = 0; i < s->nb_streams; i++) {
6986 MOVStreamContext *sc = s->streams[i]->priv_data;
6988 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
6990 if (stream_index == i)
6993 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
6994 mov_seek_stream(s, st, timestamp, flags);
6997 for (i = 0; i < s->nb_streams; i++) {
6998 MOVStreamContext *sc;
7001 mov_current_sample_set(sc, 0);
7004 MOVStreamContext *sc;
7005 AVIndexEntry *entry = mov_find_next_sample(s, &st);
7007 return AVERROR_INVALIDDATA;
7009 if (sc->ffindex == stream_index && sc->current_sample == sample)
7011 mov_current_sample_inc(sc);
7017 #define OFFSET(x) offsetof(MOVContext, x)
7018 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
7019 static const AVOption mov_options[] = {
7020 {"use_absolute_path",
7021 "allow using absolute path when opening alias, this is a possible security issue",
7022 OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
7024 {"seek_streams_individually",
7025 "Seek each stream individually to the to the closest point",
7026 OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
7028 {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
7030 {"advanced_editlist",
7031 "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
7032 OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
7034 {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
7037 "use mfra for fragment timestamps",
7038 OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
7039 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
7041 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
7042 FLAGS, "use_mfra_for" },
7043 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
7044 FLAGS, "use_mfra_for" },
7045 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
7046 FLAGS, "use_mfra_for" },
7047 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
7048 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7049 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
7050 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7051 { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
7052 AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7053 { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
7054 "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
7055 AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
7056 .flags = AV_OPT_FLAG_DECODING_PARAM },
7057 { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7058 { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
7059 {.i64 = 0}, 0, 1, FLAGS },
7064 static const AVClass mov_class = {
7065 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
7066 .item_name = av_default_item_name,
7067 .option = mov_options,
7068 .version = LIBAVUTIL_VERSION_INT,
7071 AVInputFormat ff_mov_demuxer = {
7072 .name = "mov,mp4,m4a,3gp,3g2,mj2",
7073 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
7074 .priv_class = &mov_class,
7075 .priv_data_size = sizeof(MOVContext),
7076 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
7077 .read_probe = mov_probe,
7078 .read_header = mov_read_header,
7079 .read_packet = mov_read_packet,
7080 .read_close = mov_read_close,
7081 .read_seek = mov_read_seek,
7082 .flags = AVFMT_NO_BYTE_SEEK,