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_readwrite.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/dict.h"
34 #include "avio_internal.h"
37 #include "libavcodec/get_bits.h"
45 * First version by Francois Revol revol@free.fr
46 * Seek function by Gael Chardon gael.dev@4now.net
48 * Features and limitations:
49 * - reads most of the QT files I have (at least the structure),
50 * Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
51 * - the code is quite ugly... maybe I won't do it recursive next time :-)
53 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
54 * when coding this :) (it's a writer anyway)
56 * Reference documents:
57 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
59 * http://developer.apple.com/documentation/QuickTime/QTFF/
60 * http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
61 * QuickTime is a trademark of Apple (AFAIK :))
64 #include "qtpalette.h"
70 /* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
72 /* those functions parse an atom */
74 0: continue to parse next atom
75 <0: error occurred, exit
77 /* links atom IDs to parse functions */
78 typedef struct MOVParseTableEntry {
80 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
83 static const MOVParseTableEntry mov_default_parse_table[];
85 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
86 unsigned len, const char *key)
91 avio_rb16(pb); // unknown
92 current = avio_rb16(pb);
93 total = avio_rb16(pb);
95 snprintf(buf, sizeof(buf), "%d", current);
97 snprintf(buf, sizeof(buf), "%d/%d", current, total);
98 av_dict_set(&c->fc->metadata, key, buf, 0);
103 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
104 unsigned len, const char *key)
108 /* bypass padding bytes */
113 snprintf(buf, sizeof(buf), "%hu", avio_r8(pb));
114 av_dict_set(&c->fc->metadata, key, buf, 0);
119 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
120 unsigned len, const char *key)
124 snprintf(buf, sizeof(buf), "%hu", avio_r8(pb));
125 av_dict_set(&c->fc->metadata, key, buf, 0);
130 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
131 unsigned len, const char *key)
136 avio_r8(pb); // unknown
139 if (genre < 1 || genre > ID3v1_GENRE_MAX)
141 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
142 av_dict_set(&c->fc->metadata, key, buf, 0);
147 static const uint32_t mac_to_unicode[128] = {
148 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
149 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
150 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
151 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
152 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
153 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
154 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
155 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
156 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
157 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
158 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
159 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
160 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
161 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
162 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
163 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
166 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
167 char *dst, int dstlen)
170 char *end = dst+dstlen-1;
173 for (i = 0; i < len; i++) {
174 uint8_t t, c = avio_r8(pb);
175 if (c < 0x80 && p < end)
178 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
184 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
186 #ifdef MOV_EXPORT_ALL_METADATA
189 char str[1024], key2[16], language[4] = {0};
190 const char *key = NULL;
191 uint16_t str_size, langcode = 0;
192 uint32_t data_type = 0;
193 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
196 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
197 case MKTAG(0xa9,'a','u','t'):
198 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
199 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
200 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
201 case MKTAG( 'c','p','r','t'):
202 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
203 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
204 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
205 case MKTAG(0xa9,'c','m','t'):
206 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
207 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
208 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
209 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
210 case MKTAG( 'g','n','r','e'): key = "genre";
211 parse = mov_metadata_gnre; break;
212 case MKTAG(0xa9,'t','o','o'):
213 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
214 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
215 case MKTAG( 'd','e','s','c'): key = "description";break;
216 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
217 case MKTAG( 't','v','s','h'): key = "show"; break;
218 case MKTAG( 't','v','e','n'): key = "episode_id";break;
219 case MKTAG( 't','v','n','n'): key = "network"; break;
220 case MKTAG( 't','r','k','n'): key = "track";
221 parse = mov_metadata_track_or_disc_number; break;
222 case MKTAG( 'd','i','s','k'): key = "disc";
223 parse = mov_metadata_track_or_disc_number; break;
224 case MKTAG( 't','v','e','s'): key = "episode_sort";
225 parse = mov_metadata_int8_bypass_padding; break;
226 case MKTAG( 't','v','s','n'): key = "season_number";
227 parse = mov_metadata_int8_bypass_padding; break;
228 case MKTAG( 's','t','i','k'): key = "media_type";
229 parse = mov_metadata_int8_no_padding; break;
230 case MKTAG( 'h','d','v','d'): key = "hd_video";
231 parse = mov_metadata_int8_no_padding; break;
232 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
233 parse = mov_metadata_int8_no_padding; break;
236 if (c->itunes_metadata && atom.size > 8) {
237 int data_size = avio_rb32(pb);
238 int tag = avio_rl32(pb);
239 if (tag == MKTAG('d','a','t','a')) {
240 data_type = avio_rb32(pb); // type
241 avio_rb32(pb); // unknown
242 str_size = data_size - 16;
245 } else if (atom.size > 4 && key && !c->itunes_metadata) {
246 str_size = avio_rb16(pb); // string length
247 langcode = avio_rb16(pb);
248 ff_mov_lang_to_iso639(langcode, language);
251 str_size = atom.size;
253 #ifdef MOV_EXPORT_ALL_METADATA
255 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
265 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
268 parse(c, pb, str_size, key);
270 if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
271 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
273 avio_read(pb, str, str_size);
276 av_dict_set(&c->fc->metadata, key, str, 0);
277 if (*language && strcmp(language, "und")) {
278 snprintf(key2, sizeof(key2), "%s-%s", key, language);
279 av_dict_set(&c->fc->metadata, key2, str, 0);
282 av_dlog(c->fc, "lang \"%3s\" ", language);
283 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
284 key, str, (char*)&atom.type, str_size, atom.size);
289 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
292 int i, nb_chapters, str_len, version;
295 if ((atom.size -= 5) < 0)
298 version = avio_r8(pb);
301 avio_rb32(pb); // ???
302 nb_chapters = avio_r8(pb);
304 for (i = 0; i < nb_chapters; i++) {
308 start = avio_rb64(pb);
309 str_len = avio_r8(pb);
311 if ((atom.size -= 9+str_len) < 0)
314 avio_read(pb, str, str_len);
316 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
321 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
323 int64_t total_size = 0;
328 atom.size = INT64_MAX;
329 while (total_size + 8 < atom.size && !url_feof(pb)) {
330 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
333 if (atom.size >= 8) {
334 a.size = avio_rb32(pb);
335 a.type = avio_rl32(pb);
337 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
338 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
340 if (a.size == 1) { /* 64 bit extended size */
341 a.size = avio_rb64(pb) - 8;
345 a.size = atom.size - total_size;
352 a.size = FFMIN(a.size, atom.size - total_size);
354 for (i = 0; mov_default_parse_table[i].type; i++)
355 if (mov_default_parse_table[i].type == a.type) {
356 parse = mov_default_parse_table[i].parse;
360 // container is user data
361 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
362 atom.type == MKTAG('i','l','s','t')))
363 parse = mov_read_udta_string;
365 if (!parse) { /* skip leaf atoms data */
366 avio_skip(pb, a.size);
368 int64_t start_pos = avio_tell(pb);
370 int err = parse(c, pb, a);
373 if (c->found_moov && c->found_mdat &&
374 (!pb->seekable || start_pos + a.size == avio_size(pb)))
376 left = a.size - avio_tell(pb) + start_pos;
377 if (left > 0) /* skip garbage at atom end */
381 total_size += a.size;
384 if (total_size < atom.size && atom.size < 0x7ffff)
385 avio_skip(pb, atom.size - total_size);
390 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
393 MOVStreamContext *sc;
396 if (c->fc->nb_streams < 1)
398 st = c->fc->streams[c->fc->nb_streams-1];
401 avio_rb32(pb); // version + flags
402 entries = avio_rb32(pb);
403 if (entries >= UINT_MAX / sizeof(*sc->drefs))
405 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
407 return AVERROR(ENOMEM);
408 sc->drefs_count = entries;
410 for (i = 0; i < sc->drefs_count; i++) {
411 MOVDref *dref = &sc->drefs[i];
412 uint32_t size = avio_rb32(pb);
413 int64_t next = avio_tell(pb) + size - 4;
418 dref->type = avio_rl32(pb);
419 avio_rb32(pb); // version + flags
420 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
422 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
423 /* macintosh alias record */
424 uint16_t volume_len, len;
429 volume_len = avio_r8(pb);
430 volume_len = FFMIN(volume_len, 27);
431 avio_read(pb, dref->volume, 27);
432 dref->volume[volume_len] = 0;
433 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
438 len = FFMIN(len, 63);
439 avio_read(pb, dref->filename, 63);
440 dref->filename[len] = 0;
441 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
445 /* read next level up_from_alias/down_to_target */
446 dref->nlvl_from = avio_rb16(pb);
447 dref->nlvl_to = avio_rb16(pb);
448 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
449 dref->nlvl_from, dref->nlvl_to);
453 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
454 type = avio_rb16(pb);
456 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
459 if (type == 2) { // absolute path
461 dref->path = av_mallocz(len+1);
463 return AVERROR(ENOMEM);
464 avio_read(pb, dref->path, len);
465 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
467 memmove(dref->path, dref->path+volume_len, len);
470 for (j = 0; j < len; j++)
471 if (dref->path[j] == ':')
473 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
474 } else if (type == 0) { // directory name
476 dref->dir = av_malloc(len+1);
478 return AVERROR(ENOMEM);
479 avio_read(pb, dref->dir, len);
481 for (j = 0; j < len; j++)
482 if (dref->dir[j] == ':')
484 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
489 avio_seek(pb, next, SEEK_SET);
494 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
498 uint32_t av_unused ctype;
500 if (c->fc->nb_streams < 1) // meta before first trak
503 st = c->fc->streams[c->fc->nb_streams-1];
505 avio_r8(pb); /* version */
506 avio_rb24(pb); /* flags */
509 ctype = avio_rl32(pb);
510 type = avio_rl32(pb); /* component subtype */
512 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
513 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
515 if (type == MKTAG('v','i','d','e'))
516 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
517 else if (type == MKTAG('s','o','u','n'))
518 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
519 else if (type == MKTAG('m','1','a',' '))
520 st->codec->codec_id = CODEC_ID_MP2;
521 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
522 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
524 avio_rb32(pb); /* component manufacture */
525 avio_rb32(pb); /* component flags */
526 avio_rb32(pb); /* component flags mask */
531 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
536 if (fc->nb_streams < 1)
538 st = fc->streams[fc->nb_streams-1];
540 avio_rb32(pb); /* version + flags */
541 ff_mp4_read_descr(fc, pb, &tag);
542 if (tag == MP4ESDescrTag) {
543 ff_mp4_parse_es_descr(pb, NULL);
545 avio_rb16(pb); /* ID */
547 ff_mp4_read_descr(fc, pb, &tag);
548 if (tag == MP4DecConfigDescrTag)
549 ff_mp4_read_dec_config_descr(fc, st, pb);
553 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
555 return ff_mov_read_esds(c->fc, pb, atom);
558 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
561 int ac3info, acmod, lfeon, bsmod;
563 if (c->fc->nb_streams < 1)
565 st = c->fc->streams[c->fc->nb_streams-1];
567 ac3info = avio_rb24(pb);
568 bsmod = (ac3info >> 14) & 0x7;
569 acmod = (ac3info >> 11) & 0x7;
570 lfeon = (ac3info >> 10) & 0x1;
571 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
572 st->codec->audio_service_type = bsmod;
573 if (st->codec->channels > 1 && bsmod == 0x7)
574 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
579 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
583 if (c->fc->nb_streams < 1)
585 st = c->fc->streams[c->fc->nb_streams-1];
587 ff_get_wav_header(pb, st->codec, atom.size);
592 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
594 const int num = avio_rb32(pb);
595 const int den = avio_rb32(pb);
598 if (c->fc->nb_streams < 1)
600 st = c->fc->streams[c->fc->nb_streams-1];
602 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
603 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
604 av_log(c->fc, AV_LOG_WARNING,
605 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
606 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
608 } else if (den != 0) {
609 st->sample_aspect_ratio.num = num;
610 st->sample_aspect_ratio.den = den;
615 /* this atom contains actual media data */
616 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
618 if (atom.size == 0) /* wrong one (MP4) */
621 return 0; /* now go for moov */
624 /* read major brand, minor version and compatible brands and store them as metadata */
625 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
629 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
630 char* comp_brands_str;
631 uint8_t type[5] = {0};
633 avio_read(pb, type, 4);
634 if (strcmp(type, "qt "))
636 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
637 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
638 minor_ver = avio_rb32(pb); /* minor version */
639 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
640 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
642 comp_brand_size = atom.size - 8;
643 if (comp_brand_size < 0)
645 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
646 if (!comp_brands_str)
647 return AVERROR(ENOMEM);
648 avio_read(pb, comp_brands_str, comp_brand_size);
649 comp_brands_str[comp_brand_size] = 0;
650 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
651 av_freep(&comp_brands_str);
656 /* this atom should contain all header atoms */
657 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
659 if (mov_read_default(c, pb, atom) < 0)
661 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
662 /* so we don't parse the whole file if over a network */
664 return 0; /* now go for mdat */
667 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
669 c->fragment.moof_offset = avio_tell(pb) - 8;
670 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
671 return mov_read_default(c, pb, atom);
674 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
679 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
682 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
683 av_dict_set(metadata, "creation_time", buffer, 0);
687 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
690 MOVStreamContext *sc;
692 char language[4] = {0};
694 time_t creation_time;
696 if (c->fc->nb_streams < 1)
698 st = c->fc->streams[c->fc->nb_streams-1];
701 version = avio_r8(pb);
703 return -1; /* unsupported */
705 avio_rb24(pb); /* flags */
707 creation_time = avio_rb64(pb);
710 creation_time = avio_rb32(pb);
711 avio_rb32(pb); /* modification time */
713 mov_metadata_creation_time(&st->metadata, creation_time);
715 sc->time_scale = avio_rb32(pb);
716 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
718 lang = avio_rb16(pb); /* language */
719 if (ff_mov_lang_to_iso639(lang, language))
720 av_dict_set(&st->metadata, "language", language, 0);
721 avio_rb16(pb); /* quality */
726 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
728 time_t creation_time;
729 int version = avio_r8(pb); /* version */
730 avio_rb24(pb); /* flags */
733 creation_time = avio_rb64(pb);
736 creation_time = avio_rb32(pb);
737 avio_rb32(pb); /* modification time */
739 mov_metadata_creation_time(&c->fc->metadata, creation_time);
740 c->time_scale = avio_rb32(pb); /* time scale */
742 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
744 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
745 avio_rb32(pb); /* preferred scale */
747 avio_rb16(pb); /* preferred volume */
749 avio_skip(pb, 10); /* reserved */
751 avio_skip(pb, 36); /* display matrix */
753 avio_rb32(pb); /* preview time */
754 avio_rb32(pb); /* preview duration */
755 avio_rb32(pb); /* poster time */
756 avio_rb32(pb); /* selection time */
757 avio_rb32(pb); /* selection duration */
758 avio_rb32(pb); /* current time */
759 avio_rb32(pb); /* next track ID */
764 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
768 if (c->fc->nb_streams < 1)
770 st = c->fc->streams[c->fc->nb_streams-1];
772 if ((uint64_t)atom.size > (1<<30))
775 // currently SVQ3 decoder expect full STSD header - so let's fake it
776 // this should be fixed and just SMI header should be passed
777 av_free(st->codec->extradata);
778 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
779 if (!st->codec->extradata)
780 return AVERROR(ENOMEM);
781 st->codec->extradata_size = 0x5a + atom.size;
782 memcpy(st->codec->extradata, "SVQ3", 4); // fake
783 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
784 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
788 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
793 if (c->fc->nb_streams < 1)
795 st = c->fc->streams[c->fc->nb_streams-1];
797 little_endian = avio_rb16(pb) & 0xFF;
798 av_dlog(c->fc, "enda %d\n", little_endian);
799 if (little_endian == 1) {
800 switch (st->codec->codec_id) {
801 case CODEC_ID_PCM_S24BE:
802 st->codec->codec_id = CODEC_ID_PCM_S24LE;
804 case CODEC_ID_PCM_S32BE:
805 st->codec->codec_id = CODEC_ID_PCM_S32LE;
807 case CODEC_ID_PCM_F32BE:
808 st->codec->codec_id = CODEC_ID_PCM_F32LE;
810 case CODEC_ID_PCM_F64BE:
811 st->codec->codec_id = CODEC_ID_PCM_F64LE;
820 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
821 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
822 enum CodecID codec_id)
828 if (c->fc->nb_streams < 1) // will happen with jp2 files
830 st= c->fc->streams[c->fc->nb_streams-1];
832 if (st->codec->codec_id != codec_id)
833 return 0; /* unexpected codec_id - don't mess with extradata */
835 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
836 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
838 buf= av_realloc(st->codec->extradata, size);
841 st->codec->extradata= buf;
842 buf+= st->codec->extradata_size;
843 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
844 AV_WB32( buf , atom.size + 8);
845 AV_WL32( buf + 4, atom.type);
846 avio_read(pb, buf + 8, atom.size);
850 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
851 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
853 return mov_read_extradata(c, pb, atom, CODEC_ID_ALAC);
856 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
858 return mov_read_extradata(c, pb, atom, CODEC_ID_AVS);
861 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
863 return mov_read_extradata(c, pb, atom, CODEC_ID_MJPEG);
866 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
868 return mov_read_extradata(c, pb, atom, CODEC_ID_JPEG2000);
871 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
875 if (c->fc->nb_streams < 1)
877 st = c->fc->streams[c->fc->nb_streams-1];
879 if ((uint64_t)atom.size > (1<<30))
882 if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
883 // pass all frma atom to codec, needed at least for QDMC and QDM2
884 av_free(st->codec->extradata);
885 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
886 if (!st->codec->extradata)
887 return AVERROR(ENOMEM);
888 st->codec->extradata_size = atom.size;
889 avio_read(pb, st->codec->extradata, atom.size);
890 } else if (atom.size > 8) { /* to read frma, esds atoms */
891 if (mov_read_default(c, pb, atom) < 0)
894 avio_skip(pb, atom.size);
899 * This function reads atom content and puts data in extradata without tag
900 * nor size unlike mov_read_extradata.
902 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
906 if (c->fc->nb_streams < 1)
908 st = c->fc->streams[c->fc->nb_streams-1];
910 if ((uint64_t)atom.size > (1<<30))
913 av_free(st->codec->extradata);
914 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
915 if (!st->codec->extradata)
916 return AVERROR(ENOMEM);
917 st->codec->extradata_size = atom.size;
918 avio_read(pb, st->codec->extradata, atom.size);
923 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
924 * but can have extradata appended at the end after the 40 bytes belonging
927 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
931 if (c->fc->nb_streams < 1)
935 st = c->fc->streams[c->fc->nb_streams-1];
937 if ((uint64_t)atom.size > (1<<30))
940 av_free(st->codec->extradata);
941 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
942 if (!st->codec->extradata)
943 return AVERROR(ENOMEM);
944 st->codec->extradata_size = atom.size - 40;
946 avio_read(pb, st->codec->extradata, atom.size - 40);
950 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
953 MOVStreamContext *sc;
954 unsigned int i, entries;
956 if (c->fc->nb_streams < 1)
958 st = c->fc->streams[c->fc->nb_streams-1];
961 avio_r8(pb); /* version */
962 avio_rb24(pb); /* flags */
964 entries = avio_rb32(pb);
966 if (entries >= UINT_MAX/sizeof(int64_t))
969 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
970 if (!sc->chunk_offsets)
971 return AVERROR(ENOMEM);
972 sc->chunk_count = entries;
974 if (atom.type == MKTAG('s','t','c','o'))
975 for (i=0; i<entries; i++)
976 sc->chunk_offsets[i] = avio_rb32(pb);
977 else if (atom.type == MKTAG('c','o','6','4'))
978 for (i=0; i<entries; i++)
979 sc->chunk_offsets[i] = avio_rb64(pb);
987 * Compute codec id for 'lpcm' tag.
988 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
990 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
992 if (flags & 1) { // floating point
993 if (flags & 2) { // big endian
994 if (bps == 32) return CODEC_ID_PCM_F32BE;
995 else if (bps == 64) return CODEC_ID_PCM_F64BE;
997 if (bps == 32) return CODEC_ID_PCM_F32LE;
998 else if (bps == 64) return CODEC_ID_PCM_F64LE;
1004 if (flags & 4) return CODEC_ID_PCM_S8;
1005 else return CODEC_ID_PCM_U8;
1006 else if (bps == 16) return CODEC_ID_PCM_S16BE;
1007 else if (bps == 24) return CODEC_ID_PCM_S24BE;
1008 else if (bps == 32) return CODEC_ID_PCM_S32BE;
1011 if (flags & 4) return CODEC_ID_PCM_S8;
1012 else return CODEC_ID_PCM_U8;
1013 else if (bps == 16) return CODEC_ID_PCM_S16LE;
1014 else if (bps == 24) return CODEC_ID_PCM_S24LE;
1015 else if (bps == 32) return CODEC_ID_PCM_S32LE;
1018 return CODEC_ID_NONE;
1021 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1024 MOVStreamContext *sc;
1025 int j, pseudo_stream_id;
1027 if (c->fc->nb_streams < 1)
1029 st = c->fc->streams[c->fc->nb_streams-1];
1032 for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
1033 //Parsing Sample description table
1036 MOVAtom a = { AV_RL32("stsd") };
1037 int64_t start_pos = avio_tell(pb);
1038 int size = avio_rb32(pb); /* size */
1039 uint32_t format = avio_rl32(pb); /* data format */
1042 avio_rb32(pb); /* reserved */
1043 avio_rb16(pb); /* reserved */
1044 dref_id = avio_rb16(pb);
1047 if (st->codec->codec_tag &&
1048 st->codec->codec_tag != format &&
1049 (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
1050 : st->codec->codec_tag != MKTAG('j','p','e','g'))
1052 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1053 * export it as a separate AVStream but this needs a few changes
1054 * in the MOV demuxer, patch welcome. */
1056 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1057 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1060 /* we cannot demux concatenated h264 streams because of different extradata */
1061 if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1063 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1064 sc->dref_id= dref_id;
1066 st->codec->codec_tag = format;
1067 id = ff_codec_get_id(codec_movaudio_tags, format);
1068 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1069 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1071 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1072 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1073 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1074 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1075 id = ff_codec_get_id(codec_movvideo_tags, format);
1077 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1079 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1080 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){
1081 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1083 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1087 av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1088 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1089 (format >> 24) & 0xff, st->codec->codec_type);
1091 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1092 unsigned int color_depth, len;
1093 int color_greyscale;
1095 st->codec->codec_id = id;
1096 avio_rb16(pb); /* version */
1097 avio_rb16(pb); /* revision level */
1098 avio_rb32(pb); /* vendor */
1099 avio_rb32(pb); /* temporal quality */
1100 avio_rb32(pb); /* spatial quality */
1102 st->codec->width = avio_rb16(pb); /* width */
1103 st->codec->height = avio_rb16(pb); /* height */
1105 avio_rb32(pb); /* horiz resolution */
1106 avio_rb32(pb); /* vert resolution */
1107 avio_rb32(pb); /* data size, always 0 */
1108 avio_rb16(pb); /* frames per samples */
1110 len = avio_r8(pb); /* codec name, pascal string */
1113 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1115 avio_skip(pb, 31 - len);
1116 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1117 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1118 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1120 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1121 st->codec->color_table_id = avio_rb16(pb); /* colortable id */
1122 av_dlog(c->fc, "depth %d, ctab id %d\n",
1123 st->codec->bits_per_coded_sample, st->codec->color_table_id);
1124 /* figure out the palette situation */
1125 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1126 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1128 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1129 if ((color_depth == 2) || (color_depth == 4) ||
1130 (color_depth == 8)) {
1131 /* for palette traversal */
1132 unsigned int color_start, color_count, color_end;
1133 unsigned char r, g, b;
1135 if (color_greyscale) {
1136 int color_index, color_dec;
1137 /* compute the greyscale palette */
1138 st->codec->bits_per_coded_sample = color_depth;
1139 color_count = 1 << color_depth;
1141 color_dec = 256 / (color_count - 1);
1142 for (j = 0; j < color_count; j++) {
1143 if (id == CODEC_ID_CINEPAK){
1144 r = g = b = color_count - 1 - color_index;
1146 r = g = b = color_index;
1148 (r << 16) | (g << 8) | (b);
1149 color_index -= color_dec;
1150 if (color_index < 0)
1153 } else if (st->codec->color_table_id) {
1154 const uint8_t *color_table;
1155 /* if flag bit 3 is set, use the default palette */
1156 color_count = 1 << color_depth;
1157 if (color_depth == 2)
1158 color_table = ff_qt_default_palette_4;
1159 else if (color_depth == 4)
1160 color_table = ff_qt_default_palette_16;
1162 color_table = ff_qt_default_palette_256;
1164 for (j = 0; j < color_count; j++) {
1165 r = color_table[j * 3 + 0];
1166 g = color_table[j * 3 + 1];
1167 b = color_table[j * 3 + 2];
1169 (r << 16) | (g << 8) | (b);
1172 /* load the palette from the file */
1173 color_start = avio_rb32(pb);
1174 color_count = avio_rb16(pb);
1175 color_end = avio_rb16(pb);
1176 if ((color_start <= 255) &&
1177 (color_end <= 255)) {
1178 for (j = color_start; j <= color_end; j++) {
1179 /* each R, G, or B component is 16 bits;
1180 * only use the top 8 bits; skip alpha bytes
1191 (r << 16) | (g << 8) | (b);
1195 sc->has_palette = 1;
1197 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1198 int bits_per_sample, flags;
1199 uint16_t version = avio_rb16(pb);
1201 st->codec->codec_id = id;
1202 avio_rb16(pb); /* revision level */
1203 avio_rb32(pb); /* vendor */
1205 st->codec->channels = avio_rb16(pb); /* channel count */
1206 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1207 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1209 sc->audio_cid = avio_rb16(pb);
1210 avio_rb16(pb); /* packet size = 0 */
1212 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1214 //Read QT version 1 fields. In version 0 these do not exist.
1215 av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1218 sc->samples_per_frame = avio_rb32(pb);
1219 avio_rb32(pb); /* bytes per packet */
1220 sc->bytes_per_frame = avio_rb32(pb);
1221 avio_rb32(pb); /* bytes per sample */
1222 } else if (version==2) {
1223 avio_rb32(pb); /* sizeof struct only */
1224 st->codec->sample_rate = av_int2dbl(avio_rb64(pb)); /* float 64 */
1225 st->codec->channels = avio_rb32(pb);
1226 avio_rb32(pb); /* always 0x7F000000 */
1227 st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1228 flags = avio_rb32(pb); /* lpcm format specific flag */
1229 sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1230 sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1231 if (format == MKTAG('l','p','c','m'))
1232 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1236 switch (st->codec->codec_id) {
1237 case CODEC_ID_PCM_S8:
1238 case CODEC_ID_PCM_U8:
1239 if (st->codec->bits_per_coded_sample == 16)
1240 st->codec->codec_id = CODEC_ID_PCM_S16BE;
1242 case CODEC_ID_PCM_S16LE:
1243 case CODEC_ID_PCM_S16BE:
1244 if (st->codec->bits_per_coded_sample == 8)
1245 st->codec->codec_id = CODEC_ID_PCM_S8;
1246 else if (st->codec->bits_per_coded_sample == 24)
1247 st->codec->codec_id =
1248 st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1249 CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1251 /* set values for old format before stsd version 1 appeared */
1252 case CODEC_ID_MACE3:
1253 sc->samples_per_frame = 6;
1254 sc->bytes_per_frame = 2*st->codec->channels;
1256 case CODEC_ID_MACE6:
1257 sc->samples_per_frame = 6;
1258 sc->bytes_per_frame = 1*st->codec->channels;
1260 case CODEC_ID_ADPCM_IMA_QT:
1261 sc->samples_per_frame = 64;
1262 sc->bytes_per_frame = 34*st->codec->channels;
1265 sc->samples_per_frame = 160;
1266 sc->bytes_per_frame = 33;
1272 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1273 if (bits_per_sample) {
1274 st->codec->bits_per_coded_sample = bits_per_sample;
1275 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1277 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1278 // ttxt stsd contains display flags, justification, background
1279 // color, fonts, and default styles, so fake an atom to read it
1280 MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1281 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1282 mov_read_glbl(c, pb, fake_atom);
1283 st->codec->codec_id= id;
1284 st->codec->width = sc->width;
1285 st->codec->height = sc->height;
1287 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1289 avio_rb32(pb); /* reserved */
1290 val = avio_rb32(pb); /* flags */
1292 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1295 st->codec->time_base.den = get_byte(pb);
1296 st->codec->time_base.num = 1;
1298 /* other codec type, just skip (rtp, mp4s, ...) */
1299 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1301 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1302 a.size = size - (avio_tell(pb) - start_pos);
1304 if (mov_read_default(c, pb, a) < 0)
1306 } else if (a.size > 0)
1307 avio_skip(pb, a.size);
1310 if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1311 st->codec->sample_rate= sc->time_scale;
1313 /* special codec parameters handling */
1314 switch (st->codec->codec_id) {
1315 #if CONFIG_DV_DEMUXER
1316 case CODEC_ID_DVAUDIO:
1317 c->dv_fctx = avformat_alloc_context();
1318 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1320 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1323 sc->dv_audio_container = 1;
1324 st->codec->codec_id = CODEC_ID_PCM_S16LE;
1327 /* no ifdef since parameters are always those */
1328 case CODEC_ID_QCELP:
1329 // force sample rate for qcelp when not stored in mov
1330 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1331 st->codec->sample_rate = 8000;
1332 st->codec->frame_size= 160;
1333 st->codec->channels= 1; /* really needed */
1335 case CODEC_ID_AMR_NB:
1336 case CODEC_ID_AMR_WB:
1337 st->codec->frame_size= sc->samples_per_frame;
1338 st->codec->channels= 1; /* really needed */
1339 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1340 if (st->codec->codec_id == CODEC_ID_AMR_NB)
1341 st->codec->sample_rate = 8000;
1342 else if (st->codec->codec_id == CODEC_ID_AMR_WB)
1343 st->codec->sample_rate = 16000;
1347 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1348 st->need_parsing = AVSTREAM_PARSE_FULL;
1351 case CODEC_ID_ADPCM_MS:
1352 case CODEC_ID_ADPCM_IMA_WAV:
1353 st->codec->frame_size = sc->samples_per_frame;
1354 st->codec->block_align = sc->bytes_per_frame;
1357 if (st->codec->extradata_size == 36) {
1358 st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1359 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1360 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1364 st->need_parsing = AVSTREAM_PARSE_FULL;
1373 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1377 avio_r8(pb); /* version */
1378 avio_rb24(pb); /* flags */
1379 entries = avio_rb32(pb);
1381 return ff_mov_read_stsd_entries(c, pb, entries);
1384 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1387 MOVStreamContext *sc;
1388 unsigned int i, entries;
1390 if (c->fc->nb_streams < 1)
1392 st = c->fc->streams[c->fc->nb_streams-1];
1395 avio_r8(pb); /* version */
1396 avio_rb24(pb); /* flags */
1398 entries = avio_rb32(pb);
1400 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1402 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1404 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1406 return AVERROR(ENOMEM);
1407 sc->stsc_count = entries;
1409 for (i=0; i<entries; i++) {
1410 sc->stsc_data[i].first = avio_rb32(pb);
1411 sc->stsc_data[i].count = avio_rb32(pb);
1412 sc->stsc_data[i].id = avio_rb32(pb);
1417 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1420 MOVStreamContext *sc;
1421 unsigned i, entries;
1423 if (c->fc->nb_streams < 1)
1425 st = c->fc->streams[c->fc->nb_streams-1];
1428 avio_rb32(pb); // version + flags
1430 entries = avio_rb32(pb);
1431 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1433 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1435 return AVERROR(ENOMEM);
1436 sc->stps_count = entries;
1438 for (i = 0; i < entries; i++) {
1439 sc->stps_data[i] = avio_rb32(pb);
1440 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1446 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1449 MOVStreamContext *sc;
1450 unsigned int i, entries;
1452 if (c->fc->nb_streams < 1)
1454 st = c->fc->streams[c->fc->nb_streams-1];
1457 avio_r8(pb); /* version */
1458 avio_rb24(pb); /* flags */
1460 entries = avio_rb32(pb);
1462 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1464 if (entries >= UINT_MAX / sizeof(int))
1466 sc->keyframes = av_malloc(entries * sizeof(int));
1468 return AVERROR(ENOMEM);
1469 sc->keyframe_count = entries;
1471 for (i=0; i<entries; i++) {
1472 sc->keyframes[i] = avio_rb32(pb);
1473 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1478 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1481 MOVStreamContext *sc;
1482 unsigned int i, entries, sample_size, field_size, num_bytes;
1486 if (c->fc->nb_streams < 1)
1488 st = c->fc->streams[c->fc->nb_streams-1];
1491 avio_r8(pb); /* version */
1492 avio_rb24(pb); /* flags */
1494 if (atom.type == MKTAG('s','t','s','z')) {
1495 sample_size = avio_rb32(pb);
1496 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1497 sc->sample_size = sample_size;
1501 avio_rb24(pb); /* reserved */
1502 field_size = avio_r8(pb);
1504 entries = avio_rb32(pb);
1506 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1508 sc->sample_count = entries;
1512 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1513 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1517 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1519 sc->sample_sizes = av_malloc(entries * sizeof(int));
1520 if (!sc->sample_sizes)
1521 return AVERROR(ENOMEM);
1523 num_bytes = (entries*field_size+4)>>3;
1525 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1527 av_freep(&sc->sample_sizes);
1528 return AVERROR(ENOMEM);
1531 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1532 av_freep(&sc->sample_sizes);
1537 init_get_bits(&gb, buf, 8*num_bytes);
1539 for (i=0; i<entries; i++)
1540 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1546 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1549 MOVStreamContext *sc;
1550 unsigned int i, entries;
1552 int64_t total_sample_count=0;
1554 if (c->fc->nb_streams < 1)
1556 st = c->fc->streams[c->fc->nb_streams-1];
1559 avio_r8(pb); /* version */
1560 avio_rb24(pb); /* flags */
1561 entries = avio_rb32(pb);
1563 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1564 c->fc->nb_streams-1, entries);
1566 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1569 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1571 return AVERROR(ENOMEM);
1573 sc->stts_count = entries;
1575 for (i=0; i<entries; i++) {
1576 int sample_duration;
1579 sample_count=avio_rb32(pb);
1580 sample_duration = avio_rb32(pb);
1581 /* sample_duration < 0 is invalid based on the spec */
1582 if (sample_duration < 0) {
1583 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d", sample_duration);
1584 sample_duration = 1;
1586 sc->stts_data[i].count= sample_count;
1587 sc->stts_data[i].duration= sample_duration;
1589 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1590 sample_count, sample_duration);
1592 duration+=(int64_t)sample_duration*sample_count;
1593 total_sample_count+=sample_count;
1596 st->nb_frames= total_sample_count;
1598 st->duration= duration;
1602 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1605 MOVStreamContext *sc;
1606 unsigned int i, entries;
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].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1619 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1621 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1623 return AVERROR(ENOMEM);
1624 sc->ctts_count = entries;
1626 for (i=0; i<entries; i++) {
1627 int count =avio_rb32(pb);
1628 int duration =avio_rb32(pb);
1630 sc->ctts_data[i].count = count;
1631 sc->ctts_data[i].duration= duration;
1632 if (duration < 0 && i+2<entries)
1633 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1636 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1641 static void mov_build_index(MOVContext *mov, AVStream *st)
1643 MOVStreamContext *sc = st->priv_data;
1644 int64_t current_offset;
1645 int64_t current_dts = 0;
1646 unsigned int stts_index = 0;
1647 unsigned int stsc_index = 0;
1648 unsigned int stss_index = 0;
1649 unsigned int stps_index = 0;
1651 uint64_t stream_size = 0;
1653 /* adjust first dts according to edit list */
1654 if (sc->time_offset && mov->time_scale > 0) {
1655 if (sc->time_offset < 0)
1656 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
1657 current_dts = -sc->time_offset;
1658 if (sc->ctts_data && sc->stts_data &&
1659 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1660 /* more than 16 frames delay, dts are likely wrong
1661 this happens with files created by iMovie */
1663 st->codec->has_b_frames = 1;
1667 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1668 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1669 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1670 unsigned int current_sample = 0;
1671 unsigned int stts_sample = 0;
1672 unsigned int sample_size;
1673 unsigned int distance = 0;
1674 int key_off = sc->keyframes && sc->keyframes[0] == 1;
1676 current_dts -= sc->dts_shift;
1678 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
1680 st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
1681 if (!st->index_entries)
1683 st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
1685 for (i = 0; i < sc->chunk_count; i++) {
1686 current_offset = sc->chunk_offsets[i];
1687 while (stsc_index + 1 < sc->stsc_count &&
1688 i + 1 == sc->stsc_data[stsc_index + 1].first)
1690 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1692 if (current_sample >= sc->sample_count) {
1693 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1697 if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1699 if (stss_index + 1 < sc->keyframe_count)
1701 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1703 if (stps_index + 1 < sc->stps_count)
1708 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1709 if (sc->pseudo_stream_id == -1 ||
1710 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1711 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1712 e->pos = current_offset;
1713 e->timestamp = current_dts;
1714 e->size = sample_size;
1715 e->min_distance = distance;
1716 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1717 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1718 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1719 current_offset, current_dts, sample_size, distance, keyframe);
1722 current_offset += sample_size;
1723 stream_size += sample_size;
1724 current_dts += sc->stts_data[stts_index].duration;
1728 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1734 if (st->duration > 0)
1735 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1737 unsigned chunk_samples, total = 0;
1739 // compute total chunk count
1740 for (i = 0; i < sc->stsc_count; i++) {
1741 unsigned count, chunk_count;
1743 chunk_samples = sc->stsc_data[i].count;
1744 if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1745 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1749 if (sc->samples_per_frame >= 160) { // gsm
1750 count = chunk_samples / sc->samples_per_frame;
1751 } else if (sc->samples_per_frame > 1) {
1752 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1753 count = (chunk_samples+samples-1) / samples;
1755 count = (chunk_samples+1023) / 1024;
1758 if (i < sc->stsc_count - 1)
1759 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1761 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1762 total += chunk_count * count;
1765 av_dlog(mov->fc, "chunk count %d\n", total);
1766 if (total >= UINT_MAX / sizeof(*st->index_entries))
1768 st->index_entries = av_malloc(total*sizeof(*st->index_entries));
1769 if (!st->index_entries)
1771 st->index_entries_allocated_size = total*sizeof(*st->index_entries);
1774 for (i = 0; i < sc->chunk_count; i++) {
1775 current_offset = sc->chunk_offsets[i];
1776 if (stsc_index + 1 < sc->stsc_count &&
1777 i + 1 == sc->stsc_data[stsc_index + 1].first)
1779 chunk_samples = sc->stsc_data[stsc_index].count;
1781 while (chunk_samples > 0) {
1783 unsigned size, samples;
1785 if (sc->samples_per_frame >= 160) { // gsm
1786 samples = sc->samples_per_frame;
1787 size = sc->bytes_per_frame;
1789 if (sc->samples_per_frame > 1) {
1790 samples = FFMIN((1024 / sc->samples_per_frame)*
1791 sc->samples_per_frame, chunk_samples);
1792 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1794 samples = FFMIN(1024, chunk_samples);
1795 size = samples * sc->sample_size;
1799 if (st->nb_index_entries >= total) {
1800 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1803 e = &st->index_entries[st->nb_index_entries++];
1804 e->pos = current_offset;
1805 e->timestamp = current_dts;
1807 e->min_distance = 0;
1808 e->flags = AVINDEX_KEYFRAME;
1809 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1810 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1813 current_offset += size;
1814 current_dts += samples;
1815 chunk_samples -= samples;
1821 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref)
1823 /* try relative path, we do not try the absolute because it can leak information about our
1824 system to an attacker */
1825 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1826 char filename[1024];
1827 const char *src_path;
1830 /* find a source dir */
1831 src_path = strrchr(src, '/');
1837 /* find a next level down to target */
1838 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1839 if (ref->path[l] == '/') {
1840 if (i == ref->nlvl_to - 1)
1846 /* compose filename if next level down to target was found */
1847 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
1848 memcpy(filename, src, src_path - src);
1849 filename[src_path - src] = 0;
1851 for (i = 1; i < ref->nlvl_from; i++)
1852 av_strlcat(filename, "../", 1024);
1854 av_strlcat(filename, ref->path + l + 1, 1024);
1856 if (!avio_open(pb, filename, AVIO_FLAG_READ))
1861 return AVERROR(ENOENT);
1864 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1867 MOVStreamContext *sc;
1870 st = avformat_new_stream(c->fc, NULL);
1871 if (!st) return AVERROR(ENOMEM);
1872 st->id = c->fc->nb_streams;
1873 sc = av_mallocz(sizeof(MOVStreamContext));
1874 if (!sc) return AVERROR(ENOMEM);
1877 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1878 sc->ffindex = st->index;
1880 if ((ret = mov_read_default(c, pb, atom)) < 0)
1884 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1885 (!sc->sample_size && !sc->sample_count))) {
1886 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1891 if (sc->time_scale <= 0) {
1892 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
1893 sc->time_scale = c->time_scale;
1894 if (sc->time_scale <= 0)
1898 av_set_pts_info(st, 64, 1, sc->time_scale);
1900 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1901 !st->codec->frame_size && sc->stts_count == 1) {
1902 st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
1903 st->codec->sample_rate, sc->time_scale);
1904 av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
1907 mov_build_index(c, st);
1909 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1910 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
1911 if (mov_open_dref(&sc->pb, c->fc->filename, dref) < 0)
1912 av_log(c->fc, AV_LOG_ERROR,
1913 "stream %d, error opening alias: path='%s', dir='%s', "
1914 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
1915 st->index, dref->path, dref->dir, dref->filename,
1916 dref->volume, dref->nlvl_from, dref->nlvl_to);
1920 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1921 if (!st->sample_aspect_ratio.num &&
1922 (st->codec->width != sc->width || st->codec->height != sc->height)) {
1923 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
1924 ((double)st->codec->width * sc->height), INT_MAX);
1927 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1928 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
1930 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
1931 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
1932 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
1935 switch (st->codec->codec_id) {
1936 #if CONFIG_H261_DECODER
1939 #if CONFIG_H263_DECODER
1942 #if CONFIG_H264_DECODER
1945 #if CONFIG_MPEG4_DECODER
1946 case CODEC_ID_MPEG4:
1948 st->codec->width = 0; /* let decoder init width/height */
1949 st->codec->height= 0;
1953 /* Do not need those anymore. */
1954 av_freep(&sc->chunk_offsets);
1955 av_freep(&sc->stsc_data);
1956 av_freep(&sc->sample_sizes);
1957 av_freep(&sc->keyframes);
1958 av_freep(&sc->stts_data);
1959 av_freep(&sc->stps_data);
1964 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1967 c->itunes_metadata = 1;
1968 ret = mov_read_default(c, pb, atom);
1969 c->itunes_metadata = 0;
1973 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1975 while (atom.size > 8) {
1976 uint32_t tag = avio_rl32(pb);
1978 if (tag == MKTAG('h','d','l','r')) {
1979 avio_seek(pb, -8, SEEK_CUR);
1981 return mov_read_default(c, pb, atom);
1987 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1992 int64_t disp_transform[2];
1993 int display_matrix[3][2];
1995 MOVStreamContext *sc;
1998 if (c->fc->nb_streams < 1)
2000 st = c->fc->streams[c->fc->nb_streams-1];
2003 version = avio_r8(pb);
2004 avio_rb24(pb); /* flags */
2006 MOV_TRACK_ENABLED 0x0001
2007 MOV_TRACK_IN_MOVIE 0x0002
2008 MOV_TRACK_IN_PREVIEW 0x0004
2009 MOV_TRACK_IN_POSTER 0x0008
2016 avio_rb32(pb); /* creation time */
2017 avio_rb32(pb); /* modification time */
2019 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2020 avio_rb32(pb); /* reserved */
2022 /* highlevel (considering edits) duration in movie timebase */
2023 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2024 avio_rb32(pb); /* reserved */
2025 avio_rb32(pb); /* reserved */
2027 avio_rb16(pb); /* layer */
2028 avio_rb16(pb); /* alternate group */
2029 avio_rb16(pb); /* volume */
2030 avio_rb16(pb); /* reserved */
2032 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2033 // they're kept in fixed point format through all calculations
2034 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2035 for (i = 0; i < 3; i++) {
2036 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2037 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2038 avio_rb32(pb); // 2.30 fixed point (not used)
2041 width = avio_rb32(pb); // 16.16 fixed point track width
2042 height = avio_rb32(pb); // 16.16 fixed point track height
2043 sc->width = width >> 16;
2044 sc->height = height >> 16;
2046 if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2047 av_dict_set(&st->metadata, "rotate", "180", 0);
2050 // transform the display width/height according to the matrix
2051 // skip this if the display matrix is the default identity matrix
2052 // or if it is rotating the picture, ex iPhone 3GS
2053 // to keep the same scale, use [width height 1<<16]
2054 if (width && height &&
2055 ((display_matrix[0][0] != 65536 ||
2056 display_matrix[1][1] != 65536) &&
2057 !display_matrix[0][1] &&
2058 !display_matrix[1][0] &&
2059 !display_matrix[2][0] && !display_matrix[2][1])) {
2060 for (i = 0; i < 2; i++)
2062 (int64_t) width * display_matrix[0][i] +
2063 (int64_t) height * display_matrix[1][i] +
2064 ((int64_t) display_matrix[2][i] << 16);
2066 //sample aspect ratio is new width/height divided by old width/height
2067 st->sample_aspect_ratio = av_d2q(
2068 ((double) disp_transform[0] * height) /
2069 ((double) disp_transform[1] * width), INT_MAX);
2074 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2076 MOVFragment *frag = &c->fragment;
2077 MOVTrackExt *trex = NULL;
2078 int flags, track_id, i;
2080 avio_r8(pb); /* version */
2081 flags = avio_rb24(pb);
2083 track_id = avio_rb32(pb);
2086 frag->track_id = track_id;
2087 for (i = 0; i < c->trex_count; i++)
2088 if (c->trex_data[i].track_id == frag->track_id) {
2089 trex = &c->trex_data[i];
2093 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2097 if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
2098 else frag->base_data_offset = frag->moof_offset;
2099 if (flags & 0x02) frag->stsd_id = avio_rb32(pb);
2100 else frag->stsd_id = trex->stsd_id;
2102 frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
2103 frag->size = flags & 0x10 ? avio_rb32(pb) : trex->size;
2104 frag->flags = flags & 0x20 ? avio_rb32(pb) : trex->flags;
2105 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2109 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2111 c->chapter_track = avio_rb32(pb);
2115 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2119 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2121 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2123 return AVERROR(ENOMEM);
2124 c->trex_data = trex;
2125 trex = &c->trex_data[c->trex_count++];
2126 avio_r8(pb); /* version */
2127 avio_rb24(pb); /* flags */
2128 trex->track_id = avio_rb32(pb);
2129 trex->stsd_id = avio_rb32(pb);
2130 trex->duration = avio_rb32(pb);
2131 trex->size = avio_rb32(pb);
2132 trex->flags = avio_rb32(pb);
2136 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2138 MOVFragment *frag = &c->fragment;
2139 AVStream *st = NULL;
2140 MOVStreamContext *sc;
2144 int data_offset = 0;
2145 unsigned entries, first_sample_flags = frag->flags;
2146 int flags, distance, i;
2148 for (i = 0; i < c->fc->nb_streams; i++) {
2149 if (c->fc->streams[i]->id == frag->track_id) {
2150 st = c->fc->streams[i];
2155 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2159 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2161 avio_r8(pb); /* version */
2162 flags = avio_rb24(pb);
2163 entries = avio_rb32(pb);
2164 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2166 /* Always assume the presence of composition time offsets.
2167 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2168 * 1) in the initial movie, there are no samples.
2169 * 2) in the first movie fragment, there is only one sample without composition time offset.
2170 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2171 if (!sc->ctts_count && sc->sample_count)
2173 /* Complement ctts table if moov atom doesn't have ctts atom. */
2174 ctts_data = av_malloc(sizeof(*sc->ctts_data));
2176 return AVERROR(ENOMEM);
2177 sc->ctts_data = ctts_data;
2178 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2179 sc->ctts_data[sc->ctts_count].duration = 0;
2182 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2184 ctts_data = av_realloc(sc->ctts_data,
2185 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2187 return AVERROR(ENOMEM);
2188 sc->ctts_data = ctts_data;
2190 if (flags & 0x001) data_offset = avio_rb32(pb);
2191 if (flags & 0x004) first_sample_flags = avio_rb32(pb);
2192 dts = st->duration - sc->time_offset;
2193 offset = frag->base_data_offset + data_offset;
2195 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2196 for (i = 0; i < entries; i++) {
2197 unsigned sample_size = frag->size;
2198 int sample_flags = i ? frag->flags : first_sample_flags;
2199 unsigned sample_duration = frag->duration;
2202 if (flags & 0x100) sample_duration = avio_rb32(pb);
2203 if (flags & 0x200) sample_size = avio_rb32(pb);
2204 if (flags & 0x400) sample_flags = avio_rb32(pb);
2205 sc->ctts_data[sc->ctts_count].count = 1;
2206 sc->ctts_data[sc->ctts_count].duration = (flags & 0x800) ? avio_rb32(pb) : 0;
2208 if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
2209 (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
2211 av_add_index_entry(st, offset, dts, sample_size, distance,
2212 keyframe ? AVINDEX_KEYFRAME : 0);
2213 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2214 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2215 offset, dts, sample_size, distance, keyframe);
2217 dts += sample_duration;
2218 offset += sample_size;
2220 frag->moof_offset = offset;
2221 st->duration = dts + sc->time_offset;
2225 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2226 /* like the files created with Adobe Premiere 5.0, for samples see */
2227 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2228 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2233 return 0; /* continue */
2234 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2235 avio_skip(pb, atom.size - 4);
2238 atom.type = avio_rl32(pb);
2240 if (atom.type != MKTAG('m','d','a','t')) {
2241 avio_skip(pb, atom.size);
2244 err = mov_read_mdat(c, pb, atom);
2248 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2253 uint8_t *moov_data; /* uncompressed data */
2254 long cmov_len, moov_len;
2257 avio_rb32(pb); /* dcom atom */
2258 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2260 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2261 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2264 avio_rb32(pb); /* cmvd atom */
2265 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2267 moov_len = avio_rb32(pb); /* uncompressed size */
2268 cmov_len = atom.size - 6 * 4;
2270 cmov_data = av_malloc(cmov_len);
2272 return AVERROR(ENOMEM);
2273 moov_data = av_malloc(moov_len);
2276 return AVERROR(ENOMEM);
2278 avio_read(pb, cmov_data, cmov_len);
2279 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2280 goto free_and_return;
2281 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2282 goto free_and_return;
2283 atom.type = MKTAG('m','o','o','v');
2284 atom.size = moov_len;
2285 ret = mov_read_default(c, &ctx, atom);
2291 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2296 /* edit list atom */
2297 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2299 MOVStreamContext *sc;
2300 int i, edit_count, version;
2302 if (c->fc->nb_streams < 1)
2304 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2306 version = avio_r8(pb); /* version */
2307 avio_rb24(pb); /* flags */
2308 edit_count = avio_rb32(pb); /* entries */
2310 if ((uint64_t)edit_count*12+8 > atom.size)
2313 for (i=0; i<edit_count; i++){
2317 duration = avio_rb64(pb);
2318 time = avio_rb64(pb);
2320 duration = avio_rb32(pb); /* segment duration */
2321 time = (int32_t)avio_rb32(pb); /* media time */
2323 avio_rb32(pb); /* Media rate */
2324 if (i == 0 && time >= -1) {
2325 sc->time_offset = time != -1 ? time : -duration;
2330 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2331 "a/v desync might occur, patch welcome\n");
2333 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2337 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2340 return AVERROR_INVALIDDATA;
2342 ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
2346 static const MOVParseTableEntry mov_default_parse_table[] = {
2347 { MKTAG('a','v','s','s'), mov_read_avss },
2348 { MKTAG('c','h','p','l'), mov_read_chpl },
2349 { MKTAG('c','o','6','4'), mov_read_stco },
2350 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2351 { MKTAG('d','i','n','f'), mov_read_default },
2352 { MKTAG('d','r','e','f'), mov_read_dref },
2353 { MKTAG('e','d','t','s'), mov_read_default },
2354 { MKTAG('e','l','s','t'), mov_read_elst },
2355 { MKTAG('e','n','d','a'), mov_read_enda },
2356 { MKTAG('f','i','e','l'), mov_read_fiel },
2357 { MKTAG('f','t','y','p'), mov_read_ftyp },
2358 { MKTAG('g','l','b','l'), mov_read_glbl },
2359 { MKTAG('h','d','l','r'), mov_read_hdlr },
2360 { MKTAG('i','l','s','t'), mov_read_ilst },
2361 { MKTAG('j','p','2','h'), mov_read_jp2h },
2362 { MKTAG('m','d','a','t'), mov_read_mdat },
2363 { MKTAG('m','d','h','d'), mov_read_mdhd },
2364 { MKTAG('m','d','i','a'), mov_read_default },
2365 { MKTAG('m','e','t','a'), mov_read_meta },
2366 { MKTAG('m','i','n','f'), mov_read_default },
2367 { MKTAG('m','o','o','f'), mov_read_moof },
2368 { MKTAG('m','o','o','v'), mov_read_moov },
2369 { MKTAG('m','v','e','x'), mov_read_default },
2370 { MKTAG('m','v','h','d'), mov_read_mvhd },
2371 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2372 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
2373 { MKTAG('a','v','c','C'), mov_read_glbl },
2374 { MKTAG('p','a','s','p'), mov_read_pasp },
2375 { MKTAG('s','t','b','l'), mov_read_default },
2376 { MKTAG('s','t','c','o'), mov_read_stco },
2377 { MKTAG('s','t','p','s'), mov_read_stps },
2378 { MKTAG('s','t','r','f'), mov_read_strf },
2379 { MKTAG('s','t','s','c'), mov_read_stsc },
2380 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2381 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2382 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2383 { MKTAG('s','t','t','s'), mov_read_stts },
2384 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2385 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2386 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2387 { MKTAG('t','r','a','k'), mov_read_trak },
2388 { MKTAG('t','r','a','f'), mov_read_default },
2389 { MKTAG('t','r','e','f'), mov_read_default },
2390 { MKTAG('c','h','a','p'), mov_read_chap },
2391 { MKTAG('t','r','e','x'), mov_read_trex },
2392 { MKTAG('t','r','u','n'), mov_read_trun },
2393 { MKTAG('u','d','t','a'), mov_read_default },
2394 { MKTAG('w','a','v','e'), mov_read_wave },
2395 { MKTAG('e','s','d','s'), mov_read_esds },
2396 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2397 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2398 { MKTAG('w','f','e','x'), mov_read_wfex },
2399 { MKTAG('c','m','o','v'), mov_read_cmov },
2400 { MKTAG('c','h','a','n'), mov_read_chan },
2404 static int mov_probe(AVProbeData *p)
2406 unsigned int offset;
2410 /* check file header */
2413 /* ignore invalid offset */
2414 if ((offset + 8) > (unsigned int)p->buf_size)
2416 tag = AV_RL32(p->buf + offset + 4);
2418 /* check for obvious tags */
2419 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2420 case MKTAG('m','o','o','v'):
2421 case MKTAG('m','d','a','t'):
2422 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2423 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2424 case MKTAG('f','t','y','p'):
2425 return AVPROBE_SCORE_MAX;
2426 /* those are more common words, so rate then a bit less */
2427 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2428 case MKTAG('w','i','d','e'):
2429 case MKTAG('f','r','e','e'):
2430 case MKTAG('j','u','n','k'):
2431 case MKTAG('p','i','c','t'):
2432 return AVPROBE_SCORE_MAX - 5;
2433 case MKTAG(0x82,0x82,0x7f,0x7d):
2434 case MKTAG('s','k','i','p'):
2435 case MKTAG('u','u','i','d'):
2436 case MKTAG('p','r','f','l'):
2437 offset = AV_RB32(p->buf+offset) + offset;
2438 /* if we only find those cause probedata is too small at least rate them */
2439 score = AVPROBE_SCORE_MAX - 50;
2442 /* unrecognized tag */
2448 // must be done after parsing all trak because there's no order requirement
2449 static void mov_read_chapters(AVFormatContext *s)
2451 MOVContext *mov = s->priv_data;
2452 AVStream *st = NULL;
2453 MOVStreamContext *sc;
2457 for (i = 0; i < s->nb_streams; i++)
2458 if (s->streams[i]->id == mov->chapter_track) {
2463 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2467 st->discard = AVDISCARD_ALL;
2469 cur_pos = avio_tell(sc->pb);
2471 for (i = 0; i < st->nb_index_entries; i++) {
2472 AVIndexEntry *sample = &st->index_entries[i];
2473 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2478 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2479 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2483 // the first two bytes are the length of the title
2484 len = avio_rb16(sc->pb);
2485 if (len > sample->size-2)
2487 title_len = 2*len + 1;
2488 if (!(title = av_mallocz(title_len)))
2491 // The samples could theoretically be in any encoding if there's an encd
2492 // atom following, but in practice are only utf-8 or utf-16, distinguished
2493 // instead by the presence of a BOM
2497 ch = avio_rb16(sc->pb);
2499 avio_get_str16be(sc->pb, len, title, title_len);
2500 else if (ch == 0xfffe)
2501 avio_get_str16le(sc->pb, len, title, title_len);
2504 if (len == 1 || len == 2)
2507 get_strz(sc->pb, title + 2, len - 1);
2511 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2515 avio_seek(sc->pb, cur_pos, SEEK_SET);
2518 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
2520 MOVContext *mov = s->priv_data;
2521 AVIOContext *pb = s->pb;
2523 MOVAtom atom = { AV_RL32("root") };
2526 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2528 atom.size = avio_size(pb);
2530 atom.size = INT64_MAX;
2532 /* check MOV header */
2533 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2534 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2537 if (!mov->found_moov) {
2538 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2541 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2543 if (pb->seekable && mov->chapter_track > 0)
2544 mov_read_chapters(s);
2549 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2551 AVIndexEntry *sample = NULL;
2552 int64_t best_dts = INT64_MAX;
2554 for (i = 0; i < s->nb_streams; i++) {
2555 AVStream *avst = s->streams[i];
2556 MOVStreamContext *msc = avst->priv_data;
2557 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2558 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2559 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2560 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2561 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2563 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2564 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2565 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2566 sample = current_sample;
2575 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2577 MOVContext *mov = s->priv_data;
2578 MOVStreamContext *sc;
2579 AVIndexEntry *sample;
2580 AVStream *st = NULL;
2583 sample = mov_find_next_sample(s, &st);
2585 mov->found_mdat = 0;
2586 if (s->pb->seekable||
2587 mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2590 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2594 /* must be done just before reading, to avoid infinite loop on sample */
2595 sc->current_sample++;
2597 if (st->discard != AVDISCARD_ALL) {
2598 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2599 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2600 sc->ffindex, sample->pos);
2603 ret = av_get_packet(sc->pb, pkt, sample->size);
2606 if (sc->has_palette) {
2609 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2611 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2613 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2614 sc->has_palette = 0;
2617 #if CONFIG_DV_DEMUXER
2618 if (mov->dv_demux && sc->dv_audio_container) {
2619 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
2622 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
2629 pkt->stream_index = sc->ffindex;
2630 pkt->dts = sample->timestamp;
2631 if (sc->ctts_data) {
2632 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2633 /* update ctts context */
2635 if (sc->ctts_index < sc->ctts_count &&
2636 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2638 sc->ctts_sample = 0;
2641 pkt->dts = AV_NOPTS_VALUE;
2643 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2644 st->index_entries[sc->current_sample].timestamp : st->duration;
2645 pkt->duration = next_dts - pkt->dts;
2646 pkt->pts = pkt->dts;
2648 if (st->discard == AVDISCARD_ALL)
2650 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2651 pkt->pos = sample->pos;
2652 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2653 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2657 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2659 MOVStreamContext *sc = st->priv_data;
2660 int sample, time_sample;
2663 sample = av_index_search_timestamp(st, timestamp, flags);
2664 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2665 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2667 if (sample < 0) /* not sure what to do */
2669 sc->current_sample = sample;
2670 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2671 /* adjust ctts index */
2672 if (sc->ctts_data) {
2674 for (i = 0; i < sc->ctts_count; i++) {
2675 int next = time_sample + sc->ctts_data[i].count;
2676 if (next > sc->current_sample) {
2678 sc->ctts_sample = sc->current_sample - time_sample;
2687 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2690 int64_t seek_timestamp, timestamp;
2694 if (stream_index >= s->nb_streams)
2696 if (sample_time < 0)
2699 st = s->streams[stream_index];
2700 sample = mov_seek_stream(s, st, sample_time, flags);
2704 /* adjust seek timestamp to found sample timestamp */
2705 seek_timestamp = st->index_entries[sample].timestamp;
2707 for (i = 0; i < s->nb_streams; i++) {
2709 if (stream_index == i)
2712 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2713 mov_seek_stream(s, st, timestamp, flags);
2718 static int mov_read_close(AVFormatContext *s)
2720 MOVContext *mov = s->priv_data;
2723 for (i = 0; i < s->nb_streams; i++) {
2724 AVStream *st = s->streams[i];
2725 MOVStreamContext *sc = st->priv_data;
2727 av_freep(&sc->ctts_data);
2728 for (j = 0; j < sc->drefs_count; j++) {
2729 av_freep(&sc->drefs[j].path);
2730 av_freep(&sc->drefs[j].dir);
2732 av_freep(&sc->drefs);
2733 if (sc->pb && sc->pb != s->pb)
2737 if (mov->dv_demux) {
2738 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2739 av_freep(&mov->dv_fctx->streams[i]->codec);
2740 av_freep(&mov->dv_fctx->streams[i]);
2742 av_freep(&mov->dv_fctx);
2743 av_freep(&mov->dv_demux);
2746 av_freep(&mov->trex_data);
2751 AVInputFormat ff_mov_demuxer = {
2752 .name = "mov,mp4,m4a,3gp,3g2,mj2",
2753 .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2754 .priv_data_size = sizeof(MOVContext),
2755 .read_probe = mov_probe,
2756 .read_header = mov_read_header,
2757 .read_packet = mov_read_packet,
2758 .read_close = mov_read_close,
2759 .read_seek = mov_read_seek,