3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 //#define MOV_EXPORT_ALL_METADATA
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/intfloat.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/dict.h"
35 #include "avio_internal.h"
38 #include "libavcodec/get_bits.h"
47 * First version by Francois Revol revol@free.fr
48 * Seek function by Gael Chardon gael.dev@4now.net
51 #include "qtpalette.h"
57 /* those functions parse an atom */
58 /* links atom IDs to parse functions */
59 typedef struct MOVParseTableEntry {
61 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
64 static const MOVParseTableEntry mov_default_parse_table[];
66 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
67 unsigned len, const char *key)
71 short current, total = 0;
72 avio_rb16(pb); // unknown
73 current = avio_rb16(pb);
75 total = avio_rb16(pb);
77 snprintf(buf, sizeof(buf), "%d", current);
79 snprintf(buf, sizeof(buf), "%d/%d", current, total);
80 av_dict_set(&c->fc->metadata, key, buf, 0);
85 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
86 unsigned len, const char *key)
90 /* bypass padding bytes */
95 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
96 av_dict_set(&c->fc->metadata, key, buf, 0);
101 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
102 unsigned len, const char *key)
106 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
107 av_dict_set(&c->fc->metadata, key, buf, 0);
112 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
113 unsigned len, const char *key)
118 avio_r8(pb); // unknown
121 if (genre < 1 || genre > ID3v1_GENRE_MAX)
123 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
124 av_dict_set(&c->fc->metadata, key, buf, 0);
129 static const uint32_t mac_to_unicode[128] = {
130 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
131 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
132 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
133 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
134 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
135 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
136 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
137 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
138 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
139 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
140 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
141 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
142 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
143 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
144 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
145 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
148 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
149 char *dst, int dstlen)
152 char *end = dst+dstlen-1;
155 for (i = 0; i < len; i++) {
156 uint8_t t, c = avio_r8(pb);
157 if (c < 0x80 && p < end)
160 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
166 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
168 #ifdef MOV_EXPORT_ALL_METADATA
171 char str[1024], key2[16], language[4] = {0};
172 const char *key = NULL;
173 uint16_t str_size, langcode = 0;
174 uint32_t data_type = 0;
175 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
178 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
179 case MKTAG(0xa9,'a','u','t'):
180 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
181 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
182 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
183 case MKTAG( 'c','p','r','t'):
184 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
185 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
186 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
187 case MKTAG(0xa9,'c','m','t'):
188 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
189 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
190 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
191 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
192 case MKTAG( 'g','n','r','e'): key = "genre";
193 parse = mov_metadata_gnre; break;
194 case MKTAG(0xa9,'t','o','o'):
195 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
196 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
197 case MKTAG( 'd','e','s','c'): key = "description";break;
198 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
199 case MKTAG( 't','v','s','h'): key = "show"; break;
200 case MKTAG( 't','v','e','n'): key = "episode_id";break;
201 case MKTAG( 't','v','n','n'): key = "network"; break;
202 case MKTAG( 't','r','k','n'): key = "track";
203 parse = mov_metadata_track_or_disc_number; break;
204 case MKTAG( 'd','i','s','k'): key = "disc";
205 parse = mov_metadata_track_or_disc_number; break;
206 case MKTAG( 't','v','e','s'): key = "episode_sort";
207 parse = mov_metadata_int8_bypass_padding; break;
208 case MKTAG( 't','v','s','n'): key = "season_number";
209 parse = mov_metadata_int8_bypass_padding; break;
210 case MKTAG( 's','t','i','k'): key = "media_type";
211 parse = mov_metadata_int8_no_padding; break;
212 case MKTAG( 'h','d','v','d'): key = "hd_video";
213 parse = mov_metadata_int8_no_padding; break;
214 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
215 parse = mov_metadata_int8_no_padding; break;
218 if (c->itunes_metadata && atom.size > 8) {
219 int data_size = avio_rb32(pb);
220 int tag = avio_rl32(pb);
221 if (tag == MKTAG('d','a','t','a')) {
222 data_type = avio_rb32(pb); // type
223 avio_rb32(pb); // unknown
224 str_size = data_size - 16;
227 } else if (atom.size > 4 && key && !c->itunes_metadata) {
228 str_size = avio_rb16(pb); // string length
229 langcode = avio_rb16(pb);
230 ff_mov_lang_to_iso639(langcode, language);
233 str_size = atom.size;
235 #ifdef MOV_EXPORT_ALL_METADATA
237 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
247 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
250 parse(c, pb, str_size, key);
252 if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
253 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
255 avio_read(pb, str, str_size);
258 av_dict_set(&c->fc->metadata, key, str, 0);
259 if (*language && strcmp(language, "und")) {
260 snprintf(key2, sizeof(key2), "%s-%s", key, language);
261 av_dict_set(&c->fc->metadata, key2, str, 0);
264 av_dlog(c->fc, "lang \"%3s\" ", language);
265 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
266 key, str, (char*)&atom.type, str_size, atom.size);
271 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
274 int i, nb_chapters, str_len, version;
277 if ((atom.size -= 5) < 0)
280 version = avio_r8(pb);
283 avio_rb32(pb); // ???
284 nb_chapters = avio_r8(pb);
286 for (i = 0; i < nb_chapters; i++) {
290 start = avio_rb64(pb);
291 str_len = avio_r8(pb);
293 if ((atom.size -= 9+str_len) < 0)
296 avio_read(pb, str, str_len);
298 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
303 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
305 int64_t total_size = 0;
310 atom.size = INT64_MAX;
311 while (total_size + 8 <= atom.size && !url_feof(pb)) {
312 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
315 if (atom.size >= 8) {
316 a.size = avio_rb32(pb);
317 a.type = avio_rl32(pb);
319 if (a.size == 1) { /* 64 bit extended size */
320 a.size = avio_rb64(pb) - 8;
324 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
325 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
327 a.size = atom.size - total_size + 8;
332 a.size = FFMIN(a.size, atom.size - total_size);
334 for (i = 0; mov_default_parse_table[i].type; i++)
335 if (mov_default_parse_table[i].type == a.type) {
336 parse = mov_default_parse_table[i].parse;
340 // container is user data
341 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
342 atom.type == MKTAG('i','l','s','t')))
343 parse = mov_read_udta_string;
345 if (!parse) { /* skip leaf atoms data */
346 avio_skip(pb, a.size);
348 int64_t start_pos = avio_tell(pb);
350 int err = parse(c, pb, a);
353 if (c->found_moov && c->found_mdat &&
354 (!pb->seekable || start_pos + a.size == avio_size(pb)))
356 left = a.size - avio_tell(pb) + start_pos;
357 if (left > 0) /* skip garbage at atom end */
361 total_size += a.size;
364 if (total_size < atom.size && atom.size < 0x7ffff)
365 avio_skip(pb, atom.size - total_size);
370 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
373 MOVStreamContext *sc;
376 if (c->fc->nb_streams < 1)
378 st = c->fc->streams[c->fc->nb_streams-1];
381 avio_rb32(pb); // version + flags
382 entries = avio_rb32(pb);
383 if (entries >= UINT_MAX / sizeof(*sc->drefs))
385 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
387 return AVERROR(ENOMEM);
388 sc->drefs_count = entries;
390 for (i = 0; i < sc->drefs_count; i++) {
391 MOVDref *dref = &sc->drefs[i];
392 uint32_t size = avio_rb32(pb);
393 int64_t next = avio_tell(pb) + size - 4;
398 dref->type = avio_rl32(pb);
399 avio_rb32(pb); // version + flags
400 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
402 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
403 /* macintosh alias record */
404 uint16_t volume_len, len;
409 volume_len = avio_r8(pb);
410 volume_len = FFMIN(volume_len, 27);
411 avio_read(pb, dref->volume, 27);
412 dref->volume[volume_len] = 0;
413 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
418 len = FFMIN(len, 63);
419 avio_read(pb, dref->filename, 63);
420 dref->filename[len] = 0;
421 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
425 /* read next level up_from_alias/down_to_target */
426 dref->nlvl_from = avio_rb16(pb);
427 dref->nlvl_to = avio_rb16(pb);
428 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
429 dref->nlvl_from, dref->nlvl_to);
433 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
436 type = avio_rb16(pb);
438 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
441 if (type == 2) { // absolute path
443 dref->path = av_mallocz(len+1);
445 return AVERROR(ENOMEM);
446 avio_read(pb, dref->path, len);
447 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
449 memmove(dref->path, dref->path+volume_len, len);
452 for (j = 0; j < len; j++)
453 if (dref->path[j] == ':')
455 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
456 } else if (type == 0) { // directory name
458 dref->dir = av_malloc(len+1);
460 return AVERROR(ENOMEM);
461 avio_read(pb, dref->dir, len);
463 for (j = 0; j < len; j++)
464 if (dref->dir[j] == ':')
466 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
471 avio_seek(pb, next, SEEK_SET);
476 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
480 uint32_t av_unused ctype;
484 if (c->fc->nb_streams < 1) // meta before first trak
487 st = c->fc->streams[c->fc->nb_streams-1];
489 avio_r8(pb); /* version */
490 avio_rb24(pb); /* flags */
493 ctype = avio_rl32(pb);
494 type = avio_rl32(pb); /* component subtype */
496 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
497 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
499 if (type == MKTAG('v','i','d','e'))
500 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
501 else if (type == MKTAG('s','o','u','n'))
502 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
503 else if (type == MKTAG('m','1','a',' '))
504 st->codec->codec_id = CODEC_ID_MP2;
505 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
506 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
508 avio_rb32(pb); /* component manufacture */
509 avio_rb32(pb); /* component flags */
510 avio_rb32(pb); /* component flags mask */
512 title_size = atom.size - 24;
513 if (title_size > 0) {
514 title_str = av_malloc(title_size + 1); /* Add null terminator */
516 return AVERROR(ENOMEM);
517 avio_read(pb, title_str, title_size);
518 title_str[title_size] = 0;
519 av_dict_set(&st->metadata, "handler_name", title_str, 0);
520 av_freep(&title_str);
526 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
531 if (fc->nb_streams < 1)
533 st = fc->streams[fc->nb_streams-1];
535 avio_rb32(pb); /* version + flags */
536 ff_mp4_read_descr(fc, pb, &tag);
537 if (tag == MP4ESDescrTag) {
538 ff_mp4_parse_es_descr(pb, NULL);
540 avio_rb16(pb); /* ID */
542 ff_mp4_read_descr(fc, pb, &tag);
543 if (tag == MP4DecConfigDescrTag)
544 ff_mp4_read_dec_config_descr(fc, st, pb);
548 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
550 return ff_mov_read_esds(c->fc, pb, atom);
553 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
556 int ac3info, acmod, lfeon, bsmod;
558 if (c->fc->nb_streams < 1)
560 st = c->fc->streams[c->fc->nb_streams-1];
562 ac3info = avio_rb24(pb);
563 bsmod = (ac3info >> 14) & 0x7;
564 acmod = (ac3info >> 11) & 0x7;
565 lfeon = (ac3info >> 10) & 0x1;
566 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
567 st->codec->audio_service_type = bsmod;
568 if (st->codec->channels > 1 && bsmod == 0x7)
569 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
574 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
578 uint32_t flags, layout_tag, bitmap, num_descr;
580 if (c->fc->nb_streams < 1)
582 st = c->fc->streams[c->fc->nb_streams-1];
587 version = avio_r8(pb);
588 flags = avio_rb24(pb);
590 layout_tag = avio_rb32(pb);
591 bitmap = avio_rb32(pb);
592 num_descr = avio_rb32(pb);
594 if (atom.size < 16ULL + num_descr * 20ULL)
597 av_dlog(c->fc, "chan: size=%ld version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
598 atom.size, version, flags, layout_tag, bitmap, num_descr);
601 /* TODO: use the channel descriptions if the layout tag is 0 */
603 for (i = 0; i < num_descr; i++) {
604 uint32_t label, cflags;
606 label = avio_rb32(pb); // mChannelLabel
607 cflags = avio_rb32(pb); // mChannelFlags
608 AV_WN32(&coords[0], avio_rl32(pb)); // mCoordinates[0]
609 AV_WN32(&coords[1], avio_rl32(pb)); // mCoordinates[1]
610 AV_WN32(&coords[2], avio_rl32(pb)); // mCoordinates[2]
614 st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
619 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
623 if (c->fc->nb_streams < 1)
625 st = c->fc->streams[c->fc->nb_streams-1];
627 ff_get_wav_header(pb, st->codec, atom.size);
632 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
634 const int num = avio_rb32(pb);
635 const int den = avio_rb32(pb);
638 if (c->fc->nb_streams < 1)
640 st = c->fc->streams[c->fc->nb_streams-1];
642 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
643 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
644 av_log(c->fc, AV_LOG_WARNING,
645 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
646 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
648 } else if (den != 0) {
649 st->sample_aspect_ratio.num = num;
650 st->sample_aspect_ratio.den = den;
655 /* this atom contains actual media data */
656 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
658 if (atom.size == 0) /* wrong one (MP4) */
661 return 0; /* now go for moov */
664 /* read major brand, minor version and compatible brands and store them as metadata */
665 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
669 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
670 char* comp_brands_str;
671 uint8_t type[5] = {0};
673 avio_read(pb, type, 4);
674 if (strcmp(type, "qt "))
676 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
677 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
678 minor_ver = avio_rb32(pb); /* minor version */
679 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
680 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
682 comp_brand_size = atom.size - 8;
683 if (comp_brand_size < 0)
685 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
686 if (!comp_brands_str)
687 return AVERROR(ENOMEM);
688 avio_read(pb, comp_brands_str, comp_brand_size);
689 comp_brands_str[comp_brand_size] = 0;
690 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
691 av_freep(&comp_brands_str);
696 /* this atom should contain all header atoms */
697 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
699 if (mov_read_default(c, pb, atom) < 0)
701 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
702 /* so we don't parse the whole file if over a network */
704 return 0; /* now go for mdat */
707 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
709 c->fragment.moof_offset = avio_tell(pb) - 8;
710 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
711 return mov_read_default(c, pb, atom);
714 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
719 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
722 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
723 av_dict_set(metadata, "creation_time", buffer, 0);
727 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
730 MOVStreamContext *sc;
732 char language[4] = {0};
734 time_t creation_time;
736 if (c->fc->nb_streams < 1)
738 st = c->fc->streams[c->fc->nb_streams-1];
741 version = avio_r8(pb);
743 return -1; /* unsupported */
745 avio_rb24(pb); /* flags */
747 creation_time = avio_rb64(pb);
750 creation_time = avio_rb32(pb);
751 avio_rb32(pb); /* modification time */
753 mov_metadata_creation_time(&st->metadata, creation_time);
755 sc->time_scale = avio_rb32(pb);
756 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
758 lang = avio_rb16(pb); /* language */
759 if (ff_mov_lang_to_iso639(lang, language))
760 av_dict_set(&st->metadata, "language", language, 0);
761 avio_rb16(pb); /* quality */
766 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
768 time_t creation_time;
769 int version = avio_r8(pb); /* version */
770 avio_rb24(pb); /* flags */
773 creation_time = avio_rb64(pb);
776 creation_time = avio_rb32(pb);
777 avio_rb32(pb); /* modification time */
779 mov_metadata_creation_time(&c->fc->metadata, creation_time);
780 c->time_scale = avio_rb32(pb); /* time scale */
782 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
784 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
785 avio_rb32(pb); /* preferred scale */
787 avio_rb16(pb); /* preferred volume */
789 avio_skip(pb, 10); /* reserved */
791 avio_skip(pb, 36); /* display matrix */
793 avio_rb32(pb); /* preview time */
794 avio_rb32(pb); /* preview duration */
795 avio_rb32(pb); /* poster time */
796 avio_rb32(pb); /* selection time */
797 avio_rb32(pb); /* selection duration */
798 avio_rb32(pb); /* current time */
799 avio_rb32(pb); /* next track ID */
804 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
808 if (c->fc->nb_streams < 1)
810 st = c->fc->streams[c->fc->nb_streams-1];
812 if ((uint64_t)atom.size > (1<<30))
815 // currently SVQ3 decoder expect full STSD header - so let's fake it
816 // this should be fixed and just SMI header should be passed
817 av_free(st->codec->extradata);
818 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
819 if (!st->codec->extradata)
820 return AVERROR(ENOMEM);
821 st->codec->extradata_size = 0x5a + atom.size;
822 memcpy(st->codec->extradata, "SVQ3", 4); // fake
823 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
824 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
828 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
833 if (c->fc->nb_streams < 1)
835 st = c->fc->streams[c->fc->nb_streams-1];
837 little_endian = avio_rb16(pb) & 0xFF;
838 av_dlog(c->fc, "enda %d\n", little_endian);
839 if (little_endian == 1) {
840 switch (st->codec->codec_id) {
841 case CODEC_ID_PCM_S24BE:
842 st->codec->codec_id = CODEC_ID_PCM_S24LE;
844 case CODEC_ID_PCM_S32BE:
845 st->codec->codec_id = CODEC_ID_PCM_S32LE;
847 case CODEC_ID_PCM_F32BE:
848 st->codec->codec_id = CODEC_ID_PCM_F32LE;
850 case CODEC_ID_PCM_F64BE:
851 st->codec->codec_id = CODEC_ID_PCM_F64LE;
860 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
861 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
862 enum CodecID codec_id)
868 if (c->fc->nb_streams < 1) // will happen with jp2 files
870 st= c->fc->streams[c->fc->nb_streams-1];
872 if (st->codec->codec_id != codec_id)
873 return 0; /* unexpected codec_id - don't mess with extradata */
875 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
876 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
878 buf= av_realloc(st->codec->extradata, size);
881 st->codec->extradata= buf;
882 buf+= st->codec->extradata_size;
883 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
884 AV_WB32( buf , atom.size + 8);
885 AV_WL32( buf + 4, atom.type);
886 avio_read(pb, buf + 8, atom.size);
890 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
891 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
893 return mov_read_extradata(c, pb, atom, CODEC_ID_ALAC);
896 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
898 return mov_read_extradata(c, pb, atom, CODEC_ID_AVS);
901 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
903 return mov_read_extradata(c, pb, atom, CODEC_ID_MJPEG);
906 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
908 return mov_read_extradata(c, pb, atom, CODEC_ID_JPEG2000);
911 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
915 if (c->fc->nb_streams < 1)
917 st = c->fc->streams[c->fc->nb_streams-1];
919 if ((uint64_t)atom.size > (1<<30))
922 if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
923 // pass all frma atom to codec, needed at least for QDMC and QDM2
924 av_free(st->codec->extradata);
925 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
926 if (!st->codec->extradata)
927 return AVERROR(ENOMEM);
928 st->codec->extradata_size = atom.size;
929 avio_read(pb, st->codec->extradata, atom.size);
930 } else if (atom.size > 8) { /* to read frma, esds atoms */
931 if (mov_read_default(c, pb, atom) < 0)
934 avio_skip(pb, atom.size);
939 * This function reads atom content and puts data in extradata without tag
940 * nor size unlike mov_read_extradata.
942 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
946 if (c->fc->nb_streams < 1)
948 st = c->fc->streams[c->fc->nb_streams-1];
950 if ((uint64_t)atom.size > (1<<30))
953 av_free(st->codec->extradata);
954 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
955 if (!st->codec->extradata)
956 return AVERROR(ENOMEM);
957 st->codec->extradata_size = atom.size;
958 avio_read(pb, st->codec->extradata, atom.size);
963 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
964 * but can have extradata appended at the end after the 40 bytes belonging
967 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
971 if (c->fc->nb_streams < 1)
975 st = c->fc->streams[c->fc->nb_streams-1];
977 if ((uint64_t)atom.size > (1<<30))
980 av_free(st->codec->extradata);
981 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
982 if (!st->codec->extradata)
983 return AVERROR(ENOMEM);
984 st->codec->extradata_size = atom.size - 40;
986 avio_read(pb, st->codec->extradata, atom.size - 40);
990 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
993 MOVStreamContext *sc;
994 unsigned int i, entries;
996 if (c->fc->nb_streams < 1)
998 st = c->fc->streams[c->fc->nb_streams-1];
1001 avio_r8(pb); /* version */
1002 avio_rb24(pb); /* flags */
1004 entries = avio_rb32(pb);
1008 if (entries >= UINT_MAX/sizeof(int64_t))
1011 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1012 if (!sc->chunk_offsets)
1013 return AVERROR(ENOMEM);
1014 sc->chunk_count = entries;
1016 if (atom.type == MKTAG('s','t','c','o'))
1017 for (i=0; i<entries; i++)
1018 sc->chunk_offsets[i] = avio_rb32(pb);
1019 else if (atom.type == MKTAG('c','o','6','4'))
1020 for (i=0; i<entries; i++)
1021 sc->chunk_offsets[i] = avio_rb64(pb);
1029 * Compute codec id for 'lpcm' tag.
1030 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1032 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1034 if (flags & 1) { // floating point
1035 if (flags & 2) { // big endian
1036 if (bps == 32) return CODEC_ID_PCM_F32BE;
1037 else if (bps == 64) return CODEC_ID_PCM_F64BE;
1039 if (bps == 32) return CODEC_ID_PCM_F32LE;
1040 else if (bps == 64) return CODEC_ID_PCM_F64LE;
1046 if (flags & 4) return CODEC_ID_PCM_S8;
1047 else return CODEC_ID_PCM_U8;
1048 else if (bps == 16) return CODEC_ID_PCM_S16BE;
1049 else if (bps == 24) return CODEC_ID_PCM_S24BE;
1050 else if (bps == 32) return CODEC_ID_PCM_S32BE;
1053 if (flags & 4) return CODEC_ID_PCM_S8;
1054 else return CODEC_ID_PCM_U8;
1055 else if (bps == 16) return CODEC_ID_PCM_S16LE;
1056 else if (bps == 24) return CODEC_ID_PCM_S24LE;
1057 else if (bps == 32) return CODEC_ID_PCM_S32LE;
1060 return CODEC_ID_NONE;
1063 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1066 MOVStreamContext *sc;
1067 int j, pseudo_stream_id;
1069 if (c->fc->nb_streams < 1)
1071 st = c->fc->streams[c->fc->nb_streams-1];
1074 for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
1075 //Parsing Sample description table
1078 MOVAtom a = { AV_RL32("stsd") };
1079 int64_t start_pos = avio_tell(pb);
1080 int size = avio_rb32(pb); /* size */
1081 uint32_t format = avio_rl32(pb); /* data format */
1084 avio_rb32(pb); /* reserved */
1085 avio_rb16(pb); /* reserved */
1086 dref_id = avio_rb16(pb);
1087 }else if (size <= 0){
1088 av_log(c->fc, AV_LOG_ERROR, "invalid size %d in stsd\n", size);
1092 if (st->codec->codec_tag &&
1093 st->codec->codec_tag != format &&
1094 (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
1095 : st->codec->codec_tag != MKTAG('j','p','e','g'))
1097 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1098 * export it as a separate AVStream but this needs a few changes
1099 * in the MOV demuxer, patch welcome. */
1101 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1102 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1105 /* we cannot demux concatenated h264 streams because of different extradata */
1106 if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1108 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1109 sc->dref_id= dref_id;
1111 st->codec->codec_tag = format;
1112 id = ff_codec_get_id(codec_movaudio_tags, format);
1113 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1114 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1116 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1117 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1118 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1119 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1120 id = ff_codec_get_id(codec_movvideo_tags, format);
1122 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1124 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1125 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){
1126 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1128 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1132 av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1133 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1134 (format >> 24) & 0xff, st->codec->codec_type);
1136 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1137 unsigned int color_depth, len;
1138 int color_greyscale;
1140 st->codec->codec_id = id;
1141 avio_rb16(pb); /* version */
1142 avio_rb16(pb); /* revision level */
1143 avio_rb32(pb); /* vendor */
1144 avio_rb32(pb); /* temporal quality */
1145 avio_rb32(pb); /* spatial quality */
1147 st->codec->width = avio_rb16(pb); /* width */
1148 st->codec->height = avio_rb16(pb); /* height */
1150 avio_rb32(pb); /* horiz resolution */
1151 avio_rb32(pb); /* vert resolution */
1152 avio_rb32(pb); /* data size, always 0 */
1153 avio_rb16(pb); /* frames per samples */
1155 len = avio_r8(pb); /* codec name, pascal string */
1158 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1160 avio_skip(pb, 31 - len);
1161 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1162 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1163 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1165 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1166 st->codec->color_table_id = avio_rb16(pb); /* colortable id */
1167 av_dlog(c->fc, "depth %d, ctab id %d\n",
1168 st->codec->bits_per_coded_sample, st->codec->color_table_id);
1169 /* figure out the palette situation */
1170 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1171 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1173 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1174 if ((color_depth == 2) || (color_depth == 4) ||
1175 (color_depth == 8)) {
1176 /* for palette traversal */
1177 unsigned int color_start, color_count, color_end;
1178 unsigned char r, g, b;
1180 if (color_greyscale) {
1181 int color_index, color_dec;
1182 /* compute the greyscale palette */
1183 st->codec->bits_per_coded_sample = color_depth;
1184 color_count = 1 << color_depth;
1186 color_dec = 256 / (color_count - 1);
1187 for (j = 0; j < color_count; j++) {
1188 if (id == CODEC_ID_CINEPAK){
1189 r = g = b = color_count - 1 - color_index;
1191 r = g = b = color_index;
1193 (r << 16) | (g << 8) | (b);
1194 color_index -= color_dec;
1195 if (color_index < 0)
1198 } else if (st->codec->color_table_id) {
1199 const uint8_t *color_table;
1200 /* if flag bit 3 is set, use the default palette */
1201 color_count = 1 << color_depth;
1202 if (color_depth == 2)
1203 color_table = ff_qt_default_palette_4;
1204 else if (color_depth == 4)
1205 color_table = ff_qt_default_palette_16;
1207 color_table = ff_qt_default_palette_256;
1209 for (j = 0; j < color_count; j++) {
1210 r = color_table[j * 3 + 0];
1211 g = color_table[j * 3 + 1];
1212 b = color_table[j * 3 + 2];
1214 (r << 16) | (g << 8) | (b);
1217 /* load the palette from the file */
1218 color_start = avio_rb32(pb);
1219 color_count = avio_rb16(pb);
1220 color_end = avio_rb16(pb);
1221 if ((color_start <= 255) &&
1222 (color_end <= 255)) {
1223 for (j = color_start; j <= color_end; j++) {
1224 /* each R, G, or B component is 16 bits;
1225 * only use the top 8 bits; skip alpha bytes
1236 (r << 16) | (g << 8) | (b);
1240 sc->has_palette = 1;
1242 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1243 int bits_per_sample, flags;
1244 uint16_t version = avio_rb16(pb);
1246 st->codec->codec_id = id;
1247 avio_rb16(pb); /* revision level */
1248 avio_rb32(pb); /* vendor */
1250 st->codec->channels = avio_rb16(pb); /* channel count */
1251 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1252 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1254 sc->audio_cid = avio_rb16(pb);
1255 avio_rb16(pb); /* packet size = 0 */
1257 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1259 //Read QT version 1 fields. In version 0 these do not exist.
1260 av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1263 sc->samples_per_frame = avio_rb32(pb);
1264 avio_rb32(pb); /* bytes per packet */
1265 sc->bytes_per_frame = avio_rb32(pb);
1266 avio_rb32(pb); /* bytes per sample */
1267 } else if (version==2) {
1268 avio_rb32(pb); /* sizeof struct only */
1269 st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
1270 st->codec->channels = avio_rb32(pb);
1271 avio_rb32(pb); /* always 0x7F000000 */
1272 st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1273 flags = avio_rb32(pb); /* lpcm format specific flag */
1274 sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1275 sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1276 if (format == MKTAG('l','p','c','m'))
1277 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1281 switch (st->codec->codec_id) {
1282 case CODEC_ID_PCM_S8:
1283 case CODEC_ID_PCM_U8:
1284 if (st->codec->bits_per_coded_sample == 16)
1285 st->codec->codec_id = CODEC_ID_PCM_S16BE;
1287 case CODEC_ID_PCM_S16LE:
1288 case CODEC_ID_PCM_S16BE:
1289 if (st->codec->bits_per_coded_sample == 8)
1290 st->codec->codec_id = CODEC_ID_PCM_S8;
1291 else if (st->codec->bits_per_coded_sample == 24)
1292 st->codec->codec_id =
1293 st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1294 CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1296 /* set values for old format before stsd version 1 appeared */
1297 case CODEC_ID_MACE3:
1298 sc->samples_per_frame = 6;
1299 sc->bytes_per_frame = 2*st->codec->channels;
1301 case CODEC_ID_MACE6:
1302 sc->samples_per_frame = 6;
1303 sc->bytes_per_frame = 1*st->codec->channels;
1305 case CODEC_ID_ADPCM_IMA_QT:
1306 sc->samples_per_frame = 64;
1307 sc->bytes_per_frame = 34*st->codec->channels;
1310 sc->samples_per_frame = 160;
1311 sc->bytes_per_frame = 33;
1317 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1318 if (bits_per_sample) {
1319 st->codec->bits_per_coded_sample = bits_per_sample;
1320 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1322 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1323 // ttxt stsd contains display flags, justification, background
1324 // color, fonts, and default styles, so fake an atom to read it
1325 MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1326 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1327 mov_read_glbl(c, pb, fake_atom);
1328 st->codec->codec_id= id;
1329 st->codec->width = sc->width;
1330 st->codec->height = sc->height;
1332 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1334 avio_rb32(pb); /* reserved */
1335 val = avio_rb32(pb); /* flags */
1337 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1340 st->codec->time_base.den = avio_r8(pb);
1341 st->codec->time_base.num = 1;
1343 /* other codec type, just skip (rtp, mp4s, ...) */
1344 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1346 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1347 a.size = size - (avio_tell(pb) - start_pos);
1349 if (mov_read_default(c, pb, a) < 0)
1351 } else if (a.size > 0)
1352 avio_skip(pb, a.size);
1355 if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1356 st->codec->sample_rate= sc->time_scale;
1358 /* special codec parameters handling */
1359 switch (st->codec->codec_id) {
1360 #if CONFIG_DV_DEMUXER
1361 case CODEC_ID_DVAUDIO:
1362 c->dv_fctx = avformat_alloc_context();
1363 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1365 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1368 sc->dv_audio_container = 1;
1369 st->codec->codec_id = CODEC_ID_PCM_S16LE;
1372 /* no ifdef since parameters are always those */
1373 case CODEC_ID_QCELP:
1374 // force sample rate for qcelp when not stored in mov
1375 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1376 st->codec->sample_rate = 8000;
1377 st->codec->frame_size= 160;
1378 st->codec->channels= 1; /* really needed */
1380 case CODEC_ID_AMR_NB:
1381 st->codec->channels= 1; /* really needed */
1382 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1383 st->codec->sample_rate = 8000;
1384 /* force frame_size, too, samples_per_frame isn't always set properly */
1385 st->codec->frame_size = 160;
1387 case CODEC_ID_AMR_WB:
1388 st->codec->channels = 1;
1389 st->codec->sample_rate = 16000;
1390 st->codec->frame_size = 320;
1394 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1395 st->need_parsing = AVSTREAM_PARSE_FULL;
1398 case CODEC_ID_ADPCM_MS:
1399 case CODEC_ID_ADPCM_IMA_WAV:
1400 st->codec->frame_size = sc->samples_per_frame;
1401 st->codec->block_align = sc->bytes_per_frame;
1404 if (st->codec->extradata_size == 36) {
1405 st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1406 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1407 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1411 st->need_parsing = AVSTREAM_PARSE_FULL;
1413 case CODEC_ID_MPEG1VIDEO:
1414 st->need_parsing = AVSTREAM_PARSE_FULL;
1423 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1427 avio_r8(pb); /* version */
1428 avio_rb24(pb); /* flags */
1429 entries = avio_rb32(pb);
1431 return ff_mov_read_stsd_entries(c, pb, entries);
1434 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1437 MOVStreamContext *sc;
1438 unsigned int i, entries;
1440 if (c->fc->nb_streams < 1)
1442 st = c->fc->streams[c->fc->nb_streams-1];
1445 avio_r8(pb); /* version */
1446 avio_rb24(pb); /* flags */
1448 entries = avio_rb32(pb);
1450 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1454 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1456 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1458 return AVERROR(ENOMEM);
1459 sc->stsc_count = entries;
1461 for (i=0; i<entries; i++) {
1462 sc->stsc_data[i].first = avio_rb32(pb);
1463 sc->stsc_data[i].count = avio_rb32(pb);
1464 sc->stsc_data[i].id = avio_rb32(pb);
1469 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1472 MOVStreamContext *sc;
1473 unsigned i, entries;
1475 if (c->fc->nb_streams < 1)
1477 st = c->fc->streams[c->fc->nb_streams-1];
1480 avio_rb32(pb); // version + flags
1482 entries = avio_rb32(pb);
1483 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1485 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1487 return AVERROR(ENOMEM);
1488 sc->stps_count = entries;
1490 for (i = 0; i < entries; i++) {
1491 sc->stps_data[i] = avio_rb32(pb);
1492 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1498 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1501 MOVStreamContext *sc;
1502 unsigned int i, entries;
1504 if (c->fc->nb_streams < 1)
1506 st = c->fc->streams[c->fc->nb_streams-1];
1509 avio_r8(pb); /* version */
1510 avio_rb24(pb); /* flags */
1512 entries = avio_rb32(pb);
1514 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1516 if (entries >= UINT_MAX / sizeof(int))
1518 sc->keyframes = av_malloc(entries * sizeof(int));
1520 return AVERROR(ENOMEM);
1521 sc->keyframe_count = entries;
1523 for (i=0; i<entries; i++) {
1524 sc->keyframes[i] = avio_rb32(pb);
1525 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1530 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1533 MOVStreamContext *sc;
1534 unsigned int i, entries, sample_size, field_size, num_bytes;
1538 if (c->fc->nb_streams < 1)
1540 st = c->fc->streams[c->fc->nb_streams-1];
1543 avio_r8(pb); /* version */
1544 avio_rb24(pb); /* flags */
1546 if (atom.type == MKTAG('s','t','s','z')) {
1547 sample_size = avio_rb32(pb);
1548 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1549 sc->sample_size = sample_size;
1553 avio_rb24(pb); /* reserved */
1554 field_size = avio_r8(pb);
1556 entries = avio_rb32(pb);
1558 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1560 sc->sample_count = entries;
1564 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1565 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1571 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1573 sc->sample_sizes = av_malloc(entries * sizeof(int));
1574 if (!sc->sample_sizes)
1575 return AVERROR(ENOMEM);
1577 num_bytes = (entries*field_size+4)>>3;
1579 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1581 av_freep(&sc->sample_sizes);
1582 return AVERROR(ENOMEM);
1585 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1586 av_freep(&sc->sample_sizes);
1591 init_get_bits(&gb, buf, 8*num_bytes);
1593 for (i=0; i<entries; i++)
1594 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1600 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1603 MOVStreamContext *sc;
1604 unsigned int i, entries;
1606 int64_t total_sample_count=0;
1608 if (c->fc->nb_streams < 1)
1610 st = c->fc->streams[c->fc->nb_streams-1];
1613 avio_r8(pb); /* version */
1614 avio_rb24(pb); /* flags */
1615 entries = avio_rb32(pb);
1617 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1618 c->fc->nb_streams-1, entries);
1620 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1623 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1625 return AVERROR(ENOMEM);
1627 sc->stts_count = entries;
1629 for (i=0; i<entries; i++) {
1630 int sample_duration;
1633 sample_count=avio_rb32(pb);
1634 sample_duration = avio_rb32(pb);
1635 /* sample_duration < 0 is invalid based on the spec */
1636 if (sample_duration < 0) {
1637 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d", sample_duration);
1638 sample_duration = 1;
1640 sc->stts_data[i].count= sample_count;
1641 sc->stts_data[i].duration= sample_duration;
1643 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1644 sample_count, sample_duration);
1646 duration+=(int64_t)sample_duration*sample_count;
1647 total_sample_count+=sample_count;
1650 st->nb_frames= total_sample_count;
1652 st->duration= duration;
1656 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1659 MOVStreamContext *sc;
1660 unsigned int i, entries;
1662 if (c->fc->nb_streams < 1)
1664 st = c->fc->streams[c->fc->nb_streams-1];
1667 avio_r8(pb); /* version */
1668 avio_rb24(pb); /* flags */
1669 entries = avio_rb32(pb);
1671 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1675 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1677 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1679 return AVERROR(ENOMEM);
1680 sc->ctts_count = entries;
1682 for (i=0; i<entries; i++) {
1683 int count =avio_rb32(pb);
1684 int duration =avio_rb32(pb);
1686 sc->ctts_data[i].count = count;
1687 sc->ctts_data[i].duration= duration;
1688 if (duration < 0 && i+2<entries)
1689 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1692 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1697 static void mov_build_index(MOVContext *mov, AVStream *st)
1699 MOVStreamContext *sc = st->priv_data;
1700 int64_t current_offset;
1701 int64_t current_dts = 0;
1702 unsigned int stts_index = 0;
1703 unsigned int stsc_index = 0;
1704 unsigned int stss_index = 0;
1705 unsigned int stps_index = 0;
1707 uint64_t stream_size = 0;
1709 /* adjust first dts according to edit list */
1710 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
1711 if (sc->empty_duration)
1712 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
1713 sc->time_offset = sc->start_time - sc->empty_duration;
1714 current_dts = -sc->time_offset;
1715 if (sc->ctts_data && sc->stts_data &&
1716 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1717 /* more than 16 frames delay, dts are likely wrong
1718 this happens with files created by iMovie */
1720 st->codec->has_b_frames = 1;
1724 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1725 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1726 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1727 unsigned int current_sample = 0;
1728 unsigned int stts_sample = 0;
1729 unsigned int sample_size;
1730 unsigned int distance = 0;
1731 int key_off = sc->keyframes && sc->keyframes[0] == 1;
1733 current_dts -= sc->dts_shift;
1735 if (!sc->sample_count)
1737 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
1739 st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
1740 if (!st->index_entries)
1742 st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
1744 for (i = 0; i < sc->chunk_count; i++) {
1745 current_offset = sc->chunk_offsets[i];
1746 while (stsc_index + 1 < sc->stsc_count &&
1747 i + 1 == sc->stsc_data[stsc_index + 1].first)
1749 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1751 if (current_sample >= sc->sample_count) {
1752 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1756 if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1758 if (stss_index + 1 < sc->keyframe_count)
1760 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1762 if (stps_index + 1 < sc->stps_count)
1767 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1768 if (sc->pseudo_stream_id == -1 ||
1769 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1770 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1771 e->pos = current_offset;
1772 e->timestamp = current_dts;
1773 e->size = sample_size;
1774 e->min_distance = distance;
1775 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1776 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1777 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1778 current_offset, current_dts, sample_size, distance, keyframe);
1781 current_offset += sample_size;
1782 stream_size += sample_size;
1783 current_dts += sc->stts_data[stts_index].duration;
1787 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1793 if (st->duration > 0)
1794 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1796 unsigned chunk_samples, total = 0;
1798 // compute total chunk count
1799 for (i = 0; i < sc->stsc_count; i++) {
1800 unsigned count, chunk_count;
1802 chunk_samples = sc->stsc_data[i].count;
1803 if (i != sc->stsc_count - 1 &&
1804 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1805 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1809 if (sc->samples_per_frame >= 160) { // gsm
1810 count = chunk_samples / sc->samples_per_frame;
1811 } else if (sc->samples_per_frame > 1) {
1812 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1813 count = (chunk_samples+samples-1) / samples;
1815 count = (chunk_samples+1023) / 1024;
1818 if (i < sc->stsc_count - 1)
1819 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1821 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1822 total += chunk_count * count;
1825 av_dlog(mov->fc, "chunk count %d\n", total);
1826 if (total >= UINT_MAX / sizeof(*st->index_entries))
1828 st->index_entries = av_malloc(total*sizeof(*st->index_entries));
1829 if (!st->index_entries)
1831 st->index_entries_allocated_size = total*sizeof(*st->index_entries);
1834 for (i = 0; i < sc->chunk_count; i++) {
1835 current_offset = sc->chunk_offsets[i];
1836 if (stsc_index + 1 < sc->stsc_count &&
1837 i + 1 == sc->stsc_data[stsc_index + 1].first)
1839 chunk_samples = sc->stsc_data[stsc_index].count;
1841 while (chunk_samples > 0) {
1843 unsigned size, samples;
1845 if (sc->samples_per_frame >= 160) { // gsm
1846 samples = sc->samples_per_frame;
1847 size = sc->bytes_per_frame;
1849 if (sc->samples_per_frame > 1) {
1850 samples = FFMIN((1024 / sc->samples_per_frame)*
1851 sc->samples_per_frame, chunk_samples);
1852 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1854 samples = FFMIN(1024, chunk_samples);
1855 size = samples * sc->sample_size;
1859 if (st->nb_index_entries >= total) {
1860 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1863 e = &st->index_entries[st->nb_index_entries++];
1864 e->pos = current_offset;
1865 e->timestamp = current_dts;
1867 e->min_distance = 0;
1868 e->flags = AVINDEX_KEYFRAME;
1869 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1870 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1873 current_offset += size;
1874 current_dts += samples;
1875 chunk_samples -= samples;
1881 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
1882 AVIOInterruptCB *int_cb)
1884 /* try relative path, we do not try the absolute because it can leak information about our
1885 system to an attacker */
1886 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1887 char filename[1024];
1888 const char *src_path;
1891 /* find a source dir */
1892 src_path = strrchr(src, '/');
1898 /* find a next level down to target */
1899 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1900 if (ref->path[l] == '/') {
1901 if (i == ref->nlvl_to - 1)
1907 /* compose filename if next level down to target was found */
1908 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
1909 memcpy(filename, src, src_path - src);
1910 filename[src_path - src] = 0;
1912 for (i = 1; i < ref->nlvl_from; i++)
1913 av_strlcat(filename, "../", 1024);
1915 av_strlcat(filename, ref->path + l + 1, 1024);
1917 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
1922 return AVERROR(ENOENT);
1925 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1928 MOVStreamContext *sc;
1931 st = avformat_new_stream(c->fc, NULL);
1932 if (!st) return AVERROR(ENOMEM);
1933 st->id = c->fc->nb_streams;
1934 sc = av_mallocz(sizeof(MOVStreamContext));
1935 if (!sc) return AVERROR(ENOMEM);
1938 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1939 sc->ffindex = st->index;
1941 if ((ret = mov_read_default(c, pb, atom)) < 0)
1945 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1946 (!sc->sample_size && !sc->sample_count))) {
1947 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1952 if (sc->time_scale <= 0) {
1953 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
1954 sc->time_scale = c->time_scale;
1955 if (sc->time_scale <= 0)
1959 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
1961 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1962 !st->codec->frame_size && sc->stts_count == 1) {
1963 st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
1964 st->codec->sample_rate, sc->time_scale);
1965 av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
1968 mov_build_index(c, st);
1970 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1971 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
1972 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
1973 av_log(c->fc, AV_LOG_ERROR,
1974 "stream %d, error opening alias: path='%s', dir='%s', "
1975 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
1976 st->index, dref->path, dref->dir, dref->filename,
1977 dref->volume, dref->nlvl_from, dref->nlvl_to);
1981 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1982 if (!st->sample_aspect_ratio.num &&
1983 (st->codec->width != sc->width || st->codec->height != sc->height)) {
1984 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
1985 ((double)st->codec->width * sc->height), INT_MAX);
1988 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1989 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
1991 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
1992 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
1993 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
1996 switch (st->codec->codec_id) {
1997 #if CONFIG_H261_DECODER
2000 #if CONFIG_H263_DECODER
2003 #if CONFIG_H264_DECODER
2006 #if CONFIG_MPEG4_DECODER
2007 case CODEC_ID_MPEG4:
2009 st->codec->width = 0; /* let decoder init width/height */
2010 st->codec->height= 0;
2014 /* Do not need those anymore. */
2015 av_freep(&sc->chunk_offsets);
2016 av_freep(&sc->stsc_data);
2017 av_freep(&sc->sample_sizes);
2018 av_freep(&sc->keyframes);
2019 av_freep(&sc->stts_data);
2020 av_freep(&sc->stps_data);
2025 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2028 c->itunes_metadata = 1;
2029 ret = mov_read_default(c, pb, atom);
2030 c->itunes_metadata = 0;
2034 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2036 while (atom.size > 8) {
2037 uint32_t tag = avio_rl32(pb);
2039 if (tag == MKTAG('h','d','l','r')) {
2040 avio_seek(pb, -8, SEEK_CUR);
2042 return mov_read_default(c, pb, atom);
2048 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2053 int64_t disp_transform[2];
2054 int display_matrix[3][2];
2056 MOVStreamContext *sc;
2059 if (c->fc->nb_streams < 1)
2061 st = c->fc->streams[c->fc->nb_streams-1];
2064 version = avio_r8(pb);
2065 avio_rb24(pb); /* flags */
2067 MOV_TRACK_ENABLED 0x0001
2068 MOV_TRACK_IN_MOVIE 0x0002
2069 MOV_TRACK_IN_PREVIEW 0x0004
2070 MOV_TRACK_IN_POSTER 0x0008
2077 avio_rb32(pb); /* creation time */
2078 avio_rb32(pb); /* modification time */
2080 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2081 avio_rb32(pb); /* reserved */
2083 /* highlevel (considering edits) duration in movie timebase */
2084 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2085 avio_rb32(pb); /* reserved */
2086 avio_rb32(pb); /* reserved */
2088 avio_rb16(pb); /* layer */
2089 avio_rb16(pb); /* alternate group */
2090 avio_rb16(pb); /* volume */
2091 avio_rb16(pb); /* reserved */
2093 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2094 // they're kept in fixed point format through all calculations
2095 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2096 for (i = 0; i < 3; i++) {
2097 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2098 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2099 avio_rb32(pb); // 2.30 fixed point (not used)
2102 width = avio_rb32(pb); // 16.16 fixed point track width
2103 height = avio_rb32(pb); // 16.16 fixed point track height
2104 sc->width = width >> 16;
2105 sc->height = height >> 16;
2107 if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2108 av_dict_set(&st->metadata, "rotate", "180", 0);
2111 // transform the display width/height according to the matrix
2112 // skip this if the display matrix is the default identity matrix
2113 // or if it is rotating the picture, ex iPhone 3GS
2114 // to keep the same scale, use [width height 1<<16]
2115 if (width && height &&
2116 ((display_matrix[0][0] != 65536 ||
2117 display_matrix[1][1] != 65536) &&
2118 !display_matrix[0][1] &&
2119 !display_matrix[1][0] &&
2120 !display_matrix[2][0] && !display_matrix[2][1])) {
2121 for (i = 0; i < 2; i++)
2123 (int64_t) width * display_matrix[0][i] +
2124 (int64_t) height * display_matrix[1][i] +
2125 ((int64_t) display_matrix[2][i] << 16);
2127 //sample aspect ratio is new width/height divided by old width/height
2128 st->sample_aspect_ratio = av_d2q(
2129 ((double) disp_transform[0] * height) /
2130 ((double) disp_transform[1] * width), INT_MAX);
2135 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2137 MOVFragment *frag = &c->fragment;
2138 MOVTrackExt *trex = NULL;
2139 int flags, track_id, i;
2141 avio_r8(pb); /* version */
2142 flags = avio_rb24(pb);
2144 track_id = avio_rb32(pb);
2147 frag->track_id = track_id;
2148 for (i = 0; i < c->trex_count; i++)
2149 if (c->trex_data[i].track_id == frag->track_id) {
2150 trex = &c->trex_data[i];
2154 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2158 if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
2159 else frag->base_data_offset = frag->moof_offset;
2160 if (flags & 0x02) frag->stsd_id = avio_rb32(pb);
2161 else frag->stsd_id = trex->stsd_id;
2163 frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
2164 frag->size = flags & 0x10 ? avio_rb32(pb) : trex->size;
2165 frag->flags = flags & 0x20 ? avio_rb32(pb) : trex->flags;
2166 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2170 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2172 c->chapter_track = avio_rb32(pb);
2176 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2180 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2182 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2184 return AVERROR(ENOMEM);
2185 c->trex_data = trex;
2186 trex = &c->trex_data[c->trex_count++];
2187 avio_r8(pb); /* version */
2188 avio_rb24(pb); /* flags */
2189 trex->track_id = avio_rb32(pb);
2190 trex->stsd_id = avio_rb32(pb);
2191 trex->duration = avio_rb32(pb);
2192 trex->size = avio_rb32(pb);
2193 trex->flags = avio_rb32(pb);
2197 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2199 MOVFragment *frag = &c->fragment;
2200 AVStream *st = NULL;
2201 MOVStreamContext *sc;
2205 int data_offset = 0;
2206 unsigned entries, first_sample_flags = frag->flags;
2207 int flags, distance, i;
2209 for (i = 0; i < c->fc->nb_streams; i++) {
2210 if (c->fc->streams[i]->id == frag->track_id) {
2211 st = c->fc->streams[i];
2216 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2220 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2222 avio_r8(pb); /* version */
2223 flags = avio_rb24(pb);
2224 entries = avio_rb32(pb);
2225 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2227 /* Always assume the presence of composition time offsets.
2228 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2229 * 1) in the initial movie, there are no samples.
2230 * 2) in the first movie fragment, there is only one sample without composition time offset.
2231 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2232 if (!sc->ctts_count && sc->sample_count)
2234 /* Complement ctts table if moov atom doesn't have ctts atom. */
2235 ctts_data = av_malloc(sizeof(*sc->ctts_data));
2237 return AVERROR(ENOMEM);
2238 sc->ctts_data = ctts_data;
2239 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2240 sc->ctts_data[sc->ctts_count].duration = 0;
2243 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2245 ctts_data = av_realloc(sc->ctts_data,
2246 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2248 return AVERROR(ENOMEM);
2249 sc->ctts_data = ctts_data;
2251 if (flags & 0x001) data_offset = avio_rb32(pb);
2252 if (flags & 0x004) first_sample_flags = avio_rb32(pb);
2253 dts = st->duration - sc->time_offset;
2254 offset = frag->base_data_offset + data_offset;
2256 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2257 for (i = 0; i < entries; i++) {
2258 unsigned sample_size = frag->size;
2259 int sample_flags = i ? frag->flags : first_sample_flags;
2260 unsigned sample_duration = frag->duration;
2263 if (flags & 0x100) sample_duration = avio_rb32(pb);
2264 if (flags & 0x200) sample_size = avio_rb32(pb);
2265 if (flags & 0x400) sample_flags = avio_rb32(pb);
2266 sc->ctts_data[sc->ctts_count].count = 1;
2267 sc->ctts_data[sc->ctts_count].duration = (flags & 0x800) ? avio_rb32(pb) : 0;
2269 if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
2270 (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
2272 av_add_index_entry(st, offset, dts, sample_size, distance,
2273 keyframe ? AVINDEX_KEYFRAME : 0);
2274 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2275 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2276 offset, dts, sample_size, distance, keyframe);
2278 dts += sample_duration;
2279 offset += sample_size;
2281 frag->moof_offset = offset;
2282 st->duration = dts + sc->time_offset;
2286 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2287 /* like the files created with Adobe Premiere 5.0, for samples see */
2288 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2289 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2294 return 0; /* continue */
2295 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2296 avio_skip(pb, atom.size - 4);
2299 atom.type = avio_rl32(pb);
2301 if (atom.type != MKTAG('m','d','a','t')) {
2302 avio_skip(pb, atom.size);
2305 err = mov_read_mdat(c, pb, atom);
2309 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2314 uint8_t *moov_data; /* uncompressed data */
2315 long cmov_len, moov_len;
2318 avio_rb32(pb); /* dcom atom */
2319 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2321 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2322 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2325 avio_rb32(pb); /* cmvd atom */
2326 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2328 moov_len = avio_rb32(pb); /* uncompressed size */
2329 cmov_len = atom.size - 6 * 4;
2331 cmov_data = av_malloc(cmov_len);
2333 return AVERROR(ENOMEM);
2334 moov_data = av_malloc(moov_len);
2337 return AVERROR(ENOMEM);
2339 avio_read(pb, cmov_data, cmov_len);
2340 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2341 goto free_and_return;
2342 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2343 goto free_and_return;
2344 atom.type = MKTAG('m','o','o','v');
2345 atom.size = moov_len;
2346 ret = mov_read_default(c, &ctx, atom);
2352 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2357 /* edit list atom */
2358 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2360 MOVStreamContext *sc;
2361 int i, edit_count, version, edit_start_index = 0;
2363 if (c->fc->nb_streams < 1)
2365 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2367 version = avio_r8(pb); /* version */
2368 avio_rb24(pb); /* flags */
2369 edit_count = avio_rb32(pb); /* entries */
2371 if ((uint64_t)edit_count*12+8 > atom.size)
2374 for (i=0; i<edit_count; i++){
2378 duration = avio_rb64(pb);
2379 time = avio_rb64(pb);
2381 duration = avio_rb32(pb); /* segment duration */
2382 time = (int32_t)avio_rb32(pb); /* media time */
2384 avio_rb32(pb); /* Media rate */
2385 if (i == 0 && time == -1) {
2386 sc->empty_duration = duration;
2387 edit_start_index = 1;
2388 } else if (i == edit_start_index && time >= 0)
2389 sc->start_time = time;
2393 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2394 "a/v desync might occur, patch welcome\n");
2396 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2400 static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2405 ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
2409 static const MOVParseTableEntry mov_default_parse_table[] = {
2410 { MKTAG('a','v','s','s'), mov_read_avss },
2411 { MKTAG('c','h','p','l'), mov_read_chpl },
2412 { MKTAG('c','o','6','4'), mov_read_stco },
2413 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2414 { MKTAG('d','i','n','f'), mov_read_default },
2415 { MKTAG('d','r','e','f'), mov_read_dref },
2416 { MKTAG('e','d','t','s'), mov_read_default },
2417 { MKTAG('e','l','s','t'), mov_read_elst },
2418 { MKTAG('e','n','d','a'), mov_read_enda },
2419 { MKTAG('f','i','e','l'), mov_read_fiel },
2420 { MKTAG('f','t','y','p'), mov_read_ftyp },
2421 { MKTAG('g','l','b','l'), mov_read_glbl },
2422 { MKTAG('h','d','l','r'), mov_read_hdlr },
2423 { MKTAG('i','l','s','t'), mov_read_ilst },
2424 { MKTAG('j','p','2','h'), mov_read_jp2h },
2425 { MKTAG('m','d','a','t'), mov_read_mdat },
2426 { MKTAG('m','d','h','d'), mov_read_mdhd },
2427 { MKTAG('m','d','i','a'), mov_read_default },
2428 { MKTAG('m','e','t','a'), mov_read_meta },
2429 { MKTAG('m','i','n','f'), mov_read_default },
2430 { MKTAG('m','o','o','f'), mov_read_moof },
2431 { MKTAG('m','o','o','v'), mov_read_moov },
2432 { MKTAG('m','v','e','x'), mov_read_default },
2433 { MKTAG('m','v','h','d'), mov_read_mvhd },
2434 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2435 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
2436 { MKTAG('a','v','c','C'), mov_read_glbl },
2437 { MKTAG('p','a','s','p'), mov_read_pasp },
2438 { MKTAG('s','t','b','l'), mov_read_default },
2439 { MKTAG('s','t','c','o'), mov_read_stco },
2440 { MKTAG('s','t','p','s'), mov_read_stps },
2441 { MKTAG('s','t','r','f'), mov_read_strf },
2442 { MKTAG('s','t','s','c'), mov_read_stsc },
2443 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2444 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2445 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2446 { MKTAG('s','t','t','s'), mov_read_stts },
2447 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2448 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2449 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2450 { MKTAG('t','r','a','k'), mov_read_trak },
2451 { MKTAG('t','r','a','f'), mov_read_default },
2452 { MKTAG('t','r','e','f'), mov_read_default },
2453 { MKTAG('c','h','a','p'), mov_read_chap },
2454 { MKTAG('t','r','e','x'), mov_read_trex },
2455 { MKTAG('t','r','u','n'), mov_read_trun },
2456 { MKTAG('u','d','t','a'), mov_read_default },
2457 { MKTAG('w','a','v','e'), mov_read_wave },
2458 { MKTAG('e','s','d','s'), mov_read_esds },
2459 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2460 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2461 { MKTAG('w','f','e','x'), mov_read_wfex },
2462 { MKTAG('c','m','o','v'), mov_read_cmov },
2463 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2467 static int mov_probe(AVProbeData *p)
2469 unsigned int offset;
2473 /* check file header */
2476 /* ignore invalid offset */
2477 if ((offset + 8) > (unsigned int)p->buf_size)
2479 tag = AV_RL32(p->buf + offset + 4);
2481 /* check for obvious tags */
2482 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2483 case MKTAG('m','o','o','v'):
2484 case MKTAG('m','d','a','t'):
2485 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2486 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2487 case MKTAG('f','t','y','p'):
2488 return AVPROBE_SCORE_MAX;
2489 /* those are more common words, so rate then a bit less */
2490 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2491 case MKTAG('w','i','d','e'):
2492 case MKTAG('f','r','e','e'):
2493 case MKTAG('j','u','n','k'):
2494 case MKTAG('p','i','c','t'):
2495 return AVPROBE_SCORE_MAX - 5;
2496 case MKTAG(0x82,0x82,0x7f,0x7d):
2497 case MKTAG('s','k','i','p'):
2498 case MKTAG('u','u','i','d'):
2499 case MKTAG('p','r','f','l'):
2500 offset = AV_RB32(p->buf+offset) + offset;
2501 /* if we only find those cause probedata is too small at least rate them */
2502 score = AVPROBE_SCORE_MAX - 50;
2505 /* unrecognized tag */
2511 // must be done after parsing all trak because there's no order requirement
2512 static void mov_read_chapters(AVFormatContext *s)
2514 MOVContext *mov = s->priv_data;
2515 AVStream *st = NULL;
2516 MOVStreamContext *sc;
2520 for (i = 0; i < s->nb_streams; i++)
2521 if (s->streams[i]->id == mov->chapter_track) {
2526 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2530 st->discard = AVDISCARD_ALL;
2532 cur_pos = avio_tell(sc->pb);
2534 for (i = 0; i < st->nb_index_entries; i++) {
2535 AVIndexEntry *sample = &st->index_entries[i];
2536 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2541 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2542 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2546 // the first two bytes are the length of the title
2547 len = avio_rb16(sc->pb);
2548 if (len > sample->size-2)
2550 title_len = 2*len + 1;
2551 if (!(title = av_mallocz(title_len)))
2554 // The samples could theoretically be in any encoding if there's an encd
2555 // atom following, but in practice are only utf-8 or utf-16, distinguished
2556 // instead by the presence of a BOM
2560 ch = avio_rb16(sc->pb);
2562 avio_get_str16be(sc->pb, len, title, title_len);
2563 else if (ch == 0xfffe)
2564 avio_get_str16le(sc->pb, len, title, title_len);
2567 if (len == 1 || len == 2)
2570 get_strz(sc->pb, title + 2, len - 1);
2574 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2578 avio_seek(sc->pb, cur_pos, SEEK_SET);
2581 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
2583 MOVContext *mov = s->priv_data;
2584 AVIOContext *pb = s->pb;
2586 MOVAtom atom = { AV_RL32("root") };
2589 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2591 atom.size = avio_size(pb);
2593 atom.size = INT64_MAX;
2595 /* check MOV header */
2596 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2597 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2600 if (!mov->found_moov) {
2601 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2604 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2606 if (pb->seekable && mov->chapter_track > 0)
2607 mov_read_chapters(s);
2612 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2614 AVIndexEntry *sample = NULL;
2615 int64_t best_dts = INT64_MAX;
2617 for (i = 0; i < s->nb_streams; i++) {
2618 AVStream *avst = s->streams[i];
2619 MOVStreamContext *msc = avst->priv_data;
2620 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2621 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2622 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2623 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2624 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2626 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2627 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2628 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2629 sample = current_sample;
2638 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2640 MOVContext *mov = s->priv_data;
2641 MOVStreamContext *sc;
2642 AVIndexEntry *sample;
2643 AVStream *st = NULL;
2646 sample = mov_find_next_sample(s, &st);
2648 mov->found_mdat = 0;
2649 if (s->pb->seekable||
2650 mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2653 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2657 /* must be done just before reading, to avoid infinite loop on sample */
2658 sc->current_sample++;
2660 if (st->discard != AVDISCARD_ALL) {
2661 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2662 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2663 sc->ffindex, sample->pos);
2666 ret = av_get_packet(sc->pb, pkt, sample->size);
2669 if (sc->has_palette) {
2672 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2674 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2676 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2677 sc->has_palette = 0;
2680 #if CONFIG_DV_DEMUXER
2681 if (mov->dv_demux && sc->dv_audio_container) {
2682 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
2685 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
2692 pkt->stream_index = sc->ffindex;
2693 pkt->dts = sample->timestamp;
2694 if (sc->ctts_data) {
2695 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2696 /* update ctts context */
2698 if (sc->ctts_index < sc->ctts_count &&
2699 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2701 sc->ctts_sample = 0;
2704 pkt->dts = AV_NOPTS_VALUE;
2706 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2707 st->index_entries[sc->current_sample].timestamp : st->duration;
2708 pkt->duration = next_dts - pkt->dts;
2709 pkt->pts = pkt->dts;
2711 if (st->discard == AVDISCARD_ALL)
2713 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2714 pkt->pos = sample->pos;
2715 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2716 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2720 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2722 MOVStreamContext *sc = st->priv_data;
2723 int sample, time_sample;
2726 sample = av_index_search_timestamp(st, timestamp, flags);
2727 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2728 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2730 if (sample < 0) /* not sure what to do */
2732 sc->current_sample = sample;
2733 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2734 /* adjust ctts index */
2735 if (sc->ctts_data) {
2737 for (i = 0; i < sc->ctts_count; i++) {
2738 int next = time_sample + sc->ctts_data[i].count;
2739 if (next > sc->current_sample) {
2741 sc->ctts_sample = sc->current_sample - time_sample;
2750 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2753 int64_t seek_timestamp, timestamp;
2757 if (stream_index >= s->nb_streams)
2759 if (sample_time < 0)
2762 st = s->streams[stream_index];
2763 sample = mov_seek_stream(s, st, sample_time, flags);
2767 /* adjust seek timestamp to found sample timestamp */
2768 seek_timestamp = st->index_entries[sample].timestamp;
2770 for (i = 0; i < s->nb_streams; i++) {
2772 if (stream_index == i)
2775 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2776 mov_seek_stream(s, st, timestamp, flags);
2781 static int mov_read_close(AVFormatContext *s)
2783 MOVContext *mov = s->priv_data;
2786 for (i = 0; i < s->nb_streams; i++) {
2787 AVStream *st = s->streams[i];
2788 MOVStreamContext *sc = st->priv_data;
2790 av_freep(&sc->ctts_data);
2791 for (j = 0; j < sc->drefs_count; j++) {
2792 av_freep(&sc->drefs[j].path);
2793 av_freep(&sc->drefs[j].dir);
2795 av_freep(&sc->drefs);
2796 if (sc->pb && sc->pb != s->pb)
2800 if (mov->dv_demux) {
2801 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2802 av_freep(&mov->dv_fctx->streams[i]->codec);
2803 av_freep(&mov->dv_fctx->streams[i]);
2805 av_freep(&mov->dv_fctx);
2806 av_freep(&mov->dv_demux);
2809 av_freep(&mov->trex_data);
2814 AVInputFormat ff_mov_demuxer = {
2815 .name = "mov,mp4,m4a,3gp,3g2,mj2",
2816 .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2817 .priv_data_size = sizeof(MOVContext),
2818 .read_probe = mov_probe,
2819 .read_header = mov_read_header,
2820 .read_packet = mov_read_packet,
2821 .read_close = mov_read_close,
2822 .read_seek = mov_read_seek,