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 langcode = 0;
179 uint32_t data_type = 0, str_size;
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:
1544 st->codec->block_align = sc->bytes_per_frame;
1547 if (st->codec->extradata_size == 36) {
1548 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1549 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1553 st->need_parsing = AVSTREAM_PARSE_FULL;
1555 case CODEC_ID_MPEG1VIDEO:
1556 st->need_parsing = AVSTREAM_PARSE_FULL;
1559 st->need_parsing = AVSTREAM_PARSE_FULL;
1568 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1572 avio_r8(pb); /* version */
1573 avio_rb24(pb); /* flags */
1574 entries = avio_rb32(pb);
1576 return ff_mov_read_stsd_entries(c, pb, entries);
1579 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1582 MOVStreamContext *sc;
1583 unsigned int i, entries;
1585 if (c->fc->nb_streams < 1)
1587 st = c->fc->streams[c->fc->nb_streams-1];
1590 avio_r8(pb); /* version */
1591 avio_rb24(pb); /* flags */
1593 entries = avio_rb32(pb);
1595 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1599 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1600 return AVERROR_INVALIDDATA;
1601 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1603 return AVERROR(ENOMEM);
1604 sc->stsc_count = entries;
1606 for (i=0; i<entries; i++) {
1607 sc->stsc_data[i].first = avio_rb32(pb);
1608 sc->stsc_data[i].count = avio_rb32(pb);
1609 sc->stsc_data[i].id = avio_rb32(pb);
1614 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1617 MOVStreamContext *sc;
1618 unsigned i, entries;
1620 if (c->fc->nb_streams < 1)
1622 st = c->fc->streams[c->fc->nb_streams-1];
1625 avio_rb32(pb); // version + flags
1627 entries = avio_rb32(pb);
1628 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1629 return AVERROR_INVALIDDATA;
1630 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1632 return AVERROR(ENOMEM);
1633 sc->stps_count = entries;
1635 for (i = 0; i < entries; i++) {
1636 sc->stps_data[i] = avio_rb32(pb);
1637 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1643 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1646 MOVStreamContext *sc;
1647 unsigned int i, entries;
1649 if (c->fc->nb_streams < 1)
1651 st = c->fc->streams[c->fc->nb_streams-1];
1654 avio_r8(pb); /* version */
1655 avio_rb24(pb); /* flags */
1657 entries = avio_rb32(pb);
1659 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1663 sc->keyframe_absent = 1;
1666 if (entries >= UINT_MAX / sizeof(int))
1667 return AVERROR_INVALIDDATA;
1668 sc->keyframes = av_malloc(entries * sizeof(int));
1670 return AVERROR(ENOMEM);
1671 sc->keyframe_count = entries;
1673 for (i=0; i<entries; i++) {
1674 sc->keyframes[i] = avio_rb32(pb);
1675 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1680 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1683 MOVStreamContext *sc;
1684 unsigned int i, entries, sample_size, field_size, num_bytes;
1688 if (c->fc->nb_streams < 1)
1690 st = c->fc->streams[c->fc->nb_streams-1];
1693 avio_r8(pb); /* version */
1694 avio_rb24(pb); /* flags */
1696 if (atom.type == MKTAG('s','t','s','z')) {
1697 sample_size = avio_rb32(pb);
1698 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1699 sc->sample_size = sample_size;
1700 sc->alt_sample_size = sample_size;
1704 avio_rb24(pb); /* reserved */
1705 field_size = avio_r8(pb);
1707 entries = avio_rb32(pb);
1709 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1711 sc->sample_count = entries;
1715 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1716 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1717 return AVERROR_INVALIDDATA;
1722 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1723 return AVERROR_INVALIDDATA;
1724 sc->sample_sizes = av_malloc(entries * sizeof(int));
1725 if (!sc->sample_sizes)
1726 return AVERROR(ENOMEM);
1728 num_bytes = (entries*field_size+4)>>3;
1730 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1732 av_freep(&sc->sample_sizes);
1733 return AVERROR(ENOMEM);
1736 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1737 av_freep(&sc->sample_sizes);
1739 return AVERROR_INVALIDDATA;
1742 init_get_bits(&gb, buf, 8*num_bytes);
1744 for (i = 0; i < entries; i++) {
1745 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1746 sc->data_size += sc->sample_sizes[i];
1753 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1756 MOVStreamContext *sc;
1757 unsigned int i, entries;
1759 int64_t total_sample_count=0;
1761 if (c->fc->nb_streams < 1)
1763 st = c->fc->streams[c->fc->nb_streams-1];
1766 avio_r8(pb); /* version */
1767 avio_rb24(pb); /* flags */
1768 entries = avio_rb32(pb);
1770 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1771 c->fc->nb_streams-1, entries);
1773 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1776 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1778 return AVERROR(ENOMEM);
1780 sc->stts_count = entries;
1782 for (i=0; i<entries; i++) {
1783 int sample_duration;
1786 sample_count=avio_rb32(pb);
1787 sample_duration = avio_rb32(pb);
1788 /* sample_duration < 0 is invalid based on the spec */
1789 if (sample_duration < 0) {
1790 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
1791 sample_duration = 1;
1793 sc->stts_data[i].count= sample_count;
1794 sc->stts_data[i].duration= sample_duration;
1796 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1797 sample_count, sample_duration);
1799 duration+=(int64_t)sample_duration*sample_count;
1800 total_sample_count+=sample_count;
1803 st->nb_frames= total_sample_count;
1805 st->duration= duration;
1806 sc->track_end = duration;
1810 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1813 MOVStreamContext *sc;
1814 unsigned int i, entries;
1816 if (c->fc->nb_streams < 1)
1818 st = c->fc->streams[c->fc->nb_streams-1];
1821 avio_r8(pb); /* version */
1822 avio_rb24(pb); /* flags */
1823 entries = avio_rb32(pb);
1825 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1829 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1830 return AVERROR_INVALIDDATA;
1831 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1833 return AVERROR(ENOMEM);
1834 sc->ctts_count = entries;
1836 for (i=0; i<entries; i++) {
1837 int count =avio_rb32(pb);
1838 int duration =avio_rb32(pb);
1840 sc->ctts_data[i].count = count;
1841 sc->ctts_data[i].duration= duration;
1843 if (FFABS(duration) > (1<<28) && i+2<entries) {
1844 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
1845 av_freep(&sc->ctts_data);
1850 if (duration < 0 && i+2<entries)
1851 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1854 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1859 static void mov_build_index(MOVContext *mov, AVStream *st)
1861 MOVStreamContext *sc = st->priv_data;
1862 int64_t current_offset;
1863 int64_t current_dts = 0;
1864 unsigned int stts_index = 0;
1865 unsigned int stsc_index = 0;
1866 unsigned int stss_index = 0;
1867 unsigned int stps_index = 0;
1869 uint64_t stream_size = 0;
1872 /* adjust first dts according to edit list */
1873 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
1874 if (sc->empty_duration)
1875 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
1876 sc->time_offset = sc->start_time - sc->empty_duration;
1877 current_dts = -sc->time_offset;
1878 if (sc->ctts_count>0 && sc->stts_count>0 &&
1879 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1880 /* more than 16 frames delay, dts are likely wrong
1881 this happens with files created by iMovie */
1883 st->codec->has_b_frames = 1;
1887 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1888 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1889 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1890 unsigned int current_sample = 0;
1891 unsigned int stts_sample = 0;
1892 unsigned int sample_size;
1893 unsigned int distance = 0;
1894 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
1896 current_dts -= sc->dts_shift;
1898 if (!sc->sample_count || st->nb_index_entries)
1900 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1902 mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1905 st->index_entries = mem;
1906 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
1908 for (i = 0; i < sc->chunk_count; i++) {
1909 current_offset = sc->chunk_offsets[i];
1910 while (stsc_index + 1 < sc->stsc_count &&
1911 i + 1 == sc->stsc_data[stsc_index + 1].first)
1913 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1915 if (current_sample >= sc->sample_count) {
1916 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1920 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
1922 if (stss_index + 1 < sc->keyframe_count)
1924 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1926 if (stps_index + 1 < sc->stps_count)
1931 sample_size = sc->alt_sample_size > 0 ? sc->alt_sample_size : sc->sample_sizes[current_sample];
1932 if (sc->pseudo_stream_id == -1 ||
1933 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1934 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1935 e->pos = current_offset;
1936 e->timestamp = current_dts;
1937 e->size = sample_size;
1938 e->min_distance = distance;
1939 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1940 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1941 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1942 current_offset, current_dts, sample_size, distance, keyframe);
1945 current_offset += sample_size;
1946 stream_size += sample_size;
1947 current_dts += sc->stts_data[stts_index].duration;
1951 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1957 if (st->duration > 0)
1958 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1960 unsigned chunk_samples, total = 0;
1962 // compute total chunk count
1963 for (i = 0; i < sc->stsc_count; i++) {
1964 unsigned count, chunk_count;
1966 chunk_samples = sc->stsc_data[i].count;
1967 if (i != sc->stsc_count - 1 &&
1968 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1969 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1973 if (sc->samples_per_frame >= 160) { // gsm
1974 count = chunk_samples / sc->samples_per_frame;
1975 } else if (sc->samples_per_frame > 1) {
1976 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1977 count = (chunk_samples+samples-1) / samples;
1979 count = (chunk_samples+1023) / 1024;
1982 if (i < sc->stsc_count - 1)
1983 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1985 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1986 total += chunk_count * count;
1989 av_dlog(mov->fc, "chunk count %d\n", total);
1990 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1992 mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
1995 st->index_entries = mem;
1996 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
1999 for (i = 0; i < sc->chunk_count; i++) {
2000 current_offset = sc->chunk_offsets[i];
2001 if (stsc_index + 1 < sc->stsc_count &&
2002 i + 1 == sc->stsc_data[stsc_index + 1].first)
2004 chunk_samples = sc->stsc_data[stsc_index].count;
2006 while (chunk_samples > 0) {
2008 unsigned size, samples;
2010 if (sc->samples_per_frame >= 160) { // gsm
2011 samples = sc->samples_per_frame;
2012 size = sc->bytes_per_frame;
2014 if (sc->samples_per_frame > 1) {
2015 samples = FFMIN((1024 / sc->samples_per_frame)*
2016 sc->samples_per_frame, chunk_samples);
2017 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2019 samples = FFMIN(1024, chunk_samples);
2020 size = samples * sc->sample_size;
2024 if (st->nb_index_entries >= total) {
2025 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2028 e = &st->index_entries[st->nb_index_entries++];
2029 e->pos = current_offset;
2030 e->timestamp = current_dts;
2032 e->min_distance = 0;
2033 e->flags = AVINDEX_KEYFRAME;
2034 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2035 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2038 current_offset += size;
2039 current_dts += samples;
2040 chunk_samples -= samples;
2046 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2047 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2049 /* try relative path, we do not try the absolute because it can leak information about our
2050 system to an attacker */
2051 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2052 char filename[1024];
2053 const char *src_path;
2056 /* find a source dir */
2057 src_path = strrchr(src, '/');
2063 /* find a next level down to target */
2064 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2065 if (ref->path[l] == '/') {
2066 if (i == ref->nlvl_to - 1)
2072 /* compose filename if next level down to target was found */
2073 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2074 memcpy(filename, src, src_path - src);
2075 filename[src_path - src] = 0;
2077 for (i = 1; i < ref->nlvl_from; i++)
2078 av_strlcat(filename, "../", 1024);
2080 av_strlcat(filename, ref->path + l + 1, 1024);
2082 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2085 } else if (use_absolute_path) {
2086 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2087 "this is a possible security issue\n");
2088 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2092 return AVERROR(ENOENT);
2095 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2098 MOVStreamContext *sc;
2101 st = avformat_new_stream(c->fc, NULL);
2102 if (!st) return AVERROR(ENOMEM);
2103 st->id = c->fc->nb_streams;
2104 sc = av_mallocz(sizeof(MOVStreamContext));
2105 if (!sc) return AVERROR(ENOMEM);
2108 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2109 sc->ffindex = st->index;
2111 if ((ret = mov_read_default(c, pb, atom)) < 0)
2115 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2116 (!sc->sample_size && !sc->sample_count))) {
2117 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2122 if (sc->time_scale <= 0) {
2123 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2124 sc->time_scale = c->time_scale;
2125 if (sc->time_scale <= 0)
2129 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2131 mov_build_index(c, st);
2133 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2134 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2135 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2136 c->use_absolute_path, c->fc) < 0)
2137 av_log(c->fc, AV_LOG_ERROR,
2138 "stream %d, error opening alias: path='%s', dir='%s', "
2139 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2140 st->index, dref->path, dref->dir, dref->filename,
2141 dref->volume, dref->nlvl_from, dref->nlvl_to);
2145 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2146 if (!st->sample_aspect_ratio.num &&
2147 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2148 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2149 ((double)st->codec->width * sc->height), INT_MAX);
2152 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2153 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2155 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2156 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2157 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2160 switch (st->codec->codec_id) {
2161 #if CONFIG_H261_DECODER
2164 #if CONFIG_H263_DECODER
2167 #if CONFIG_MPEG4_DECODER
2168 case CODEC_ID_MPEG4:
2170 st->codec->width = 0; /* let decoder init width/height */
2171 st->codec->height= 0;
2175 /* Do not need those anymore. */
2176 av_freep(&sc->chunk_offsets);
2177 av_freep(&sc->stsc_data);
2178 av_freep(&sc->sample_sizes);
2179 av_freep(&sc->keyframes);
2180 av_freep(&sc->stts_data);
2181 av_freep(&sc->stps_data);
2186 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2189 c->itunes_metadata = 1;
2190 ret = mov_read_default(c, pb, atom);
2191 c->itunes_metadata = 0;
2195 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2197 while (atom.size > 8) {
2198 uint32_t tag = avio_rl32(pb);
2200 if (tag == MKTAG('h','d','l','r')) {
2201 avio_seek(pb, -8, SEEK_CUR);
2203 return mov_read_default(c, pb, atom);
2209 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2214 int64_t disp_transform[2];
2215 int display_matrix[3][2];
2217 MOVStreamContext *sc;
2220 if (c->fc->nb_streams < 1)
2222 st = c->fc->streams[c->fc->nb_streams-1];
2225 version = avio_r8(pb);
2226 avio_rb24(pb); /* flags */
2228 MOV_TRACK_ENABLED 0x0001
2229 MOV_TRACK_IN_MOVIE 0x0002
2230 MOV_TRACK_IN_PREVIEW 0x0004
2231 MOV_TRACK_IN_POSTER 0x0008
2238 avio_rb32(pb); /* creation time */
2239 avio_rb32(pb); /* modification time */
2241 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2242 avio_rb32(pb); /* reserved */
2244 /* highlevel (considering edits) duration in movie timebase */
2245 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2246 avio_rb32(pb); /* reserved */
2247 avio_rb32(pb); /* reserved */
2249 avio_rb16(pb); /* layer */
2250 avio_rb16(pb); /* alternate group */
2251 avio_rb16(pb); /* volume */
2252 avio_rb16(pb); /* reserved */
2254 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2255 // they're kept in fixed point format through all calculations
2256 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2257 for (i = 0; i < 3; i++) {
2258 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2259 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2260 avio_rb32(pb); // 2.30 fixed point (not used)
2263 width = avio_rb32(pb); // 16.16 fixed point track width
2264 height = avio_rb32(pb); // 16.16 fixed point track height
2265 sc->width = width >> 16;
2266 sc->height = height >> 16;
2268 //Assign clockwise rotate values based on transform matrix so that
2269 //we can compensate for iPhone orientation during capture.
2271 if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2272 av_dict_set(&st->metadata, "rotate", "90", 0);
2275 if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2276 av_dict_set(&st->metadata, "rotate", "180", 0);
2279 if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2280 av_dict_set(&st->metadata, "rotate", "270", 0);
2283 // transform the display width/height according to the matrix
2284 // skip this if the display matrix is the default identity matrix
2285 // or if it is rotating the picture, ex iPhone 3GS
2286 // to keep the same scale, use [width height 1<<16]
2287 if (width && height &&
2288 ((display_matrix[0][0] != 65536 ||
2289 display_matrix[1][1] != 65536) &&
2290 !display_matrix[0][1] &&
2291 !display_matrix[1][0] &&
2292 !display_matrix[2][0] && !display_matrix[2][1])) {
2293 for (i = 0; i < 2; i++)
2295 (int64_t) width * display_matrix[0][i] +
2296 (int64_t) height * display_matrix[1][i] +
2297 ((int64_t) display_matrix[2][i] << 16);
2299 //sample aspect ratio is new width/height divided by old width/height
2300 st->sample_aspect_ratio = av_d2q(
2301 ((double) disp_transform[0] * height) /
2302 ((double) disp_transform[1] * width), INT_MAX);
2307 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2309 MOVFragment *frag = &c->fragment;
2310 MOVTrackExt *trex = NULL;
2311 int flags, track_id, i;
2313 avio_r8(pb); /* version */
2314 flags = avio_rb24(pb);
2316 track_id = avio_rb32(pb);
2318 return AVERROR_INVALIDDATA;
2319 frag->track_id = track_id;
2320 for (i = 0; i < c->trex_count; i++)
2321 if (c->trex_data[i].track_id == frag->track_id) {
2322 trex = &c->trex_data[i];
2326 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2327 return AVERROR_INVALIDDATA;
2330 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2331 avio_rb64(pb) : frag->moof_offset;
2332 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2334 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2335 avio_rb32(pb) : trex->duration;
2336 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2337 avio_rb32(pb) : trex->size;
2338 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2339 avio_rb32(pb) : trex->flags;
2340 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2344 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2346 c->chapter_track = avio_rb32(pb);
2350 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2354 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2355 return AVERROR_INVALIDDATA;
2356 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2358 return AVERROR(ENOMEM);
2360 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2362 c->trex_data = trex;
2363 trex = &c->trex_data[c->trex_count++];
2364 avio_r8(pb); /* version */
2365 avio_rb24(pb); /* flags */
2366 trex->track_id = avio_rb32(pb);
2367 trex->stsd_id = avio_rb32(pb);
2368 trex->duration = avio_rb32(pb);
2369 trex->size = avio_rb32(pb);
2370 trex->flags = avio_rb32(pb);
2374 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2376 MOVFragment *frag = &c->fragment;
2377 AVStream *st = NULL;
2378 MOVStreamContext *sc;
2382 int data_offset = 0;
2383 unsigned entries, first_sample_flags = frag->flags;
2384 int flags, distance, i, found_keyframe = 0;
2386 for (i = 0; i < c->fc->nb_streams; i++) {
2387 if (c->fc->streams[i]->id == frag->track_id) {
2388 st = c->fc->streams[i];
2393 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2394 return AVERROR_INVALIDDATA;
2397 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2399 avio_r8(pb); /* version */
2400 flags = avio_rb24(pb);
2401 entries = avio_rb32(pb);
2402 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2404 /* Always assume the presence of composition time offsets.
2405 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2406 * 1) in the initial movie, there are no samples.
2407 * 2) in the first movie fragment, there is only one sample without composition time offset.
2408 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2409 if (!sc->ctts_count && sc->sample_count)
2411 /* Complement ctts table if moov atom doesn't have ctts atom. */
2412 ctts_data = av_malloc(sizeof(*sc->ctts_data));
2414 return AVERROR(ENOMEM);
2415 sc->ctts_data = ctts_data;
2416 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2417 sc->ctts_data[sc->ctts_count].duration = 0;
2420 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2421 return AVERROR_INVALIDDATA;
2422 ctts_data = av_realloc(sc->ctts_data,
2423 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2425 return AVERROR(ENOMEM);
2426 sc->ctts_data = ctts_data;
2428 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2429 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2430 dts = sc->track_end - sc->time_offset;
2431 offset = frag->base_data_offset + data_offset;
2433 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2434 for (i = 0; i < entries; i++) {
2435 unsigned sample_size = frag->size;
2436 int sample_flags = i ? frag->flags : first_sample_flags;
2437 unsigned sample_duration = frag->duration;
2440 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2441 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2442 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2443 sc->ctts_data[sc->ctts_count].count = 1;
2444 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2447 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2449 else if (!found_keyframe)
2450 keyframe = found_keyframe =
2451 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2452 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2455 av_add_index_entry(st, offset, dts, sample_size, distance,
2456 keyframe ? AVINDEX_KEYFRAME : 0);
2457 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2458 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2459 offset, dts, sample_size, distance, keyframe);
2461 dts += sample_duration;
2462 offset += sample_size;
2463 sc->data_size += sample_size;
2465 frag->moof_offset = offset;
2466 st->duration = sc->track_end = dts + sc->time_offset;
2470 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2471 /* like the files created with Adobe Premiere 5.0, for samples see */
2472 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2473 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2478 return 0; /* continue */
2479 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2480 avio_skip(pb, atom.size - 4);
2483 atom.type = avio_rl32(pb);
2485 if (atom.type != MKTAG('m','d','a','t')) {
2486 avio_skip(pb, atom.size);
2489 err = mov_read_mdat(c, pb, atom);
2493 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2498 uint8_t *moov_data; /* uncompressed data */
2499 long cmov_len, moov_len;
2502 avio_rb32(pb); /* dcom atom */
2503 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2504 return AVERROR_INVALIDDATA;
2505 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2506 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2507 return AVERROR_INVALIDDATA;
2509 avio_rb32(pb); /* cmvd atom */
2510 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2511 return AVERROR_INVALIDDATA;
2512 moov_len = avio_rb32(pb); /* uncompressed size */
2513 cmov_len = atom.size - 6 * 4;
2515 cmov_data = av_malloc(cmov_len);
2517 return AVERROR(ENOMEM);
2518 moov_data = av_malloc(moov_len);
2521 return AVERROR(ENOMEM);
2523 avio_read(pb, cmov_data, cmov_len);
2524 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2525 goto free_and_return;
2526 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2527 goto free_and_return;
2528 atom.type = MKTAG('m','o','o','v');
2529 atom.size = moov_len;
2530 ret = mov_read_default(c, &ctx, atom);
2536 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2537 return AVERROR(ENOSYS);
2541 /* edit list atom */
2542 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2544 MOVStreamContext *sc;
2545 int i, edit_count, version, edit_start_index = 0;
2547 if (c->fc->nb_streams < 1)
2549 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2551 version = avio_r8(pb); /* version */
2552 avio_rb24(pb); /* flags */
2553 edit_count = avio_rb32(pb); /* entries */
2555 if ((uint64_t)edit_count*12+8 > atom.size)
2556 return AVERROR_INVALIDDATA;
2558 for (i=0; i<edit_count; i++){
2562 duration = avio_rb64(pb);
2563 time = avio_rb64(pb);
2565 duration = avio_rb32(pb); /* segment duration */
2566 time = (int32_t)avio_rb32(pb); /* media time */
2568 avio_rb32(pb); /* Media rate */
2569 if (i == 0 && time == -1) {
2570 sc->empty_duration = duration;
2571 edit_start_index = 1;
2572 } else if (i == edit_start_index && time >= 0)
2573 sc->start_time = time;
2577 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2578 "a/v desync might occur, patch welcome\n");
2580 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2584 static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2589 ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
2593 static int mov_read_tref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2596 MOVStreamContext *sc;
2598 if (c->fc->nb_streams < 1)
2599 return AVERROR_INVALIDDATA;
2600 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
2602 size = avio_rb32(pb);
2606 sc->trefs_count = (size - 4) / 8;
2607 sc->trefs = av_malloc(sc->trefs_count * sizeof(*sc->trefs));
2609 return AVERROR(ENOMEM);
2611 sc->tref_type = avio_rl32(pb);
2612 for (i = 0; i < sc->trefs_count; i++)
2613 sc->trefs[i] = avio_rb32(pb);
2617 static const MOVParseTableEntry mov_default_parse_table[] = {
2618 { MKTAG('A','P','R','G'), mov_read_aprg },
2619 { MKTAG('a','v','s','s'), mov_read_avss },
2620 { MKTAG('c','h','p','l'), mov_read_chpl },
2621 { MKTAG('c','o','6','4'), mov_read_stco },
2622 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2623 { MKTAG('d','i','n','f'), mov_read_default },
2624 { MKTAG('d','r','e','f'), mov_read_dref },
2625 { MKTAG('e','d','t','s'), mov_read_default },
2626 { MKTAG('e','l','s','t'), mov_read_elst },
2627 { MKTAG('e','n','d','a'), mov_read_enda },
2628 { MKTAG('f','i','e','l'), mov_read_fiel },
2629 { MKTAG('f','t','y','p'), mov_read_ftyp },
2630 { MKTAG('g','l','b','l'), mov_read_glbl },
2631 { MKTAG('h','d','l','r'), mov_read_hdlr },
2632 { MKTAG('i','l','s','t'), mov_read_ilst },
2633 { MKTAG('j','p','2','h'), mov_read_jp2h },
2634 { MKTAG('m','d','a','t'), mov_read_mdat },
2635 { MKTAG('m','d','h','d'), mov_read_mdhd },
2636 { MKTAG('m','d','i','a'), mov_read_default },
2637 { MKTAG('m','e','t','a'), mov_read_meta },
2638 { MKTAG('m','i','n','f'), mov_read_default },
2639 { MKTAG('m','o','o','f'), mov_read_moof },
2640 { MKTAG('m','o','o','v'), mov_read_moov },
2641 { MKTAG('m','v','e','x'), mov_read_default },
2642 { MKTAG('m','v','h','d'), mov_read_mvhd },
2643 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2644 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
2645 { MKTAG('a','v','c','C'), mov_read_glbl },
2646 { MKTAG('p','a','s','p'), mov_read_pasp },
2647 { MKTAG('s','t','b','l'), mov_read_default },
2648 { MKTAG('s','t','c','o'), mov_read_stco },
2649 { MKTAG('s','t','p','s'), mov_read_stps },
2650 { MKTAG('s','t','r','f'), mov_read_strf },
2651 { MKTAG('s','t','s','c'), mov_read_stsc },
2652 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2653 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2654 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2655 { MKTAG('s','t','t','s'), mov_read_stts },
2656 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2657 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2658 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2659 { MKTAG('t','r','a','k'), mov_read_trak },
2660 { MKTAG('t','r','a','f'), mov_read_default },
2661 { MKTAG('t','r','e','f'), mov_read_tref },
2662 { MKTAG('c','h','a','p'), mov_read_chap },
2663 { MKTAG('t','r','e','x'), mov_read_trex },
2664 { MKTAG('t','r','u','n'), mov_read_trun },
2665 { MKTAG('u','d','t','a'), mov_read_default },
2666 { MKTAG('w','a','v','e'), mov_read_wave },
2667 { MKTAG('e','s','d','s'), mov_read_esds },
2668 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2669 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2670 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2671 { MKTAG('w','f','e','x'), mov_read_wfex },
2672 { MKTAG('c','m','o','v'), mov_read_cmov },
2673 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2674 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2678 static int mov_probe(AVProbeData *p)
2680 unsigned int offset;
2684 /* check file header */
2687 /* ignore invalid offset */
2688 if ((offset + 8) > (unsigned int)p->buf_size)
2690 tag = AV_RL32(p->buf + offset + 4);
2692 /* check for obvious tags */
2693 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2694 case MKTAG('m','o','o','v'):
2695 case MKTAG('m','d','a','t'):
2696 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2697 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2698 case MKTAG('f','t','y','p'):
2699 return AVPROBE_SCORE_MAX;
2700 /* those are more common words, so rate then a bit less */
2701 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2702 case MKTAG('w','i','d','e'):
2703 case MKTAG('f','r','e','e'):
2704 case MKTAG('j','u','n','k'):
2705 case MKTAG('p','i','c','t'):
2706 return AVPROBE_SCORE_MAX - 5;
2707 case MKTAG(0x82,0x82,0x7f,0x7d):
2708 case MKTAG('s','k','i','p'):
2709 case MKTAG('u','u','i','d'):
2710 case MKTAG('p','r','f','l'):
2711 offset = AV_RB32(p->buf+offset) + offset;
2712 /* if we only find those cause probedata is too small at least rate them */
2713 score = AVPROBE_SCORE_MAX - 50;
2716 /* unrecognized tag */
2722 // must be done after parsing all trak because there's no order requirement
2723 static void mov_read_chapters(AVFormatContext *s)
2725 MOVContext *mov = s->priv_data;
2726 AVStream *st = NULL;
2727 MOVStreamContext *sc;
2731 for (i = 0; i < s->nb_streams; i++)
2732 if (s->streams[i]->id == mov->chapter_track) {
2737 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2741 st->discard = AVDISCARD_ALL;
2743 cur_pos = avio_tell(sc->pb);
2745 for (i = 0; i < st->nb_index_entries; i++) {
2746 AVIndexEntry *sample = &st->index_entries[i];
2747 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2752 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2753 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2757 // the first two bytes are the length of the title
2758 len = avio_rb16(sc->pb);
2759 if (len > sample->size-2)
2761 title_len = 2*len + 1;
2762 if (!(title = av_mallocz(title_len)))
2765 // The samples could theoretically be in any encoding if there's an encd
2766 // atom following, but in practice are only utf-8 or utf-16, distinguished
2767 // instead by the presence of a BOM
2771 ch = avio_rb16(sc->pb);
2773 avio_get_str16be(sc->pb, len, title, title_len);
2774 else if (ch == 0xfffe)
2775 avio_get_str16le(sc->pb, len, title, title_len);
2778 if (len == 1 || len == 2)
2781 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
2785 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2789 avio_seek(sc->pb, cur_pos, SEEK_SET);
2792 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
2793 uint32_t value, int flags)
2796 char buf[AV_TIMECODE_STR_SIZE];
2797 AVRational rate = {st->codec->time_base.den,
2798 st->codec->time_base.num};
2799 int ret = av_timecode_init(&tc, rate, flags, 0, s);
2802 av_dict_set(&st->metadata, "timecode",
2803 av_timecode_make_string(&tc, buf, value), 0);
2807 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
2809 MOVStreamContext *sc = st->priv_data;
2811 int64_t cur_pos = avio_tell(sc->pb);
2814 if (!st->nb_index_entries)
2817 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
2818 value = avio_rb32(s->pb);
2820 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
2821 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
2822 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
2824 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
2825 * not the case) and thus assume "frame number format" instead of QT one.
2826 * No sample with tmcd track can be found with a QT timecode at the moment,
2827 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
2829 parse_timecode_in_framenum_format(s, st, value, flags);
2831 avio_seek(sc->pb, cur_pos, SEEK_SET);
2835 static int mov_read_close(AVFormatContext *s)
2837 MOVContext *mov = s->priv_data;
2840 for (i = 0; i < s->nb_streams; i++) {
2841 AVStream *st = s->streams[i];
2842 MOVStreamContext *sc = st->priv_data;
2844 av_freep(&sc->ctts_data);
2845 for (j = 0; j < sc->drefs_count; j++) {
2846 av_freep(&sc->drefs[j].path);
2847 av_freep(&sc->drefs[j].dir);
2849 av_freep(&sc->drefs);
2850 av_freep(&sc->trefs);
2851 if (sc->pb && sc->pb != s->pb)
2854 av_freep(&sc->chunk_offsets);
2855 av_freep(&sc->keyframes);
2856 av_freep(&sc->sample_sizes);
2857 av_freep(&sc->stps_data);
2858 av_freep(&sc->stsc_data);
2859 av_freep(&sc->stts_data);
2862 if (mov->dv_demux) {
2863 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2864 av_freep(&mov->dv_fctx->streams[i]->codec);
2865 av_freep(&mov->dv_fctx->streams[i]);
2867 av_freep(&mov->dv_fctx);
2868 av_freep(&mov->dv_demux);
2871 av_freep(&mov->trex_data);
2876 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
2880 for (i = 0; i < s->nb_streams; i++) {
2881 AVStream *st = s->streams[i];
2882 MOVStreamContext *sc = st->priv_data;
2884 if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
2886 for (j = 0; j < sc->trefs_count; j++)
2887 if (tmcd_id == sc->trefs[j])
2893 /* look for a tmcd track not referenced by any video track, and export it globally */
2894 static void export_orphan_timecode(AVFormatContext *s)
2898 for (i = 0; i < s->nb_streams; i++) {
2899 AVStream *st = s->streams[i];
2901 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
2902 !tmcd_is_referenced(s, i + 1)) {
2903 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
2905 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
2912 static int mov_read_header(AVFormatContext *s)
2914 MOVContext *mov = s->priv_data;
2915 AVIOContext *pb = s->pb;
2917 MOVAtom atom = { AV_RL32("root") };
2920 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2922 atom.size = avio_size(pb);
2924 atom.size = INT64_MAX;
2926 /* check MOV header */
2927 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2928 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2932 if (!mov->found_moov) {
2933 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2935 return AVERROR_INVALIDDATA;
2937 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2940 if (mov->chapter_track > 0)
2941 mov_read_chapters(s);
2942 for (i = 0; i < s->nb_streams; i++)
2943 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
2944 mov_read_timecode_track(s, s->streams[i]);
2947 /* copy timecode metadata from tmcd tracks to the related video streams */
2948 for (i = 0; i < s->nb_streams; i++) {
2949 AVStream *st = s->streams[i];
2950 MOVStreamContext *sc = st->priv_data;
2951 if (sc->tref_type == AV_RL32("tmcd") && sc->trefs_count) {
2952 AVDictionaryEntry *tcr;
2953 int tmcd_st_id = sc->trefs[0] - 1;
2955 if (tmcd_st_id < 0 || tmcd_st_id >= s->nb_streams)
2957 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
2959 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
2962 export_orphan_timecode(s);
2964 if (mov->trex_data) {
2965 for (i = 0; i < s->nb_streams; i++) {
2966 AVStream *st = s->streams[i];
2967 MOVStreamContext *sc = st->priv_data;
2969 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
2976 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2978 AVIndexEntry *sample = NULL;
2979 int64_t best_dts = INT64_MAX;
2981 for (i = 0; i < s->nb_streams; i++) {
2982 AVStream *avst = s->streams[i];
2983 MOVStreamContext *msc = avst->priv_data;
2984 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2985 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2986 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2987 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2988 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2990 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2991 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2992 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2993 sample = current_sample;
3002 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3004 MOVContext *mov = s->priv_data;
3005 MOVStreamContext *sc;
3006 AVIndexEntry *sample;
3007 AVStream *st = NULL;
3011 sample = mov_find_next_sample(s, &st);
3013 mov->found_mdat = 0;
3014 if (!mov->next_root_atom)
3016 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3017 mov->next_root_atom = 0;
3018 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3021 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3025 /* must be done just before reading, to avoid infinite loop on sample */
3026 sc->current_sample++;
3028 if (st->discard != AVDISCARD_ALL) {
3029 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3030 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3031 sc->ffindex, sample->pos);
3032 return AVERROR_INVALIDDATA;
3034 ret = av_get_packet(sc->pb, pkt, sample->size);
3037 if (sc->has_palette) {
3040 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3042 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3044 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3045 sc->has_palette = 0;
3048 #if CONFIG_DV_DEMUXER
3049 if (mov->dv_demux && sc->dv_audio_container) {
3050 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
3053 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3060 pkt->stream_index = sc->ffindex;
3061 pkt->dts = sample->timestamp;
3062 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3063 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3064 /* update ctts context */
3066 if (sc->ctts_index < sc->ctts_count &&
3067 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3069 sc->ctts_sample = 0;
3072 pkt->dts = AV_NOPTS_VALUE;
3074 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3075 st->index_entries[sc->current_sample].timestamp : st->duration;
3076 pkt->duration = next_dts - pkt->dts;
3077 pkt->pts = pkt->dts;
3079 if (st->discard == AVDISCARD_ALL)
3081 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3082 pkt->pos = sample->pos;
3083 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3084 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3088 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3090 MOVStreamContext *sc = st->priv_data;
3091 int sample, time_sample;
3094 sample = av_index_search_timestamp(st, timestamp, flags);
3095 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3096 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3098 if (sample < 0) /* not sure what to do */
3099 return AVERROR_INVALIDDATA;
3100 sc->current_sample = sample;
3101 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3102 /* adjust ctts index */
3103 if (sc->ctts_data) {
3105 for (i = 0; i < sc->ctts_count; i++) {
3106 int next = time_sample + sc->ctts_data[i].count;
3107 if (next > sc->current_sample) {
3109 sc->ctts_sample = sc->current_sample - time_sample;
3118 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3121 int64_t seek_timestamp, timestamp;
3125 if (stream_index >= s->nb_streams)
3126 return AVERROR_INVALIDDATA;
3127 if (sample_time < 0)
3130 st = s->streams[stream_index];
3131 sample = mov_seek_stream(s, st, sample_time, flags);
3135 /* adjust seek timestamp to found sample timestamp */
3136 seek_timestamp = st->index_entries[sample].timestamp;
3138 for (i = 0; i < s->nb_streams; i++) {
3140 if (stream_index == i)
3143 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3144 mov_seek_stream(s, st, timestamp, flags);
3149 static const AVOption options[] = {
3150 {"use_absolute_path",
3151 "allow using absolute path when opening alias, this is a possible security issue",
3152 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.dbl = 0},
3153 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3157 static const AVClass class = {
3158 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3159 .item_name = av_default_item_name,
3161 .version = LIBAVUTIL_VERSION_INT,
3164 AVInputFormat ff_mov_demuxer = {
3165 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3166 .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
3167 .priv_data_size = sizeof(MOVContext),
3168 .read_probe = mov_probe,
3169 .read_header = mov_read_header,
3170 .read_packet = mov_read_packet,
3171 .read_close = mov_read_close,
3172 .read_seek = mov_read_seek,
3173 .priv_class = &class,