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/attributes.h"
29 #include "libavutil/audioconvert.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/intfloat.h"
32 #include "libavutil/mathematics.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/dict.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/timecode.h"
37 #include "libavcodec/ac3tab.h"
40 #include "avio_internal.h"
43 #include "libavcodec/get_bits.h"
52 * First version by Francois Revol revol@free.fr
53 * Seek function by Gael Chardon gael.dev@4now.net
56 #include "qtpalette.h"
62 /* those functions parse an atom */
63 /* links atom IDs to parse functions */
64 typedef struct MOVParseTableEntry {
66 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
69 static const MOVParseTableEntry mov_default_parse_table[];
71 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
72 unsigned len, const char *key)
76 short current, total = 0;
77 avio_rb16(pb); // unknown
78 current = avio_rb16(pb);
80 total = avio_rb16(pb);
82 snprintf(buf, sizeof(buf), "%d", current);
84 snprintf(buf, sizeof(buf), "%d/%d", current, total);
85 av_dict_set(&c->fc->metadata, key, buf, 0);
90 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
91 unsigned len, const char *key)
95 /* bypass padding bytes */
100 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
101 av_dict_set(&c->fc->metadata, key, buf, 0);
106 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
107 unsigned len, const char *key)
111 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
112 av_dict_set(&c->fc->metadata, key, buf, 0);
117 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
118 unsigned len, const char *key)
123 avio_r8(pb); // unknown
126 if (genre < 1 || genre > ID3v1_GENRE_MAX)
128 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
129 av_dict_set(&c->fc->metadata, key, buf, 0);
134 static const uint32_t mac_to_unicode[128] = {
135 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
136 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
137 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
138 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
139 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
140 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
141 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
142 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
143 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
144 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
145 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
146 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
147 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
148 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
149 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
150 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
153 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
154 char *dst, int dstlen)
157 char *end = dst+dstlen-1;
160 for (i = 0; i < len; i++) {
161 uint8_t t, c = avio_r8(pb);
162 if (c < 0x80 && p < end)
165 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
171 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
173 #ifdef MOV_EXPORT_ALL_METADATA
176 char str[1024], key2[16], language[4] = {0};
177 const char *key = NULL;
178 uint16_t str_size, langcode = 0;
179 uint32_t data_type = 0;
180 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
183 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
184 case MKTAG(0xa9,'a','u','t'):
185 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
186 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
187 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
188 case MKTAG( 'c','p','r','t'):
189 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
190 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
191 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
192 case MKTAG(0xa9,'c','m','t'):
193 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
194 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
195 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
196 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
197 case MKTAG( 'g','n','r','e'): key = "genre";
198 parse = mov_metadata_gnre; break;
199 case MKTAG(0xa9,'t','o','o'):
200 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
201 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
202 case MKTAG( 'd','e','s','c'): key = "description";break;
203 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
204 case MKTAG( 't','v','s','h'): key = "show"; break;
205 case MKTAG( 't','v','e','n'): key = "episode_id";break;
206 case MKTAG( 't','v','n','n'): key = "network"; break;
207 case MKTAG( 't','r','k','n'): key = "track";
208 parse = mov_metadata_track_or_disc_number; break;
209 case MKTAG( 'd','i','s','k'): key = "disc";
210 parse = mov_metadata_track_or_disc_number; break;
211 case MKTAG( 't','v','e','s'): key = "episode_sort";
212 parse = mov_metadata_int8_bypass_padding; break;
213 case MKTAG( 't','v','s','n'): key = "season_number";
214 parse = mov_metadata_int8_bypass_padding; break;
215 case MKTAG( 's','t','i','k'): key = "media_type";
216 parse = mov_metadata_int8_no_padding; break;
217 case MKTAG( 'h','d','v','d'): key = "hd_video";
218 parse = mov_metadata_int8_no_padding; break;
219 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
220 parse = mov_metadata_int8_no_padding; break;
223 if (c->itunes_metadata && atom.size > 8) {
224 int data_size = avio_rb32(pb);
225 int tag = avio_rl32(pb);
226 if (tag == MKTAG('d','a','t','a')) {
227 data_type = avio_rb32(pb); // type
228 avio_rb32(pb); // unknown
229 str_size = data_size - 16;
232 } else if (atom.size > 4 && key && !c->itunes_metadata) {
233 str_size = avio_rb16(pb); // string length
234 langcode = avio_rb16(pb);
235 ff_mov_lang_to_iso639(langcode, language);
238 str_size = atom.size;
240 #ifdef MOV_EXPORT_ALL_METADATA
242 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
250 return AVERROR_INVALIDDATA;
252 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
255 parse(c, pb, str_size, key);
257 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
258 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
260 avio_read(pb, str, str_size);
263 av_dict_set(&c->fc->metadata, key, str, 0);
264 if (*language && strcmp(language, "und")) {
265 snprintf(key2, sizeof(key2), "%s-%s", key, language);
266 av_dict_set(&c->fc->metadata, key2, str, 0);
269 av_dlog(c->fc, "lang \"%3s\" ", language);
270 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
271 key, str, (char*)&atom.type, str_size, atom.size);
276 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
279 int i, nb_chapters, str_len, version;
282 if ((atom.size -= 5) < 0)
285 version = avio_r8(pb);
288 avio_rb32(pb); // ???
289 nb_chapters = avio_r8(pb);
291 for (i = 0; i < nb_chapters; i++) {
295 start = avio_rb64(pb);
296 str_len = avio_r8(pb);
298 if ((atom.size -= 9+str_len) < 0)
301 avio_read(pb, str, str_len);
303 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
308 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
310 int64_t total_size = 0;
315 atom.size = INT64_MAX;
316 while (total_size + 8 <= atom.size && !url_feof(pb)) {
317 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
320 if (atom.size >= 8) {
321 a.size = avio_rb32(pb);
322 a.type = avio_rl32(pb);
323 if (atom.type != MKTAG('r','o','o','t') &&
324 atom.type != MKTAG('m','o','o','v'))
326 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
328 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
334 if (a.size == 1) { /* 64 bit extended size */
335 a.size = avio_rb64(pb) - 8;
339 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
340 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
342 a.size = atom.size - total_size + 8;
347 a.size = FFMIN(a.size, atom.size - total_size);
349 for (i = 0; mov_default_parse_table[i].type; i++)
350 if (mov_default_parse_table[i].type == a.type) {
351 parse = mov_default_parse_table[i].parse;
355 // container is user data
356 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
357 atom.type == MKTAG('i','l','s','t')))
358 parse = mov_read_udta_string;
360 if (!parse) { /* skip leaf atoms data */
361 avio_skip(pb, a.size);
363 int64_t start_pos = avio_tell(pb);
365 int err = parse(c, pb, a);
368 if (c->found_moov && c->found_mdat &&
369 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
370 start_pos + a.size == avio_size(pb))) {
371 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
372 c->next_root_atom = start_pos + a.size;
375 left = a.size - avio_tell(pb) + start_pos;
376 if (left > 0) /* skip garbage at atom end */
380 total_size += a.size;
383 if (total_size < atom.size && atom.size < 0x7ffff)
384 avio_skip(pb, atom.size - total_size);
389 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
392 MOVStreamContext *sc;
395 if (c->fc->nb_streams < 1)
397 st = c->fc->streams[c->fc->nb_streams-1];
400 avio_rb32(pb); // version + flags
401 entries = avio_rb32(pb);
402 if (entries >= UINT_MAX / sizeof(*sc->drefs))
403 return AVERROR_INVALIDDATA;
406 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
408 return AVERROR(ENOMEM);
409 sc->drefs_count = entries;
411 for (i = 0; i < sc->drefs_count; i++) {
412 MOVDref *dref = &sc->drefs[i];
413 uint32_t size = avio_rb32(pb);
414 int64_t next = avio_tell(pb) + size - 4;
417 return AVERROR_INVALIDDATA;
419 dref->type = avio_rl32(pb);
420 avio_rb32(pb); // version + flags
421 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
423 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
424 /* macintosh alias record */
425 uint16_t volume_len, len;
430 volume_len = avio_r8(pb);
431 volume_len = FFMIN(volume_len, 27);
432 avio_read(pb, dref->volume, 27);
433 dref->volume[volume_len] = 0;
434 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
439 len = FFMIN(len, 63);
440 avio_read(pb, dref->filename, 63);
441 dref->filename[len] = 0;
442 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
446 /* read next level up_from_alias/down_to_target */
447 dref->nlvl_from = avio_rb16(pb);
448 dref->nlvl_to = avio_rb16(pb);
449 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
450 dref->nlvl_from, dref->nlvl_to);
454 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
457 type = avio_rb16(pb);
459 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
462 if (type == 2) { // absolute path
464 dref->path = av_mallocz(len+1);
466 return AVERROR(ENOMEM);
467 avio_read(pb, dref->path, len);
468 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
470 memmove(dref->path, dref->path+volume_len, len);
473 for (j = 0; j < len; j++)
474 if (dref->path[j] == ':')
476 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
477 } else if (type == 0) { // directory name
479 dref->dir = av_malloc(len+1);
481 return AVERROR(ENOMEM);
482 avio_read(pb, dref->dir, len);
484 for (j = 0; j < len; j++)
485 if (dref->dir[j] == ':')
487 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
492 avio_seek(pb, next, SEEK_SET);
497 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
501 uint32_t av_unused ctype;
505 if (c->fc->nb_streams < 1) // meta before first trak
508 st = c->fc->streams[c->fc->nb_streams-1];
510 avio_r8(pb); /* version */
511 avio_rb24(pb); /* flags */
514 ctype = avio_rl32(pb);
515 type = avio_rl32(pb); /* component subtype */
517 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
518 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
520 if (type == MKTAG('v','i','d','e'))
521 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
522 else if (type == MKTAG('s','o','u','n'))
523 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
524 else if (type == MKTAG('m','1','a',' '))
525 st->codec->codec_id = CODEC_ID_MP2;
526 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
527 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
529 avio_rb32(pb); /* component manufacture */
530 avio_rb32(pb); /* component flags */
531 avio_rb32(pb); /* component flags mask */
533 title_size = atom.size - 24;
534 if (title_size > 0) {
535 title_str = av_malloc(title_size + 1); /* Add null terminator */
537 return AVERROR(ENOMEM);
538 avio_read(pb, title_str, title_size);
539 title_str[title_size] = 0;
541 av_dict_set(&st->metadata, "handler_name", title_str +
542 (!c->isom && title_str[0] == title_size - 1), 0);
543 av_freep(&title_str);
549 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
554 if (fc->nb_streams < 1)
556 st = fc->streams[fc->nb_streams-1];
558 avio_rb32(pb); /* version + flags */
559 ff_mp4_read_descr(fc, pb, &tag);
560 if (tag == MP4ESDescrTag) {
561 ff_mp4_parse_es_descr(pb, NULL);
563 avio_rb16(pb); /* ID */
565 ff_mp4_read_descr(fc, pb, &tag);
566 if (tag == MP4DecConfigDescrTag)
567 ff_mp4_read_dec_config_descr(fc, st, pb);
571 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
573 return ff_mov_read_esds(c->fc, pb, atom);
576 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
579 int ac3info, acmod, lfeon, bsmod;
581 if (c->fc->nb_streams < 1)
583 st = c->fc->streams[c->fc->nb_streams-1];
585 ac3info = avio_rb24(pb);
586 bsmod = (ac3info >> 14) & 0x7;
587 acmod = (ac3info >> 11) & 0x7;
588 lfeon = (ac3info >> 10) & 0x1;
589 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
590 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
592 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
593 st->codec->audio_service_type = bsmod;
594 if (st->codec->channels > 1 && bsmod == 0x7)
595 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
600 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
603 int eac3info, acmod, lfeon, bsmod;
605 if (c->fc->nb_streams < 1)
607 st = c->fc->streams[c->fc->nb_streams-1];
609 /* No need to parse fields for additional independent substreams and its
610 * associated dependent substreams since libavcodec's E-AC-3 decoder
611 * does not support them yet. */
612 avio_rb16(pb); /* data_rate and num_ind_sub */
613 eac3info = avio_rb24(pb);
614 bsmod = (eac3info >> 12) & 0x1f;
615 acmod = (eac3info >> 9) & 0x7;
616 lfeon = (eac3info >> 8) & 0x1;
617 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
619 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
620 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
621 st->codec->audio_service_type = bsmod;
622 if (st->codec->channels > 1 && bsmod == 0x7)
623 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
628 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
631 uint8_t av_unused version;
632 uint32_t av_unused flags;
633 uint32_t layout_tag, bitmap, num_descr, label_mask;
636 if (c->fc->nb_streams < 1)
638 st = c->fc->streams[c->fc->nb_streams-1];
643 version = avio_r8(pb);
644 flags = avio_rb24(pb);
646 layout_tag = avio_rb32(pb);
647 bitmap = avio_rb32(pb);
648 num_descr = avio_rb32(pb);
650 if (atom.size < 16ULL + num_descr * 20ULL)
653 av_dlog(c->fc, "chan: size=%" PRId64 " version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
654 atom.size, version, flags, layout_tag, bitmap, num_descr);
657 for (i = 0; i < num_descr; i++) {
659 label = avio_rb32(pb); // mChannelLabel
660 avio_rb32(pb); // mChannelFlags
661 avio_rl32(pb); // mCoordinates[0]
662 avio_rl32(pb); // mCoordinates[1]
663 avio_rl32(pb); // mCoordinates[2]
664 if (layout_tag == 0) {
665 uint32_t mask_incr = ff_mov_get_channel_label(label);
666 if (mask_incr == 0) {
670 label_mask |= mask_incr;
674 st->codec->channel_layout = label_mask;
676 st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
681 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
685 if (c->fc->nb_streams < 1)
687 st = c->fc->streams[c->fc->nb_streams-1];
689 ff_get_wav_header(pb, st->codec, atom.size);
694 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
696 const int num = avio_rb32(pb);
697 const int den = avio_rb32(pb);
700 if (c->fc->nb_streams < 1)
702 st = c->fc->streams[c->fc->nb_streams-1];
704 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
705 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
706 av_log(c->fc, AV_LOG_WARNING,
707 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
708 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
710 } else if (den != 0) {
711 st->sample_aspect_ratio.num = num;
712 st->sample_aspect_ratio.den = den;
717 /* this atom contains actual media data */
718 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
720 if (atom.size == 0) /* wrong one (MP4) */
723 return 0; /* now go for moov */
726 /* read major brand, minor version and compatible brands and store them as metadata */
727 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
731 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
732 char* comp_brands_str;
733 uint8_t type[5] = {0};
735 avio_read(pb, type, 4);
736 if (strcmp(type, "qt "))
738 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
739 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
740 minor_ver = avio_rb32(pb); /* minor version */
741 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
742 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
744 comp_brand_size = atom.size - 8;
745 if (comp_brand_size < 0)
746 return AVERROR_INVALIDDATA;
747 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
748 if (!comp_brands_str)
749 return AVERROR(ENOMEM);
750 avio_read(pb, comp_brands_str, comp_brand_size);
751 comp_brands_str[comp_brand_size] = 0;
752 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
753 av_freep(&comp_brands_str);
758 /* this atom should contain all header atoms */
759 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
763 if ((ret = mov_read_default(c, pb, atom)) < 0)
765 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
766 /* so we don't parse the whole file if over a network */
768 return 0; /* now go for mdat */
771 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
773 c->fragment.moof_offset = avio_tell(pb) - 8;
774 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
775 return mov_read_default(c, pb, atom);
778 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
783 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
786 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
787 av_dict_set(metadata, "creation_time", buffer, 0);
791 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
794 MOVStreamContext *sc;
796 char language[4] = {0};
798 time_t creation_time;
800 if (c->fc->nb_streams < 1)
802 st = c->fc->streams[c->fc->nb_streams-1];
805 version = avio_r8(pb);
807 av_log_ask_for_sample(c, "unsupported version %d\n", version);
808 return AVERROR_PATCHWELCOME;
810 avio_rb24(pb); /* flags */
812 creation_time = avio_rb64(pb);
815 creation_time = avio_rb32(pb);
816 avio_rb32(pb); /* modification time */
818 mov_metadata_creation_time(&st->metadata, creation_time);
820 sc->time_scale = avio_rb32(pb);
821 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
823 lang = avio_rb16(pb); /* language */
824 if (ff_mov_lang_to_iso639(lang, language))
825 av_dict_set(&st->metadata, "language", language, 0);
826 avio_rb16(pb); /* quality */
831 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
833 time_t creation_time;
834 int version = avio_r8(pb); /* version */
835 avio_rb24(pb); /* flags */
838 creation_time = avio_rb64(pb);
841 creation_time = avio_rb32(pb);
842 avio_rb32(pb); /* modification time */
844 mov_metadata_creation_time(&c->fc->metadata, creation_time);
845 c->time_scale = avio_rb32(pb); /* time scale */
847 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
849 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
850 // set the AVCodecContext duration because the duration of individual tracks
852 if (c->time_scale > 0)
853 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
854 avio_rb32(pb); /* preferred scale */
856 avio_rb16(pb); /* preferred volume */
858 avio_skip(pb, 10); /* reserved */
860 avio_skip(pb, 36); /* display matrix */
862 avio_rb32(pb); /* preview time */
863 avio_rb32(pb); /* preview duration */
864 avio_rb32(pb); /* poster time */
865 avio_rb32(pb); /* selection time */
866 avio_rb32(pb); /* selection duration */
867 avio_rb32(pb); /* current time */
868 avio_rb32(pb); /* next track ID */
872 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
876 if (c->fc->nb_streams < 1)
878 st = c->fc->streams[c->fc->nb_streams-1];
880 if ((uint64_t)atom.size > (1<<30))
881 return AVERROR_INVALIDDATA;
883 // currently SVQ3 decoder expect full STSD header - so let's fake it
884 // this should be fixed and just SMI header should be passed
885 av_free(st->codec->extradata);
886 st->codec->extradata_size = 0;
887 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
888 if (!st->codec->extradata)
889 return AVERROR(ENOMEM);
890 st->codec->extradata_size = 0x5a + atom.size;
891 memcpy(st->codec->extradata, "SVQ3", 4); // fake
892 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
893 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
897 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
902 if (c->fc->nb_streams < 1)
904 st = c->fc->streams[c->fc->nb_streams-1];
906 little_endian = avio_rb16(pb) & 0xFF;
907 av_dlog(c->fc, "enda %d\n", little_endian);
908 if (little_endian == 1) {
909 switch (st->codec->codec_id) {
910 case CODEC_ID_PCM_S24BE:
911 st->codec->codec_id = CODEC_ID_PCM_S24LE;
913 case CODEC_ID_PCM_S32BE:
914 st->codec->codec_id = CODEC_ID_PCM_S32LE;
916 case CODEC_ID_PCM_F32BE:
917 st->codec->codec_id = CODEC_ID_PCM_F32LE;
919 case CODEC_ID_PCM_F64BE:
920 st->codec->codec_id = CODEC_ID_PCM_F64LE;
929 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
932 unsigned mov_field_order;
933 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
935 if (c->fc->nb_streams < 1) // will happen with jp2 files
937 st = c->fc->streams[c->fc->nb_streams-1];
939 return AVERROR_INVALIDDATA;
940 mov_field_order = avio_rb16(pb);
941 if ((mov_field_order & 0xFF00) == 0x0100)
942 decoded_field_order = AV_FIELD_PROGRESSIVE;
943 else if ((mov_field_order & 0xFF00) == 0x0200) {
944 switch (mov_field_order & 0xFF) {
945 case 0x01: decoded_field_order = AV_FIELD_TT;
947 case 0x06: decoded_field_order = AV_FIELD_BB;
949 case 0x09: decoded_field_order = AV_FIELD_TB;
951 case 0x0E: decoded_field_order = AV_FIELD_BT;
955 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
956 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
958 st->codec->field_order = decoded_field_order;
963 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
964 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
965 enum CodecID codec_id)
971 if (c->fc->nb_streams < 1) // will happen with jp2 files
973 st= c->fc->streams[c->fc->nb_streams-1];
975 if (st->codec->codec_id != codec_id)
976 return 0; /* unexpected codec_id - don't mess with extradata */
978 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
979 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
980 return AVERROR_INVALIDDATA;
981 buf= av_realloc(st->codec->extradata, size);
983 return AVERROR(ENOMEM);
984 st->codec->extradata= buf;
985 buf+= st->codec->extradata_size;
986 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
987 AV_WB32( buf , atom.size + 8);
988 AV_WL32( buf + 4, atom.type);
989 avio_read(pb, buf + 8, atom.size);
993 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
994 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
996 return mov_read_extradata(c, pb, atom, CODEC_ID_ALAC);
999 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1001 return mov_read_extradata(c, pb, atom, CODEC_ID_AVS);
1004 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1006 return mov_read_extradata(c, pb, atom, CODEC_ID_JPEG2000);
1009 static int mov_read_aprg(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1011 return mov_read_extradata(c, pb, atom, CODEC_ID_AVUI);
1014 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1018 if (c->fc->nb_streams < 1)
1020 st = c->fc->streams[c->fc->nb_streams-1];
1022 if ((uint64_t)atom.size > (1<<30))
1023 return AVERROR_INVALIDDATA;
1025 if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
1026 // pass all frma atom to codec, needed at least for QDMC and QDM2
1027 av_free(st->codec->extradata);
1028 st->codec->extradata_size = 0;
1029 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1030 if (!st->codec->extradata)
1031 return AVERROR(ENOMEM);
1032 st->codec->extradata_size = atom.size;
1033 avio_read(pb, st->codec->extradata, atom.size);
1034 } else if (atom.size > 8) { /* to read frma, esds atoms */
1036 if ((ret = mov_read_default(c, pb, atom)) < 0)
1039 avio_skip(pb, atom.size);
1044 * This function reads atom content and puts data in extradata without tag
1045 * nor size unlike mov_read_extradata.
1047 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1051 if (c->fc->nb_streams < 1)
1053 st = c->fc->streams[c->fc->nb_streams-1];
1055 if ((uint64_t)atom.size > (1<<30))
1056 return AVERROR_INVALIDDATA;
1058 if (atom.size >= 10) {
1059 // Broken files created by legacy versions of libavformat will
1060 // wrap a whole fiel atom inside of a glbl atom.
1061 unsigned size = avio_rb32(pb);
1062 unsigned type = avio_rl32(pb);
1063 avio_seek(pb, -8, SEEK_CUR);
1064 if (type == MKTAG('f','i','e','l') && size == atom.size)
1065 return mov_read_default(c, pb, atom);
1067 av_free(st->codec->extradata);
1068 st->codec->extradata_size = 0;
1069 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1070 if (!st->codec->extradata)
1071 return AVERROR(ENOMEM);
1072 st->codec->extradata_size = atom.size;
1073 avio_read(pb, st->codec->extradata, atom.size);
1077 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1080 uint8_t profile_level;
1082 if (c->fc->nb_streams < 1)
1084 st = c->fc->streams[c->fc->nb_streams-1];
1086 if (atom.size >= (1<<28) || atom.size < 7)
1087 return AVERROR_INVALIDDATA;
1089 profile_level = avio_r8(pb);
1090 if (profile_level & 0xf0 != 0xc0)
1093 av_free(st->codec->extradata);
1094 st->codec->extradata_size = 0;
1095 st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
1096 if (!st->codec->extradata)
1097 return AVERROR(ENOMEM);
1098 st->codec->extradata_size = atom.size - 7;
1099 avio_seek(pb, 6, SEEK_CUR);
1100 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
1105 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1106 * but can have extradata appended at the end after the 40 bytes belonging
1109 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1113 if (c->fc->nb_streams < 1)
1115 if (atom.size <= 40)
1117 st = c->fc->streams[c->fc->nb_streams-1];
1119 if ((uint64_t)atom.size > (1<<30))
1120 return AVERROR_INVALIDDATA;
1122 av_free(st->codec->extradata);
1123 st->codec->extradata_size = 0;
1124 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1125 if (!st->codec->extradata)
1126 return AVERROR(ENOMEM);
1127 st->codec->extradata_size = atom.size - 40;
1129 avio_read(pb, st->codec->extradata, atom.size - 40);
1133 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1136 MOVStreamContext *sc;
1137 unsigned int i, entries;
1139 if (c->fc->nb_streams < 1)
1141 st = c->fc->streams[c->fc->nb_streams-1];
1144 avio_r8(pb); /* version */
1145 avio_rb24(pb); /* flags */
1147 entries = avio_rb32(pb);
1151 if (entries >= UINT_MAX/sizeof(int64_t))
1152 return AVERROR_INVALIDDATA;
1154 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1155 if (!sc->chunk_offsets)
1156 return AVERROR(ENOMEM);
1157 sc->chunk_count = entries;
1159 if (atom.type == MKTAG('s','t','c','o'))
1160 for (i=0; i<entries; i++)
1161 sc->chunk_offsets[i] = avio_rb32(pb);
1162 else if (atom.type == MKTAG('c','o','6','4'))
1163 for (i=0; i<entries; i++)
1164 sc->chunk_offsets[i] = avio_rb64(pb);
1166 return AVERROR_INVALIDDATA;
1172 * Compute codec id for 'lpcm' tag.
1173 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1175 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1177 if (flags & 1) { // floating point
1178 if (flags & 2) { // big endian
1179 if (bps == 32) return CODEC_ID_PCM_F32BE;
1180 else if (bps == 64) return CODEC_ID_PCM_F64BE;
1182 if (bps == 32) return CODEC_ID_PCM_F32LE;
1183 else if (bps == 64) return CODEC_ID_PCM_F64LE;
1189 if (flags & 4) return CODEC_ID_PCM_S8;
1190 else return CODEC_ID_PCM_U8;
1191 else if (bps == 16) return CODEC_ID_PCM_S16BE;
1192 else if (bps == 24) return CODEC_ID_PCM_S24BE;
1193 else if (bps == 32) return CODEC_ID_PCM_S32BE;
1196 if (flags & 4) return CODEC_ID_PCM_S8;
1197 else return CODEC_ID_PCM_U8;
1198 else if (bps == 16) return CODEC_ID_PCM_S16LE;
1199 else if (bps == 24) return CODEC_ID_PCM_S24LE;
1200 else if (bps == 32) return CODEC_ID_PCM_S32LE;
1203 return CODEC_ID_NONE;
1206 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1209 MOVStreamContext *sc;
1210 int j, pseudo_stream_id;
1212 if (c->fc->nb_streams < 1)
1214 st = c->fc->streams[c->fc->nb_streams-1];
1217 for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
1218 //Parsing Sample description table
1221 MOVAtom a = { AV_RL32("stsd") };
1222 int64_t start_pos = avio_tell(pb);
1223 int size = avio_rb32(pb); /* size */
1224 uint32_t format = avio_rl32(pb); /* data format */
1227 avio_rb32(pb); /* reserved */
1228 avio_rb16(pb); /* reserved */
1229 dref_id = avio_rb16(pb);
1230 }else if (size <= 0){
1231 av_log(c->fc, AV_LOG_ERROR, "invalid size %d in stsd\n", size);
1235 if (st->codec->codec_tag &&
1236 st->codec->codec_tag != format &&
1237 (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
1238 : st->codec->codec_tag != MKTAG('j','p','e','g'))
1240 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1241 * export it as a separate AVStream but this needs a few changes
1242 * in the MOV demuxer, patch welcome. */
1243 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1244 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1247 /* we cannot demux concatenated h264 streams because of different extradata */
1248 if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1249 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 might not play corrently.\n");
1250 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1251 sc->dref_id= dref_id;
1253 st->codec->codec_tag = format;
1254 id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1255 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1256 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1258 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1259 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1260 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1261 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1262 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1264 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1266 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1267 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1268 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1269 st->codec->codec_id == CODEC_ID_NONE)){
1270 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1272 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1276 av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1277 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1278 (format >> 24) & 0xff, st->codec->codec_type);
1280 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1281 unsigned int color_depth, len;
1282 int color_greyscale;
1285 st->codec->codec_id = id;
1286 avio_rb16(pb); /* version */
1287 avio_rb16(pb); /* revision level */
1288 avio_rb32(pb); /* vendor */
1289 avio_rb32(pb); /* temporal quality */
1290 avio_rb32(pb); /* spatial quality */
1292 st->codec->width = avio_rb16(pb); /* width */
1293 st->codec->height = avio_rb16(pb); /* height */
1295 avio_rb32(pb); /* horiz resolution */
1296 avio_rb32(pb); /* vert resolution */
1297 avio_rb32(pb); /* data size, always 0 */
1298 avio_rb16(pb); /* frames per samples */
1300 len = avio_r8(pb); /* codec name, pascal string */
1303 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1305 avio_skip(pb, 31 - len);
1306 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1307 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1308 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1310 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1311 color_table_id = avio_rb16(pb); /* colortable id */
1312 av_dlog(c->fc, "depth %d, ctab id %d\n",
1313 st->codec->bits_per_coded_sample, color_table_id);
1314 /* figure out the palette situation */
1315 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1316 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1318 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1319 if ((color_depth == 2) || (color_depth == 4) ||
1320 (color_depth == 8)) {
1321 /* for palette traversal */
1322 unsigned int color_start, color_count, color_end;
1323 unsigned char a, r, g, b;
1325 if (color_greyscale) {
1326 int color_index, color_dec;
1327 /* compute the greyscale palette */
1328 st->codec->bits_per_coded_sample = color_depth;
1329 color_count = 1 << color_depth;
1331 color_dec = 256 / (color_count - 1);
1332 for (j = 0; j < color_count; j++) {
1333 if (id == CODEC_ID_CINEPAK){
1334 r = g = b = color_count - 1 - color_index;
1336 r = g = b = color_index;
1338 (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1339 color_index -= color_dec;
1340 if (color_index < 0)
1343 } else if (color_table_id) {
1344 const uint8_t *color_table;
1345 /* if flag bit 3 is set, use the default palette */
1346 color_count = 1 << color_depth;
1347 if (color_depth == 2)
1348 color_table = ff_qt_default_palette_4;
1349 else if (color_depth == 4)
1350 color_table = ff_qt_default_palette_16;
1352 color_table = ff_qt_default_palette_256;
1354 for (j = 0; j < color_count; j++) {
1355 r = color_table[j * 3 + 0];
1356 g = color_table[j * 3 + 1];
1357 b = color_table[j * 3 + 2];
1359 (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1362 /* load the palette from the file */
1363 color_start = avio_rb32(pb);
1364 color_count = avio_rb16(pb);
1365 color_end = avio_rb16(pb);
1366 if ((color_start <= 255) &&
1367 (color_end <= 255)) {
1368 for (j = color_start; j <= color_end; j++) {
1369 /* each A, R, G, or B component is 16 bits;
1370 * only use the top 8 bits */
1380 (a << 24 ) | (r << 16) | (g << 8) | (b);
1384 sc->has_palette = 1;
1386 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1387 int bits_per_sample, flags;
1388 uint16_t version = avio_rb16(pb);
1390 st->codec->codec_id = id;
1391 avio_rb16(pb); /* revision level */
1392 avio_rb32(pb); /* vendor */
1394 st->codec->channels = avio_rb16(pb); /* channel count */
1395 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1396 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1398 sc->audio_cid = avio_rb16(pb);
1399 avio_rb16(pb); /* packet size = 0 */
1401 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1403 //Read QT version 1 fields. In version 0 these do not exist.
1404 av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1407 sc->samples_per_frame = avio_rb32(pb);
1408 avio_rb32(pb); /* bytes per packet */
1409 sc->bytes_per_frame = avio_rb32(pb);
1410 avio_rb32(pb); /* bytes per sample */
1411 } else if (version==2) {
1412 avio_rb32(pb); /* sizeof struct only */
1413 st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
1414 st->codec->channels = avio_rb32(pb);
1415 avio_rb32(pb); /* always 0x7F000000 */
1416 st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1417 flags = avio_rb32(pb); /* lpcm format specific flag */
1418 sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1419 sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1420 if (format == MKTAG('l','p','c','m'))
1421 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1425 switch (st->codec->codec_id) {
1426 case CODEC_ID_PCM_S8:
1427 case CODEC_ID_PCM_U8:
1428 if (st->codec->bits_per_coded_sample == 16)
1429 st->codec->codec_id = CODEC_ID_PCM_S16BE;
1431 case CODEC_ID_PCM_S16LE:
1432 case CODEC_ID_PCM_S16BE:
1433 if (st->codec->bits_per_coded_sample == 8)
1434 st->codec->codec_id = CODEC_ID_PCM_S8;
1435 else if (st->codec->bits_per_coded_sample == 24)
1436 st->codec->codec_id =
1437 st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1438 CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1440 /* set values for old format before stsd version 1 appeared */
1441 case CODEC_ID_MACE3:
1442 sc->samples_per_frame = 6;
1443 sc->bytes_per_frame = 2*st->codec->channels;
1445 case CODEC_ID_MACE6:
1446 sc->samples_per_frame = 6;
1447 sc->bytes_per_frame = 1*st->codec->channels;
1449 case CODEC_ID_ADPCM_IMA_QT:
1450 sc->samples_per_frame = 64;
1451 sc->bytes_per_frame = 34*st->codec->channels;
1454 sc->samples_per_frame = 160;
1455 sc->bytes_per_frame = 33;
1461 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1462 if (bits_per_sample) {
1463 st->codec->bits_per_coded_sample = bits_per_sample;
1464 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1466 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1467 // ttxt stsd contains display flags, justification, background
1468 // color, fonts, and default styles, so fake an atom to read it
1469 MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1470 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1471 mov_read_glbl(c, pb, fake_atom);
1472 st->codec->codec_id= id;
1473 st->codec->width = sc->width;
1474 st->codec->height = sc->height;
1476 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1477 MOVStreamContext *tmcd_ctx = st->priv_data;
1479 avio_rb32(pb); /* reserved */
1480 val = avio_rb32(pb); /* flags */
1481 tmcd_ctx->tmcd_flags = val;
1483 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1484 avio_rb32(pb); /* time scale */
1485 avio_rb32(pb); /* frame duration */
1486 st->codec->time_base.den = avio_r8(pb); /* number of frame */
1487 st->codec->time_base.num = 1;
1489 /* other codec type, just skip (rtp, mp4s, ...) */
1490 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1492 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1493 a.size = size - (avio_tell(pb) - start_pos);
1496 if ((ret = mov_read_default(c, pb, a)) < 0)
1498 } else if (a.size > 0)
1499 avio_skip(pb, a.size);
1502 if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1503 st->codec->sample_rate= sc->time_scale;
1505 /* special codec parameters handling */
1506 switch (st->codec->codec_id) {
1507 #if CONFIG_DV_DEMUXER
1508 case CODEC_ID_DVAUDIO:
1509 c->dv_fctx = avformat_alloc_context();
1510 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1512 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1513 return AVERROR(ENOMEM);
1515 sc->dv_audio_container = 1;
1516 st->codec->codec_id = CODEC_ID_PCM_S16LE;
1519 /* no ifdef since parameters are always those */
1520 case CODEC_ID_QCELP:
1521 // force sample rate for qcelp when not stored in mov
1522 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1523 st->codec->sample_rate = 8000;
1524 st->codec->channels= 1; /* really needed */
1526 case CODEC_ID_AMR_NB:
1527 st->codec->channels= 1; /* really needed */
1528 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1529 st->codec->sample_rate = 8000;
1531 case CODEC_ID_AMR_WB:
1532 st->codec->channels = 1;
1533 st->codec->sample_rate = 16000;
1537 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1538 st->need_parsing = AVSTREAM_PARSE_FULL;
1541 case CODEC_ID_ADPCM_MS:
1542 case CODEC_ID_ADPCM_IMA_WAV:
1543 st->codec->block_align = sc->bytes_per_frame;
1546 if (st->codec->extradata_size == 36) {
1547 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1548 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1552 st->need_parsing = AVSTREAM_PARSE_FULL;
1554 case CODEC_ID_MPEG1VIDEO:
1555 st->need_parsing = AVSTREAM_PARSE_FULL;
1558 st->need_parsing = AVSTREAM_PARSE_FULL;
1567 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1571 avio_r8(pb); /* version */
1572 avio_rb24(pb); /* flags */
1573 entries = avio_rb32(pb);
1575 return ff_mov_read_stsd_entries(c, pb, entries);
1578 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1581 MOVStreamContext *sc;
1582 unsigned int i, entries;
1584 if (c->fc->nb_streams < 1)
1586 st = c->fc->streams[c->fc->nb_streams-1];
1589 avio_r8(pb); /* version */
1590 avio_rb24(pb); /* flags */
1592 entries = avio_rb32(pb);
1594 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1598 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1599 return AVERROR_INVALIDDATA;
1600 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1602 return AVERROR(ENOMEM);
1603 sc->stsc_count = entries;
1605 for (i=0; i<entries; i++) {
1606 sc->stsc_data[i].first = avio_rb32(pb);
1607 sc->stsc_data[i].count = avio_rb32(pb);
1608 sc->stsc_data[i].id = avio_rb32(pb);
1613 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1616 MOVStreamContext *sc;
1617 unsigned i, entries;
1619 if (c->fc->nb_streams < 1)
1621 st = c->fc->streams[c->fc->nb_streams-1];
1624 avio_rb32(pb); // version + flags
1626 entries = avio_rb32(pb);
1627 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1628 return AVERROR_INVALIDDATA;
1629 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1631 return AVERROR(ENOMEM);
1632 sc->stps_count = entries;
1634 for (i = 0; i < entries; i++) {
1635 sc->stps_data[i] = avio_rb32(pb);
1636 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1642 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1645 MOVStreamContext *sc;
1646 unsigned int i, entries;
1648 if (c->fc->nb_streams < 1)
1650 st = c->fc->streams[c->fc->nb_streams-1];
1653 avio_r8(pb); /* version */
1654 avio_rb24(pb); /* flags */
1656 entries = avio_rb32(pb);
1658 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1662 sc->keyframe_absent = 1;
1665 if (entries >= UINT_MAX / sizeof(int))
1666 return AVERROR_INVALIDDATA;
1667 sc->keyframes = av_malloc(entries * sizeof(int));
1669 return AVERROR(ENOMEM);
1670 sc->keyframe_count = entries;
1672 for (i=0; i<entries; i++) {
1673 sc->keyframes[i] = avio_rb32(pb);
1674 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1679 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1682 MOVStreamContext *sc;
1683 unsigned int i, entries, sample_size, field_size, num_bytes;
1687 if (c->fc->nb_streams < 1)
1689 st = c->fc->streams[c->fc->nb_streams-1];
1692 avio_r8(pb); /* version */
1693 avio_rb24(pb); /* flags */
1695 if (atom.type == MKTAG('s','t','s','z')) {
1696 sample_size = avio_rb32(pb);
1697 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1698 sc->sample_size = sample_size;
1699 sc->alt_sample_size = sample_size;
1703 avio_rb24(pb); /* reserved */
1704 field_size = avio_r8(pb);
1706 entries = avio_rb32(pb);
1708 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1710 sc->sample_count = entries;
1714 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1715 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1716 return AVERROR_INVALIDDATA;
1721 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1722 return AVERROR_INVALIDDATA;
1723 sc->sample_sizes = av_malloc(entries * sizeof(int));
1724 if (!sc->sample_sizes)
1725 return AVERROR(ENOMEM);
1727 num_bytes = (entries*field_size+4)>>3;
1729 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1731 av_freep(&sc->sample_sizes);
1732 return AVERROR(ENOMEM);
1735 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1736 av_freep(&sc->sample_sizes);
1738 return AVERROR_INVALIDDATA;
1741 init_get_bits(&gb, buf, 8*num_bytes);
1743 for (i = 0; i < entries; i++) {
1744 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1745 sc->data_size += sc->sample_sizes[i];
1752 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1755 MOVStreamContext *sc;
1756 unsigned int i, entries;
1758 int64_t total_sample_count=0;
1760 if (c->fc->nb_streams < 1)
1762 st = c->fc->streams[c->fc->nb_streams-1];
1765 avio_r8(pb); /* version */
1766 avio_rb24(pb); /* flags */
1767 entries = avio_rb32(pb);
1769 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1770 c->fc->nb_streams-1, entries);
1772 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1775 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1777 return AVERROR(ENOMEM);
1779 sc->stts_count = entries;
1781 for (i=0; i<entries; i++) {
1782 int sample_duration;
1785 sample_count=avio_rb32(pb);
1786 sample_duration = avio_rb32(pb);
1787 /* sample_duration < 0 is invalid based on the spec */
1788 if (sample_duration < 0) {
1789 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
1790 sample_duration = 1;
1792 sc->stts_data[i].count= sample_count;
1793 sc->stts_data[i].duration= sample_duration;
1795 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1796 sample_count, sample_duration);
1798 duration+=(int64_t)sample_duration*sample_count;
1799 total_sample_count+=sample_count;
1802 st->nb_frames= total_sample_count;
1804 st->duration= duration;
1805 sc->track_end = duration;
1809 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1812 MOVStreamContext *sc;
1813 unsigned int i, entries;
1815 if (c->fc->nb_streams < 1)
1817 st = c->fc->streams[c->fc->nb_streams-1];
1820 avio_r8(pb); /* version */
1821 avio_rb24(pb); /* flags */
1822 entries = avio_rb32(pb);
1824 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1828 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1829 return AVERROR_INVALIDDATA;
1830 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1832 return AVERROR(ENOMEM);
1833 sc->ctts_count = entries;
1835 for (i=0; i<entries; i++) {
1836 int count =avio_rb32(pb);
1837 int duration =avio_rb32(pb);
1839 sc->ctts_data[i].count = count;
1840 sc->ctts_data[i].duration= duration;
1842 if (FFABS(duration) > (1<<28) && i+2<entries) {
1843 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
1844 av_freep(&sc->ctts_data);
1849 if (duration < 0 && i+2<entries)
1850 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1853 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1858 static void mov_build_index(MOVContext *mov, AVStream *st)
1860 MOVStreamContext *sc = st->priv_data;
1861 int64_t current_offset;
1862 int64_t current_dts = 0;
1863 unsigned int stts_index = 0;
1864 unsigned int stsc_index = 0;
1865 unsigned int stss_index = 0;
1866 unsigned int stps_index = 0;
1868 uint64_t stream_size = 0;
1871 /* adjust first dts according to edit list */
1872 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
1873 if (sc->empty_duration)
1874 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
1875 sc->time_offset = sc->start_time - sc->empty_duration;
1876 current_dts = -sc->time_offset;
1877 if (sc->ctts_count>0 && sc->stts_count>0 &&
1878 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1879 /* more than 16 frames delay, dts are likely wrong
1880 this happens with files created by iMovie */
1882 st->codec->has_b_frames = 1;
1886 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1887 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1888 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1889 unsigned int current_sample = 0;
1890 unsigned int stts_sample = 0;
1891 unsigned int sample_size;
1892 unsigned int distance = 0;
1893 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
1895 current_dts -= sc->dts_shift;
1897 if (!sc->sample_count || st->nb_index_entries)
1899 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1901 mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1904 st->index_entries = mem;
1905 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
1907 for (i = 0; i < sc->chunk_count; i++) {
1908 current_offset = sc->chunk_offsets[i];
1909 while (stsc_index + 1 < sc->stsc_count &&
1910 i + 1 == sc->stsc_data[stsc_index + 1].first)
1912 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1914 if (current_sample >= sc->sample_count) {
1915 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1919 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
1921 if (stss_index + 1 < sc->keyframe_count)
1923 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1925 if (stps_index + 1 < sc->stps_count)
1930 sample_size = sc->alt_sample_size > 0 ? sc->alt_sample_size : sc->sample_sizes[current_sample];
1931 if (sc->pseudo_stream_id == -1 ||
1932 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1933 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1934 e->pos = current_offset;
1935 e->timestamp = current_dts;
1936 e->size = sample_size;
1937 e->min_distance = distance;
1938 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1939 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1940 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1941 current_offset, current_dts, sample_size, distance, keyframe);
1944 current_offset += sample_size;
1945 stream_size += sample_size;
1946 current_dts += sc->stts_data[stts_index].duration;
1950 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1956 if (st->duration > 0)
1957 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1959 unsigned chunk_samples, total = 0;
1961 // compute total chunk count
1962 for (i = 0; i < sc->stsc_count; i++) {
1963 unsigned count, chunk_count;
1965 chunk_samples = sc->stsc_data[i].count;
1966 if (i != sc->stsc_count - 1 &&
1967 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1968 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1972 if (sc->samples_per_frame >= 160) { // gsm
1973 count = chunk_samples / sc->samples_per_frame;
1974 } else if (sc->samples_per_frame > 1) {
1975 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1976 count = (chunk_samples+samples-1) / samples;
1978 count = (chunk_samples+1023) / 1024;
1981 if (i < sc->stsc_count - 1)
1982 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1984 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1985 total += chunk_count * count;
1988 av_dlog(mov->fc, "chunk count %d\n", total);
1989 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1991 mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
1994 st->index_entries = mem;
1995 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
1998 for (i = 0; i < sc->chunk_count; i++) {
1999 current_offset = sc->chunk_offsets[i];
2000 if (stsc_index + 1 < sc->stsc_count &&
2001 i + 1 == sc->stsc_data[stsc_index + 1].first)
2003 chunk_samples = sc->stsc_data[stsc_index].count;
2005 while (chunk_samples > 0) {
2007 unsigned size, samples;
2009 if (sc->samples_per_frame >= 160) { // gsm
2010 samples = sc->samples_per_frame;
2011 size = sc->bytes_per_frame;
2013 if (sc->samples_per_frame > 1) {
2014 samples = FFMIN((1024 / sc->samples_per_frame)*
2015 sc->samples_per_frame, chunk_samples);
2016 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2018 samples = FFMIN(1024, chunk_samples);
2019 size = samples * sc->sample_size;
2023 if (st->nb_index_entries >= total) {
2024 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2027 e = &st->index_entries[st->nb_index_entries++];
2028 e->pos = current_offset;
2029 e->timestamp = current_dts;
2031 e->min_distance = 0;
2032 e->flags = AVINDEX_KEYFRAME;
2033 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2034 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2037 current_offset += size;
2038 current_dts += samples;
2039 chunk_samples -= samples;
2045 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2046 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2048 /* try relative path, we do not try the absolute because it can leak information about our
2049 system to an attacker */
2050 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2051 char filename[1024];
2052 const char *src_path;
2055 /* find a source dir */
2056 src_path = strrchr(src, '/');
2062 /* find a next level down to target */
2063 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2064 if (ref->path[l] == '/') {
2065 if (i == ref->nlvl_to - 1)
2071 /* compose filename if next level down to target was found */
2072 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2073 memcpy(filename, src, src_path - src);
2074 filename[src_path - src] = 0;
2076 for (i = 1; i < ref->nlvl_from; i++)
2077 av_strlcat(filename, "../", 1024);
2079 av_strlcat(filename, ref->path + l + 1, 1024);
2081 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2084 } else if (use_absolute_path) {
2085 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2086 "this is a possible security issue\n");
2087 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2091 return AVERROR(ENOENT);
2094 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2097 MOVStreamContext *sc;
2100 st = avformat_new_stream(c->fc, NULL);
2101 if (!st) return AVERROR(ENOMEM);
2102 st->id = c->fc->nb_streams;
2103 sc = av_mallocz(sizeof(MOVStreamContext));
2104 if (!sc) return AVERROR(ENOMEM);
2107 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2108 sc->ffindex = st->index;
2110 if ((ret = mov_read_default(c, pb, atom)) < 0)
2114 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2115 (!sc->sample_size && !sc->sample_count))) {
2116 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2121 if (sc->time_scale <= 0) {
2122 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2123 sc->time_scale = c->time_scale;
2124 if (sc->time_scale <= 0)
2128 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2130 mov_build_index(c, st);
2132 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2133 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2134 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2135 c->use_absolute_path, c->fc) < 0)
2136 av_log(c->fc, AV_LOG_ERROR,
2137 "stream %d, error opening alias: path='%s', dir='%s', "
2138 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2139 st->index, dref->path, dref->dir, dref->filename,
2140 dref->volume, dref->nlvl_from, dref->nlvl_to);
2144 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2145 if (!st->sample_aspect_ratio.num &&
2146 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2147 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2148 ((double)st->codec->width * sc->height), INT_MAX);
2151 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2152 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2154 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2155 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2156 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2159 switch (st->codec->codec_id) {
2160 #if CONFIG_H261_DECODER
2163 #if CONFIG_H263_DECODER
2166 #if CONFIG_MPEG4_DECODER
2167 case CODEC_ID_MPEG4:
2169 st->codec->width = 0; /* let decoder init width/height */
2170 st->codec->height= 0;
2174 /* Do not need those anymore. */
2175 av_freep(&sc->chunk_offsets);
2176 av_freep(&sc->stsc_data);
2177 av_freep(&sc->sample_sizes);
2178 av_freep(&sc->keyframes);
2179 av_freep(&sc->stts_data);
2180 av_freep(&sc->stps_data);
2185 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2188 c->itunes_metadata = 1;
2189 ret = mov_read_default(c, pb, atom);
2190 c->itunes_metadata = 0;
2194 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2196 while (atom.size > 8) {
2197 uint32_t tag = avio_rl32(pb);
2199 if (tag == MKTAG('h','d','l','r')) {
2200 avio_seek(pb, -8, SEEK_CUR);
2202 return mov_read_default(c, pb, atom);
2208 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2213 int64_t disp_transform[2];
2214 int display_matrix[3][2];
2216 MOVStreamContext *sc;
2219 if (c->fc->nb_streams < 1)
2221 st = c->fc->streams[c->fc->nb_streams-1];
2224 version = avio_r8(pb);
2225 avio_rb24(pb); /* flags */
2227 MOV_TRACK_ENABLED 0x0001
2228 MOV_TRACK_IN_MOVIE 0x0002
2229 MOV_TRACK_IN_PREVIEW 0x0004
2230 MOV_TRACK_IN_POSTER 0x0008
2237 avio_rb32(pb); /* creation time */
2238 avio_rb32(pb); /* modification time */
2240 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2241 avio_rb32(pb); /* reserved */
2243 /* highlevel (considering edits) duration in movie timebase */
2244 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2245 avio_rb32(pb); /* reserved */
2246 avio_rb32(pb); /* reserved */
2248 avio_rb16(pb); /* layer */
2249 avio_rb16(pb); /* alternate group */
2250 avio_rb16(pb); /* volume */
2251 avio_rb16(pb); /* reserved */
2253 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2254 // they're kept in fixed point format through all calculations
2255 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2256 for (i = 0; i < 3; i++) {
2257 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2258 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2259 avio_rb32(pb); // 2.30 fixed point (not used)
2262 width = avio_rb32(pb); // 16.16 fixed point track width
2263 height = avio_rb32(pb); // 16.16 fixed point track height
2264 sc->width = width >> 16;
2265 sc->height = height >> 16;
2267 //Assign clockwise rotate values based on transform matrix so that
2268 //we can compensate for iPhone orientation during capture.
2270 if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2271 av_dict_set(&st->metadata, "rotate", "90", 0);
2274 if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2275 av_dict_set(&st->metadata, "rotate", "180", 0);
2278 if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2279 av_dict_set(&st->metadata, "rotate", "270", 0);
2282 // transform the display width/height according to the matrix
2283 // skip this if the display matrix is the default identity matrix
2284 // or if it is rotating the picture, ex iPhone 3GS
2285 // to keep the same scale, use [width height 1<<16]
2286 if (width && height &&
2287 ((display_matrix[0][0] != 65536 ||
2288 display_matrix[1][1] != 65536) &&
2289 !display_matrix[0][1] &&
2290 !display_matrix[1][0] &&
2291 !display_matrix[2][0] && !display_matrix[2][1])) {
2292 for (i = 0; i < 2; i++)
2294 (int64_t) width * display_matrix[0][i] +
2295 (int64_t) height * display_matrix[1][i] +
2296 ((int64_t) display_matrix[2][i] << 16);
2298 //sample aspect ratio is new width/height divided by old width/height
2299 st->sample_aspect_ratio = av_d2q(
2300 ((double) disp_transform[0] * height) /
2301 ((double) disp_transform[1] * width), INT_MAX);
2306 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2308 MOVFragment *frag = &c->fragment;
2309 MOVTrackExt *trex = NULL;
2310 int flags, track_id, i;
2312 avio_r8(pb); /* version */
2313 flags = avio_rb24(pb);
2315 track_id = avio_rb32(pb);
2317 return AVERROR_INVALIDDATA;
2318 frag->track_id = track_id;
2319 for (i = 0; i < c->trex_count; i++)
2320 if (c->trex_data[i].track_id == frag->track_id) {
2321 trex = &c->trex_data[i];
2325 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2326 return AVERROR_INVALIDDATA;
2329 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2330 avio_rb64(pb) : frag->moof_offset;
2331 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2333 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2334 avio_rb32(pb) : trex->duration;
2335 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2336 avio_rb32(pb) : trex->size;
2337 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2338 avio_rb32(pb) : trex->flags;
2339 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2343 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2345 c->chapter_track = avio_rb32(pb);
2349 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2353 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2354 return AVERROR_INVALIDDATA;
2355 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2357 return AVERROR(ENOMEM);
2359 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2361 c->trex_data = trex;
2362 trex = &c->trex_data[c->trex_count++];
2363 avio_r8(pb); /* version */
2364 avio_rb24(pb); /* flags */
2365 trex->track_id = avio_rb32(pb);
2366 trex->stsd_id = avio_rb32(pb);
2367 trex->duration = avio_rb32(pb);
2368 trex->size = avio_rb32(pb);
2369 trex->flags = avio_rb32(pb);
2373 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2375 MOVFragment *frag = &c->fragment;
2376 AVStream *st = NULL;
2377 MOVStreamContext *sc;
2381 int data_offset = 0;
2382 unsigned entries, first_sample_flags = frag->flags;
2383 int flags, distance, i, found_keyframe = 0;
2385 for (i = 0; i < c->fc->nb_streams; i++) {
2386 if (c->fc->streams[i]->id == frag->track_id) {
2387 st = c->fc->streams[i];
2392 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2393 return AVERROR_INVALIDDATA;
2396 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2398 avio_r8(pb); /* version */
2399 flags = avio_rb24(pb);
2400 entries = avio_rb32(pb);
2401 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2403 /* Always assume the presence of composition time offsets.
2404 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2405 * 1) in the initial movie, there are no samples.
2406 * 2) in the first movie fragment, there is only one sample without composition time offset.
2407 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2408 if (!sc->ctts_count && sc->sample_count)
2410 /* Complement ctts table if moov atom doesn't have ctts atom. */
2411 ctts_data = av_malloc(sizeof(*sc->ctts_data));
2413 return AVERROR(ENOMEM);
2414 sc->ctts_data = ctts_data;
2415 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2416 sc->ctts_data[sc->ctts_count].duration = 0;
2419 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2420 return AVERROR_INVALIDDATA;
2421 ctts_data = av_realloc(sc->ctts_data,
2422 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2424 return AVERROR(ENOMEM);
2425 sc->ctts_data = ctts_data;
2427 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2428 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2429 dts = sc->track_end - sc->time_offset;
2430 offset = frag->base_data_offset + data_offset;
2432 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2433 for (i = 0; i < entries; i++) {
2434 unsigned sample_size = frag->size;
2435 int sample_flags = i ? frag->flags : first_sample_flags;
2436 unsigned sample_duration = frag->duration;
2439 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2440 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2441 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2442 sc->ctts_data[sc->ctts_count].count = 1;
2443 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2446 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2448 else if (!found_keyframe)
2449 keyframe = found_keyframe =
2450 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2451 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2454 av_add_index_entry(st, offset, dts, sample_size, distance,
2455 keyframe ? AVINDEX_KEYFRAME : 0);
2456 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2457 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2458 offset, dts, sample_size, distance, keyframe);
2460 dts += sample_duration;
2461 offset += sample_size;
2462 sc->data_size += sample_size;
2464 frag->moof_offset = offset;
2465 st->duration = sc->track_end = dts + sc->time_offset;
2469 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2470 /* like the files created with Adobe Premiere 5.0, for samples see */
2471 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2472 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2477 return 0; /* continue */
2478 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2479 avio_skip(pb, atom.size - 4);
2482 atom.type = avio_rl32(pb);
2484 if (atom.type != MKTAG('m','d','a','t')) {
2485 avio_skip(pb, atom.size);
2488 err = mov_read_mdat(c, pb, atom);
2492 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2497 uint8_t *moov_data; /* uncompressed data */
2498 long cmov_len, moov_len;
2501 avio_rb32(pb); /* dcom atom */
2502 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2503 return AVERROR_INVALIDDATA;
2504 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2505 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2506 return AVERROR_INVALIDDATA;
2508 avio_rb32(pb); /* cmvd atom */
2509 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2510 return AVERROR_INVALIDDATA;
2511 moov_len = avio_rb32(pb); /* uncompressed size */
2512 cmov_len = atom.size - 6 * 4;
2514 cmov_data = av_malloc(cmov_len);
2516 return AVERROR(ENOMEM);
2517 moov_data = av_malloc(moov_len);
2520 return AVERROR(ENOMEM);
2522 avio_read(pb, cmov_data, cmov_len);
2523 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2524 goto free_and_return;
2525 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2526 goto free_and_return;
2527 atom.type = MKTAG('m','o','o','v');
2528 atom.size = moov_len;
2529 ret = mov_read_default(c, &ctx, atom);
2535 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2536 return AVERROR(ENOSYS);
2540 /* edit list atom */
2541 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2543 MOVStreamContext *sc;
2544 int i, edit_count, version, edit_start_index = 0;
2546 if (c->fc->nb_streams < 1)
2548 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2550 version = avio_r8(pb); /* version */
2551 avio_rb24(pb); /* flags */
2552 edit_count = avio_rb32(pb); /* entries */
2554 if ((uint64_t)edit_count*12+8 > atom.size)
2555 return AVERROR_INVALIDDATA;
2557 for (i=0; i<edit_count; i++){
2561 duration = avio_rb64(pb);
2562 time = avio_rb64(pb);
2564 duration = avio_rb32(pb); /* segment duration */
2565 time = (int32_t)avio_rb32(pb); /* media time */
2567 avio_rb32(pb); /* Media rate */
2568 if (i == 0 && time == -1) {
2569 sc->empty_duration = duration;
2570 edit_start_index = 1;
2571 } else if (i == edit_start_index && time >= 0)
2572 sc->start_time = time;
2576 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2577 "a/v desync might occur, patch welcome\n");
2579 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2583 static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2588 ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
2592 static const MOVParseTableEntry mov_default_parse_table[] = {
2593 { MKTAG('A','P','R','G'), mov_read_aprg },
2594 { MKTAG('a','v','s','s'), mov_read_avss },
2595 { MKTAG('c','h','p','l'), mov_read_chpl },
2596 { MKTAG('c','o','6','4'), mov_read_stco },
2597 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2598 { MKTAG('d','i','n','f'), mov_read_default },
2599 { MKTAG('d','r','e','f'), mov_read_dref },
2600 { MKTAG('e','d','t','s'), mov_read_default },
2601 { MKTAG('e','l','s','t'), mov_read_elst },
2602 { MKTAG('e','n','d','a'), mov_read_enda },
2603 { MKTAG('f','i','e','l'), mov_read_fiel },
2604 { MKTAG('f','t','y','p'), mov_read_ftyp },
2605 { MKTAG('g','l','b','l'), mov_read_glbl },
2606 { MKTAG('h','d','l','r'), mov_read_hdlr },
2607 { MKTAG('i','l','s','t'), mov_read_ilst },
2608 { MKTAG('j','p','2','h'), mov_read_jp2h },
2609 { MKTAG('m','d','a','t'), mov_read_mdat },
2610 { MKTAG('m','d','h','d'), mov_read_mdhd },
2611 { MKTAG('m','d','i','a'), mov_read_default },
2612 { MKTAG('m','e','t','a'), mov_read_meta },
2613 { MKTAG('m','i','n','f'), mov_read_default },
2614 { MKTAG('m','o','o','f'), mov_read_moof },
2615 { MKTAG('m','o','o','v'), mov_read_moov },
2616 { MKTAG('m','v','e','x'), mov_read_default },
2617 { MKTAG('m','v','h','d'), mov_read_mvhd },
2618 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2619 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
2620 { MKTAG('a','v','c','C'), mov_read_glbl },
2621 { MKTAG('p','a','s','p'), mov_read_pasp },
2622 { MKTAG('s','t','b','l'), mov_read_default },
2623 { MKTAG('s','t','c','o'), mov_read_stco },
2624 { MKTAG('s','t','p','s'), mov_read_stps },
2625 { MKTAG('s','t','r','f'), mov_read_strf },
2626 { MKTAG('s','t','s','c'), mov_read_stsc },
2627 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2628 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2629 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2630 { MKTAG('s','t','t','s'), mov_read_stts },
2631 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2632 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2633 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2634 { MKTAG('t','r','a','k'), mov_read_trak },
2635 { MKTAG('t','r','a','f'), mov_read_default },
2636 { MKTAG('t','r','e','f'), mov_read_default },
2637 { MKTAG('c','h','a','p'), mov_read_chap },
2638 { MKTAG('t','r','e','x'), mov_read_trex },
2639 { MKTAG('t','r','u','n'), mov_read_trun },
2640 { MKTAG('u','d','t','a'), mov_read_default },
2641 { MKTAG('w','a','v','e'), mov_read_wave },
2642 { MKTAG('e','s','d','s'), mov_read_esds },
2643 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2644 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2645 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2646 { MKTAG('w','f','e','x'), mov_read_wfex },
2647 { MKTAG('c','m','o','v'), mov_read_cmov },
2648 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2649 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2653 static int mov_probe(AVProbeData *p)
2655 unsigned int offset;
2659 /* check file header */
2662 /* ignore invalid offset */
2663 if ((offset + 8) > (unsigned int)p->buf_size)
2665 tag = AV_RL32(p->buf + offset + 4);
2667 /* check for obvious tags */
2668 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2669 case MKTAG('m','o','o','v'):
2670 case MKTAG('m','d','a','t'):
2671 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2672 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2673 case MKTAG('f','t','y','p'):
2674 return AVPROBE_SCORE_MAX;
2675 /* those are more common words, so rate then a bit less */
2676 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2677 case MKTAG('w','i','d','e'):
2678 case MKTAG('f','r','e','e'):
2679 case MKTAG('j','u','n','k'):
2680 case MKTAG('p','i','c','t'):
2681 return AVPROBE_SCORE_MAX - 5;
2682 case MKTAG(0x82,0x82,0x7f,0x7d):
2683 case MKTAG('s','k','i','p'):
2684 case MKTAG('u','u','i','d'):
2685 case MKTAG('p','r','f','l'):
2686 offset = AV_RB32(p->buf+offset) + offset;
2687 /* if we only find those cause probedata is too small at least rate them */
2688 score = AVPROBE_SCORE_MAX - 50;
2691 /* unrecognized tag */
2697 // must be done after parsing all trak because there's no order requirement
2698 static void mov_read_chapters(AVFormatContext *s)
2700 MOVContext *mov = s->priv_data;
2701 AVStream *st = NULL;
2702 MOVStreamContext *sc;
2706 for (i = 0; i < s->nb_streams; i++)
2707 if (s->streams[i]->id == mov->chapter_track) {
2712 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2716 st->discard = AVDISCARD_ALL;
2718 cur_pos = avio_tell(sc->pb);
2720 for (i = 0; i < st->nb_index_entries; i++) {
2721 AVIndexEntry *sample = &st->index_entries[i];
2722 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2727 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2728 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2732 // the first two bytes are the length of the title
2733 len = avio_rb16(sc->pb);
2734 if (len > sample->size-2)
2736 title_len = 2*len + 1;
2737 if (!(title = av_mallocz(title_len)))
2740 // The samples could theoretically be in any encoding if there's an encd
2741 // atom following, but in practice are only utf-8 or utf-16, distinguished
2742 // instead by the presence of a BOM
2746 ch = avio_rb16(sc->pb);
2748 avio_get_str16be(sc->pb, len, title, title_len);
2749 else if (ch == 0xfffe)
2750 avio_get_str16le(sc->pb, len, title, title_len);
2753 if (len == 1 || len == 2)
2756 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
2760 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2764 avio_seek(sc->pb, cur_pos, SEEK_SET);
2767 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
2768 uint32_t value, int flags)
2771 char buf[AV_TIMECODE_STR_SIZE];
2772 AVRational rate = {st->codec->time_base.den,
2773 st->codec->time_base.num};
2774 int ret = av_timecode_init(&tc, rate, flags, 0, s);
2777 av_dict_set(&st->metadata, "timecode",
2778 av_timecode_make_string(&tc, buf, value), 0);
2782 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
2784 MOVStreamContext *sc = st->priv_data;
2786 int64_t cur_pos = avio_tell(sc->pb);
2789 if (!st->nb_index_entries)
2792 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
2793 value = avio_rb32(s->pb);
2795 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
2796 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
2797 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
2799 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
2800 * not the case) and thus assume "frame number format" instead of QT one.
2801 * No sample with tmcd track can be found with a QT timecode at the moment,
2802 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
2804 parse_timecode_in_framenum_format(s, st, value, flags);
2806 avio_seek(sc->pb, cur_pos, SEEK_SET);
2810 static int mov_read_close(AVFormatContext *s)
2812 MOVContext *mov = s->priv_data;
2815 for (i = 0; i < s->nb_streams; i++) {
2816 AVStream *st = s->streams[i];
2817 MOVStreamContext *sc = st->priv_data;
2819 av_freep(&sc->ctts_data);
2820 for (j = 0; j < sc->drefs_count; j++) {
2821 av_freep(&sc->drefs[j].path);
2822 av_freep(&sc->drefs[j].dir);
2824 av_freep(&sc->drefs);
2825 if (sc->pb && sc->pb != s->pb)
2828 av_freep(&sc->chunk_offsets);
2829 av_freep(&sc->keyframes);
2830 av_freep(&sc->sample_sizes);
2831 av_freep(&sc->stps_data);
2832 av_freep(&sc->stsc_data);
2833 av_freep(&sc->stts_data);
2836 if (mov->dv_demux) {
2837 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2838 av_freep(&mov->dv_fctx->streams[i]->codec);
2839 av_freep(&mov->dv_fctx->streams[i]);
2841 av_freep(&mov->dv_fctx);
2842 av_freep(&mov->dv_demux);
2845 av_freep(&mov->trex_data);
2850 static int mov_read_header(AVFormatContext *s)
2852 MOVContext *mov = s->priv_data;
2853 AVIOContext *pb = s->pb;
2855 MOVAtom atom = { AV_RL32("root") };
2858 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2860 atom.size = avio_size(pb);
2862 atom.size = INT64_MAX;
2864 /* check MOV header */
2865 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2866 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2870 if (!mov->found_moov) {
2871 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2873 return AVERROR_INVALIDDATA;
2875 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2879 if (mov->chapter_track > 0)
2880 mov_read_chapters(s);
2881 for (i = 0; i < s->nb_streams; i++)
2882 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
2883 mov_read_timecode_track(s, s->streams[i]);
2886 if (mov->trex_data) {
2888 for (i = 0; i < s->nb_streams; i++) {
2889 AVStream *st = s->streams[i];
2890 MOVStreamContext *sc = st->priv_data;
2892 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
2899 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2901 AVIndexEntry *sample = NULL;
2902 int64_t best_dts = INT64_MAX;
2904 for (i = 0; i < s->nb_streams; i++) {
2905 AVStream *avst = s->streams[i];
2906 MOVStreamContext *msc = avst->priv_data;
2907 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2908 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2909 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2910 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2911 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2913 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2914 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2915 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2916 sample = current_sample;
2925 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2927 MOVContext *mov = s->priv_data;
2928 MOVStreamContext *sc;
2929 AVIndexEntry *sample;
2930 AVStream *st = NULL;
2934 sample = mov_find_next_sample(s, &st);
2936 mov->found_mdat = 0;
2937 if (!mov->next_root_atom)
2939 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
2940 mov->next_root_atom = 0;
2941 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2944 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2948 /* must be done just before reading, to avoid infinite loop on sample */
2949 sc->current_sample++;
2951 if (st->discard != AVDISCARD_ALL) {
2952 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2953 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2954 sc->ffindex, sample->pos);
2955 return AVERROR_INVALIDDATA;
2957 ret = av_get_packet(sc->pb, pkt, sample->size);
2960 if (sc->has_palette) {
2963 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2965 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2967 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2968 sc->has_palette = 0;
2971 #if CONFIG_DV_DEMUXER
2972 if (mov->dv_demux && sc->dv_audio_container) {
2973 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
2976 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
2983 pkt->stream_index = sc->ffindex;
2984 pkt->dts = sample->timestamp;
2985 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
2986 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2987 /* update ctts context */
2989 if (sc->ctts_index < sc->ctts_count &&
2990 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2992 sc->ctts_sample = 0;
2995 pkt->dts = AV_NOPTS_VALUE;
2997 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2998 st->index_entries[sc->current_sample].timestamp : st->duration;
2999 pkt->duration = next_dts - pkt->dts;
3000 pkt->pts = pkt->dts;
3002 if (st->discard == AVDISCARD_ALL)
3004 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3005 pkt->pos = sample->pos;
3006 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3007 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3011 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3013 MOVStreamContext *sc = st->priv_data;
3014 int sample, time_sample;
3017 sample = av_index_search_timestamp(st, timestamp, flags);
3018 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3019 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3021 if (sample < 0) /* not sure what to do */
3022 return AVERROR_INVALIDDATA;
3023 sc->current_sample = sample;
3024 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3025 /* adjust ctts index */
3026 if (sc->ctts_data) {
3028 for (i = 0; i < sc->ctts_count; i++) {
3029 int next = time_sample + sc->ctts_data[i].count;
3030 if (next > sc->current_sample) {
3032 sc->ctts_sample = sc->current_sample - time_sample;
3041 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3044 int64_t seek_timestamp, timestamp;
3048 if (stream_index >= s->nb_streams)
3049 return AVERROR_INVALIDDATA;
3050 if (sample_time < 0)
3053 st = s->streams[stream_index];
3054 sample = mov_seek_stream(s, st, sample_time, flags);
3058 /* adjust seek timestamp to found sample timestamp */
3059 seek_timestamp = st->index_entries[sample].timestamp;
3061 for (i = 0; i < s->nb_streams; i++) {
3063 if (stream_index == i)
3066 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3067 mov_seek_stream(s, st, timestamp, flags);
3072 static const AVOption options[] = {
3073 {"use_absolute_path",
3074 "allow using absolute path when opening alias, this is a possible security issue",
3075 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.dbl = 0},
3076 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3079 static const AVClass class = {"mov,mp4,m4a,3gp,3g2,mj2", av_default_item_name, options, LIBAVUTIL_VERSION_INT};
3082 AVInputFormat ff_mov_demuxer = {
3083 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3084 .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
3085 .priv_data_size = sizeof(MOVContext),
3086 .read_probe = mov_probe,
3087 .read_header = mov_read_header,
3088 .read_packet = mov_read_packet,
3089 .read_close = mov_read_close,
3090 .read_seek = mov_read_seek,
3091 .priv_class = &class,