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 FFmpeg.
8 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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"
33 #include "libavutil/opt.h"
36 #include "avio_internal.h"
39 #include "libavcodec/get_bits.h"
40 #include "libavcodec/timecode.h"
49 * First version by Francois Revol revol@free.fr
50 * Seek function by Gael Chardon gael.dev@4now.net
53 #include "qtpalette.h"
59 /* those functions parse an atom */
60 /* links atom IDs to parse functions */
61 typedef struct MOVParseTableEntry {
63 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
66 static const MOVParseTableEntry mov_default_parse_table[];
68 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
69 unsigned len, const char *key)
73 short current, total = 0;
74 avio_rb16(pb); // unknown
75 current = avio_rb16(pb);
77 total = avio_rb16(pb);
79 snprintf(buf, sizeof(buf), "%d", current);
81 snprintf(buf, sizeof(buf), "%d/%d", current, total);
82 av_dict_set(&c->fc->metadata, key, buf, 0);
87 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
88 unsigned len, const char *key)
92 /* bypass padding bytes */
97 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
98 av_dict_set(&c->fc->metadata, key, buf, 0);
103 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
104 unsigned len, const char *key)
108 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
109 av_dict_set(&c->fc->metadata, key, buf, 0);
114 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
115 unsigned len, const char *key)
120 avio_r8(pb); // unknown
123 if (genre < 1 || genre > ID3v1_GENRE_MAX)
125 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
126 av_dict_set(&c->fc->metadata, key, buf, 0);
131 static const uint32_t mac_to_unicode[128] = {
132 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
133 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
134 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
135 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
136 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
137 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
138 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
139 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
140 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
141 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
142 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
143 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
144 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
145 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
146 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
147 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
150 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
151 char *dst, int dstlen)
154 char *end = dst+dstlen-1;
157 for (i = 0; i < len; i++) {
158 uint8_t t, c = avio_r8(pb);
159 if (c < 0x80 && p < end)
162 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
168 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
170 #ifdef MOV_EXPORT_ALL_METADATA
173 char str[1024], key2[16], language[4] = {0};
174 const char *key = NULL;
175 uint16_t str_size, langcode = 0;
176 uint32_t data_type = 0;
177 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
180 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
181 case MKTAG(0xa9,'a','u','t'):
182 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
183 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
184 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
185 case MKTAG( 'c','p','r','t'):
186 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
187 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
188 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
189 case MKTAG(0xa9,'c','m','t'):
190 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
191 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
192 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
193 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
194 case MKTAG( 'g','n','r','e'): key = "genre";
195 parse = mov_metadata_gnre; break;
196 case MKTAG(0xa9,'t','o','o'):
197 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
198 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
199 case MKTAG( 'd','e','s','c'): key = "description";break;
200 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
201 case MKTAG( 't','v','s','h'): key = "show"; break;
202 case MKTAG( 't','v','e','n'): key = "episode_id";break;
203 case MKTAG( 't','v','n','n'): key = "network"; break;
204 case MKTAG( 't','r','k','n'): key = "track";
205 parse = mov_metadata_track_or_disc_number; break;
206 case MKTAG( 'd','i','s','k'): key = "disc";
207 parse = mov_metadata_track_or_disc_number; break;
208 case MKTAG( 't','v','e','s'): key = "episode_sort";
209 parse = mov_metadata_int8_bypass_padding; break;
210 case MKTAG( 't','v','s','n'): key = "season_number";
211 parse = mov_metadata_int8_bypass_padding; break;
212 case MKTAG( 's','t','i','k'): key = "media_type";
213 parse = mov_metadata_int8_no_padding; break;
214 case MKTAG( 'h','d','v','d'): key = "hd_video";
215 parse = mov_metadata_int8_no_padding; break;
216 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
217 parse = mov_metadata_int8_no_padding; break;
220 if (c->itunes_metadata && atom.size > 8) {
221 int data_size = avio_rb32(pb);
222 int tag = avio_rl32(pb);
223 if (tag == MKTAG('d','a','t','a')) {
224 data_type = avio_rb32(pb); // type
225 avio_rb32(pb); // unknown
226 str_size = data_size - 16;
229 } else if (atom.size > 4 && key && !c->itunes_metadata) {
230 str_size = avio_rb16(pb); // string length
231 langcode = avio_rb16(pb);
232 ff_mov_lang_to_iso639(langcode, language);
235 str_size = atom.size;
237 #ifdef MOV_EXPORT_ALL_METADATA
239 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
247 return AVERROR_INVALIDDATA;
249 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
252 parse(c, pb, str_size, key);
254 if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
255 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
257 avio_read(pb, str, str_size);
260 av_dict_set(&c->fc->metadata, key, str, 0);
261 if (*language && strcmp(language, "und")) {
262 snprintf(key2, sizeof(key2), "%s-%s", key, language);
263 av_dict_set(&c->fc->metadata, key2, str, 0);
266 av_dlog(c->fc, "lang \"%3s\" ", language);
267 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
268 key, str, (char*)&atom.type, str_size, atom.size);
273 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
276 int i, nb_chapters, str_len, version;
279 if ((atom.size -= 5) < 0)
282 version = avio_r8(pb);
285 avio_rb32(pb); // ???
286 nb_chapters = avio_r8(pb);
288 for (i = 0; i < nb_chapters; i++) {
292 start = avio_rb64(pb);
293 str_len = avio_r8(pb);
295 if ((atom.size -= 9+str_len) < 0)
298 avio_read(pb, str, str_len);
300 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
305 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
307 int64_t total_size = 0;
312 atom.size = INT64_MAX;
313 while (total_size + 8 <= atom.size && !url_feof(pb)) {
314 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
317 if (atom.size >= 8) {
318 a.size = avio_rb32(pb);
319 a.type = avio_rl32(pb);
321 if (a.size == 1) { /* 64 bit extended size */
322 a.size = avio_rb64(pb) - 8;
326 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
327 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
329 a.size = atom.size - total_size + 8;
334 a.size = FFMIN(a.size, atom.size - total_size);
336 for (i = 0; mov_default_parse_table[i].type; i++)
337 if (mov_default_parse_table[i].type == a.type) {
338 parse = mov_default_parse_table[i].parse;
342 // container is user data
343 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
344 atom.type == MKTAG('i','l','s','t')))
345 parse = mov_read_udta_string;
347 if (!parse) { /* skip leaf atoms data */
348 avio_skip(pb, a.size);
350 int64_t start_pos = avio_tell(pb);
352 int err = parse(c, pb, a);
355 if (c->found_moov && c->found_mdat &&
356 (!pb->seekable || start_pos + a.size == avio_size(pb)))
358 left = a.size - avio_tell(pb) + start_pos;
359 if (left > 0) /* skip garbage at atom end */
363 total_size += a.size;
366 if (total_size < atom.size && atom.size < 0x7ffff)
367 avio_skip(pb, atom.size - total_size);
372 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
375 MOVStreamContext *sc;
378 if (c->fc->nb_streams < 1)
380 st = c->fc->streams[c->fc->nb_streams-1];
383 avio_rb32(pb); // version + flags
384 entries = avio_rb32(pb);
385 if (entries >= UINT_MAX / sizeof(*sc->drefs))
386 return AVERROR_INVALIDDATA;
387 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
389 return AVERROR(ENOMEM);
390 sc->drefs_count = entries;
392 for (i = 0; i < sc->drefs_count; i++) {
393 MOVDref *dref = &sc->drefs[i];
394 uint32_t size = avio_rb32(pb);
395 int64_t next = avio_tell(pb) + size - 4;
398 return AVERROR_INVALIDDATA;
400 dref->type = avio_rl32(pb);
401 avio_rb32(pb); // version + flags
402 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
404 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
405 /* macintosh alias record */
406 uint16_t volume_len, len;
411 volume_len = avio_r8(pb);
412 volume_len = FFMIN(volume_len, 27);
413 avio_read(pb, dref->volume, 27);
414 dref->volume[volume_len] = 0;
415 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
420 len = FFMIN(len, 63);
421 avio_read(pb, dref->filename, 63);
422 dref->filename[len] = 0;
423 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
427 /* read next level up_from_alias/down_to_target */
428 dref->nlvl_from = avio_rb16(pb);
429 dref->nlvl_to = avio_rb16(pb);
430 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
431 dref->nlvl_from, dref->nlvl_to);
435 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
438 type = avio_rb16(pb);
440 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
443 if (type == 2) { // absolute path
445 dref->path = av_mallocz(len+1);
447 return AVERROR(ENOMEM);
448 avio_read(pb, dref->path, len);
449 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
451 memmove(dref->path, dref->path+volume_len, len);
454 for (j = 0; j < len; j++)
455 if (dref->path[j] == ':')
457 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
458 } else if (type == 0) { // directory name
460 dref->dir = av_malloc(len+1);
462 return AVERROR(ENOMEM);
463 avio_read(pb, dref->dir, len);
465 for (j = 0; j < len; j++)
466 if (dref->dir[j] == ':')
468 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
473 avio_seek(pb, next, SEEK_SET);
478 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
482 uint32_t av_unused ctype;
486 if (c->fc->nb_streams < 1) // meta before first trak
489 st = c->fc->streams[c->fc->nb_streams-1];
491 avio_r8(pb); /* version */
492 avio_rb24(pb); /* flags */
495 ctype = avio_rl32(pb);
496 type = avio_rl32(pb); /* component subtype */
498 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
499 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
501 if (type == MKTAG('v','i','d','e'))
502 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
503 else if (type == MKTAG('s','o','u','n'))
504 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
505 else if (type == MKTAG('m','1','a',' '))
506 st->codec->codec_id = CODEC_ID_MP2;
507 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
508 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
510 avio_rb32(pb); /* component manufacture */
511 avio_rb32(pb); /* component flags */
512 avio_rb32(pb); /* component flags mask */
514 title_size = atom.size - 24;
515 if (title_size > 0) {
516 title_str = av_malloc(title_size + 1); /* Add null terminator */
518 return AVERROR(ENOMEM);
519 avio_read(pb, title_str, title_size);
520 title_str[title_size] = 0;
521 av_dict_set(&st->metadata, "handler_name", title_str, 0);
522 av_freep(&title_str);
528 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
533 if (fc->nb_streams < 1)
535 st = fc->streams[fc->nb_streams-1];
537 avio_rb32(pb); /* version + flags */
538 ff_mp4_read_descr(fc, pb, &tag);
539 if (tag == MP4ESDescrTag) {
540 ff_mp4_parse_es_descr(pb, NULL);
542 avio_rb16(pb); /* ID */
544 ff_mp4_read_descr(fc, pb, &tag);
545 if (tag == MP4DecConfigDescrTag)
546 ff_mp4_read_dec_config_descr(fc, st, pb);
550 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
552 return ff_mov_read_esds(c->fc, pb, atom);
555 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
558 int ac3info, acmod, lfeon, bsmod;
560 if (c->fc->nb_streams < 1)
562 st = c->fc->streams[c->fc->nb_streams-1];
564 ac3info = avio_rb24(pb);
565 bsmod = (ac3info >> 14) & 0x7;
566 acmod = (ac3info >> 11) & 0x7;
567 lfeon = (ac3info >> 10) & 0x1;
568 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
569 st->codec->audio_service_type = bsmod;
570 if (st->codec->channels > 1 && bsmod == 0x7)
571 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
576 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
580 uint32_t flags, layout_tag, bitmap, num_descr, label_mask;
583 if (c->fc->nb_streams < 1)
585 st = c->fc->streams[c->fc->nb_streams-1];
590 version = avio_r8(pb);
591 flags = avio_rb24(pb);
593 layout_tag = avio_rb32(pb);
594 bitmap = avio_rb32(pb);
595 num_descr = avio_rb32(pb);
597 if (atom.size < 16ULL + num_descr * 20ULL)
600 av_dlog(c->fc, "chan: size=%" PRId64 " version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
601 atom.size, version, flags, layout_tag, bitmap, num_descr);
604 for (i = 0; i < num_descr; i++) {
605 uint32_t label, cflags;
606 label = avio_rb32(pb); // mChannelLabel
607 cflags = avio_rb32(pb); // mChannelFlags
608 avio_rl32(pb); // mCoordinates[0]
609 avio_rl32(pb); // mCoordinates[1]
610 avio_rl32(pb); // mCoordinates[2]
611 if (layout_tag == 0) {
612 uint32_t mask_incr = ff_mov_get_channel_label(label);
613 if (mask_incr == 0) {
617 label_mask |= mask_incr;
621 st->codec->channel_layout = label_mask;
623 st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
628 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
632 if (c->fc->nb_streams < 1)
634 st = c->fc->streams[c->fc->nb_streams-1];
636 ff_get_wav_header(pb, st->codec, atom.size);
641 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
643 const int num = avio_rb32(pb);
644 const int den = avio_rb32(pb);
647 if (c->fc->nb_streams < 1)
649 st = c->fc->streams[c->fc->nb_streams-1];
651 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
652 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
653 av_log(c->fc, AV_LOG_WARNING,
654 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
655 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
657 } else if (den != 0) {
658 st->sample_aspect_ratio.num = num;
659 st->sample_aspect_ratio.den = den;
664 /* this atom contains actual media data */
665 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
667 if (atom.size == 0) /* wrong one (MP4) */
670 return 0; /* now go for moov */
673 /* read major brand, minor version and compatible brands and store them as metadata */
674 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
678 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
679 char* comp_brands_str;
680 uint8_t type[5] = {0};
682 avio_read(pb, type, 4);
683 if (strcmp(type, "qt "))
685 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
686 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
687 minor_ver = avio_rb32(pb); /* minor version */
688 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
689 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
691 comp_brand_size = atom.size - 8;
692 if (comp_brand_size < 0)
693 return AVERROR_INVALIDDATA;
694 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
695 if (!comp_brands_str)
696 return AVERROR(ENOMEM);
697 avio_read(pb, comp_brands_str, comp_brand_size);
698 comp_brands_str[comp_brand_size] = 0;
699 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
700 av_freep(&comp_brands_str);
705 /* this atom should contain all header atoms */
706 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
710 if ((ret = mov_read_default(c, pb, atom)) < 0)
712 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
713 /* so we don't parse the whole file if over a network */
715 return 0; /* now go for mdat */
718 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
720 c->fragment.moof_offset = avio_tell(pb) - 8;
721 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
722 return mov_read_default(c, pb, atom);
725 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
730 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
733 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
734 av_dict_set(metadata, "creation_time", buffer, 0);
738 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
741 MOVStreamContext *sc;
743 char language[4] = {0};
745 time_t creation_time;
747 if (c->fc->nb_streams < 1)
749 st = c->fc->streams[c->fc->nb_streams-1];
752 version = avio_r8(pb);
754 av_log_ask_for_sample(c, "unsupported version %d\n", version);
755 return AVERROR_PATCHWELCOME;
757 avio_rb24(pb); /* flags */
759 creation_time = avio_rb64(pb);
762 creation_time = avio_rb32(pb);
763 avio_rb32(pb); /* modification time */
765 mov_metadata_creation_time(&st->metadata, creation_time);
767 sc->time_scale = avio_rb32(pb);
768 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
770 lang = avio_rb16(pb); /* language */
771 if (ff_mov_lang_to_iso639(lang, language))
772 av_dict_set(&st->metadata, "language", language, 0);
773 avio_rb16(pb); /* quality */
778 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
780 time_t creation_time;
781 int version = avio_r8(pb); /* version */
782 avio_rb24(pb); /* flags */
785 creation_time = avio_rb64(pb);
788 creation_time = avio_rb32(pb);
789 avio_rb32(pb); /* modification time */
791 mov_metadata_creation_time(&c->fc->metadata, creation_time);
792 c->time_scale = avio_rb32(pb); /* time scale */
794 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
796 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
797 // set the AVCodecContext duration because the duration of individual tracks
799 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
800 avio_rb32(pb); /* preferred scale */
802 avio_rb16(pb); /* preferred volume */
804 avio_skip(pb, 10); /* reserved */
806 avio_skip(pb, 36); /* display matrix */
808 avio_rb32(pb); /* preview time */
809 avio_rb32(pb); /* preview duration */
810 avio_rb32(pb); /* poster time */
811 avio_rb32(pb); /* selection time */
812 avio_rb32(pb); /* selection duration */
813 avio_rb32(pb); /* current time */
814 avio_rb32(pb); /* next track ID */
818 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
822 if (c->fc->nb_streams < 1)
824 st = c->fc->streams[c->fc->nb_streams-1];
826 if ((uint64_t)atom.size > (1<<30))
827 return AVERROR_INVALIDDATA;
829 // currently SVQ3 decoder expect full STSD header - so let's fake it
830 // this should be fixed and just SMI header should be passed
831 av_free(st->codec->extradata);
832 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
833 if (!st->codec->extradata)
834 return AVERROR(ENOMEM);
835 st->codec->extradata_size = 0x5a + atom.size;
836 memcpy(st->codec->extradata, "SVQ3", 4); // fake
837 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
838 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
842 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
847 if (c->fc->nb_streams < 1)
849 st = c->fc->streams[c->fc->nb_streams-1];
851 little_endian = avio_rb16(pb) & 0xFF;
852 av_dlog(c->fc, "enda %d\n", little_endian);
853 if (little_endian == 1) {
854 switch (st->codec->codec_id) {
855 case CODEC_ID_PCM_S24BE:
856 st->codec->codec_id = CODEC_ID_PCM_S24LE;
858 case CODEC_ID_PCM_S32BE:
859 st->codec->codec_id = CODEC_ID_PCM_S32LE;
861 case CODEC_ID_PCM_F32BE:
862 st->codec->codec_id = CODEC_ID_PCM_F32LE;
864 case CODEC_ID_PCM_F64BE:
865 st->codec->codec_id = CODEC_ID_PCM_F64LE;
874 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
877 unsigned mov_field_order;
878 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
880 if (c->fc->nb_streams < 1) // will happen with jp2 files
882 st = c->fc->streams[c->fc->nb_streams-1];
884 return AVERROR_INVALIDDATA;
885 mov_field_order = avio_rb16(pb);
886 if ((mov_field_order & 0xFF00) == 0x0100)
887 decoded_field_order = AV_FIELD_PROGRESSIVE;
888 else if ((mov_field_order & 0xFF00) == 0x0200) {
889 switch (mov_field_order & 0xFF) {
890 case 0x01: decoded_field_order = AV_FIELD_TT;
892 case 0x06: decoded_field_order = AV_FIELD_BB;
894 case 0x09: decoded_field_order = AV_FIELD_TB;
896 case 0x0E: decoded_field_order = AV_FIELD_BT;
900 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
901 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
903 st->codec->field_order = decoded_field_order;
908 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
909 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
910 enum CodecID codec_id)
916 if (c->fc->nb_streams < 1) // will happen with jp2 files
918 st= c->fc->streams[c->fc->nb_streams-1];
920 if (st->codec->codec_id != codec_id)
921 return 0; /* unexpected codec_id - don't mess with extradata */
923 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
924 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
925 return AVERROR_INVALIDDATA;
926 buf= av_realloc(st->codec->extradata, size);
928 return AVERROR(ENOMEM);
929 st->codec->extradata= buf;
930 buf+= st->codec->extradata_size;
931 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
932 AV_WB32( buf , atom.size + 8);
933 AV_WL32( buf + 4, atom.type);
934 avio_read(pb, buf + 8, atom.size);
938 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
939 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
941 return mov_read_extradata(c, pb, atom, CODEC_ID_ALAC);
944 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
946 return mov_read_extradata(c, pb, atom, CODEC_ID_AVS);
949 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
951 return mov_read_extradata(c, pb, atom, CODEC_ID_JPEG2000);
954 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
958 if (c->fc->nb_streams < 1)
960 st = c->fc->streams[c->fc->nb_streams-1];
962 if ((uint64_t)atom.size > (1<<30))
963 return AVERROR_INVALIDDATA;
965 if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
966 // pass all frma atom to codec, needed at least for QDMC and QDM2
967 av_free(st->codec->extradata);
968 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
969 if (!st->codec->extradata)
970 return AVERROR(ENOMEM);
971 st->codec->extradata_size = atom.size;
972 avio_read(pb, st->codec->extradata, atom.size);
973 } else if (atom.size > 8) { /* to read frma, esds atoms */
975 if ((ret = mov_read_default(c, pb, atom)) < 0)
978 avio_skip(pb, atom.size);
983 * This function reads atom content and puts data in extradata without tag
984 * nor size unlike mov_read_extradata.
986 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
990 if (c->fc->nb_streams < 1)
992 st = c->fc->streams[c->fc->nb_streams-1];
994 if ((uint64_t)atom.size > (1<<30))
995 return AVERROR_INVALIDDATA;
997 if (atom.size >= 10) {
998 // Broken files created by legacy versions of Libav and FFmpeg will
999 // wrap a whole fiel atom inside of a glbl atom.
1000 unsigned size = avio_rb32(pb);
1001 unsigned type = avio_rl32(pb);
1002 avio_seek(pb, -8, SEEK_CUR);
1003 if (type == MKTAG('f','i','e','l') && size == atom.size)
1004 return mov_read_default(c, pb, atom);
1006 av_free(st->codec->extradata);
1007 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1008 if (!st->codec->extradata)
1009 return AVERROR(ENOMEM);
1010 st->codec->extradata_size = atom.size;
1011 avio_read(pb, st->codec->extradata, atom.size);
1016 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1017 * but can have extradata appended at the end after the 40 bytes belonging
1020 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1024 if (c->fc->nb_streams < 1)
1026 if (atom.size <= 40)
1028 st = c->fc->streams[c->fc->nb_streams-1];
1030 if ((uint64_t)atom.size > (1<<30))
1031 return AVERROR_INVALIDDATA;
1033 av_free(st->codec->extradata);
1034 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1035 if (!st->codec->extradata)
1036 return AVERROR(ENOMEM);
1037 st->codec->extradata_size = atom.size - 40;
1039 avio_read(pb, st->codec->extradata, atom.size - 40);
1043 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1046 MOVStreamContext *sc;
1047 unsigned int i, entries;
1049 if (c->fc->nb_streams < 1)
1051 st = c->fc->streams[c->fc->nb_streams-1];
1054 avio_r8(pb); /* version */
1055 avio_rb24(pb); /* flags */
1057 entries = avio_rb32(pb);
1061 if (entries >= UINT_MAX/sizeof(int64_t))
1062 return AVERROR_INVALIDDATA;
1064 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1065 if (!sc->chunk_offsets)
1066 return AVERROR(ENOMEM);
1067 sc->chunk_count = entries;
1069 if (atom.type == MKTAG('s','t','c','o'))
1070 for (i=0; i<entries; i++)
1071 sc->chunk_offsets[i] = avio_rb32(pb);
1072 else if (atom.type == MKTAG('c','o','6','4'))
1073 for (i=0; i<entries; i++)
1074 sc->chunk_offsets[i] = avio_rb64(pb);
1076 return AVERROR_INVALIDDATA;
1082 * Compute codec id for 'lpcm' tag.
1083 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1085 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1087 if (flags & 1) { // floating point
1088 if (flags & 2) { // big endian
1089 if (bps == 32) return CODEC_ID_PCM_F32BE;
1090 else if (bps == 64) return CODEC_ID_PCM_F64BE;
1092 if (bps == 32) return CODEC_ID_PCM_F32LE;
1093 else if (bps == 64) return CODEC_ID_PCM_F64LE;
1099 if (flags & 4) return CODEC_ID_PCM_S8;
1100 else return CODEC_ID_PCM_U8;
1101 else if (bps == 16) return CODEC_ID_PCM_S16BE;
1102 else if (bps == 24) return CODEC_ID_PCM_S24BE;
1103 else if (bps == 32) return CODEC_ID_PCM_S32BE;
1106 if (flags & 4) return CODEC_ID_PCM_S8;
1107 else return CODEC_ID_PCM_U8;
1108 else if (bps == 16) return CODEC_ID_PCM_S16LE;
1109 else if (bps == 24) return CODEC_ID_PCM_S24LE;
1110 else if (bps == 32) return CODEC_ID_PCM_S32LE;
1113 return CODEC_ID_NONE;
1116 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1119 MOVStreamContext *sc;
1120 int j, pseudo_stream_id;
1122 if (c->fc->nb_streams < 1)
1124 st = c->fc->streams[c->fc->nb_streams-1];
1127 for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
1128 //Parsing Sample description table
1131 MOVAtom a = { AV_RL32("stsd") };
1132 int64_t start_pos = avio_tell(pb);
1133 int size = avio_rb32(pb); /* size */
1134 uint32_t format = avio_rl32(pb); /* data format */
1137 avio_rb32(pb); /* reserved */
1138 avio_rb16(pb); /* reserved */
1139 dref_id = avio_rb16(pb);
1140 }else if (size <= 0){
1141 av_log(c->fc, AV_LOG_ERROR, "invalid size %d in stsd\n", size);
1145 if (st->codec->codec_tag &&
1146 st->codec->codec_tag != format &&
1147 (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
1148 : st->codec->codec_tag != MKTAG('j','p','e','g'))
1150 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1151 * export it as a separate AVStream but this needs a few changes
1152 * in the MOV demuxer, patch welcome. */
1154 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1155 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1158 /* we cannot demux concatenated h264 streams because of different extradata */
1159 if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1161 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1162 sc->dref_id= dref_id;
1164 st->codec->codec_tag = format;
1165 id = ff_codec_get_id(codec_movaudio_tags, format);
1166 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1167 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1169 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1170 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1171 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1172 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1173 id = ff_codec_get_id(codec_movvideo_tags, format);
1175 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1177 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1178 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){
1179 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1181 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1185 av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1186 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1187 (format >> 24) & 0xff, st->codec->codec_type);
1189 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1190 unsigned int color_depth, len;
1191 int color_greyscale;
1193 st->codec->codec_id = id;
1194 avio_rb16(pb); /* version */
1195 avio_rb16(pb); /* revision level */
1196 avio_rb32(pb); /* vendor */
1197 avio_rb32(pb); /* temporal quality */
1198 avio_rb32(pb); /* spatial quality */
1200 st->codec->width = avio_rb16(pb); /* width */
1201 st->codec->height = avio_rb16(pb); /* height */
1203 avio_rb32(pb); /* horiz resolution */
1204 avio_rb32(pb); /* vert resolution */
1205 avio_rb32(pb); /* data size, always 0 */
1206 avio_rb16(pb); /* frames per samples */
1208 len = avio_r8(pb); /* codec name, pascal string */
1211 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1213 avio_skip(pb, 31 - len);
1214 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1215 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1216 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1218 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1219 st->codec->color_table_id = avio_rb16(pb); /* colortable id */
1220 av_dlog(c->fc, "depth %d, ctab id %d\n",
1221 st->codec->bits_per_coded_sample, st->codec->color_table_id);
1222 /* figure out the palette situation */
1223 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1224 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1226 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1227 if ((color_depth == 2) || (color_depth == 4) ||
1228 (color_depth == 8)) {
1229 /* for palette traversal */
1230 unsigned int color_start, color_count, color_end;
1231 unsigned char a, r, g, b;
1233 if (color_greyscale) {
1234 int color_index, color_dec;
1235 /* compute the greyscale palette */
1236 st->codec->bits_per_coded_sample = color_depth;
1237 color_count = 1 << color_depth;
1239 color_dec = 256 / (color_count - 1);
1240 for (j = 0; j < color_count; j++) {
1241 if (id == CODEC_ID_CINEPAK){
1242 r = g = b = color_count - 1 - color_index;
1244 r = g = b = color_index;
1246 (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1247 color_index -= color_dec;
1248 if (color_index < 0)
1251 } else if (st->codec->color_table_id) {
1252 const uint8_t *color_table;
1253 /* if flag bit 3 is set, use the default palette */
1254 color_count = 1 << color_depth;
1255 if (color_depth == 2)
1256 color_table = ff_qt_default_palette_4;
1257 else if (color_depth == 4)
1258 color_table = ff_qt_default_palette_16;
1260 color_table = ff_qt_default_palette_256;
1262 for (j = 0; j < color_count; j++) {
1263 r = color_table[j * 3 + 0];
1264 g = color_table[j * 3 + 1];
1265 b = color_table[j * 3 + 2];
1267 (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1270 /* load the palette from the file */
1271 color_start = avio_rb32(pb);
1272 color_count = avio_rb16(pb);
1273 color_end = avio_rb16(pb);
1274 if ((color_start <= 255) &&
1275 (color_end <= 255)) {
1276 for (j = color_start; j <= color_end; j++) {
1277 /* each A, R, G, or B component is 16 bits;
1278 * only use the top 8 bits */
1288 (a << 24 ) | (r << 16) | (g << 8) | (b);
1292 sc->has_palette = 1;
1294 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1295 int bits_per_sample, flags;
1296 uint16_t version = avio_rb16(pb);
1298 st->codec->codec_id = id;
1299 avio_rb16(pb); /* revision level */
1300 avio_rb32(pb); /* vendor */
1302 st->codec->channels = avio_rb16(pb); /* channel count */
1303 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1304 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1306 sc->audio_cid = avio_rb16(pb);
1307 avio_rb16(pb); /* packet size = 0 */
1309 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1311 //Read QT version 1 fields. In version 0 these do not exist.
1312 av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1315 sc->samples_per_frame = avio_rb32(pb);
1316 avio_rb32(pb); /* bytes per packet */
1317 sc->bytes_per_frame = avio_rb32(pb);
1318 avio_rb32(pb); /* bytes per sample */
1319 } else if (version==2) {
1320 avio_rb32(pb); /* sizeof struct only */
1321 st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
1322 st->codec->channels = avio_rb32(pb);
1323 avio_rb32(pb); /* always 0x7F000000 */
1324 st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1325 flags = avio_rb32(pb); /* lpcm format specific flag */
1326 sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1327 sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1328 if (format == MKTAG('l','p','c','m'))
1329 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1333 switch (st->codec->codec_id) {
1334 case CODEC_ID_PCM_S8:
1335 case CODEC_ID_PCM_U8:
1336 if (st->codec->bits_per_coded_sample == 16)
1337 st->codec->codec_id = CODEC_ID_PCM_S16BE;
1339 case CODEC_ID_PCM_S16LE:
1340 case CODEC_ID_PCM_S16BE:
1341 if (st->codec->bits_per_coded_sample == 8)
1342 st->codec->codec_id = CODEC_ID_PCM_S8;
1343 else if (st->codec->bits_per_coded_sample == 24)
1344 st->codec->codec_id =
1345 st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1346 CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1348 /* set values for old format before stsd version 1 appeared */
1349 case CODEC_ID_MACE3:
1350 sc->samples_per_frame = 6;
1351 sc->bytes_per_frame = 2*st->codec->channels;
1353 case CODEC_ID_MACE6:
1354 sc->samples_per_frame = 6;
1355 sc->bytes_per_frame = 1*st->codec->channels;
1357 case CODEC_ID_ADPCM_IMA_QT:
1358 sc->samples_per_frame = 64;
1359 sc->bytes_per_frame = 34*st->codec->channels;
1362 sc->samples_per_frame = 160;
1363 sc->bytes_per_frame = 33;
1369 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1370 if (bits_per_sample) {
1371 st->codec->bits_per_coded_sample = bits_per_sample;
1372 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1374 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1375 // ttxt stsd contains display flags, justification, background
1376 // color, fonts, and default styles, so fake an atom to read it
1377 MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1378 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1379 mov_read_glbl(c, pb, fake_atom);
1380 st->codec->codec_id= id;
1381 st->codec->width = sc->width;
1382 st->codec->height = sc->height;
1384 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1386 avio_rb32(pb); /* reserved */
1387 val = avio_rb32(pb); /* flags */
1389 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1390 avio_rb32(pb); /* time scale */
1391 avio_rb32(pb); /* frame duration */
1392 st->codec->time_base.den = avio_r8(pb); /* number of frame */
1393 st->codec->time_base.num = 1;
1395 /* other codec type, just skip (rtp, mp4s, ...) */
1396 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1398 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1399 a.size = size - (avio_tell(pb) - start_pos);
1402 if ((ret = mov_read_default(c, pb, a)) < 0)
1404 } else if (a.size > 0)
1405 avio_skip(pb, a.size);
1408 if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1409 st->codec->sample_rate= sc->time_scale;
1411 /* special codec parameters handling */
1412 switch (st->codec->codec_id) {
1413 #if CONFIG_DV_DEMUXER
1414 case CODEC_ID_DVAUDIO:
1415 c->dv_fctx = avformat_alloc_context();
1416 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1418 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1419 return AVERROR(ENOMEM);
1421 sc->dv_audio_container = 1;
1422 st->codec->codec_id = CODEC_ID_PCM_S16LE;
1425 /* no ifdef since parameters are always those */
1426 case CODEC_ID_QCELP:
1427 // force sample rate for qcelp when not stored in mov
1428 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1429 st->codec->sample_rate = 8000;
1430 st->codec->frame_size= 160;
1431 st->codec->channels= 1; /* really needed */
1433 case CODEC_ID_AMR_NB:
1434 st->codec->channels= 1; /* really needed */
1435 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1436 st->codec->sample_rate = 8000;
1437 /* force frame_size, too, samples_per_frame isn't always set properly */
1438 st->codec->frame_size = 160;
1440 case CODEC_ID_AMR_WB:
1441 st->codec->channels = 1;
1442 st->codec->sample_rate = 16000;
1443 st->codec->frame_size = 320;
1447 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1448 st->need_parsing = AVSTREAM_PARSE_FULL;
1451 case CODEC_ID_ADPCM_MS:
1452 case CODEC_ID_ADPCM_IMA_WAV:
1453 st->codec->frame_size = sc->samples_per_frame;
1454 st->codec->block_align = sc->bytes_per_frame;
1457 if (st->codec->extradata_size == 36) {
1458 st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1459 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1460 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1464 st->need_parsing = AVSTREAM_PARSE_FULL;
1466 case CODEC_ID_MPEG1VIDEO:
1467 st->need_parsing = AVSTREAM_PARSE_FULL;
1476 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1480 avio_r8(pb); /* version */
1481 avio_rb24(pb); /* flags */
1482 entries = avio_rb32(pb);
1484 return ff_mov_read_stsd_entries(c, pb, entries);
1487 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1490 MOVStreamContext *sc;
1491 unsigned int i, entries;
1493 if (c->fc->nb_streams < 1)
1495 st = c->fc->streams[c->fc->nb_streams-1];
1498 avio_r8(pb); /* version */
1499 avio_rb24(pb); /* flags */
1501 entries = avio_rb32(pb);
1503 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1507 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1508 return AVERROR_INVALIDDATA;
1509 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1511 return AVERROR(ENOMEM);
1512 sc->stsc_count = entries;
1514 for (i=0; i<entries; i++) {
1515 sc->stsc_data[i].first = avio_rb32(pb);
1516 sc->stsc_data[i].count = avio_rb32(pb);
1517 sc->stsc_data[i].id = avio_rb32(pb);
1522 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1525 MOVStreamContext *sc;
1526 unsigned i, entries;
1528 if (c->fc->nb_streams < 1)
1530 st = c->fc->streams[c->fc->nb_streams-1];
1533 avio_rb32(pb); // version + flags
1535 entries = avio_rb32(pb);
1536 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1537 return AVERROR_INVALIDDATA;
1538 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1540 return AVERROR(ENOMEM);
1541 sc->stps_count = entries;
1543 for (i = 0; i < entries; i++) {
1544 sc->stps_data[i] = avio_rb32(pb);
1545 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1551 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1554 MOVStreamContext *sc;
1555 unsigned int i, entries;
1557 if (c->fc->nb_streams < 1)
1559 st = c->fc->streams[c->fc->nb_streams-1];
1562 avio_r8(pb); /* version */
1563 avio_rb24(pb); /* flags */
1565 entries = avio_rb32(pb);
1567 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1569 if (entries >= UINT_MAX / sizeof(int))
1570 return AVERROR_INVALIDDATA;
1571 sc->keyframes = av_malloc(entries * sizeof(int));
1573 return AVERROR(ENOMEM);
1574 sc->keyframe_count = entries;
1576 for (i=0; i<entries; i++) {
1577 sc->keyframes[i] = avio_rb32(pb);
1578 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1583 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1586 MOVStreamContext *sc;
1587 unsigned int i, entries, sample_size, field_size, num_bytes;
1591 if (c->fc->nb_streams < 1)
1593 st = c->fc->streams[c->fc->nb_streams-1];
1596 avio_r8(pb); /* version */
1597 avio_rb24(pb); /* flags */
1599 if (atom.type == MKTAG('s','t','s','z')) {
1600 sample_size = avio_rb32(pb);
1601 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1602 sc->sample_size = sample_size;
1606 avio_rb24(pb); /* reserved */
1607 field_size = avio_r8(pb);
1609 entries = avio_rb32(pb);
1611 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1613 sc->sample_count = entries;
1617 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1618 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1619 return AVERROR_INVALIDDATA;
1624 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1625 return AVERROR_INVALIDDATA;
1626 sc->sample_sizes = av_malloc(entries * sizeof(int));
1627 if (!sc->sample_sizes)
1628 return AVERROR(ENOMEM);
1630 num_bytes = (entries*field_size+4)>>3;
1632 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1634 av_freep(&sc->sample_sizes);
1635 return AVERROR(ENOMEM);
1638 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1639 av_freep(&sc->sample_sizes);
1641 return AVERROR_INVALIDDATA;
1644 init_get_bits(&gb, buf, 8*num_bytes);
1646 for (i = 0; i < entries; i++) {
1647 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1648 sc->data_size += sc->sample_sizes[i];
1655 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1658 MOVStreamContext *sc;
1659 unsigned int i, entries;
1661 int64_t total_sample_count=0;
1663 if (c->fc->nb_streams < 1)
1665 st = c->fc->streams[c->fc->nb_streams-1];
1668 avio_r8(pb); /* version */
1669 avio_rb24(pb); /* flags */
1670 entries = avio_rb32(pb);
1672 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1673 c->fc->nb_streams-1, entries);
1675 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1678 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1680 return AVERROR(ENOMEM);
1682 sc->stts_count = entries;
1684 for (i=0; i<entries; i++) {
1685 int sample_duration;
1688 sample_count=avio_rb32(pb);
1689 sample_duration = avio_rb32(pb);
1690 /* sample_duration < 0 is invalid based on the spec */
1691 if (sample_duration < 0) {
1692 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
1693 sample_duration = 1;
1695 sc->stts_data[i].count= sample_count;
1696 sc->stts_data[i].duration= sample_duration;
1698 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1699 sample_count, sample_duration);
1701 duration+=(int64_t)sample_duration*sample_count;
1702 total_sample_count+=sample_count;
1705 st->nb_frames= total_sample_count;
1707 st->duration= duration;
1711 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1714 MOVStreamContext *sc;
1715 unsigned int i, entries;
1717 if (c->fc->nb_streams < 1)
1719 st = c->fc->streams[c->fc->nb_streams-1];
1722 avio_r8(pb); /* version */
1723 avio_rb24(pb); /* flags */
1724 entries = avio_rb32(pb);
1726 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1730 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1731 return AVERROR_INVALIDDATA;
1732 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1734 return AVERROR(ENOMEM);
1735 sc->ctts_count = entries;
1737 for (i=0; i<entries; i++) {
1738 int count =avio_rb32(pb);
1739 int duration =avio_rb32(pb);
1741 sc->ctts_data[i].count = count;
1742 sc->ctts_data[i].duration= duration;
1743 if (duration < 0 && i+2<entries)
1744 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1747 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1752 static void mov_build_index(MOVContext *mov, AVStream *st)
1754 MOVStreamContext *sc = st->priv_data;
1755 int64_t current_offset;
1756 int64_t current_dts = 0;
1757 unsigned int stts_index = 0;
1758 unsigned int stsc_index = 0;
1759 unsigned int stss_index = 0;
1760 unsigned int stps_index = 0;
1762 uint64_t stream_size = 0;
1764 /* adjust first dts according to edit list */
1765 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
1766 if (sc->empty_duration)
1767 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
1768 sc->time_offset = sc->start_time - sc->empty_duration;
1769 current_dts = -sc->time_offset;
1770 if (sc->ctts_data && sc->stts_data &&
1771 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1772 /* more than 16 frames delay, dts are likely wrong
1773 this happens with files created by iMovie */
1775 st->codec->has_b_frames = 1;
1779 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1780 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1781 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1782 unsigned int current_sample = 0;
1783 unsigned int stts_sample = 0;
1784 unsigned int sample_size;
1785 unsigned int distance = 0;
1786 int key_off = sc->keyframes && sc->keyframes[0] == 1;
1788 current_dts -= sc->dts_shift;
1790 if (!sc->sample_count)
1792 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
1794 st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
1795 if (!st->index_entries)
1797 st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
1799 for (i = 0; i < sc->chunk_count; i++) {
1800 current_offset = sc->chunk_offsets[i];
1801 while (stsc_index + 1 < sc->stsc_count &&
1802 i + 1 == sc->stsc_data[stsc_index + 1].first)
1804 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1806 if (current_sample >= sc->sample_count) {
1807 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1811 if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1813 if (stss_index + 1 < sc->keyframe_count)
1815 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1817 if (stps_index + 1 < sc->stps_count)
1822 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1823 if (sc->pseudo_stream_id == -1 ||
1824 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1825 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1826 e->pos = current_offset;
1827 e->timestamp = current_dts;
1828 e->size = sample_size;
1829 e->min_distance = distance;
1830 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1831 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1832 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1833 current_offset, current_dts, sample_size, distance, keyframe);
1836 current_offset += sample_size;
1837 stream_size += sample_size;
1838 current_dts += sc->stts_data[stts_index].duration;
1842 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1848 if (st->duration > 0)
1849 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1851 unsigned chunk_samples, total = 0;
1853 // compute total chunk count
1854 for (i = 0; i < sc->stsc_count; i++) {
1855 unsigned count, chunk_count;
1857 chunk_samples = sc->stsc_data[i].count;
1858 if (i != sc->stsc_count - 1 &&
1859 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1860 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1864 if (sc->samples_per_frame >= 160) { // gsm
1865 count = chunk_samples / sc->samples_per_frame;
1866 } else if (sc->samples_per_frame > 1) {
1867 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1868 count = (chunk_samples+samples-1) / samples;
1870 count = (chunk_samples+1023) / 1024;
1873 if (i < sc->stsc_count - 1)
1874 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1876 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1877 total += chunk_count * count;
1880 av_dlog(mov->fc, "chunk count %d\n", total);
1881 if (total >= UINT_MAX / sizeof(*st->index_entries))
1883 st->index_entries = av_malloc(total*sizeof(*st->index_entries));
1884 if (!st->index_entries)
1886 st->index_entries_allocated_size = total*sizeof(*st->index_entries);
1889 for (i = 0; i < sc->chunk_count; i++) {
1890 current_offset = sc->chunk_offsets[i];
1891 if (stsc_index + 1 < sc->stsc_count &&
1892 i + 1 == sc->stsc_data[stsc_index + 1].first)
1894 chunk_samples = sc->stsc_data[stsc_index].count;
1896 while (chunk_samples > 0) {
1898 unsigned size, samples;
1900 if (sc->samples_per_frame >= 160) { // gsm
1901 samples = sc->samples_per_frame;
1902 size = sc->bytes_per_frame;
1904 if (sc->samples_per_frame > 1) {
1905 samples = FFMIN((1024 / sc->samples_per_frame)*
1906 sc->samples_per_frame, chunk_samples);
1907 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1909 samples = FFMIN(1024, chunk_samples);
1910 size = samples * sc->sample_size;
1914 if (st->nb_index_entries >= total) {
1915 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1918 e = &st->index_entries[st->nb_index_entries++];
1919 e->pos = current_offset;
1920 e->timestamp = current_dts;
1922 e->min_distance = 0;
1923 e->flags = AVINDEX_KEYFRAME;
1924 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1925 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1928 current_offset += size;
1929 current_dts += samples;
1930 chunk_samples -= samples;
1936 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
1937 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
1939 /* try relative path, we do not try the absolute because it can leak information about our
1940 system to an attacker */
1941 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1942 char filename[1024];
1943 const char *src_path;
1946 /* find a source dir */
1947 src_path = strrchr(src, '/');
1953 /* find a next level down to target */
1954 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1955 if (ref->path[l] == '/') {
1956 if (i == ref->nlvl_to - 1)
1962 /* compose filename if next level down to target was found */
1963 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
1964 memcpy(filename, src, src_path - src);
1965 filename[src_path - src] = 0;
1967 for (i = 1; i < ref->nlvl_from; i++)
1968 av_strlcat(filename, "../", 1024);
1970 av_strlcat(filename, ref->path + l + 1, 1024);
1972 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
1975 } else if (use_absolute_path) {
1976 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
1977 "this is a possible security issue\n");
1978 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
1982 return AVERROR(ENOENT);
1985 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1988 MOVStreamContext *sc;
1991 st = avformat_new_stream(c->fc, NULL);
1992 if (!st) return AVERROR(ENOMEM);
1993 st->id = c->fc->nb_streams;
1994 sc = av_mallocz(sizeof(MOVStreamContext));
1995 if (!sc) return AVERROR(ENOMEM);
1998 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1999 sc->ffindex = st->index;
2001 if ((ret = mov_read_default(c, pb, atom)) < 0)
2005 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2006 (!sc->sample_size && !sc->sample_count))) {
2007 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2012 if (sc->time_scale <= 0) {
2013 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2014 sc->time_scale = c->time_scale;
2015 if (sc->time_scale <= 0)
2019 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2021 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2022 !st->codec->frame_size && sc->stts_count == 1) {
2023 st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
2024 st->codec->sample_rate, sc->time_scale);
2025 av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
2028 mov_build_index(c, st);
2030 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2031 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2032 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2033 c->use_absolute_path, c->fc) < 0)
2034 av_log(c->fc, AV_LOG_ERROR,
2035 "stream %d, error opening alias: path='%s', dir='%s', "
2036 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2037 st->index, dref->path, dref->dir, dref->filename,
2038 dref->volume, dref->nlvl_from, dref->nlvl_to);
2042 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2043 if (!st->sample_aspect_ratio.num &&
2044 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2045 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2046 ((double)st->codec->width * sc->height), INT_MAX);
2049 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2050 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2052 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2053 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2054 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2057 switch (st->codec->codec_id) {
2058 #if CONFIG_H261_DECODER
2061 #if CONFIG_H263_DECODER
2064 #if CONFIG_H264_DECODER
2067 #if CONFIG_MPEG4_DECODER
2068 case CODEC_ID_MPEG4:
2070 st->codec->width = 0; /* let decoder init width/height */
2071 st->codec->height= 0;
2075 /* Do not need those anymore. */
2076 av_freep(&sc->chunk_offsets);
2077 av_freep(&sc->stsc_data);
2078 av_freep(&sc->sample_sizes);
2079 av_freep(&sc->keyframes);
2080 av_freep(&sc->stts_data);
2081 av_freep(&sc->stps_data);
2086 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2089 c->itunes_metadata = 1;
2090 ret = mov_read_default(c, pb, atom);
2091 c->itunes_metadata = 0;
2095 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2097 while (atom.size > 8) {
2098 uint32_t tag = avio_rl32(pb);
2100 if (tag == MKTAG('h','d','l','r')) {
2101 avio_seek(pb, -8, SEEK_CUR);
2103 return mov_read_default(c, pb, atom);
2109 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2114 int64_t disp_transform[2];
2115 int display_matrix[3][2];
2117 MOVStreamContext *sc;
2120 if (c->fc->nb_streams < 1)
2122 st = c->fc->streams[c->fc->nb_streams-1];
2125 version = avio_r8(pb);
2126 avio_rb24(pb); /* flags */
2128 MOV_TRACK_ENABLED 0x0001
2129 MOV_TRACK_IN_MOVIE 0x0002
2130 MOV_TRACK_IN_PREVIEW 0x0004
2131 MOV_TRACK_IN_POSTER 0x0008
2138 avio_rb32(pb); /* creation time */
2139 avio_rb32(pb); /* modification time */
2141 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2142 avio_rb32(pb); /* reserved */
2144 /* highlevel (considering edits) duration in movie timebase */
2145 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2146 avio_rb32(pb); /* reserved */
2147 avio_rb32(pb); /* reserved */
2149 avio_rb16(pb); /* layer */
2150 avio_rb16(pb); /* alternate group */
2151 avio_rb16(pb); /* volume */
2152 avio_rb16(pb); /* reserved */
2154 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2155 // they're kept in fixed point format through all calculations
2156 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2157 for (i = 0; i < 3; i++) {
2158 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2159 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2160 avio_rb32(pb); // 2.30 fixed point (not used)
2163 width = avio_rb32(pb); // 16.16 fixed point track width
2164 height = avio_rb32(pb); // 16.16 fixed point track height
2165 sc->width = width >> 16;
2166 sc->height = height >> 16;
2168 //Assign clockwise rotate values based on transform matrix so that
2169 //we can compensate for iPhone orientation during capture.
2171 if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2172 av_dict_set(&st->metadata, "rotate", "90", 0);
2175 if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2176 av_dict_set(&st->metadata, "rotate", "180", 0);
2179 if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2180 av_dict_set(&st->metadata, "rotate", "270", 0);
2183 // transform the display width/height according to the matrix
2184 // skip this if the display matrix is the default identity matrix
2185 // or if it is rotating the picture, ex iPhone 3GS
2186 // to keep the same scale, use [width height 1<<16]
2187 if (width && height &&
2188 ((display_matrix[0][0] != 65536 ||
2189 display_matrix[1][1] != 65536) &&
2190 !display_matrix[0][1] &&
2191 !display_matrix[1][0] &&
2192 !display_matrix[2][0] && !display_matrix[2][1])) {
2193 for (i = 0; i < 2; i++)
2195 (int64_t) width * display_matrix[0][i] +
2196 (int64_t) height * display_matrix[1][i] +
2197 ((int64_t) display_matrix[2][i] << 16);
2199 //sample aspect ratio is new width/height divided by old width/height
2200 st->sample_aspect_ratio = av_d2q(
2201 ((double) disp_transform[0] * height) /
2202 ((double) disp_transform[1] * width), INT_MAX);
2207 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2209 MOVFragment *frag = &c->fragment;
2210 MOVTrackExt *trex = NULL;
2211 int flags, track_id, i;
2213 avio_r8(pb); /* version */
2214 flags = avio_rb24(pb);
2216 track_id = avio_rb32(pb);
2218 return AVERROR_INVALIDDATA;
2219 frag->track_id = track_id;
2220 for (i = 0; i < c->trex_count; i++)
2221 if (c->trex_data[i].track_id == frag->track_id) {
2222 trex = &c->trex_data[i];
2226 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2227 return AVERROR_INVALIDDATA;
2230 if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
2231 else frag->base_data_offset = frag->moof_offset;
2232 if (flags & 0x02) frag->stsd_id = avio_rb32(pb);
2233 else frag->stsd_id = trex->stsd_id;
2235 frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
2236 frag->size = flags & 0x10 ? avio_rb32(pb) : trex->size;
2237 frag->flags = flags & 0x20 ? avio_rb32(pb) : trex->flags;
2238 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2242 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2244 c->chapter_track = avio_rb32(pb);
2248 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2252 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2253 return AVERROR_INVALIDDATA;
2254 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2256 return AVERROR(ENOMEM);
2258 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2260 c->trex_data = trex;
2261 trex = &c->trex_data[c->trex_count++];
2262 avio_r8(pb); /* version */
2263 avio_rb24(pb); /* flags */
2264 trex->track_id = avio_rb32(pb);
2265 trex->stsd_id = avio_rb32(pb);
2266 trex->duration = avio_rb32(pb);
2267 trex->size = avio_rb32(pb);
2268 trex->flags = avio_rb32(pb);
2272 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2274 MOVFragment *frag = &c->fragment;
2275 AVStream *st = NULL;
2276 MOVStreamContext *sc;
2280 int data_offset = 0;
2281 unsigned entries, first_sample_flags = frag->flags;
2282 int flags, distance, i;
2284 for (i = 0; i < c->fc->nb_streams; i++) {
2285 if (c->fc->streams[i]->id == frag->track_id) {
2286 st = c->fc->streams[i];
2291 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2292 return AVERROR_INVALIDDATA;
2295 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2297 avio_r8(pb); /* version */
2298 flags = avio_rb24(pb);
2299 entries = avio_rb32(pb);
2300 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2302 /* Always assume the presence of composition time offsets.
2303 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2304 * 1) in the initial movie, there are no samples.
2305 * 2) in the first movie fragment, there is only one sample without composition time offset.
2306 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2307 if (!sc->ctts_count && sc->sample_count)
2309 /* Complement ctts table if moov atom doesn't have ctts atom. */
2310 ctts_data = av_malloc(sizeof(*sc->ctts_data));
2312 return AVERROR(ENOMEM);
2313 sc->ctts_data = ctts_data;
2314 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2315 sc->ctts_data[sc->ctts_count].duration = 0;
2318 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2319 return AVERROR_INVALIDDATA;
2320 ctts_data = av_realloc(sc->ctts_data,
2321 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2323 return AVERROR(ENOMEM);
2324 sc->ctts_data = ctts_data;
2326 if (flags & 0x001) data_offset = avio_rb32(pb);
2327 if (flags & 0x004) first_sample_flags = avio_rb32(pb);
2328 dts = st->duration - sc->time_offset;
2329 offset = frag->base_data_offset + data_offset;
2331 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2332 for (i = 0; i < entries; i++) {
2333 unsigned sample_size = frag->size;
2334 int sample_flags = i ? frag->flags : first_sample_flags;
2335 unsigned sample_duration = frag->duration;
2338 if (flags & 0x100) sample_duration = avio_rb32(pb);
2339 if (flags & 0x200) sample_size = avio_rb32(pb);
2340 if (flags & 0x400) sample_flags = avio_rb32(pb);
2341 sc->ctts_data[sc->ctts_count].count = 1;
2342 sc->ctts_data[sc->ctts_count].duration = (flags & 0x800) ? avio_rb32(pb) : 0;
2344 if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
2345 (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
2347 av_add_index_entry(st, offset, dts, sample_size, distance,
2348 keyframe ? AVINDEX_KEYFRAME : 0);
2349 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2350 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2351 offset, dts, sample_size, distance, keyframe);
2353 dts += sample_duration;
2354 offset += sample_size;
2355 sc->data_size += sample_size;
2357 frag->moof_offset = offset;
2358 st->duration = dts + sc->time_offset;
2362 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2363 /* like the files created with Adobe Premiere 5.0, for samples see */
2364 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2365 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2370 return 0; /* continue */
2371 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2372 avio_skip(pb, atom.size - 4);
2375 atom.type = avio_rl32(pb);
2377 if (atom.type != MKTAG('m','d','a','t')) {
2378 avio_skip(pb, atom.size);
2381 err = mov_read_mdat(c, pb, atom);
2385 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2390 uint8_t *moov_data; /* uncompressed data */
2391 long cmov_len, moov_len;
2394 avio_rb32(pb); /* dcom atom */
2395 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2396 return AVERROR_INVALIDDATA;
2397 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2398 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2399 return AVERROR_INVALIDDATA;
2401 avio_rb32(pb); /* cmvd atom */
2402 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2403 return AVERROR_INVALIDDATA;
2404 moov_len = avio_rb32(pb); /* uncompressed size */
2405 cmov_len = atom.size - 6 * 4;
2407 cmov_data = av_malloc(cmov_len);
2409 return AVERROR(ENOMEM);
2410 moov_data = av_malloc(moov_len);
2413 return AVERROR(ENOMEM);
2415 avio_read(pb, cmov_data, cmov_len);
2416 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2417 goto free_and_return;
2418 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2419 goto free_and_return;
2420 atom.type = MKTAG('m','o','o','v');
2421 atom.size = moov_len;
2422 ret = mov_read_default(c, &ctx, atom);
2428 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2429 return AVERROR(ENOSYS);
2433 /* edit list atom */
2434 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2436 MOVStreamContext *sc;
2437 int i, edit_count, version, edit_start_index = 0;
2439 if (c->fc->nb_streams < 1)
2441 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2443 version = avio_r8(pb); /* version */
2444 avio_rb24(pb); /* flags */
2445 edit_count = avio_rb32(pb); /* entries */
2447 if ((uint64_t)edit_count*12+8 > atom.size)
2448 return AVERROR_INVALIDDATA;
2450 for (i=0; i<edit_count; i++){
2454 duration = avio_rb64(pb);
2455 time = avio_rb64(pb);
2457 duration = avio_rb32(pb); /* segment duration */
2458 time = (int32_t)avio_rb32(pb); /* media time */
2460 avio_rb32(pb); /* Media rate */
2461 if (i == 0 && time == -1) {
2462 sc->empty_duration = duration;
2463 edit_start_index = 1;
2464 } else if (i == edit_start_index && time >= 0)
2465 sc->start_time = time;
2469 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2470 "a/v desync might occur, patch welcome\n");
2472 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2476 static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2481 ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
2485 static const MOVParseTableEntry mov_default_parse_table[] = {
2486 { MKTAG('a','v','s','s'), mov_read_avss },
2487 { MKTAG('c','h','p','l'), mov_read_chpl },
2488 { MKTAG('c','o','6','4'), mov_read_stco },
2489 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2490 { MKTAG('d','i','n','f'), mov_read_default },
2491 { MKTAG('d','r','e','f'), mov_read_dref },
2492 { MKTAG('e','d','t','s'), mov_read_default },
2493 { MKTAG('e','l','s','t'), mov_read_elst },
2494 { MKTAG('e','n','d','a'), mov_read_enda },
2495 { MKTAG('f','i','e','l'), mov_read_fiel },
2496 { MKTAG('f','t','y','p'), mov_read_ftyp },
2497 { MKTAG('g','l','b','l'), mov_read_glbl },
2498 { MKTAG('h','d','l','r'), mov_read_hdlr },
2499 { MKTAG('i','l','s','t'), mov_read_ilst },
2500 { MKTAG('j','p','2','h'), mov_read_jp2h },
2501 { MKTAG('m','d','a','t'), mov_read_mdat },
2502 { MKTAG('m','d','h','d'), mov_read_mdhd },
2503 { MKTAG('m','d','i','a'), mov_read_default },
2504 { MKTAG('m','e','t','a'), mov_read_meta },
2505 { MKTAG('m','i','n','f'), mov_read_default },
2506 { MKTAG('m','o','o','f'), mov_read_moof },
2507 { MKTAG('m','o','o','v'), mov_read_moov },
2508 { MKTAG('m','v','e','x'), mov_read_default },
2509 { MKTAG('m','v','h','d'), mov_read_mvhd },
2510 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2511 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
2512 { MKTAG('a','v','c','C'), mov_read_glbl },
2513 { MKTAG('p','a','s','p'), mov_read_pasp },
2514 { MKTAG('s','t','b','l'), mov_read_default },
2515 { MKTAG('s','t','c','o'), mov_read_stco },
2516 { MKTAG('s','t','p','s'), mov_read_stps },
2517 { MKTAG('s','t','r','f'), mov_read_strf },
2518 { MKTAG('s','t','s','c'), mov_read_stsc },
2519 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2520 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2521 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2522 { MKTAG('s','t','t','s'), mov_read_stts },
2523 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2524 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2525 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2526 { MKTAG('t','r','a','k'), mov_read_trak },
2527 { MKTAG('t','r','a','f'), mov_read_default },
2528 { MKTAG('t','r','e','f'), mov_read_default },
2529 { MKTAG('c','h','a','p'), mov_read_chap },
2530 { MKTAG('t','r','e','x'), mov_read_trex },
2531 { MKTAG('t','r','u','n'), mov_read_trun },
2532 { MKTAG('u','d','t','a'), mov_read_default },
2533 { MKTAG('w','a','v','e'), mov_read_wave },
2534 { MKTAG('e','s','d','s'), mov_read_esds },
2535 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2536 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2537 { MKTAG('w','f','e','x'), mov_read_wfex },
2538 { MKTAG('c','m','o','v'), mov_read_cmov },
2539 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2543 static int mov_probe(AVProbeData *p)
2545 unsigned int offset;
2549 /* check file header */
2552 /* ignore invalid offset */
2553 if ((offset + 8) > (unsigned int)p->buf_size)
2555 tag = AV_RL32(p->buf + offset + 4);
2557 /* check for obvious tags */
2558 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2559 case MKTAG('m','o','o','v'):
2560 case MKTAG('m','d','a','t'):
2561 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2562 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2563 case MKTAG('f','t','y','p'):
2564 return AVPROBE_SCORE_MAX;
2565 /* those are more common words, so rate then a bit less */
2566 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2567 case MKTAG('w','i','d','e'):
2568 case MKTAG('f','r','e','e'):
2569 case MKTAG('j','u','n','k'):
2570 case MKTAG('p','i','c','t'):
2571 return AVPROBE_SCORE_MAX - 5;
2572 case MKTAG(0x82,0x82,0x7f,0x7d):
2573 case MKTAG('s','k','i','p'):
2574 case MKTAG('u','u','i','d'):
2575 case MKTAG('p','r','f','l'):
2576 offset = AV_RB32(p->buf+offset) + offset;
2577 /* if we only find those cause probedata is too small at least rate them */
2578 score = AVPROBE_SCORE_MAX - 50;
2581 /* unrecognized tag */
2587 // must be done after parsing all trak because there's no order requirement
2588 static void mov_read_chapters(AVFormatContext *s)
2590 MOVContext *mov = s->priv_data;
2591 AVStream *st = NULL;
2592 MOVStreamContext *sc;
2596 for (i = 0; i < s->nb_streams; i++)
2597 if (s->streams[i]->id == mov->chapter_track) {
2602 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2606 st->discard = AVDISCARD_ALL;
2608 cur_pos = avio_tell(sc->pb);
2610 for (i = 0; i < st->nb_index_entries; i++) {
2611 AVIndexEntry *sample = &st->index_entries[i];
2612 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2617 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2618 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2622 // the first two bytes are the length of the title
2623 len = avio_rb16(sc->pb);
2624 if (len > sample->size-2)
2626 title_len = 2*len + 1;
2627 if (!(title = av_mallocz(title_len)))
2630 // The samples could theoretically be in any encoding if there's an encd
2631 // atom following, but in practice are only utf-8 or utf-16, distinguished
2632 // instead by the presence of a BOM
2636 ch = avio_rb16(sc->pb);
2638 avio_get_str16be(sc->pb, len, title, title_len);
2639 else if (ch == 0xfffe)
2640 avio_get_str16le(sc->pb, len, title, title_len);
2643 if (len == 1 || len == 2)
2646 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
2650 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2654 avio_seek(sc->pb, cur_pos, SEEK_SET);
2657 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
2661 struct ff_timecode tc = {
2662 .drop = st->codec->flags2 & CODEC_FLAG2_DROP_FRAME_TIMECODE,
2663 .rate = (AVRational){st->codec->time_base.den,
2664 st->codec->time_base.num},
2667 if (avpriv_check_timecode_rate(s, tc.rate, tc.drop) < 0)
2668 return AVERROR(EINVAL);
2669 av_dict_set(&st->metadata, "timecode",
2670 avpriv_timecode_to_string(buf, &tc, value), 0);
2674 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
2676 MOVStreamContext *sc = st->priv_data;
2677 int64_t cur_pos = avio_tell(sc->pb);
2680 if (!st->nb_index_entries)
2683 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
2684 value = avio_rb32(s->pb);
2686 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
2687 * not the case) and thus assume "frame number format" instead of QT one.
2688 * No sample with tmcd track can be found with a QT timecode at the moment,
2689 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
2691 parse_timecode_in_framenum_format(s, st, value);
2693 avio_seek(sc->pb, cur_pos, SEEK_SET);
2697 static int mov_read_header(AVFormatContext *s)
2699 MOVContext *mov = s->priv_data;
2700 AVIOContext *pb = s->pb;
2702 MOVAtom atom = { AV_RL32("root") };
2705 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2707 atom.size = avio_size(pb);
2709 atom.size = INT64_MAX;
2711 /* check MOV header */
2712 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2713 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2716 if (!mov->found_moov) {
2717 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2718 return AVERROR_INVALIDDATA;
2720 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2724 if (mov->chapter_track > 0)
2725 mov_read_chapters(s);
2726 for (i = 0; i < s->nb_streams; i++)
2727 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
2728 mov_read_timecode_track(s, s->streams[i]);
2731 if (mov->trex_data) {
2733 for (i = 0; i < s->nb_streams; i++) {
2734 AVStream *st = s->streams[i];
2735 MOVStreamContext *sc = st->priv_data;
2737 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
2744 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2746 AVIndexEntry *sample = NULL;
2747 int64_t best_dts = INT64_MAX;
2749 for (i = 0; i < s->nb_streams; i++) {
2750 AVStream *avst = s->streams[i];
2751 MOVStreamContext *msc = avst->priv_data;
2752 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2753 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2754 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2755 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2756 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2758 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2759 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2760 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2761 sample = current_sample;
2770 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2772 MOVContext *mov = s->priv_data;
2773 MOVStreamContext *sc;
2774 AVIndexEntry *sample;
2775 AVStream *st = NULL;
2779 sample = mov_find_next_sample(s, &st);
2781 mov->found_mdat = 0;
2782 if (s->pb->seekable||
2783 mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2786 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2790 /* must be done just before reading, to avoid infinite loop on sample */
2791 sc->current_sample++;
2793 if (st->discard != AVDISCARD_ALL) {
2794 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2795 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2796 sc->ffindex, sample->pos);
2797 return AVERROR_INVALIDDATA;
2799 ret = av_get_packet(sc->pb, pkt, sample->size);
2802 if (sc->has_palette) {
2805 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2807 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2809 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2810 sc->has_palette = 0;
2813 #if CONFIG_DV_DEMUXER
2814 if (mov->dv_demux && sc->dv_audio_container) {
2815 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
2818 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
2825 pkt->stream_index = sc->ffindex;
2826 pkt->dts = sample->timestamp;
2827 if (sc->ctts_data) {
2828 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2829 /* update ctts context */
2831 if (sc->ctts_index < sc->ctts_count &&
2832 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2834 sc->ctts_sample = 0;
2837 pkt->dts = AV_NOPTS_VALUE;
2839 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2840 st->index_entries[sc->current_sample].timestamp : st->duration;
2841 pkt->duration = next_dts - pkt->dts;
2842 pkt->pts = pkt->dts;
2844 if (st->discard == AVDISCARD_ALL)
2846 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2847 pkt->pos = sample->pos;
2848 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2849 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2853 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2855 MOVStreamContext *sc = st->priv_data;
2856 int sample, time_sample;
2859 sample = av_index_search_timestamp(st, timestamp, flags);
2860 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2861 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2863 if (sample < 0) /* not sure what to do */
2864 return AVERROR_INVALIDDATA;
2865 sc->current_sample = sample;
2866 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2867 /* adjust ctts index */
2868 if (sc->ctts_data) {
2870 for (i = 0; i < sc->ctts_count; i++) {
2871 int next = time_sample + sc->ctts_data[i].count;
2872 if (next > sc->current_sample) {
2874 sc->ctts_sample = sc->current_sample - time_sample;
2883 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2886 int64_t seek_timestamp, timestamp;
2890 if (stream_index >= s->nb_streams)
2891 return AVERROR_INVALIDDATA;
2892 if (sample_time < 0)
2895 st = s->streams[stream_index];
2896 sample = mov_seek_stream(s, st, sample_time, flags);
2900 /* adjust seek timestamp to found sample timestamp */
2901 seek_timestamp = st->index_entries[sample].timestamp;
2903 for (i = 0; i < s->nb_streams; i++) {
2905 if (stream_index == i)
2908 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2909 mov_seek_stream(s, st, timestamp, flags);
2914 static int mov_read_close(AVFormatContext *s)
2916 MOVContext *mov = s->priv_data;
2919 for (i = 0; i < s->nb_streams; i++) {
2920 AVStream *st = s->streams[i];
2921 MOVStreamContext *sc = st->priv_data;
2923 av_freep(&sc->ctts_data);
2924 for (j = 0; j < sc->drefs_count; j++) {
2925 av_freep(&sc->drefs[j].path);
2926 av_freep(&sc->drefs[j].dir);
2928 av_freep(&sc->drefs);
2929 if (sc->pb && sc->pb != s->pb)
2933 if (mov->dv_demux) {
2934 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2935 av_freep(&mov->dv_fctx->streams[i]->codec);
2936 av_freep(&mov->dv_fctx->streams[i]);
2938 av_freep(&mov->dv_fctx);
2939 av_freep(&mov->dv_demux);
2942 av_freep(&mov->trex_data);
2947 static const AVOption options[] = {
2948 {"use_absolute_path",
2949 "allow using absolute path when opening alias, this is a possible security issue",
2950 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.dbl = 0},
2951 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
2954 static const AVClass class = {"mov,mp4,m4a,3gp,3g2,mj2", av_default_item_name, options, LIBAVUTIL_VERSION_INT};
2956 AVInputFormat ff_mov_demuxer = {
2957 .name = "mov,mp4,m4a,3gp,3g2,mj2",
2958 .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2959 .priv_data_size = sizeof(MOVContext),
2960 .read_probe = mov_probe,
2961 .read_header = mov_read_header,
2962 .read_packet = mov_read_packet,
2963 .read_close = mov_read_close,
2964 .read_seek = mov_read_seek,
2965 .priv_class = &class,