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 //#define MOV_EXPORT_ALL_METADATA
32 #include "libavutil/attributes.h"
33 #include "libavutil/channel_layout.h"
34 #include "libavutil/intreadwrite.h"
35 #include "libavutil/intfloat.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/timecode.h"
41 #include "libavcodec/ac3tab.h"
44 #include "avio_internal.h"
47 #include "libavcodec/get_bits.h"
50 #include "replaygain.h"
56 #include "qtpalette.h"
62 /* those functions parse an atom */
63 /* links atom IDs to parse functions */
64 typedef struct MOVParseTableEntry {
66 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
69 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
71 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
72 unsigned len, const char *key)
76 short current, total = 0;
77 avio_rb16(pb); // unknown
78 current = avio_rb16(pb);
80 total = avio_rb16(pb);
82 snprintf(buf, sizeof(buf), "%d", current);
84 snprintf(buf, sizeof(buf), "%d/%d", current, total);
85 av_dict_set(&c->fc->metadata, key, buf, 0);
90 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
91 unsigned len, const char *key)
95 /* bypass padding bytes */
100 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
101 av_dict_set(&c->fc->metadata, key, buf, 0);
106 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
107 unsigned len, const char *key)
111 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
112 av_dict_set(&c->fc->metadata, key, buf, 0);
117 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
118 unsigned len, const char *key)
123 avio_r8(pb); // unknown
126 if (genre < 1 || genre > ID3v1_GENRE_MAX)
128 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
129 av_dict_set(&c->fc->metadata, key, buf, 0);
134 static const uint32_t mac_to_unicode[128] = {
135 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
136 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
137 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
138 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
139 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
140 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
141 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
142 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
143 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
144 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
145 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
146 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
147 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
148 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
149 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
150 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
153 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
154 char *dst, int dstlen)
157 char *end = dst+dstlen-1;
160 for (i = 0; i < len; i++) {
161 uint8_t t, c = avio_r8(pb);
162 if (c < 0x80 && p < end)
165 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
171 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
175 MOVStreamContext *sc;
180 case 0xd: id = AV_CODEC_ID_MJPEG; break;
181 case 0xe: id = AV_CODEC_ID_PNG; break;
182 case 0x1b: id = AV_CODEC_ID_BMP; break;
184 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
189 st = avformat_new_stream(c->fc, NULL);
191 return AVERROR(ENOMEM);
192 sc = av_mallocz(sizeof(*sc));
194 return AVERROR(ENOMEM);
197 ret = av_get_packet(pb, &pkt, len);
201 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
203 st->attached_pic = pkt;
204 st->attached_pic.stream_index = st->index;
205 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
207 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
208 st->codec->codec_id = id;
213 static int mov_metadata_raw(MOVContext *c, AVIOContext *pb,
214 unsigned len, const char *key)
216 char *value = av_malloc(len + 1);
218 return AVERROR(ENOMEM);
219 avio_read(pb, value, len);
221 return av_dict_set(&c->fc->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);
224 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
226 #ifdef MOV_EXPORT_ALL_METADATA
229 char str[1024], key2[16], language[4] = {0};
230 const char *key = NULL;
231 uint16_t langcode = 0;
232 uint32_t data_type = 0, str_size;
233 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
236 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
237 case MKTAG(0xa9,'a','u','t'):
238 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
239 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
240 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
241 case MKTAG( 'c','p','i','l'): key = "compilation";
242 parse = mov_metadata_int8_no_padding; break;
243 case MKTAG( 'c','p','r','t'):
244 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
245 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
246 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
247 case MKTAG(0xa9,'c','m','t'):
248 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
249 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
250 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
251 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
252 case MKTAG( 'g','n','r','e'): key = "genre";
253 parse = mov_metadata_gnre; break;
254 case MKTAG(0xa9,'t','o','o'):
255 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
256 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
257 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
258 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
259 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
260 case MKTAG( 'd','e','s','c'): key = "description";break;
261 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
262 case MKTAG( 't','v','s','h'): key = "show"; break;
263 case MKTAG( 't','v','e','n'): key = "episode_id";break;
264 case MKTAG( 't','v','n','n'): key = "network"; break;
265 case MKTAG( 't','r','k','n'): key = "track";
266 parse = mov_metadata_track_or_disc_number; break;
267 case MKTAG( 'd','i','s','k'): key = "disc";
268 parse = mov_metadata_track_or_disc_number; break;
269 case MKTAG( 't','v','e','s'): key = "episode_sort";
270 parse = mov_metadata_int8_bypass_padding; break;
271 case MKTAG( 't','v','s','n'): key = "season_number";
272 parse = mov_metadata_int8_bypass_padding; break;
273 case MKTAG( 's','t','i','k'): key = "media_type";
274 parse = mov_metadata_int8_no_padding; break;
275 case MKTAG( 'h','d','v','d'): key = "hd_video";
276 parse = mov_metadata_int8_no_padding; break;
277 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
278 parse = mov_metadata_int8_no_padding; break;
279 case MKTAG( '@','P','R','M'):
280 return mov_metadata_raw(c, pb, atom.size, "premiere_version");
281 case MKTAG( '@','P','R','Q'):
282 return mov_metadata_raw(c, pb, atom.size, "quicktime_version");
285 if (c->itunes_metadata && atom.size > 8) {
286 int data_size = avio_rb32(pb);
287 int tag = avio_rl32(pb);
288 if (tag == MKTAG('d','a','t','a')) {
289 data_type = avio_rb32(pb); // type
290 avio_rb32(pb); // unknown
291 str_size = data_size - 16;
294 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
295 int ret = mov_read_covr(c, pb, data_type, str_size);
297 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
302 } else if (atom.size > 4 && key && !c->itunes_metadata) {
303 str_size = avio_rb16(pb); // string length
304 langcode = avio_rb16(pb);
305 ff_mov_lang_to_iso639(langcode, language);
308 str_size = atom.size;
310 #ifdef MOV_EXPORT_ALL_METADATA
312 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
320 return AVERROR_INVALIDDATA;
322 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
325 parse(c, pb, str_size, key);
327 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
328 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
330 int ret = avio_read(pb, str, str_size);
332 return ret < 0 ? ret : AVERROR_INVALIDDATA;
335 av_dict_set(&c->fc->metadata, key, str, 0);
336 if (*language && strcmp(language, "und")) {
337 snprintf(key2, sizeof(key2), "%s-%s", key, language);
338 av_dict_set(&c->fc->metadata, key2, str, 0);
341 av_dlog(c->fc, "lang \"%3s\" ", language);
342 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
343 key, str, (char*)&atom.type, str_size, atom.size);
348 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
351 int i, nb_chapters, str_len, version;
354 if ((atom.size -= 5) < 0)
357 version = avio_r8(pb);
360 avio_rb32(pb); // ???
361 nb_chapters = avio_r8(pb);
363 for (i = 0; i < nb_chapters; i++) {
367 start = avio_rb64(pb);
368 str_len = avio_r8(pb);
370 if ((atom.size -= 9+str_len) < 0)
373 avio_read(pb, str, str_len);
375 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
380 #define MIN_DATA_ENTRY_BOX_SIZE 12
381 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
384 MOVStreamContext *sc;
387 if (c->fc->nb_streams < 1)
389 st = c->fc->streams[c->fc->nb_streams-1];
392 avio_rb32(pb); // version + flags
393 entries = avio_rb32(pb);
394 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
395 entries >= UINT_MAX / sizeof(*sc->drefs))
396 return AVERROR_INVALIDDATA;
399 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
401 return AVERROR(ENOMEM);
402 sc->drefs_count = entries;
404 for (i = 0; i < sc->drefs_count; i++) {
405 MOVDref *dref = &sc->drefs[i];
406 uint32_t size = avio_rb32(pb);
407 int64_t next = avio_tell(pb) + size - 4;
410 return AVERROR_INVALIDDATA;
412 dref->type = avio_rl32(pb);
413 avio_rb32(pb); // version + flags
414 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
416 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
417 /* macintosh alias record */
418 uint16_t volume_len, len;
423 volume_len = avio_r8(pb);
424 volume_len = FFMIN(volume_len, 27);
425 avio_read(pb, dref->volume, 27);
426 dref->volume[volume_len] = 0;
427 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
432 len = FFMIN(len, 63);
433 avio_read(pb, dref->filename, 63);
434 dref->filename[len] = 0;
435 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
439 /* read next level up_from_alias/down_to_target */
440 dref->nlvl_from = avio_rb16(pb);
441 dref->nlvl_to = avio_rb16(pb);
442 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
443 dref->nlvl_from, dref->nlvl_to);
447 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
450 type = avio_rb16(pb);
452 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
455 if (type == 2) { // absolute path
457 dref->path = av_mallocz(len+1);
459 return AVERROR(ENOMEM);
460 avio_read(pb, dref->path, len);
461 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
463 memmove(dref->path, dref->path+volume_len, len);
466 for (j = 0; j < len; j++)
467 if (dref->path[j] == ':')
469 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
470 } else if (type == 0) { // directory name
472 dref->dir = av_malloc(len+1);
474 return AVERROR(ENOMEM);
475 if (avio_read(pb, dref->dir, len) != len)
476 return AVERROR_INVALIDDATA;
478 for (j = 0; j < len; j++)
479 if (dref->dir[j] == ':')
481 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
486 avio_seek(pb, next, SEEK_SET);
491 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
495 uint32_t av_unused ctype;
499 if (c->fc->nb_streams < 1) // meta before first trak
502 st = c->fc->streams[c->fc->nb_streams-1];
504 avio_r8(pb); /* version */
505 avio_rb24(pb); /* flags */
508 ctype = avio_rl32(pb);
509 type = avio_rl32(pb); /* component subtype */
511 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
512 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
514 if (type == MKTAG('v','i','d','e'))
515 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
516 else if (type == MKTAG('s','o','u','n'))
517 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
518 else if (type == MKTAG('m','1','a',' '))
519 st->codec->codec_id = AV_CODEC_ID_MP2;
520 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
521 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
523 avio_rb32(pb); /* component manufacture */
524 avio_rb32(pb); /* component flags */
525 avio_rb32(pb); /* component flags mask */
527 title_size = atom.size - 24;
528 if (title_size > 0) {
529 title_str = av_malloc(title_size + 1); /* Add null terminator */
531 return AVERROR(ENOMEM);
532 avio_read(pb, title_str, title_size);
533 title_str[title_size] = 0;
535 av_dict_set(&st->metadata, "handler_name", title_str +
536 (!c->isom && title_str[0] == title_size - 1), 0);
537 av_freep(&title_str);
543 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
548 if (fc->nb_streams < 1)
550 st = fc->streams[fc->nb_streams-1];
552 avio_rb32(pb); /* version + flags */
553 ff_mp4_read_descr(fc, pb, &tag);
554 if (tag == MP4ESDescrTag) {
555 ff_mp4_parse_es_descr(pb, NULL);
557 avio_rb16(pb); /* ID */
559 ff_mp4_read_descr(fc, pb, &tag);
560 if (tag == MP4DecConfigDescrTag)
561 ff_mp4_read_dec_config_descr(fc, st, pb);
565 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
567 return ff_mov_read_esds(c->fc, pb, atom);
570 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
573 int ac3info, acmod, lfeon, bsmod;
575 if (c->fc->nb_streams < 1)
577 st = c->fc->streams[c->fc->nb_streams-1];
579 ac3info = avio_rb24(pb);
580 bsmod = (ac3info >> 14) & 0x7;
581 acmod = (ac3info >> 11) & 0x7;
582 lfeon = (ac3info >> 10) & 0x1;
583 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
584 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
586 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
587 st->codec->audio_service_type = bsmod;
588 if (st->codec->channels > 1 && bsmod == 0x7)
589 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
594 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
597 int eac3info, acmod, lfeon, bsmod;
599 if (c->fc->nb_streams < 1)
601 st = c->fc->streams[c->fc->nb_streams-1];
603 /* No need to parse fields for additional independent substreams and its
604 * associated dependent substreams since libavcodec's E-AC-3 decoder
605 * does not support them yet. */
606 avio_rb16(pb); /* data_rate and num_ind_sub */
607 eac3info = avio_rb24(pb);
608 bsmod = (eac3info >> 12) & 0x1f;
609 acmod = (eac3info >> 9) & 0x7;
610 lfeon = (eac3info >> 8) & 0x1;
611 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
613 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
614 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
615 st->codec->audio_service_type = bsmod;
616 if (st->codec->channels > 1 && bsmod == 0x7)
617 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
622 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
626 if (c->fc->nb_streams < 1)
628 st = c->fc->streams[c->fc->nb_streams-1];
633 /* skip version and flags */
636 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
641 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
645 if (c->fc->nb_streams < 1)
647 st = c->fc->streams[c->fc->nb_streams-1];
649 if (ff_get_wav_header(pb, st->codec, atom.size) < 0) {
650 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
656 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
658 const int num = avio_rb32(pb);
659 const int den = avio_rb32(pb);
662 if (c->fc->nb_streams < 1)
664 st = c->fc->streams[c->fc->nb_streams-1];
666 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
667 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
668 av_log(c->fc, AV_LOG_WARNING,
669 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
670 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
672 } else if (den != 0) {
673 st->sample_aspect_ratio.num = num;
674 st->sample_aspect_ratio.den = den;
679 /* this atom contains actual media data */
680 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
682 if (atom.size == 0) /* wrong one (MP4) */
685 return 0; /* now go for moov */
688 /* read major brand, minor version and compatible brands and store them as metadata */
689 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
693 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
694 char* comp_brands_str;
695 uint8_t type[5] = {0};
697 avio_read(pb, type, 4);
698 if (strcmp(type, "qt "))
700 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
701 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
702 minor_ver = avio_rb32(pb); /* minor version */
703 snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);
704 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
706 comp_brand_size = atom.size - 8;
707 if (comp_brand_size < 0)
708 return AVERROR_INVALIDDATA;
709 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
710 if (!comp_brands_str)
711 return AVERROR(ENOMEM);
712 avio_read(pb, comp_brands_str, comp_brand_size);
713 comp_brands_str[comp_brand_size] = 0;
714 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
715 av_freep(&comp_brands_str);
720 /* this atom should contain all header atoms */
721 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
726 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
727 avio_skip(pb, atom.size);
731 if ((ret = mov_read_default(c, pb, atom)) < 0)
733 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
734 /* so we don't parse the whole file if over a network */
736 return 0; /* now go for mdat */
739 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
741 c->fragment.moof_offset = avio_tell(pb) - 8;
742 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
743 return mov_read_default(c, pb, atom);
746 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
752 if(time >= 2082844800)
753 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
755 ptm = gmtime(&timet);
757 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
758 av_dict_set(metadata, "creation_time", buffer, 0);
762 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
765 MOVStreamContext *sc;
767 char language[4] = {0};
769 int64_t creation_time;
771 if (c->fc->nb_streams < 1)
773 st = c->fc->streams[c->fc->nb_streams-1];
776 if (sc->time_scale) {
777 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
778 return AVERROR_INVALIDDATA;
781 version = avio_r8(pb);
783 avpriv_request_sample(c->fc, "Version %d", version);
784 return AVERROR_PATCHWELCOME;
786 avio_rb24(pb); /* flags */
788 creation_time = avio_rb64(pb);
791 creation_time = avio_rb32(pb);
792 avio_rb32(pb); /* modification time */
794 mov_metadata_creation_time(&st->metadata, creation_time);
796 sc->time_scale = avio_rb32(pb);
797 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
799 lang = avio_rb16(pb); /* language */
800 if (ff_mov_lang_to_iso639(lang, language))
801 av_dict_set(&st->metadata, "language", language, 0);
802 avio_rb16(pb); /* quality */
807 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
809 int64_t creation_time;
810 int version = avio_r8(pb); /* version */
811 avio_rb24(pb); /* flags */
814 creation_time = avio_rb64(pb);
817 creation_time = avio_rb32(pb);
818 avio_rb32(pb); /* modification time */
820 mov_metadata_creation_time(&c->fc->metadata, creation_time);
821 c->time_scale = avio_rb32(pb); /* time scale */
823 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
825 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
826 // set the AVCodecContext duration because the duration of individual tracks
828 if (c->time_scale > 0 && !c->trex_data)
829 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
830 avio_rb32(pb); /* preferred scale */
832 avio_rb16(pb); /* preferred volume */
834 avio_skip(pb, 10); /* reserved */
836 avio_skip(pb, 36); /* display matrix */
838 avio_rb32(pb); /* preview time */
839 avio_rb32(pb); /* preview duration */
840 avio_rb32(pb); /* poster time */
841 avio_rb32(pb); /* selection time */
842 avio_rb32(pb); /* selection duration */
843 avio_rb32(pb); /* current time */
844 avio_rb32(pb); /* next track ID */
848 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
853 if (c->fc->nb_streams < 1)
855 st = c->fc->streams[c->fc->nb_streams-1];
857 little_endian = avio_rb16(pb) & 0xFF;
858 av_dlog(c->fc, "enda %d\n", little_endian);
859 if (little_endian == 1) {
860 switch (st->codec->codec_id) {
861 case AV_CODEC_ID_PCM_S24BE:
862 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
864 case AV_CODEC_ID_PCM_S32BE:
865 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
867 case AV_CODEC_ID_PCM_F32BE:
868 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
870 case AV_CODEC_ID_PCM_F64BE:
871 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
880 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
883 unsigned mov_field_order;
884 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
886 if (c->fc->nb_streams < 1) // will happen with jp2 files
888 st = c->fc->streams[c->fc->nb_streams-1];
890 return AVERROR_INVALIDDATA;
891 mov_field_order = avio_rb16(pb);
892 if ((mov_field_order & 0xFF00) == 0x0100)
893 decoded_field_order = AV_FIELD_PROGRESSIVE;
894 else if ((mov_field_order & 0xFF00) == 0x0200) {
895 switch (mov_field_order & 0xFF) {
896 case 0x01: decoded_field_order = AV_FIELD_TT;
898 case 0x06: decoded_field_order = AV_FIELD_BB;
900 case 0x09: decoded_field_order = AV_FIELD_TB;
902 case 0x0E: decoded_field_order = AV_FIELD_BT;
906 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
907 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
909 st->codec->field_order = decoded_field_order;
914 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
915 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
916 enum AVCodecID codec_id)
923 if (c->fc->nb_streams < 1) // will happen with jp2 files
925 st= c->fc->streams[c->fc->nb_streams-1];
927 if (st->codec->codec_id != codec_id)
928 return 0; /* unexpected codec_id - don't mess with extradata */
930 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
931 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
932 return AVERROR_INVALIDDATA;
933 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
934 st->codec->extradata_size = 0;
937 buf = st->codec->extradata + st->codec->extradata_size;
938 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
939 AV_WB32( buf , atom.size + 8);
940 AV_WL32( buf + 4, atom.type);
941 err = avio_read(pb, buf + 8, atom.size);
944 } else if (err < atom.size) {
945 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
946 st->codec->extradata_size -= atom.size - err;
948 memset(buf + 8 + err, 0, FF_INPUT_BUFFER_PADDING_SIZE);
952 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
953 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
955 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
958 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
960 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
963 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
965 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
968 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
970 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
973 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
975 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
977 if (!ret && c->fc->nb_streams >= 1) {
978 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
979 if (avctx->extradata_size >= 40) {
980 avctx->height = AV_RB16(&avctx->extradata[36]);
981 avctx->width = AV_RB16(&avctx->extradata[38]);
987 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
989 if (c->fc->nb_streams >= 1) {
990 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
991 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
992 codec->codec_id == AV_CODEC_ID_H264 &&
995 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
996 if (avio_rb16(pb) == 0xd4d)
1002 return mov_read_avid(c, pb, atom);
1005 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1007 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1010 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1014 if (c->fc->nb_streams < 1)
1016 st = c->fc->streams[c->fc->nb_streams-1];
1018 if ((uint64_t)atom.size > (1<<30))
1019 return AVERROR_INVALIDDATA;
1021 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1022 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1023 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1024 // pass all frma atom to codec, needed at least for QDMC and QDM2
1025 av_free(st->codec->extradata);
1026 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1027 return AVERROR(ENOMEM);
1028 } else if (atom.size > 8) { /* to read frma, esds atoms */
1030 if ((ret = mov_read_default(c, pb, atom)) < 0)
1033 avio_skip(pb, atom.size);
1038 * This function reads atom content and puts data in extradata without tag
1039 * nor size unlike mov_read_extradata.
1041 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1045 if (c->fc->nb_streams < 1)
1047 st = c->fc->streams[c->fc->nb_streams-1];
1049 if ((uint64_t)atom.size > (1<<30))
1050 return AVERROR_INVALIDDATA;
1052 if (atom.size >= 10) {
1053 // Broken files created by legacy versions of libavformat will
1054 // wrap a whole fiel atom inside of a glbl atom.
1055 unsigned size = avio_rb32(pb);
1056 unsigned type = avio_rl32(pb);
1057 avio_seek(pb, -8, SEEK_CUR);
1058 if (type == MKTAG('f','i','e','l') && size == atom.size)
1059 return mov_read_default(c, pb, atom);
1061 av_free(st->codec->extradata);
1062 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1063 return AVERROR(ENOMEM);
1068 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1071 uint8_t profile_level;
1074 if (c->fc->nb_streams < 1)
1076 st = c->fc->streams[c->fc->nb_streams-1];
1078 if (atom.size >= (1<<28) || atom.size < 7)
1079 return AVERROR_INVALIDDATA;
1081 profile_level = avio_r8(pb);
1082 if ((profile_level & 0xf0) != 0xc0)
1085 avio_seek(pb, 6, SEEK_CUR);
1086 av_free(st->codec->extradata);
1087 if ((ret = ff_get_extradata(st->codec, pb, atom.size - 7)) < 0)
1094 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1095 * but can have extradata appended at the end after the 40 bytes belonging
1098 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1102 if (c->fc->nb_streams < 1)
1104 if (atom.size <= 40)
1106 st = c->fc->streams[c->fc->nb_streams-1];
1108 if ((uint64_t)atom.size > (1<<30))
1109 return AVERROR_INVALIDDATA;
1112 av_free(st->codec->extradata);
1113 if (ff_get_extradata(st->codec, pb, atom.size - 40) < 0)
1114 return AVERROR(ENOMEM);
1118 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1121 MOVStreamContext *sc;
1122 unsigned int i, entries;
1124 if (c->fc->nb_streams < 1)
1126 st = c->fc->streams[c->fc->nb_streams-1];
1129 avio_r8(pb); /* version */
1130 avio_rb24(pb); /* flags */
1132 entries = avio_rb32(pb);
1136 if (entries >= UINT_MAX/sizeof(int64_t))
1137 return AVERROR_INVALIDDATA;
1139 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1140 if (!sc->chunk_offsets)
1141 return AVERROR(ENOMEM);
1142 sc->chunk_count = entries;
1144 if (atom.type == MKTAG('s','t','c','o'))
1145 for (i = 0; i < entries && !pb->eof_reached; i++)
1146 sc->chunk_offsets[i] = avio_rb32(pb);
1147 else if (atom.type == MKTAG('c','o','6','4'))
1148 for (i = 0; i < entries && !pb->eof_reached; i++)
1149 sc->chunk_offsets[i] = avio_rb64(pb);
1151 return AVERROR_INVALIDDATA;
1153 sc->chunk_count = i;
1155 if (pb->eof_reached)
1162 * Compute codec id for 'lpcm' tag.
1163 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1165 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1172 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1175 static int mov_codec_id(AVStream *st, uint32_t format)
1177 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1180 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1181 (format & 0xFFFF) == 'T' + ('S' << 8)))
1182 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1184 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1185 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1186 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1187 /* skip old asf mpeg4 tag */
1188 format && format != MKTAG('m','p','4','s')) {
1189 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1191 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1193 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1194 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1195 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1196 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1197 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1199 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1203 st->codec->codec_tag = format;
1208 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1209 AVStream *st, MOVStreamContext *sc)
1211 unsigned int color_depth, len, j;
1212 int color_greyscale;
1215 avio_rb16(pb); /* version */
1216 avio_rb16(pb); /* revision level */
1217 avio_rb32(pb); /* vendor */
1218 avio_rb32(pb); /* temporal quality */
1219 avio_rb32(pb); /* spatial quality */
1221 st->codec->width = avio_rb16(pb); /* width */
1222 st->codec->height = avio_rb16(pb); /* height */
1224 avio_rb32(pb); /* horiz resolution */
1225 avio_rb32(pb); /* vert resolution */
1226 avio_rb32(pb); /* data size, always 0 */
1227 avio_rb16(pb); /* frames per samples */
1229 len = avio_r8(pb); /* codec name, pascal string */
1232 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1234 avio_skip(pb, 31 - len);
1235 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1236 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1237 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1238 st->codec->width &= ~1;
1239 st->codec->height &= ~1;
1241 /* Flash Media Server uses tag H263 with Sorenson Spark */
1242 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1243 !memcmp(st->codec->codec_name, "Sorenson H263", 13))
1244 st->codec->codec_id = AV_CODEC_ID_FLV1;
1246 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1247 color_table_id = avio_rb16(pb); /* colortable id */
1248 av_dlog(c->fc, "depth %d, ctab id %d\n",
1249 st->codec->bits_per_coded_sample, color_table_id);
1250 /* figure out the palette situation */
1251 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1252 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1253 /* Do not create a greyscale palette for cinepak */
1254 if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1257 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1258 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1259 /* for palette traversal */
1260 unsigned int color_start, color_count, color_end;
1261 unsigned char a, r, g, b;
1263 if (color_greyscale) {
1264 int color_index, color_dec;
1265 /* compute the greyscale palette */
1266 st->codec->bits_per_coded_sample = color_depth;
1267 color_count = 1 << color_depth;
1269 color_dec = 256 / (color_count - 1);
1270 for (j = 0; j < color_count; j++) {
1271 r = g = b = color_index;
1272 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1273 color_index -= color_dec;
1274 if (color_index < 0)
1277 } else if (color_table_id) {
1278 const uint8_t *color_table;
1279 /* if flag bit 3 is set, use the default palette */
1280 color_count = 1 << color_depth;
1281 if (color_depth == 2)
1282 color_table = ff_qt_default_palette_4;
1283 else if (color_depth == 4)
1284 color_table = ff_qt_default_palette_16;
1286 color_table = ff_qt_default_palette_256;
1288 for (j = 0; j < color_count; j++) {
1289 r = color_table[j * 3 + 0];
1290 g = color_table[j * 3 + 1];
1291 b = color_table[j * 3 + 2];
1292 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1295 /* load the palette from the file */
1296 color_start = avio_rb32(pb);
1297 color_count = avio_rb16(pb);
1298 color_end = avio_rb16(pb);
1299 if ((color_start <= 255) && (color_end <= 255)) {
1300 for (j = color_start; j <= color_end; j++) {
1301 /* each A, R, G, or B component is 16 bits;
1302 * only use the top 8 bits */
1311 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1315 sc->has_palette = 1;
1319 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1320 AVStream *st, MOVStreamContext *sc)
1322 int bits_per_sample, flags;
1323 uint16_t version = avio_rb16(pb);
1324 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1326 avio_rb16(pb); /* revision level */
1327 avio_rb32(pb); /* vendor */
1329 st->codec->channels = avio_rb16(pb); /* channel count */
1330 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1331 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1333 sc->audio_cid = avio_rb16(pb);
1334 avio_rb16(pb); /* packet size = 0 */
1336 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1338 // Read QT version 1 fields. In version 0 these do not exist.
1339 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1341 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1344 sc->samples_per_frame = avio_rb32(pb);
1345 avio_rb32(pb); /* bytes per packet */
1346 sc->bytes_per_frame = avio_rb32(pb);
1347 avio_rb32(pb); /* bytes per sample */
1348 } else if (version == 2) {
1349 avio_rb32(pb); /* sizeof struct only */
1350 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1351 st->codec->channels = avio_rb32(pb);
1352 avio_rb32(pb); /* always 0x7F000000 */
1353 st->codec->bits_per_coded_sample = avio_rb32(pb);
1355 flags = avio_rb32(pb); /* lpcm format specific flag */
1356 sc->bytes_per_frame = avio_rb32(pb);
1357 sc->samples_per_frame = avio_rb32(pb);
1358 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1359 st->codec->codec_id =
1360 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1365 switch (st->codec->codec_id) {
1366 case AV_CODEC_ID_PCM_S8:
1367 case AV_CODEC_ID_PCM_U8:
1368 if (st->codec->bits_per_coded_sample == 16)
1369 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1371 case AV_CODEC_ID_PCM_S16LE:
1372 case AV_CODEC_ID_PCM_S16BE:
1373 if (st->codec->bits_per_coded_sample == 8)
1374 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1375 else if (st->codec->bits_per_coded_sample == 24)
1376 st->codec->codec_id =
1377 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1378 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1380 /* set values for old format before stsd version 1 appeared */
1381 case AV_CODEC_ID_MACE3:
1382 sc->samples_per_frame = 6;
1383 sc->bytes_per_frame = 2 * st->codec->channels;
1385 case AV_CODEC_ID_MACE6:
1386 sc->samples_per_frame = 6;
1387 sc->bytes_per_frame = 1 * st->codec->channels;
1389 case AV_CODEC_ID_ADPCM_IMA_QT:
1390 sc->samples_per_frame = 64;
1391 sc->bytes_per_frame = 34 * st->codec->channels;
1393 case AV_CODEC_ID_GSM:
1394 sc->samples_per_frame = 160;
1395 sc->bytes_per_frame = 33;
1401 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1402 if (bits_per_sample) {
1403 st->codec->bits_per_coded_sample = bits_per_sample;
1404 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1408 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1409 AVStream *st, MOVStreamContext *sc,
1412 // ttxt stsd contains display flags, justification, background
1413 // color, fonts, and default styles, so fake an atom to read it
1414 MOVAtom fake_atom = { .size = size };
1415 // mp4s contains a regular esds atom
1416 if (st->codec->codec_tag != AV_RL32("mp4s"))
1417 mov_read_glbl(c, pb, fake_atom);
1418 st->codec->width = sc->width;
1419 st->codec->height = sc->height;
1422 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1427 y = (ycbcr >> 16) & 0xFF;
1428 cr = (ycbcr >> 8) & 0xFF;
1431 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1432 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1433 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1435 return (r << 16) | (g << 8) | b;
1438 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1440 char buf[256] = {0};
1441 uint8_t *src = st->codec->extradata;
1444 if (st->codec->extradata_size != 64)
1447 if (st->codec->width > 0 && st->codec->height > 0)
1448 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1449 st->codec->width, st->codec->height);
1450 av_strlcat(buf, "palette: ", sizeof(buf));
1452 for (i = 0; i < 16; i++) {
1453 uint32_t yuv = AV_RB32(src + i * 4);
1454 uint32_t rgba = yuv_to_rgba(yuv);
1456 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1459 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1462 av_freep(&st->codec->extradata);
1463 st->codec->extradata_size = 0;
1464 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1465 if (!st->codec->extradata)
1466 return AVERROR(ENOMEM);
1467 st->codec->extradata_size = strlen(buf);
1468 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1473 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1474 AVStream *st, MOVStreamContext *sc,
1477 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1478 if (ff_get_extradata(st->codec, pb, size) < 0)
1479 return AVERROR(ENOMEM);
1481 MOVStreamContext *tmcd_ctx = st->priv_data;
1483 val = AV_RB32(st->codec->extradata + 4);
1484 tmcd_ctx->tmcd_flags = val;
1486 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1487 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
1488 st->codec->time_base.num = 1;
1491 /* other codec type, just skip (rtp, mp4s ...) */
1492 avio_skip(pb, size);
1497 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1498 AVStream *st, MOVStreamContext *sc)
1500 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1501 !st->codec->sample_rate && sc->time_scale > 1)
1502 st->codec->sample_rate = sc->time_scale;
1504 /* special codec parameters handling */
1505 switch (st->codec->codec_id) {
1506 #if CONFIG_DV_DEMUXER
1507 case AV_CODEC_ID_DVAUDIO:
1508 c->dv_fctx = avformat_alloc_context();
1509 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1511 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1512 return AVERROR(ENOMEM);
1514 sc->dv_audio_container = 1;
1515 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1518 /* no ifdef since parameters are always those */
1519 case AV_CODEC_ID_QCELP:
1520 st->codec->channels = 1;
1521 // force sample rate for qcelp when not stored in mov
1522 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1523 st->codec->sample_rate = 8000;
1524 // FIXME: Why is the following needed for some files?
1525 sc->samples_per_frame = 160;
1526 if (!sc->bytes_per_frame)
1527 sc->bytes_per_frame = 35;
1529 case AV_CODEC_ID_AMR_NB:
1530 st->codec->channels = 1;
1531 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1532 st->codec->sample_rate = 8000;
1534 case AV_CODEC_ID_AMR_WB:
1535 st->codec->channels = 1;
1536 st->codec->sample_rate = 16000;
1538 case AV_CODEC_ID_MP2:
1539 case AV_CODEC_ID_MP3:
1540 /* force type after stsd for m1a hdlr */
1541 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1542 st->need_parsing = AVSTREAM_PARSE_FULL;
1544 case AV_CODEC_ID_GSM:
1545 case AV_CODEC_ID_ADPCM_MS:
1546 case AV_CODEC_ID_ADPCM_IMA_WAV:
1547 case AV_CODEC_ID_ILBC:
1548 case AV_CODEC_ID_MACE3:
1549 case AV_CODEC_ID_MACE6:
1550 case AV_CODEC_ID_QDM2:
1551 st->codec->block_align = sc->bytes_per_frame;
1553 case AV_CODEC_ID_ALAC:
1554 if (st->codec->extradata_size == 36) {
1555 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1556 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1559 case AV_CODEC_ID_AC3:
1560 case AV_CODEC_ID_MPEG1VIDEO:
1561 case AV_CODEC_ID_VC1:
1562 st->need_parsing = AVSTREAM_PARSE_FULL;
1570 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1571 int codec_tag, int format,
1574 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1577 (codec_tag != format &&
1578 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1579 : codec_tag != MKTAG('j','p','e','g')))) {
1580 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1581 * export it as a separate AVStream but this needs a few changes
1582 * in the MOV demuxer, patch welcome. */
1584 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1585 avio_skip(pb, size);
1588 if ( codec_tag == AV_RL32("avc1") ||
1589 codec_tag == AV_RL32("hvc1") ||
1590 codec_tag == AV_RL32("hev1")
1592 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
1597 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1600 MOVStreamContext *sc;
1601 int pseudo_stream_id;
1603 if (c->fc->nb_streams < 1)
1605 st = c->fc->streams[c->fc->nb_streams-1];
1608 for (pseudo_stream_id = 0;
1609 pseudo_stream_id < entries && !pb->eof_reached;
1610 pseudo_stream_id++) {
1611 //Parsing Sample description table
1613 int ret, dref_id = 1;
1614 MOVAtom a = { AV_RL32("stsd") };
1615 int64_t start_pos = avio_tell(pb);
1616 int64_t size = avio_rb32(pb); /* size */
1617 uint32_t format = avio_rl32(pb); /* data format */
1620 avio_rb32(pb); /* reserved */
1621 avio_rb16(pb); /* reserved */
1622 dref_id = avio_rb16(pb);
1623 }else if (size <= 7){
1624 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1625 return AVERROR_INVALIDDATA;
1628 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1629 size - (avio_tell(pb) - start_pos)))
1632 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1633 sc->dref_id= dref_id;
1635 id = mov_codec_id(st, format);
1637 av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1638 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1639 (format >> 24) & 0xff, st->codec->codec_type);
1641 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1642 st->codec->codec_id = id;
1643 mov_parse_stsd_video(c, pb, st, sc);
1644 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1645 st->codec->codec_id = id;
1646 mov_parse_stsd_audio(c, pb, st, sc);
1647 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1648 st->codec->codec_id = id;
1649 mov_parse_stsd_subtitle(c, pb, st, sc,
1650 size - (avio_tell(pb) - start_pos));
1652 ret = mov_parse_stsd_data(c, pb, st, sc,
1653 size - (avio_tell(pb) - start_pos));
1657 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1658 a.size = size - (avio_tell(pb) - start_pos);
1660 if ((ret = mov_read_default(c, pb, a)) < 0)
1662 } else if (a.size > 0)
1663 avio_skip(pb, a.size);
1666 if (pb->eof_reached)
1669 return mov_finalize_stsd_codec(c, pb, st, sc);
1672 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1676 avio_r8(pb); /* version */
1677 avio_rb24(pb); /* flags */
1678 entries = avio_rb32(pb);
1680 return ff_mov_read_stsd_entries(c, pb, entries);
1683 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1686 MOVStreamContext *sc;
1687 unsigned int i, entries;
1689 if (c->fc->nb_streams < 1)
1691 st = c->fc->streams[c->fc->nb_streams-1];
1694 avio_r8(pb); /* version */
1695 avio_rb24(pb); /* flags */
1697 entries = avio_rb32(pb);
1699 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1703 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1704 return AVERROR_INVALIDDATA;
1705 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1707 return AVERROR(ENOMEM);
1709 for (i = 0; i < entries && !pb->eof_reached; i++) {
1710 sc->stsc_data[i].first = avio_rb32(pb);
1711 sc->stsc_data[i].count = avio_rb32(pb);
1712 sc->stsc_data[i].id = avio_rb32(pb);
1717 if (pb->eof_reached)
1723 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1726 MOVStreamContext *sc;
1727 unsigned i, entries;
1729 if (c->fc->nb_streams < 1)
1731 st = c->fc->streams[c->fc->nb_streams-1];
1734 avio_rb32(pb); // version + flags
1736 entries = avio_rb32(pb);
1737 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1738 return AVERROR_INVALIDDATA;
1739 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1741 return AVERROR(ENOMEM);
1743 for (i = 0; i < entries && !pb->eof_reached; i++) {
1744 sc->stps_data[i] = avio_rb32(pb);
1745 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1750 if (pb->eof_reached)
1756 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1759 MOVStreamContext *sc;
1760 unsigned int i, entries;
1762 if (c->fc->nb_streams < 1)
1764 st = c->fc->streams[c->fc->nb_streams-1];
1767 avio_r8(pb); /* version */
1768 avio_rb24(pb); /* flags */
1770 entries = avio_rb32(pb);
1772 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1776 sc->keyframe_absent = 1;
1777 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1778 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1781 if (entries >= UINT_MAX / sizeof(int))
1782 return AVERROR_INVALIDDATA;
1783 sc->keyframes = av_malloc(entries * sizeof(int));
1785 return AVERROR(ENOMEM);
1787 for (i = 0; i < entries && !pb->eof_reached; i++) {
1788 sc->keyframes[i] = avio_rb32(pb);
1789 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1792 sc->keyframe_count = i;
1794 if (pb->eof_reached)
1800 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1803 MOVStreamContext *sc;
1804 unsigned int i, entries, sample_size, field_size, num_bytes;
1808 if (c->fc->nb_streams < 1)
1810 st = c->fc->streams[c->fc->nb_streams-1];
1813 avio_r8(pb); /* version */
1814 avio_rb24(pb); /* flags */
1816 if (atom.type == MKTAG('s','t','s','z')) {
1817 sample_size = avio_rb32(pb);
1818 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1819 sc->sample_size = sample_size;
1820 sc->stsz_sample_size = sample_size;
1824 avio_rb24(pb); /* reserved */
1825 field_size = avio_r8(pb);
1827 entries = avio_rb32(pb);
1829 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1831 sc->sample_count = entries;
1835 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1836 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1837 return AVERROR_INVALIDDATA;
1842 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1843 return AVERROR_INVALIDDATA;
1844 sc->sample_sizes = av_malloc(entries * sizeof(int));
1845 if (!sc->sample_sizes)
1846 return AVERROR(ENOMEM);
1848 num_bytes = (entries*field_size+4)>>3;
1850 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1852 av_freep(&sc->sample_sizes);
1853 return AVERROR(ENOMEM);
1856 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1857 av_freep(&sc->sample_sizes);
1859 return AVERROR_INVALIDDATA;
1862 init_get_bits(&gb, buf, 8*num_bytes);
1864 for (i = 0; i < entries && !pb->eof_reached; i++) {
1865 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1866 sc->data_size += sc->sample_sizes[i];
1869 sc->sample_count = i;
1871 if (pb->eof_reached)
1878 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1881 MOVStreamContext *sc;
1882 unsigned int i, entries;
1884 int64_t total_sample_count=0;
1886 if (c->fc->nb_streams < 1)
1888 st = c->fc->streams[c->fc->nb_streams-1];
1891 avio_r8(pb); /* version */
1892 avio_rb24(pb); /* flags */
1893 entries = avio_rb32(pb);
1895 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1896 c->fc->nb_streams-1, entries);
1898 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1901 av_free(sc->stts_data);
1902 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1904 return AVERROR(ENOMEM);
1906 for (i = 0; i < entries && !pb->eof_reached; i++) {
1907 int sample_duration;
1910 sample_count=avio_rb32(pb);
1911 sample_duration = avio_rb32(pb);
1913 /* sample_duration < 0 is invalid based on the spec */
1914 if (sample_duration < 0) {
1915 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta %d in STTS, at %d st:%d\n",
1916 sample_duration, i, c->fc->nb_streams-1);
1917 sample_duration = 1;
1919 if (sample_count < 0) {
1920 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
1921 return AVERROR_INVALIDDATA;
1923 sc->stts_data[i].count= sample_count;
1924 sc->stts_data[i].duration= sample_duration;
1926 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1927 sample_count, sample_duration);
1931 && sample_count == 1
1932 && total_sample_count > 100
1933 && sample_duration/10 > duration / total_sample_count)
1934 sample_duration = duration / total_sample_count;
1935 duration+=(int64_t)sample_duration*sample_count;
1936 total_sample_count+=sample_count;
1941 sc->duration_for_fps += duration;
1942 sc->nb_frames_for_fps += total_sample_count;
1944 if (pb->eof_reached)
1947 st->nb_frames= total_sample_count;
1949 st->duration= duration;
1950 sc->track_end = duration;
1954 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
1957 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1961 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1964 MOVStreamContext *sc;
1965 unsigned int i, entries;
1967 if (c->fc->nb_streams < 1)
1969 st = c->fc->streams[c->fc->nb_streams-1];
1972 avio_r8(pb); /* version */
1973 avio_rb24(pb); /* flags */
1974 entries = avio_rb32(pb);
1976 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1980 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1981 return AVERROR_INVALIDDATA;
1982 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1984 return AVERROR(ENOMEM);
1986 for (i = 0; i < entries && !pb->eof_reached; i++) {
1987 int count =avio_rb32(pb);
1988 int duration =avio_rb32(pb);
1990 sc->ctts_data[i].count = count;
1991 sc->ctts_data[i].duration= duration;
1993 av_dlog(c->fc, "count=%d, duration=%d\n",
1996 if (FFABS(duration) > (1<<28) && i+2<entries) {
1997 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
1998 av_freep(&sc->ctts_data);
2004 mov_update_dts_shift(sc, duration);
2009 if (pb->eof_reached)
2012 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
2017 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2020 MOVStreamContext *sc;
2021 unsigned int i, entries;
2023 uint32_t grouping_type;
2025 if (c->fc->nb_streams < 1)
2027 st = c->fc->streams[c->fc->nb_streams-1];
2030 version = avio_r8(pb); /* version */
2031 avio_rb24(pb); /* flags */
2032 grouping_type = avio_rl32(pb);
2033 if (grouping_type != MKTAG( 'r','a','p',' '))
2034 return 0; /* only support 'rap ' grouping */
2036 avio_rb32(pb); /* grouping_type_parameter */
2038 entries = avio_rb32(pb);
2041 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2042 return AVERROR_INVALIDDATA;
2043 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2045 return AVERROR(ENOMEM);
2047 for (i = 0; i < entries && !pb->eof_reached; i++) {
2048 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2049 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2052 sc->rap_group_count = i;
2054 return pb->eof_reached ? AVERROR_EOF : 0;
2057 static void mov_build_index(MOVContext *mov, AVStream *st)
2059 MOVStreamContext *sc = st->priv_data;
2060 int64_t current_offset;
2061 int64_t current_dts = 0;
2062 unsigned int stts_index = 0;
2063 unsigned int stsc_index = 0;
2064 unsigned int stss_index = 0;
2065 unsigned int stps_index = 0;
2067 uint64_t stream_size = 0;
2069 /* adjust first dts according to edit list */
2070 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
2071 if (sc->empty_duration)
2072 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
2073 sc->time_offset = sc->start_time - sc->empty_duration;
2074 current_dts = -sc->time_offset;
2075 if (sc->ctts_count>0 && sc->stts_count>0 &&
2076 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2077 /* more than 16 frames delay, dts are likely wrong
2078 this happens with files created by iMovie */
2080 st->codec->has_b_frames = 1;
2084 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2085 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2086 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2087 unsigned int current_sample = 0;
2088 unsigned int stts_sample = 0;
2089 unsigned int sample_size;
2090 unsigned int distance = 0;
2091 unsigned int rap_group_index = 0;
2092 unsigned int rap_group_sample = 0;
2093 int rap_group_present = sc->rap_group_count && sc->rap_group;
2094 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2096 current_dts -= sc->dts_shift;
2098 if (!sc->sample_count || st->nb_index_entries)
2100 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2102 if (av_reallocp_array(&st->index_entries,
2103 st->nb_index_entries + sc->sample_count,
2104 sizeof(*st->index_entries)) < 0) {
2105 st->nb_index_entries = 0;
2108 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2110 for (i = 0; i < sc->chunk_count; i++) {
2111 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2112 current_offset = sc->chunk_offsets[i];
2113 while (stsc_index + 1 < sc->stsc_count &&
2114 i + 1 == sc->stsc_data[stsc_index + 1].first)
2117 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2118 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2119 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2120 sc->stsz_sample_size = sc->sample_size;
2122 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2123 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2124 sc->stsz_sample_size = sc->sample_size;
2127 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2129 if (current_sample >= sc->sample_count) {
2130 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2134 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2136 if (stss_index + 1 < sc->keyframe_count)
2138 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2140 if (stps_index + 1 < sc->stps_count)
2143 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2144 if (sc->rap_group[rap_group_index].index > 0)
2146 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2147 rap_group_sample = 0;
2151 if (sc->keyframe_absent
2153 && !rap_group_present
2154 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2158 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2159 if (sc->pseudo_stream_id == -1 ||
2160 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2161 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2162 e->pos = current_offset;
2163 e->timestamp = current_dts;
2164 e->size = sample_size;
2165 e->min_distance = distance;
2166 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2167 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2168 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2169 current_offset, current_dts, sample_size, distance, keyframe);
2170 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2171 ff_rfps_add_frame(mov->fc, st, current_dts);
2174 current_offset += sample_size;
2175 stream_size += sample_size;
2176 current_dts += sc->stts_data[stts_index].duration;
2180 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2186 if (st->duration > 0)
2187 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2189 unsigned chunk_samples, total = 0;
2191 // compute total chunk count
2192 for (i = 0; i < sc->stsc_count; i++) {
2193 unsigned count, chunk_count;
2195 chunk_samples = sc->stsc_data[i].count;
2196 if (i != sc->stsc_count - 1 &&
2197 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2198 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2202 if (sc->samples_per_frame >= 160) { // gsm
2203 count = chunk_samples / sc->samples_per_frame;
2204 } else if (sc->samples_per_frame > 1) {
2205 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2206 count = (chunk_samples+samples-1) / samples;
2208 count = (chunk_samples+1023) / 1024;
2211 if (i < sc->stsc_count - 1)
2212 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2214 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2215 total += chunk_count * count;
2218 av_dlog(mov->fc, "chunk count %d\n", total);
2219 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2221 if (av_reallocp_array(&st->index_entries,
2222 st->nb_index_entries + total,
2223 sizeof(*st->index_entries)) < 0) {
2224 st->nb_index_entries = 0;
2227 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2230 for (i = 0; i < sc->chunk_count; i++) {
2231 current_offset = sc->chunk_offsets[i];
2232 if (stsc_index + 1 < sc->stsc_count &&
2233 i + 1 == sc->stsc_data[stsc_index + 1].first)
2235 chunk_samples = sc->stsc_data[stsc_index].count;
2237 while (chunk_samples > 0) {
2239 unsigned size, samples;
2241 if (sc->samples_per_frame >= 160) { // gsm
2242 samples = sc->samples_per_frame;
2243 size = sc->bytes_per_frame;
2245 if (sc->samples_per_frame > 1) {
2246 samples = FFMIN((1024 / sc->samples_per_frame)*
2247 sc->samples_per_frame, chunk_samples);
2248 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2250 samples = FFMIN(1024, chunk_samples);
2251 size = samples * sc->sample_size;
2255 if (st->nb_index_entries >= total) {
2256 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2259 e = &st->index_entries[st->nb_index_entries++];
2260 e->pos = current_offset;
2261 e->timestamp = current_dts;
2263 e->min_distance = 0;
2264 e->flags = AVINDEX_KEYFRAME;
2265 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2266 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2269 current_offset += size;
2270 current_dts += samples;
2271 chunk_samples -= samples;
2277 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2278 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2280 /* try relative path, we do not try the absolute because it can leak information about our
2281 system to an attacker */
2282 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2283 char filename[1024];
2284 const char *src_path;
2287 /* find a source dir */
2288 src_path = strrchr(src, '/');
2294 /* find a next level down to target */
2295 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2296 if (ref->path[l] == '/') {
2297 if (i == ref->nlvl_to - 1)
2303 /* compose filename if next level down to target was found */
2304 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2305 memcpy(filename, src, src_path - src);
2306 filename[src_path - src] = 0;
2308 for (i = 1; i < ref->nlvl_from; i++)
2309 av_strlcat(filename, "../", 1024);
2311 av_strlcat(filename, ref->path + l + 1, 1024);
2313 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2316 } else if (use_absolute_path) {
2317 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2318 "this is a possible security issue\n");
2319 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2323 return AVERROR(ENOENT);
2326 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2328 if (sc->time_scale <= 0) {
2329 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2330 sc->time_scale = c->time_scale;
2331 if (sc->time_scale <= 0)
2336 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2339 MOVStreamContext *sc;
2342 st = avformat_new_stream(c->fc, NULL);
2343 if (!st) return AVERROR(ENOMEM);
2344 st->id = c->fc->nb_streams;
2345 sc = av_mallocz(sizeof(MOVStreamContext));
2346 if (!sc) return AVERROR(ENOMEM);
2349 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2350 sc->ffindex = st->index;
2352 if ((ret = mov_read_default(c, pb, atom)) < 0)
2356 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2357 (!sc->sample_size && !sc->sample_count))) {
2358 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2363 fix_timescale(c, sc);
2365 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2367 mov_build_index(c, st);
2369 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2370 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2371 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2372 c->use_absolute_path, c->fc) < 0)
2373 av_log(c->fc, AV_LOG_ERROR,
2374 "stream %d, error opening alias: path='%s', dir='%s', "
2375 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2376 st->index, dref->path, dref->dir, dref->filename,
2377 dref->volume, dref->nlvl_from, dref->nlvl_to);
2380 sc->pb_is_copied = 1;
2383 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2384 if (!st->sample_aspect_ratio.num &&
2385 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2386 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2387 ((double)st->codec->width * sc->height), INT_MAX);
2390 #if FF_API_R_FRAME_RATE
2391 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2392 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2393 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2397 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2398 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2399 TAG_IS_AVCI(st->codec->codec_tag)) {
2400 ret = ff_generate_avci_extradata(st);
2405 switch (st->codec->codec_id) {
2406 #if CONFIG_H261_DECODER
2407 case AV_CODEC_ID_H261:
2409 #if CONFIG_H263_DECODER
2410 case AV_CODEC_ID_H263:
2412 #if CONFIG_MPEG4_DECODER
2413 case AV_CODEC_ID_MPEG4:
2415 st->codec->width = 0; /* let decoder init width/height */
2416 st->codec->height= 0;
2420 /* Do not need those anymore. */
2421 av_freep(&sc->chunk_offsets);
2422 av_freep(&sc->stsc_data);
2423 av_freep(&sc->sample_sizes);
2424 av_freep(&sc->keyframes);
2425 av_freep(&sc->stts_data);
2426 av_freep(&sc->stps_data);
2427 av_freep(&sc->rap_group);
2432 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2435 c->itunes_metadata = 1;
2436 ret = mov_read_default(c, pb, atom);
2437 c->itunes_metadata = 0;
2441 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
2443 int64_t end = avio_tell(pb) + size;
2444 uint8_t *key = NULL, *val = NULL;
2447 MOVStreamContext *sc;
2449 if (c->fc->nb_streams < 1)
2451 st = c->fc->streams[c->fc->nb_streams-1];
2454 for (i = 0; i < 2; i++) {
2458 if (end - avio_tell(pb) <= 12)
2461 len = avio_rb32(pb);
2462 tag = avio_rl32(pb);
2463 avio_skip(pb, 4); // flags
2465 if (len < 12 || len - 12 > end - avio_tell(pb))
2469 if (tag == MKTAG('n', 'a', 'm', 'e'))
2471 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2478 *p = av_malloc(len + 1);
2481 avio_read(pb, *p, len);
2486 if (strcmp(key, "iTunSMPB") == 0) {
2487 int priming, remainder, samples;
2488 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
2489 if(priming>0 && priming<16384)
2490 sc->start_pad = priming;
2492 } else if (strcmp(key, "cdec") == 0) {
2494 av_dict_set(&c->fc->metadata, key, val,
2495 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2500 avio_seek(pb, end, SEEK_SET);
2506 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2508 int64_t end = avio_tell(pb) + atom.size;
2514 len = avio_rb32(pb);
2515 tag = avio_rl32(pb);
2517 if (len > atom.size)
2520 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2521 uint8_t domain[128];
2524 avio_skip(pb, 4); // flags
2527 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2528 avio_skip(pb, len - domain_len);
2529 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
2533 av_log(c->fc, AV_LOG_VERBOSE,
2534 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2538 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2540 while (atom.size > 8) {
2541 uint32_t tag = avio_rl32(pb);
2543 if (tag == MKTAG('h','d','l','r')) {
2544 avio_seek(pb, -8, SEEK_CUR);
2546 return mov_read_default(c, pb, atom);
2552 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2557 int64_t disp_transform[2];
2558 int display_matrix[3][2];
2560 MOVStreamContext *sc;
2564 if (c->fc->nb_streams < 1)
2566 st = c->fc->streams[c->fc->nb_streams-1];
2569 version = avio_r8(pb);
2570 flags = avio_rb24(pb);
2571 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2577 avio_rb32(pb); /* creation time */
2578 avio_rb32(pb); /* modification time */
2580 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2581 avio_rb32(pb); /* reserved */
2583 /* highlevel (considering edits) duration in movie timebase */
2584 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2585 avio_rb32(pb); /* reserved */
2586 avio_rb32(pb); /* reserved */
2588 avio_rb16(pb); /* layer */
2589 avio_rb16(pb); /* alternate group */
2590 avio_rb16(pb); /* volume */
2591 avio_rb16(pb); /* reserved */
2593 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2594 // they're kept in fixed point format through all calculations
2595 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2596 for (i = 0; i < 3; i++) {
2597 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2598 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2599 avio_rb32(pb); // 2.30 fixed point (not used)
2602 width = avio_rb32(pb); // 16.16 fixed point track width
2603 height = avio_rb32(pb); // 16.16 fixed point track height
2604 sc->width = width >> 16;
2605 sc->height = height >> 16;
2607 //Assign clockwise rotate values based on transform matrix so that
2608 //we can compensate for iPhone orientation during capture.
2610 if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2611 av_dict_set(&st->metadata, "rotate", "90", 0);
2614 if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2615 av_dict_set(&st->metadata, "rotate", "180", 0);
2618 if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2619 av_dict_set(&st->metadata, "rotate", "270", 0);
2622 // transform the display width/height according to the matrix
2623 // skip this if the display matrix is the default identity matrix
2624 // or if it is rotating the picture, ex iPhone 3GS
2625 // to keep the same scale, use [width height 1<<16]
2626 if (width && height &&
2627 ((display_matrix[0][0] != 65536 ||
2628 display_matrix[1][1] != 65536) &&
2629 !display_matrix[0][1] &&
2630 !display_matrix[1][0] &&
2631 !display_matrix[2][0] && !display_matrix[2][1])) {
2632 for (i = 0; i < 2; i++)
2634 (int64_t) width * display_matrix[0][i] +
2635 (int64_t) height * display_matrix[1][i] +
2636 ((int64_t) display_matrix[2][i] << 16);
2638 //sample aspect ratio is new width/height divided by old width/height
2639 st->sample_aspect_ratio = av_d2q(
2640 ((double) disp_transform[0] * height) /
2641 ((double) disp_transform[1] * width), INT_MAX);
2646 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2648 MOVFragment *frag = &c->fragment;
2649 MOVTrackExt *trex = NULL;
2650 int flags, track_id, i;
2652 avio_r8(pb); /* version */
2653 flags = avio_rb24(pb);
2655 track_id = avio_rb32(pb);
2657 return AVERROR_INVALIDDATA;
2658 frag->track_id = track_id;
2659 for (i = 0; i < c->trex_count; i++)
2660 if (c->trex_data[i].track_id == frag->track_id) {
2661 trex = &c->trex_data[i];
2665 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2666 return AVERROR_INVALIDDATA;
2669 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2670 avio_rb64(pb) : frag->moof_offset;
2671 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2673 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2674 avio_rb32(pb) : trex->duration;
2675 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2676 avio_rb32(pb) : trex->size;
2677 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2678 avio_rb32(pb) : trex->flags;
2679 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2683 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2685 c->chapter_track = avio_rb32(pb);
2689 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2694 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2695 return AVERROR_INVALIDDATA;
2696 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2697 sizeof(*c->trex_data))) < 0) {
2702 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2704 trex = &c->trex_data[c->trex_count++];
2705 avio_r8(pb); /* version */
2706 avio_rb24(pb); /* flags */
2707 trex->track_id = avio_rb32(pb);
2708 trex->stsd_id = avio_rb32(pb);
2709 trex->duration = avio_rb32(pb);
2710 trex->size = avio_rb32(pb);
2711 trex->flags = avio_rb32(pb);
2715 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2717 MOVFragment *frag = &c->fragment;
2718 AVStream *st = NULL;
2719 MOVStreamContext *sc;
2723 int data_offset = 0;
2724 unsigned entries, first_sample_flags = frag->flags;
2725 int flags, distance, i, found_keyframe = 0, err;
2727 for (i = 0; i < c->fc->nb_streams; i++) {
2728 if (c->fc->streams[i]->id == frag->track_id) {
2729 st = c->fc->streams[i];
2734 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2735 return AVERROR_INVALIDDATA;
2738 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
2740 avio_r8(pb); /* version */
2741 flags = avio_rb24(pb);
2742 entries = avio_rb32(pb);
2743 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2745 /* Always assume the presence of composition time offsets.
2746 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2747 * 1) in the initial movie, there are no samples.
2748 * 2) in the first movie fragment, there is only one sample without composition time offset.
2749 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2750 if (!sc->ctts_count && sc->sample_count)
2752 /* Complement ctts table if moov atom doesn't have ctts atom. */
2753 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2755 return AVERROR(ENOMEM);
2756 sc->ctts_data = ctts_data;
2757 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2758 sc->ctts_data[sc->ctts_count].duration = 0;
2761 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2762 return AVERROR_INVALIDDATA;
2763 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2764 sizeof(*sc->ctts_data))) < 0) {
2768 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2769 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2770 dts = sc->track_end - sc->time_offset;
2771 offset = frag->base_data_offset + data_offset;
2773 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2774 for (i = 0; i < entries && !pb->eof_reached; i++) {
2775 unsigned sample_size = frag->size;
2776 int sample_flags = i ? frag->flags : first_sample_flags;
2777 unsigned sample_duration = frag->duration;
2780 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2781 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2782 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2783 sc->ctts_data[sc->ctts_count].count = 1;
2784 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2786 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
2788 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2790 else if (!found_keyframe)
2791 keyframe = found_keyframe =
2792 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2793 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2796 av_add_index_entry(st, offset, dts, sample_size, distance,
2797 keyframe ? AVINDEX_KEYFRAME : 0);
2798 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2799 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2800 offset, dts, sample_size, distance, keyframe);
2802 dts += sample_duration;
2803 offset += sample_size;
2804 sc->data_size += sample_size;
2805 sc->duration_for_fps += sample_duration;
2806 sc->nb_frames_for_fps ++;
2809 if (pb->eof_reached)
2812 frag->moof_offset = offset;
2813 st->duration = sc->track_end = dts + sc->time_offset;
2817 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2818 /* like the files created with Adobe Premiere 5.0, for samples see */
2819 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2820 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2825 return 0; /* continue */
2826 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2827 avio_skip(pb, atom.size - 4);
2830 atom.type = avio_rl32(pb);
2832 if (atom.type != MKTAG('m','d','a','t')) {
2833 avio_skip(pb, atom.size);
2836 err = mov_read_mdat(c, pb, atom);
2840 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2845 uint8_t *moov_data; /* uncompressed data */
2846 long cmov_len, moov_len;
2849 avio_rb32(pb); /* dcom atom */
2850 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2851 return AVERROR_INVALIDDATA;
2852 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2853 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
2854 return AVERROR_INVALIDDATA;
2856 avio_rb32(pb); /* cmvd atom */
2857 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2858 return AVERROR_INVALIDDATA;
2859 moov_len = avio_rb32(pb); /* uncompressed size */
2860 cmov_len = atom.size - 6 * 4;
2862 cmov_data = av_malloc(cmov_len);
2864 return AVERROR(ENOMEM);
2865 moov_data = av_malloc(moov_len);
2868 return AVERROR(ENOMEM);
2870 avio_read(pb, cmov_data, cmov_len);
2871 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2872 goto free_and_return;
2873 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2874 goto free_and_return;
2875 atom.type = MKTAG('m','o','o','v');
2876 atom.size = moov_len;
2877 ret = mov_read_default(c, &ctx, atom);
2883 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2884 return AVERROR(ENOSYS);
2888 /* edit list atom */
2889 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2891 MOVStreamContext *sc;
2892 int i, edit_count, version, edit_start_index = 0;
2893 int unsupported = 0;
2895 if (c->fc->nb_streams < 1 || c->ignore_editlist)
2897 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2899 version = avio_r8(pb); /* version */
2900 avio_rb24(pb); /* flags */
2901 edit_count = avio_rb32(pb); /* entries */
2903 if ((uint64_t)edit_count*12+8 > atom.size)
2904 return AVERROR_INVALIDDATA;
2906 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2907 for (i=0; i<edit_count; i++){
2912 duration = avio_rb64(pb);
2913 time = avio_rb64(pb);
2915 duration = avio_rb32(pb); /* segment duration */
2916 time = (int32_t)avio_rb32(pb); /* media time */
2918 rate = avio_rb32(pb);
2919 if (i == 0 && time == -1) {
2920 sc->empty_duration = duration;
2921 edit_start_index = 1;
2922 } else if (i == edit_start_index && time >= 0)
2923 sc->start_time = time;
2927 av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
2928 duration, time, rate / 65536.0);
2932 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2933 "a/v desync might occur, patch welcome\n");
2938 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2940 MOVStreamContext *sc;
2942 if (c->fc->nb_streams < 1)
2943 return AVERROR_INVALIDDATA;
2944 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
2945 sc->timecode_track = avio_rb32(pb);
2949 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2953 static const uint8_t uuid_isml_manifest[] = {
2954 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2955 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2958 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
2959 return AVERROR_INVALIDDATA;
2961 ret = avio_read(pb, uuid, sizeof(uuid));
2964 } else if (ret != sizeof(uuid)) {
2965 return AVERROR_INVALIDDATA;
2967 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
2968 uint8_t *buffer, *ptr;
2970 size_t len = atom.size - sizeof(uuid);
2973 return AVERROR_INVALIDDATA;
2975 ret = avio_skip(pb, 4); // zeroes
2978 buffer = av_mallocz(len + 1);
2980 return AVERROR(ENOMEM);
2982 ret = avio_read(pb, buffer, len);
2986 } else if (ret != len) {
2988 return AVERROR_INVALIDDATA;
2992 while ((ptr = av_stristr(ptr, "systemBitrate=\"")) != NULL) {
2993 ptr += sizeof("systemBitrate=\"") - 1;
2994 c->bitrates_count++;
2995 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
2997 c->bitrates_count = 0;
2999 return AVERROR(ENOMEM);
3002 ret = strtol(ptr, &endptr, 10);
3003 if (ret < 0 || errno || *endptr != '"') {
3004 c->bitrates[c->bitrates_count - 1] = 0;
3006 c->bitrates[c->bitrates_count - 1] = ret;
3015 static const MOVParseTableEntry mov_default_parse_table[] = {
3016 { MKTAG('A','C','L','R'), mov_read_avid },
3017 { MKTAG('A','P','R','G'), mov_read_avid },
3018 { MKTAG('A','A','L','P'), mov_read_avid },
3019 { MKTAG('A','R','E','S'), mov_read_ares },
3020 { MKTAG('a','v','s','s'), mov_read_avss },
3021 { MKTAG('c','h','p','l'), mov_read_chpl },
3022 { MKTAG('c','o','6','4'), mov_read_stco },
3023 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3024 { MKTAG('d','i','n','f'), mov_read_default },
3025 { MKTAG('d','r','e','f'), mov_read_dref },
3026 { MKTAG('e','d','t','s'), mov_read_default },
3027 { MKTAG('e','l','s','t'), mov_read_elst },
3028 { MKTAG('e','n','d','a'), mov_read_enda },
3029 { MKTAG('f','i','e','l'), mov_read_fiel },
3030 { MKTAG('f','t','y','p'), mov_read_ftyp },
3031 { MKTAG('g','l','b','l'), mov_read_glbl },
3032 { MKTAG('h','d','l','r'), mov_read_hdlr },
3033 { MKTAG('i','l','s','t'), mov_read_ilst },
3034 { MKTAG('j','p','2','h'), mov_read_jp2h },
3035 { MKTAG('m','d','a','t'), mov_read_mdat },
3036 { MKTAG('m','d','h','d'), mov_read_mdhd },
3037 { MKTAG('m','d','i','a'), mov_read_default },
3038 { MKTAG('m','e','t','a'), mov_read_meta },
3039 { MKTAG('m','i','n','f'), mov_read_default },
3040 { MKTAG('m','o','o','f'), mov_read_moof },
3041 { MKTAG('m','o','o','v'), mov_read_moov },
3042 { MKTAG('m','v','e','x'), mov_read_default },
3043 { MKTAG('m','v','h','d'), mov_read_mvhd },
3044 { MKTAG('S','M','I',' '), mov_read_svq3 },
3045 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
3046 { MKTAG('a','v','c','C'), mov_read_glbl },
3047 { MKTAG('p','a','s','p'), mov_read_pasp },
3048 { MKTAG('s','t','b','l'), mov_read_default },
3049 { MKTAG('s','t','c','o'), mov_read_stco },
3050 { MKTAG('s','t','p','s'), mov_read_stps },
3051 { MKTAG('s','t','r','f'), mov_read_strf },
3052 { MKTAG('s','t','s','c'), mov_read_stsc },
3053 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3054 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3055 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3056 { MKTAG('s','t','t','s'), mov_read_stts },
3057 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3058 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3059 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3060 { MKTAG('t','r','a','k'), mov_read_trak },
3061 { MKTAG('t','r','a','f'), mov_read_default },
3062 { MKTAG('t','r','e','f'), mov_read_default },
3063 { MKTAG('t','m','c','d'), mov_read_tmcd },
3064 { MKTAG('c','h','a','p'), mov_read_chap },
3065 { MKTAG('t','r','e','x'), mov_read_trex },
3066 { MKTAG('t','r','u','n'), mov_read_trun },
3067 { MKTAG('u','d','t','a'), mov_read_default },
3068 { MKTAG('w','a','v','e'), mov_read_wave },
3069 { MKTAG('e','s','d','s'), mov_read_esds },
3070 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3071 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3072 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3073 { MKTAG('w','f','e','x'), mov_read_wfex },
3074 { MKTAG('c','m','o','v'), mov_read_cmov },
3075 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3076 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3077 { MKTAG('s','b','g','p'), mov_read_sbgp },
3078 { MKTAG('h','v','c','C'), mov_read_glbl },
3079 { MKTAG('u','u','i','d'), mov_read_uuid },
3080 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
3081 { MKTAG('-','-','-','-'), mov_read_custom },
3085 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3087 int64_t total_size = 0;
3092 atom.size = INT64_MAX;
3093 while (total_size + 8 <= atom.size && !url_feof(pb)) {
3094 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3097 if (atom.size >= 8) {
3098 a.size = avio_rb32(pb);
3099 a.type = avio_rl32(pb);
3100 if (atom.type != MKTAG('r','o','o','t') &&
3101 atom.type != MKTAG('m','o','o','v'))
3103 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
3105 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
3111 if (a.size == 1) { /* 64 bit extended size */
3112 a.size = avio_rb64(pb) - 8;
3116 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3117 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3119 a.size = atom.size - total_size + 8;
3124 a.size = FFMIN(a.size, atom.size - total_size);
3126 for (i = 0; mov_default_parse_table[i].type; i++)
3127 if (mov_default_parse_table[i].type == a.type) {
3128 parse = mov_default_parse_table[i].parse;
3132 // container is user data
3133 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3134 atom.type == MKTAG('i','l','s','t')))
3135 parse = mov_read_udta_string;
3137 if (!parse) { /* skip leaf atoms data */
3138 avio_skip(pb, a.size);
3140 int64_t start_pos = avio_tell(pb);
3142 int err = parse(c, pb, a);
3145 if (c->found_moov && c->found_mdat &&
3146 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3147 start_pos + a.size == avio_size(pb))) {
3148 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3149 c->next_root_atom = start_pos + a.size;
3152 left = a.size - avio_tell(pb) + start_pos;
3153 if (left > 0) /* skip garbage at atom end */
3154 avio_skip(pb, left);
3155 else if (left < 0) {
3156 av_log(c->fc, AV_LOG_WARNING,
3157 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3158 (char*)&a.type, -left);
3159 avio_seek(pb, left, SEEK_CUR);
3163 total_size += a.size;
3166 if (total_size < atom.size && atom.size < 0x7ffff)
3167 avio_skip(pb, atom.size - total_size);
3172 static int mov_probe(AVProbeData *p)
3177 int moov_offset = -1;
3179 /* check file header */
3182 /* ignore invalid offset */
3183 if ((offset + 8) > (unsigned int)p->buf_size)
3185 tag = AV_RL32(p->buf + offset + 4);
3187 /* check for obvious tags */
3188 case MKTAG('m','o','o','v'):
3189 moov_offset = offset + 4;
3190 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
3191 case MKTAG('m','d','a','t'):
3192 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3193 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3194 case MKTAG('f','t','y','p'):
3195 if (AV_RB32(p->buf+offset) < 8 &&
3196 (AV_RB32(p->buf+offset) != 1 ||
3197 offset + 12 > (unsigned int)p->buf_size ||
3198 AV_RB64(p->buf+offset + 8) == 0)) {
3199 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3201 score = AVPROBE_SCORE_MAX;
3203 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3205 /* those are more common words, so rate then a bit less */
3206 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3207 case MKTAG('w','i','d','e'):
3208 case MKTAG('f','r','e','e'):
3209 case MKTAG('j','u','n','k'):
3210 case MKTAG('p','i','c','t'):
3211 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
3212 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3214 case MKTAG(0x82,0x82,0x7f,0x7d):
3215 case MKTAG('s','k','i','p'):
3216 case MKTAG('u','u','i','d'):
3217 case MKTAG('p','r','f','l'):
3218 /* if we only find those cause probedata is too small at least rate them */
3219 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3220 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3223 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3226 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
3227 /* moov atom in the header - we should make sure that this is not a
3228 * MOV-packed MPEG-PS */
3229 offset = moov_offset;
3231 while(offset < (p->buf_size - 16)){ /* Sufficient space */
3232 /* We found an actual hdlr atom */
3233 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
3234 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
3235 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
3236 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
3237 /* We found a media handler reference atom describing an
3238 * MPEG-PS-in-MOV, return a
3239 * low score to force expanding the probe window until
3240 * mpegps_probe finds what it needs */
3251 // must be done after parsing all trak because there's no order requirement
3252 static void mov_read_chapters(AVFormatContext *s)
3254 MOVContext *mov = s->priv_data;
3255 AVStream *st = NULL;
3256 MOVStreamContext *sc;
3260 for (i = 0; i < s->nb_streams; i++)
3261 if (s->streams[i]->id == mov->chapter_track) {
3266 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3270 st->discard = AVDISCARD_ALL;
3272 cur_pos = avio_tell(sc->pb);
3274 for (i = 0; i < st->nb_index_entries; i++) {
3275 AVIndexEntry *sample = &st->index_entries[i];
3276 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3281 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3282 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3286 // the first two bytes are the length of the title
3287 len = avio_rb16(sc->pb);
3288 if (len > sample->size-2)
3290 title_len = 2*len + 1;
3291 if (!(title = av_mallocz(title_len)))
3294 // The samples could theoretically be in any encoding if there's an encd
3295 // atom following, but in practice are only utf-8 or utf-16, distinguished
3296 // instead by the presence of a BOM
3300 ch = avio_rb16(sc->pb);
3302 avio_get_str16be(sc->pb, len, title, title_len);
3303 else if (ch == 0xfffe)
3304 avio_get_str16le(sc->pb, len, title, title_len);
3307 if (len == 1 || len == 2)
3310 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3314 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3318 avio_seek(sc->pb, cur_pos, SEEK_SET);
3321 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
3322 uint32_t value, int flags)
3325 char buf[AV_TIMECODE_STR_SIZE];
3326 AVRational rate = {st->codec->time_base.den,
3327 st->codec->time_base.num};
3328 int ret = av_timecode_init(&tc, rate, flags, 0, s);
3331 av_dict_set(&st->metadata, "timecode",
3332 av_timecode_make_string(&tc, buf, value), 0);
3336 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
3338 MOVStreamContext *sc = st->priv_data;
3340 int64_t cur_pos = avio_tell(sc->pb);
3343 if (!st->nb_index_entries)
3346 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3347 value = avio_rb32(s->pb);
3349 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3350 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3351 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3353 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3354 * not the case) and thus assume "frame number format" instead of QT one.
3355 * No sample with tmcd track can be found with a QT timecode at the moment,
3356 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3358 parse_timecode_in_framenum_format(s, st, value, flags);
3360 avio_seek(sc->pb, cur_pos, SEEK_SET);
3364 static int mov_read_close(AVFormatContext *s)
3366 MOVContext *mov = s->priv_data;
3369 for (i = 0; i < s->nb_streams; i++) {
3370 AVStream *st = s->streams[i];
3371 MOVStreamContext *sc = st->priv_data;
3373 av_freep(&sc->ctts_data);
3374 for (j = 0; j < sc->drefs_count; j++) {
3375 av_freep(&sc->drefs[j].path);
3376 av_freep(&sc->drefs[j].dir);
3378 av_freep(&sc->drefs);
3380 sc->drefs_count = 0;
3382 if (!sc->pb_is_copied)
3386 av_freep(&sc->chunk_offsets);
3387 av_freep(&sc->stsc_data);
3388 av_freep(&sc->sample_sizes);
3389 av_freep(&sc->keyframes);
3390 av_freep(&sc->stts_data);
3391 av_freep(&sc->stps_data);
3392 av_freep(&sc->rap_group);
3395 if (mov->dv_demux) {
3396 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
3397 av_freep(&mov->dv_fctx->streams[i]->codec);
3398 av_freep(&mov->dv_fctx->streams[i]);
3400 av_freep(&mov->dv_fctx);
3401 av_freep(&mov->dv_demux);
3404 av_freep(&mov->trex_data);
3405 av_freep(&mov->bitrates);
3410 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3414 for (i = 0; i < s->nb_streams; i++) {
3415 AVStream *st = s->streams[i];
3416 MOVStreamContext *sc = st->priv_data;
3418 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3419 sc->timecode_track == tmcd_id)
3425 /* look for a tmcd track not referenced by any video track, and export it globally */
3426 static void export_orphan_timecode(AVFormatContext *s)
3430 for (i = 0; i < s->nb_streams; i++) {
3431 AVStream *st = s->streams[i];
3433 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3434 !tmcd_is_referenced(s, i + 1)) {
3435 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3437 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3444 static int mov_read_header(AVFormatContext *s)
3446 MOVContext *mov = s->priv_data;
3447 AVIOContext *pb = s->pb;
3449 MOVAtom atom = { AV_RL32("root") };
3453 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3455 atom.size = avio_size(pb);
3457 atom.size = INT64_MAX;
3459 /* check MOV header */
3460 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3461 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3465 if (!mov->found_moov) {
3466 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3468 return AVERROR_INVALIDDATA;
3470 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3473 if (mov->chapter_track > 0)
3474 mov_read_chapters(s);
3475 for (i = 0; i < s->nb_streams; i++)
3476 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3477 mov_read_timecode_track(s, s->streams[i]);
3480 /* copy timecode metadata from tmcd tracks to the related video streams */
3481 for (i = 0; i < s->nb_streams; i++) {
3482 AVStream *st = s->streams[i];
3483 MOVStreamContext *sc = st->priv_data;
3484 if (sc->timecode_track > 0) {
3485 AVDictionaryEntry *tcr;
3486 int tmcd_st_id = -1;
3488 for (j = 0; j < s->nb_streams; j++)
3489 if (s->streams[j]->id == sc->timecode_track)
3492 if (tmcd_st_id < 0 || tmcd_st_id == i)
3494 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
3496 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
3499 export_orphan_timecode(s);
3501 for (i = 0; i < s->nb_streams; i++) {
3502 AVStream *st = s->streams[i];
3503 MOVStreamContext *sc = st->priv_data;
3504 fix_timescale(mov, sc);
3505 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
3506 st->skip_samples = sc->start_pad;
3508 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
3509 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3510 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
3511 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3512 if (st->codec->width <= 0 && st->codec->height <= 0) {
3513 st->codec->width = sc->width;
3514 st->codec->height = sc->height;
3516 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3517 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3523 if (mov->trex_data) {
3524 for (i = 0; i < s->nb_streams; i++) {
3525 AVStream *st = s->streams[i];
3526 MOVStreamContext *sc = st->priv_data;
3527 if (st->duration > 0)
3528 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3532 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
3533 if (mov->bitrates[i]) {
3534 s->streams[i]->codec->bit_rate = mov->bitrates[i];
3538 ff_rfps_calculate(s);
3540 for (i = 0; i < s->nb_streams; i++) {
3541 AVStream *st = s->streams[i];
3543 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
3546 err = ff_replaygain_export(st, s->metadata);
3556 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3558 AVIndexEntry *sample = NULL;
3559 int64_t best_dts = INT64_MAX;
3561 for (i = 0; i < s->nb_streams; i++) {
3562 AVStream *avst = s->streams[i];
3563 MOVStreamContext *msc = avst->priv_data;
3564 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3565 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3566 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3567 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3568 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3570 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3571 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3572 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3573 sample = current_sample;
3582 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3584 MOVContext *mov = s->priv_data;
3585 MOVStreamContext *sc;
3586 AVIndexEntry *sample;
3587 AVStream *st = NULL;
3591 sample = mov_find_next_sample(s, &st);
3593 mov->found_mdat = 0;
3594 if (!mov->next_root_atom)
3596 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3597 mov->next_root_atom = 0;
3598 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3601 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3605 /* must be done just before reading, to avoid infinite loop on sample */
3606 sc->current_sample++;
3608 if (mov->next_root_atom) {
3609 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
3610 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
3613 if (st->discard != AVDISCARD_ALL) {
3614 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3615 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3616 sc->ffindex, sample->pos);
3617 return AVERROR_INVALIDDATA;
3619 ret = av_get_packet(sc->pb, pkt, sample->size);
3622 if (sc->has_palette) {
3625 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3627 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3629 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3630 sc->has_palette = 0;
3633 #if CONFIG_DV_DEMUXER
3634 if (mov->dv_demux && sc->dv_audio_container) {
3635 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
3638 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3645 pkt->stream_index = sc->ffindex;
3646 pkt->dts = sample->timestamp;
3647 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3648 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3649 /* update ctts context */
3651 if (sc->ctts_index < sc->ctts_count &&
3652 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3654 sc->ctts_sample = 0;
3657 pkt->dts = AV_NOPTS_VALUE;
3659 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3660 st->index_entries[sc->current_sample].timestamp : st->duration;
3661 pkt->duration = next_dts - pkt->dts;
3662 pkt->pts = pkt->dts;
3664 if (st->discard == AVDISCARD_ALL)
3666 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3667 pkt->pos = sample->pos;
3668 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3669 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3673 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3675 MOVStreamContext *sc = st->priv_data;
3676 int sample, time_sample;
3679 sample = av_index_search_timestamp(st, timestamp, flags);
3680 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3681 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3683 if (sample < 0) /* not sure what to do */
3684 return AVERROR_INVALIDDATA;
3685 sc->current_sample = sample;
3686 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3687 /* adjust ctts index */
3688 if (sc->ctts_data) {
3690 for (i = 0; i < sc->ctts_count; i++) {
3691 int next = time_sample + sc->ctts_data[i].count;
3692 if (next > sc->current_sample) {
3694 sc->ctts_sample = sc->current_sample - time_sample;
3703 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3706 int64_t seek_timestamp, timestamp;
3710 if (stream_index >= s->nb_streams)
3711 return AVERROR_INVALIDDATA;
3713 st = s->streams[stream_index];
3714 sample = mov_seek_stream(s, st, sample_time, flags);
3718 /* adjust seek timestamp to found sample timestamp */
3719 seek_timestamp = st->index_entries[sample].timestamp;
3721 for (i = 0; i < s->nb_streams; i++) {
3722 MOVStreamContext *sc = s->streams[i]->priv_data;
3724 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
3726 if (stream_index == i)
3729 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3730 mov_seek_stream(s, st, timestamp, flags);
3735 static const AVOption options[] = {
3736 {"use_absolute_path",
3737 "allow using absolute path when opening alias, this is a possible security issue",
3738 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
3739 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3740 {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
3741 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3745 static const AVClass mov_class = {
3746 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3747 .item_name = av_default_item_name,
3749 .version = LIBAVUTIL_VERSION_INT,
3752 AVInputFormat ff_mov_demuxer = {
3753 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3754 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3755 .priv_data_size = sizeof(MOVContext),
3756 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
3757 .read_probe = mov_probe,
3758 .read_header = mov_read_header,
3759 .read_packet = mov_read_packet,
3760 .read_close = mov_read_close,
3761 .read_seek = mov_read_seek,
3762 .priv_class = &mov_class,
3763 .flags = AVFMT_NO_BYTE_SEEK,