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 Libav.
11 * Libav 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 * Libav 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 Libav; 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 "libavcodec/ac3tab.h"
42 #include "avio_internal.h"
45 #include "libavcodec/get_bits.h"
48 #include "replaygain.h"
54 #include "qtpalette.h"
60 /* those functions parse an atom */
61 /* links atom IDs to parse functions */
62 typedef struct MOVParseTableEntry {
64 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
67 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
69 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
70 unsigned len, const char *key)
74 short current, total = 0;
75 avio_rb16(pb); // unknown
76 current = avio_rb16(pb);
78 total = avio_rb16(pb);
80 snprintf(buf, sizeof(buf), "%d", current);
82 snprintf(buf, sizeof(buf), "%d/%d", current, total);
83 av_dict_set(&c->fc->metadata, key, buf, 0);
88 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
89 unsigned len, const char *key)
93 /* bypass padding bytes */
98 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
99 av_dict_set(&c->fc->metadata, key, buf, 0);
104 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
105 unsigned len, const char *key)
109 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
110 av_dict_set(&c->fc->metadata, key, buf, 0);
115 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
116 unsigned len, const char *key)
121 avio_r8(pb); // unknown
124 if (genre < 1 || genre > ID3v1_GENRE_MAX)
126 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
127 av_dict_set(&c->fc->metadata, key, buf, 0);
132 static const uint32_t mac_to_unicode[128] = {
133 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
134 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
135 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
136 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
137 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
138 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
139 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
140 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
141 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
142 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
143 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
144 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
145 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
146 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
147 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
148 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
151 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
152 char *dst, int dstlen)
155 char *end = dst+dstlen-1;
158 for (i = 0; i < len; i++) {
159 uint8_t t, c = avio_r8(pb);
160 if (c < 0x80 && p < end)
163 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
169 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
173 MOVStreamContext *sc;
178 case 0xd: id = AV_CODEC_ID_MJPEG; break;
179 case 0xe: id = AV_CODEC_ID_PNG; break;
180 case 0x1b: id = AV_CODEC_ID_BMP; break;
182 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
187 st = avformat_new_stream(c->fc, NULL);
189 return AVERROR(ENOMEM);
190 sc = av_mallocz(sizeof(*sc));
192 return AVERROR(ENOMEM);
195 ret = av_get_packet(pb, &pkt, len);
199 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
201 st->attached_pic = pkt;
202 st->attached_pic.stream_index = st->index;
203 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
205 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
206 st->codec->codec_id = id;
211 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
213 #ifdef MOV_EXPORT_ALL_METADATA
216 char str[1024], key2[16], language[4] = {0};
217 const char *key = NULL;
218 uint16_t langcode = 0;
219 uint32_t data_type = 0, str_size;
220 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
223 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
224 case MKTAG(0xa9,'a','u','t'):
225 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
226 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
227 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
228 case MKTAG( 'c','p','r','t'):
229 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
230 case MKTAG(0xa9,'c','m','t'):
231 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
232 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
233 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
234 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
235 case MKTAG( 'g','n','r','e'): key = "genre";
236 parse = mov_metadata_gnre; break;
237 case MKTAG(0xa9,'t','o','o'):
238 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
239 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
240 case MKTAG( 'd','e','s','c'): key = "description";break;
241 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
242 case MKTAG( 't','v','s','h'): key = "show"; break;
243 case MKTAG( 't','v','e','n'): key = "episode_id";break;
244 case MKTAG( 't','v','n','n'): key = "network"; break;
245 case MKTAG( 't','r','k','n'): key = "track";
246 parse = mov_metadata_track_or_disc_number; break;
247 case MKTAG( 'd','i','s','k'): key = "disc";
248 parse = mov_metadata_track_or_disc_number; break;
249 case MKTAG( 't','v','e','s'): key = "episode_sort";
250 parse = mov_metadata_int8_bypass_padding; break;
251 case MKTAG( 't','v','s','n'): key = "season_number";
252 parse = mov_metadata_int8_bypass_padding; break;
253 case MKTAG( 's','t','i','k'): key = "media_type";
254 parse = mov_metadata_int8_no_padding; break;
255 case MKTAG( 'h','d','v','d'): key = "hd_video";
256 parse = mov_metadata_int8_no_padding; break;
257 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
258 parse = mov_metadata_int8_no_padding; break;
261 if (c->itunes_metadata && atom.size > 8) {
262 int data_size = avio_rb32(pb);
263 int tag = avio_rl32(pb);
264 if (tag == MKTAG('d','a','t','a')) {
265 data_type = avio_rb32(pb); // type
266 avio_rb32(pb); // unknown
267 str_size = data_size - 16;
270 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
271 int ret = mov_read_covr(c, pb, data_type, str_size);
273 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
278 } else if (atom.size > 4 && key && !c->itunes_metadata) {
279 str_size = avio_rb16(pb); // string length
280 langcode = avio_rb16(pb);
281 ff_mov_lang_to_iso639(langcode, language);
284 str_size = atom.size;
286 #ifdef MOV_EXPORT_ALL_METADATA
288 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
296 return AVERROR_INVALIDDATA;
298 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
301 parse(c, pb, str_size, key);
303 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
304 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
306 avio_read(pb, str, str_size);
309 av_dict_set(&c->fc->metadata, key, str, 0);
310 if (*language && strcmp(language, "und")) {
311 snprintf(key2, sizeof(key2), "%s-%s", key, language);
312 av_dict_set(&c->fc->metadata, key2, str, 0);
315 av_dlog(c->fc, "lang \"%3s\" ", language);
316 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
317 key, str, (char*)&atom.type, str_size, atom.size);
322 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
325 int i, nb_chapters, str_len, version;
328 if ((atom.size -= 5) < 0)
331 version = avio_r8(pb);
334 avio_rb32(pb); // ???
335 nb_chapters = avio_r8(pb);
337 for (i = 0; i < nb_chapters; i++) {
341 start = avio_rb64(pb);
342 str_len = avio_r8(pb);
344 if ((atom.size -= 9+str_len) < 0)
347 avio_read(pb, str, str_len);
349 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
354 #define MIN_DATA_ENTRY_BOX_SIZE 12
355 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
358 MOVStreamContext *sc;
361 if (c->fc->nb_streams < 1)
363 st = c->fc->streams[c->fc->nb_streams-1];
366 avio_rb32(pb); // version + flags
367 entries = avio_rb32(pb);
368 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
369 entries >= UINT_MAX / sizeof(*sc->drefs))
370 return AVERROR_INVALIDDATA;
372 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
374 return AVERROR(ENOMEM);
375 sc->drefs_count = entries;
377 for (i = 0; i < sc->drefs_count; i++) {
378 MOVDref *dref = &sc->drefs[i];
379 uint32_t size = avio_rb32(pb);
380 int64_t next = avio_tell(pb) + size - 4;
383 return AVERROR_INVALIDDATA;
385 dref->type = avio_rl32(pb);
386 avio_rb32(pb); // version + flags
387 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
389 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
390 /* macintosh alias record */
391 uint16_t volume_len, len;
396 volume_len = avio_r8(pb);
397 volume_len = FFMIN(volume_len, 27);
398 avio_read(pb, dref->volume, 27);
399 dref->volume[volume_len] = 0;
400 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
405 len = FFMIN(len, 63);
406 avio_read(pb, dref->filename, 63);
407 dref->filename[len] = 0;
408 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
412 /* read next level up_from_alias/down_to_target */
413 dref->nlvl_from = avio_rb16(pb);
414 dref->nlvl_to = avio_rb16(pb);
415 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
416 dref->nlvl_from, dref->nlvl_to);
420 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
423 type = avio_rb16(pb);
425 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
428 if (type == 2) { // absolute path
430 dref->path = av_mallocz(len+1);
432 return AVERROR(ENOMEM);
433 avio_read(pb, dref->path, len);
434 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
436 memmove(dref->path, dref->path+volume_len, len);
439 for (j = 0; j < len; j++)
440 if (dref->path[j] == ':')
442 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
443 } else if (type == 0) { // directory name
445 dref->dir = av_malloc(len+1);
447 return AVERROR(ENOMEM);
448 avio_read(pb, dref->dir, len);
450 for (j = 0; j < len; j++)
451 if (dref->dir[j] == ':')
453 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
458 avio_seek(pb, next, SEEK_SET);
463 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
467 uint32_t av_unused ctype;
469 if (c->fc->nb_streams < 1) // meta before first trak
472 st = c->fc->streams[c->fc->nb_streams-1];
474 avio_r8(pb); /* version */
475 avio_rb24(pb); /* flags */
478 ctype = avio_rl32(pb);
479 type = avio_rl32(pb); /* component subtype */
481 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
482 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
484 if (type == MKTAG('v','i','d','e'))
485 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
486 else if (type == MKTAG('s','o','u','n'))
487 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
488 else if (type == MKTAG('m','1','a',' '))
489 st->codec->codec_id = AV_CODEC_ID_MP2;
490 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
491 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
493 avio_rb32(pb); /* component manufacture */
494 avio_rb32(pb); /* component flags */
495 avio_rb32(pb); /* component flags mask */
500 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
505 if (fc->nb_streams < 1)
507 st = fc->streams[fc->nb_streams-1];
509 avio_rb32(pb); /* version + flags */
510 ff_mp4_read_descr(fc, pb, &tag);
511 if (tag == MP4ESDescrTag) {
512 ff_mp4_parse_es_descr(pb, NULL);
514 avio_rb16(pb); /* ID */
516 ff_mp4_read_descr(fc, pb, &tag);
517 if (tag == MP4DecConfigDescrTag)
518 ff_mp4_read_dec_config_descr(fc, st, pb);
522 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
524 return ff_mov_read_esds(c->fc, pb, atom);
527 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
530 int ac3info, acmod, lfeon, bsmod;
532 if (c->fc->nb_streams < 1)
534 st = c->fc->streams[c->fc->nb_streams-1];
536 ac3info = avio_rb24(pb);
537 bsmod = (ac3info >> 14) & 0x7;
538 acmod = (ac3info >> 11) & 0x7;
539 lfeon = (ac3info >> 10) & 0x1;
540 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
541 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
543 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
544 st->codec->audio_service_type = bsmod;
545 if (st->codec->channels > 1 && bsmod == 0x7)
546 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
551 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
554 int eac3info, acmod, lfeon, bsmod;
556 if (c->fc->nb_streams < 1)
558 st = c->fc->streams[c->fc->nb_streams-1];
560 /* No need to parse fields for additional independent substreams and its
561 * associated dependent substreams since libavcodec's E-AC-3 decoder
562 * does not support them yet. */
563 avio_rb16(pb); /* data_rate and num_ind_sub */
564 eac3info = avio_rb24(pb);
565 bsmod = (eac3info >> 12) & 0x1f;
566 acmod = (eac3info >> 9) & 0x7;
567 lfeon = (eac3info >> 8) & 0x1;
568 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
570 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
571 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
572 st->codec->audio_service_type = bsmod;
573 if (st->codec->channels > 1 && bsmod == 0x7)
574 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
579 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
583 if (c->fc->nb_streams < 1)
585 st = c->fc->streams[c->fc->nb_streams-1];
590 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
595 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
599 if (c->fc->nb_streams < 1)
601 st = c->fc->streams[c->fc->nb_streams-1];
603 ff_get_wav_header(pb, st->codec, atom.size);
608 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
610 const int num = avio_rb32(pb);
611 const int den = avio_rb32(pb);
614 if (c->fc->nb_streams < 1)
616 st = c->fc->streams[c->fc->nb_streams-1];
618 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
619 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
620 av_log(c->fc, AV_LOG_WARNING,
621 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
622 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
624 } else if (den != 0) {
625 st->sample_aspect_ratio.num = num;
626 st->sample_aspect_ratio.den = den;
631 /* this atom contains actual media data */
632 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
634 if (atom.size == 0) /* wrong one (MP4) */
637 return 0; /* now go for moov */
640 /* read major brand, minor version and compatible brands and store them as metadata */
641 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
645 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
646 char* comp_brands_str;
647 uint8_t type[5] = {0};
649 avio_read(pb, type, 4);
650 if (strcmp(type, "qt "))
652 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
653 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
654 minor_ver = avio_rb32(pb); /* minor version */
655 snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);
656 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
658 comp_brand_size = atom.size - 8;
659 if (comp_brand_size < 0)
660 return AVERROR_INVALIDDATA;
661 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
662 if (!comp_brands_str)
663 return AVERROR(ENOMEM);
664 avio_read(pb, comp_brands_str, comp_brand_size);
665 comp_brands_str[comp_brand_size] = 0;
666 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
667 av_freep(&comp_brands_str);
672 /* this atom should contain all header atoms */
673 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
677 if ((ret = mov_read_default(c, pb, atom)) < 0)
679 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
680 /* so we don't parse the whole file if over a network */
682 return 0; /* now go for mdat */
685 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
687 c->fragment.moof_offset = avio_tell(pb) - 8;
688 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
689 return mov_read_default(c, pb, atom);
692 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
697 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
700 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
701 av_dict_set(metadata, "creation_time", buffer, 0);
705 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
708 MOVStreamContext *sc;
710 char language[4] = {0};
712 time_t creation_time;
714 if (c->fc->nb_streams < 1)
716 st = c->fc->streams[c->fc->nb_streams-1];
719 if (sc->time_scale) {
720 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
721 return AVERROR_INVALIDDATA;
724 version = avio_r8(pb);
726 avpriv_request_sample(c->fc, "Version %d", version);
727 return AVERROR_PATCHWELCOME;
729 avio_rb24(pb); /* flags */
731 creation_time = avio_rb64(pb);
734 creation_time = avio_rb32(pb);
735 avio_rb32(pb); /* modification time */
737 mov_metadata_creation_time(&st->metadata, creation_time);
739 sc->time_scale = avio_rb32(pb);
740 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
742 lang = avio_rb16(pb); /* language */
743 if (ff_mov_lang_to_iso639(lang, language))
744 av_dict_set(&st->metadata, "language", language, 0);
745 avio_rb16(pb); /* quality */
750 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
752 time_t creation_time;
753 int version = avio_r8(pb); /* version */
754 avio_rb24(pb); /* flags */
757 creation_time = avio_rb64(pb);
760 creation_time = avio_rb32(pb);
761 avio_rb32(pb); /* modification time */
763 mov_metadata_creation_time(&c->fc->metadata, creation_time);
764 c->time_scale = avio_rb32(pb); /* time scale */
766 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
768 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
769 avio_rb32(pb); /* preferred scale */
771 avio_rb16(pb); /* preferred volume */
773 avio_skip(pb, 10); /* reserved */
775 avio_skip(pb, 36); /* display matrix */
777 avio_rb32(pb); /* preview time */
778 avio_rb32(pb); /* preview duration */
779 avio_rb32(pb); /* poster time */
780 avio_rb32(pb); /* selection time */
781 avio_rb32(pb); /* selection duration */
782 avio_rb32(pb); /* current time */
783 avio_rb32(pb); /* next track ID */
788 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
792 if (c->fc->nb_streams < 1)
794 st = c->fc->streams[c->fc->nb_streams-1];
796 if ((uint64_t)atom.size > (1<<30))
797 return AVERROR_INVALIDDATA;
799 // currently SVQ3 decoder expect full STSD header - so let's fake it
800 // this should be fixed and just SMI header should be passed
801 av_free(st->codec->extradata);
802 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
803 if (!st->codec->extradata)
804 return AVERROR(ENOMEM);
805 st->codec->extradata_size = 0x5a + atom.size;
806 memcpy(st->codec->extradata, "SVQ3", 4); // fake
807 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
808 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
812 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
817 if (c->fc->nb_streams < 1)
819 st = c->fc->streams[c->fc->nb_streams-1];
821 little_endian = avio_rb16(pb);
822 av_dlog(c->fc, "enda %d\n", little_endian);
823 if (little_endian == 1) {
824 switch (st->codec->codec_id) {
825 case AV_CODEC_ID_PCM_S24BE:
826 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
828 case AV_CODEC_ID_PCM_S32BE:
829 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
831 case AV_CODEC_ID_PCM_F32BE:
832 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
834 case AV_CODEC_ID_PCM_F64BE:
835 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
844 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
847 unsigned mov_field_order;
848 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
850 if (c->fc->nb_streams < 1) // will happen with jp2 files
852 st = c->fc->streams[c->fc->nb_streams-1];
854 return AVERROR_INVALIDDATA;
855 mov_field_order = avio_rb16(pb);
856 if ((mov_field_order & 0xFF00) == 0x0100)
857 decoded_field_order = AV_FIELD_PROGRESSIVE;
858 else if ((mov_field_order & 0xFF00) == 0x0200) {
859 switch (mov_field_order & 0xFF) {
860 case 0x01: decoded_field_order = AV_FIELD_TT;
862 case 0x06: decoded_field_order = AV_FIELD_BB;
864 case 0x09: decoded_field_order = AV_FIELD_TB;
866 case 0x0E: decoded_field_order = AV_FIELD_BT;
870 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
871 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
873 st->codec->field_order = decoded_field_order;
878 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
879 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
886 if (c->fc->nb_streams < 1) // will happen with jp2 files
888 st= c->fc->streams[c->fc->nb_streams-1];
889 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
890 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
891 return AVERROR_INVALIDDATA;
892 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
893 st->codec->extradata_size = 0;
896 buf = st->codec->extradata + st->codec->extradata_size;
897 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
898 AV_WB32( buf , atom.size + 8);
899 AV_WL32( buf + 4, atom.type);
900 avio_read(pb, buf + 8, atom.size);
904 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
908 if (c->fc->nb_streams < 1)
910 st = c->fc->streams[c->fc->nb_streams-1];
912 if ((uint64_t)atom.size > (1<<30))
913 return AVERROR_INVALIDDATA;
915 if (st->codec->codec_id == AV_CODEC_ID_QDM2 || st->codec->codec_id == AV_CODEC_ID_QDMC) {
916 // pass all frma atom to codec, needed at least for QDMC and QDM2
917 av_free(st->codec->extradata);
918 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
919 if (!st->codec->extradata)
920 return AVERROR(ENOMEM);
921 st->codec->extradata_size = atom.size;
922 avio_read(pb, st->codec->extradata, atom.size);
923 } else if (atom.size > 8) { /* to read frma, esds atoms */
925 if ((ret = mov_read_default(c, pb, atom)) < 0)
928 avio_skip(pb, atom.size);
933 * This function reads atom content and puts data in extradata without tag
934 * nor size unlike mov_read_extradata.
936 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
940 if (c->fc->nb_streams < 1)
942 st = c->fc->streams[c->fc->nb_streams-1];
944 if ((uint64_t)atom.size > (1<<30))
945 return AVERROR_INVALIDDATA;
947 if (atom.size >= 10) {
948 // Broken files created by legacy versions of libavformat will
949 // wrap a whole fiel atom inside of a glbl atom.
950 unsigned size = avio_rb32(pb);
951 unsigned type = avio_rl32(pb);
952 avio_seek(pb, -8, SEEK_CUR);
953 if (type == MKTAG('f','i','e','l') && size == atom.size)
954 return mov_read_default(c, pb, atom);
956 av_free(st->codec->extradata);
957 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
958 if (!st->codec->extradata)
959 return AVERROR(ENOMEM);
960 st->codec->extradata_size = atom.size;
961 avio_read(pb, st->codec->extradata, atom.size);
965 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
968 uint8_t profile_level;
970 if (c->fc->nb_streams < 1)
972 st = c->fc->streams[c->fc->nb_streams-1];
974 if (atom.size >= (1<<28) || atom.size < 7)
975 return AVERROR_INVALIDDATA;
977 profile_level = avio_r8(pb);
978 if ((profile_level & 0xf0) != 0xc0)
981 av_free(st->codec->extradata);
982 st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
983 if (!st->codec->extradata)
984 return AVERROR(ENOMEM);
985 st->codec->extradata_size = atom.size - 7;
986 avio_seek(pb, 6, SEEK_CUR);
987 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
992 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
993 * but can have extradata appended at the end after the 40 bytes belonging
996 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1000 if (c->fc->nb_streams < 1)
1002 if (atom.size <= 40)
1004 st = c->fc->streams[c->fc->nb_streams-1];
1006 if ((uint64_t)atom.size > (1<<30))
1007 return AVERROR_INVALIDDATA;
1009 av_free(st->codec->extradata);
1010 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1011 if (!st->codec->extradata)
1012 return AVERROR(ENOMEM);
1013 st->codec->extradata_size = atom.size - 40;
1015 avio_read(pb, st->codec->extradata, atom.size - 40);
1019 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1022 MOVStreamContext *sc;
1023 unsigned int i, entries;
1025 if (c->fc->nb_streams < 1)
1027 st = c->fc->streams[c->fc->nb_streams-1];
1030 avio_r8(pb); /* version */
1031 avio_rb24(pb); /* flags */
1033 entries = avio_rb32(pb);
1037 if (entries >= UINT_MAX/sizeof(int64_t))
1038 return AVERROR_INVALIDDATA;
1040 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1041 if (!sc->chunk_offsets)
1042 return AVERROR(ENOMEM);
1043 sc->chunk_count = entries;
1045 if (atom.type == MKTAG('s','t','c','o'))
1046 for (i = 0; i < entries && !pb->eof_reached; i++)
1047 sc->chunk_offsets[i] = avio_rb32(pb);
1048 else if (atom.type == MKTAG('c','o','6','4'))
1049 for (i = 0; i < entries && !pb->eof_reached; i++)
1050 sc->chunk_offsets[i] = avio_rb64(pb);
1052 return AVERROR_INVALIDDATA;
1054 sc->chunk_count = i;
1056 if (pb->eof_reached)
1063 * Compute codec id for 'lpcm' tag.
1064 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1066 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1073 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1076 static int mov_codec_id(AVStream *st, uint32_t format)
1078 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1081 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1082 (format & 0xFFFF) == 'T' + ('S' << 8)))
1083 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1085 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1086 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1087 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1088 /* skip old asf mpeg4 tag */
1089 format && format != MKTAG('m','p','4','s')) {
1090 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1092 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1094 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1095 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
1096 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1098 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1102 st->codec->codec_tag = format;
1107 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1108 AVStream *st, MOVStreamContext *sc)
1110 uint8_t codec_name[32];
1111 unsigned int color_depth, len, j;
1112 int color_greyscale;
1115 avio_rb16(pb); /* version */
1116 avio_rb16(pb); /* revision level */
1117 avio_rb32(pb); /* vendor */
1118 avio_rb32(pb); /* temporal quality */
1119 avio_rb32(pb); /* spatial quality */
1121 st->codec->width = avio_rb16(pb); /* width */
1122 st->codec->height = avio_rb16(pb); /* height */
1124 avio_rb32(pb); /* horiz resolution */
1125 avio_rb32(pb); /* vert resolution */
1126 avio_rb32(pb); /* data size, always 0 */
1127 avio_rb16(pb); /* frames per samples */
1129 len = avio_r8(pb); /* codec name, pascal string */
1132 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1134 avio_skip(pb, 31 - len);
1137 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1139 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1140 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1141 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1142 /* Flash Media Server uses tag H263 with Sorenson Spark */
1143 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1144 !memcmp(codec_name, "Sorenson H263", 13))
1145 st->codec->codec_id = AV_CODEC_ID_FLV1;
1147 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1148 color_table_id = avio_rb16(pb); /* colortable id */
1149 av_dlog(c->fc, "depth %d, ctab id %d\n",
1150 st->codec->bits_per_coded_sample, color_table_id);
1151 /* figure out the palette situation */
1152 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1153 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1155 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1156 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1157 /* for palette traversal */
1158 unsigned int color_start, color_count, color_end;
1159 unsigned char r, g, b;
1161 if (color_greyscale) {
1162 int color_index, color_dec;
1163 /* compute the greyscale palette */
1164 st->codec->bits_per_coded_sample = color_depth;
1165 color_count = 1 << color_depth;
1167 color_dec = 256 / (color_count - 1);
1168 for (j = 0; j < color_count; j++) {
1169 r = g = b = color_index;
1170 sc->palette[j] = (r << 16) | (g << 8) | (b);
1171 color_index -= color_dec;
1172 if (color_index < 0)
1175 } else if (color_table_id) {
1176 const uint8_t *color_table;
1177 /* if flag bit 3 is set, use the default palette */
1178 color_count = 1 << color_depth;
1179 if (color_depth == 2)
1180 color_table = ff_qt_default_palette_4;
1181 else if (color_depth == 4)
1182 color_table = ff_qt_default_palette_16;
1184 color_table = ff_qt_default_palette_256;
1186 for (j = 0; j < color_count; j++) {
1187 r = color_table[j * 3 + 0];
1188 g = color_table[j * 3 + 1];
1189 b = color_table[j * 3 + 2];
1190 sc->palette[j] = (r << 16) | (g << 8) | (b);
1193 /* load the palette from the file */
1194 color_start = avio_rb32(pb);
1195 color_count = avio_rb16(pb);
1196 color_end = avio_rb16(pb);
1197 if ((color_start <= 255) && (color_end <= 255)) {
1198 for (j = color_start; j <= color_end; j++) {
1199 /* each R, G, or B component is 16 bits;
1200 * only use the top 8 bits; skip alpha bytes
1210 sc->palette[j] = (r << 16) | (g << 8) | (b);
1214 sc->has_palette = 1;
1218 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1219 AVStream *st, MOVStreamContext *sc)
1221 int bits_per_sample, flags;
1222 uint16_t version = avio_rb16(pb);
1224 avio_rb16(pb); /* revision level */
1225 avio_rb32(pb); /* vendor */
1227 st->codec->channels = avio_rb16(pb); /* channel count */
1228 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1229 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1231 sc->audio_cid = avio_rb16(pb);
1232 avio_rb16(pb); /* packet size = 0 */
1234 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1236 // Read QT version 1 fields. In version 0 these do not exist.
1237 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1240 sc->samples_per_frame = avio_rb32(pb);
1241 avio_rb32(pb); /* bytes per packet */
1242 sc->bytes_per_frame = avio_rb32(pb);
1243 avio_rb32(pb); /* bytes per sample */
1244 } else if (version == 2) {
1245 avio_rb32(pb); /* sizeof struct only */
1246 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1247 st->codec->channels = avio_rb32(pb);
1248 avio_rb32(pb); /* always 0x7F000000 */
1249 st->codec->bits_per_coded_sample = avio_rb32(pb);
1251 flags = avio_rb32(pb); /* lpcm format specific flag */
1252 sc->bytes_per_frame = avio_rb32(pb);
1253 sc->samples_per_frame = avio_rb32(pb);
1254 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1255 st->codec->codec_id =
1256 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1261 switch (st->codec->codec_id) {
1262 case AV_CODEC_ID_PCM_S8:
1263 case AV_CODEC_ID_PCM_U8:
1264 if (st->codec->bits_per_coded_sample == 16)
1265 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1267 case AV_CODEC_ID_PCM_S16LE:
1268 case AV_CODEC_ID_PCM_S16BE:
1269 if (st->codec->bits_per_coded_sample == 8)
1270 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1271 else if (st->codec->bits_per_coded_sample == 24)
1272 st->codec->codec_id =
1273 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1274 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1276 /* set values for old format before stsd version 1 appeared */
1277 case AV_CODEC_ID_MACE3:
1278 sc->samples_per_frame = 6;
1279 sc->bytes_per_frame = 2 * st->codec->channels;
1281 case AV_CODEC_ID_MACE6:
1282 sc->samples_per_frame = 6;
1283 sc->bytes_per_frame = 1 * st->codec->channels;
1285 case AV_CODEC_ID_ADPCM_IMA_QT:
1286 sc->samples_per_frame = 64;
1287 sc->bytes_per_frame = 34 * st->codec->channels;
1289 case AV_CODEC_ID_GSM:
1290 sc->samples_per_frame = 160;
1291 sc->bytes_per_frame = 33;
1297 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1298 if (bits_per_sample) {
1299 st->codec->bits_per_coded_sample = bits_per_sample;
1300 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1304 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1305 AVStream *st, MOVStreamContext *sc,
1308 // ttxt stsd contains display flags, justification, background
1309 // color, fonts, and default styles, so fake an atom to read it
1310 MOVAtom fake_atom = { .size = size };
1311 // mp4s contains a regular esds atom
1312 if (st->codec->codec_tag != AV_RL32("mp4s"))
1313 mov_read_glbl(c, pb, fake_atom);
1314 st->codec->width = sc->width;
1315 st->codec->height = sc->height;
1318 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1323 y = (ycbcr >> 16) & 0xFF;
1324 cr = (ycbcr >> 8) & 0xFF;
1327 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1328 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1329 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1331 return (r << 16) | (g << 8) | b;
1334 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1336 char buf[256] = {0};
1337 uint8_t *src = st->codec->extradata;
1340 if (st->codec->extradata_size != 64)
1343 if (st->codec->width > 0 && st->codec->height > 0)
1344 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1345 st->codec->width, st->codec->height);
1346 av_strlcat(buf, "palette: ", sizeof(buf));
1348 for (i = 0; i < 16; i++) {
1349 uint32_t yuv = AV_RB32(src + i * 4);
1350 uint32_t rgba = yuv_to_rgba(yuv);
1352 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1355 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1358 av_freep(&st->codec->extradata);
1359 st->codec->extradata_size = 0;
1360 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1361 if (!st->codec->extradata)
1362 return AVERROR(ENOMEM);
1363 st->codec->extradata_size = strlen(buf);
1364 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1369 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1370 AVStream *st, MOVStreamContext *sc,
1373 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1374 st->codec->extradata_size = size;
1375 st->codec->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
1376 if (!st->codec->extradata)
1377 return AVERROR(ENOMEM);
1378 avio_read(pb, st->codec->extradata, size);
1380 /* other codec type, just skip (rtp, mp4s ...) */
1381 avio_skip(pb, size);
1386 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1387 AVStream *st, MOVStreamContext *sc)
1389 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1390 !st->codec->sample_rate && sc->time_scale > 1)
1391 st->codec->sample_rate = sc->time_scale;
1393 /* special codec parameters handling */
1394 switch (st->codec->codec_id) {
1395 #if CONFIG_DV_DEMUXER
1396 case AV_CODEC_ID_DVAUDIO:
1397 c->dv_fctx = avformat_alloc_context();
1398 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1400 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1401 return AVERROR(ENOMEM);
1403 sc->dv_audio_container = 1;
1404 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1407 /* no ifdef since parameters are always those */
1408 case AV_CODEC_ID_QCELP:
1409 st->codec->channels = 1;
1410 // force sample rate for qcelp when not stored in mov
1411 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1412 st->codec->sample_rate = 8000;
1414 case AV_CODEC_ID_AMR_NB:
1415 st->codec->channels = 1;
1416 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1417 st->codec->sample_rate = 8000;
1419 case AV_CODEC_ID_AMR_WB:
1420 st->codec->channels = 1;
1421 st->codec->sample_rate = 16000;
1423 case AV_CODEC_ID_MP2:
1424 case AV_CODEC_ID_MP3:
1425 /* force type after stsd for m1a hdlr */
1426 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1427 st->need_parsing = AVSTREAM_PARSE_FULL;
1429 case AV_CODEC_ID_GSM:
1430 case AV_CODEC_ID_ADPCM_MS:
1431 case AV_CODEC_ID_ADPCM_IMA_WAV:
1432 case AV_CODEC_ID_ILBC:
1433 st->codec->block_align = sc->bytes_per_frame;
1435 case AV_CODEC_ID_ALAC:
1436 if (st->codec->extradata_size == 36) {
1437 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1438 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1441 case AV_CODEC_ID_VC1:
1442 st->need_parsing = AVSTREAM_PARSE_FULL;
1450 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1451 int codec_tag, int format,
1454 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1457 (codec_tag == AV_RL32("avc1") ||
1458 codec_tag == AV_RL32("hvc1") ||
1459 codec_tag == AV_RL32("hev1") ||
1460 (codec_tag != format &&
1461 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1462 : codec_tag != MKTAG('j','p','e','g'))))) {
1463 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1464 * export it as a separate AVStream but this needs a few changes
1465 * in the MOV demuxer, patch welcome. */
1467 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1468 avio_skip(pb, size);
1475 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1478 MOVStreamContext *sc;
1479 int pseudo_stream_id;
1481 if (c->fc->nb_streams < 1)
1483 st = c->fc->streams[c->fc->nb_streams-1];
1486 for (pseudo_stream_id = 0;
1487 pseudo_stream_id < entries && !pb->eof_reached;
1488 pseudo_stream_id++) {
1489 //Parsing Sample description table
1491 int ret, dref_id = 1;
1492 MOVAtom a = { AV_RL32("stsd") };
1493 int64_t start_pos = avio_tell(pb);
1494 uint32_t size = avio_rb32(pb); /* size */
1495 uint32_t format = avio_rl32(pb); /* data format */
1498 avio_rb32(pb); /* reserved */
1499 avio_rb16(pb); /* reserved */
1500 dref_id = avio_rb16(pb);
1502 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRIu32" in stsd\n", size);
1503 return AVERROR_INVALIDDATA;
1506 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1507 size - (avio_tell(pb) - start_pos)))
1510 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1511 sc->dref_id= dref_id;
1513 id = mov_codec_id(st, format);
1515 av_dlog(c->fc, "size=%"PRIu32" 4CC= %"PRIu8"%"PRIu8"%"PRIu8"%"PRIu8" codec_type=%d\n", size,
1516 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1517 (format >> 24) & 0xff, st->codec->codec_type);
1519 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1520 st->codec->codec_id = id;
1521 mov_parse_stsd_video(c, pb, st, sc);
1522 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1523 st->codec->codec_id = id;
1524 mov_parse_stsd_audio(c, pb, st, sc);
1525 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1526 st->codec->codec_id = id;
1527 mov_parse_stsd_subtitle(c, pb, st, sc,
1528 size - (avio_tell(pb) - start_pos));
1530 ret = mov_parse_stsd_data(c, pb, st, sc,
1531 size - (avio_tell(pb) - start_pos));
1535 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1536 a.size = size - (avio_tell(pb) - start_pos);
1538 if ((ret = mov_read_default(c, pb, a)) < 0)
1540 } else if (a.size > 0)
1541 avio_skip(pb, a.size);
1544 if (pb->eof_reached)
1547 return mov_finalize_stsd_codec(c, pb, st, sc);
1550 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1554 avio_r8(pb); /* version */
1555 avio_rb24(pb); /* flags */
1556 entries = avio_rb32(pb);
1558 return ff_mov_read_stsd_entries(c, pb, entries);
1561 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1564 MOVStreamContext *sc;
1565 unsigned int i, entries;
1567 if (c->fc->nb_streams < 1)
1569 st = c->fc->streams[c->fc->nb_streams-1];
1572 avio_r8(pb); /* version */
1573 avio_rb24(pb); /* flags */
1575 entries = avio_rb32(pb);
1577 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1581 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1582 return AVERROR_INVALIDDATA;
1583 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1585 return AVERROR(ENOMEM);
1587 for (i = 0; i < entries && !pb->eof_reached; i++) {
1588 sc->stsc_data[i].first = avio_rb32(pb);
1589 sc->stsc_data[i].count = avio_rb32(pb);
1590 sc->stsc_data[i].id = avio_rb32(pb);
1595 if (pb->eof_reached)
1601 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1604 MOVStreamContext *sc;
1605 unsigned i, entries;
1607 if (c->fc->nb_streams < 1)
1609 st = c->fc->streams[c->fc->nb_streams-1];
1612 avio_rb32(pb); // version + flags
1614 entries = avio_rb32(pb);
1615 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1616 return AVERROR_INVALIDDATA;
1617 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1619 return AVERROR(ENOMEM);
1621 for (i = 0; i < entries && !pb->eof_reached; i++) {
1622 sc->stps_data[i] = avio_rb32(pb);
1623 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1628 if (pb->eof_reached)
1634 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1637 MOVStreamContext *sc;
1638 unsigned int i, entries;
1640 if (c->fc->nb_streams < 1)
1642 st = c->fc->streams[c->fc->nb_streams-1];
1645 avio_r8(pb); /* version */
1646 avio_rb24(pb); /* flags */
1648 entries = avio_rb32(pb);
1650 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1654 sc->keyframe_absent = 1;
1657 if (entries >= UINT_MAX / sizeof(int))
1658 return AVERROR_INVALIDDATA;
1659 sc->keyframes = av_malloc(entries * sizeof(int));
1661 return AVERROR(ENOMEM);
1663 for (i = 0; i < entries && !pb->eof_reached; i++) {
1664 sc->keyframes[i] = avio_rb32(pb);
1665 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1668 sc->keyframe_count = i;
1670 if (pb->eof_reached)
1676 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1679 MOVStreamContext *sc;
1680 unsigned int i, entries, sample_size, field_size, num_bytes;
1684 if (c->fc->nb_streams < 1)
1686 st = c->fc->streams[c->fc->nb_streams-1];
1689 avio_r8(pb); /* version */
1690 avio_rb24(pb); /* flags */
1692 if (atom.type == MKTAG('s','t','s','z')) {
1693 sample_size = avio_rb32(pb);
1694 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1695 sc->sample_size = sample_size;
1699 avio_rb24(pb); /* reserved */
1700 field_size = avio_r8(pb);
1702 entries = avio_rb32(pb);
1704 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1706 sc->sample_count = entries;
1710 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1711 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1712 return AVERROR_INVALIDDATA;
1717 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1718 return AVERROR_INVALIDDATA;
1719 sc->sample_sizes = av_malloc(entries * sizeof(int));
1720 if (!sc->sample_sizes)
1721 return AVERROR(ENOMEM);
1723 num_bytes = (entries*field_size+4)>>3;
1725 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1727 av_freep(&sc->sample_sizes);
1728 return AVERROR(ENOMEM);
1731 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1732 av_freep(&sc->sample_sizes);
1734 return AVERROR_INVALIDDATA;
1737 init_get_bits(&gb, buf, 8*num_bytes);
1739 for (i = 0; i < entries && !pb->eof_reached; i++) {
1740 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1741 sc->data_size += sc->sample_sizes[i];
1744 sc->sample_count = i;
1746 if (pb->eof_reached)
1753 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1756 MOVStreamContext *sc;
1757 unsigned int i, entries;
1759 int64_t total_sample_count=0;
1761 if (c->fc->nb_streams < 1)
1763 st = c->fc->streams[c->fc->nb_streams-1];
1766 avio_r8(pb); /* version */
1767 avio_rb24(pb); /* flags */
1768 entries = avio_rb32(pb);
1770 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1771 c->fc->nb_streams-1, entries);
1775 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1776 return AVERROR(EINVAL);
1778 av_free(sc->stts_data);
1779 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1781 return AVERROR(ENOMEM);
1783 for (i = 0; i < entries && !pb->eof_reached; i++) {
1784 int sample_duration;
1787 sample_count=avio_rb32(pb);
1788 sample_duration = avio_rb32(pb);
1789 if (sample_count < 0) {
1790 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
1791 return AVERROR_INVALIDDATA;
1793 sc->stts_data[i].count= sample_count;
1794 sc->stts_data[i].duration= sample_duration;
1796 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1797 sample_count, sample_duration);
1799 duration+=(int64_t)sample_duration*sample_count;
1800 total_sample_count+=sample_count;
1805 if (pb->eof_reached)
1808 st->nb_frames= total_sample_count;
1810 st->duration= duration;
1811 sc->track_end = duration;
1815 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1818 MOVStreamContext *sc;
1819 unsigned int i, entries;
1821 if (c->fc->nb_streams < 1)
1823 st = c->fc->streams[c->fc->nb_streams-1];
1826 avio_r8(pb); /* version */
1827 avio_rb24(pb); /* flags */
1828 entries = avio_rb32(pb);
1830 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1834 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1835 return AVERROR_INVALIDDATA;
1836 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1838 return AVERROR(ENOMEM);
1840 for (i = 0; i < entries && !pb->eof_reached; i++) {
1841 int count =avio_rb32(pb);
1842 int duration =avio_rb32(pb);
1844 sc->ctts_data[i].count = count;
1845 sc->ctts_data[i].duration= duration;
1847 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1852 if (pb->eof_reached)
1855 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1860 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1863 MOVStreamContext *sc;
1864 unsigned int i, entries;
1866 uint32_t grouping_type;
1868 if (c->fc->nb_streams < 1)
1870 st = c->fc->streams[c->fc->nb_streams-1];
1873 version = avio_r8(pb); /* version */
1874 avio_rb24(pb); /* flags */
1875 grouping_type = avio_rl32(pb);
1876 if (grouping_type != MKTAG( 'r','a','p',' '))
1877 return 0; /* only support 'rap ' grouping */
1879 avio_rb32(pb); /* grouping_type_parameter */
1881 entries = avio_rb32(pb);
1884 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
1885 return AVERROR_INVALIDDATA;
1886 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
1888 return AVERROR(ENOMEM);
1890 for (i = 0; i < entries && !pb->eof_reached; i++) {
1891 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
1892 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
1895 sc->rap_group_count = i;
1897 return pb->eof_reached ? AVERROR_EOF : 0;
1900 static void mov_build_index(MOVContext *mov, AVStream *st)
1902 MOVStreamContext *sc = st->priv_data;
1903 int64_t current_offset;
1904 int64_t current_dts = 0;
1905 unsigned int stts_index = 0;
1906 unsigned int stsc_index = 0;
1907 unsigned int stss_index = 0;
1908 unsigned int stps_index = 0;
1910 uint64_t stream_size = 0;
1912 /* adjust first dts according to edit list */
1913 if (sc->time_offset && mov->time_scale > 0) {
1914 if (sc->time_offset < 0)
1915 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
1916 current_dts = -sc->time_offset;
1917 if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
1918 sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1919 /* more than 16 frames delay, dts are likely wrong
1920 this happens with files created by iMovie */
1922 st->codec->has_b_frames = 1;
1926 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1927 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1928 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1929 unsigned int current_sample = 0;
1930 unsigned int stts_sample = 0;
1931 unsigned int sample_size;
1932 unsigned int distance = 0;
1933 unsigned int rap_group_index = 0;
1934 unsigned int rap_group_sample = 0;
1935 int rap_group_present = sc->rap_group_count && sc->rap_group;
1936 int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
1938 current_dts -= sc->dts_shift;
1940 if (!sc->sample_count)
1942 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1944 if (av_reallocp_array(&st->index_entries,
1945 st->nb_index_entries + sc->sample_count,
1946 sizeof(*st->index_entries)) < 0) {
1947 st->nb_index_entries = 0;
1950 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
1952 for (i = 0; i < sc->chunk_count; i++) {
1953 current_offset = sc->chunk_offsets[i];
1954 while (stsc_index + 1 < sc->stsc_count &&
1955 i + 1 == sc->stsc_data[stsc_index + 1].first)
1957 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1959 if (current_sample >= sc->sample_count) {
1960 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1964 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
1966 if (stss_index + 1 < sc->keyframe_count)
1968 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1970 if (stps_index + 1 < sc->stps_count)
1973 if (rap_group_present && rap_group_index < sc->rap_group_count) {
1974 if (sc->rap_group[rap_group_index].index > 0)
1976 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
1977 rap_group_sample = 0;
1983 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1984 if (sc->pseudo_stream_id == -1 ||
1985 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1986 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1987 e->pos = current_offset;
1988 e->timestamp = current_dts;
1989 e->size = sample_size;
1990 e->min_distance = distance;
1991 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1992 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1993 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1994 current_offset, current_dts, sample_size, distance, keyframe);
1997 current_offset += sample_size;
1998 stream_size += sample_size;
1999 current_dts += sc->stts_data[stts_index].duration;
2003 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2009 if (st->duration > 0)
2010 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2012 unsigned chunk_samples, total = 0;
2014 // compute total chunk count
2015 for (i = 0; i < sc->stsc_count; i++) {
2016 unsigned count, chunk_count;
2018 chunk_samples = sc->stsc_data[i].count;
2019 if (i != sc->stsc_count - 1 &&
2020 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2021 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2025 if (sc->samples_per_frame >= 160) { // gsm
2026 count = chunk_samples / sc->samples_per_frame;
2027 } else if (sc->samples_per_frame > 1) {
2028 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2029 count = (chunk_samples+samples-1) / samples;
2031 count = (chunk_samples+1023) / 1024;
2034 if (i < sc->stsc_count - 1)
2035 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2037 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2038 total += chunk_count * count;
2041 av_dlog(mov->fc, "chunk count %d\n", total);
2042 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2044 if (av_reallocp_array(&st->index_entries,
2045 st->nb_index_entries + total,
2046 sizeof(*st->index_entries)) < 0) {
2047 st->nb_index_entries = 0;
2050 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2053 for (i = 0; i < sc->chunk_count; i++) {
2054 current_offset = sc->chunk_offsets[i];
2055 if (stsc_index + 1 < sc->stsc_count &&
2056 i + 1 == sc->stsc_data[stsc_index + 1].first)
2058 chunk_samples = sc->stsc_data[stsc_index].count;
2060 while (chunk_samples > 0) {
2062 unsigned size, samples;
2064 if (sc->samples_per_frame >= 160) { // gsm
2065 samples = sc->samples_per_frame;
2066 size = sc->bytes_per_frame;
2068 if (sc->samples_per_frame > 1) {
2069 samples = FFMIN((1024 / sc->samples_per_frame)*
2070 sc->samples_per_frame, chunk_samples);
2071 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2073 samples = FFMIN(1024, chunk_samples);
2074 size = samples * sc->sample_size;
2078 if (st->nb_index_entries >= total) {
2079 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2082 e = &st->index_entries[st->nb_index_entries++];
2083 e->pos = current_offset;
2084 e->timestamp = current_dts;
2086 e->min_distance = 0;
2087 e->flags = AVINDEX_KEYFRAME;
2088 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2089 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2092 current_offset += size;
2093 current_dts += samples;
2094 chunk_samples -= samples;
2100 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
2101 AVIOInterruptCB *int_cb)
2103 /* try relative path, we do not try the absolute because it can leak information about our
2104 system to an attacker */
2105 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2106 char filename[1024];
2110 /* find a source dir */
2111 src_path = strrchr(src, '/');
2117 /* find a next level down to target */
2118 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2119 if (ref->path[l] == '/') {
2120 if (i == ref->nlvl_to - 1)
2126 /* compose filename if next level down to target was found */
2127 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2128 memcpy(filename, src, src_path - src);
2129 filename[src_path - src] = 0;
2131 for (i = 1; i < ref->nlvl_from; i++)
2132 av_strlcat(filename, "../", 1024);
2134 av_strlcat(filename, ref->path + l + 1, 1024);
2136 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2141 return AVERROR(ENOENT);
2144 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2147 MOVStreamContext *sc;
2150 st = avformat_new_stream(c->fc, NULL);
2151 if (!st) return AVERROR(ENOMEM);
2152 st->id = c->fc->nb_streams;
2153 sc = av_mallocz(sizeof(MOVStreamContext));
2154 if (!sc) return AVERROR(ENOMEM);
2157 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2158 sc->ffindex = st->index;
2160 if ((ret = mov_read_default(c, pb, atom)) < 0)
2164 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2165 (!sc->sample_size && !sc->sample_count))) {
2166 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2171 if (sc->time_scale <= 0) {
2172 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2173 sc->time_scale = c->time_scale;
2174 if (sc->time_scale <= 0)
2178 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2180 mov_build_index(c, st);
2182 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2183 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2184 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
2185 av_log(c->fc, AV_LOG_ERROR,
2186 "stream %d, error opening alias: path='%s', dir='%s', "
2187 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2188 st->index, dref->path, dref->dir, dref->filename,
2189 dref->volume, dref->nlvl_from, dref->nlvl_to);
2193 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2194 if (!st->sample_aspect_ratio.num &&
2195 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2196 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2197 ((double)st->codec->width * sc->height), INT_MAX);
2201 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2202 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2203 TAG_IS_AVCI(st->codec->codec_tag)) {
2204 ret = ff_generate_avci_extradata(st);
2209 switch (st->codec->codec_id) {
2210 #if CONFIG_H261_DECODER
2211 case AV_CODEC_ID_H261:
2213 #if CONFIG_H263_DECODER
2214 case AV_CODEC_ID_H263:
2216 #if CONFIG_MPEG4_DECODER
2217 case AV_CODEC_ID_MPEG4:
2219 st->codec->width = 0; /* let decoder init width/height */
2220 st->codec->height= 0;
2224 /* Do not need those anymore. */
2225 av_freep(&sc->chunk_offsets);
2226 av_freep(&sc->stsc_data);
2227 av_freep(&sc->sample_sizes);
2228 av_freep(&sc->keyframes);
2229 av_freep(&sc->stts_data);
2230 av_freep(&sc->stps_data);
2231 av_freep(&sc->rap_group);
2236 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2239 c->itunes_metadata = 1;
2240 ret = mov_read_default(c, pb, atom);
2241 c->itunes_metadata = 0;
2245 static int mov_read_replaygain(MOVContext *c, AVIOContext *pb, int size)
2247 int64_t end = avio_tell(pb) + size;
2248 uint8_t *key = NULL, *val = NULL;
2251 for (i = 0; i < 2; i++) {
2255 if (end - avio_tell(pb) <= 12)
2258 len = avio_rb32(pb);
2259 tag = avio_rl32(pb);
2260 avio_skip(pb, 4); // flags
2262 if (len < 12 || len - 12 > end - avio_tell(pb))
2266 if (tag == MKTAG('n', 'a', 'm', 'e'))
2268 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2275 *p = av_malloc(len + 1);
2278 avio_read(pb, *p, len);
2283 av_dict_set(&c->fc->metadata, key, val,
2284 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2288 avio_seek(pb, end, SEEK_SET);
2294 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2296 int64_t end = avio_tell(pb) + atom.size;
2302 len = avio_rb32(pb);
2303 tag = avio_rl32(pb);
2305 if (len > atom.size)
2308 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2309 uint8_t domain[128];
2312 avio_skip(pb, 4); // flags
2315 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2316 avio_skip(pb, len - domain_len);
2317 if (!strcmp(domain, "org.hydrogenaudio.replaygain"))
2318 return mov_read_replaygain(c, pb, end - avio_tell(pb));
2322 av_log(c->fc, AV_LOG_VERBOSE,
2323 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2327 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2329 while (atom.size > 8) {
2330 uint32_t tag = avio_rl32(pb);
2332 if (tag == MKTAG('h','d','l','r')) {
2333 avio_seek(pb, -8, SEEK_CUR);
2335 return mov_read_default(c, pb, atom);
2341 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2346 int64_t disp_transform[2];
2347 int display_matrix[3][3];
2349 MOVStreamContext *sc;
2353 if (c->fc->nb_streams < 1)
2355 st = c->fc->streams[c->fc->nb_streams-1];
2358 version = avio_r8(pb);
2359 flags = avio_rb24(pb);
2360 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2366 avio_rb32(pb); /* creation time */
2367 avio_rb32(pb); /* modification time */
2369 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2370 avio_rb32(pb); /* reserved */
2372 /* highlevel (considering edits) duration in movie timebase */
2373 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2374 avio_rb32(pb); /* reserved */
2375 avio_rb32(pb); /* reserved */
2377 avio_rb16(pb); /* layer */
2378 avio_rb16(pb); /* alternate group */
2379 avio_rb16(pb); /* volume */
2380 avio_rb16(pb); /* reserved */
2382 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2383 // they're kept in fixed point format through all calculations
2384 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2385 // side data, but the scale factor is not needed to calculate aspect ratio
2386 for (i = 0; i < 3; i++) {
2387 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2388 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2389 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2392 width = avio_rb32(pb); // 16.16 fixed point track width
2393 height = avio_rb32(pb); // 16.16 fixed point track height
2394 sc->width = width >> 16;
2395 sc->height = height >> 16;
2397 // save the matrix when it is not the default identity
2398 if (display_matrix[0][0] != (1 << 16) ||
2399 display_matrix[1][1] != (1 << 16) ||
2400 display_matrix[2][2] != (1 << 30) ||
2401 display_matrix[0][1] || display_matrix[0][2] ||
2402 display_matrix[1][0] || display_matrix[1][2] ||
2403 display_matrix[2][0] || display_matrix[2][1]) {
2406 av_freep(&sc->display_matrix);
2407 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2408 if (!sc->display_matrix)
2409 return AVERROR(ENOMEM);
2411 for (i = 0; i < 3; i++)
2412 for (j = 0; j < 3; j++)
2413 sc->display_matrix[i * 3 + j] = display_matrix[j][i];
2416 // transform the display width/height according to the matrix
2417 // skip this if the display matrix is the default identity matrix
2418 // or if it is rotating the picture, ex iPhone 3GS
2419 // to keep the same scale, use [width height 1<<16]
2420 if (width && height &&
2421 ((display_matrix[0][0] != 65536 ||
2422 display_matrix[1][1] != 65536) &&
2423 !display_matrix[0][1] &&
2424 !display_matrix[1][0] &&
2425 !display_matrix[2][0] && !display_matrix[2][1])) {
2426 for (i = 0; i < 2; i++)
2428 (int64_t) width * display_matrix[0][i] +
2429 (int64_t) height * display_matrix[1][i] +
2430 ((int64_t) display_matrix[2][i] << 16);
2432 //sample aspect ratio is new width/height divided by old width/height
2433 st->sample_aspect_ratio = av_d2q(
2434 ((double) disp_transform[0] * height) /
2435 ((double) disp_transform[1] * width), INT_MAX);
2440 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2442 MOVFragment *frag = &c->fragment;
2443 MOVTrackExt *trex = NULL;
2444 int flags, track_id, i;
2446 avio_r8(pb); /* version */
2447 flags = avio_rb24(pb);
2449 track_id = avio_rb32(pb);
2451 return AVERROR_INVALIDDATA;
2452 frag->track_id = track_id;
2453 for (i = 0; i < c->trex_count; i++)
2454 if (c->trex_data[i].track_id == frag->track_id) {
2455 trex = &c->trex_data[i];
2459 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2460 return AVERROR_INVALIDDATA;
2463 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2464 avio_rb64(pb) : frag->moof_offset;
2465 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2467 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2468 avio_rb32(pb) : trex->duration;
2469 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2470 avio_rb32(pb) : trex->size;
2471 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2472 avio_rb32(pb) : trex->flags;
2473 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2477 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2479 c->chapter_track = avio_rb32(pb);
2483 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2488 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2489 return AVERROR_INVALIDDATA;
2490 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2491 sizeof(*c->trex_data))) < 0) {
2495 trex = &c->trex_data[c->trex_count++];
2496 avio_r8(pb); /* version */
2497 avio_rb24(pb); /* flags */
2498 trex->track_id = avio_rb32(pb);
2499 trex->stsd_id = avio_rb32(pb);
2500 trex->duration = avio_rb32(pb);
2501 trex->size = avio_rb32(pb);
2502 trex->flags = avio_rb32(pb);
2506 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2508 MOVFragment *frag = &c->fragment;
2509 AVStream *st = NULL;
2510 MOVStreamContext *sc;
2514 int data_offset = 0;
2515 unsigned entries, first_sample_flags = frag->flags;
2516 int flags, distance, i, found_keyframe = 0, err;
2518 for (i = 0; i < c->fc->nb_streams; i++) {
2519 if (c->fc->streams[i]->id == frag->track_id) {
2520 st = c->fc->streams[i];
2525 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2526 return AVERROR_INVALIDDATA;
2529 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2531 avio_r8(pb); /* version */
2532 flags = avio_rb24(pb);
2533 entries = avio_rb32(pb);
2534 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2536 /* Always assume the presence of composition time offsets.
2537 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2538 * 1) in the initial movie, there are no samples.
2539 * 2) in the first movie fragment, there is only one sample without composition time offset.
2540 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2541 if (!sc->ctts_count && sc->sample_count)
2543 /* Complement ctts table if moov atom doesn't have ctts atom. */
2544 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2546 return AVERROR(ENOMEM);
2547 sc->ctts_data = ctts_data;
2548 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2549 sc->ctts_data[sc->ctts_count].duration = 0;
2552 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2553 return AVERROR_INVALIDDATA;
2554 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2555 sizeof(*sc->ctts_data))) < 0) {
2559 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2560 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2561 dts = sc->track_end - sc->time_offset;
2562 offset = frag->base_data_offset + data_offset;
2564 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2565 for (i = 0; i < entries && !pb->eof_reached; i++) {
2566 unsigned sample_size = frag->size;
2567 int sample_flags = i ? frag->flags : first_sample_flags;
2568 unsigned sample_duration = frag->duration;
2571 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2572 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2573 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2574 sc->ctts_data[sc->ctts_count].count = 1;
2575 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2578 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2580 else if (!found_keyframe)
2581 keyframe = found_keyframe =
2582 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2583 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2586 av_add_index_entry(st, offset, dts, sample_size, distance,
2587 keyframe ? AVINDEX_KEYFRAME : 0);
2588 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2589 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2590 offset, dts, sample_size, distance, keyframe);
2592 dts += sample_duration;
2593 offset += sample_size;
2594 sc->data_size += sample_size;
2597 if (pb->eof_reached)
2600 frag->moof_offset = offset;
2601 st->duration = sc->track_end = dts + sc->time_offset;
2605 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2606 /* like the files created with Adobe Premiere 5.0, for samples see */
2607 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2608 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2613 return 0; /* continue */
2614 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2615 avio_skip(pb, atom.size - 4);
2618 atom.type = avio_rl32(pb);
2620 if (atom.type != MKTAG('m','d','a','t')) {
2621 avio_skip(pb, atom.size);
2624 err = mov_read_mdat(c, pb, atom);
2628 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2633 uint8_t *moov_data; /* uncompressed data */
2634 long cmov_len, moov_len;
2637 avio_rb32(pb); /* dcom atom */
2638 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2639 return AVERROR_INVALIDDATA;
2640 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2641 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2642 return AVERROR_INVALIDDATA;
2644 avio_rb32(pb); /* cmvd atom */
2645 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2646 return AVERROR_INVALIDDATA;
2647 moov_len = avio_rb32(pb); /* uncompressed size */
2648 cmov_len = atom.size - 6 * 4;
2650 cmov_data = av_malloc(cmov_len);
2652 return AVERROR(ENOMEM);
2653 moov_data = av_malloc(moov_len);
2656 return AVERROR(ENOMEM);
2658 avio_read(pb, cmov_data, cmov_len);
2659 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2660 goto free_and_return;
2661 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2662 goto free_and_return;
2663 atom.type = MKTAG('m','o','o','v');
2664 atom.size = moov_len;
2665 ret = mov_read_default(c, &ctx, atom);
2671 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2672 return AVERROR(ENOSYS);
2676 /* edit list atom */
2677 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2679 MOVStreamContext *sc;
2680 int i, edit_count, version;
2682 if (c->fc->nb_streams < 1)
2684 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2686 version = avio_r8(pb); /* version */
2687 avio_rb24(pb); /* flags */
2688 edit_count = avio_rb32(pb); /* entries */
2690 if ((uint64_t)edit_count*12+8 > atom.size)
2691 return AVERROR_INVALIDDATA;
2693 for (i=0; i<edit_count; i++){
2697 duration = avio_rb64(pb);
2698 time = avio_rb64(pb);
2700 duration = avio_rb32(pb); /* segment duration */
2701 time = (int32_t)avio_rb32(pb); /* media time */
2703 avio_rb32(pb); /* Media rate */
2704 if (i == 0 && time >= -1) {
2705 sc->time_offset = time != -1 ? time : -duration;
2710 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2711 "a/v desync might occur, patch welcome\n");
2713 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2717 static const MOVParseTableEntry mov_default_parse_table[] = {
2718 { MKTAG('a','v','s','s'), mov_read_extradata },
2719 { MKTAG('c','h','p','l'), mov_read_chpl },
2720 { MKTAG('c','o','6','4'), mov_read_stco },
2721 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2722 { MKTAG('d','i','n','f'), mov_read_default },
2723 { MKTAG('d','r','e','f'), mov_read_dref },
2724 { MKTAG('e','d','t','s'), mov_read_default },
2725 { MKTAG('e','l','s','t'), mov_read_elst },
2726 { MKTAG('e','n','d','a'), mov_read_enda },
2727 { MKTAG('f','i','e','l'), mov_read_fiel },
2728 { MKTAG('f','t','y','p'), mov_read_ftyp },
2729 { MKTAG('g','l','b','l'), mov_read_glbl },
2730 { MKTAG('h','d','l','r'), mov_read_hdlr },
2731 { MKTAG('i','l','s','t'), mov_read_ilst },
2732 { MKTAG('j','p','2','h'), mov_read_extradata },
2733 { MKTAG('m','d','a','t'), mov_read_mdat },
2734 { MKTAG('m','d','h','d'), mov_read_mdhd },
2735 { MKTAG('m','d','i','a'), mov_read_default },
2736 { MKTAG('m','e','t','a'), mov_read_meta },
2737 { MKTAG('m','i','n','f'), mov_read_default },
2738 { MKTAG('m','o','o','f'), mov_read_moof },
2739 { MKTAG('m','o','o','v'), mov_read_moov },
2740 { MKTAG('m','v','e','x'), mov_read_default },
2741 { MKTAG('m','v','h','d'), mov_read_mvhd },
2742 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2743 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2744 { MKTAG('a','v','c','C'), mov_read_glbl },
2745 { MKTAG('p','a','s','p'), mov_read_pasp },
2746 { MKTAG('s','t','b','l'), mov_read_default },
2747 { MKTAG('s','t','c','o'), mov_read_stco },
2748 { MKTAG('s','t','p','s'), mov_read_stps },
2749 { MKTAG('s','t','r','f'), mov_read_strf },
2750 { MKTAG('s','t','s','c'), mov_read_stsc },
2751 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2752 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2753 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2754 { MKTAG('s','t','t','s'), mov_read_stts },
2755 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2756 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2757 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2758 { MKTAG('t','r','a','k'), mov_read_trak },
2759 { MKTAG('t','r','a','f'), mov_read_default },
2760 { MKTAG('t','r','e','f'), mov_read_default },
2761 { MKTAG('c','h','a','p'), mov_read_chap },
2762 { MKTAG('t','r','e','x'), mov_read_trex },
2763 { MKTAG('t','r','u','n'), mov_read_trun },
2764 { MKTAG('u','d','t','a'), mov_read_default },
2765 { MKTAG('w','a','v','e'), mov_read_wave },
2766 { MKTAG('e','s','d','s'), mov_read_esds },
2767 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2768 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2769 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2770 { MKTAG('w','f','e','x'), mov_read_wfex },
2771 { MKTAG('c','m','o','v'), mov_read_cmov },
2772 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2773 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2774 { MKTAG('s','b','g','p'), mov_read_sbgp },
2775 { MKTAG('h','v','c','C'), mov_read_glbl },
2776 { MKTAG('-','-','-','-'), mov_read_custom },
2780 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2782 int64_t total_size = 0;
2787 atom.size = INT64_MAX;
2788 while (total_size + 8 < atom.size && !pb->eof_reached) {
2789 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
2792 if (atom.size >= 8) {
2793 a.size = avio_rb32(pb);
2794 a.type = avio_rl32(pb);
2796 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
2797 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
2799 if (a.size == 1) { /* 64 bit extended size */
2800 a.size = avio_rb64(pb) - 8;
2804 a.size = atom.size - total_size;
2811 a.size = FFMIN(a.size, atom.size - total_size);
2813 for (i = 0; mov_default_parse_table[i].type; i++)
2814 if (mov_default_parse_table[i].type == a.type) {
2815 parse = mov_default_parse_table[i].parse;
2819 // container is user data
2820 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
2821 atom.type == MKTAG('i','l','s','t')))
2822 parse = mov_read_udta_string;
2824 if (!parse) { /* skip leaf atoms data */
2825 avio_skip(pb, a.size);
2827 int64_t start_pos = avio_tell(pb);
2829 int err = parse(c, pb, a);
2832 if (c->found_moov && c->found_mdat &&
2833 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
2834 start_pos + a.size == avio_size(pb))) {
2835 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
2836 c->next_root_atom = start_pos + a.size;
2839 left = a.size - avio_tell(pb) + start_pos;
2840 if (left > 0) /* skip garbage at atom end */
2841 avio_skip(pb, left);
2842 else if (left < 0) {
2843 av_log(c->fc, AV_LOG_WARNING,
2844 "overread end of atom '%.4s' by %"PRId64" bytes\n",
2845 (char*)&a.type, -left);
2846 avio_seek(pb, left, SEEK_CUR);
2850 total_size += a.size;
2853 if (total_size < atom.size && atom.size < 0x7ffff)
2854 avio_skip(pb, atom.size - total_size);
2859 static int mov_probe(AVProbeData *p)
2861 unsigned int offset;
2865 /* check file header */
2868 /* ignore invalid offset */
2869 if ((offset + 8) > (unsigned int)p->buf_size)
2871 tag = AV_RL32(p->buf + offset + 4);
2873 /* check for obvious tags */
2874 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2875 case MKTAG('m','o','o','v'):
2876 case MKTAG('m','d','a','t'):
2877 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2878 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2879 case MKTAG('f','t','y','p'):
2880 return AVPROBE_SCORE_MAX;
2881 /* those are more common words, so rate then a bit less */
2882 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2883 case MKTAG('w','i','d','e'):
2884 case MKTAG('f','r','e','e'):
2885 case MKTAG('j','u','n','k'):
2886 case MKTAG('p','i','c','t'):
2887 return AVPROBE_SCORE_MAX - 5;
2888 case MKTAG(0x82,0x82,0x7f,0x7d):
2889 case MKTAG('s','k','i','p'):
2890 case MKTAG('u','u','i','d'):
2891 case MKTAG('p','r','f','l'):
2892 offset = AV_RB32(p->buf+offset) + offset;
2893 /* if we only find those cause probedata is too small at least rate them */
2894 score = AVPROBE_SCORE_EXTENSION;
2897 /* unrecognized tag */
2903 // must be done after parsing all trak because there's no order requirement
2904 static void mov_read_chapters(AVFormatContext *s)
2906 MOVContext *mov = s->priv_data;
2907 AVStream *st = NULL;
2908 MOVStreamContext *sc;
2912 for (i = 0; i < s->nb_streams; i++)
2913 if (s->streams[i]->id == mov->chapter_track) {
2918 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2922 st->discard = AVDISCARD_ALL;
2924 cur_pos = avio_tell(sc->pb);
2926 for (i = 0; i < st->nb_index_entries; i++) {
2927 AVIndexEntry *sample = &st->index_entries[i];
2928 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2933 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2934 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2938 // the first two bytes are the length of the title
2939 len = avio_rb16(sc->pb);
2940 if (len > sample->size-2)
2942 title_len = 2*len + 1;
2943 if (!(title = av_mallocz(title_len)))
2946 // The samples could theoretically be in any encoding if there's an encd
2947 // atom following, but in practice are only utf-8 or utf-16, distinguished
2948 // instead by the presence of a BOM
2952 ch = avio_rb16(sc->pb);
2954 avio_get_str16be(sc->pb, len, title, title_len);
2955 else if (ch == 0xfffe)
2956 avio_get_str16le(sc->pb, len, title, title_len);
2959 if (len == 1 || len == 2)
2962 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
2966 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2970 avio_seek(sc->pb, cur_pos, SEEK_SET);
2973 static int mov_read_close(AVFormatContext *s)
2975 MOVContext *mov = s->priv_data;
2978 for (i = 0; i < s->nb_streams; i++) {
2979 AVStream *st = s->streams[i];
2980 MOVStreamContext *sc = st->priv_data;
2982 av_freep(&sc->ctts_data);
2983 for (j = 0; j < sc->drefs_count; j++) {
2984 av_freep(&sc->drefs[j].path);
2985 av_freep(&sc->drefs[j].dir);
2987 av_freep(&sc->drefs);
2988 if (sc->pb && sc->pb != s->pb)
2991 av_freep(&sc->chunk_offsets);
2992 av_freep(&sc->stsc_data);
2993 av_freep(&sc->sample_sizes);
2994 av_freep(&sc->keyframes);
2995 av_freep(&sc->stts_data);
2996 av_freep(&sc->stps_data);
2997 av_freep(&sc->rap_group);
2998 av_freep(&sc->display_matrix);
3001 if (mov->dv_demux) {
3002 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
3003 av_freep(&mov->dv_fctx->streams[i]->codec);
3004 av_freep(&mov->dv_fctx->streams[i]);
3006 av_freep(&mov->dv_fctx);
3007 av_freep(&mov->dv_demux);
3010 av_freep(&mov->trex_data);
3015 static int mov_read_header(AVFormatContext *s)
3017 MOVContext *mov = s->priv_data;
3018 AVIOContext *pb = s->pb;
3020 MOVAtom atom = { AV_RL32("root") };
3024 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3026 atom.size = avio_size(pb);
3028 atom.size = INT64_MAX;
3030 /* check MOV header */
3031 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3032 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3036 if (!mov->found_moov) {
3037 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3039 return AVERROR_INVALIDDATA;
3041 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3043 if (pb->seekable && mov->chapter_track > 0)
3044 mov_read_chapters(s);
3046 for (i = 0; i < s->nb_streams; i++) {
3047 AVStream *st = s->streams[i];
3048 MOVStreamContext *sc = st->priv_data;
3050 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3051 if (st->codec->width <= 0 && st->codec->width <= 0) {
3052 st->codec->width = sc->width;
3053 st->codec->height = sc->height;
3055 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3056 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3062 if (mov->trex_data) {
3063 for (i = 0; i < s->nb_streams; i++) {
3064 AVStream *st = s->streams[i];
3065 MOVStreamContext *sc = st->priv_data;
3066 if (st->duration > 0)
3067 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3071 for (i = 0; i < s->nb_streams; i++) {
3072 AVStream *st = s->streams[i];
3073 MOVStreamContext *sc = st->priv_data;
3075 switch (st->codec->codec_type) {
3076 case AVMEDIA_TYPE_AUDIO:
3077 err = ff_replaygain_export(st, s->metadata);
3083 case AVMEDIA_TYPE_VIDEO:
3084 if (sc->display_matrix) {
3085 AVPacketSideData *sd, *tmp;
3087 tmp = av_realloc_array(st->side_data,
3088 st->nb_side_data + 1, sizeof(*tmp));
3090 return AVERROR(ENOMEM);
3092 st->side_data = tmp;
3095 sd = &st->side_data[st->nb_side_data - 1];
3096 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
3097 sd->size = sizeof(int32_t) * 9;
3098 sd->data = (uint8_t*)sc->display_matrix;
3099 sc->display_matrix = NULL;
3108 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3110 AVIndexEntry *sample = NULL;
3111 int64_t best_dts = INT64_MAX;
3113 for (i = 0; i < s->nb_streams; i++) {
3114 AVStream *avst = s->streams[i];
3115 MOVStreamContext *msc = avst->priv_data;
3116 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3117 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3118 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3119 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3120 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3122 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3123 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3124 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3125 sample = current_sample;
3134 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3136 MOVContext *mov = s->priv_data;
3137 MOVStreamContext *sc;
3138 AVIndexEntry *sample;
3139 AVStream *st = NULL;
3142 sample = mov_find_next_sample(s, &st);
3144 mov->found_mdat = 0;
3145 if (!mov->next_root_atom)
3147 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3148 mov->next_root_atom = 0;
3149 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3152 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3156 /* must be done just before reading, to avoid infinite loop on sample */
3157 sc->current_sample++;
3159 if (st->discard != AVDISCARD_ALL) {
3160 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3161 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3162 sc->ffindex, sample->pos);
3163 return AVERROR_INVALIDDATA;
3165 ret = av_get_packet(sc->pb, pkt, sample->size);
3168 if (sc->has_palette) {
3171 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3173 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3175 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3176 sc->has_palette = 0;
3179 #if CONFIG_DV_DEMUXER
3180 if (mov->dv_demux && sc->dv_audio_container) {
3181 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
3184 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3191 pkt->stream_index = sc->ffindex;
3192 pkt->dts = sample->timestamp;
3193 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3194 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3195 /* update ctts context */
3197 if (sc->ctts_index < sc->ctts_count &&
3198 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3200 sc->ctts_sample = 0;
3203 pkt->dts = AV_NOPTS_VALUE;
3205 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3206 st->index_entries[sc->current_sample].timestamp : st->duration;
3207 pkt->duration = next_dts - pkt->dts;
3208 pkt->pts = pkt->dts;
3210 if (st->discard == AVDISCARD_ALL)
3212 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3213 pkt->pos = sample->pos;
3214 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3215 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3219 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3221 MOVStreamContext *sc = st->priv_data;
3222 int sample, time_sample;
3225 sample = av_index_search_timestamp(st, timestamp, flags);
3226 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3227 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3229 if (sample < 0) /* not sure what to do */
3230 return AVERROR_INVALIDDATA;
3231 sc->current_sample = sample;
3232 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3233 /* adjust ctts index */
3234 if (sc->ctts_data) {
3236 for (i = 0; i < sc->ctts_count; i++) {
3237 int next = time_sample + sc->ctts_data[i].count;
3238 if (next > sc->current_sample) {
3240 sc->ctts_sample = sc->current_sample - time_sample;
3249 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3252 int64_t seek_timestamp, timestamp;
3256 if (stream_index >= s->nb_streams)
3257 return AVERROR_INVALIDDATA;
3258 if (sample_time < 0)
3261 st = s->streams[stream_index];
3262 sample = mov_seek_stream(s, st, sample_time, flags);
3266 /* adjust seek timestamp to found sample timestamp */
3267 seek_timestamp = st->index_entries[sample].timestamp;
3269 for (i = 0; i < s->nb_streams; i++) {
3271 if (stream_index == i)
3274 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3275 mov_seek_stream(s, st, timestamp, flags);
3280 AVInputFormat ff_mov_demuxer = {
3281 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3282 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3283 .priv_data_size = sizeof(MOVContext),
3284 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
3285 .read_probe = mov_probe,
3286 .read_header = mov_read_header,
3287 .read_packet = mov_read_packet,
3288 .read_close = mov_read_close,
3289 .read_seek = mov_read_seek,