3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * first version by Francois Revol <revol@free.fr>
7 * seek function by Gael Chardon <gael.dev@4now.net>
9 * This file is part of Libav.
11 * Libav is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * Libav is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with Libav; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include "libavutil/attributes.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/intfloat.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/time_internal.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/dict.h"
38 #include "libavutil/opt.h"
39 #include "libavcodec/ac3tab.h"
42 #include "avio_internal.h"
45 #include "libavcodec/get_bits.h"
48 #include "replaygain.h"
54 #include "qtpalette.h"
60 /* those functions parse an atom */
61 /* links atom IDs to parse functions */
62 typedef struct MOVParseTableEntry {
64 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
67 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
69 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
70 unsigned len, const char *key)
74 short current, total = 0;
75 avio_rb16(pb); // unknown
76 current = avio_rb16(pb);
78 total = avio_rb16(pb);
80 snprintf(buf, sizeof(buf), "%d", current);
82 snprintf(buf, sizeof(buf), "%d/%d", current, total);
83 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
84 av_dict_set(&c->fc->metadata, key, buf, 0);
89 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
90 unsigned len, const char *key)
94 /* bypass padding bytes */
99 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
100 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
101 av_dict_set(&c->fc->metadata, key, buf, 0);
106 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
107 unsigned len, const char *key)
111 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
112 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
113 av_dict_set(&c->fc->metadata, key, buf, 0);
118 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
119 unsigned len, const char *key)
124 avio_r8(pb); // unknown
127 if (genre < 1 || genre > ID3v1_GENRE_MAX)
129 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
130 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
131 av_dict_set(&c->fc->metadata, key, buf, 0);
136 static const uint32_t mac_to_unicode[128] = {
137 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
138 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
139 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
140 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
141 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
142 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
143 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
144 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
145 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
146 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
147 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
148 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
149 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
150 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
151 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
152 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
155 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
156 char *dst, int dstlen)
159 char *end = dst+dstlen-1;
162 for (i = 0; i < len; i++) {
163 uint8_t t, c = avio_r8(pb);
164 if (c < 0x80 && p < end)
167 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
173 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
177 MOVStreamContext *sc;
182 case 0xd: id = AV_CODEC_ID_MJPEG; break;
183 case 0xe: id = AV_CODEC_ID_PNG; break;
184 case 0x1b: id = AV_CODEC_ID_BMP; break;
186 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
191 st = avformat_new_stream(c->fc, NULL);
193 return AVERROR(ENOMEM);
194 sc = av_mallocz(sizeof(*sc));
196 return AVERROR(ENOMEM);
199 ret = av_get_packet(pb, &pkt, len);
203 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
205 st->attached_pic = pkt;
206 st->attached_pic.stream_index = st->index;
207 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
209 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
210 st->codec->codec_id = id;
215 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
217 char language[4] = { 0 };
219 uint16_t langcode = 0;
220 double longitude, latitude;
221 const char *key = "location";
223 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4)
224 return AVERROR_INVALIDDATA;
226 avio_skip(pb, 4); // version+flags
227 langcode = avio_rb16(pb);
228 ff_mov_lang_to_iso639(langcode, language);
231 len -= avio_get_str(pb, len, buf, sizeof(buf)); // place name
233 return AVERROR_INVALIDDATA;
234 avio_skip(pb, 1); // role
238 return AVERROR_INVALIDDATA;
239 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
240 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
242 // Try to output in the same format as the ?xyz field
243 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f/", latitude, longitude);
244 if (*language && strcmp(language, "und")) {
246 snprintf(key2, sizeof(key2), "%s-%s", key, language);
247 av_dict_set(&c->fc->metadata, key2, buf, 0);
249 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
250 return av_dict_set(&c->fc->metadata, key, buf, 0);
253 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
256 char *str, key2[32], language[4] = {0};
257 const char *key = NULL;
258 uint16_t langcode = 0;
259 uint32_t data_type = 0, str_size, str_size_alloc;
260 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
263 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
264 case MKTAG(0xa9,'a','u','t'):
265 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
266 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
267 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
268 case MKTAG( 'c','p','r','t'):
269 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
270 case MKTAG(0xa9,'c','m','t'):
271 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
272 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
273 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
274 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
275 case MKTAG( 'g','n','r','e'): key = "genre";
276 parse = mov_metadata_gnre; break;
277 case MKTAG(0xa9,'t','o','o'):
278 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
279 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
280 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
281 case MKTAG( 'd','e','s','c'): key = "description";break;
282 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
283 case MKTAG( 't','v','s','h'): key = "show"; break;
284 case MKTAG( 't','v','e','n'): key = "episode_id";break;
285 case MKTAG( 't','v','n','n'): key = "network"; break;
286 case MKTAG( 't','r','k','n'): key = "track";
287 parse = mov_metadata_track_or_disc_number; break;
288 case MKTAG( 'd','i','s','k'): key = "disc";
289 parse = mov_metadata_track_or_disc_number; break;
290 case MKTAG( 't','v','e','s'): key = "episode_sort";
291 parse = mov_metadata_int8_bypass_padding; break;
292 case MKTAG( 't','v','s','n'): key = "season_number";
293 parse = mov_metadata_int8_bypass_padding; break;
294 case MKTAG( 's','t','i','k'): key = "media_type";
295 parse = mov_metadata_int8_no_padding; break;
296 case MKTAG( 'h','d','v','d'): key = "hd_video";
297 parse = mov_metadata_int8_no_padding; break;
298 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
299 parse = mov_metadata_int8_no_padding; break;
300 case MKTAG( 'l','o','c','i'):
301 return mov_metadata_loci(c, pb, atom.size);
304 if (c->itunes_metadata && atom.size > 8) {
305 int data_size = avio_rb32(pb);
306 int tag = avio_rl32(pb);
307 if (tag == MKTAG('d','a','t','a')) {
308 data_type = avio_rb32(pb); // type
309 avio_rb32(pb); // unknown
310 str_size = data_size - 16;
313 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
314 int ret = mov_read_covr(c, pb, data_type, str_size);
316 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
321 } else if (atom.size > 4 && key && !c->itunes_metadata) {
322 str_size = avio_rb16(pb); // string length
323 langcode = avio_rb16(pb);
324 ff_mov_lang_to_iso639(langcode, language);
327 str_size = atom.size;
329 if (c->export_all && !key) {
330 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
337 return AVERROR_INVALIDDATA;
339 // allocate twice as much as worst-case
340 str_size_alloc = str_size * 2;
341 str = av_malloc(str_size_alloc);
343 return AVERROR(ENOMEM);
346 parse(c, pb, str_size, key);
348 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
349 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
351 avio_read(pb, str, str_size);
354 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
355 av_dict_set(&c->fc->metadata, key, str, 0);
356 if (*language && strcmp(language, "und")) {
357 snprintf(key2, sizeof(key2), "%s-%s", key, language);
358 av_dict_set(&c->fc->metadata, key2, str, 0);
361 av_dlog(c->fc, "lang \"%3s\" ", language);
362 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
363 key, str, (char*)&atom.type, str_size_alloc, atom.size);
369 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
372 int i, nb_chapters, str_len, version;
375 if ((atom.size -= 5) < 0)
378 version = avio_r8(pb);
381 avio_rb32(pb); // ???
382 nb_chapters = avio_r8(pb);
384 for (i = 0; i < nb_chapters; i++) {
388 start = avio_rb64(pb);
389 str_len = avio_r8(pb);
391 if ((atom.size -= 9+str_len) < 0)
394 avio_read(pb, str, str_len);
396 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
401 #define MIN_DATA_ENTRY_BOX_SIZE 12
402 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
405 MOVStreamContext *sc;
408 if (c->fc->nb_streams < 1)
410 st = c->fc->streams[c->fc->nb_streams-1];
413 avio_rb32(pb); // version + flags
414 entries = avio_rb32(pb);
415 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
416 entries >= UINT_MAX / sizeof(*sc->drefs))
417 return AVERROR_INVALIDDATA;
419 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
421 return AVERROR(ENOMEM);
422 sc->drefs_count = entries;
424 for (i = 0; i < sc->drefs_count; i++) {
425 MOVDref *dref = &sc->drefs[i];
426 uint32_t size = avio_rb32(pb);
427 int64_t next = avio_tell(pb) + size - 4;
430 return AVERROR_INVALIDDATA;
432 dref->type = avio_rl32(pb);
433 avio_rb32(pb); // version + flags
434 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
436 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
437 /* macintosh alias record */
438 uint16_t volume_len, len;
443 volume_len = avio_r8(pb);
444 volume_len = FFMIN(volume_len, 27);
445 avio_read(pb, dref->volume, 27);
446 dref->volume[volume_len] = 0;
447 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
452 len = FFMIN(len, 63);
453 avio_read(pb, dref->filename, 63);
454 dref->filename[len] = 0;
455 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
459 /* read next level up_from_alias/down_to_target */
460 dref->nlvl_from = avio_rb16(pb);
461 dref->nlvl_to = avio_rb16(pb);
462 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
463 dref->nlvl_from, dref->nlvl_to);
467 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
470 type = avio_rb16(pb);
472 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
475 if (type == 2) { // absolute path
477 dref->path = av_mallocz(len+1);
479 return AVERROR(ENOMEM);
480 avio_read(pb, dref->path, len);
481 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
483 memmove(dref->path, dref->path+volume_len, len);
486 for (j = 0; j < len; j++)
487 if (dref->path[j] == ':')
489 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
490 } else if (type == 0) { // directory name
492 dref->dir = av_malloc(len+1);
494 return AVERROR(ENOMEM);
495 avio_read(pb, dref->dir, len);
497 for (j = 0; j < len; j++)
498 if (dref->dir[j] == ':')
500 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
505 avio_seek(pb, next, SEEK_SET);
510 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
514 uint32_t av_unused ctype;
516 if (c->fc->nb_streams < 1) // meta before first trak
519 st = c->fc->streams[c->fc->nb_streams-1];
521 avio_r8(pb); /* version */
522 avio_rb24(pb); /* flags */
525 ctype = avio_rl32(pb);
526 type = avio_rl32(pb); /* component subtype */
528 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
529 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
531 if (type == MKTAG('v','i','d','e'))
532 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
533 else if (type == MKTAG('s','o','u','n'))
534 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
535 else if (type == MKTAG('m','1','a',' '))
536 st->codec->codec_id = AV_CODEC_ID_MP2;
537 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
538 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
540 avio_rb32(pb); /* component manufacture */
541 avio_rb32(pb); /* component flags */
542 avio_rb32(pb); /* component flags mask */
547 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
552 if (fc->nb_streams < 1)
554 st = fc->streams[fc->nb_streams-1];
556 avio_rb32(pb); /* version + flags */
557 ff_mp4_read_descr(fc, pb, &tag);
558 if (tag == MP4ESDescrTag) {
559 ff_mp4_parse_es_descr(pb, NULL);
561 avio_rb16(pb); /* ID */
563 ff_mp4_read_descr(fc, pb, &tag);
564 if (tag == MP4DecConfigDescrTag)
565 ff_mp4_read_dec_config_descr(fc, st, pb);
569 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
571 return ff_mov_read_esds(c->fc, pb);
574 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
577 int ac3info, acmod, lfeon, bsmod;
579 if (c->fc->nb_streams < 1)
581 st = c->fc->streams[c->fc->nb_streams-1];
583 ac3info = avio_rb24(pb);
584 bsmod = (ac3info >> 14) & 0x7;
585 acmod = (ac3info >> 11) & 0x7;
586 lfeon = (ac3info >> 10) & 0x1;
587 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
588 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
590 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
591 st->codec->audio_service_type = bsmod;
592 if (st->codec->channels > 1 && bsmod == 0x7)
593 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
598 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
601 int eac3info, acmod, lfeon, bsmod;
603 if (c->fc->nb_streams < 1)
605 st = c->fc->streams[c->fc->nb_streams-1];
607 /* No need to parse fields for additional independent substreams and its
608 * associated dependent substreams since libavcodec's E-AC-3 decoder
609 * does not support them yet. */
610 avio_rb16(pb); /* data_rate and num_ind_sub */
611 eac3info = avio_rb24(pb);
612 bsmod = (eac3info >> 12) & 0x1f;
613 acmod = (eac3info >> 9) & 0x7;
614 lfeon = (eac3info >> 8) & 0x1;
615 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
617 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
618 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
619 st->codec->audio_service_type = bsmod;
620 if (st->codec->channels > 1 && bsmod == 0x7)
621 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
626 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
630 if (c->fc->nb_streams < 1)
632 st = c->fc->streams[c->fc->nb_streams-1];
637 /* skip version and flags */
640 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
645 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
649 if (c->fc->nb_streams < 1)
651 st = c->fc->streams[c->fc->nb_streams-1];
653 return ff_get_wav_header(pb, st->codec, atom.size);
656 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
658 const int num = avio_rb32(pb);
659 const int den = avio_rb32(pb);
662 if (c->fc->nb_streams < 1)
664 st = c->fc->streams[c->fc->nb_streams-1];
666 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
667 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
668 av_log(c->fc, AV_LOG_WARNING,
669 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
670 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
672 } else if (den != 0) {
673 st->sample_aspect_ratio.num = num;
674 st->sample_aspect_ratio.den = den;
679 /* this atom contains actual media data */
680 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
682 if (atom.size == 0) /* wrong one (MP4) */
685 return 0; /* now go for moov */
688 /* read major brand, minor version and compatible brands and store them as metadata */
689 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
693 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
694 char* comp_brands_str;
695 uint8_t type[5] = {0};
697 avio_read(pb, type, 4);
698 if (strcmp(type, "qt "))
700 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
701 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
702 minor_ver = avio_rb32(pb); /* minor version */
703 snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);
704 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
706 comp_brand_size = atom.size - 8;
707 if (comp_brand_size < 0)
708 return AVERROR_INVALIDDATA;
709 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
710 if (!comp_brands_str)
711 return AVERROR(ENOMEM);
712 avio_read(pb, comp_brands_str, comp_brand_size);
713 comp_brands_str[comp_brand_size] = 0;
714 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
715 av_freep(&comp_brands_str);
720 /* this atom should contain all header atoms */
721 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
725 if ((ret = mov_read_default(c, pb, atom)) < 0)
727 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
728 /* so we don't parse the whole file if over a network */
730 return 0; /* now go for mdat */
733 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
735 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
736 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
737 return mov_read_default(c, pb, atom);
740 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
744 struct tm *ptm, tmbuf;
745 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
746 ptm = gmtime_r(&time, &tmbuf);
748 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
749 av_dict_set(metadata, "creation_time", buffer, 0);
753 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
756 MOVStreamContext *sc;
758 char language[4] = {0};
760 time_t creation_time;
762 if (c->fc->nb_streams < 1)
764 st = c->fc->streams[c->fc->nb_streams-1];
767 if (sc->time_scale) {
768 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
769 return AVERROR_INVALIDDATA;
772 version = avio_r8(pb);
774 avpriv_request_sample(c->fc, "Version %d", version);
775 return AVERROR_PATCHWELCOME;
777 avio_rb24(pb); /* flags */
779 creation_time = avio_rb64(pb);
782 creation_time = avio_rb32(pb);
783 avio_rb32(pb); /* modification time */
785 mov_metadata_creation_time(&st->metadata, creation_time);
787 sc->time_scale = avio_rb32(pb);
788 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
790 lang = avio_rb16(pb); /* language */
791 if (ff_mov_lang_to_iso639(lang, language))
792 av_dict_set(&st->metadata, "language", language, 0);
793 avio_rb16(pb); /* quality */
798 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
800 time_t creation_time;
801 int version = avio_r8(pb); /* version */
802 avio_rb24(pb); /* flags */
805 creation_time = avio_rb64(pb);
808 creation_time = avio_rb32(pb);
809 avio_rb32(pb); /* modification time */
811 mov_metadata_creation_time(&c->fc->metadata, creation_time);
812 c->time_scale = avio_rb32(pb); /* time scale */
814 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
816 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
817 avio_rb32(pb); /* preferred scale */
819 avio_rb16(pb); /* preferred volume */
821 avio_skip(pb, 10); /* reserved */
823 avio_skip(pb, 36); /* display matrix */
825 avio_rb32(pb); /* preview time */
826 avio_rb32(pb); /* preview duration */
827 avio_rb32(pb); /* poster time */
828 avio_rb32(pb); /* selection time */
829 avio_rb32(pb); /* selection duration */
830 avio_rb32(pb); /* current time */
831 avio_rb32(pb); /* next track ID */
836 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
840 if (c->fc->nb_streams < 1)
842 st = c->fc->streams[c->fc->nb_streams-1];
844 if ((uint64_t)atom.size > (1<<30))
845 return AVERROR_INVALIDDATA;
847 // currently SVQ3 decoder expect full STSD header - so let's fake it
848 // this should be fixed and just SMI header should be passed
849 av_free(st->codec->extradata);
850 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
851 if (!st->codec->extradata)
852 return AVERROR(ENOMEM);
853 st->codec->extradata_size = 0x5a + atom.size;
854 memcpy(st->codec->extradata, "SVQ3", 4); // fake
855 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
856 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
860 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
865 if (c->fc->nb_streams < 1)
867 st = c->fc->streams[c->fc->nb_streams-1];
869 little_endian = avio_rb16(pb);
870 av_dlog(c->fc, "enda %d\n", little_endian);
871 if (little_endian == 1) {
872 switch (st->codec->codec_id) {
873 case AV_CODEC_ID_PCM_S24BE:
874 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
876 case AV_CODEC_ID_PCM_S32BE:
877 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
879 case AV_CODEC_ID_PCM_F32BE:
880 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
882 case AV_CODEC_ID_PCM_F64BE:
883 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
892 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
895 char color_parameter_type[5] = { 0 };
896 int color_primaries, color_trc, color_matrix;
898 if (c->fc->nb_streams < 1)
900 st = c->fc->streams[c->fc->nb_streams - 1];
902 avio_read(pb, color_parameter_type, 4);
903 if (strncmp(color_parameter_type, "nclx", 4) &&
904 strncmp(color_parameter_type, "nclc", 4)) {
905 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
906 color_parameter_type);
910 color_primaries = avio_rb16(pb);
911 color_trc = avio_rb16(pb);
912 color_matrix = avio_rb16(pb);
914 av_dlog(c->fc, "%s: pri %"PRIu16" trc %"PRIu16" matrix %"PRIu16"",
915 color_parameter_type, color_primaries, color_trc, color_matrix);
918 uint8_t color_range = avio_r8(pb) >> 7;
919 av_dlog(c->fc, " full %"PRIu8"", color_range)
921 st->codec->color_range = AVCOL_RANGE_JPEG;
923 st->codec->color_range = AVCOL_RANGE_MPEG;
924 /* 14496-12 references JPEG XR specs (rather than the more complete
925 * 23001-8) so some adjusting is required */
926 if (color_primaries >= AVCOL_PRI_FILM)
927 color_primaries = AVCOL_PRI_UNSPECIFIED;
928 if ((color_trc >= AVCOL_TRC_LINEAR &&
929 color_trc <= AVCOL_TRC_LOG_SQRT) ||
930 color_trc >= AVCOL_TRC_BT2020_10)
931 color_trc = AVCOL_TRC_UNSPECIFIED;
932 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
933 color_matrix = AVCOL_SPC_UNSPECIFIED;
934 st->codec->color_primaries = color_primaries;
935 st->codec->color_trc = color_trc;
936 st->codec->colorspace = color_matrix;
938 /* color primaries, Table 4-4 */
939 switch (color_primaries) {
940 case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
941 case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
942 case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
944 /* color transfer, Table 4-5 */
946 case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
947 case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
949 /* color matrix, Table 4-6 */
950 switch (color_matrix) {
951 case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
952 case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
953 case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
961 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
964 unsigned mov_field_order;
965 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
967 if (c->fc->nb_streams < 1) // will happen with jp2 files
969 st = c->fc->streams[c->fc->nb_streams-1];
971 return AVERROR_INVALIDDATA;
972 mov_field_order = avio_rb16(pb);
973 if ((mov_field_order & 0xFF00) == 0x0100)
974 decoded_field_order = AV_FIELD_PROGRESSIVE;
975 else if ((mov_field_order & 0xFF00) == 0x0200) {
976 switch (mov_field_order & 0xFF) {
977 case 0x01: decoded_field_order = AV_FIELD_TT;
979 case 0x06: decoded_field_order = AV_FIELD_BB;
981 case 0x09: decoded_field_order = AV_FIELD_TB;
983 case 0x0E: decoded_field_order = AV_FIELD_BT;
987 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
988 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
990 st->codec->field_order = decoded_field_order;
995 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
996 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1003 if (c->fc->nb_streams < 1) // will happen with jp2 files
1005 st= c->fc->streams[c->fc->nb_streams-1];
1006 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
1007 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1008 return AVERROR_INVALIDDATA;
1009 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
1010 st->codec->extradata_size = 0;
1013 buf = st->codec->extradata + st->codec->extradata_size;
1014 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
1015 AV_WB32( buf , atom.size + 8);
1016 AV_WL32( buf + 4, atom.type);
1017 avio_read(pb, buf + 8, atom.size);
1021 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1025 if (c->fc->nb_streams < 1)
1027 st = c->fc->streams[c->fc->nb_streams-1];
1029 if ((uint64_t)atom.size > (1<<30))
1030 return AVERROR_INVALIDDATA;
1032 if (st->codec->codec_id == AV_CODEC_ID_QDM2 || st->codec->codec_id == AV_CODEC_ID_QDMC) {
1033 // pass all frma atom to codec, needed at least for QDMC and QDM2
1034 av_free(st->codec->extradata);
1035 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1036 if (!st->codec->extradata)
1037 return AVERROR(ENOMEM);
1038 st->codec->extradata_size = atom.size;
1039 avio_read(pb, st->codec->extradata, atom.size);
1040 } else if (atom.size > 8) { /* to read frma, esds atoms */
1042 if ((ret = mov_read_default(c, pb, atom)) < 0)
1045 avio_skip(pb, atom.size);
1050 * This function reads atom content and puts data in extradata without tag
1051 * nor size unlike mov_read_extradata.
1053 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1057 if (c->fc->nb_streams < 1)
1059 st = c->fc->streams[c->fc->nb_streams-1];
1061 if ((uint64_t)atom.size > (1<<30))
1062 return AVERROR_INVALIDDATA;
1064 if (atom.size >= 10) {
1065 // Broken files created by legacy versions of libavformat will
1066 // wrap a whole fiel atom inside of a glbl atom.
1067 unsigned size = avio_rb32(pb);
1068 unsigned type = avio_rl32(pb);
1069 avio_seek(pb, -8, SEEK_CUR);
1070 if (type == MKTAG('f','i','e','l') && size == atom.size)
1071 return mov_read_default(c, pb, atom);
1073 av_free(st->codec->extradata);
1074 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1075 if (!st->codec->extradata)
1076 return AVERROR(ENOMEM);
1077 st->codec->extradata_size = atom.size;
1078 avio_read(pb, st->codec->extradata, atom.size);
1082 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1085 uint8_t profile_level;
1087 if (c->fc->nb_streams < 1)
1089 st = c->fc->streams[c->fc->nb_streams-1];
1091 if (atom.size >= (1<<28) || atom.size < 7)
1092 return AVERROR_INVALIDDATA;
1094 profile_level = avio_r8(pb);
1095 if ((profile_level & 0xf0) != 0xc0)
1098 av_free(st->codec->extradata);
1099 st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
1100 if (!st->codec->extradata)
1101 return AVERROR(ENOMEM);
1102 st->codec->extradata_size = atom.size - 7;
1103 avio_seek(pb, 6, SEEK_CUR);
1104 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
1109 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1110 * but can have extradata appended at the end after the 40 bytes belonging
1113 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1117 if (c->fc->nb_streams < 1)
1119 if (atom.size <= 40)
1121 st = c->fc->streams[c->fc->nb_streams-1];
1123 if ((uint64_t)atom.size > (1<<30))
1124 return AVERROR_INVALIDDATA;
1126 av_free(st->codec->extradata);
1127 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1128 if (!st->codec->extradata)
1129 return AVERROR(ENOMEM);
1130 st->codec->extradata_size = atom.size - 40;
1132 avio_read(pb, st->codec->extradata, atom.size - 40);
1136 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1139 MOVStreamContext *sc;
1140 unsigned int i, entries;
1142 if (c->fc->nb_streams < 1)
1144 st = c->fc->streams[c->fc->nb_streams-1];
1147 avio_r8(pb); /* version */
1148 avio_rb24(pb); /* flags */
1150 entries = avio_rb32(pb);
1154 if (entries >= UINT_MAX/sizeof(int64_t))
1155 return AVERROR_INVALIDDATA;
1157 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1158 if (!sc->chunk_offsets)
1159 return AVERROR(ENOMEM);
1160 sc->chunk_count = entries;
1162 if (atom.type == MKTAG('s','t','c','o'))
1163 for (i = 0; i < entries && !pb->eof_reached; i++)
1164 sc->chunk_offsets[i] = avio_rb32(pb);
1165 else if (atom.type == MKTAG('c','o','6','4'))
1166 for (i = 0; i < entries && !pb->eof_reached; i++)
1167 sc->chunk_offsets[i] = avio_rb64(pb);
1169 return AVERROR_INVALIDDATA;
1171 sc->chunk_count = i;
1173 if (pb->eof_reached)
1180 * Compute codec id for 'lpcm' tag.
1181 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1183 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1190 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1193 static int mov_codec_id(AVStream *st, uint32_t format)
1195 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1198 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1199 (format & 0xFFFF) == 'T' + ('S' << 8)))
1200 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1202 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1203 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1204 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1205 /* skip old asf mpeg4 tag */
1206 format && format != MKTAG('m','p','4','s')) {
1207 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1209 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1211 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1212 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
1213 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1215 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1219 st->codec->codec_tag = format;
1224 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1225 AVStream *st, MOVStreamContext *sc)
1227 uint8_t codec_name[32];
1228 unsigned int color_depth, len, j;
1229 int color_greyscale;
1232 avio_rb16(pb); /* version */
1233 avio_rb16(pb); /* revision level */
1234 avio_rb32(pb); /* vendor */
1235 avio_rb32(pb); /* temporal quality */
1236 avio_rb32(pb); /* spatial quality */
1238 st->codec->width = avio_rb16(pb); /* width */
1239 st->codec->height = avio_rb16(pb); /* height */
1241 avio_rb32(pb); /* horiz resolution */
1242 avio_rb32(pb); /* vert resolution */
1243 avio_rb32(pb); /* data size, always 0 */
1244 avio_rb16(pb); /* frames per samples */
1246 len = avio_r8(pb); /* codec name, pascal string */
1249 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1251 avio_skip(pb, 31 - len);
1254 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1256 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1257 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1258 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1259 /* Flash Media Server uses tag H263 with Sorenson Spark */
1260 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1261 !memcmp(codec_name, "Sorenson H263", 13))
1262 st->codec->codec_id = AV_CODEC_ID_FLV1;
1264 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1265 color_table_id = avio_rb16(pb); /* colortable id */
1266 av_dlog(c->fc, "depth %d, ctab id %d\n",
1267 st->codec->bits_per_coded_sample, color_table_id);
1268 /* figure out the palette situation */
1269 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1270 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1272 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1273 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1274 /* for palette traversal */
1275 unsigned int color_start, color_count, color_end;
1276 unsigned char r, g, b;
1278 if (color_greyscale) {
1279 int color_index, color_dec;
1280 /* compute the greyscale palette */
1281 st->codec->bits_per_coded_sample = color_depth;
1282 color_count = 1 << color_depth;
1284 color_dec = 256 / (color_count - 1);
1285 for (j = 0; j < color_count; j++) {
1286 r = g = b = color_index;
1287 sc->palette[j] = (r << 16) | (g << 8) | (b);
1288 color_index -= color_dec;
1289 if (color_index < 0)
1292 } else if (color_table_id) {
1293 const uint8_t *color_table;
1294 /* if flag bit 3 is set, use the default palette */
1295 color_count = 1 << color_depth;
1296 if (color_depth == 2)
1297 color_table = ff_qt_default_palette_4;
1298 else if (color_depth == 4)
1299 color_table = ff_qt_default_palette_16;
1301 color_table = ff_qt_default_palette_256;
1303 for (j = 0; j < color_count; j++) {
1304 r = color_table[j * 3 + 0];
1305 g = color_table[j * 3 + 1];
1306 b = color_table[j * 3 + 2];
1307 sc->palette[j] = (r << 16) | (g << 8) | (b);
1310 /* load the palette from the file */
1311 color_start = avio_rb32(pb);
1312 color_count = avio_rb16(pb);
1313 color_end = avio_rb16(pb);
1314 if ((color_start <= 255) && (color_end <= 255)) {
1315 for (j = color_start; j <= color_end; j++) {
1316 /* each R, G, or B component is 16 bits;
1317 * only use the top 8 bits; skip alpha bytes
1327 sc->palette[j] = (r << 16) | (g << 8) | (b);
1331 sc->has_palette = 1;
1335 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1336 AVStream *st, MOVStreamContext *sc)
1338 int bits_per_sample, flags;
1339 uint16_t version = avio_rb16(pb);
1341 avio_rb16(pb); /* revision level */
1342 avio_rb32(pb); /* vendor */
1344 st->codec->channels = avio_rb16(pb); /* channel count */
1345 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1346 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1348 sc->audio_cid = avio_rb16(pb);
1349 avio_rb16(pb); /* packet size = 0 */
1351 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1353 // Read QT version 1 fields. In version 0 these do not exist.
1354 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1357 sc->samples_per_frame = avio_rb32(pb);
1358 avio_rb32(pb); /* bytes per packet */
1359 sc->bytes_per_frame = avio_rb32(pb);
1360 avio_rb32(pb); /* bytes per sample */
1361 } else if (version == 2) {
1362 avio_rb32(pb); /* sizeof struct only */
1363 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1364 st->codec->channels = avio_rb32(pb);
1365 avio_rb32(pb); /* always 0x7F000000 */
1366 st->codec->bits_per_coded_sample = avio_rb32(pb);
1368 flags = avio_rb32(pb); /* lpcm format specific flag */
1369 sc->bytes_per_frame = avio_rb32(pb);
1370 sc->samples_per_frame = avio_rb32(pb);
1371 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1372 st->codec->codec_id =
1373 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1378 switch (st->codec->codec_id) {
1379 case AV_CODEC_ID_PCM_S8:
1380 case AV_CODEC_ID_PCM_U8:
1381 if (st->codec->bits_per_coded_sample == 16)
1382 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1384 case AV_CODEC_ID_PCM_S16LE:
1385 case AV_CODEC_ID_PCM_S16BE:
1386 if (st->codec->bits_per_coded_sample == 8)
1387 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1388 else if (st->codec->bits_per_coded_sample == 24)
1389 st->codec->codec_id =
1390 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1391 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1393 /* set values for old format before stsd version 1 appeared */
1394 case AV_CODEC_ID_MACE3:
1395 sc->samples_per_frame = 6;
1396 sc->bytes_per_frame = 2 * st->codec->channels;
1398 case AV_CODEC_ID_MACE6:
1399 sc->samples_per_frame = 6;
1400 sc->bytes_per_frame = 1 * st->codec->channels;
1402 case AV_CODEC_ID_ADPCM_IMA_QT:
1403 sc->samples_per_frame = 64;
1404 sc->bytes_per_frame = 34 * st->codec->channels;
1406 case AV_CODEC_ID_GSM:
1407 sc->samples_per_frame = 160;
1408 sc->bytes_per_frame = 33;
1414 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1415 if (bits_per_sample) {
1416 st->codec->bits_per_coded_sample = bits_per_sample;
1417 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1421 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1422 AVStream *st, MOVStreamContext *sc,
1425 // ttxt stsd contains display flags, justification, background
1426 // color, fonts, and default styles, so fake an atom to read it
1427 MOVAtom fake_atom = { .size = size };
1428 // mp4s contains a regular esds atom
1429 if (st->codec->codec_tag != AV_RL32("mp4s"))
1430 mov_read_glbl(c, pb, fake_atom);
1431 st->codec->width = sc->width;
1432 st->codec->height = sc->height;
1435 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1440 y = (ycbcr >> 16) & 0xFF;
1441 cr = (ycbcr >> 8) & 0xFF;
1444 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1445 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1446 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1448 return (r << 16) | (g << 8) | b;
1451 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1453 char buf[256] = {0};
1454 uint8_t *src = st->codec->extradata;
1457 if (st->codec->extradata_size != 64)
1460 if (st->codec->width > 0 && st->codec->height > 0)
1461 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1462 st->codec->width, st->codec->height);
1463 av_strlcat(buf, "palette: ", sizeof(buf));
1465 for (i = 0; i < 16; i++) {
1466 uint32_t yuv = AV_RB32(src + i * 4);
1467 uint32_t rgba = yuv_to_rgba(yuv);
1469 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1472 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1475 av_freep(&st->codec->extradata);
1476 st->codec->extradata_size = 0;
1477 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1478 if (!st->codec->extradata)
1479 return AVERROR(ENOMEM);
1480 st->codec->extradata_size = strlen(buf);
1481 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1486 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1487 AVStream *st, MOVStreamContext *sc,
1490 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1491 st->codec->extradata_size = size;
1492 st->codec->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
1493 if (!st->codec->extradata)
1494 return AVERROR(ENOMEM);
1495 avio_read(pb, st->codec->extradata, size);
1497 /* other codec type, just skip (rtp, mp4s ...) */
1498 avio_skip(pb, size);
1503 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1504 AVStream *st, MOVStreamContext *sc)
1506 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1507 !st->codec->sample_rate && sc->time_scale > 1)
1508 st->codec->sample_rate = sc->time_scale;
1510 /* special codec parameters handling */
1511 switch (st->codec->codec_id) {
1512 #if CONFIG_DV_DEMUXER
1513 case AV_CODEC_ID_DVAUDIO:
1514 c->dv_fctx = avformat_alloc_context();
1515 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1517 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1518 return AVERROR(ENOMEM);
1520 sc->dv_audio_container = 1;
1521 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1524 /* no ifdef since parameters are always those */
1525 case AV_CODEC_ID_QCELP:
1526 st->codec->channels = 1;
1527 // force sample rate for qcelp when not stored in mov
1528 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1529 st->codec->sample_rate = 8000;
1531 case AV_CODEC_ID_AMR_NB:
1532 st->codec->channels = 1;
1533 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1534 st->codec->sample_rate = 8000;
1536 case AV_CODEC_ID_AMR_WB:
1537 st->codec->channels = 1;
1538 st->codec->sample_rate = 16000;
1540 case AV_CODEC_ID_MP2:
1541 case AV_CODEC_ID_MP3:
1542 /* force type after stsd for m1a hdlr */
1543 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1544 st->need_parsing = AVSTREAM_PARSE_FULL;
1546 case AV_CODEC_ID_GSM:
1547 case AV_CODEC_ID_ADPCM_MS:
1548 case AV_CODEC_ID_ADPCM_IMA_WAV:
1549 case AV_CODEC_ID_ILBC:
1550 st->codec->block_align = sc->bytes_per_frame;
1552 case AV_CODEC_ID_ALAC:
1553 if (st->codec->extradata_size == 36) {
1554 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1555 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1558 case AV_CODEC_ID_VC1:
1559 st->need_parsing = AVSTREAM_PARSE_FULL;
1567 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1568 int codec_tag, int format,
1571 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1574 (codec_tag == AV_RL32("avc1") ||
1575 codec_tag == AV_RL32("hvc1") ||
1576 codec_tag == AV_RL32("hev1") ||
1577 (codec_tag != format &&
1578 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1579 : codec_tag != MKTAG('j','p','e','g'))))) {
1580 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1581 * export it as a separate AVStream but this needs a few changes
1582 * in the MOV demuxer, patch welcome. */
1584 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1585 avio_skip(pb, size);
1592 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1595 MOVStreamContext *sc;
1596 int pseudo_stream_id;
1598 if (c->fc->nb_streams < 1)
1600 st = c->fc->streams[c->fc->nb_streams-1];
1603 for (pseudo_stream_id = 0;
1604 pseudo_stream_id < entries && !pb->eof_reached;
1605 pseudo_stream_id++) {
1606 //Parsing Sample description table
1608 int ret, dref_id = 1;
1609 MOVAtom a = { AV_RL32("stsd") };
1610 int64_t start_pos = avio_tell(pb);
1611 uint32_t size = avio_rb32(pb); /* size */
1612 uint32_t format = avio_rl32(pb); /* data format */
1615 avio_rb32(pb); /* reserved */
1616 avio_rb16(pb); /* reserved */
1617 dref_id = avio_rb16(pb);
1619 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRIu32" in stsd\n", size);
1620 return AVERROR_INVALIDDATA;
1623 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1624 size - (avio_tell(pb) - start_pos)))
1627 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1628 sc->dref_id= dref_id;
1630 id = mov_codec_id(st, format);
1632 av_dlog(c->fc, "size=%"PRIu32" 4CC= %"PRIu8"%"PRIu8"%"PRIu8"%"PRIu8" codec_type=%d\n", size,
1633 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1634 (format >> 24) & 0xff, st->codec->codec_type);
1636 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1637 st->codec->codec_id = id;
1638 mov_parse_stsd_video(c, pb, st, sc);
1639 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1640 st->codec->codec_id = id;
1641 mov_parse_stsd_audio(c, pb, st, sc);
1642 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1643 st->codec->codec_id = id;
1644 mov_parse_stsd_subtitle(c, pb, st, sc,
1645 size - (avio_tell(pb) - start_pos));
1647 ret = mov_parse_stsd_data(c, pb, st, sc,
1648 size - (avio_tell(pb) - start_pos));
1652 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1653 a.size = size - (avio_tell(pb) - start_pos);
1655 if ((ret = mov_read_default(c, pb, a)) < 0)
1657 } else if (a.size > 0)
1658 avio_skip(pb, a.size);
1661 if (pb->eof_reached)
1664 return mov_finalize_stsd_codec(c, pb, st, sc);
1667 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1671 avio_r8(pb); /* version */
1672 avio_rb24(pb); /* flags */
1673 entries = avio_rb32(pb);
1675 return ff_mov_read_stsd_entries(c, pb, entries);
1678 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1681 MOVStreamContext *sc;
1682 unsigned int i, entries;
1684 if (c->fc->nb_streams < 1)
1686 st = c->fc->streams[c->fc->nb_streams-1];
1689 avio_r8(pb); /* version */
1690 avio_rb24(pb); /* flags */
1692 entries = avio_rb32(pb);
1694 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1698 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1699 return AVERROR_INVALIDDATA;
1700 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1702 return AVERROR(ENOMEM);
1704 for (i = 0; i < entries && !pb->eof_reached; i++) {
1705 sc->stsc_data[i].first = avio_rb32(pb);
1706 sc->stsc_data[i].count = avio_rb32(pb);
1707 sc->stsc_data[i].id = avio_rb32(pb);
1712 if (pb->eof_reached)
1718 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1721 MOVStreamContext *sc;
1722 unsigned i, entries;
1724 if (c->fc->nb_streams < 1)
1726 st = c->fc->streams[c->fc->nb_streams-1];
1729 avio_rb32(pb); // version + flags
1731 entries = avio_rb32(pb);
1732 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1733 return AVERROR_INVALIDDATA;
1734 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1736 return AVERROR(ENOMEM);
1738 for (i = 0; i < entries && !pb->eof_reached; i++) {
1739 sc->stps_data[i] = avio_rb32(pb);
1740 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1745 if (pb->eof_reached)
1751 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1754 MOVStreamContext *sc;
1755 unsigned int i, entries;
1757 if (c->fc->nb_streams < 1)
1759 st = c->fc->streams[c->fc->nb_streams-1];
1762 avio_r8(pb); /* version */
1763 avio_rb24(pb); /* flags */
1765 entries = avio_rb32(pb);
1767 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1771 sc->keyframe_absent = 1;
1774 if (entries >= UINT_MAX / sizeof(int))
1775 return AVERROR_INVALIDDATA;
1776 sc->keyframes = av_malloc(entries * sizeof(int));
1778 return AVERROR(ENOMEM);
1780 for (i = 0; i < entries && !pb->eof_reached; i++) {
1781 sc->keyframes[i] = avio_rb32(pb);
1782 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1785 sc->keyframe_count = i;
1787 if (pb->eof_reached)
1793 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1796 MOVStreamContext *sc;
1797 unsigned int i, entries, sample_size, field_size, num_bytes;
1801 if (c->fc->nb_streams < 1)
1803 st = c->fc->streams[c->fc->nb_streams-1];
1806 avio_r8(pb); /* version */
1807 avio_rb24(pb); /* flags */
1809 if (atom.type == MKTAG('s','t','s','z')) {
1810 sample_size = avio_rb32(pb);
1811 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1812 sc->sample_size = sample_size;
1816 avio_rb24(pb); /* reserved */
1817 field_size = avio_r8(pb);
1819 entries = avio_rb32(pb);
1821 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1823 sc->sample_count = entries;
1827 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1828 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1829 return AVERROR_INVALIDDATA;
1834 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1835 return AVERROR_INVALIDDATA;
1836 sc->sample_sizes = av_malloc(entries * sizeof(int));
1837 if (!sc->sample_sizes)
1838 return AVERROR(ENOMEM);
1840 num_bytes = (entries*field_size+4)>>3;
1842 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1844 av_freep(&sc->sample_sizes);
1845 return AVERROR(ENOMEM);
1848 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1849 av_freep(&sc->sample_sizes);
1851 return AVERROR_INVALIDDATA;
1854 init_get_bits(&gb, buf, 8*num_bytes);
1856 for (i = 0; i < entries && !pb->eof_reached; i++) {
1857 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1858 sc->data_size += sc->sample_sizes[i];
1861 sc->sample_count = i;
1863 if (pb->eof_reached)
1870 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1873 MOVStreamContext *sc;
1874 unsigned int i, entries;
1876 int64_t total_sample_count=0;
1878 if (c->fc->nb_streams < 1)
1880 st = c->fc->streams[c->fc->nb_streams-1];
1883 avio_r8(pb); /* version */
1884 avio_rb24(pb); /* flags */
1885 entries = avio_rb32(pb);
1887 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1888 c->fc->nb_streams-1, entries);
1892 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1893 return AVERROR(EINVAL);
1895 av_free(sc->stts_data);
1896 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1898 return AVERROR(ENOMEM);
1900 for (i = 0; i < entries && !pb->eof_reached; i++) {
1901 int sample_duration;
1904 sample_count=avio_rb32(pb);
1905 sample_duration = avio_rb32(pb);
1906 if (sample_count < 0) {
1907 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
1908 return AVERROR_INVALIDDATA;
1910 sc->stts_data[i].count= sample_count;
1911 sc->stts_data[i].duration= sample_duration;
1913 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1914 sample_count, sample_duration);
1916 duration+=(int64_t)sample_duration*sample_count;
1917 total_sample_count+=sample_count;
1922 if (pb->eof_reached)
1925 st->nb_frames= total_sample_count;
1927 st->duration= duration;
1928 sc->track_end = duration;
1932 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1935 MOVStreamContext *sc;
1936 unsigned int i, entries;
1938 if (c->fc->nb_streams < 1)
1940 st = c->fc->streams[c->fc->nb_streams-1];
1943 avio_r8(pb); /* version */
1944 avio_rb24(pb); /* flags */
1945 entries = avio_rb32(pb);
1947 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1951 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1952 return AVERROR_INVALIDDATA;
1953 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1955 return AVERROR(ENOMEM);
1957 for (i = 0; i < entries && !pb->eof_reached; i++) {
1958 int count =avio_rb32(pb);
1959 int duration =avio_rb32(pb);
1961 sc->ctts_data[i].count = count;
1962 sc->ctts_data[i].duration= duration;
1964 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1969 if (pb->eof_reached)
1972 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1977 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1980 MOVStreamContext *sc;
1981 unsigned int i, entries;
1983 uint32_t grouping_type;
1985 if (c->fc->nb_streams < 1)
1987 st = c->fc->streams[c->fc->nb_streams-1];
1990 version = avio_r8(pb); /* version */
1991 avio_rb24(pb); /* flags */
1992 grouping_type = avio_rl32(pb);
1993 if (grouping_type != MKTAG( 'r','a','p',' '))
1994 return 0; /* only support 'rap ' grouping */
1996 avio_rb32(pb); /* grouping_type_parameter */
1998 entries = avio_rb32(pb);
2001 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2002 return AVERROR_INVALIDDATA;
2003 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2005 return AVERROR(ENOMEM);
2007 for (i = 0; i < entries && !pb->eof_reached; i++) {
2008 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2009 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2012 sc->rap_group_count = i;
2014 return pb->eof_reached ? AVERROR_EOF : 0;
2017 static void mov_build_index(MOVContext *mov, AVStream *st)
2019 MOVStreamContext *sc = st->priv_data;
2020 int64_t current_offset;
2021 int64_t current_dts = 0;
2022 unsigned int stts_index = 0;
2023 unsigned int stsc_index = 0;
2024 unsigned int stss_index = 0;
2025 unsigned int stps_index = 0;
2027 uint64_t stream_size = 0;
2029 /* adjust first dts according to edit list */
2030 if (sc->time_offset && mov->time_scale > 0) {
2031 if (sc->time_offset < 0)
2032 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
2033 current_dts = -sc->time_offset;
2034 if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
2035 sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
2036 /* more than 16 frames delay, dts are likely wrong
2037 this happens with files created by iMovie */
2039 st->codec->has_b_frames = 1;
2043 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2044 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2045 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2046 unsigned int current_sample = 0;
2047 unsigned int stts_sample = 0;
2048 unsigned int sample_size;
2049 unsigned int distance = 0;
2050 unsigned int rap_group_index = 0;
2051 unsigned int rap_group_sample = 0;
2052 int rap_group_present = sc->rap_group_count && sc->rap_group;
2053 int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
2055 current_dts -= sc->dts_shift;
2057 if (!sc->sample_count)
2059 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2061 if (av_reallocp_array(&st->index_entries,
2062 st->nb_index_entries + sc->sample_count,
2063 sizeof(*st->index_entries)) < 0) {
2064 st->nb_index_entries = 0;
2067 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2069 for (i = 0; i < sc->chunk_count; i++) {
2070 current_offset = sc->chunk_offsets[i];
2071 while (stsc_index + 1 < sc->stsc_count &&
2072 i + 1 == sc->stsc_data[stsc_index + 1].first)
2074 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2076 if (current_sample >= sc->sample_count) {
2077 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2081 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2083 if (stss_index + 1 < sc->keyframe_count)
2085 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2087 if (stps_index + 1 < sc->stps_count)
2090 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2091 if (sc->rap_group[rap_group_index].index > 0)
2093 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2094 rap_group_sample = 0;
2100 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
2101 if (sc->pseudo_stream_id == -1 ||
2102 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2103 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2104 e->pos = current_offset;
2105 e->timestamp = current_dts;
2106 e->size = sample_size;
2107 e->min_distance = distance;
2108 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2109 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2110 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2111 current_offset, current_dts, sample_size, distance, keyframe);
2114 current_offset += sample_size;
2115 stream_size += sample_size;
2116 current_dts += sc->stts_data[stts_index].duration;
2120 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2126 if (st->duration > 0)
2127 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2129 unsigned chunk_samples, total = 0;
2131 // compute total chunk count
2132 for (i = 0; i < sc->stsc_count; i++) {
2133 unsigned count, chunk_count;
2135 chunk_samples = sc->stsc_data[i].count;
2136 if (i != sc->stsc_count - 1 &&
2137 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2138 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2142 if (sc->samples_per_frame >= 160) { // gsm
2143 count = chunk_samples / sc->samples_per_frame;
2144 } else if (sc->samples_per_frame > 1) {
2145 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2146 count = (chunk_samples+samples-1) / samples;
2148 count = (chunk_samples+1023) / 1024;
2151 if (i < sc->stsc_count - 1)
2152 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2154 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2155 total += chunk_count * count;
2158 av_dlog(mov->fc, "chunk count %d\n", total);
2159 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2161 if (av_reallocp_array(&st->index_entries,
2162 st->nb_index_entries + total,
2163 sizeof(*st->index_entries)) < 0) {
2164 st->nb_index_entries = 0;
2167 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2170 for (i = 0; i < sc->chunk_count; i++) {
2171 current_offset = sc->chunk_offsets[i];
2172 if (stsc_index + 1 < sc->stsc_count &&
2173 i + 1 == sc->stsc_data[stsc_index + 1].first)
2175 chunk_samples = sc->stsc_data[stsc_index].count;
2177 while (chunk_samples > 0) {
2179 unsigned size, samples;
2181 if (sc->samples_per_frame >= 160) { // gsm
2182 samples = sc->samples_per_frame;
2183 size = sc->bytes_per_frame;
2185 if (sc->samples_per_frame > 1) {
2186 samples = FFMIN((1024 / sc->samples_per_frame)*
2187 sc->samples_per_frame, chunk_samples);
2188 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2190 samples = FFMIN(1024, chunk_samples);
2191 size = samples * sc->sample_size;
2195 if (st->nb_index_entries >= total) {
2196 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2199 e = &st->index_entries[st->nb_index_entries++];
2200 e->pos = current_offset;
2201 e->timestamp = current_dts;
2203 e->min_distance = 0;
2204 e->flags = AVINDEX_KEYFRAME;
2205 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2206 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2209 current_offset += size;
2210 current_dts += samples;
2211 chunk_samples -= samples;
2217 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
2218 AVIOInterruptCB *int_cb)
2220 /* try relative path, we do not try the absolute because it can leak information about our
2221 system to an attacker */
2222 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2223 char filename[1024];
2227 /* find a source dir */
2228 src_path = strrchr(src, '/');
2234 /* find a next level down to target */
2235 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2236 if (ref->path[l] == '/') {
2237 if (i == ref->nlvl_to - 1)
2243 /* compose filename if next level down to target was found */
2244 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2245 memcpy(filename, src, src_path - src);
2246 filename[src_path - src] = 0;
2248 for (i = 1; i < ref->nlvl_from; i++)
2249 av_strlcat(filename, "../", 1024);
2251 av_strlcat(filename, ref->path + l + 1, 1024);
2253 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2258 return AVERROR(ENOENT);
2261 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2264 MOVStreamContext *sc;
2267 st = avformat_new_stream(c->fc, NULL);
2268 if (!st) return AVERROR(ENOMEM);
2269 st->id = c->fc->nb_streams;
2270 sc = av_mallocz(sizeof(MOVStreamContext));
2271 if (!sc) return AVERROR(ENOMEM);
2274 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2275 sc->ffindex = st->index;
2277 if ((ret = mov_read_default(c, pb, atom)) < 0)
2281 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2282 (!sc->sample_size && !sc->sample_count))) {
2283 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2288 if (sc->time_scale <= 0) {
2289 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2290 sc->time_scale = c->time_scale;
2291 if (sc->time_scale <= 0)
2295 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2297 mov_build_index(c, st);
2299 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2300 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2301 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
2302 av_log(c->fc, AV_LOG_ERROR,
2303 "stream %d, error opening alias: path='%s', dir='%s', "
2304 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2305 st->index, dref->path, dref->dir, dref->filename,
2306 dref->volume, dref->nlvl_from, dref->nlvl_to);
2310 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2311 if (!st->sample_aspect_ratio.num &&
2312 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2313 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2314 ((double)st->codec->width * sc->height), INT_MAX);
2318 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2319 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2320 TAG_IS_AVCI(st->codec->codec_tag)) {
2321 ret = ff_generate_avci_extradata(st);
2326 switch (st->codec->codec_id) {
2327 #if CONFIG_H261_DECODER
2328 case AV_CODEC_ID_H261:
2330 #if CONFIG_H263_DECODER
2331 case AV_CODEC_ID_H263:
2333 #if CONFIG_MPEG4_DECODER
2334 case AV_CODEC_ID_MPEG4:
2336 st->codec->width = 0; /* let decoder init width/height */
2337 st->codec->height= 0;
2341 /* Do not need those anymore. */
2342 av_freep(&sc->chunk_offsets);
2343 av_freep(&sc->stsc_data);
2344 av_freep(&sc->sample_sizes);
2345 av_freep(&sc->keyframes);
2346 av_freep(&sc->stts_data);
2347 av_freep(&sc->stps_data);
2348 av_freep(&sc->rap_group);
2353 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2356 c->itunes_metadata = 1;
2357 ret = mov_read_default(c, pb, atom);
2358 c->itunes_metadata = 0;
2362 static int mov_read_replaygain(MOVContext *c, AVIOContext *pb, int size)
2364 int64_t end = avio_tell(pb) + size;
2365 uint8_t *key = NULL, *val = NULL;
2368 for (i = 0; i < 2; i++) {
2372 if (end - avio_tell(pb) <= 12)
2375 len = avio_rb32(pb);
2376 tag = avio_rl32(pb);
2377 avio_skip(pb, 4); // flags
2379 if (len < 12 || len - 12 > end - avio_tell(pb))
2383 if (tag == MKTAG('n', 'a', 'm', 'e'))
2385 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2392 *p = av_malloc(len + 1);
2395 avio_read(pb, *p, len);
2400 av_dict_set(&c->fc->metadata, key, val,
2401 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2405 avio_seek(pb, end, SEEK_SET);
2411 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2413 int64_t end = avio_tell(pb) + atom.size;
2419 len = avio_rb32(pb);
2420 tag = avio_rl32(pb);
2422 if (len > atom.size)
2425 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2426 uint8_t domain[128];
2429 avio_skip(pb, 4); // flags
2432 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2433 avio_skip(pb, len - domain_len);
2434 if (!strcmp(domain, "org.hydrogenaudio.replaygain"))
2435 return mov_read_replaygain(c, pb, end - avio_tell(pb));
2439 av_log(c->fc, AV_LOG_VERBOSE,
2440 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2444 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2446 while (atom.size > 8) {
2447 uint32_t tag = avio_rl32(pb);
2449 if (tag == MKTAG('h','d','l','r')) {
2450 avio_seek(pb, -8, SEEK_CUR);
2452 return mov_read_default(c, pb, atom);
2458 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2463 int64_t disp_transform[2];
2464 int display_matrix[3][3];
2466 MOVStreamContext *sc;
2470 if (c->fc->nb_streams < 1)
2472 st = c->fc->streams[c->fc->nb_streams-1];
2475 version = avio_r8(pb);
2476 flags = avio_rb24(pb);
2477 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2483 avio_rb32(pb); /* creation time */
2484 avio_rb32(pb); /* modification time */
2486 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2487 avio_rb32(pb); /* reserved */
2489 /* highlevel (considering edits) duration in movie timebase */
2490 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2491 avio_rb32(pb); /* reserved */
2492 avio_rb32(pb); /* reserved */
2494 avio_rb16(pb); /* layer */
2495 avio_rb16(pb); /* alternate group */
2496 avio_rb16(pb); /* volume */
2497 avio_rb16(pb); /* reserved */
2499 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2500 // they're kept in fixed point format through all calculations
2501 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2502 // side data, but the scale factor is not needed to calculate aspect ratio
2503 for (i = 0; i < 3; i++) {
2504 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2505 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2506 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2509 width = avio_rb32(pb); // 16.16 fixed point track width
2510 height = avio_rb32(pb); // 16.16 fixed point track height
2511 sc->width = width >> 16;
2512 sc->height = height >> 16;
2514 // save the matrix when it is not the default identity
2515 if (display_matrix[0][0] != (1 << 16) ||
2516 display_matrix[1][1] != (1 << 16) ||
2517 display_matrix[2][2] != (1 << 30) ||
2518 display_matrix[0][1] || display_matrix[0][2] ||
2519 display_matrix[1][0] || display_matrix[1][2] ||
2520 display_matrix[2][0] || display_matrix[2][1]) {
2523 av_freep(&sc->display_matrix);
2524 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2525 if (!sc->display_matrix)
2526 return AVERROR(ENOMEM);
2528 for (i = 0; i < 3; i++)
2529 for (j = 0; j < 3; j++)
2530 sc->display_matrix[i * 3 + j] = display_matrix[j][i];
2533 // transform the display width/height according to the matrix
2534 // skip this if the display matrix is the default identity matrix
2535 // or if it is rotating the picture, ex iPhone 3GS
2536 // to keep the same scale, use [width height 1<<16]
2537 if (width && height &&
2538 ((display_matrix[0][0] != 65536 ||
2539 display_matrix[1][1] != 65536) &&
2540 !display_matrix[0][1] &&
2541 !display_matrix[1][0] &&
2542 !display_matrix[2][0] && !display_matrix[2][1])) {
2543 for (i = 0; i < 2; i++)
2545 (int64_t) width * display_matrix[0][i] +
2546 (int64_t) height * display_matrix[1][i] +
2547 ((int64_t) display_matrix[2][i] << 16);
2549 //sample aspect ratio is new width/height divided by old width/height
2550 st->sample_aspect_ratio = av_d2q(
2551 ((double) disp_transform[0] * height) /
2552 ((double) disp_transform[1] * width), INT_MAX);
2557 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2559 MOVFragment *frag = &c->fragment;
2560 MOVTrackExt *trex = NULL;
2561 int flags, track_id, i;
2563 avio_r8(pb); /* version */
2564 flags = avio_rb24(pb);
2566 track_id = avio_rb32(pb);
2568 return AVERROR_INVALIDDATA;
2569 frag->track_id = track_id;
2570 for (i = 0; i < c->trex_count; i++)
2571 if (c->trex_data[i].track_id == frag->track_id) {
2572 trex = &c->trex_data[i];
2576 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2577 return AVERROR_INVALIDDATA;
2580 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2581 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
2582 frag->moof_offset : frag->implicit_offset;
2583 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2585 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2586 avio_rb32(pb) : trex->duration;
2587 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2588 avio_rb32(pb) : trex->size;
2589 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2590 avio_rb32(pb) : trex->flags;
2591 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2595 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2597 c->chapter_track = avio_rb32(pb);
2601 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2606 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2607 return AVERROR_INVALIDDATA;
2608 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2609 sizeof(*c->trex_data))) < 0) {
2613 trex = &c->trex_data[c->trex_count++];
2614 avio_r8(pb); /* version */
2615 avio_rb24(pb); /* flags */
2616 trex->track_id = avio_rb32(pb);
2617 trex->stsd_id = avio_rb32(pb);
2618 trex->duration = avio_rb32(pb);
2619 trex->size = avio_rb32(pb);
2620 trex->flags = avio_rb32(pb);
2624 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2626 MOVFragment *frag = &c->fragment;
2627 AVStream *st = NULL;
2628 MOVStreamContext *sc;
2631 for (i = 0; i < c->fc->nb_streams; i++) {
2632 if (c->fc->streams[i]->id == frag->track_id) {
2633 st = c->fc->streams[i];
2638 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2639 return AVERROR_INVALIDDATA;
2642 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
2644 version = avio_r8(pb);
2645 avio_rb24(pb); /* flags */
2647 sc->track_end = avio_rb64(pb);
2649 sc->track_end = avio_rb32(pb);
2654 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2656 MOVFragment *frag = &c->fragment;
2657 AVStream *st = NULL;
2658 MOVStreamContext *sc;
2662 int data_offset = 0;
2663 unsigned entries, first_sample_flags = frag->flags;
2664 int flags, distance, i, found_keyframe = 0, err;
2666 for (i = 0; i < c->fc->nb_streams; i++) {
2667 if (c->fc->streams[i]->id == frag->track_id) {
2668 st = c->fc->streams[i];
2673 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2674 return AVERROR_INVALIDDATA;
2677 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2679 avio_r8(pb); /* version */
2680 flags = avio_rb24(pb);
2681 entries = avio_rb32(pb);
2682 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2684 /* Always assume the presence of composition time offsets.
2685 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2686 * 1) in the initial movie, there are no samples.
2687 * 2) in the first movie fragment, there is only one sample without composition time offset.
2688 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2689 if (!sc->ctts_count && sc->sample_count)
2691 /* Complement ctts table if moov atom doesn't have ctts atom. */
2692 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2694 return AVERROR(ENOMEM);
2695 sc->ctts_data = ctts_data;
2696 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2697 sc->ctts_data[sc->ctts_count].duration = 0;
2700 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2701 return AVERROR_INVALIDDATA;
2702 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2703 sizeof(*sc->ctts_data))) < 0) {
2707 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2708 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2709 dts = sc->track_end - sc->time_offset;
2710 offset = frag->base_data_offset + data_offset;
2712 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2713 for (i = 0; i < entries && !pb->eof_reached; i++) {
2714 unsigned sample_size = frag->size;
2715 int sample_flags = i ? frag->flags : first_sample_flags;
2716 unsigned sample_duration = frag->duration;
2719 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2720 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2721 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2722 sc->ctts_data[sc->ctts_count].count = 1;
2723 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2726 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2728 else if (!found_keyframe)
2729 keyframe = found_keyframe =
2730 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2731 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2734 av_add_index_entry(st, offset, dts, sample_size, distance,
2735 keyframe ? AVINDEX_KEYFRAME : 0);
2736 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2737 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2738 offset, dts, sample_size, distance, keyframe);
2740 dts += sample_duration;
2741 offset += sample_size;
2742 sc->data_size += sample_size;
2745 if (pb->eof_reached)
2748 frag->implicit_offset = offset;
2749 st->duration = sc->track_end = dts + sc->time_offset;
2753 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2754 /* like the files created with Adobe Premiere 5.0, for samples see */
2755 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2756 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2761 return 0; /* continue */
2762 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2763 avio_skip(pb, atom.size - 4);
2766 atom.type = avio_rl32(pb);
2768 if (atom.type != MKTAG('m','d','a','t')) {
2769 avio_skip(pb, atom.size);
2772 err = mov_read_mdat(c, pb, atom);
2776 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2781 uint8_t *moov_data; /* uncompressed data */
2782 long cmov_len, moov_len;
2785 avio_rb32(pb); /* dcom atom */
2786 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2787 return AVERROR_INVALIDDATA;
2788 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2789 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2790 return AVERROR_INVALIDDATA;
2792 avio_rb32(pb); /* cmvd atom */
2793 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2794 return AVERROR_INVALIDDATA;
2795 moov_len = avio_rb32(pb); /* uncompressed size */
2796 cmov_len = atom.size - 6 * 4;
2798 cmov_data = av_malloc(cmov_len);
2800 return AVERROR(ENOMEM);
2801 moov_data = av_malloc(moov_len);
2804 return AVERROR(ENOMEM);
2806 avio_read(pb, cmov_data, cmov_len);
2807 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2808 goto free_and_return;
2809 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2810 goto free_and_return;
2811 atom.type = MKTAG('m','o','o','v');
2812 atom.size = moov_len;
2813 ret = mov_read_default(c, &ctx, atom);
2819 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2820 return AVERROR(ENOSYS);
2824 /* edit list atom */
2825 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2827 MOVStreamContext *sc;
2828 int i, edit_count, version;
2830 if (c->fc->nb_streams < 1)
2832 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2834 version = avio_r8(pb); /* version */
2835 avio_rb24(pb); /* flags */
2836 edit_count = avio_rb32(pb); /* entries */
2838 if ((uint64_t)edit_count*12+8 > atom.size)
2839 return AVERROR_INVALIDDATA;
2841 for (i=0; i<edit_count; i++){
2845 duration = avio_rb64(pb);
2846 time = avio_rb64(pb);
2848 duration = avio_rb32(pb); /* segment duration */
2849 time = (int32_t)avio_rb32(pb); /* media time */
2851 avio_rb32(pb); /* Media rate */
2852 if (i == 0 && time >= -1) {
2853 sc->time_offset = time != -1 ? time : -duration;
2858 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2859 "a/v desync might occur, patch welcome\n");
2861 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2865 static const MOVParseTableEntry mov_default_parse_table[] = {
2866 { MKTAG('a','v','s','s'), mov_read_extradata },
2867 { MKTAG('c','h','p','l'), mov_read_chpl },
2868 { MKTAG('c','o','6','4'), mov_read_stco },
2869 { MKTAG('c','o','l','r'), mov_read_colr },
2870 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2871 { MKTAG('d','i','n','f'), mov_read_default },
2872 { MKTAG('d','r','e','f'), mov_read_dref },
2873 { MKTAG('e','d','t','s'), mov_read_default },
2874 { MKTAG('e','l','s','t'), mov_read_elst },
2875 { MKTAG('e','n','d','a'), mov_read_enda },
2876 { MKTAG('f','i','e','l'), mov_read_fiel },
2877 { MKTAG('f','t','y','p'), mov_read_ftyp },
2878 { MKTAG('g','l','b','l'), mov_read_glbl },
2879 { MKTAG('h','d','l','r'), mov_read_hdlr },
2880 { MKTAG('i','l','s','t'), mov_read_ilst },
2881 { MKTAG('j','p','2','h'), mov_read_extradata },
2882 { MKTAG('m','d','a','t'), mov_read_mdat },
2883 { MKTAG('m','d','h','d'), mov_read_mdhd },
2884 { MKTAG('m','d','i','a'), mov_read_default },
2885 { MKTAG('m','e','t','a'), mov_read_meta },
2886 { MKTAG('m','i','n','f'), mov_read_default },
2887 { MKTAG('m','o','o','f'), mov_read_moof },
2888 { MKTAG('m','o','o','v'), mov_read_moov },
2889 { MKTAG('m','v','e','x'), mov_read_default },
2890 { MKTAG('m','v','h','d'), mov_read_mvhd },
2891 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2892 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2893 { MKTAG('a','v','c','C'), mov_read_glbl },
2894 { MKTAG('p','a','s','p'), mov_read_pasp },
2895 { MKTAG('s','t','b','l'), mov_read_default },
2896 { MKTAG('s','t','c','o'), mov_read_stco },
2897 { MKTAG('s','t','p','s'), mov_read_stps },
2898 { MKTAG('s','t','r','f'), mov_read_strf },
2899 { MKTAG('s','t','s','c'), mov_read_stsc },
2900 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2901 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2902 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2903 { MKTAG('s','t','t','s'), mov_read_stts },
2904 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2905 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2906 { MKTAG('t','f','d','t'), mov_read_tfdt },
2907 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2908 { MKTAG('t','r','a','k'), mov_read_trak },
2909 { MKTAG('t','r','a','f'), mov_read_default },
2910 { MKTAG('t','r','e','f'), mov_read_default },
2911 { MKTAG('c','h','a','p'), mov_read_chap },
2912 { MKTAG('t','r','e','x'), mov_read_trex },
2913 { MKTAG('t','r','u','n'), mov_read_trun },
2914 { MKTAG('u','d','t','a'), mov_read_default },
2915 { MKTAG('w','a','v','e'), mov_read_wave },
2916 { MKTAG('e','s','d','s'), mov_read_esds },
2917 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2918 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2919 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2920 { MKTAG('w','f','e','x'), mov_read_wfex },
2921 { MKTAG('c','m','o','v'), mov_read_cmov },
2922 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2923 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2924 { MKTAG('s','b','g','p'), mov_read_sbgp },
2925 { MKTAG('h','v','c','C'), mov_read_glbl },
2926 { MKTAG('-','-','-','-'), mov_read_custom },
2930 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2932 int64_t total_size = 0;
2937 atom.size = INT64_MAX;
2938 while (total_size + 8 < atom.size && !pb->eof_reached) {
2939 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
2942 if (atom.size >= 8) {
2943 a.size = avio_rb32(pb);
2944 a.type = avio_rl32(pb);
2946 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
2947 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
2949 if (a.size == 1) { /* 64 bit extended size */
2950 a.size = avio_rb64(pb) - 8;
2954 a.size = atom.size - total_size;
2961 a.size = FFMIN(a.size, atom.size - total_size);
2963 for (i = 0; mov_default_parse_table[i].type; i++)
2964 if (mov_default_parse_table[i].type == a.type) {
2965 parse = mov_default_parse_table[i].parse;
2969 // container is user data
2970 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
2971 atom.type == MKTAG('i','l','s','t')))
2972 parse = mov_read_udta_string;
2974 if (!parse) { /* skip leaf atoms data */
2975 avio_skip(pb, a.size);
2977 int64_t start_pos = avio_tell(pb);
2979 int err = parse(c, pb, a);
2982 if (c->found_moov && c->found_mdat &&
2983 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
2984 start_pos + a.size == avio_size(pb))) {
2985 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
2986 c->next_root_atom = start_pos + a.size;
2989 left = a.size - avio_tell(pb) + start_pos;
2990 if (left > 0) /* skip garbage at atom end */
2991 avio_skip(pb, left);
2992 else if (left < 0) {
2993 av_log(c->fc, AV_LOG_WARNING,
2994 "overread end of atom '%.4s' by %"PRId64" bytes\n",
2995 (char*)&a.type, -left);
2996 avio_seek(pb, left, SEEK_CUR);
3000 total_size += a.size;
3003 if (total_size < atom.size && atom.size < 0x7ffff)
3004 avio_skip(pb, atom.size - total_size);
3009 static int mov_probe(AVProbeData *p)
3011 unsigned int offset;
3015 /* check file header */
3018 /* ignore invalid offset */
3019 if ((offset + 8) > (unsigned int)p->buf_size)
3021 tag = AV_RL32(p->buf + offset + 4);
3023 /* check for obvious tags */
3024 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
3025 case MKTAG('m','o','o','v'):
3026 case MKTAG('m','d','a','t'):
3027 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3028 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3029 case MKTAG('f','t','y','p'):
3030 return AVPROBE_SCORE_MAX;
3031 /* those are more common words, so rate then a bit less */
3032 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3033 case MKTAG('w','i','d','e'):
3034 case MKTAG('f','r','e','e'):
3035 case MKTAG('j','u','n','k'):
3036 case MKTAG('p','i','c','t'):
3037 return AVPROBE_SCORE_MAX - 5;
3038 case MKTAG(0x82,0x82,0x7f,0x7d):
3039 case MKTAG('s','k','i','p'):
3040 case MKTAG('u','u','i','d'):
3041 case MKTAG('p','r','f','l'):
3042 offset = AV_RB32(p->buf+offset) + offset;
3043 /* if we only find those cause probedata is too small at least rate them */
3044 score = AVPROBE_SCORE_EXTENSION;
3047 /* unrecognized tag */
3053 // must be done after parsing all trak because there's no order requirement
3054 static void mov_read_chapters(AVFormatContext *s)
3056 MOVContext *mov = s->priv_data;
3057 AVStream *st = NULL;
3058 MOVStreamContext *sc;
3062 for (i = 0; i < s->nb_streams; i++)
3063 if (s->streams[i]->id == mov->chapter_track) {
3068 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3072 st->discard = AVDISCARD_ALL;
3074 cur_pos = avio_tell(sc->pb);
3076 for (i = 0; i < st->nb_index_entries; i++) {
3077 AVIndexEntry *sample = &st->index_entries[i];
3078 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3083 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3084 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3088 // the first two bytes are the length of the title
3089 len = avio_rb16(sc->pb);
3090 if (len > sample->size-2)
3092 title_len = 2*len + 1;
3093 if (!(title = av_mallocz(title_len)))
3096 // The samples could theoretically be in any encoding if there's an encd
3097 // atom following, but in practice are only utf-8 or utf-16, distinguished
3098 // instead by the presence of a BOM
3102 ch = avio_rb16(sc->pb);
3104 avio_get_str16be(sc->pb, len, title, title_len);
3105 else if (ch == 0xfffe)
3106 avio_get_str16le(sc->pb, len, title, title_len);
3109 if (len == 1 || len == 2)
3112 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
3116 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3120 avio_seek(sc->pb, cur_pos, SEEK_SET);
3123 static int mov_read_close(AVFormatContext *s)
3125 MOVContext *mov = s->priv_data;
3128 for (i = 0; i < s->nb_streams; i++) {
3129 AVStream *st = s->streams[i];
3130 MOVStreamContext *sc = st->priv_data;
3132 av_freep(&sc->ctts_data);
3133 for (j = 0; j < sc->drefs_count; j++) {
3134 av_freep(&sc->drefs[j].path);
3135 av_freep(&sc->drefs[j].dir);
3137 av_freep(&sc->drefs);
3138 if (sc->pb && sc->pb != s->pb)
3141 av_freep(&sc->chunk_offsets);
3142 av_freep(&sc->stsc_data);
3143 av_freep(&sc->sample_sizes);
3144 av_freep(&sc->keyframes);
3145 av_freep(&sc->stts_data);
3146 av_freep(&sc->stps_data);
3147 av_freep(&sc->rap_group);
3148 av_freep(&sc->display_matrix);
3151 if (mov->dv_demux) {
3152 avformat_free_context(mov->dv_fctx);
3153 mov->dv_fctx = NULL;
3156 av_freep(&mov->trex_data);
3161 static int mov_read_header(AVFormatContext *s)
3163 MOVContext *mov = s->priv_data;
3164 AVIOContext *pb = s->pb;
3166 MOVAtom atom = { AV_RL32("root") };
3170 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3172 atom.size = avio_size(pb);
3174 atom.size = INT64_MAX;
3176 /* check MOV header */
3177 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3178 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3182 if (!mov->found_moov) {
3183 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3185 return AVERROR_INVALIDDATA;
3187 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3189 if (pb->seekable && mov->chapter_track > 0)
3190 mov_read_chapters(s);
3192 for (i = 0; i < s->nb_streams; i++) {
3193 AVStream *st = s->streams[i];
3194 MOVStreamContext *sc = st->priv_data;
3196 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3197 if (st->codec->width <= 0 || st->codec->height <= 0) {
3198 st->codec->width = sc->width;
3199 st->codec->height = sc->height;
3201 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3202 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3208 if (mov->trex_data) {
3209 for (i = 0; i < s->nb_streams; i++) {
3210 AVStream *st = s->streams[i];
3211 MOVStreamContext *sc = st->priv_data;
3212 if (st->duration > 0)
3213 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3217 for (i = 0; i < s->nb_streams; i++) {
3218 AVStream *st = s->streams[i];
3219 MOVStreamContext *sc = st->priv_data;
3221 switch (st->codec->codec_type) {
3222 case AVMEDIA_TYPE_AUDIO:
3223 err = ff_replaygain_export(st, s->metadata);
3229 case AVMEDIA_TYPE_VIDEO:
3230 if (sc->display_matrix) {
3231 AVPacketSideData *sd, *tmp;
3233 tmp = av_realloc_array(st->side_data,
3234 st->nb_side_data + 1, sizeof(*tmp));
3236 return AVERROR(ENOMEM);
3238 st->side_data = tmp;
3241 sd = &st->side_data[st->nb_side_data - 1];
3242 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
3243 sd->size = sizeof(int32_t) * 9;
3244 sd->data = (uint8_t*)sc->display_matrix;
3245 sc->display_matrix = NULL;
3254 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3256 AVIndexEntry *sample = NULL;
3257 int64_t best_dts = INT64_MAX;
3259 for (i = 0; i < s->nb_streams; i++) {
3260 AVStream *avst = s->streams[i];
3261 MOVStreamContext *msc = avst->priv_data;
3262 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3263 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3264 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3265 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3266 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3268 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3269 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3270 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3271 sample = current_sample;
3280 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3282 MOVContext *mov = s->priv_data;
3283 MOVStreamContext *sc;
3284 AVIndexEntry *sample;
3285 AVStream *st = NULL;
3288 sample = mov_find_next_sample(s, &st);
3290 mov->found_mdat = 0;
3291 if (!mov->next_root_atom)
3293 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3294 mov->next_root_atom = 0;
3295 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3298 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3302 /* must be done just before reading, to avoid infinite loop on sample */
3303 sc->current_sample++;
3305 if (st->discard != AVDISCARD_ALL) {
3306 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3307 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3308 sc->ffindex, sample->pos);
3309 return AVERROR_INVALIDDATA;
3311 ret = av_get_packet(sc->pb, pkt, sample->size);
3314 if (sc->has_palette) {
3317 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3319 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3321 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3322 sc->has_palette = 0;
3325 #if CONFIG_DV_DEMUXER
3326 if (mov->dv_demux && sc->dv_audio_container) {
3327 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
3330 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3337 pkt->stream_index = sc->ffindex;
3338 pkt->dts = sample->timestamp;
3339 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3340 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3341 /* update ctts context */
3343 if (sc->ctts_index < sc->ctts_count &&
3344 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3346 sc->ctts_sample = 0;
3349 pkt->dts = AV_NOPTS_VALUE;
3351 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3352 st->index_entries[sc->current_sample].timestamp : st->duration;
3353 pkt->duration = next_dts - pkt->dts;
3354 pkt->pts = pkt->dts;
3356 if (st->discard == AVDISCARD_ALL)
3358 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3359 pkt->pos = sample->pos;
3360 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3361 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3365 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3367 MOVStreamContext *sc = st->priv_data;
3368 int sample, time_sample;
3371 sample = av_index_search_timestamp(st, timestamp, flags);
3372 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3373 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3375 if (sample < 0) /* not sure what to do */
3376 return AVERROR_INVALIDDATA;
3377 sc->current_sample = sample;
3378 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3379 /* adjust ctts index */
3380 if (sc->ctts_data) {
3382 for (i = 0; i < sc->ctts_count; i++) {
3383 int next = time_sample + sc->ctts_data[i].count;
3384 if (next > sc->current_sample) {
3386 sc->ctts_sample = sc->current_sample - time_sample;
3395 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3398 int64_t seek_timestamp, timestamp;
3402 if (stream_index >= s->nb_streams)
3403 return AVERROR_INVALIDDATA;
3404 if (sample_time < 0)
3407 st = s->streams[stream_index];
3408 sample = mov_seek_stream(s, st, sample_time, flags);
3412 /* adjust seek timestamp to found sample timestamp */
3413 seek_timestamp = st->index_entries[sample].timestamp;
3415 for (i = 0; i < s->nb_streams; i++) {
3417 if (stream_index == i)
3420 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3421 mov_seek_stream(s, st, timestamp, flags);
3426 #define OFFSET(x) offsetof(MOVContext, x)
3427 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
3428 static const AVOption mov_options[] = {
3429 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
3430 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
3434 static const AVClass mov_class = {
3435 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3436 .item_name = av_default_item_name,
3437 .option = mov_options,
3438 .version = LIBAVUTIL_VERSION_INT,
3441 AVInputFormat ff_mov_demuxer = {
3442 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3443 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3444 .priv_class = &mov_class,
3445 .priv_data_size = sizeof(MOVContext),
3446 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
3447 .read_probe = mov_probe,
3448 .read_header = mov_read_header,
3449 .read_packet = mov_read_packet,
3450 .read_close = mov_read_close,
3451 .read_seek = mov_read_seek,