3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * This file is part of Libav.
8 * Libav is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * Libav is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with Libav; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 //#define MOV_EXPORT_ALL_METADATA
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/intfloat.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/dict.h"
35 #include "avio_internal.h"
38 #include "libavcodec/get_bits.h"
47 * First version by Francois Revol revol@free.fr
48 * Seek function by Gael Chardon gael.dev@4now.net
51 #include "qtpalette.h"
57 /* those functions parse an atom */
58 /* links atom IDs to parse functions */
59 typedef struct MOVParseTableEntry {
61 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
64 static const MOVParseTableEntry mov_default_parse_table[];
66 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
67 unsigned len, const char *key)
72 avio_rb16(pb); // unknown
73 current = avio_rb16(pb);
74 total = avio_rb16(pb);
76 snprintf(buf, sizeof(buf), "%d", current);
78 snprintf(buf, sizeof(buf), "%d/%d", current, total);
79 av_dict_set(&c->fc->metadata, key, buf, 0);
84 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
85 unsigned len, const char *key)
89 /* bypass padding bytes */
94 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
95 av_dict_set(&c->fc->metadata, key, buf, 0);
100 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
101 unsigned len, const char *key)
105 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
106 av_dict_set(&c->fc->metadata, key, buf, 0);
111 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
112 unsigned len, const char *key)
117 avio_r8(pb); // unknown
120 if (genre < 1 || genre > ID3v1_GENRE_MAX)
122 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
123 av_dict_set(&c->fc->metadata, key, buf, 0);
128 static const uint32_t mac_to_unicode[128] = {
129 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
130 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
131 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
132 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
133 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
134 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
135 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
136 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
137 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
138 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
139 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
140 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
141 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
142 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
143 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
144 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
147 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
148 char *dst, int dstlen)
151 char *end = dst+dstlen-1;
154 for (i = 0; i < len; i++) {
155 uint8_t t, c = avio_r8(pb);
156 if (c < 0x80 && p < end)
159 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
165 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
167 #ifdef MOV_EXPORT_ALL_METADATA
170 char str[1024], key2[16], language[4] = {0};
171 const char *key = NULL;
172 uint16_t str_size, langcode = 0;
173 uint32_t data_type = 0;
174 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
177 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
178 case MKTAG(0xa9,'a','u','t'):
179 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
180 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
181 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
182 case MKTAG( 'c','p','r','t'):
183 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
184 case MKTAG(0xa9,'c','m','t'):
185 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
186 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
187 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
188 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
189 case MKTAG( 'g','n','r','e'): key = "genre";
190 parse = mov_metadata_gnre; break;
191 case MKTAG(0xa9,'t','o','o'):
192 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
193 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
194 case MKTAG( 'd','e','s','c'): key = "description";break;
195 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
196 case MKTAG( 't','v','s','h'): key = "show"; break;
197 case MKTAG( 't','v','e','n'): key = "episode_id";break;
198 case MKTAG( 't','v','n','n'): key = "network"; break;
199 case MKTAG( 't','r','k','n'): key = "track";
200 parse = mov_metadata_track_or_disc_number; break;
201 case MKTAG( 'd','i','s','k'): key = "disc";
202 parse = mov_metadata_track_or_disc_number; break;
203 case MKTAG( 't','v','e','s'): key = "episode_sort";
204 parse = mov_metadata_int8_bypass_padding; break;
205 case MKTAG( 't','v','s','n'): key = "season_number";
206 parse = mov_metadata_int8_bypass_padding; break;
207 case MKTAG( 's','t','i','k'): key = "media_type";
208 parse = mov_metadata_int8_no_padding; break;
209 case MKTAG( 'h','d','v','d'): key = "hd_video";
210 parse = mov_metadata_int8_no_padding; break;
211 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
212 parse = mov_metadata_int8_no_padding; break;
215 if (c->itunes_metadata && atom.size > 8) {
216 int data_size = avio_rb32(pb);
217 int tag = avio_rl32(pb);
218 if (tag == MKTAG('d','a','t','a')) {
219 data_type = avio_rb32(pb); // type
220 avio_rb32(pb); // unknown
221 str_size = data_size - 16;
224 } else if (atom.size > 4 && key && !c->itunes_metadata) {
225 str_size = avio_rb16(pb); // string length
226 langcode = avio_rb16(pb);
227 ff_mov_lang_to_iso639(langcode, language);
230 str_size = atom.size;
232 #ifdef MOV_EXPORT_ALL_METADATA
234 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
244 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
247 parse(c, pb, str_size, key);
249 if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
250 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
252 avio_read(pb, str, str_size);
255 av_dict_set(&c->fc->metadata, key, str, 0);
256 if (*language && strcmp(language, "und")) {
257 snprintf(key2, sizeof(key2), "%s-%s", key, language);
258 av_dict_set(&c->fc->metadata, key2, str, 0);
261 av_dlog(c->fc, "lang \"%3s\" ", language);
262 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
263 key, str, (char*)&atom.type, str_size, atom.size);
268 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
271 int i, nb_chapters, str_len, version;
274 if ((atom.size -= 5) < 0)
277 version = avio_r8(pb);
280 avio_rb32(pb); // ???
281 nb_chapters = avio_r8(pb);
283 for (i = 0; i < nb_chapters; i++) {
287 start = avio_rb64(pb);
288 str_len = avio_r8(pb);
290 if ((atom.size -= 9+str_len) < 0)
293 avio_read(pb, str, str_len);
295 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
300 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
302 int64_t total_size = 0;
307 atom.size = INT64_MAX;
308 while (total_size + 8 < atom.size && !pb->eof_reached) {
309 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
312 if (atom.size >= 8) {
313 a.size = avio_rb32(pb);
314 a.type = avio_rl32(pb);
316 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
317 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
319 if (a.size == 1) { /* 64 bit extended size */
320 a.size = avio_rb64(pb) - 8;
324 a.size = atom.size - total_size;
331 a.size = FFMIN(a.size, atom.size - total_size);
333 for (i = 0; mov_default_parse_table[i].type; i++)
334 if (mov_default_parse_table[i].type == a.type) {
335 parse = mov_default_parse_table[i].parse;
339 // container is user data
340 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
341 atom.type == MKTAG('i','l','s','t')))
342 parse = mov_read_udta_string;
344 if (!parse) { /* skip leaf atoms data */
345 avio_skip(pb, a.size);
347 int64_t start_pos = avio_tell(pb);
349 int err = parse(c, pb, a);
352 if (c->found_moov && c->found_mdat &&
353 (!pb->seekable || start_pos + a.size == avio_size(pb)))
355 left = a.size - avio_tell(pb) + start_pos;
356 if (left > 0) /* skip garbage at atom end */
360 total_size += a.size;
363 if (total_size < atom.size && atom.size < 0x7ffff)
364 avio_skip(pb, atom.size - total_size);
369 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
372 MOVStreamContext *sc;
375 if (c->fc->nb_streams < 1)
377 st = c->fc->streams[c->fc->nb_streams-1];
380 avio_rb32(pb); // version + flags
381 entries = avio_rb32(pb);
382 if (entries >= UINT_MAX / sizeof(*sc->drefs))
384 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
386 return AVERROR(ENOMEM);
387 sc->drefs_count = entries;
389 for (i = 0; i < sc->drefs_count; i++) {
390 MOVDref *dref = &sc->drefs[i];
391 uint32_t size = avio_rb32(pb);
392 int64_t next = avio_tell(pb) + size - 4;
397 dref->type = avio_rl32(pb);
398 avio_rb32(pb); // version + flags
399 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
401 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
402 /* macintosh alias record */
403 uint16_t volume_len, len;
408 volume_len = avio_r8(pb);
409 volume_len = FFMIN(volume_len, 27);
410 avio_read(pb, dref->volume, 27);
411 dref->volume[volume_len] = 0;
412 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
417 len = FFMIN(len, 63);
418 avio_read(pb, dref->filename, 63);
419 dref->filename[len] = 0;
420 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
424 /* read next level up_from_alias/down_to_target */
425 dref->nlvl_from = avio_rb16(pb);
426 dref->nlvl_to = avio_rb16(pb);
427 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
428 dref->nlvl_from, dref->nlvl_to);
432 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
433 type = avio_rb16(pb);
435 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
438 if (type == 2) { // absolute path
440 dref->path = av_mallocz(len+1);
442 return AVERROR(ENOMEM);
443 avio_read(pb, dref->path, len);
444 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
446 memmove(dref->path, dref->path+volume_len, len);
449 for (j = 0; j < len; j++)
450 if (dref->path[j] == ':')
452 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
453 } else if (type == 0) { // directory name
455 dref->dir = av_malloc(len+1);
457 return AVERROR(ENOMEM);
458 avio_read(pb, dref->dir, len);
460 for (j = 0; j < len; j++)
461 if (dref->dir[j] == ':')
463 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
468 avio_seek(pb, next, SEEK_SET);
473 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
477 uint32_t av_unused ctype;
479 if (c->fc->nb_streams < 1) // meta before first trak
482 st = c->fc->streams[c->fc->nb_streams-1];
484 avio_r8(pb); /* version */
485 avio_rb24(pb); /* flags */
488 ctype = avio_rl32(pb);
489 type = avio_rl32(pb); /* component subtype */
491 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
492 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
494 if (type == MKTAG('v','i','d','e'))
495 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
496 else if (type == MKTAG('s','o','u','n'))
497 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
498 else if (type == MKTAG('m','1','a',' '))
499 st->codec->codec_id = CODEC_ID_MP2;
500 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
501 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
503 avio_rb32(pb); /* component manufacture */
504 avio_rb32(pb); /* component flags */
505 avio_rb32(pb); /* component flags mask */
510 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
515 if (fc->nb_streams < 1)
517 st = fc->streams[fc->nb_streams-1];
519 avio_rb32(pb); /* version + flags */
520 ff_mp4_read_descr(fc, pb, &tag);
521 if (tag == MP4ESDescrTag) {
522 ff_mp4_parse_es_descr(pb, NULL);
524 avio_rb16(pb); /* ID */
526 ff_mp4_read_descr(fc, pb, &tag);
527 if (tag == MP4DecConfigDescrTag)
528 ff_mp4_read_dec_config_descr(fc, st, pb);
532 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
534 return ff_mov_read_esds(c->fc, pb, atom);
537 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
540 int ac3info, acmod, lfeon, bsmod;
542 if (c->fc->nb_streams < 1)
544 st = c->fc->streams[c->fc->nb_streams-1];
546 ac3info = avio_rb24(pb);
547 bsmod = (ac3info >> 14) & 0x7;
548 acmod = (ac3info >> 11) & 0x7;
549 lfeon = (ac3info >> 10) & 0x1;
550 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
551 st->codec->audio_service_type = bsmod;
552 if (st->codec->channels > 1 && bsmod == 0x7)
553 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
558 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
562 uint32_t flags, layout_tag, bitmap, num_descr;
564 if (c->fc->nb_streams < 1)
566 st = c->fc->streams[c->fc->nb_streams-1];
571 version = avio_r8(pb);
572 flags = avio_rb24(pb);
574 layout_tag = avio_rb32(pb);
575 bitmap = avio_rb32(pb);
576 num_descr = avio_rb32(pb);
578 if (atom.size < 16ULL + num_descr * 20ULL)
581 av_dlog(c->fc, "chan: size=%ld version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
582 atom.size, version, flags, layout_tag, bitmap, num_descr);
585 /* TODO: use the channel descriptions if the layout tag is 0 */
587 for (i = 0; i < num_descr; i++) {
588 uint32_t label, cflags;
590 label = avio_rb32(pb); // mChannelLabel
591 cflags = avio_rb32(pb); // mChannelFlags
592 AV_WN32(&coords[0], avio_rl32(pb)); // mCoordinates[0]
593 AV_WN32(&coords[1], avio_rl32(pb)); // mCoordinates[1]
594 AV_WN32(&coords[2], avio_rl32(pb)); // mCoordinates[2]
598 st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
603 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
607 if (c->fc->nb_streams < 1)
609 st = c->fc->streams[c->fc->nb_streams-1];
611 ff_get_wav_header(pb, st->codec, atom.size);
616 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
618 const int num = avio_rb32(pb);
619 const int den = avio_rb32(pb);
622 if (c->fc->nb_streams < 1)
624 st = c->fc->streams[c->fc->nb_streams-1];
626 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
627 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
628 av_log(c->fc, AV_LOG_WARNING,
629 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
630 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
632 } else if (den != 0) {
633 st->sample_aspect_ratio.num = num;
634 st->sample_aspect_ratio.den = den;
639 /* this atom contains actual media data */
640 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
642 if (atom.size == 0) /* wrong one (MP4) */
645 return 0; /* now go for moov */
648 /* read major brand, minor version and compatible brands and store them as metadata */
649 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
653 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
654 char* comp_brands_str;
655 uint8_t type[5] = {0};
657 avio_read(pb, type, 4);
658 if (strcmp(type, "qt "))
660 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
661 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
662 minor_ver = avio_rb32(pb); /* minor version */
663 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
664 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
666 comp_brand_size = atom.size - 8;
667 if (comp_brand_size < 0)
669 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
670 if (!comp_brands_str)
671 return AVERROR(ENOMEM);
672 avio_read(pb, comp_brands_str, comp_brand_size);
673 comp_brands_str[comp_brand_size] = 0;
674 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
675 av_freep(&comp_brands_str);
680 /* this atom should contain all header atoms */
681 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
683 if (mov_read_default(c, pb, atom) < 0)
685 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
686 /* so we don't parse the whole file if over a network */
688 return 0; /* now go for mdat */
691 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
693 c->fragment.moof_offset = avio_tell(pb) - 8;
694 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
695 return mov_read_default(c, pb, atom);
698 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
703 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
706 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
707 av_dict_set(metadata, "creation_time", buffer, 0);
711 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
714 MOVStreamContext *sc;
716 char language[4] = {0};
718 time_t creation_time;
720 if (c->fc->nb_streams < 1)
722 st = c->fc->streams[c->fc->nb_streams-1];
725 version = avio_r8(pb);
727 return -1; /* unsupported */
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))
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 CODEC_ID_PCM_S24BE:
826 st->codec->codec_id = CODEC_ID_PCM_S24LE;
828 case CODEC_ID_PCM_S32BE:
829 st->codec->codec_id = CODEC_ID_PCM_S32LE;
831 case CODEC_ID_PCM_F32BE:
832 st->codec->codec_id = CODEC_ID_PCM_F32LE;
834 case CODEC_ID_PCM_F64BE:
835 st->codec->codec_id = 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)
885 if (c->fc->nb_streams < 1) // will happen with jp2 files
887 st= c->fc->streams[c->fc->nb_streams-1];
888 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
889 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
891 buf= av_realloc(st->codec->extradata, size);
894 st->codec->extradata= buf;
895 buf+= st->codec->extradata_size;
896 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
897 AV_WB32( buf , atom.size + 8);
898 AV_WL32( buf + 4, atom.type);
899 avio_read(pb, buf + 8, atom.size);
903 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
907 if (c->fc->nb_streams < 1)
909 st = c->fc->streams[c->fc->nb_streams-1];
911 if ((uint64_t)atom.size > (1<<30))
914 if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
915 // pass all frma atom to codec, needed at least for QDMC and QDM2
916 av_free(st->codec->extradata);
917 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
918 if (!st->codec->extradata)
919 return AVERROR(ENOMEM);
920 st->codec->extradata_size = atom.size;
921 avio_read(pb, st->codec->extradata, atom.size);
922 } else if (atom.size > 8) { /* to read frma, esds atoms */
923 if (mov_read_default(c, pb, atom) < 0)
926 avio_skip(pb, atom.size);
931 * This function reads atom content and puts data in extradata without tag
932 * nor size unlike mov_read_extradata.
934 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
938 if (c->fc->nb_streams < 1)
940 st = c->fc->streams[c->fc->nb_streams-1];
942 if ((uint64_t)atom.size > (1<<30))
945 if (atom.size >= 10) {
946 // Broken files created by legacy versions of Libav and FFmpeg will
947 // wrap a whole fiel atom inside of a glbl atom.
948 unsigned size = avio_rb32(pb);
949 unsigned type = avio_rl32(pb);
950 avio_seek(pb, -8, SEEK_CUR);
951 if (type == MKTAG('f','i','e','l') && size == atom.size)
952 return mov_read_default(c, pb, atom);
954 av_free(st->codec->extradata);
955 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
956 if (!st->codec->extradata)
957 return AVERROR(ENOMEM);
958 st->codec->extradata_size = atom.size;
959 avio_read(pb, st->codec->extradata, atom.size);
964 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
965 * but can have extradata appended at the end after the 40 bytes belonging
968 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
972 if (c->fc->nb_streams < 1)
976 st = c->fc->streams[c->fc->nb_streams-1];
978 if ((uint64_t)atom.size > (1<<30))
981 av_free(st->codec->extradata);
982 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
983 if (!st->codec->extradata)
984 return AVERROR(ENOMEM);
985 st->codec->extradata_size = atom.size - 40;
987 avio_read(pb, st->codec->extradata, atom.size - 40);
991 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
994 MOVStreamContext *sc;
995 unsigned int i, entries;
997 if (c->fc->nb_streams < 1)
999 st = c->fc->streams[c->fc->nb_streams-1];
1002 avio_r8(pb); /* version */
1003 avio_rb24(pb); /* flags */
1005 entries = avio_rb32(pb);
1009 if (entries >= UINT_MAX/sizeof(int64_t))
1012 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1013 if (!sc->chunk_offsets)
1014 return AVERROR(ENOMEM);
1015 sc->chunk_count = entries;
1017 if (atom.type == MKTAG('s','t','c','o'))
1018 for (i=0; i<entries; i++)
1019 sc->chunk_offsets[i] = avio_rb32(pb);
1020 else if (atom.type == MKTAG('c','o','6','4'))
1021 for (i=0; i<entries; i++)
1022 sc->chunk_offsets[i] = avio_rb64(pb);
1030 * Compute codec id for 'lpcm' tag.
1031 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1033 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1035 if (flags & 1) { // floating point
1036 if (flags & 2) { // big endian
1037 if (bps == 32) return CODEC_ID_PCM_F32BE;
1038 else if (bps == 64) return CODEC_ID_PCM_F64BE;
1040 if (bps == 32) return CODEC_ID_PCM_F32LE;
1041 else if (bps == 64) return CODEC_ID_PCM_F64LE;
1047 if (flags & 4) return CODEC_ID_PCM_S8;
1048 else return CODEC_ID_PCM_U8;
1049 else if (bps == 16) return CODEC_ID_PCM_S16BE;
1050 else if (bps == 24) return CODEC_ID_PCM_S24BE;
1051 else if (bps == 32) return CODEC_ID_PCM_S32BE;
1054 if (flags & 4) return CODEC_ID_PCM_S8;
1055 else return CODEC_ID_PCM_U8;
1056 else if (bps == 16) return CODEC_ID_PCM_S16LE;
1057 else if (bps == 24) return CODEC_ID_PCM_S24LE;
1058 else if (bps == 32) return CODEC_ID_PCM_S32LE;
1061 return CODEC_ID_NONE;
1064 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1067 MOVStreamContext *sc;
1068 int j, pseudo_stream_id;
1070 if (c->fc->nb_streams < 1)
1072 st = c->fc->streams[c->fc->nb_streams-1];
1075 for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
1076 //Parsing Sample description table
1079 MOVAtom a = { AV_RL32("stsd") };
1080 int64_t start_pos = avio_tell(pb);
1081 int size = avio_rb32(pb); /* size */
1082 uint32_t format = avio_rl32(pb); /* data format */
1085 avio_rb32(pb); /* reserved */
1086 avio_rb16(pb); /* reserved */
1087 dref_id = avio_rb16(pb);
1090 if (st->codec->codec_tag &&
1091 st->codec->codec_tag != format &&
1092 (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
1093 : st->codec->codec_tag != MKTAG('j','p','e','g'))
1095 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1096 * export it as a separate AVStream but this needs a few changes
1097 * in the MOV demuxer, patch welcome. */
1099 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1100 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1103 /* we cannot demux concatenated h264 streams because of different extradata */
1104 if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1106 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1107 sc->dref_id= dref_id;
1109 st->codec->codec_tag = format;
1110 id = ff_codec_get_id(codec_movaudio_tags, format);
1111 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1112 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1114 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1115 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1116 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1117 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1118 id = ff_codec_get_id(codec_movvideo_tags, format);
1120 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1122 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1123 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){
1124 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1126 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1130 av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1131 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1132 (format >> 24) & 0xff, st->codec->codec_type);
1134 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1135 unsigned int color_depth, len;
1136 int color_greyscale;
1138 st->codec->codec_id = id;
1139 avio_rb16(pb); /* version */
1140 avio_rb16(pb); /* revision level */
1141 avio_rb32(pb); /* vendor */
1142 avio_rb32(pb); /* temporal quality */
1143 avio_rb32(pb); /* spatial quality */
1145 st->codec->width = avio_rb16(pb); /* width */
1146 st->codec->height = avio_rb16(pb); /* height */
1148 avio_rb32(pb); /* horiz resolution */
1149 avio_rb32(pb); /* vert resolution */
1150 avio_rb32(pb); /* data size, always 0 */
1151 avio_rb16(pb); /* frames per samples */
1153 len = avio_r8(pb); /* codec name, pascal string */
1156 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1158 avio_skip(pb, 31 - len);
1159 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1160 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1161 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1163 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1164 st->codec->color_table_id = avio_rb16(pb); /* colortable id */
1165 av_dlog(c->fc, "depth %d, ctab id %d\n",
1166 st->codec->bits_per_coded_sample, st->codec->color_table_id);
1167 /* figure out the palette situation */
1168 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1169 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1171 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1172 if ((color_depth == 2) || (color_depth == 4) ||
1173 (color_depth == 8)) {
1174 /* for palette traversal */
1175 unsigned int color_start, color_count, color_end;
1176 unsigned char r, g, b;
1178 if (color_greyscale) {
1179 int color_index, color_dec;
1180 /* compute the greyscale palette */
1181 st->codec->bits_per_coded_sample = color_depth;
1182 color_count = 1 << color_depth;
1184 color_dec = 256 / (color_count - 1);
1185 for (j = 0; j < color_count; j++) {
1186 r = g = b = color_index;
1188 (r << 16) | (g << 8) | (b);
1189 color_index -= color_dec;
1190 if (color_index < 0)
1193 } else if (st->codec->color_table_id) {
1194 const uint8_t *color_table;
1195 /* if flag bit 3 is set, use the default palette */
1196 color_count = 1 << color_depth;
1197 if (color_depth == 2)
1198 color_table = ff_qt_default_palette_4;
1199 else if (color_depth == 4)
1200 color_table = ff_qt_default_palette_16;
1202 color_table = ff_qt_default_palette_256;
1204 for (j = 0; j < color_count; j++) {
1205 r = color_table[j * 3 + 0];
1206 g = color_table[j * 3 + 1];
1207 b = color_table[j * 3 + 2];
1209 (r << 16) | (g << 8) | (b);
1212 /* load the palette from the file */
1213 color_start = avio_rb32(pb);
1214 color_count = avio_rb16(pb);
1215 color_end = avio_rb16(pb);
1216 if ((color_start <= 255) &&
1217 (color_end <= 255)) {
1218 for (j = color_start; j <= color_end; j++) {
1219 /* each R, G, or B component is 16 bits;
1220 * only use the top 8 bits; skip alpha bytes
1231 (r << 16) | (g << 8) | (b);
1235 sc->has_palette = 1;
1237 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1238 int bits_per_sample, flags;
1239 uint16_t version = avio_rb16(pb);
1241 st->codec->codec_id = id;
1242 avio_rb16(pb); /* revision level */
1243 avio_rb32(pb); /* vendor */
1245 st->codec->channels = avio_rb16(pb); /* channel count */
1246 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1247 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1249 sc->audio_cid = avio_rb16(pb);
1250 avio_rb16(pb); /* packet size = 0 */
1252 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1254 //Read QT version 1 fields. In version 0 these do not exist.
1255 av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1258 sc->samples_per_frame = avio_rb32(pb);
1259 avio_rb32(pb); /* bytes per packet */
1260 sc->bytes_per_frame = avio_rb32(pb);
1261 avio_rb32(pb); /* bytes per sample */
1262 } else if (version==2) {
1263 avio_rb32(pb); /* sizeof struct only */
1264 st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
1265 st->codec->channels = avio_rb32(pb);
1266 avio_rb32(pb); /* always 0x7F000000 */
1267 st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1268 flags = avio_rb32(pb); /* lpcm format specific flag */
1269 sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1270 sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1271 if (format == MKTAG('l','p','c','m'))
1272 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1276 switch (st->codec->codec_id) {
1277 case CODEC_ID_PCM_S8:
1278 case CODEC_ID_PCM_U8:
1279 if (st->codec->bits_per_coded_sample == 16)
1280 st->codec->codec_id = CODEC_ID_PCM_S16BE;
1282 case CODEC_ID_PCM_S16LE:
1283 case CODEC_ID_PCM_S16BE:
1284 if (st->codec->bits_per_coded_sample == 8)
1285 st->codec->codec_id = CODEC_ID_PCM_S8;
1286 else if (st->codec->bits_per_coded_sample == 24)
1287 st->codec->codec_id =
1288 st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1289 CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1291 /* set values for old format before stsd version 1 appeared */
1292 case CODEC_ID_MACE3:
1293 sc->samples_per_frame = 6;
1294 sc->bytes_per_frame = 2*st->codec->channels;
1296 case CODEC_ID_MACE6:
1297 sc->samples_per_frame = 6;
1298 sc->bytes_per_frame = 1*st->codec->channels;
1300 case CODEC_ID_ADPCM_IMA_QT:
1301 sc->samples_per_frame = 64;
1302 sc->bytes_per_frame = 34*st->codec->channels;
1305 sc->samples_per_frame = 160;
1306 sc->bytes_per_frame = 33;
1312 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1313 if (bits_per_sample) {
1314 st->codec->bits_per_coded_sample = bits_per_sample;
1315 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1317 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1318 // ttxt stsd contains display flags, justification, background
1319 // color, fonts, and default styles, so fake an atom to read it
1320 MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1321 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1322 mov_read_glbl(c, pb, fake_atom);
1323 st->codec->codec_id= id;
1324 st->codec->width = sc->width;
1325 st->codec->height = sc->height;
1327 /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1328 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1330 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1331 a.size = size - (avio_tell(pb) - start_pos);
1333 if (mov_read_default(c, pb, a) < 0)
1335 } else if (a.size > 0)
1336 avio_skip(pb, a.size);
1339 if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1340 st->codec->sample_rate= sc->time_scale;
1342 /* special codec parameters handling */
1343 switch (st->codec->codec_id) {
1344 #if CONFIG_DV_DEMUXER
1345 case CODEC_ID_DVAUDIO:
1346 c->dv_fctx = avformat_alloc_context();
1347 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1349 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1352 sc->dv_audio_container = 1;
1353 st->codec->codec_id = CODEC_ID_PCM_S16LE;
1356 /* no ifdef since parameters are always those */
1357 case CODEC_ID_QCELP:
1358 // force sample rate for qcelp when not stored in mov
1359 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1360 st->codec->sample_rate = 8000;
1361 st->codec->frame_size= 160;
1362 st->codec->channels= 1; /* really needed */
1364 case CODEC_ID_AMR_NB:
1365 st->codec->channels= 1; /* really needed */
1366 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1367 st->codec->sample_rate = 8000;
1368 /* force frame_size, too, samples_per_frame isn't always set properly */
1369 st->codec->frame_size = 160;
1371 case CODEC_ID_AMR_WB:
1372 st->codec->channels = 1;
1373 st->codec->sample_rate = 16000;
1374 st->codec->frame_size = 320;
1378 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1379 st->need_parsing = AVSTREAM_PARSE_FULL;
1382 case CODEC_ID_ADPCM_MS:
1383 case CODEC_ID_ADPCM_IMA_WAV:
1384 st->codec->frame_size = sc->samples_per_frame;
1385 st->codec->block_align = sc->bytes_per_frame;
1388 if (st->codec->extradata_size == 36) {
1389 st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1390 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1391 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1401 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1405 avio_r8(pb); /* version */
1406 avio_rb24(pb); /* flags */
1407 entries = avio_rb32(pb);
1409 return ff_mov_read_stsd_entries(c, pb, entries);
1412 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1415 MOVStreamContext *sc;
1416 unsigned int i, entries;
1418 if (c->fc->nb_streams < 1)
1420 st = c->fc->streams[c->fc->nb_streams-1];
1423 avio_r8(pb); /* version */
1424 avio_rb24(pb); /* flags */
1426 entries = avio_rb32(pb);
1428 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1432 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1434 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1436 return AVERROR(ENOMEM);
1437 sc->stsc_count = entries;
1439 for (i=0; i<entries; i++) {
1440 sc->stsc_data[i].first = avio_rb32(pb);
1441 sc->stsc_data[i].count = avio_rb32(pb);
1442 sc->stsc_data[i].id = avio_rb32(pb);
1447 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1450 MOVStreamContext *sc;
1451 unsigned i, entries;
1453 if (c->fc->nb_streams < 1)
1455 st = c->fc->streams[c->fc->nb_streams-1];
1458 avio_rb32(pb); // version + flags
1460 entries = avio_rb32(pb);
1461 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1463 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1465 return AVERROR(ENOMEM);
1466 sc->stps_count = entries;
1468 for (i = 0; i < entries; i++) {
1469 sc->stps_data[i] = avio_rb32(pb);
1470 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1476 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1479 MOVStreamContext *sc;
1480 unsigned int i, entries;
1482 if (c->fc->nb_streams < 1)
1484 st = c->fc->streams[c->fc->nb_streams-1];
1487 avio_r8(pb); /* version */
1488 avio_rb24(pb); /* flags */
1490 entries = avio_rb32(pb);
1492 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1494 if (entries >= UINT_MAX / sizeof(int))
1496 sc->keyframes = av_malloc(entries * sizeof(int));
1498 return AVERROR(ENOMEM);
1499 sc->keyframe_count = entries;
1501 for (i=0; i<entries; i++) {
1502 sc->keyframes[i] = avio_rb32(pb);
1503 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1508 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1511 MOVStreamContext *sc;
1512 unsigned int i, entries, sample_size, field_size, num_bytes;
1516 if (c->fc->nb_streams < 1)
1518 st = c->fc->streams[c->fc->nb_streams-1];
1521 avio_r8(pb); /* version */
1522 avio_rb24(pb); /* flags */
1524 if (atom.type == MKTAG('s','t','s','z')) {
1525 sample_size = avio_rb32(pb);
1526 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1527 sc->sample_size = sample_size;
1531 avio_rb24(pb); /* reserved */
1532 field_size = avio_r8(pb);
1534 entries = avio_rb32(pb);
1536 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1538 sc->sample_count = entries;
1542 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1543 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1549 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1551 sc->sample_sizes = av_malloc(entries * sizeof(int));
1552 if (!sc->sample_sizes)
1553 return AVERROR(ENOMEM);
1555 num_bytes = (entries*field_size+4)>>3;
1557 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1559 av_freep(&sc->sample_sizes);
1560 return AVERROR(ENOMEM);
1563 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1564 av_freep(&sc->sample_sizes);
1569 init_get_bits(&gb, buf, 8*num_bytes);
1571 for (i=0; i<entries; i++)
1572 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1578 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1581 MOVStreamContext *sc;
1582 unsigned int i, entries;
1584 int64_t total_sample_count=0;
1586 if (c->fc->nb_streams < 1)
1588 st = c->fc->streams[c->fc->nb_streams-1];
1591 avio_r8(pb); /* version */
1592 avio_rb24(pb); /* flags */
1593 entries = avio_rb32(pb);
1595 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1596 c->fc->nb_streams-1, entries);
1600 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1601 return AVERROR(EINVAL);
1603 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1605 return AVERROR(ENOMEM);
1607 sc->stts_count = entries;
1609 for (i=0; i<entries; i++) {
1610 int sample_duration;
1613 sample_count=avio_rb32(pb);
1614 sample_duration = avio_rb32(pb);
1615 sc->stts_data[i].count= sample_count;
1616 sc->stts_data[i].duration= sample_duration;
1618 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1619 sample_count, sample_duration);
1621 duration+=(int64_t)sample_duration*sample_count;
1622 total_sample_count+=sample_count;
1625 st->nb_frames= total_sample_count;
1627 st->duration= duration;
1631 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1634 MOVStreamContext *sc;
1635 unsigned int i, entries;
1637 if (c->fc->nb_streams < 1)
1639 st = c->fc->streams[c->fc->nb_streams-1];
1642 avio_r8(pb); /* version */
1643 avio_rb24(pb); /* flags */
1644 entries = avio_rb32(pb);
1646 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1650 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1652 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1654 return AVERROR(ENOMEM);
1655 sc->ctts_count = entries;
1657 for (i=0; i<entries; i++) {
1658 int count =avio_rb32(pb);
1659 int duration =avio_rb32(pb);
1661 sc->ctts_data[i].count = count;
1662 sc->ctts_data[i].duration= duration;
1664 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1667 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1672 static void mov_build_index(MOVContext *mov, AVStream *st)
1674 MOVStreamContext *sc = st->priv_data;
1675 int64_t current_offset;
1676 int64_t current_dts = 0;
1677 unsigned int stts_index = 0;
1678 unsigned int stsc_index = 0;
1679 unsigned int stss_index = 0;
1680 unsigned int stps_index = 0;
1682 uint64_t stream_size = 0;
1684 /* adjust first dts according to edit list */
1685 if (sc->time_offset && mov->time_scale > 0) {
1686 if (sc->time_offset < 0)
1687 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
1688 current_dts = -sc->time_offset;
1689 if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
1690 sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1691 /* more than 16 frames delay, dts are likely wrong
1692 this happens with files created by iMovie */
1694 st->codec->has_b_frames = 1;
1698 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1699 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1700 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1701 unsigned int current_sample = 0;
1702 unsigned int stts_sample = 0;
1703 unsigned int sample_size;
1704 unsigned int distance = 0;
1705 int key_off = sc->keyframes && sc->keyframes[0] == 1;
1707 current_dts -= sc->dts_shift;
1709 if (!sc->sample_count)
1711 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
1713 st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
1714 if (!st->index_entries)
1716 st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
1718 for (i = 0; i < sc->chunk_count; i++) {
1719 current_offset = sc->chunk_offsets[i];
1720 while (stsc_index + 1 < sc->stsc_count &&
1721 i + 1 == sc->stsc_data[stsc_index + 1].first)
1723 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1725 if (current_sample >= sc->sample_count) {
1726 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1730 if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1732 if (stss_index + 1 < sc->keyframe_count)
1734 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1736 if (stps_index + 1 < sc->stps_count)
1741 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1742 if (sc->pseudo_stream_id == -1 ||
1743 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1744 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1745 e->pos = current_offset;
1746 e->timestamp = current_dts;
1747 e->size = sample_size;
1748 e->min_distance = distance;
1749 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1750 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1751 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1752 current_offset, current_dts, sample_size, distance, keyframe);
1755 current_offset += sample_size;
1756 stream_size += sample_size;
1757 current_dts += sc->stts_data[stts_index].duration;
1761 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1767 if (st->duration > 0)
1768 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1770 unsigned chunk_samples, total = 0;
1772 // compute total chunk count
1773 for (i = 0; i < sc->stsc_count; i++) {
1774 unsigned count, chunk_count;
1776 chunk_samples = sc->stsc_data[i].count;
1777 if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1778 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1782 if (sc->samples_per_frame >= 160) { // gsm
1783 count = chunk_samples / sc->samples_per_frame;
1784 } else if (sc->samples_per_frame > 1) {
1785 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1786 count = (chunk_samples+samples-1) / samples;
1788 count = (chunk_samples+1023) / 1024;
1791 if (i < sc->stsc_count - 1)
1792 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1794 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1795 total += chunk_count * count;
1798 av_dlog(mov->fc, "chunk count %d\n", total);
1799 if (total >= UINT_MAX / sizeof(*st->index_entries))
1801 st->index_entries = av_malloc(total*sizeof(*st->index_entries));
1802 if (!st->index_entries)
1804 st->index_entries_allocated_size = total*sizeof(*st->index_entries);
1807 for (i = 0; i < sc->chunk_count; i++) {
1808 current_offset = sc->chunk_offsets[i];
1809 if (stsc_index + 1 < sc->stsc_count &&
1810 i + 1 == sc->stsc_data[stsc_index + 1].first)
1812 chunk_samples = sc->stsc_data[stsc_index].count;
1814 while (chunk_samples > 0) {
1816 unsigned size, samples;
1818 if (sc->samples_per_frame >= 160) { // gsm
1819 samples = sc->samples_per_frame;
1820 size = sc->bytes_per_frame;
1822 if (sc->samples_per_frame > 1) {
1823 samples = FFMIN((1024 / sc->samples_per_frame)*
1824 sc->samples_per_frame, chunk_samples);
1825 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1827 samples = FFMIN(1024, chunk_samples);
1828 size = samples * sc->sample_size;
1832 if (st->nb_index_entries >= total) {
1833 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1836 e = &st->index_entries[st->nb_index_entries++];
1837 e->pos = current_offset;
1838 e->timestamp = current_dts;
1840 e->min_distance = 0;
1841 e->flags = AVINDEX_KEYFRAME;
1842 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1843 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1846 current_offset += size;
1847 current_dts += samples;
1848 chunk_samples -= samples;
1854 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
1855 AVIOInterruptCB *int_cb)
1857 /* try relative path, we do not try the absolute because it can leak information about our
1858 system to an attacker */
1859 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1860 char filename[1024];
1864 /* find a source dir */
1865 src_path = strrchr(src, '/');
1871 /* find a next level down to target */
1872 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1873 if (ref->path[l] == '/') {
1874 if (i == ref->nlvl_to - 1)
1880 /* compose filename if next level down to target was found */
1881 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
1882 memcpy(filename, src, src_path - src);
1883 filename[src_path - src] = 0;
1885 for (i = 1; i < ref->nlvl_from; i++)
1886 av_strlcat(filename, "../", 1024);
1888 av_strlcat(filename, ref->path + l + 1, 1024);
1890 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
1895 return AVERROR(ENOENT);
1898 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1901 MOVStreamContext *sc;
1904 st = avformat_new_stream(c->fc, NULL);
1905 if (!st) return AVERROR(ENOMEM);
1906 st->id = c->fc->nb_streams;
1907 sc = av_mallocz(sizeof(MOVStreamContext));
1908 if (!sc) return AVERROR(ENOMEM);
1911 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1912 sc->ffindex = st->index;
1914 if ((ret = mov_read_default(c, pb, atom)) < 0)
1918 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1919 (!sc->sample_size && !sc->sample_count))) {
1920 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1925 if (sc->time_scale <= 0) {
1926 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
1927 sc->time_scale = c->time_scale;
1928 if (sc->time_scale <= 0)
1932 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
1934 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1935 !st->codec->frame_size && sc->stts_count == 1) {
1936 st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
1937 st->codec->sample_rate, sc->time_scale);
1938 av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
1941 mov_build_index(c, st);
1943 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1944 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
1945 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
1946 av_log(c->fc, AV_LOG_ERROR,
1947 "stream %d, error opening alias: path='%s', dir='%s', "
1948 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
1949 st->index, dref->path, dref->dir, dref->filename,
1950 dref->volume, dref->nlvl_from, dref->nlvl_to);
1954 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1955 if (!st->sample_aspect_ratio.num &&
1956 (st->codec->width != sc->width || st->codec->height != sc->height)) {
1957 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
1958 ((double)st->codec->width * sc->height), INT_MAX);
1961 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1962 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
1964 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
1965 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
1966 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
1969 switch (st->codec->codec_id) {
1970 #if CONFIG_H261_DECODER
1973 #if CONFIG_H263_DECODER
1976 #if CONFIG_H264_DECODER
1979 #if CONFIG_MPEG4_DECODER
1980 case CODEC_ID_MPEG4:
1982 st->codec->width = 0; /* let decoder init width/height */
1983 st->codec->height= 0;
1987 /* Do not need those anymore. */
1988 av_freep(&sc->chunk_offsets);
1989 av_freep(&sc->stsc_data);
1990 av_freep(&sc->sample_sizes);
1991 av_freep(&sc->keyframes);
1992 av_freep(&sc->stts_data);
1993 av_freep(&sc->stps_data);
1998 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2001 c->itunes_metadata = 1;
2002 ret = mov_read_default(c, pb, atom);
2003 c->itunes_metadata = 0;
2007 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2009 while (atom.size > 8) {
2010 uint32_t tag = avio_rl32(pb);
2012 if (tag == MKTAG('h','d','l','r')) {
2013 avio_seek(pb, -8, SEEK_CUR);
2015 return mov_read_default(c, pb, atom);
2021 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2026 int64_t disp_transform[2];
2027 int display_matrix[3][2];
2029 MOVStreamContext *sc;
2032 if (c->fc->nb_streams < 1)
2034 st = c->fc->streams[c->fc->nb_streams-1];
2037 version = avio_r8(pb);
2038 avio_rb24(pb); /* flags */
2040 MOV_TRACK_ENABLED 0x0001
2041 MOV_TRACK_IN_MOVIE 0x0002
2042 MOV_TRACK_IN_PREVIEW 0x0004
2043 MOV_TRACK_IN_POSTER 0x0008
2050 avio_rb32(pb); /* creation time */
2051 avio_rb32(pb); /* modification time */
2053 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2054 avio_rb32(pb); /* reserved */
2056 /* highlevel (considering edits) duration in movie timebase */
2057 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2058 avio_rb32(pb); /* reserved */
2059 avio_rb32(pb); /* reserved */
2061 avio_rb16(pb); /* layer */
2062 avio_rb16(pb); /* alternate group */
2063 avio_rb16(pb); /* volume */
2064 avio_rb16(pb); /* reserved */
2066 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2067 // they're kept in fixed point format through all calculations
2068 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2069 for (i = 0; i < 3; i++) {
2070 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2071 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2072 avio_rb32(pb); // 2.30 fixed point (not used)
2075 width = avio_rb32(pb); // 16.16 fixed point track width
2076 height = avio_rb32(pb); // 16.16 fixed point track height
2077 sc->width = width >> 16;
2078 sc->height = height >> 16;
2080 // transform the display width/height according to the matrix
2081 // skip this if the display matrix is the default identity matrix
2082 // or if it is rotating the picture, ex iPhone 3GS
2083 // to keep the same scale, use [width height 1<<16]
2084 if (width && height &&
2085 ((display_matrix[0][0] != 65536 ||
2086 display_matrix[1][1] != 65536) &&
2087 !display_matrix[0][1] &&
2088 !display_matrix[1][0] &&
2089 !display_matrix[2][0] && !display_matrix[2][1])) {
2090 for (i = 0; i < 2; i++)
2092 (int64_t) width * display_matrix[0][i] +
2093 (int64_t) height * display_matrix[1][i] +
2094 ((int64_t) display_matrix[2][i] << 16);
2096 //sample aspect ratio is new width/height divided by old width/height
2097 st->sample_aspect_ratio = av_d2q(
2098 ((double) disp_transform[0] * height) /
2099 ((double) disp_transform[1] * width), INT_MAX);
2104 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2106 MOVFragment *frag = &c->fragment;
2107 MOVTrackExt *trex = NULL;
2108 int flags, track_id, i;
2110 avio_r8(pb); /* version */
2111 flags = avio_rb24(pb);
2113 track_id = avio_rb32(pb);
2116 frag->track_id = track_id;
2117 for (i = 0; i < c->trex_count; i++)
2118 if (c->trex_data[i].track_id == frag->track_id) {
2119 trex = &c->trex_data[i];
2123 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2127 if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
2128 else frag->base_data_offset = frag->moof_offset;
2129 if (flags & 0x02) frag->stsd_id = avio_rb32(pb);
2130 else frag->stsd_id = trex->stsd_id;
2132 frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
2133 frag->size = flags & 0x10 ? avio_rb32(pb) : trex->size;
2134 frag->flags = flags & 0x20 ? avio_rb32(pb) : trex->flags;
2135 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2139 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2141 c->chapter_track = avio_rb32(pb);
2145 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2149 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2151 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2153 return AVERROR(ENOMEM);
2154 c->trex_data = trex;
2155 trex = &c->trex_data[c->trex_count++];
2156 avio_r8(pb); /* version */
2157 avio_rb24(pb); /* flags */
2158 trex->track_id = avio_rb32(pb);
2159 trex->stsd_id = avio_rb32(pb);
2160 trex->duration = avio_rb32(pb);
2161 trex->size = avio_rb32(pb);
2162 trex->flags = avio_rb32(pb);
2166 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2168 MOVFragment *frag = &c->fragment;
2169 AVStream *st = NULL;
2170 MOVStreamContext *sc;
2174 int data_offset = 0;
2175 unsigned entries, first_sample_flags = frag->flags;
2176 int flags, distance, i;
2178 for (i = 0; i < c->fc->nb_streams; i++) {
2179 if (c->fc->streams[i]->id == frag->track_id) {
2180 st = c->fc->streams[i];
2185 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2189 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2191 avio_r8(pb); /* version */
2192 flags = avio_rb24(pb);
2193 entries = avio_rb32(pb);
2194 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2196 /* Always assume the presence of composition time offsets.
2197 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2198 * 1) in the initial movie, there are no samples.
2199 * 2) in the first movie fragment, there is only one sample without composition time offset.
2200 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2201 if (!sc->ctts_count && sc->sample_count)
2203 /* Complement ctts table if moov atom doesn't have ctts atom. */
2204 ctts_data = av_malloc(sizeof(*sc->ctts_data));
2206 return AVERROR(ENOMEM);
2207 sc->ctts_data = ctts_data;
2208 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2209 sc->ctts_data[sc->ctts_count].duration = 0;
2212 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2214 ctts_data = av_realloc(sc->ctts_data,
2215 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2217 return AVERROR(ENOMEM);
2218 sc->ctts_data = ctts_data;
2220 if (flags & 0x001) data_offset = avio_rb32(pb);
2221 if (flags & 0x004) first_sample_flags = avio_rb32(pb);
2222 dts = st->duration - sc->time_offset;
2223 offset = frag->base_data_offset + data_offset;
2225 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2226 for (i = 0; i < entries; i++) {
2227 unsigned sample_size = frag->size;
2228 int sample_flags = i ? frag->flags : first_sample_flags;
2229 unsigned sample_duration = frag->duration;
2232 if (flags & 0x100) sample_duration = avio_rb32(pb);
2233 if (flags & 0x200) sample_size = avio_rb32(pb);
2234 if (flags & 0x400) sample_flags = avio_rb32(pb);
2235 sc->ctts_data[sc->ctts_count].count = 1;
2236 sc->ctts_data[sc->ctts_count].duration = (flags & 0x800) ? avio_rb32(pb) : 0;
2238 if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
2239 (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
2241 av_add_index_entry(st, offset, dts, sample_size, distance,
2242 keyframe ? AVINDEX_KEYFRAME : 0);
2243 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2244 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2245 offset, dts, sample_size, distance, keyframe);
2247 dts += sample_duration;
2248 offset += sample_size;
2250 frag->moof_offset = offset;
2251 st->duration = dts + sc->time_offset;
2255 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2256 /* like the files created with Adobe Premiere 5.0, for samples see */
2257 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2258 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2263 return 0; /* continue */
2264 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2265 avio_skip(pb, atom.size - 4);
2268 atom.type = avio_rl32(pb);
2270 if (atom.type != MKTAG('m','d','a','t')) {
2271 avio_skip(pb, atom.size);
2274 err = mov_read_mdat(c, pb, atom);
2278 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2283 uint8_t *moov_data; /* uncompressed data */
2284 long cmov_len, moov_len;
2287 avio_rb32(pb); /* dcom atom */
2288 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2290 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2291 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2294 avio_rb32(pb); /* cmvd atom */
2295 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2297 moov_len = avio_rb32(pb); /* uncompressed size */
2298 cmov_len = atom.size - 6 * 4;
2300 cmov_data = av_malloc(cmov_len);
2302 return AVERROR(ENOMEM);
2303 moov_data = av_malloc(moov_len);
2306 return AVERROR(ENOMEM);
2308 avio_read(pb, cmov_data, cmov_len);
2309 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2310 goto free_and_return;
2311 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2312 goto free_and_return;
2313 atom.type = MKTAG('m','o','o','v');
2314 atom.size = moov_len;
2315 ret = mov_read_default(c, &ctx, atom);
2321 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2326 /* edit list atom */
2327 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2329 MOVStreamContext *sc;
2330 int i, edit_count, version;
2332 if (c->fc->nb_streams < 1)
2334 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2336 version = avio_r8(pb); /* version */
2337 avio_rb24(pb); /* flags */
2338 edit_count = avio_rb32(pb); /* entries */
2340 if ((uint64_t)edit_count*12+8 > atom.size)
2343 for (i=0; i<edit_count; i++){
2347 duration = avio_rb64(pb);
2348 time = avio_rb64(pb);
2350 duration = avio_rb32(pb); /* segment duration */
2351 time = (int32_t)avio_rb32(pb); /* media time */
2353 avio_rb32(pb); /* Media rate */
2354 if (i == 0 && time >= -1) {
2355 sc->time_offset = time != -1 ? time : -duration;
2360 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2361 "a/v desync might occur, patch welcome\n");
2363 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2367 static const MOVParseTableEntry mov_default_parse_table[] = {
2368 { MKTAG('a','v','s','s'), mov_read_extradata },
2369 { MKTAG('c','h','p','l'), mov_read_chpl },
2370 { MKTAG('c','o','6','4'), mov_read_stco },
2371 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2372 { MKTAG('d','i','n','f'), mov_read_default },
2373 { MKTAG('d','r','e','f'), mov_read_dref },
2374 { MKTAG('e','d','t','s'), mov_read_default },
2375 { MKTAG('e','l','s','t'), mov_read_elst },
2376 { MKTAG('e','n','d','a'), mov_read_enda },
2377 { MKTAG('f','i','e','l'), mov_read_fiel },
2378 { MKTAG('f','t','y','p'), mov_read_ftyp },
2379 { MKTAG('g','l','b','l'), mov_read_glbl },
2380 { MKTAG('h','d','l','r'), mov_read_hdlr },
2381 { MKTAG('i','l','s','t'), mov_read_ilst },
2382 { MKTAG('j','p','2','h'), mov_read_extradata },
2383 { MKTAG('m','d','a','t'), mov_read_mdat },
2384 { MKTAG('m','d','h','d'), mov_read_mdhd },
2385 { MKTAG('m','d','i','a'), mov_read_default },
2386 { MKTAG('m','e','t','a'), mov_read_meta },
2387 { MKTAG('m','i','n','f'), mov_read_default },
2388 { MKTAG('m','o','o','f'), mov_read_moof },
2389 { MKTAG('m','o','o','v'), mov_read_moov },
2390 { MKTAG('m','v','e','x'), mov_read_default },
2391 { MKTAG('m','v','h','d'), mov_read_mvhd },
2392 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2393 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2394 { MKTAG('a','v','c','C'), mov_read_glbl },
2395 { MKTAG('p','a','s','p'), mov_read_pasp },
2396 { MKTAG('s','t','b','l'), mov_read_default },
2397 { MKTAG('s','t','c','o'), mov_read_stco },
2398 { MKTAG('s','t','p','s'), mov_read_stps },
2399 { MKTAG('s','t','r','f'), mov_read_strf },
2400 { MKTAG('s','t','s','c'), mov_read_stsc },
2401 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2402 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2403 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2404 { MKTAG('s','t','t','s'), mov_read_stts },
2405 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2406 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2407 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2408 { MKTAG('t','r','a','k'), mov_read_trak },
2409 { MKTAG('t','r','a','f'), mov_read_default },
2410 { MKTAG('t','r','e','f'), mov_read_default },
2411 { MKTAG('c','h','a','p'), mov_read_chap },
2412 { MKTAG('t','r','e','x'), mov_read_trex },
2413 { MKTAG('t','r','u','n'), mov_read_trun },
2414 { MKTAG('u','d','t','a'), mov_read_default },
2415 { MKTAG('w','a','v','e'), mov_read_wave },
2416 { MKTAG('e','s','d','s'), mov_read_esds },
2417 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2418 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2419 { MKTAG('w','f','e','x'), mov_read_wfex },
2420 { MKTAG('c','m','o','v'), mov_read_cmov },
2421 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2425 static int mov_probe(AVProbeData *p)
2427 unsigned int offset;
2431 /* check file header */
2434 /* ignore invalid offset */
2435 if ((offset + 8) > (unsigned int)p->buf_size)
2437 tag = AV_RL32(p->buf + offset + 4);
2439 /* check for obvious tags */
2440 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2441 case MKTAG('m','o','o','v'):
2442 case MKTAG('m','d','a','t'):
2443 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2444 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2445 case MKTAG('f','t','y','p'):
2446 return AVPROBE_SCORE_MAX;
2447 /* those are more common words, so rate then a bit less */
2448 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2449 case MKTAG('w','i','d','e'):
2450 case MKTAG('f','r','e','e'):
2451 case MKTAG('j','u','n','k'):
2452 case MKTAG('p','i','c','t'):
2453 return AVPROBE_SCORE_MAX - 5;
2454 case MKTAG(0x82,0x82,0x7f,0x7d):
2455 case MKTAG('s','k','i','p'):
2456 case MKTAG('u','u','i','d'):
2457 case MKTAG('p','r','f','l'):
2458 offset = AV_RB32(p->buf+offset) + offset;
2459 /* if we only find those cause probedata is too small at least rate them */
2460 score = AVPROBE_SCORE_MAX - 50;
2463 /* unrecognized tag */
2469 // must be done after parsing all trak because there's no order requirement
2470 static void mov_read_chapters(AVFormatContext *s)
2472 MOVContext *mov = s->priv_data;
2473 AVStream *st = NULL;
2474 MOVStreamContext *sc;
2478 for (i = 0; i < s->nb_streams; i++)
2479 if (s->streams[i]->id == mov->chapter_track) {
2484 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2488 st->discard = AVDISCARD_ALL;
2490 cur_pos = avio_tell(sc->pb);
2492 for (i = 0; i < st->nb_index_entries; i++) {
2493 AVIndexEntry *sample = &st->index_entries[i];
2494 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2499 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2500 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2504 // the first two bytes are the length of the title
2505 len = avio_rb16(sc->pb);
2506 if (len > sample->size-2)
2508 title_len = 2*len + 1;
2509 if (!(title = av_mallocz(title_len)))
2512 // The samples could theoretically be in any encoding if there's an encd
2513 // atom following, but in practice are only utf-8 or utf-16, distinguished
2514 // instead by the presence of a BOM
2518 ch = avio_rb16(sc->pb);
2520 avio_get_str16be(sc->pb, len, title, title_len);
2521 else if (ch == 0xfffe)
2522 avio_get_str16le(sc->pb, len, title, title_len);
2525 if (len == 1 || len == 2)
2528 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
2532 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2536 avio_seek(sc->pb, cur_pos, SEEK_SET);
2539 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
2541 MOVContext *mov = s->priv_data;
2542 AVIOContext *pb = s->pb;
2544 MOVAtom atom = { AV_RL32("root") };
2547 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2549 atom.size = avio_size(pb);
2551 atom.size = INT64_MAX;
2553 /* check MOV header */
2554 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2555 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2558 if (!mov->found_moov) {
2559 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2562 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2564 if (pb->seekable && mov->chapter_track > 0)
2565 mov_read_chapters(s);
2570 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2572 AVIndexEntry *sample = NULL;
2573 int64_t best_dts = INT64_MAX;
2575 for (i = 0; i < s->nb_streams; i++) {
2576 AVStream *avst = s->streams[i];
2577 MOVStreamContext *msc = avst->priv_data;
2578 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2579 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2580 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2581 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2582 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2584 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2585 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2586 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2587 sample = current_sample;
2596 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2598 MOVContext *mov = s->priv_data;
2599 MOVStreamContext *sc;
2600 AVIndexEntry *sample;
2601 AVStream *st = NULL;
2604 sample = mov_find_next_sample(s, &st);
2606 mov->found_mdat = 0;
2607 if (s->pb->seekable||
2608 mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2611 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2615 /* must be done just before reading, to avoid infinite loop on sample */
2616 sc->current_sample++;
2618 if (st->discard != AVDISCARD_ALL) {
2619 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2620 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2621 sc->ffindex, sample->pos);
2624 ret = av_get_packet(sc->pb, pkt, sample->size);
2627 if (sc->has_palette) {
2630 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2632 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2634 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2635 sc->has_palette = 0;
2638 #if CONFIG_DV_DEMUXER
2639 if (mov->dv_demux && sc->dv_audio_container) {
2640 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2643 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
2650 pkt->stream_index = sc->ffindex;
2651 pkt->dts = sample->timestamp;
2652 if (sc->ctts_data) {
2653 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2654 /* update ctts context */
2656 if (sc->ctts_index < sc->ctts_count &&
2657 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2659 sc->ctts_sample = 0;
2662 pkt->dts = AV_NOPTS_VALUE;
2664 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2665 st->index_entries[sc->current_sample].timestamp : st->duration;
2666 pkt->duration = next_dts - pkt->dts;
2667 pkt->pts = pkt->dts;
2669 if (st->discard == AVDISCARD_ALL)
2671 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2672 pkt->pos = sample->pos;
2673 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2674 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2678 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2680 MOVStreamContext *sc = st->priv_data;
2681 int sample, time_sample;
2684 sample = av_index_search_timestamp(st, timestamp, flags);
2685 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2686 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2688 if (sample < 0) /* not sure what to do */
2690 sc->current_sample = sample;
2691 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2692 /* adjust ctts index */
2693 if (sc->ctts_data) {
2695 for (i = 0; i < sc->ctts_count; i++) {
2696 int next = time_sample + sc->ctts_data[i].count;
2697 if (next > sc->current_sample) {
2699 sc->ctts_sample = sc->current_sample - time_sample;
2708 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2711 int64_t seek_timestamp, timestamp;
2715 if (stream_index >= s->nb_streams)
2717 if (sample_time < 0)
2720 st = s->streams[stream_index];
2721 sample = mov_seek_stream(s, st, sample_time, flags);
2725 /* adjust seek timestamp to found sample timestamp */
2726 seek_timestamp = st->index_entries[sample].timestamp;
2728 for (i = 0; i < s->nb_streams; i++) {
2730 if (stream_index == i)
2733 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2734 mov_seek_stream(s, st, timestamp, flags);
2739 static int mov_read_close(AVFormatContext *s)
2741 MOVContext *mov = s->priv_data;
2744 for (i = 0; i < s->nb_streams; i++) {
2745 AVStream *st = s->streams[i];
2746 MOVStreamContext *sc = st->priv_data;
2748 av_freep(&sc->ctts_data);
2749 for (j = 0; j < sc->drefs_count; j++) {
2750 av_freep(&sc->drefs[j].path);
2751 av_freep(&sc->drefs[j].dir);
2753 av_freep(&sc->drefs);
2754 if (sc->pb && sc->pb != s->pb)
2758 if (mov->dv_demux) {
2759 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2760 av_freep(&mov->dv_fctx->streams[i]->codec);
2761 av_freep(&mov->dv_fctx->streams[i]);
2763 av_freep(&mov->dv_fctx);
2764 av_freep(&mov->dv_demux);
2767 av_freep(&mov->trex_data);
2772 AVInputFormat ff_mov_demuxer = {
2773 .name = "mov,mp4,m4a,3gp,3g2,mj2",
2774 .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2775 .priv_data_size = sizeof(MOVContext),
2776 .read_probe = mov_probe,
2777 .read_header = mov_read_header,
2778 .read_packet = mov_read_packet,
2779 .read_close = mov_read_close,
2780 .read_seek = mov_read_seek,