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 //#define MOV_EXPORT_ALL_METADATA
32 #include "libavutil/attributes.h"
33 #include "libavutil/channel_layout.h"
34 #include "libavutil/intreadwrite.h"
35 #include "libavutil/intfloat.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/time_internal.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/dict.h"
40 #include "libavcodec/ac3tab.h"
43 #include "avio_internal.h"
46 #include "libavcodec/get_bits.h"
49 #include "replaygain.h"
55 #include "qtpalette.h"
61 /* those functions parse an atom */
62 /* links atom IDs to parse functions */
63 typedef struct MOVParseTableEntry {
65 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
68 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
70 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
71 unsigned len, const char *key)
75 short current, total = 0;
76 avio_rb16(pb); // unknown
77 current = avio_rb16(pb);
79 total = avio_rb16(pb);
81 snprintf(buf, sizeof(buf), "%d", current);
83 snprintf(buf, sizeof(buf), "%d/%d", current, total);
84 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
85 av_dict_set(&c->fc->metadata, key, buf, 0);
90 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
91 unsigned len, const char *key)
95 /* bypass padding bytes */
100 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
101 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
102 av_dict_set(&c->fc->metadata, key, buf, 0);
107 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
108 unsigned len, const char *key)
112 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
113 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
114 av_dict_set(&c->fc->metadata, key, buf, 0);
119 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
120 unsigned len, const char *key)
125 avio_r8(pb); // unknown
128 if (genre < 1 || genre > ID3v1_GENRE_MAX)
130 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
131 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
132 av_dict_set(&c->fc->metadata, key, buf, 0);
137 static const uint32_t mac_to_unicode[128] = {
138 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
139 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
140 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
141 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
142 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
143 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
144 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
145 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
146 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
147 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
148 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
149 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
150 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
151 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
152 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
153 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
156 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
157 char *dst, int dstlen)
160 char *end = dst+dstlen-1;
163 for (i = 0; i < len; i++) {
164 uint8_t t, c = avio_r8(pb);
165 if (c < 0x80 && p < end)
168 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
174 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
178 MOVStreamContext *sc;
183 case 0xd: id = AV_CODEC_ID_MJPEG; break;
184 case 0xe: id = AV_CODEC_ID_PNG; break;
185 case 0x1b: id = AV_CODEC_ID_BMP; break;
187 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
192 st = avformat_new_stream(c->fc, NULL);
194 return AVERROR(ENOMEM);
195 sc = av_mallocz(sizeof(*sc));
197 return AVERROR(ENOMEM);
200 ret = av_get_packet(pb, &pkt, len);
204 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
206 st->attached_pic = pkt;
207 st->attached_pic.stream_index = st->index;
208 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
210 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
211 st->codec->codec_id = id;
216 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
218 char language[4] = { 0 };
220 uint16_t langcode = 0;
221 double longitude, latitude;
222 const char *key = "location";
224 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4)
225 return AVERROR_INVALIDDATA;
227 avio_skip(pb, 4); // version+flags
228 langcode = avio_rb16(pb);
229 ff_mov_lang_to_iso639(langcode, language);
232 len -= avio_get_str(pb, len, buf, sizeof(buf)); // place name
234 return AVERROR_INVALIDDATA;
235 avio_skip(pb, 1); // role
239 return AVERROR_INVALIDDATA;
240 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
241 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
243 // Try to output in the same format as the ?xyz field
244 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f/", latitude, longitude);
245 if (*language && strcmp(language, "und")) {
247 snprintf(key2, sizeof(key2), "%s-%s", key, language);
248 av_dict_set(&c->fc->metadata, key2, buf, 0);
250 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
251 return av_dict_set(&c->fc->metadata, key, buf, 0);
254 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
256 #ifdef MOV_EXPORT_ALL_METADATA
259 char str[1024], key2[16], language[4] = {0};
260 const char *key = NULL;
261 uint16_t langcode = 0;
262 uint32_t data_type = 0, str_size;
263 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
266 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
267 case MKTAG(0xa9,'a','u','t'):
268 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
269 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
270 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
271 case MKTAG( 'c','p','r','t'):
272 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
273 case MKTAG(0xa9,'c','m','t'):
274 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
275 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
276 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
277 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
278 case MKTAG( 'g','n','r','e'): key = "genre";
279 parse = mov_metadata_gnre; break;
280 case MKTAG(0xa9,'t','o','o'):
281 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
282 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
283 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
284 case MKTAG( 'd','e','s','c'): key = "description";break;
285 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
286 case MKTAG( 't','v','s','h'): key = "show"; break;
287 case MKTAG( 't','v','e','n'): key = "episode_id";break;
288 case MKTAG( 't','v','n','n'): key = "network"; break;
289 case MKTAG( 't','r','k','n'): key = "track";
290 parse = mov_metadata_track_or_disc_number; break;
291 case MKTAG( 'd','i','s','k'): key = "disc";
292 parse = mov_metadata_track_or_disc_number; break;
293 case MKTAG( 't','v','e','s'): key = "episode_sort";
294 parse = mov_metadata_int8_bypass_padding; break;
295 case MKTAG( 't','v','s','n'): key = "season_number";
296 parse = mov_metadata_int8_bypass_padding; break;
297 case MKTAG( 's','t','i','k'): key = "media_type";
298 parse = mov_metadata_int8_no_padding; break;
299 case MKTAG( 'h','d','v','d'): key = "hd_video";
300 parse = mov_metadata_int8_no_padding; break;
301 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
302 parse = mov_metadata_int8_no_padding; break;
303 case MKTAG( 'l','o','c','i'):
304 return mov_metadata_loci(c, pb, atom.size);
307 if (c->itunes_metadata && atom.size > 8) {
308 int data_size = avio_rb32(pb);
309 int tag = avio_rl32(pb);
310 if (tag == MKTAG('d','a','t','a')) {
311 data_type = avio_rb32(pb); // type
312 avio_rb32(pb); // unknown
313 str_size = data_size - 16;
316 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
317 int ret = mov_read_covr(c, pb, data_type, str_size);
319 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
324 } else if (atom.size > 4 && key && !c->itunes_metadata) {
325 str_size = avio_rb16(pb); // string length
326 langcode = avio_rb16(pb);
327 ff_mov_lang_to_iso639(langcode, language);
330 str_size = atom.size;
332 #ifdef MOV_EXPORT_ALL_METADATA
334 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
342 return AVERROR_INVALIDDATA;
344 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
347 parse(c, pb, str_size, key);
349 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
350 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
352 avio_read(pb, str, str_size);
355 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
356 av_dict_set(&c->fc->metadata, key, str, 0);
357 if (*language && strcmp(language, "und")) {
358 snprintf(key2, sizeof(key2), "%s-%s", key, language);
359 av_dict_set(&c->fc->metadata, key2, str, 0);
362 av_dlog(c->fc, "lang \"%3s\" ", language);
363 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
364 key, str, (char*)&atom.type, str_size, 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 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
642 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
646 if (c->fc->nb_streams < 1)
648 st = c->fc->streams[c->fc->nb_streams-1];
650 ff_get_wav_header(pb, st->codec, atom.size);
655 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
657 const int num = avio_rb32(pb);
658 const int den = avio_rb32(pb);
661 if (c->fc->nb_streams < 1)
663 st = c->fc->streams[c->fc->nb_streams-1];
665 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
666 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
667 av_log(c->fc, AV_LOG_WARNING,
668 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
669 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
671 } else if (den != 0) {
672 st->sample_aspect_ratio.num = num;
673 st->sample_aspect_ratio.den = den;
678 /* this atom contains actual media data */
679 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
681 if (atom.size == 0) /* wrong one (MP4) */
684 return 0; /* now go for moov */
687 /* read major brand, minor version and compatible brands and store them as metadata */
688 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
692 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
693 char* comp_brands_str;
694 uint8_t type[5] = {0};
696 avio_read(pb, type, 4);
697 if (strcmp(type, "qt "))
699 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
700 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
701 minor_ver = avio_rb32(pb); /* minor version */
702 snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);
703 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
705 comp_brand_size = atom.size - 8;
706 if (comp_brand_size < 0)
707 return AVERROR_INVALIDDATA;
708 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
709 if (!comp_brands_str)
710 return AVERROR(ENOMEM);
711 avio_read(pb, comp_brands_str, comp_brand_size);
712 comp_brands_str[comp_brand_size] = 0;
713 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
714 av_freep(&comp_brands_str);
719 /* this atom should contain all header atoms */
720 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
724 if ((ret = mov_read_default(c, pb, atom)) < 0)
726 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
727 /* so we don't parse the whole file if over a network */
729 return 0; /* now go for mdat */
732 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
734 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
735 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
736 return mov_read_default(c, pb, atom);
739 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
743 struct tm *ptm, tmbuf;
744 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
745 ptm = gmtime_r(&time, &tmbuf);
747 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
748 av_dict_set(metadata, "creation_time", buffer, 0);
752 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
755 MOVStreamContext *sc;
757 char language[4] = {0};
759 time_t creation_time;
761 if (c->fc->nb_streams < 1)
763 st = c->fc->streams[c->fc->nb_streams-1];
766 if (sc->time_scale) {
767 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
768 return AVERROR_INVALIDDATA;
771 version = avio_r8(pb);
773 avpriv_request_sample(c->fc, "Version %d", version);
774 return AVERROR_PATCHWELCOME;
776 avio_rb24(pb); /* flags */
778 creation_time = avio_rb64(pb);
781 creation_time = avio_rb32(pb);
782 avio_rb32(pb); /* modification time */
784 mov_metadata_creation_time(&st->metadata, creation_time);
786 sc->time_scale = avio_rb32(pb);
787 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
789 lang = avio_rb16(pb); /* language */
790 if (ff_mov_lang_to_iso639(lang, language))
791 av_dict_set(&st->metadata, "language", language, 0);
792 avio_rb16(pb); /* quality */
797 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
799 time_t creation_time;
800 int version = avio_r8(pb); /* version */
801 avio_rb24(pb); /* flags */
804 creation_time = avio_rb64(pb);
807 creation_time = avio_rb32(pb);
808 avio_rb32(pb); /* modification time */
810 mov_metadata_creation_time(&c->fc->metadata, creation_time);
811 c->time_scale = avio_rb32(pb); /* time scale */
813 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
815 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
816 avio_rb32(pb); /* preferred scale */
818 avio_rb16(pb); /* preferred volume */
820 avio_skip(pb, 10); /* reserved */
822 avio_skip(pb, 36); /* display matrix */
824 avio_rb32(pb); /* preview time */
825 avio_rb32(pb); /* preview duration */
826 avio_rb32(pb); /* poster time */
827 avio_rb32(pb); /* selection time */
828 avio_rb32(pb); /* selection duration */
829 avio_rb32(pb); /* current time */
830 avio_rb32(pb); /* next track ID */
835 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
839 if (c->fc->nb_streams < 1)
841 st = c->fc->streams[c->fc->nb_streams-1];
843 if ((uint64_t)atom.size > (1<<30))
844 return AVERROR_INVALIDDATA;
846 // currently SVQ3 decoder expect full STSD header - so let's fake it
847 // this should be fixed and just SMI header should be passed
848 av_free(st->codec->extradata);
849 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
850 if (!st->codec->extradata)
851 return AVERROR(ENOMEM);
852 st->codec->extradata_size = 0x5a + atom.size;
853 memcpy(st->codec->extradata, "SVQ3", 4); // fake
854 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
855 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
859 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
864 if (c->fc->nb_streams < 1)
866 st = c->fc->streams[c->fc->nb_streams-1];
868 little_endian = avio_rb16(pb);
869 av_dlog(c->fc, "enda %d\n", little_endian);
870 if (little_endian == 1) {
871 switch (st->codec->codec_id) {
872 case AV_CODEC_ID_PCM_S24BE:
873 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
875 case AV_CODEC_ID_PCM_S32BE:
876 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
878 case AV_CODEC_ID_PCM_F32BE:
879 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
881 case AV_CODEC_ID_PCM_F64BE:
882 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
891 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
894 char color_parameter_type[5] = { 0 };
895 int color_primaries, color_trc, color_matrix;
897 if (c->fc->nb_streams < 1)
899 st = c->fc->streams[c->fc->nb_streams - 1];
901 avio_read(pb, color_parameter_type, 4);
902 if (strncmp(color_parameter_type, "nclx", 4) &&
903 strncmp(color_parameter_type, "nclc", 4)) {
904 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
905 color_parameter_type);
909 color_primaries = avio_rb16(pb);
910 color_trc = avio_rb16(pb);
911 color_matrix = avio_rb16(pb);
913 av_dlog(c->fc, "%s: pri %"PRIu16" trc %"PRIu16" matrix %"PRIu16"",
914 color_parameter_type, color_primaries, color_trc, color_matrix);
917 uint8_t color_range = avio_r8(pb) >> 7;
918 av_dlog(c->fc, " full %"PRIu8"", color_range)
920 st->codec->color_range = AVCOL_RANGE_JPEG;
922 st->codec->color_range = AVCOL_RANGE_MPEG;
923 /* 14496-12 references JPEG XR specs (rather than the more complete
924 * 23001-8) so some adjusting is required */
925 if (color_primaries >= AVCOL_PRI_FILM)
926 color_primaries = AVCOL_PRI_UNSPECIFIED;
927 if ((color_trc >= AVCOL_TRC_LINEAR &&
928 color_trc <= AVCOL_TRC_LOG_SQRT) ||
929 color_trc >= AVCOL_TRC_BT2020_10)
930 color_trc = AVCOL_TRC_UNSPECIFIED;
931 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
932 color_matrix = AVCOL_SPC_UNSPECIFIED;
933 st->codec->color_primaries = color_primaries;
934 st->codec->color_trc = color_trc;
935 st->codec->colorspace = color_matrix;
937 /* color primaries, Table 4-4 */
938 switch (color_primaries) {
939 case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
940 case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
941 case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
943 /* color transfer, Table 4-5 */
945 case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
946 case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
948 /* color matrix, Table 4-6 */
949 switch (color_matrix) {
950 case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
951 case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
952 case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
960 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
963 unsigned mov_field_order;
964 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
966 if (c->fc->nb_streams < 1) // will happen with jp2 files
968 st = c->fc->streams[c->fc->nb_streams-1];
970 return AVERROR_INVALIDDATA;
971 mov_field_order = avio_rb16(pb);
972 if ((mov_field_order & 0xFF00) == 0x0100)
973 decoded_field_order = AV_FIELD_PROGRESSIVE;
974 else if ((mov_field_order & 0xFF00) == 0x0200) {
975 switch (mov_field_order & 0xFF) {
976 case 0x01: decoded_field_order = AV_FIELD_TT;
978 case 0x06: decoded_field_order = AV_FIELD_BB;
980 case 0x09: decoded_field_order = AV_FIELD_TB;
982 case 0x0E: decoded_field_order = AV_FIELD_BT;
986 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
987 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
989 st->codec->field_order = decoded_field_order;
994 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
995 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1002 if (c->fc->nb_streams < 1) // will happen with jp2 files
1004 st= c->fc->streams[c->fc->nb_streams-1];
1005 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
1006 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1007 return AVERROR_INVALIDDATA;
1008 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
1009 st->codec->extradata_size = 0;
1012 buf = st->codec->extradata + st->codec->extradata_size;
1013 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
1014 AV_WB32( buf , atom.size + 8);
1015 AV_WL32( buf + 4, atom.type);
1016 avio_read(pb, buf + 8, atom.size);
1020 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1024 if (c->fc->nb_streams < 1)
1026 st = c->fc->streams[c->fc->nb_streams-1];
1028 if ((uint64_t)atom.size > (1<<30))
1029 return AVERROR_INVALIDDATA;
1031 if (st->codec->codec_id == AV_CODEC_ID_QDM2 || st->codec->codec_id == AV_CODEC_ID_QDMC) {
1032 // pass all frma atom to codec, needed at least for QDMC and QDM2
1033 av_free(st->codec->extradata);
1034 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1035 if (!st->codec->extradata)
1036 return AVERROR(ENOMEM);
1037 st->codec->extradata_size = atom.size;
1038 avio_read(pb, st->codec->extradata, atom.size);
1039 } else if (atom.size > 8) { /* to read frma, esds atoms */
1041 if ((ret = mov_read_default(c, pb, atom)) < 0)
1044 avio_skip(pb, atom.size);
1049 * This function reads atom content and puts data in extradata without tag
1050 * nor size unlike mov_read_extradata.
1052 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1056 if (c->fc->nb_streams < 1)
1058 st = c->fc->streams[c->fc->nb_streams-1];
1060 if ((uint64_t)atom.size > (1<<30))
1061 return AVERROR_INVALIDDATA;
1063 if (atom.size >= 10) {
1064 // Broken files created by legacy versions of libavformat will
1065 // wrap a whole fiel atom inside of a glbl atom.
1066 unsigned size = avio_rb32(pb);
1067 unsigned type = avio_rl32(pb);
1068 avio_seek(pb, -8, SEEK_CUR);
1069 if (type == MKTAG('f','i','e','l') && size == atom.size)
1070 return mov_read_default(c, pb, atom);
1072 av_free(st->codec->extradata);
1073 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1074 if (!st->codec->extradata)
1075 return AVERROR(ENOMEM);
1076 st->codec->extradata_size = atom.size;
1077 avio_read(pb, st->codec->extradata, atom.size);
1081 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1084 uint8_t profile_level;
1086 if (c->fc->nb_streams < 1)
1088 st = c->fc->streams[c->fc->nb_streams-1];
1090 if (atom.size >= (1<<28) || atom.size < 7)
1091 return AVERROR_INVALIDDATA;
1093 profile_level = avio_r8(pb);
1094 if ((profile_level & 0xf0) != 0xc0)
1097 av_free(st->codec->extradata);
1098 st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
1099 if (!st->codec->extradata)
1100 return AVERROR(ENOMEM);
1101 st->codec->extradata_size = atom.size - 7;
1102 avio_seek(pb, 6, SEEK_CUR);
1103 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
1108 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1109 * but can have extradata appended at the end after the 40 bytes belonging
1112 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1116 if (c->fc->nb_streams < 1)
1118 if (atom.size <= 40)
1120 st = c->fc->streams[c->fc->nb_streams-1];
1122 if ((uint64_t)atom.size > (1<<30))
1123 return AVERROR_INVALIDDATA;
1125 av_free(st->codec->extradata);
1126 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1127 if (!st->codec->extradata)
1128 return AVERROR(ENOMEM);
1129 st->codec->extradata_size = atom.size - 40;
1131 avio_read(pb, st->codec->extradata, atom.size - 40);
1135 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1138 MOVStreamContext *sc;
1139 unsigned int i, entries;
1141 if (c->fc->nb_streams < 1)
1143 st = c->fc->streams[c->fc->nb_streams-1];
1146 avio_r8(pb); /* version */
1147 avio_rb24(pb); /* flags */
1149 entries = avio_rb32(pb);
1153 if (entries >= UINT_MAX/sizeof(int64_t))
1154 return AVERROR_INVALIDDATA;
1156 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1157 if (!sc->chunk_offsets)
1158 return AVERROR(ENOMEM);
1159 sc->chunk_count = entries;
1161 if (atom.type == MKTAG('s','t','c','o'))
1162 for (i = 0; i < entries && !pb->eof_reached; i++)
1163 sc->chunk_offsets[i] = avio_rb32(pb);
1164 else if (atom.type == MKTAG('c','o','6','4'))
1165 for (i = 0; i < entries && !pb->eof_reached; i++)
1166 sc->chunk_offsets[i] = avio_rb64(pb);
1168 return AVERROR_INVALIDDATA;
1170 sc->chunk_count = i;
1172 if (pb->eof_reached)
1179 * Compute codec id for 'lpcm' tag.
1180 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1182 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1189 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1192 static int mov_codec_id(AVStream *st, uint32_t format)
1194 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1197 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1198 (format & 0xFFFF) == 'T' + ('S' << 8)))
1199 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1201 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1202 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1203 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1204 /* skip old asf mpeg4 tag */
1205 format && format != MKTAG('m','p','4','s')) {
1206 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1208 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1210 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1211 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
1212 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1214 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1218 st->codec->codec_tag = format;
1223 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1224 AVStream *st, MOVStreamContext *sc)
1226 uint8_t codec_name[32];
1227 unsigned int color_depth, len, j;
1228 int color_greyscale;
1231 avio_rb16(pb); /* version */
1232 avio_rb16(pb); /* revision level */
1233 avio_rb32(pb); /* vendor */
1234 avio_rb32(pb); /* temporal quality */
1235 avio_rb32(pb); /* spatial quality */
1237 st->codec->width = avio_rb16(pb); /* width */
1238 st->codec->height = avio_rb16(pb); /* height */
1240 avio_rb32(pb); /* horiz resolution */
1241 avio_rb32(pb); /* vert resolution */
1242 avio_rb32(pb); /* data size, always 0 */
1243 avio_rb16(pb); /* frames per samples */
1245 len = avio_r8(pb); /* codec name, pascal string */
1248 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1250 avio_skip(pb, 31 - len);
1253 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1255 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1256 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1257 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1258 /* Flash Media Server uses tag H263 with Sorenson Spark */
1259 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1260 !memcmp(codec_name, "Sorenson H263", 13))
1261 st->codec->codec_id = AV_CODEC_ID_FLV1;
1263 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1264 color_table_id = avio_rb16(pb); /* colortable id */
1265 av_dlog(c->fc, "depth %d, ctab id %d\n",
1266 st->codec->bits_per_coded_sample, color_table_id);
1267 /* figure out the palette situation */
1268 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1269 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1271 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1272 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1273 /* for palette traversal */
1274 unsigned int color_start, color_count, color_end;
1275 unsigned char r, g, b;
1277 if (color_greyscale) {
1278 int color_index, color_dec;
1279 /* compute the greyscale palette */
1280 st->codec->bits_per_coded_sample = color_depth;
1281 color_count = 1 << color_depth;
1283 color_dec = 256 / (color_count - 1);
1284 for (j = 0; j < color_count; j++) {
1285 r = g = b = color_index;
1286 sc->palette[j] = (r << 16) | (g << 8) | (b);
1287 color_index -= color_dec;
1288 if (color_index < 0)
1291 } else if (color_table_id) {
1292 const uint8_t *color_table;
1293 /* if flag bit 3 is set, use the default palette */
1294 color_count = 1 << color_depth;
1295 if (color_depth == 2)
1296 color_table = ff_qt_default_palette_4;
1297 else if (color_depth == 4)
1298 color_table = ff_qt_default_palette_16;
1300 color_table = ff_qt_default_palette_256;
1302 for (j = 0; j < color_count; j++) {
1303 r = color_table[j * 3 + 0];
1304 g = color_table[j * 3 + 1];
1305 b = color_table[j * 3 + 2];
1306 sc->palette[j] = (r << 16) | (g << 8) | (b);
1309 /* load the palette from the file */
1310 color_start = avio_rb32(pb);
1311 color_count = avio_rb16(pb);
1312 color_end = avio_rb16(pb);
1313 if ((color_start <= 255) && (color_end <= 255)) {
1314 for (j = color_start; j <= color_end; j++) {
1315 /* each R, G, or B component is 16 bits;
1316 * only use the top 8 bits; skip alpha bytes
1326 sc->palette[j] = (r << 16) | (g << 8) | (b);
1330 sc->has_palette = 1;
1334 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1335 AVStream *st, MOVStreamContext *sc)
1337 int bits_per_sample, flags;
1338 uint16_t version = avio_rb16(pb);
1340 avio_rb16(pb); /* revision level */
1341 avio_rb32(pb); /* vendor */
1343 st->codec->channels = avio_rb16(pb); /* channel count */
1344 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1345 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1347 sc->audio_cid = avio_rb16(pb);
1348 avio_rb16(pb); /* packet size = 0 */
1350 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1352 // Read QT version 1 fields. In version 0 these do not exist.
1353 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1356 sc->samples_per_frame = avio_rb32(pb);
1357 avio_rb32(pb); /* bytes per packet */
1358 sc->bytes_per_frame = avio_rb32(pb);
1359 avio_rb32(pb); /* bytes per sample */
1360 } else if (version == 2) {
1361 avio_rb32(pb); /* sizeof struct only */
1362 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1363 st->codec->channels = avio_rb32(pb);
1364 avio_rb32(pb); /* always 0x7F000000 */
1365 st->codec->bits_per_coded_sample = avio_rb32(pb);
1367 flags = avio_rb32(pb); /* lpcm format specific flag */
1368 sc->bytes_per_frame = avio_rb32(pb);
1369 sc->samples_per_frame = avio_rb32(pb);
1370 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1371 st->codec->codec_id =
1372 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1377 switch (st->codec->codec_id) {
1378 case AV_CODEC_ID_PCM_S8:
1379 case AV_CODEC_ID_PCM_U8:
1380 if (st->codec->bits_per_coded_sample == 16)
1381 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1383 case AV_CODEC_ID_PCM_S16LE:
1384 case AV_CODEC_ID_PCM_S16BE:
1385 if (st->codec->bits_per_coded_sample == 8)
1386 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1387 else if (st->codec->bits_per_coded_sample == 24)
1388 st->codec->codec_id =
1389 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1390 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1392 /* set values for old format before stsd version 1 appeared */
1393 case AV_CODEC_ID_MACE3:
1394 sc->samples_per_frame = 6;
1395 sc->bytes_per_frame = 2 * st->codec->channels;
1397 case AV_CODEC_ID_MACE6:
1398 sc->samples_per_frame = 6;
1399 sc->bytes_per_frame = 1 * st->codec->channels;
1401 case AV_CODEC_ID_ADPCM_IMA_QT:
1402 sc->samples_per_frame = 64;
1403 sc->bytes_per_frame = 34 * st->codec->channels;
1405 case AV_CODEC_ID_GSM:
1406 sc->samples_per_frame = 160;
1407 sc->bytes_per_frame = 33;
1413 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1414 if (bits_per_sample) {
1415 st->codec->bits_per_coded_sample = bits_per_sample;
1416 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1420 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1421 AVStream *st, MOVStreamContext *sc,
1424 // ttxt stsd contains display flags, justification, background
1425 // color, fonts, and default styles, so fake an atom to read it
1426 MOVAtom fake_atom = { .size = size };
1427 // mp4s contains a regular esds atom
1428 if (st->codec->codec_tag != AV_RL32("mp4s"))
1429 mov_read_glbl(c, pb, fake_atom);
1430 st->codec->width = sc->width;
1431 st->codec->height = sc->height;
1434 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1439 y = (ycbcr >> 16) & 0xFF;
1440 cr = (ycbcr >> 8) & 0xFF;
1443 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1444 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1445 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1447 return (r << 16) | (g << 8) | b;
1450 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1452 char buf[256] = {0};
1453 uint8_t *src = st->codec->extradata;
1456 if (st->codec->extradata_size != 64)
1459 if (st->codec->width > 0 && st->codec->height > 0)
1460 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1461 st->codec->width, st->codec->height);
1462 av_strlcat(buf, "palette: ", sizeof(buf));
1464 for (i = 0; i < 16; i++) {
1465 uint32_t yuv = AV_RB32(src + i * 4);
1466 uint32_t rgba = yuv_to_rgba(yuv);
1468 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1471 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1474 av_freep(&st->codec->extradata);
1475 st->codec->extradata_size = 0;
1476 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1477 if (!st->codec->extradata)
1478 return AVERROR(ENOMEM);
1479 st->codec->extradata_size = strlen(buf);
1480 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1485 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1486 AVStream *st, MOVStreamContext *sc,
1489 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1490 st->codec->extradata_size = size;
1491 st->codec->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
1492 if (!st->codec->extradata)
1493 return AVERROR(ENOMEM);
1494 avio_read(pb, st->codec->extradata, size);
1496 /* other codec type, just skip (rtp, mp4s ...) */
1497 avio_skip(pb, size);
1502 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1503 AVStream *st, MOVStreamContext *sc)
1505 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1506 !st->codec->sample_rate && sc->time_scale > 1)
1507 st->codec->sample_rate = sc->time_scale;
1509 /* special codec parameters handling */
1510 switch (st->codec->codec_id) {
1511 #if CONFIG_DV_DEMUXER
1512 case AV_CODEC_ID_DVAUDIO:
1513 c->dv_fctx = avformat_alloc_context();
1514 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1516 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1517 return AVERROR(ENOMEM);
1519 sc->dv_audio_container = 1;
1520 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1523 /* no ifdef since parameters are always those */
1524 case AV_CODEC_ID_QCELP:
1525 st->codec->channels = 1;
1526 // force sample rate for qcelp when not stored in mov
1527 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1528 st->codec->sample_rate = 8000;
1530 case AV_CODEC_ID_AMR_NB:
1531 st->codec->channels = 1;
1532 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1533 st->codec->sample_rate = 8000;
1535 case AV_CODEC_ID_AMR_WB:
1536 st->codec->channels = 1;
1537 st->codec->sample_rate = 16000;
1539 case AV_CODEC_ID_MP2:
1540 case AV_CODEC_ID_MP3:
1541 /* force type after stsd for m1a hdlr */
1542 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1543 st->need_parsing = AVSTREAM_PARSE_FULL;
1545 case AV_CODEC_ID_GSM:
1546 case AV_CODEC_ID_ADPCM_MS:
1547 case AV_CODEC_ID_ADPCM_IMA_WAV:
1548 case AV_CODEC_ID_ILBC:
1549 st->codec->block_align = sc->bytes_per_frame;
1551 case AV_CODEC_ID_ALAC:
1552 if (st->codec->extradata_size == 36) {
1553 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1554 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1557 case AV_CODEC_ID_VC1:
1558 st->need_parsing = AVSTREAM_PARSE_FULL;
1566 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1567 int codec_tag, int format,
1570 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1573 (codec_tag == AV_RL32("avc1") ||
1574 codec_tag == AV_RL32("hvc1") ||
1575 codec_tag == AV_RL32("hev1") ||
1576 (codec_tag != format &&
1577 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1578 : codec_tag != MKTAG('j','p','e','g'))))) {
1579 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1580 * export it as a separate AVStream but this needs a few changes
1581 * in the MOV demuxer, patch welcome. */
1583 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1584 avio_skip(pb, size);
1591 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1594 MOVStreamContext *sc;
1595 int pseudo_stream_id;
1597 if (c->fc->nb_streams < 1)
1599 st = c->fc->streams[c->fc->nb_streams-1];
1602 for (pseudo_stream_id = 0;
1603 pseudo_stream_id < entries && !pb->eof_reached;
1604 pseudo_stream_id++) {
1605 //Parsing Sample description table
1607 int ret, dref_id = 1;
1608 MOVAtom a = { AV_RL32("stsd") };
1609 int64_t start_pos = avio_tell(pb);
1610 uint32_t size = avio_rb32(pb); /* size */
1611 uint32_t format = avio_rl32(pb); /* data format */
1614 avio_rb32(pb); /* reserved */
1615 avio_rb16(pb); /* reserved */
1616 dref_id = avio_rb16(pb);
1618 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRIu32" in stsd\n", size);
1619 return AVERROR_INVALIDDATA;
1622 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1623 size - (avio_tell(pb) - start_pos)))
1626 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1627 sc->dref_id= dref_id;
1629 id = mov_codec_id(st, format);
1631 av_dlog(c->fc, "size=%"PRIu32" 4CC= %"PRIu8"%"PRIu8"%"PRIu8"%"PRIu8" codec_type=%d\n", size,
1632 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1633 (format >> 24) & 0xff, st->codec->codec_type);
1635 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1636 st->codec->codec_id = id;
1637 mov_parse_stsd_video(c, pb, st, sc);
1638 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1639 st->codec->codec_id = id;
1640 mov_parse_stsd_audio(c, pb, st, sc);
1641 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1642 st->codec->codec_id = id;
1643 mov_parse_stsd_subtitle(c, pb, st, sc,
1644 size - (avio_tell(pb) - start_pos));
1646 ret = mov_parse_stsd_data(c, pb, st, sc,
1647 size - (avio_tell(pb) - start_pos));
1651 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1652 a.size = size - (avio_tell(pb) - start_pos);
1654 if ((ret = mov_read_default(c, pb, a)) < 0)
1656 } else if (a.size > 0)
1657 avio_skip(pb, a.size);
1660 if (pb->eof_reached)
1663 return mov_finalize_stsd_codec(c, pb, st, sc);
1666 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1670 avio_r8(pb); /* version */
1671 avio_rb24(pb); /* flags */
1672 entries = avio_rb32(pb);
1674 return ff_mov_read_stsd_entries(c, pb, entries);
1677 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1680 MOVStreamContext *sc;
1681 unsigned int i, entries;
1683 if (c->fc->nb_streams < 1)
1685 st = c->fc->streams[c->fc->nb_streams-1];
1688 avio_r8(pb); /* version */
1689 avio_rb24(pb); /* flags */
1691 entries = avio_rb32(pb);
1693 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1697 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1698 return AVERROR_INVALIDDATA;
1699 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1701 return AVERROR(ENOMEM);
1703 for (i = 0; i < entries && !pb->eof_reached; i++) {
1704 sc->stsc_data[i].first = avio_rb32(pb);
1705 sc->stsc_data[i].count = avio_rb32(pb);
1706 sc->stsc_data[i].id = avio_rb32(pb);
1711 if (pb->eof_reached)
1717 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1720 MOVStreamContext *sc;
1721 unsigned i, entries;
1723 if (c->fc->nb_streams < 1)
1725 st = c->fc->streams[c->fc->nb_streams-1];
1728 avio_rb32(pb); // version + flags
1730 entries = avio_rb32(pb);
1731 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1732 return AVERROR_INVALIDDATA;
1733 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1735 return AVERROR(ENOMEM);
1737 for (i = 0; i < entries && !pb->eof_reached; i++) {
1738 sc->stps_data[i] = avio_rb32(pb);
1739 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1744 if (pb->eof_reached)
1750 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1753 MOVStreamContext *sc;
1754 unsigned int i, entries;
1756 if (c->fc->nb_streams < 1)
1758 st = c->fc->streams[c->fc->nb_streams-1];
1761 avio_r8(pb); /* version */
1762 avio_rb24(pb); /* flags */
1764 entries = avio_rb32(pb);
1766 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1770 sc->keyframe_absent = 1;
1773 if (entries >= UINT_MAX / sizeof(int))
1774 return AVERROR_INVALIDDATA;
1775 sc->keyframes = av_malloc(entries * sizeof(int));
1777 return AVERROR(ENOMEM);
1779 for (i = 0; i < entries && !pb->eof_reached; i++) {
1780 sc->keyframes[i] = avio_rb32(pb);
1781 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1784 sc->keyframe_count = i;
1786 if (pb->eof_reached)
1792 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1795 MOVStreamContext *sc;
1796 unsigned int i, entries, sample_size, field_size, num_bytes;
1800 if (c->fc->nb_streams < 1)
1802 st = c->fc->streams[c->fc->nb_streams-1];
1805 avio_r8(pb); /* version */
1806 avio_rb24(pb); /* flags */
1808 if (atom.type == MKTAG('s','t','s','z')) {
1809 sample_size = avio_rb32(pb);
1810 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1811 sc->sample_size = sample_size;
1815 avio_rb24(pb); /* reserved */
1816 field_size = avio_r8(pb);
1818 entries = avio_rb32(pb);
1820 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1822 sc->sample_count = entries;
1826 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1827 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1828 return AVERROR_INVALIDDATA;
1833 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1834 return AVERROR_INVALIDDATA;
1835 sc->sample_sizes = av_malloc(entries * sizeof(int));
1836 if (!sc->sample_sizes)
1837 return AVERROR(ENOMEM);
1839 num_bytes = (entries*field_size+4)>>3;
1841 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1843 av_freep(&sc->sample_sizes);
1844 return AVERROR(ENOMEM);
1847 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1848 av_freep(&sc->sample_sizes);
1850 return AVERROR_INVALIDDATA;
1853 init_get_bits(&gb, buf, 8*num_bytes);
1855 for (i = 0; i < entries && !pb->eof_reached; i++) {
1856 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1857 sc->data_size += sc->sample_sizes[i];
1860 sc->sample_count = i;
1862 if (pb->eof_reached)
1869 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1872 MOVStreamContext *sc;
1873 unsigned int i, entries;
1875 int64_t total_sample_count=0;
1877 if (c->fc->nb_streams < 1)
1879 st = c->fc->streams[c->fc->nb_streams-1];
1882 avio_r8(pb); /* version */
1883 avio_rb24(pb); /* flags */
1884 entries = avio_rb32(pb);
1886 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1887 c->fc->nb_streams-1, entries);
1891 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1892 return AVERROR(EINVAL);
1894 av_free(sc->stts_data);
1895 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1897 return AVERROR(ENOMEM);
1899 for (i = 0; i < entries && !pb->eof_reached; i++) {
1900 int sample_duration;
1903 sample_count=avio_rb32(pb);
1904 sample_duration = avio_rb32(pb);
1905 if (sample_count < 0) {
1906 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
1907 return AVERROR_INVALIDDATA;
1909 sc->stts_data[i].count= sample_count;
1910 sc->stts_data[i].duration= sample_duration;
1912 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1913 sample_count, sample_duration);
1915 duration+=(int64_t)sample_duration*sample_count;
1916 total_sample_count+=sample_count;
1921 if (pb->eof_reached)
1924 st->nb_frames= total_sample_count;
1926 st->duration= duration;
1927 sc->track_end = duration;
1931 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1934 MOVStreamContext *sc;
1935 unsigned int i, entries;
1937 if (c->fc->nb_streams < 1)
1939 st = c->fc->streams[c->fc->nb_streams-1];
1942 avio_r8(pb); /* version */
1943 avio_rb24(pb); /* flags */
1944 entries = avio_rb32(pb);
1946 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1950 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1951 return AVERROR_INVALIDDATA;
1952 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1954 return AVERROR(ENOMEM);
1956 for (i = 0; i < entries && !pb->eof_reached; i++) {
1957 int count =avio_rb32(pb);
1958 int duration =avio_rb32(pb);
1960 sc->ctts_data[i].count = count;
1961 sc->ctts_data[i].duration= duration;
1963 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1968 if (pb->eof_reached)
1971 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1976 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1979 MOVStreamContext *sc;
1980 unsigned int i, entries;
1982 uint32_t grouping_type;
1984 if (c->fc->nb_streams < 1)
1986 st = c->fc->streams[c->fc->nb_streams-1];
1989 version = avio_r8(pb); /* version */
1990 avio_rb24(pb); /* flags */
1991 grouping_type = avio_rl32(pb);
1992 if (grouping_type != MKTAG( 'r','a','p',' '))
1993 return 0; /* only support 'rap ' grouping */
1995 avio_rb32(pb); /* grouping_type_parameter */
1997 entries = avio_rb32(pb);
2000 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2001 return AVERROR_INVALIDDATA;
2002 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2004 return AVERROR(ENOMEM);
2006 for (i = 0; i < entries && !pb->eof_reached; i++) {
2007 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2008 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2011 sc->rap_group_count = i;
2013 return pb->eof_reached ? AVERROR_EOF : 0;
2016 static void mov_build_index(MOVContext *mov, AVStream *st)
2018 MOVStreamContext *sc = st->priv_data;
2019 int64_t current_offset;
2020 int64_t current_dts = 0;
2021 unsigned int stts_index = 0;
2022 unsigned int stsc_index = 0;
2023 unsigned int stss_index = 0;
2024 unsigned int stps_index = 0;
2026 uint64_t stream_size = 0;
2028 /* adjust first dts according to edit list */
2029 if (sc->time_offset && mov->time_scale > 0) {
2030 if (sc->time_offset < 0)
2031 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
2032 current_dts = -sc->time_offset;
2033 if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
2034 sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
2035 /* more than 16 frames delay, dts are likely wrong
2036 this happens with files created by iMovie */
2038 st->codec->has_b_frames = 1;
2042 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2043 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2044 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2045 unsigned int current_sample = 0;
2046 unsigned int stts_sample = 0;
2047 unsigned int sample_size;
2048 unsigned int distance = 0;
2049 unsigned int rap_group_index = 0;
2050 unsigned int rap_group_sample = 0;
2051 int rap_group_present = sc->rap_group_count && sc->rap_group;
2052 int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
2054 current_dts -= sc->dts_shift;
2056 if (!sc->sample_count)
2058 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2060 if (av_reallocp_array(&st->index_entries,
2061 st->nb_index_entries + sc->sample_count,
2062 sizeof(*st->index_entries)) < 0) {
2063 st->nb_index_entries = 0;
2066 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2068 for (i = 0; i < sc->chunk_count; i++) {
2069 current_offset = sc->chunk_offsets[i];
2070 while (stsc_index + 1 < sc->stsc_count &&
2071 i + 1 == sc->stsc_data[stsc_index + 1].first)
2073 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2075 if (current_sample >= sc->sample_count) {
2076 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2080 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2082 if (stss_index + 1 < sc->keyframe_count)
2084 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2086 if (stps_index + 1 < sc->stps_count)
2089 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2090 if (sc->rap_group[rap_group_index].index > 0)
2092 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2093 rap_group_sample = 0;
2099 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
2100 if (sc->pseudo_stream_id == -1 ||
2101 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2102 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2103 e->pos = current_offset;
2104 e->timestamp = current_dts;
2105 e->size = sample_size;
2106 e->min_distance = distance;
2107 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2108 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2109 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2110 current_offset, current_dts, sample_size, distance, keyframe);
2113 current_offset += sample_size;
2114 stream_size += sample_size;
2115 current_dts += sc->stts_data[stts_index].duration;
2119 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2125 if (st->duration > 0)
2126 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2128 unsigned chunk_samples, total = 0;
2130 // compute total chunk count
2131 for (i = 0; i < sc->stsc_count; i++) {
2132 unsigned count, chunk_count;
2134 chunk_samples = sc->stsc_data[i].count;
2135 if (i != sc->stsc_count - 1 &&
2136 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2137 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2141 if (sc->samples_per_frame >= 160) { // gsm
2142 count = chunk_samples / sc->samples_per_frame;
2143 } else if (sc->samples_per_frame > 1) {
2144 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2145 count = (chunk_samples+samples-1) / samples;
2147 count = (chunk_samples+1023) / 1024;
2150 if (i < sc->stsc_count - 1)
2151 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2153 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2154 total += chunk_count * count;
2157 av_dlog(mov->fc, "chunk count %d\n", total);
2158 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2160 if (av_reallocp_array(&st->index_entries,
2161 st->nb_index_entries + total,
2162 sizeof(*st->index_entries)) < 0) {
2163 st->nb_index_entries = 0;
2166 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2169 for (i = 0; i < sc->chunk_count; i++) {
2170 current_offset = sc->chunk_offsets[i];
2171 if (stsc_index + 1 < sc->stsc_count &&
2172 i + 1 == sc->stsc_data[stsc_index + 1].first)
2174 chunk_samples = sc->stsc_data[stsc_index].count;
2176 while (chunk_samples > 0) {
2178 unsigned size, samples;
2180 if (sc->samples_per_frame >= 160) { // gsm
2181 samples = sc->samples_per_frame;
2182 size = sc->bytes_per_frame;
2184 if (sc->samples_per_frame > 1) {
2185 samples = FFMIN((1024 / sc->samples_per_frame)*
2186 sc->samples_per_frame, chunk_samples);
2187 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2189 samples = FFMIN(1024, chunk_samples);
2190 size = samples * sc->sample_size;
2194 if (st->nb_index_entries >= total) {
2195 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2198 e = &st->index_entries[st->nb_index_entries++];
2199 e->pos = current_offset;
2200 e->timestamp = current_dts;
2202 e->min_distance = 0;
2203 e->flags = AVINDEX_KEYFRAME;
2204 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2205 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2208 current_offset += size;
2209 current_dts += samples;
2210 chunk_samples -= samples;
2216 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
2217 AVIOInterruptCB *int_cb)
2219 /* try relative path, we do not try the absolute because it can leak information about our
2220 system to an attacker */
2221 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2222 char filename[1024];
2226 /* find a source dir */
2227 src_path = strrchr(src, '/');
2233 /* find a next level down to target */
2234 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2235 if (ref->path[l] == '/') {
2236 if (i == ref->nlvl_to - 1)
2242 /* compose filename if next level down to target was found */
2243 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2244 memcpy(filename, src, src_path - src);
2245 filename[src_path - src] = 0;
2247 for (i = 1; i < ref->nlvl_from; i++)
2248 av_strlcat(filename, "../", 1024);
2250 av_strlcat(filename, ref->path + l + 1, 1024);
2252 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2257 return AVERROR(ENOENT);
2260 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2263 MOVStreamContext *sc;
2266 st = avformat_new_stream(c->fc, NULL);
2267 if (!st) return AVERROR(ENOMEM);
2268 st->id = c->fc->nb_streams;
2269 sc = av_mallocz(sizeof(MOVStreamContext));
2270 if (!sc) return AVERROR(ENOMEM);
2273 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2274 sc->ffindex = st->index;
2276 if ((ret = mov_read_default(c, pb, atom)) < 0)
2280 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2281 (!sc->sample_size && !sc->sample_count))) {
2282 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2287 if (sc->time_scale <= 0) {
2288 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2289 sc->time_scale = c->time_scale;
2290 if (sc->time_scale <= 0)
2294 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2296 mov_build_index(c, st);
2298 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2299 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2300 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
2301 av_log(c->fc, AV_LOG_ERROR,
2302 "stream %d, error opening alias: path='%s', dir='%s', "
2303 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2304 st->index, dref->path, dref->dir, dref->filename,
2305 dref->volume, dref->nlvl_from, dref->nlvl_to);
2309 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2310 if (!st->sample_aspect_ratio.num &&
2311 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2312 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2313 ((double)st->codec->width * sc->height), INT_MAX);
2317 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2318 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2319 TAG_IS_AVCI(st->codec->codec_tag)) {
2320 ret = ff_generate_avci_extradata(st);
2325 switch (st->codec->codec_id) {
2326 #if CONFIG_H261_DECODER
2327 case AV_CODEC_ID_H261:
2329 #if CONFIG_H263_DECODER
2330 case AV_CODEC_ID_H263:
2332 #if CONFIG_MPEG4_DECODER
2333 case AV_CODEC_ID_MPEG4:
2335 st->codec->width = 0; /* let decoder init width/height */
2336 st->codec->height= 0;
2340 /* Do not need those anymore. */
2341 av_freep(&sc->chunk_offsets);
2342 av_freep(&sc->stsc_data);
2343 av_freep(&sc->sample_sizes);
2344 av_freep(&sc->keyframes);
2345 av_freep(&sc->stts_data);
2346 av_freep(&sc->stps_data);
2347 av_freep(&sc->rap_group);
2352 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2355 c->itunes_metadata = 1;
2356 ret = mov_read_default(c, pb, atom);
2357 c->itunes_metadata = 0;
2361 static int mov_read_replaygain(MOVContext *c, AVIOContext *pb, int size)
2363 int64_t end = avio_tell(pb) + size;
2364 uint8_t *key = NULL, *val = NULL;
2367 for (i = 0; i < 2; i++) {
2371 if (end - avio_tell(pb) <= 12)
2374 len = avio_rb32(pb);
2375 tag = avio_rl32(pb);
2376 avio_skip(pb, 4); // flags
2378 if (len < 12 || len - 12 > end - avio_tell(pb))
2382 if (tag == MKTAG('n', 'a', 'm', 'e'))
2384 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2391 *p = av_malloc(len + 1);
2394 avio_read(pb, *p, len);
2399 av_dict_set(&c->fc->metadata, key, val,
2400 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2404 avio_seek(pb, end, SEEK_SET);
2410 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2412 int64_t end = avio_tell(pb) + atom.size;
2418 len = avio_rb32(pb);
2419 tag = avio_rl32(pb);
2421 if (len > atom.size)
2424 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2425 uint8_t domain[128];
2428 avio_skip(pb, 4); // flags
2431 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2432 avio_skip(pb, len - domain_len);
2433 if (!strcmp(domain, "org.hydrogenaudio.replaygain"))
2434 return mov_read_replaygain(c, pb, end - avio_tell(pb));
2438 av_log(c->fc, AV_LOG_VERBOSE,
2439 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2443 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2445 while (atom.size > 8) {
2446 uint32_t tag = avio_rl32(pb);
2448 if (tag == MKTAG('h','d','l','r')) {
2449 avio_seek(pb, -8, SEEK_CUR);
2451 return mov_read_default(c, pb, atom);
2457 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2462 int64_t disp_transform[2];
2463 int display_matrix[3][3];
2465 MOVStreamContext *sc;
2469 if (c->fc->nb_streams < 1)
2471 st = c->fc->streams[c->fc->nb_streams-1];
2474 version = avio_r8(pb);
2475 flags = avio_rb24(pb);
2476 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2482 avio_rb32(pb); /* creation time */
2483 avio_rb32(pb); /* modification time */
2485 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2486 avio_rb32(pb); /* reserved */
2488 /* highlevel (considering edits) duration in movie timebase */
2489 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2490 avio_rb32(pb); /* reserved */
2491 avio_rb32(pb); /* reserved */
2493 avio_rb16(pb); /* layer */
2494 avio_rb16(pb); /* alternate group */
2495 avio_rb16(pb); /* volume */
2496 avio_rb16(pb); /* reserved */
2498 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2499 // they're kept in fixed point format through all calculations
2500 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2501 // side data, but the scale factor is not needed to calculate aspect ratio
2502 for (i = 0; i < 3; i++) {
2503 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2504 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2505 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2508 width = avio_rb32(pb); // 16.16 fixed point track width
2509 height = avio_rb32(pb); // 16.16 fixed point track height
2510 sc->width = width >> 16;
2511 sc->height = height >> 16;
2513 // save the matrix when it is not the default identity
2514 if (display_matrix[0][0] != (1 << 16) ||
2515 display_matrix[1][1] != (1 << 16) ||
2516 display_matrix[2][2] != (1 << 30) ||
2517 display_matrix[0][1] || display_matrix[0][2] ||
2518 display_matrix[1][0] || display_matrix[1][2] ||
2519 display_matrix[2][0] || display_matrix[2][1]) {
2522 av_freep(&sc->display_matrix);
2523 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2524 if (!sc->display_matrix)
2525 return AVERROR(ENOMEM);
2527 for (i = 0; i < 3; i++)
2528 for (j = 0; j < 3; j++)
2529 sc->display_matrix[i * 3 + j] = display_matrix[j][i];
2532 // transform the display width/height according to the matrix
2533 // skip this if the display matrix is the default identity matrix
2534 // or if it is rotating the picture, ex iPhone 3GS
2535 // to keep the same scale, use [width height 1<<16]
2536 if (width && height &&
2537 ((display_matrix[0][0] != 65536 ||
2538 display_matrix[1][1] != 65536) &&
2539 !display_matrix[0][1] &&
2540 !display_matrix[1][0] &&
2541 !display_matrix[2][0] && !display_matrix[2][1])) {
2542 for (i = 0; i < 2; i++)
2544 (int64_t) width * display_matrix[0][i] +
2545 (int64_t) height * display_matrix[1][i] +
2546 ((int64_t) display_matrix[2][i] << 16);
2548 //sample aspect ratio is new width/height divided by old width/height
2549 st->sample_aspect_ratio = av_d2q(
2550 ((double) disp_transform[0] * height) /
2551 ((double) disp_transform[1] * width), INT_MAX);
2556 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2558 MOVFragment *frag = &c->fragment;
2559 MOVTrackExt *trex = NULL;
2560 int flags, track_id, i;
2562 avio_r8(pb); /* version */
2563 flags = avio_rb24(pb);
2565 track_id = avio_rb32(pb);
2567 return AVERROR_INVALIDDATA;
2568 frag->track_id = track_id;
2569 for (i = 0; i < c->trex_count; i++)
2570 if (c->trex_data[i].track_id == frag->track_id) {
2571 trex = &c->trex_data[i];
2575 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2576 return AVERROR_INVALIDDATA;
2579 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2580 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
2581 frag->moof_offset : frag->implicit_offset;
2582 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2584 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2585 avio_rb32(pb) : trex->duration;
2586 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2587 avio_rb32(pb) : trex->size;
2588 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2589 avio_rb32(pb) : trex->flags;
2590 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2594 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2596 c->chapter_track = avio_rb32(pb);
2600 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2605 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2606 return AVERROR_INVALIDDATA;
2607 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2608 sizeof(*c->trex_data))) < 0) {
2612 trex = &c->trex_data[c->trex_count++];
2613 avio_r8(pb); /* version */
2614 avio_rb24(pb); /* flags */
2615 trex->track_id = avio_rb32(pb);
2616 trex->stsd_id = avio_rb32(pb);
2617 trex->duration = avio_rb32(pb);
2618 trex->size = avio_rb32(pb);
2619 trex->flags = avio_rb32(pb);
2623 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2625 MOVFragment *frag = &c->fragment;
2626 AVStream *st = NULL;
2627 MOVStreamContext *sc;
2630 for (i = 0; i < c->fc->nb_streams; i++) {
2631 if (c->fc->streams[i]->id == frag->track_id) {
2632 st = c->fc->streams[i];
2637 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2638 return AVERROR_INVALIDDATA;
2641 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
2643 version = avio_r8(pb);
2644 avio_rb24(pb); /* flags */
2646 sc->track_end = avio_rb64(pb);
2648 sc->track_end = avio_rb32(pb);
2653 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2655 MOVFragment *frag = &c->fragment;
2656 AVStream *st = NULL;
2657 MOVStreamContext *sc;
2661 int data_offset = 0;
2662 unsigned entries, first_sample_flags = frag->flags;
2663 int flags, distance, i, found_keyframe = 0, err;
2665 for (i = 0; i < c->fc->nb_streams; i++) {
2666 if (c->fc->streams[i]->id == frag->track_id) {
2667 st = c->fc->streams[i];
2672 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2673 return AVERROR_INVALIDDATA;
2676 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2678 avio_r8(pb); /* version */
2679 flags = avio_rb24(pb);
2680 entries = avio_rb32(pb);
2681 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2683 /* Always assume the presence of composition time offsets.
2684 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2685 * 1) in the initial movie, there are no samples.
2686 * 2) in the first movie fragment, there is only one sample without composition time offset.
2687 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2688 if (!sc->ctts_count && sc->sample_count)
2690 /* Complement ctts table if moov atom doesn't have ctts atom. */
2691 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2693 return AVERROR(ENOMEM);
2694 sc->ctts_data = ctts_data;
2695 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2696 sc->ctts_data[sc->ctts_count].duration = 0;
2699 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2700 return AVERROR_INVALIDDATA;
2701 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2702 sizeof(*sc->ctts_data))) < 0) {
2706 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2707 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2708 dts = sc->track_end - sc->time_offset;
2709 offset = frag->base_data_offset + data_offset;
2711 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2712 for (i = 0; i < entries && !pb->eof_reached; i++) {
2713 unsigned sample_size = frag->size;
2714 int sample_flags = i ? frag->flags : first_sample_flags;
2715 unsigned sample_duration = frag->duration;
2718 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2719 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2720 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2721 sc->ctts_data[sc->ctts_count].count = 1;
2722 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2725 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2727 else if (!found_keyframe)
2728 keyframe = found_keyframe =
2729 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2730 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2733 av_add_index_entry(st, offset, dts, sample_size, distance,
2734 keyframe ? AVINDEX_KEYFRAME : 0);
2735 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2736 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2737 offset, dts, sample_size, distance, keyframe);
2739 dts += sample_duration;
2740 offset += sample_size;
2741 sc->data_size += sample_size;
2744 if (pb->eof_reached)
2747 frag->implicit_offset = offset;
2748 st->duration = sc->track_end = dts + sc->time_offset;
2752 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2753 /* like the files created with Adobe Premiere 5.0, for samples see */
2754 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2755 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2760 return 0; /* continue */
2761 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2762 avio_skip(pb, atom.size - 4);
2765 atom.type = avio_rl32(pb);
2767 if (atom.type != MKTAG('m','d','a','t')) {
2768 avio_skip(pb, atom.size);
2771 err = mov_read_mdat(c, pb, atom);
2775 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2780 uint8_t *moov_data; /* uncompressed data */
2781 long cmov_len, moov_len;
2784 avio_rb32(pb); /* dcom atom */
2785 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2786 return AVERROR_INVALIDDATA;
2787 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2788 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2789 return AVERROR_INVALIDDATA;
2791 avio_rb32(pb); /* cmvd atom */
2792 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2793 return AVERROR_INVALIDDATA;
2794 moov_len = avio_rb32(pb); /* uncompressed size */
2795 cmov_len = atom.size - 6 * 4;
2797 cmov_data = av_malloc(cmov_len);
2799 return AVERROR(ENOMEM);
2800 moov_data = av_malloc(moov_len);
2803 return AVERROR(ENOMEM);
2805 avio_read(pb, cmov_data, cmov_len);
2806 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2807 goto free_and_return;
2808 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2809 goto free_and_return;
2810 atom.type = MKTAG('m','o','o','v');
2811 atom.size = moov_len;
2812 ret = mov_read_default(c, &ctx, atom);
2818 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2819 return AVERROR(ENOSYS);
2823 /* edit list atom */
2824 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2826 MOVStreamContext *sc;
2827 int i, edit_count, version;
2829 if (c->fc->nb_streams < 1)
2831 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2833 version = avio_r8(pb); /* version */
2834 avio_rb24(pb); /* flags */
2835 edit_count = avio_rb32(pb); /* entries */
2837 if ((uint64_t)edit_count*12+8 > atom.size)
2838 return AVERROR_INVALIDDATA;
2840 for (i=0; i<edit_count; i++){
2844 duration = avio_rb64(pb);
2845 time = avio_rb64(pb);
2847 duration = avio_rb32(pb); /* segment duration */
2848 time = (int32_t)avio_rb32(pb); /* media time */
2850 avio_rb32(pb); /* Media rate */
2851 if (i == 0 && time >= -1) {
2852 sc->time_offset = time != -1 ? time : -duration;
2857 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2858 "a/v desync might occur, patch welcome\n");
2860 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2864 static const MOVParseTableEntry mov_default_parse_table[] = {
2865 { MKTAG('a','v','s','s'), mov_read_extradata },
2866 { MKTAG('c','h','p','l'), mov_read_chpl },
2867 { MKTAG('c','o','6','4'), mov_read_stco },
2868 { MKTAG('c','o','l','r'), mov_read_colr },
2869 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2870 { MKTAG('d','i','n','f'), mov_read_default },
2871 { MKTAG('d','r','e','f'), mov_read_dref },
2872 { MKTAG('e','d','t','s'), mov_read_default },
2873 { MKTAG('e','l','s','t'), mov_read_elst },
2874 { MKTAG('e','n','d','a'), mov_read_enda },
2875 { MKTAG('f','i','e','l'), mov_read_fiel },
2876 { MKTAG('f','t','y','p'), mov_read_ftyp },
2877 { MKTAG('g','l','b','l'), mov_read_glbl },
2878 { MKTAG('h','d','l','r'), mov_read_hdlr },
2879 { MKTAG('i','l','s','t'), mov_read_ilst },
2880 { MKTAG('j','p','2','h'), mov_read_extradata },
2881 { MKTAG('m','d','a','t'), mov_read_mdat },
2882 { MKTAG('m','d','h','d'), mov_read_mdhd },
2883 { MKTAG('m','d','i','a'), mov_read_default },
2884 { MKTAG('m','e','t','a'), mov_read_meta },
2885 { MKTAG('m','i','n','f'), mov_read_default },
2886 { MKTAG('m','o','o','f'), mov_read_moof },
2887 { MKTAG('m','o','o','v'), mov_read_moov },
2888 { MKTAG('m','v','e','x'), mov_read_default },
2889 { MKTAG('m','v','h','d'), mov_read_mvhd },
2890 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2891 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2892 { MKTAG('a','v','c','C'), mov_read_glbl },
2893 { MKTAG('p','a','s','p'), mov_read_pasp },
2894 { MKTAG('s','t','b','l'), mov_read_default },
2895 { MKTAG('s','t','c','o'), mov_read_stco },
2896 { MKTAG('s','t','p','s'), mov_read_stps },
2897 { MKTAG('s','t','r','f'), mov_read_strf },
2898 { MKTAG('s','t','s','c'), mov_read_stsc },
2899 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2900 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2901 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2902 { MKTAG('s','t','t','s'), mov_read_stts },
2903 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2904 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2905 { MKTAG('t','f','d','t'), mov_read_tfdt },
2906 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2907 { MKTAG('t','r','a','k'), mov_read_trak },
2908 { MKTAG('t','r','a','f'), mov_read_default },
2909 { MKTAG('t','r','e','f'), mov_read_default },
2910 { MKTAG('c','h','a','p'), mov_read_chap },
2911 { MKTAG('t','r','e','x'), mov_read_trex },
2912 { MKTAG('t','r','u','n'), mov_read_trun },
2913 { MKTAG('u','d','t','a'), mov_read_default },
2914 { MKTAG('w','a','v','e'), mov_read_wave },
2915 { MKTAG('e','s','d','s'), mov_read_esds },
2916 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2917 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2918 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2919 { MKTAG('w','f','e','x'), mov_read_wfex },
2920 { MKTAG('c','m','o','v'), mov_read_cmov },
2921 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2922 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2923 { MKTAG('s','b','g','p'), mov_read_sbgp },
2924 { MKTAG('h','v','c','C'), mov_read_glbl },
2925 { MKTAG('-','-','-','-'), mov_read_custom },
2929 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2931 int64_t total_size = 0;
2936 atom.size = INT64_MAX;
2937 while (total_size + 8 < atom.size && !pb->eof_reached) {
2938 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
2941 if (atom.size >= 8) {
2942 a.size = avio_rb32(pb);
2943 a.type = avio_rl32(pb);
2945 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
2946 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
2948 if (a.size == 1) { /* 64 bit extended size */
2949 a.size = avio_rb64(pb) - 8;
2953 a.size = atom.size - total_size;
2960 a.size = FFMIN(a.size, atom.size - total_size);
2962 for (i = 0; mov_default_parse_table[i].type; i++)
2963 if (mov_default_parse_table[i].type == a.type) {
2964 parse = mov_default_parse_table[i].parse;
2968 // container is user data
2969 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
2970 atom.type == MKTAG('i','l','s','t')))
2971 parse = mov_read_udta_string;
2973 if (!parse) { /* skip leaf atoms data */
2974 avio_skip(pb, a.size);
2976 int64_t start_pos = avio_tell(pb);
2978 int err = parse(c, pb, a);
2981 if (c->found_moov && c->found_mdat &&
2982 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
2983 start_pos + a.size == avio_size(pb))) {
2984 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
2985 c->next_root_atom = start_pos + a.size;
2988 left = a.size - avio_tell(pb) + start_pos;
2989 if (left > 0) /* skip garbage at atom end */
2990 avio_skip(pb, left);
2991 else if (left < 0) {
2992 av_log(c->fc, AV_LOG_WARNING,
2993 "overread end of atom '%.4s' by %"PRId64" bytes\n",
2994 (char*)&a.type, -left);
2995 avio_seek(pb, left, SEEK_CUR);
2999 total_size += a.size;
3002 if (total_size < atom.size && atom.size < 0x7ffff)
3003 avio_skip(pb, atom.size - total_size);
3008 static int mov_probe(AVProbeData *p)
3010 unsigned int offset;
3014 /* check file header */
3017 /* ignore invalid offset */
3018 if ((offset + 8) > (unsigned int)p->buf_size)
3020 tag = AV_RL32(p->buf + offset + 4);
3022 /* check for obvious tags */
3023 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
3024 case MKTAG('m','o','o','v'):
3025 case MKTAG('m','d','a','t'):
3026 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3027 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3028 case MKTAG('f','t','y','p'):
3029 return AVPROBE_SCORE_MAX;
3030 /* those are more common words, so rate then a bit less */
3031 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3032 case MKTAG('w','i','d','e'):
3033 case MKTAG('f','r','e','e'):
3034 case MKTAG('j','u','n','k'):
3035 case MKTAG('p','i','c','t'):
3036 return AVPROBE_SCORE_MAX - 5;
3037 case MKTAG(0x82,0x82,0x7f,0x7d):
3038 case MKTAG('s','k','i','p'):
3039 case MKTAG('u','u','i','d'):
3040 case MKTAG('p','r','f','l'):
3041 offset = AV_RB32(p->buf+offset) + offset;
3042 /* if we only find those cause probedata is too small at least rate them */
3043 score = AVPROBE_SCORE_EXTENSION;
3046 /* unrecognized tag */
3052 // must be done after parsing all trak because there's no order requirement
3053 static void mov_read_chapters(AVFormatContext *s)
3055 MOVContext *mov = s->priv_data;
3056 AVStream *st = NULL;
3057 MOVStreamContext *sc;
3061 for (i = 0; i < s->nb_streams; i++)
3062 if (s->streams[i]->id == mov->chapter_track) {
3067 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3071 st->discard = AVDISCARD_ALL;
3073 cur_pos = avio_tell(sc->pb);
3075 for (i = 0; i < st->nb_index_entries; i++) {
3076 AVIndexEntry *sample = &st->index_entries[i];
3077 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3082 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3083 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3087 // the first two bytes are the length of the title
3088 len = avio_rb16(sc->pb);
3089 if (len > sample->size-2)
3091 title_len = 2*len + 1;
3092 if (!(title = av_mallocz(title_len)))
3095 // The samples could theoretically be in any encoding if there's an encd
3096 // atom following, but in practice are only utf-8 or utf-16, distinguished
3097 // instead by the presence of a BOM
3101 ch = avio_rb16(sc->pb);
3103 avio_get_str16be(sc->pb, len, title, title_len);
3104 else if (ch == 0xfffe)
3105 avio_get_str16le(sc->pb, len, title, title_len);
3108 if (len == 1 || len == 2)
3111 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
3115 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3119 avio_seek(sc->pb, cur_pos, SEEK_SET);
3122 static int mov_read_close(AVFormatContext *s)
3124 MOVContext *mov = s->priv_data;
3127 for (i = 0; i < s->nb_streams; i++) {
3128 AVStream *st = s->streams[i];
3129 MOVStreamContext *sc = st->priv_data;
3131 av_freep(&sc->ctts_data);
3132 for (j = 0; j < sc->drefs_count; j++) {
3133 av_freep(&sc->drefs[j].path);
3134 av_freep(&sc->drefs[j].dir);
3136 av_freep(&sc->drefs);
3137 if (sc->pb && sc->pb != s->pb)
3140 av_freep(&sc->chunk_offsets);
3141 av_freep(&sc->stsc_data);
3142 av_freep(&sc->sample_sizes);
3143 av_freep(&sc->keyframes);
3144 av_freep(&sc->stts_data);
3145 av_freep(&sc->stps_data);
3146 av_freep(&sc->rap_group);
3147 av_freep(&sc->display_matrix);
3150 if (mov->dv_demux) {
3151 avformat_free_context(mov->dv_fctx);
3152 mov->dv_fctx = NULL;
3155 av_freep(&mov->trex_data);
3160 static int mov_read_header(AVFormatContext *s)
3162 MOVContext *mov = s->priv_data;
3163 AVIOContext *pb = s->pb;
3165 MOVAtom atom = { AV_RL32("root") };
3169 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3171 atom.size = avio_size(pb);
3173 atom.size = INT64_MAX;
3175 /* check MOV header */
3176 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3177 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3181 if (!mov->found_moov) {
3182 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3184 return AVERROR_INVALIDDATA;
3186 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3188 if (pb->seekable && mov->chapter_track > 0)
3189 mov_read_chapters(s);
3191 for (i = 0; i < s->nb_streams; i++) {
3192 AVStream *st = s->streams[i];
3193 MOVStreamContext *sc = st->priv_data;
3195 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3196 if (st->codec->width <= 0 || st->codec->height <= 0) {
3197 st->codec->width = sc->width;
3198 st->codec->height = sc->height;
3200 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3201 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3207 if (mov->trex_data) {
3208 for (i = 0; i < s->nb_streams; i++) {
3209 AVStream *st = s->streams[i];
3210 MOVStreamContext *sc = st->priv_data;
3211 if (st->duration > 0)
3212 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3216 for (i = 0; i < s->nb_streams; i++) {
3217 AVStream *st = s->streams[i];
3218 MOVStreamContext *sc = st->priv_data;
3220 switch (st->codec->codec_type) {
3221 case AVMEDIA_TYPE_AUDIO:
3222 err = ff_replaygain_export(st, s->metadata);
3228 case AVMEDIA_TYPE_VIDEO:
3229 if (sc->display_matrix) {
3230 AVPacketSideData *sd, *tmp;
3232 tmp = av_realloc_array(st->side_data,
3233 st->nb_side_data + 1, sizeof(*tmp));
3235 return AVERROR(ENOMEM);
3237 st->side_data = tmp;
3240 sd = &st->side_data[st->nb_side_data - 1];
3241 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
3242 sd->size = sizeof(int32_t) * 9;
3243 sd->data = (uint8_t*)sc->display_matrix;
3244 sc->display_matrix = NULL;
3253 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3255 AVIndexEntry *sample = NULL;
3256 int64_t best_dts = INT64_MAX;
3258 for (i = 0; i < s->nb_streams; i++) {
3259 AVStream *avst = s->streams[i];
3260 MOVStreamContext *msc = avst->priv_data;
3261 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3262 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3263 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3264 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3265 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3267 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3268 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3269 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3270 sample = current_sample;
3279 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3281 MOVContext *mov = s->priv_data;
3282 MOVStreamContext *sc;
3283 AVIndexEntry *sample;
3284 AVStream *st = NULL;
3287 sample = mov_find_next_sample(s, &st);
3289 mov->found_mdat = 0;
3290 if (!mov->next_root_atom)
3292 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3293 mov->next_root_atom = 0;
3294 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3297 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3301 /* must be done just before reading, to avoid infinite loop on sample */
3302 sc->current_sample++;
3304 if (st->discard != AVDISCARD_ALL) {
3305 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3306 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3307 sc->ffindex, sample->pos);
3308 return AVERROR_INVALIDDATA;
3310 ret = av_get_packet(sc->pb, pkt, sample->size);
3313 if (sc->has_palette) {
3316 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3318 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3320 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3321 sc->has_palette = 0;
3324 #if CONFIG_DV_DEMUXER
3325 if (mov->dv_demux && sc->dv_audio_container) {
3326 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
3329 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3336 pkt->stream_index = sc->ffindex;
3337 pkt->dts = sample->timestamp;
3338 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3339 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3340 /* update ctts context */
3342 if (sc->ctts_index < sc->ctts_count &&
3343 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3345 sc->ctts_sample = 0;
3348 pkt->dts = AV_NOPTS_VALUE;
3350 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3351 st->index_entries[sc->current_sample].timestamp : st->duration;
3352 pkt->duration = next_dts - pkt->dts;
3353 pkt->pts = pkt->dts;
3355 if (st->discard == AVDISCARD_ALL)
3357 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3358 pkt->pos = sample->pos;
3359 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3360 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3364 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3366 MOVStreamContext *sc = st->priv_data;
3367 int sample, time_sample;
3370 sample = av_index_search_timestamp(st, timestamp, flags);
3371 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3372 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3374 if (sample < 0) /* not sure what to do */
3375 return AVERROR_INVALIDDATA;
3376 sc->current_sample = sample;
3377 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3378 /* adjust ctts index */
3379 if (sc->ctts_data) {
3381 for (i = 0; i < sc->ctts_count; i++) {
3382 int next = time_sample + sc->ctts_data[i].count;
3383 if (next > sc->current_sample) {
3385 sc->ctts_sample = sc->current_sample - time_sample;
3394 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3397 int64_t seek_timestamp, timestamp;
3401 if (stream_index >= s->nb_streams)
3402 return AVERROR_INVALIDDATA;
3403 if (sample_time < 0)
3406 st = s->streams[stream_index];
3407 sample = mov_seek_stream(s, st, sample_time, flags);
3411 /* adjust seek timestamp to found sample timestamp */
3412 seek_timestamp = st->index_entries[sample].timestamp;
3414 for (i = 0; i < s->nb_streams; i++) {
3416 if (stream_index == i)
3419 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3420 mov_seek_stream(s, st, timestamp, flags);
3425 AVInputFormat ff_mov_demuxer = {
3426 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3427 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3428 .priv_data_size = sizeof(MOVContext),
3429 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
3430 .read_probe = mov_probe,
3431 .read_header = mov_read_header,
3432 .read_packet = mov_read_packet,
3433 .read_close = mov_read_close,
3434 .read_seek = mov_read_seek,