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 uint8_t codec_name[32];
1212 unsigned int color_depth, len, j;
1213 int color_greyscale;
1216 avio_rb16(pb); /* version */
1217 avio_rb16(pb); /* revision level */
1218 avio_rb32(pb); /* vendor */
1219 avio_rb32(pb); /* temporal quality */
1220 avio_rb32(pb); /* spatial quality */
1222 st->codec->width = avio_rb16(pb); /* width */
1223 st->codec->height = avio_rb16(pb); /* height */
1225 avio_rb32(pb); /* horiz resolution */
1226 avio_rb32(pb); /* vert resolution */
1227 avio_rb32(pb); /* data size, always 0 */
1228 avio_rb16(pb); /* frames per samples */
1230 len = avio_r8(pb); /* codec name, pascal string */
1233 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1235 avio_skip(pb, 31 - len);
1238 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1240 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1241 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1242 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1243 st->codec->width &= ~1;
1244 st->codec->height &= ~1;
1246 /* Flash Media Server uses tag H263 with Sorenson Spark */
1247 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1248 !memcmp(codec_name, "Sorenson H263", 13))
1249 st->codec->codec_id = AV_CODEC_ID_FLV1;
1251 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1252 color_table_id = avio_rb16(pb); /* colortable id */
1253 av_dlog(c->fc, "depth %d, ctab id %d\n",
1254 st->codec->bits_per_coded_sample, color_table_id);
1255 /* figure out the palette situation */
1256 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1257 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1258 /* Do not create a greyscale palette for cinepak */
1259 if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1262 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1263 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1264 /* for palette traversal */
1265 unsigned int color_start, color_count, color_end;
1266 unsigned char a, r, g, b;
1268 if (color_greyscale) {
1269 int color_index, color_dec;
1270 /* compute the greyscale palette */
1271 st->codec->bits_per_coded_sample = color_depth;
1272 color_count = 1 << color_depth;
1274 color_dec = 256 / (color_count - 1);
1275 for (j = 0; j < color_count; j++) {
1276 r = g = b = color_index;
1277 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1278 color_index -= color_dec;
1279 if (color_index < 0)
1282 } else if (color_table_id) {
1283 const uint8_t *color_table;
1284 /* if flag bit 3 is set, use the default palette */
1285 color_count = 1 << color_depth;
1286 if (color_depth == 2)
1287 color_table = ff_qt_default_palette_4;
1288 else if (color_depth == 4)
1289 color_table = ff_qt_default_palette_16;
1291 color_table = ff_qt_default_palette_256;
1293 for (j = 0; j < color_count; j++) {
1294 r = color_table[j * 3 + 0];
1295 g = color_table[j * 3 + 1];
1296 b = color_table[j * 3 + 2];
1297 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1300 /* load the palette from the file */
1301 color_start = avio_rb32(pb);
1302 color_count = avio_rb16(pb);
1303 color_end = avio_rb16(pb);
1304 if ((color_start <= 255) && (color_end <= 255)) {
1305 for (j = color_start; j <= color_end; j++) {
1306 /* each A, R, G, or B component is 16 bits;
1307 * only use the top 8 bits */
1316 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1320 sc->has_palette = 1;
1324 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1325 AVStream *st, MOVStreamContext *sc)
1327 int bits_per_sample, flags;
1328 uint16_t version = avio_rb16(pb);
1329 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1331 avio_rb16(pb); /* revision level */
1332 avio_rb32(pb); /* vendor */
1334 st->codec->channels = avio_rb16(pb); /* channel count */
1335 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1336 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1338 sc->audio_cid = avio_rb16(pb);
1339 avio_rb16(pb); /* packet size = 0 */
1341 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1343 // Read QT version 1 fields. In version 0 these do not exist.
1344 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1346 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1349 sc->samples_per_frame = avio_rb32(pb);
1350 avio_rb32(pb); /* bytes per packet */
1351 sc->bytes_per_frame = avio_rb32(pb);
1352 avio_rb32(pb); /* bytes per sample */
1353 } else if (version == 2) {
1354 avio_rb32(pb); /* sizeof struct only */
1355 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1356 st->codec->channels = avio_rb32(pb);
1357 avio_rb32(pb); /* always 0x7F000000 */
1358 st->codec->bits_per_coded_sample = avio_rb32(pb);
1360 flags = avio_rb32(pb); /* lpcm format specific flag */
1361 sc->bytes_per_frame = avio_rb32(pb);
1362 sc->samples_per_frame = avio_rb32(pb);
1363 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1364 st->codec->codec_id =
1365 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1370 switch (st->codec->codec_id) {
1371 case AV_CODEC_ID_PCM_S8:
1372 case AV_CODEC_ID_PCM_U8:
1373 if (st->codec->bits_per_coded_sample == 16)
1374 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1376 case AV_CODEC_ID_PCM_S16LE:
1377 case AV_CODEC_ID_PCM_S16BE:
1378 if (st->codec->bits_per_coded_sample == 8)
1379 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1380 else if (st->codec->bits_per_coded_sample == 24)
1381 st->codec->codec_id =
1382 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1383 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1385 /* set values for old format before stsd version 1 appeared */
1386 case AV_CODEC_ID_MACE3:
1387 sc->samples_per_frame = 6;
1388 sc->bytes_per_frame = 2 * st->codec->channels;
1390 case AV_CODEC_ID_MACE6:
1391 sc->samples_per_frame = 6;
1392 sc->bytes_per_frame = 1 * st->codec->channels;
1394 case AV_CODEC_ID_ADPCM_IMA_QT:
1395 sc->samples_per_frame = 64;
1396 sc->bytes_per_frame = 34 * st->codec->channels;
1398 case AV_CODEC_ID_GSM:
1399 sc->samples_per_frame = 160;
1400 sc->bytes_per_frame = 33;
1406 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1407 if (bits_per_sample) {
1408 st->codec->bits_per_coded_sample = bits_per_sample;
1409 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1413 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1414 AVStream *st, MOVStreamContext *sc,
1417 // ttxt stsd contains display flags, justification, background
1418 // color, fonts, and default styles, so fake an atom to read it
1419 MOVAtom fake_atom = { .size = size };
1420 // mp4s contains a regular esds atom
1421 if (st->codec->codec_tag != AV_RL32("mp4s"))
1422 mov_read_glbl(c, pb, fake_atom);
1423 st->codec->width = sc->width;
1424 st->codec->height = sc->height;
1427 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1432 y = (ycbcr >> 16) & 0xFF;
1433 cr = (ycbcr >> 8) & 0xFF;
1436 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1437 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1438 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1440 return (r << 16) | (g << 8) | b;
1443 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1445 char buf[256] = {0};
1446 uint8_t *src = st->codec->extradata;
1449 if (st->codec->extradata_size != 64)
1452 if (st->codec->width > 0 && st->codec->height > 0)
1453 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1454 st->codec->width, st->codec->height);
1455 av_strlcat(buf, "palette: ", sizeof(buf));
1457 for (i = 0; i < 16; i++) {
1458 uint32_t yuv = AV_RB32(src + i * 4);
1459 uint32_t rgba = yuv_to_rgba(yuv);
1461 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1464 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1467 av_freep(&st->codec->extradata);
1468 st->codec->extradata_size = 0;
1469 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1470 if (!st->codec->extradata)
1471 return AVERROR(ENOMEM);
1472 st->codec->extradata_size = strlen(buf);
1473 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1478 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1479 AVStream *st, MOVStreamContext *sc,
1482 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1483 if (ff_get_extradata(st->codec, pb, size) < 0)
1484 return AVERROR(ENOMEM);
1486 MOVStreamContext *tmcd_ctx = st->priv_data;
1488 val = AV_RB32(st->codec->extradata + 4);
1489 tmcd_ctx->tmcd_flags = val;
1491 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1492 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
1493 st->codec->time_base.num = 1;
1496 /* other codec type, just skip (rtp, mp4s ...) */
1497 avio_skip(pb, size);
1502 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1503 AVStream *st, MOVStreamContext *sc)
1505 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1506 !st->codec->sample_rate && sc->time_scale > 1)
1507 st->codec->sample_rate = sc->time_scale;
1509 /* special codec parameters handling */
1510 switch (st->codec->codec_id) {
1511 #if CONFIG_DV_DEMUXER
1512 case AV_CODEC_ID_DVAUDIO:
1513 c->dv_fctx = avformat_alloc_context();
1514 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1516 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1517 return AVERROR(ENOMEM);
1519 sc->dv_audio_container = 1;
1520 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1523 /* no ifdef since parameters are always those */
1524 case AV_CODEC_ID_QCELP:
1525 st->codec->channels = 1;
1526 // force sample rate for qcelp when not stored in mov
1527 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1528 st->codec->sample_rate = 8000;
1529 // FIXME: Why is the following needed for some files?
1530 sc->samples_per_frame = 160;
1531 if (!sc->bytes_per_frame)
1532 sc->bytes_per_frame = 35;
1534 case AV_CODEC_ID_AMR_NB:
1535 st->codec->channels = 1;
1536 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1537 st->codec->sample_rate = 8000;
1539 case AV_CODEC_ID_AMR_WB:
1540 st->codec->channels = 1;
1541 st->codec->sample_rate = 16000;
1543 case AV_CODEC_ID_MP2:
1544 case AV_CODEC_ID_MP3:
1545 /* force type after stsd for m1a hdlr */
1546 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1547 st->need_parsing = AVSTREAM_PARSE_FULL;
1549 case AV_CODEC_ID_GSM:
1550 case AV_CODEC_ID_ADPCM_MS:
1551 case AV_CODEC_ID_ADPCM_IMA_WAV:
1552 case AV_CODEC_ID_ILBC:
1553 case AV_CODEC_ID_MACE3:
1554 case AV_CODEC_ID_MACE6:
1555 case AV_CODEC_ID_QDM2:
1556 st->codec->block_align = sc->bytes_per_frame;
1558 case AV_CODEC_ID_ALAC:
1559 if (st->codec->extradata_size == 36) {
1560 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1561 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1564 case AV_CODEC_ID_AC3:
1565 case AV_CODEC_ID_MPEG1VIDEO:
1566 case AV_CODEC_ID_VC1:
1567 st->need_parsing = AVSTREAM_PARSE_FULL;
1575 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1576 int codec_tag, int format,
1579 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1582 (codec_tag != format &&
1583 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1584 : codec_tag != MKTAG('j','p','e','g')))) {
1585 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1586 * export it as a separate AVStream but this needs a few changes
1587 * in the MOV demuxer, patch welcome. */
1589 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1590 avio_skip(pb, size);
1593 if ( codec_tag == AV_RL32("avc1") ||
1594 codec_tag == AV_RL32("hvc1") ||
1595 codec_tag == AV_RL32("hev1")
1597 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
1602 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1605 MOVStreamContext *sc;
1606 int pseudo_stream_id;
1608 if (c->fc->nb_streams < 1)
1610 st = c->fc->streams[c->fc->nb_streams-1];
1613 for (pseudo_stream_id = 0;
1614 pseudo_stream_id < entries && !pb->eof_reached;
1615 pseudo_stream_id++) {
1616 //Parsing Sample description table
1618 int ret, dref_id = 1;
1619 MOVAtom a = { AV_RL32("stsd") };
1620 int64_t start_pos = avio_tell(pb);
1621 int64_t size = avio_rb32(pb); /* size */
1622 uint32_t format = avio_rl32(pb); /* data format */
1625 avio_rb32(pb); /* reserved */
1626 avio_rb16(pb); /* reserved */
1627 dref_id = avio_rb16(pb);
1628 }else if (size <= 7){
1629 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1630 return AVERROR_INVALIDDATA;
1633 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1634 size - (avio_tell(pb) - start_pos)))
1637 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1638 sc->dref_id= dref_id;
1640 id = mov_codec_id(st, format);
1642 av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1643 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1644 (format >> 24) & 0xff, st->codec->codec_type);
1646 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1647 st->codec->codec_id = id;
1648 mov_parse_stsd_video(c, pb, st, sc);
1649 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1650 st->codec->codec_id = id;
1651 mov_parse_stsd_audio(c, pb, st, sc);
1652 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1653 st->codec->codec_id = id;
1654 mov_parse_stsd_subtitle(c, pb, st, sc,
1655 size - (avio_tell(pb) - start_pos));
1657 ret = mov_parse_stsd_data(c, pb, st, sc,
1658 size - (avio_tell(pb) - start_pos));
1662 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1663 a.size = size - (avio_tell(pb) - start_pos);
1665 if ((ret = mov_read_default(c, pb, a)) < 0)
1667 } else if (a.size > 0)
1668 avio_skip(pb, a.size);
1671 if (pb->eof_reached)
1674 return mov_finalize_stsd_codec(c, pb, st, sc);
1677 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1681 avio_r8(pb); /* version */
1682 avio_rb24(pb); /* flags */
1683 entries = avio_rb32(pb);
1685 return ff_mov_read_stsd_entries(c, pb, entries);
1688 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1691 MOVStreamContext *sc;
1692 unsigned int i, entries;
1694 if (c->fc->nb_streams < 1)
1696 st = c->fc->streams[c->fc->nb_streams-1];
1699 avio_r8(pb); /* version */
1700 avio_rb24(pb); /* flags */
1702 entries = avio_rb32(pb);
1704 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1708 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1709 return AVERROR_INVALIDDATA;
1710 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1712 return AVERROR(ENOMEM);
1714 for (i = 0; i < entries && !pb->eof_reached; i++) {
1715 sc->stsc_data[i].first = avio_rb32(pb);
1716 sc->stsc_data[i].count = avio_rb32(pb);
1717 sc->stsc_data[i].id = avio_rb32(pb);
1722 if (pb->eof_reached)
1728 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1731 MOVStreamContext *sc;
1732 unsigned i, entries;
1734 if (c->fc->nb_streams < 1)
1736 st = c->fc->streams[c->fc->nb_streams-1];
1739 avio_rb32(pb); // version + flags
1741 entries = avio_rb32(pb);
1742 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1743 return AVERROR_INVALIDDATA;
1744 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1746 return AVERROR(ENOMEM);
1748 for (i = 0; i < entries && !pb->eof_reached; i++) {
1749 sc->stps_data[i] = avio_rb32(pb);
1750 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1755 if (pb->eof_reached)
1761 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1764 MOVStreamContext *sc;
1765 unsigned int i, entries;
1767 if (c->fc->nb_streams < 1)
1769 st = c->fc->streams[c->fc->nb_streams-1];
1772 avio_r8(pb); /* version */
1773 avio_rb24(pb); /* flags */
1775 entries = avio_rb32(pb);
1777 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1781 sc->keyframe_absent = 1;
1782 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1783 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1786 if (entries >= UINT_MAX / sizeof(int))
1787 return AVERROR_INVALIDDATA;
1788 sc->keyframes = av_malloc(entries * sizeof(int));
1790 return AVERROR(ENOMEM);
1792 for (i = 0; i < entries && !pb->eof_reached; i++) {
1793 sc->keyframes[i] = avio_rb32(pb);
1794 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1797 sc->keyframe_count = i;
1799 if (pb->eof_reached)
1805 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1808 MOVStreamContext *sc;
1809 unsigned int i, entries, sample_size, field_size, num_bytes;
1813 if (c->fc->nb_streams < 1)
1815 st = c->fc->streams[c->fc->nb_streams-1];
1818 avio_r8(pb); /* version */
1819 avio_rb24(pb); /* flags */
1821 if (atom.type == MKTAG('s','t','s','z')) {
1822 sample_size = avio_rb32(pb);
1823 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1824 sc->sample_size = sample_size;
1825 sc->stsz_sample_size = sample_size;
1829 avio_rb24(pb); /* reserved */
1830 field_size = avio_r8(pb);
1832 entries = avio_rb32(pb);
1834 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1836 sc->sample_count = entries;
1840 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1841 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1842 return AVERROR_INVALIDDATA;
1847 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1848 return AVERROR_INVALIDDATA;
1849 sc->sample_sizes = av_malloc(entries * sizeof(int));
1850 if (!sc->sample_sizes)
1851 return AVERROR(ENOMEM);
1853 num_bytes = (entries*field_size+4)>>3;
1855 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1857 av_freep(&sc->sample_sizes);
1858 return AVERROR(ENOMEM);
1861 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1862 av_freep(&sc->sample_sizes);
1864 return AVERROR_INVALIDDATA;
1867 init_get_bits(&gb, buf, 8*num_bytes);
1869 for (i = 0; i < entries && !pb->eof_reached; i++) {
1870 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1871 sc->data_size += sc->sample_sizes[i];
1874 sc->sample_count = i;
1876 if (pb->eof_reached)
1883 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1886 MOVStreamContext *sc;
1887 unsigned int i, entries;
1889 int64_t total_sample_count=0;
1891 if (c->fc->nb_streams < 1)
1893 st = c->fc->streams[c->fc->nb_streams-1];
1896 avio_r8(pb); /* version */
1897 avio_rb24(pb); /* flags */
1898 entries = avio_rb32(pb);
1900 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1901 c->fc->nb_streams-1, entries);
1903 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1906 av_free(sc->stts_data);
1907 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1909 return AVERROR(ENOMEM);
1911 for (i = 0; i < entries && !pb->eof_reached; i++) {
1912 int sample_duration;
1915 sample_count=avio_rb32(pb);
1916 sample_duration = avio_rb32(pb);
1918 /* sample_duration < 0 is invalid based on the spec */
1919 if (sample_duration < 0) {
1920 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta %d in STTS, at %d st:%d\n",
1921 sample_duration, i, c->fc->nb_streams-1);
1922 sample_duration = 1;
1924 if (sample_count < 0) {
1925 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
1926 return AVERROR_INVALIDDATA;
1928 sc->stts_data[i].count= sample_count;
1929 sc->stts_data[i].duration= sample_duration;
1931 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1932 sample_count, sample_duration);
1936 && sample_count == 1
1937 && total_sample_count > 100
1938 && sample_duration/10 > duration / total_sample_count)
1939 sample_duration = duration / total_sample_count;
1940 duration+=(int64_t)sample_duration*sample_count;
1941 total_sample_count+=sample_count;
1946 sc->duration_for_fps += duration;
1947 sc->nb_frames_for_fps += total_sample_count;
1949 if (pb->eof_reached)
1952 st->nb_frames= total_sample_count;
1954 st->duration= duration;
1955 sc->track_end = duration;
1959 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
1962 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1966 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1969 MOVStreamContext *sc;
1970 unsigned int i, entries;
1972 if (c->fc->nb_streams < 1)
1974 st = c->fc->streams[c->fc->nb_streams-1];
1977 avio_r8(pb); /* version */
1978 avio_rb24(pb); /* flags */
1979 entries = avio_rb32(pb);
1981 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1985 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1986 return AVERROR_INVALIDDATA;
1987 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1989 return AVERROR(ENOMEM);
1991 for (i = 0; i < entries && !pb->eof_reached; i++) {
1992 int count =avio_rb32(pb);
1993 int duration =avio_rb32(pb);
1995 sc->ctts_data[i].count = count;
1996 sc->ctts_data[i].duration= duration;
1998 av_dlog(c->fc, "count=%d, duration=%d\n",
2001 if (FFABS(duration) > (1<<28) && i+2<entries) {
2002 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2003 av_freep(&sc->ctts_data);
2009 mov_update_dts_shift(sc, duration);
2014 if (pb->eof_reached)
2017 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
2022 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2025 MOVStreamContext *sc;
2026 unsigned int i, entries;
2028 uint32_t grouping_type;
2030 if (c->fc->nb_streams < 1)
2032 st = c->fc->streams[c->fc->nb_streams-1];
2035 version = avio_r8(pb); /* version */
2036 avio_rb24(pb); /* flags */
2037 grouping_type = avio_rl32(pb);
2038 if (grouping_type != MKTAG( 'r','a','p',' '))
2039 return 0; /* only support 'rap ' grouping */
2041 avio_rb32(pb); /* grouping_type_parameter */
2043 entries = avio_rb32(pb);
2046 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2047 return AVERROR_INVALIDDATA;
2048 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2050 return AVERROR(ENOMEM);
2052 for (i = 0; i < entries && !pb->eof_reached; i++) {
2053 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2054 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2057 sc->rap_group_count = i;
2059 return pb->eof_reached ? AVERROR_EOF : 0;
2062 static void mov_build_index(MOVContext *mov, AVStream *st)
2064 MOVStreamContext *sc = st->priv_data;
2065 int64_t current_offset;
2066 int64_t current_dts = 0;
2067 unsigned int stts_index = 0;
2068 unsigned int stsc_index = 0;
2069 unsigned int stss_index = 0;
2070 unsigned int stps_index = 0;
2072 uint64_t stream_size = 0;
2074 /* adjust first dts according to edit list */
2075 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
2076 if (sc->empty_duration)
2077 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
2078 sc->time_offset = sc->start_time - sc->empty_duration;
2079 current_dts = -sc->time_offset;
2080 if (sc->ctts_count>0 && sc->stts_count>0 &&
2081 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2082 /* more than 16 frames delay, dts are likely wrong
2083 this happens with files created by iMovie */
2085 st->codec->has_b_frames = 1;
2089 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2090 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2091 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2092 unsigned int current_sample = 0;
2093 unsigned int stts_sample = 0;
2094 unsigned int sample_size;
2095 unsigned int distance = 0;
2096 unsigned int rap_group_index = 0;
2097 unsigned int rap_group_sample = 0;
2098 int rap_group_present = sc->rap_group_count && sc->rap_group;
2099 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2101 current_dts -= sc->dts_shift;
2103 if (!sc->sample_count || st->nb_index_entries)
2105 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2107 if (av_reallocp_array(&st->index_entries,
2108 st->nb_index_entries + sc->sample_count,
2109 sizeof(*st->index_entries)) < 0) {
2110 st->nb_index_entries = 0;
2113 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2115 for (i = 0; i < sc->chunk_count; i++) {
2116 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2117 current_offset = sc->chunk_offsets[i];
2118 while (stsc_index + 1 < sc->stsc_count &&
2119 i + 1 == sc->stsc_data[stsc_index + 1].first)
2122 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2123 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2124 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2125 sc->stsz_sample_size = sc->sample_size;
2127 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2128 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2129 sc->stsz_sample_size = sc->sample_size;
2132 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2134 if (current_sample >= sc->sample_count) {
2135 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2139 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2141 if (stss_index + 1 < sc->keyframe_count)
2143 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2145 if (stps_index + 1 < sc->stps_count)
2148 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2149 if (sc->rap_group[rap_group_index].index > 0)
2151 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2152 rap_group_sample = 0;
2156 if (sc->keyframe_absent
2158 && !rap_group_present
2159 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2163 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2164 if (sc->pseudo_stream_id == -1 ||
2165 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2166 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2167 e->pos = current_offset;
2168 e->timestamp = current_dts;
2169 e->size = sample_size;
2170 e->min_distance = distance;
2171 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2172 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2173 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2174 current_offset, current_dts, sample_size, distance, keyframe);
2175 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2176 ff_rfps_add_frame(mov->fc, st, current_dts);
2179 current_offset += sample_size;
2180 stream_size += sample_size;
2181 current_dts += sc->stts_data[stts_index].duration;
2185 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2191 if (st->duration > 0)
2192 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2194 unsigned chunk_samples, total = 0;
2196 // compute total chunk count
2197 for (i = 0; i < sc->stsc_count; i++) {
2198 unsigned count, chunk_count;
2200 chunk_samples = sc->stsc_data[i].count;
2201 if (i != sc->stsc_count - 1 &&
2202 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2203 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2207 if (sc->samples_per_frame >= 160) { // gsm
2208 count = chunk_samples / sc->samples_per_frame;
2209 } else if (sc->samples_per_frame > 1) {
2210 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2211 count = (chunk_samples+samples-1) / samples;
2213 count = (chunk_samples+1023) / 1024;
2216 if (i < sc->stsc_count - 1)
2217 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2219 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2220 total += chunk_count * count;
2223 av_dlog(mov->fc, "chunk count %d\n", total);
2224 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2226 if (av_reallocp_array(&st->index_entries,
2227 st->nb_index_entries + total,
2228 sizeof(*st->index_entries)) < 0) {
2229 st->nb_index_entries = 0;
2232 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2235 for (i = 0; i < sc->chunk_count; i++) {
2236 current_offset = sc->chunk_offsets[i];
2237 if (stsc_index + 1 < sc->stsc_count &&
2238 i + 1 == sc->stsc_data[stsc_index + 1].first)
2240 chunk_samples = sc->stsc_data[stsc_index].count;
2242 while (chunk_samples > 0) {
2244 unsigned size, samples;
2246 if (sc->samples_per_frame >= 160) { // gsm
2247 samples = sc->samples_per_frame;
2248 size = sc->bytes_per_frame;
2250 if (sc->samples_per_frame > 1) {
2251 samples = FFMIN((1024 / sc->samples_per_frame)*
2252 sc->samples_per_frame, chunk_samples);
2253 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2255 samples = FFMIN(1024, chunk_samples);
2256 size = samples * sc->sample_size;
2260 if (st->nb_index_entries >= total) {
2261 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2264 e = &st->index_entries[st->nb_index_entries++];
2265 e->pos = current_offset;
2266 e->timestamp = current_dts;
2268 e->min_distance = 0;
2269 e->flags = AVINDEX_KEYFRAME;
2270 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2271 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2274 current_offset += size;
2275 current_dts += samples;
2276 chunk_samples -= samples;
2282 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2283 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2285 /* try relative path, we do not try the absolute because it can leak information about our
2286 system to an attacker */
2287 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2288 char filename[1024];
2289 const char *src_path;
2292 /* find a source dir */
2293 src_path = strrchr(src, '/');
2299 /* find a next level down to target */
2300 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2301 if (ref->path[l] == '/') {
2302 if (i == ref->nlvl_to - 1)
2308 /* compose filename if next level down to target was found */
2309 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2310 memcpy(filename, src, src_path - src);
2311 filename[src_path - src] = 0;
2313 for (i = 1; i < ref->nlvl_from; i++)
2314 av_strlcat(filename, "../", 1024);
2316 av_strlcat(filename, ref->path + l + 1, 1024);
2318 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2321 } else if (use_absolute_path) {
2322 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2323 "this is a possible security issue\n");
2324 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2328 return AVERROR(ENOENT);
2331 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2333 if (sc->time_scale <= 0) {
2334 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2335 sc->time_scale = c->time_scale;
2336 if (sc->time_scale <= 0)
2341 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2344 MOVStreamContext *sc;
2347 st = avformat_new_stream(c->fc, NULL);
2348 if (!st) return AVERROR(ENOMEM);
2349 st->id = c->fc->nb_streams;
2350 sc = av_mallocz(sizeof(MOVStreamContext));
2351 if (!sc) return AVERROR(ENOMEM);
2354 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2355 sc->ffindex = st->index;
2357 if ((ret = mov_read_default(c, pb, atom)) < 0)
2361 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2362 (!sc->sample_size && !sc->sample_count))) {
2363 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2368 fix_timescale(c, sc);
2370 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2372 mov_build_index(c, st);
2374 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2375 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2376 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2377 c->use_absolute_path, c->fc) < 0)
2378 av_log(c->fc, AV_LOG_ERROR,
2379 "stream %d, error opening alias: path='%s', dir='%s', "
2380 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2381 st->index, dref->path, dref->dir, dref->filename,
2382 dref->volume, dref->nlvl_from, dref->nlvl_to);
2385 sc->pb_is_copied = 1;
2388 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2389 if (!st->sample_aspect_ratio.num &&
2390 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2391 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2392 ((double)st->codec->width * sc->height), INT_MAX);
2395 #if FF_API_R_FRAME_RATE
2396 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2397 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2398 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2402 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2403 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2404 TAG_IS_AVCI(st->codec->codec_tag)) {
2405 ret = ff_generate_avci_extradata(st);
2410 switch (st->codec->codec_id) {
2411 #if CONFIG_H261_DECODER
2412 case AV_CODEC_ID_H261:
2414 #if CONFIG_H263_DECODER
2415 case AV_CODEC_ID_H263:
2417 #if CONFIG_MPEG4_DECODER
2418 case AV_CODEC_ID_MPEG4:
2420 st->codec->width = 0; /* let decoder init width/height */
2421 st->codec->height= 0;
2425 /* Do not need those anymore. */
2426 av_freep(&sc->chunk_offsets);
2427 av_freep(&sc->stsc_data);
2428 av_freep(&sc->sample_sizes);
2429 av_freep(&sc->keyframes);
2430 av_freep(&sc->stts_data);
2431 av_freep(&sc->stps_data);
2432 av_freep(&sc->rap_group);
2437 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2440 c->itunes_metadata = 1;
2441 ret = mov_read_default(c, pb, atom);
2442 c->itunes_metadata = 0;
2446 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
2448 int64_t end = avio_tell(pb) + size;
2449 uint8_t *key = NULL, *val = NULL;
2452 MOVStreamContext *sc;
2454 if (c->fc->nb_streams < 1)
2456 st = c->fc->streams[c->fc->nb_streams-1];
2459 for (i = 0; i < 2; i++) {
2463 if (end - avio_tell(pb) <= 12)
2466 len = avio_rb32(pb);
2467 tag = avio_rl32(pb);
2468 avio_skip(pb, 4); // flags
2470 if (len < 12 || len - 12 > end - avio_tell(pb))
2474 if (tag == MKTAG('n', 'a', 'm', 'e'))
2476 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2483 *p = av_malloc(len + 1);
2486 avio_read(pb, *p, len);
2491 if (strcmp(key, "iTunSMPB") == 0) {
2492 int priming, remainder, samples;
2493 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
2494 if(priming>0 && priming<16384)
2495 sc->start_pad = priming;
2497 } else if (strcmp(key, "cdec") == 0) {
2499 av_dict_set(&c->fc->metadata, key, val,
2500 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2505 avio_seek(pb, end, SEEK_SET);
2511 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2513 int64_t end = avio_tell(pb) + atom.size;
2519 len = avio_rb32(pb);
2520 tag = avio_rl32(pb);
2522 if (len > atom.size)
2525 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2526 uint8_t domain[128];
2529 avio_skip(pb, 4); // flags
2532 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2533 avio_skip(pb, len - domain_len);
2534 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
2538 av_log(c->fc, AV_LOG_VERBOSE,
2539 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2543 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2545 while (atom.size > 8) {
2546 uint32_t tag = avio_rl32(pb);
2548 if (tag == MKTAG('h','d','l','r')) {
2549 avio_seek(pb, -8, SEEK_CUR);
2551 return mov_read_default(c, pb, atom);
2557 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2562 int64_t disp_transform[2];
2563 int display_matrix[3][2];
2565 MOVStreamContext *sc;
2569 if (c->fc->nb_streams < 1)
2571 st = c->fc->streams[c->fc->nb_streams-1];
2574 version = avio_r8(pb);
2575 flags = avio_rb24(pb);
2576 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2582 avio_rb32(pb); /* creation time */
2583 avio_rb32(pb); /* modification time */
2585 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2586 avio_rb32(pb); /* reserved */
2588 /* highlevel (considering edits) duration in movie timebase */
2589 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2590 avio_rb32(pb); /* reserved */
2591 avio_rb32(pb); /* reserved */
2593 avio_rb16(pb); /* layer */
2594 avio_rb16(pb); /* alternate group */
2595 avio_rb16(pb); /* volume */
2596 avio_rb16(pb); /* reserved */
2598 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2599 // they're kept in fixed point format through all calculations
2600 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2601 for (i = 0; i < 3; i++) {
2602 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2603 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2604 avio_rb32(pb); // 2.30 fixed point (not used)
2607 width = avio_rb32(pb); // 16.16 fixed point track width
2608 height = avio_rb32(pb); // 16.16 fixed point track height
2609 sc->width = width >> 16;
2610 sc->height = height >> 16;
2612 //Assign clockwise rotate values based on transform matrix so that
2613 //we can compensate for iPhone orientation during capture.
2615 if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2616 av_dict_set(&st->metadata, "rotate", "90", 0);
2619 if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2620 av_dict_set(&st->metadata, "rotate", "180", 0);
2623 if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2624 av_dict_set(&st->metadata, "rotate", "270", 0);
2627 // transform the display width/height according to the matrix
2628 // skip this if the display matrix is the default identity matrix
2629 // or if it is rotating the picture, ex iPhone 3GS
2630 // to keep the same scale, use [width height 1<<16]
2631 if (width && height &&
2632 ((display_matrix[0][0] != 65536 ||
2633 display_matrix[1][1] != 65536) &&
2634 !display_matrix[0][1] &&
2635 !display_matrix[1][0] &&
2636 !display_matrix[2][0] && !display_matrix[2][1])) {
2637 for (i = 0; i < 2; i++)
2639 (int64_t) width * display_matrix[0][i] +
2640 (int64_t) height * display_matrix[1][i] +
2641 ((int64_t) display_matrix[2][i] << 16);
2643 //sample aspect ratio is new width/height divided by old width/height
2644 st->sample_aspect_ratio = av_d2q(
2645 ((double) disp_transform[0] * height) /
2646 ((double) disp_transform[1] * width), INT_MAX);
2651 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2653 MOVFragment *frag = &c->fragment;
2654 MOVTrackExt *trex = NULL;
2655 int flags, track_id, i;
2657 avio_r8(pb); /* version */
2658 flags = avio_rb24(pb);
2660 track_id = avio_rb32(pb);
2662 return AVERROR_INVALIDDATA;
2663 frag->track_id = track_id;
2664 for (i = 0; i < c->trex_count; i++)
2665 if (c->trex_data[i].track_id == frag->track_id) {
2666 trex = &c->trex_data[i];
2670 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2671 return AVERROR_INVALIDDATA;
2674 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2675 avio_rb64(pb) : frag->moof_offset;
2676 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2678 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2679 avio_rb32(pb) : trex->duration;
2680 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2681 avio_rb32(pb) : trex->size;
2682 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2683 avio_rb32(pb) : trex->flags;
2684 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2688 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2690 c->chapter_track = avio_rb32(pb);
2694 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2699 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2700 return AVERROR_INVALIDDATA;
2701 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2702 sizeof(*c->trex_data))) < 0) {
2707 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2709 trex = &c->trex_data[c->trex_count++];
2710 avio_r8(pb); /* version */
2711 avio_rb24(pb); /* flags */
2712 trex->track_id = avio_rb32(pb);
2713 trex->stsd_id = avio_rb32(pb);
2714 trex->duration = avio_rb32(pb);
2715 trex->size = avio_rb32(pb);
2716 trex->flags = avio_rb32(pb);
2720 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2722 MOVFragment *frag = &c->fragment;
2723 AVStream *st = NULL;
2724 MOVStreamContext *sc;
2728 int data_offset = 0;
2729 unsigned entries, first_sample_flags = frag->flags;
2730 int flags, distance, i, found_keyframe = 0, err;
2732 for (i = 0; i < c->fc->nb_streams; i++) {
2733 if (c->fc->streams[i]->id == frag->track_id) {
2734 st = c->fc->streams[i];
2739 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2740 return AVERROR_INVALIDDATA;
2743 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
2745 avio_r8(pb); /* version */
2746 flags = avio_rb24(pb);
2747 entries = avio_rb32(pb);
2748 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2750 /* Always assume the presence of composition time offsets.
2751 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2752 * 1) in the initial movie, there are no samples.
2753 * 2) in the first movie fragment, there is only one sample without composition time offset.
2754 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2755 if (!sc->ctts_count && sc->sample_count)
2757 /* Complement ctts table if moov atom doesn't have ctts atom. */
2758 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2760 return AVERROR(ENOMEM);
2761 sc->ctts_data = ctts_data;
2762 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2763 sc->ctts_data[sc->ctts_count].duration = 0;
2766 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2767 return AVERROR_INVALIDDATA;
2768 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2769 sizeof(*sc->ctts_data))) < 0) {
2773 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2774 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2775 dts = sc->track_end - sc->time_offset;
2776 offset = frag->base_data_offset + data_offset;
2778 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2779 for (i = 0; i < entries && !pb->eof_reached; i++) {
2780 unsigned sample_size = frag->size;
2781 int sample_flags = i ? frag->flags : first_sample_flags;
2782 unsigned sample_duration = frag->duration;
2785 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2786 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2787 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2788 sc->ctts_data[sc->ctts_count].count = 1;
2789 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2791 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
2793 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2795 else if (!found_keyframe)
2796 keyframe = found_keyframe =
2797 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2798 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2801 av_add_index_entry(st, offset, dts, sample_size, distance,
2802 keyframe ? AVINDEX_KEYFRAME : 0);
2803 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2804 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2805 offset, dts, sample_size, distance, keyframe);
2807 dts += sample_duration;
2808 offset += sample_size;
2809 sc->data_size += sample_size;
2810 sc->duration_for_fps += sample_duration;
2811 sc->nb_frames_for_fps ++;
2814 if (pb->eof_reached)
2817 frag->moof_offset = offset;
2818 st->duration = sc->track_end = dts + sc->time_offset;
2822 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2823 /* like the files created with Adobe Premiere 5.0, for samples see */
2824 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2825 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2830 return 0; /* continue */
2831 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2832 avio_skip(pb, atom.size - 4);
2835 atom.type = avio_rl32(pb);
2837 if (atom.type != MKTAG('m','d','a','t')) {
2838 avio_skip(pb, atom.size);
2841 err = mov_read_mdat(c, pb, atom);
2845 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2850 uint8_t *moov_data; /* uncompressed data */
2851 long cmov_len, moov_len;
2854 avio_rb32(pb); /* dcom atom */
2855 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2856 return AVERROR_INVALIDDATA;
2857 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2858 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
2859 return AVERROR_INVALIDDATA;
2861 avio_rb32(pb); /* cmvd atom */
2862 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2863 return AVERROR_INVALIDDATA;
2864 moov_len = avio_rb32(pb); /* uncompressed size */
2865 cmov_len = atom.size - 6 * 4;
2867 cmov_data = av_malloc(cmov_len);
2869 return AVERROR(ENOMEM);
2870 moov_data = av_malloc(moov_len);
2873 return AVERROR(ENOMEM);
2875 avio_read(pb, cmov_data, cmov_len);
2876 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2877 goto free_and_return;
2878 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2879 goto free_and_return;
2880 atom.type = MKTAG('m','o','o','v');
2881 atom.size = moov_len;
2882 ret = mov_read_default(c, &ctx, atom);
2888 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2889 return AVERROR(ENOSYS);
2893 /* edit list atom */
2894 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2896 MOVStreamContext *sc;
2897 int i, edit_count, version, edit_start_index = 0;
2898 int unsupported = 0;
2900 if (c->fc->nb_streams < 1 || c->ignore_editlist)
2902 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2904 version = avio_r8(pb); /* version */
2905 avio_rb24(pb); /* flags */
2906 edit_count = avio_rb32(pb); /* entries */
2908 if ((uint64_t)edit_count*12+8 > atom.size)
2909 return AVERROR_INVALIDDATA;
2911 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2912 for (i=0; i<edit_count; i++){
2917 duration = avio_rb64(pb);
2918 time = avio_rb64(pb);
2920 duration = avio_rb32(pb); /* segment duration */
2921 time = (int32_t)avio_rb32(pb); /* media time */
2923 rate = avio_rb32(pb);
2924 if (i == 0 && time == -1) {
2925 sc->empty_duration = duration;
2926 edit_start_index = 1;
2927 } else if (i == edit_start_index && time >= 0)
2928 sc->start_time = time;
2932 av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
2933 duration, time, rate / 65536.0);
2937 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2938 "a/v desync might occur, patch welcome\n");
2943 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2945 MOVStreamContext *sc;
2947 if (c->fc->nb_streams < 1)
2948 return AVERROR_INVALIDDATA;
2949 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
2950 sc->timecode_track = avio_rb32(pb);
2954 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2958 static const uint8_t uuid_isml_manifest[] = {
2959 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2960 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2963 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
2964 return AVERROR_INVALIDDATA;
2966 ret = avio_read(pb, uuid, sizeof(uuid));
2969 } else if (ret != sizeof(uuid)) {
2970 return AVERROR_INVALIDDATA;
2972 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
2973 uint8_t *buffer, *ptr;
2975 size_t len = atom.size - sizeof(uuid);
2978 return AVERROR_INVALIDDATA;
2980 ret = avio_skip(pb, 4); // zeroes
2983 buffer = av_mallocz(len + 1);
2985 return AVERROR(ENOMEM);
2987 ret = avio_read(pb, buffer, len);
2991 } else if (ret != len) {
2993 return AVERROR_INVALIDDATA;
2997 while ((ptr = av_stristr(ptr, "systemBitrate=\"")) != NULL) {
2998 ptr += sizeof("systemBitrate=\"") - 1;
2999 c->bitrates_count++;
3000 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3002 c->bitrates_count = 0;
3004 return AVERROR(ENOMEM);
3007 ret = strtol(ptr, &endptr, 10);
3008 if (ret < 0 || errno || *endptr != '"') {
3009 c->bitrates[c->bitrates_count - 1] = 0;
3011 c->bitrates[c->bitrates_count - 1] = ret;
3020 static const MOVParseTableEntry mov_default_parse_table[] = {
3021 { MKTAG('A','C','L','R'), mov_read_avid },
3022 { MKTAG('A','P','R','G'), mov_read_avid },
3023 { MKTAG('A','A','L','P'), mov_read_avid },
3024 { MKTAG('A','R','E','S'), mov_read_ares },
3025 { MKTAG('a','v','s','s'), mov_read_avss },
3026 { MKTAG('c','h','p','l'), mov_read_chpl },
3027 { MKTAG('c','o','6','4'), mov_read_stco },
3028 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3029 { MKTAG('d','i','n','f'), mov_read_default },
3030 { MKTAG('d','r','e','f'), mov_read_dref },
3031 { MKTAG('e','d','t','s'), mov_read_default },
3032 { MKTAG('e','l','s','t'), mov_read_elst },
3033 { MKTAG('e','n','d','a'), mov_read_enda },
3034 { MKTAG('f','i','e','l'), mov_read_fiel },
3035 { MKTAG('f','t','y','p'), mov_read_ftyp },
3036 { MKTAG('g','l','b','l'), mov_read_glbl },
3037 { MKTAG('h','d','l','r'), mov_read_hdlr },
3038 { MKTAG('i','l','s','t'), mov_read_ilst },
3039 { MKTAG('j','p','2','h'), mov_read_jp2h },
3040 { MKTAG('m','d','a','t'), mov_read_mdat },
3041 { MKTAG('m','d','h','d'), mov_read_mdhd },
3042 { MKTAG('m','d','i','a'), mov_read_default },
3043 { MKTAG('m','e','t','a'), mov_read_meta },
3044 { MKTAG('m','i','n','f'), mov_read_default },
3045 { MKTAG('m','o','o','f'), mov_read_moof },
3046 { MKTAG('m','o','o','v'), mov_read_moov },
3047 { MKTAG('m','v','e','x'), mov_read_default },
3048 { MKTAG('m','v','h','d'), mov_read_mvhd },
3049 { MKTAG('S','M','I',' '), mov_read_svq3 },
3050 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
3051 { MKTAG('a','v','c','C'), mov_read_glbl },
3052 { MKTAG('p','a','s','p'), mov_read_pasp },
3053 { MKTAG('s','t','b','l'), mov_read_default },
3054 { MKTAG('s','t','c','o'), mov_read_stco },
3055 { MKTAG('s','t','p','s'), mov_read_stps },
3056 { MKTAG('s','t','r','f'), mov_read_strf },
3057 { MKTAG('s','t','s','c'), mov_read_stsc },
3058 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3059 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3060 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3061 { MKTAG('s','t','t','s'), mov_read_stts },
3062 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3063 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3064 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3065 { MKTAG('t','r','a','k'), mov_read_trak },
3066 { MKTAG('t','r','a','f'), mov_read_default },
3067 { MKTAG('t','r','e','f'), mov_read_default },
3068 { MKTAG('t','m','c','d'), mov_read_tmcd },
3069 { MKTAG('c','h','a','p'), mov_read_chap },
3070 { MKTAG('t','r','e','x'), mov_read_trex },
3071 { MKTAG('t','r','u','n'), mov_read_trun },
3072 { MKTAG('u','d','t','a'), mov_read_default },
3073 { MKTAG('w','a','v','e'), mov_read_wave },
3074 { MKTAG('e','s','d','s'), mov_read_esds },
3075 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3076 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3077 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3078 { MKTAG('w','f','e','x'), mov_read_wfex },
3079 { MKTAG('c','m','o','v'), mov_read_cmov },
3080 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3081 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3082 { MKTAG('s','b','g','p'), mov_read_sbgp },
3083 { MKTAG('h','v','c','C'), mov_read_glbl },
3084 { MKTAG('u','u','i','d'), mov_read_uuid },
3085 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
3086 { MKTAG('-','-','-','-'), mov_read_custom },
3090 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3092 int64_t total_size = 0;
3097 atom.size = INT64_MAX;
3098 while (total_size + 8 <= atom.size && !url_feof(pb)) {
3099 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3102 if (atom.size >= 8) {
3103 a.size = avio_rb32(pb);
3104 a.type = avio_rl32(pb);
3105 if (atom.type != MKTAG('r','o','o','t') &&
3106 atom.type != MKTAG('m','o','o','v'))
3108 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
3110 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
3116 if (a.size == 1) { /* 64 bit extended size */
3117 a.size = avio_rb64(pb) - 8;
3121 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3122 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3124 a.size = atom.size - total_size + 8;
3129 a.size = FFMIN(a.size, atom.size - total_size);
3131 for (i = 0; mov_default_parse_table[i].type; i++)
3132 if (mov_default_parse_table[i].type == a.type) {
3133 parse = mov_default_parse_table[i].parse;
3137 // container is user data
3138 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3139 atom.type == MKTAG('i','l','s','t')))
3140 parse = mov_read_udta_string;
3142 if (!parse) { /* skip leaf atoms data */
3143 avio_skip(pb, a.size);
3145 int64_t start_pos = avio_tell(pb);
3147 int err = parse(c, pb, a);
3150 if (c->found_moov && c->found_mdat &&
3151 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3152 start_pos + a.size == avio_size(pb))) {
3153 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3154 c->next_root_atom = start_pos + a.size;
3157 left = a.size - avio_tell(pb) + start_pos;
3158 if (left > 0) /* skip garbage at atom end */
3159 avio_skip(pb, left);
3160 else if (left < 0) {
3161 av_log(c->fc, AV_LOG_WARNING,
3162 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3163 (char*)&a.type, -left);
3164 avio_seek(pb, left, SEEK_CUR);
3168 total_size += a.size;
3171 if (total_size < atom.size && atom.size < 0x7ffff)
3172 avio_skip(pb, atom.size - total_size);
3177 static int mov_probe(AVProbeData *p)
3182 int moov_offset = -1;
3184 /* check file header */
3187 /* ignore invalid offset */
3188 if ((offset + 8) > (unsigned int)p->buf_size)
3190 tag = AV_RL32(p->buf + offset + 4);
3192 /* check for obvious tags */
3193 case MKTAG('m','o','o','v'):
3194 moov_offset = offset + 4;
3195 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
3196 case MKTAG('m','d','a','t'):
3197 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3198 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3199 case MKTAG('f','t','y','p'):
3200 if (AV_RB32(p->buf+offset) < 8 &&
3201 (AV_RB32(p->buf+offset) != 1 ||
3202 offset + 12 > (unsigned int)p->buf_size ||
3203 AV_RB64(p->buf+offset + 8) == 0)) {
3204 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3206 score = AVPROBE_SCORE_MAX;
3208 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3210 /* those are more common words, so rate then a bit less */
3211 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3212 case MKTAG('w','i','d','e'):
3213 case MKTAG('f','r','e','e'):
3214 case MKTAG('j','u','n','k'):
3215 case MKTAG('p','i','c','t'):
3216 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
3217 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3219 case MKTAG(0x82,0x82,0x7f,0x7d):
3220 case MKTAG('s','k','i','p'):
3221 case MKTAG('u','u','i','d'):
3222 case MKTAG('p','r','f','l'):
3223 /* if we only find those cause probedata is too small at least rate them */
3224 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3225 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3228 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3231 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
3232 /* moov atom in the header - we should make sure that this is not a
3233 * MOV-packed MPEG-PS */
3234 offset = moov_offset;
3236 while(offset < (p->buf_size - 16)){ /* Sufficient space */
3237 /* We found an actual hdlr atom */
3238 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
3239 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
3240 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
3241 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
3242 /* We found a media handler reference atom describing an
3243 * MPEG-PS-in-MOV, return a
3244 * low score to force expanding the probe window until
3245 * mpegps_probe finds what it needs */
3256 // must be done after parsing all trak because there's no order requirement
3257 static void mov_read_chapters(AVFormatContext *s)
3259 MOVContext *mov = s->priv_data;
3260 AVStream *st = NULL;
3261 MOVStreamContext *sc;
3265 for (i = 0; i < s->nb_streams; i++)
3266 if (s->streams[i]->id == mov->chapter_track) {
3271 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3275 st->discard = AVDISCARD_ALL;
3277 cur_pos = avio_tell(sc->pb);
3279 for (i = 0; i < st->nb_index_entries; i++) {
3280 AVIndexEntry *sample = &st->index_entries[i];
3281 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3286 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3287 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3291 // the first two bytes are the length of the title
3292 len = avio_rb16(sc->pb);
3293 if (len > sample->size-2)
3295 title_len = 2*len + 1;
3296 if (!(title = av_mallocz(title_len)))
3299 // The samples could theoretically be in any encoding if there's an encd
3300 // atom following, but in practice are only utf-8 or utf-16, distinguished
3301 // instead by the presence of a BOM
3305 ch = avio_rb16(sc->pb);
3307 avio_get_str16be(sc->pb, len, title, title_len);
3308 else if (ch == 0xfffe)
3309 avio_get_str16le(sc->pb, len, title, title_len);
3312 if (len == 1 || len == 2)
3315 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3319 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3323 avio_seek(sc->pb, cur_pos, SEEK_SET);
3326 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
3327 uint32_t value, int flags)
3330 char buf[AV_TIMECODE_STR_SIZE];
3331 AVRational rate = {st->codec->time_base.den,
3332 st->codec->time_base.num};
3333 int ret = av_timecode_init(&tc, rate, flags, 0, s);
3336 av_dict_set(&st->metadata, "timecode",
3337 av_timecode_make_string(&tc, buf, value), 0);
3341 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
3343 MOVStreamContext *sc = st->priv_data;
3345 int64_t cur_pos = avio_tell(sc->pb);
3348 if (!st->nb_index_entries)
3351 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3352 value = avio_rb32(s->pb);
3354 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3355 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3356 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3358 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3359 * not the case) and thus assume "frame number format" instead of QT one.
3360 * No sample with tmcd track can be found with a QT timecode at the moment,
3361 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3363 parse_timecode_in_framenum_format(s, st, value, flags);
3365 avio_seek(sc->pb, cur_pos, SEEK_SET);
3369 static int mov_read_close(AVFormatContext *s)
3371 MOVContext *mov = s->priv_data;
3374 for (i = 0; i < s->nb_streams; i++) {
3375 AVStream *st = s->streams[i];
3376 MOVStreamContext *sc = st->priv_data;
3378 av_freep(&sc->ctts_data);
3379 for (j = 0; j < sc->drefs_count; j++) {
3380 av_freep(&sc->drefs[j].path);
3381 av_freep(&sc->drefs[j].dir);
3383 av_freep(&sc->drefs);
3385 sc->drefs_count = 0;
3387 if (!sc->pb_is_copied)
3391 av_freep(&sc->chunk_offsets);
3392 av_freep(&sc->stsc_data);
3393 av_freep(&sc->sample_sizes);
3394 av_freep(&sc->keyframes);
3395 av_freep(&sc->stts_data);
3396 av_freep(&sc->stps_data);
3397 av_freep(&sc->rap_group);
3400 if (mov->dv_demux) {
3401 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
3402 av_freep(&mov->dv_fctx->streams[i]->codec);
3403 av_freep(&mov->dv_fctx->streams[i]);
3405 av_freep(&mov->dv_fctx);
3406 av_freep(&mov->dv_demux);
3409 av_freep(&mov->trex_data);
3410 av_freep(&mov->bitrates);
3415 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3419 for (i = 0; i < s->nb_streams; i++) {
3420 AVStream *st = s->streams[i];
3421 MOVStreamContext *sc = st->priv_data;
3423 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3424 sc->timecode_track == tmcd_id)
3430 /* look for a tmcd track not referenced by any video track, and export it globally */
3431 static void export_orphan_timecode(AVFormatContext *s)
3435 for (i = 0; i < s->nb_streams; i++) {
3436 AVStream *st = s->streams[i];
3438 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3439 !tmcd_is_referenced(s, i + 1)) {
3440 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3442 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3449 static int mov_read_header(AVFormatContext *s)
3451 MOVContext *mov = s->priv_data;
3452 AVIOContext *pb = s->pb;
3454 MOVAtom atom = { AV_RL32("root") };
3458 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3460 atom.size = avio_size(pb);
3462 atom.size = INT64_MAX;
3464 /* check MOV header */
3465 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3466 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3470 if (!mov->found_moov) {
3471 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3473 return AVERROR_INVALIDDATA;
3475 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3478 if (mov->chapter_track > 0)
3479 mov_read_chapters(s);
3480 for (i = 0; i < s->nb_streams; i++)
3481 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3482 mov_read_timecode_track(s, s->streams[i]);
3485 /* copy timecode metadata from tmcd tracks to the related video streams */
3486 for (i = 0; i < s->nb_streams; i++) {
3487 AVStream *st = s->streams[i];
3488 MOVStreamContext *sc = st->priv_data;
3489 if (sc->timecode_track > 0) {
3490 AVDictionaryEntry *tcr;
3491 int tmcd_st_id = -1;
3493 for (j = 0; j < s->nb_streams; j++)
3494 if (s->streams[j]->id == sc->timecode_track)
3497 if (tmcd_st_id < 0 || tmcd_st_id == i)
3499 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
3501 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
3504 export_orphan_timecode(s);
3506 for (i = 0; i < s->nb_streams; i++) {
3507 AVStream *st = s->streams[i];
3508 MOVStreamContext *sc = st->priv_data;
3509 fix_timescale(mov, sc);
3510 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
3511 st->skip_samples = sc->start_pad;
3513 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
3514 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3515 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
3516 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3517 if (st->codec->width <= 0 && st->codec->height <= 0) {
3518 st->codec->width = sc->width;
3519 st->codec->height = sc->height;
3521 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3522 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3528 if (mov->trex_data) {
3529 for (i = 0; i < s->nb_streams; i++) {
3530 AVStream *st = s->streams[i];
3531 MOVStreamContext *sc = st->priv_data;
3532 if (st->duration > 0)
3533 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3537 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
3538 if (mov->bitrates[i]) {
3539 s->streams[i]->codec->bit_rate = mov->bitrates[i];
3543 ff_rfps_calculate(s);
3545 for (i = 0; i < s->nb_streams; i++) {
3546 AVStream *st = s->streams[i];
3548 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
3551 err = ff_replaygain_export(st, s->metadata);
3561 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3563 AVIndexEntry *sample = NULL;
3564 int64_t best_dts = INT64_MAX;
3566 for (i = 0; i < s->nb_streams; i++) {
3567 AVStream *avst = s->streams[i];
3568 MOVStreamContext *msc = avst->priv_data;
3569 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3570 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3571 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3572 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3573 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3575 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3576 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3577 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3578 sample = current_sample;
3587 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3589 MOVContext *mov = s->priv_data;
3590 MOVStreamContext *sc;
3591 AVIndexEntry *sample;
3592 AVStream *st = NULL;
3596 sample = mov_find_next_sample(s, &st);
3598 mov->found_mdat = 0;
3599 if (!mov->next_root_atom)
3601 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3602 mov->next_root_atom = 0;
3603 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3606 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3610 /* must be done just before reading, to avoid infinite loop on sample */
3611 sc->current_sample++;
3613 if (mov->next_root_atom) {
3614 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
3615 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
3618 if (st->discard != AVDISCARD_ALL) {
3619 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3620 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3621 sc->ffindex, sample->pos);
3622 return AVERROR_INVALIDDATA;
3624 ret = av_get_packet(sc->pb, pkt, sample->size);
3627 if (sc->has_palette) {
3630 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3632 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3634 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3635 sc->has_palette = 0;
3638 #if CONFIG_DV_DEMUXER
3639 if (mov->dv_demux && sc->dv_audio_container) {
3640 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
3643 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3650 pkt->stream_index = sc->ffindex;
3651 pkt->dts = sample->timestamp;
3652 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3653 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3654 /* update ctts context */
3656 if (sc->ctts_index < sc->ctts_count &&
3657 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3659 sc->ctts_sample = 0;
3662 pkt->dts = AV_NOPTS_VALUE;
3664 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3665 st->index_entries[sc->current_sample].timestamp : st->duration;
3666 pkt->duration = next_dts - pkt->dts;
3667 pkt->pts = pkt->dts;
3669 if (st->discard == AVDISCARD_ALL)
3671 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3672 pkt->pos = sample->pos;
3673 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3674 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3678 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3680 MOVStreamContext *sc = st->priv_data;
3681 int sample, time_sample;
3684 sample = av_index_search_timestamp(st, timestamp, flags);
3685 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3686 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3688 if (sample < 0) /* not sure what to do */
3689 return AVERROR_INVALIDDATA;
3690 sc->current_sample = sample;
3691 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3692 /* adjust ctts index */
3693 if (sc->ctts_data) {
3695 for (i = 0; i < sc->ctts_count; i++) {
3696 int next = time_sample + sc->ctts_data[i].count;
3697 if (next > sc->current_sample) {
3699 sc->ctts_sample = sc->current_sample - time_sample;
3708 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3711 int64_t seek_timestamp, timestamp;
3715 if (stream_index >= s->nb_streams)
3716 return AVERROR_INVALIDDATA;
3718 st = s->streams[stream_index];
3719 sample = mov_seek_stream(s, st, sample_time, flags);
3723 /* adjust seek timestamp to found sample timestamp */
3724 seek_timestamp = st->index_entries[sample].timestamp;
3726 for (i = 0; i < s->nb_streams; i++) {
3727 MOVStreamContext *sc = s->streams[i]->priv_data;
3729 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
3731 if (stream_index == i)
3734 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3735 mov_seek_stream(s, st, timestamp, flags);
3740 static const AVOption options[] = {
3741 {"use_absolute_path",
3742 "allow using absolute path when opening alias, this is a possible security issue",
3743 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
3744 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3745 {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
3746 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3750 static const AVClass mov_class = {
3751 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3752 .item_name = av_default_item_name,
3754 .version = LIBAVUTIL_VERSION_INT,
3757 AVInputFormat ff_mov_demuxer = {
3758 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3759 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3760 .priv_data_size = sizeof(MOVContext),
3761 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
3762 .read_probe = mov_probe,
3763 .read_header = mov_read_header,
3764 .read_packet = mov_read_packet,
3765 .read_close = mov_read_close,
3766 .read_seek = mov_read_seek,
3767 .priv_class = &mov_class,
3768 .flags = AVFMT_NO_BYTE_SEEK,