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 FFmpeg.
11 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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/display.h"
35 #include "libavutil/intreadwrite.h"
36 #include "libavutil/intfloat.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/timecode.h"
42 #include "libavcodec/ac3tab.h"
45 #include "avio_internal.h"
48 #include "libavcodec/get_bits.h"
51 #include "replaygain.h"
57 #include "qtpalette.h"
63 /* those functions parse an atom */
64 /* links atom IDs to parse functions */
65 typedef struct MOVParseTableEntry {
67 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
70 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
72 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
73 unsigned len, const char *key)
77 short current, total = 0;
78 avio_rb16(pb); // unknown
79 current = avio_rb16(pb);
81 total = avio_rb16(pb);
83 snprintf(buf, sizeof(buf), "%d", current);
85 snprintf(buf, sizeof(buf), "%d/%d", current, total);
86 av_dict_set(&c->fc->metadata, key, buf, 0);
91 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
92 unsigned len, const char *key)
96 /* bypass padding bytes */
101 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
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 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 av_dict_set(&c->fc->metadata, key, buf, 0);
135 static const uint32_t mac_to_unicode[128] = {
136 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
137 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
138 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
139 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
140 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
141 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
142 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
143 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
144 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
145 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
146 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
147 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
148 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
149 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
150 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
151 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
154 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
155 char *dst, int dstlen)
158 char *end = dst+dstlen-1;
161 for (i = 0; i < len; i++) {
162 uint8_t t, c = avio_r8(pb);
163 if (c < 0x80 && p < end)
166 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
172 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
176 MOVStreamContext *sc;
181 case 0xd: id = AV_CODEC_ID_MJPEG; break;
182 case 0xe: id = AV_CODEC_ID_PNG; break;
183 case 0x1b: id = AV_CODEC_ID_BMP; break;
185 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
190 st = avformat_new_stream(c->fc, NULL);
192 return AVERROR(ENOMEM);
193 sc = av_mallocz(sizeof(*sc));
195 return AVERROR(ENOMEM);
198 ret = av_get_packet(pb, &pkt, len);
202 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
204 st->attached_pic = pkt;
205 st->attached_pic.stream_index = st->index;
206 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
208 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
209 st->codec->codec_id = id;
214 static int mov_metadata_raw(MOVContext *c, AVIOContext *pb,
215 unsigned len, const char *key)
217 char *value = av_malloc(len + 1);
219 return AVERROR(ENOMEM);
220 avio_read(pb, value, len);
222 return av_dict_set(&c->fc->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);
225 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
227 #ifdef MOV_EXPORT_ALL_METADATA
230 char str[1024], key2[16], language[4] = {0};
231 const char *key = NULL;
232 uint16_t langcode = 0;
233 uint32_t data_type = 0, str_size;
234 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
237 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
238 case MKTAG(0xa9,'a','u','t'):
239 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
240 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
241 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
242 case MKTAG( 'c','p','i','l'): key = "compilation";
243 parse = mov_metadata_int8_no_padding; break;
244 case MKTAG( 'c','p','r','t'):
245 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
246 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
247 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
248 case MKTAG(0xa9,'c','m','t'):
249 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
250 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
251 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
252 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
253 case MKTAG( 'g','n','r','e'): key = "genre";
254 parse = mov_metadata_gnre; break;
255 case MKTAG(0xa9,'t','o','o'):
256 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
257 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
258 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
259 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
260 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
261 case MKTAG( 'd','e','s','c'): key = "description";break;
262 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
263 case MKTAG( 't','v','s','h'): key = "show"; break;
264 case MKTAG( 't','v','e','n'): key = "episode_id";break;
265 case MKTAG( 't','v','n','n'): key = "network"; break;
266 case MKTAG( 't','r','k','n'): key = "track";
267 parse = mov_metadata_track_or_disc_number; break;
268 case MKTAG( 'd','i','s','k'): key = "disc";
269 parse = mov_metadata_track_or_disc_number; break;
270 case MKTAG( 't','v','e','s'): key = "episode_sort";
271 parse = mov_metadata_int8_bypass_padding; break;
272 case MKTAG( 't','v','s','n'): key = "season_number";
273 parse = mov_metadata_int8_bypass_padding; break;
274 case MKTAG( 's','t','i','k'): key = "media_type";
275 parse = mov_metadata_int8_no_padding; break;
276 case MKTAG( 'h','d','v','d'): key = "hd_video";
277 parse = mov_metadata_int8_no_padding; break;
278 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
279 parse = mov_metadata_int8_no_padding; break;
280 case MKTAG( '@','P','R','M'):
281 return mov_metadata_raw(c, pb, atom.size, "premiere_version");
282 case MKTAG( '@','P','R','Q'):
283 return mov_metadata_raw(c, pb, atom.size, "quicktime_version");
286 if (c->itunes_metadata && atom.size > 8) {
287 int data_size = avio_rb32(pb);
288 int tag = avio_rl32(pb);
289 if (tag == MKTAG('d','a','t','a')) {
290 data_type = avio_rb32(pb); // type
291 avio_rb32(pb); // unknown
292 str_size = data_size - 16;
295 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
296 int ret = mov_read_covr(c, pb, data_type, str_size);
298 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
303 } else if (atom.size > 4 && key && !c->itunes_metadata) {
304 str_size = avio_rb16(pb); // string length
305 langcode = avio_rb16(pb);
306 ff_mov_lang_to_iso639(langcode, language);
309 str_size = atom.size;
311 #ifdef MOV_EXPORT_ALL_METADATA
313 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
321 return AVERROR_INVALIDDATA;
323 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
326 parse(c, pb, str_size, key);
328 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
329 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
331 int ret = avio_read(pb, str, str_size);
333 return ret < 0 ? ret : AVERROR_INVALIDDATA;
336 av_dict_set(&c->fc->metadata, key, str, 0);
337 if (*language && strcmp(language, "und")) {
338 snprintf(key2, sizeof(key2), "%s-%s", key, language);
339 av_dict_set(&c->fc->metadata, key2, str, 0);
342 av_dlog(c->fc, "lang \"%3s\" ", language);
343 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
344 key, str, (char*)&atom.type, str_size, atom.size);
349 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
352 int i, nb_chapters, str_len, version;
355 if ((atom.size -= 5) < 0)
358 version = avio_r8(pb);
361 avio_rb32(pb); // ???
362 nb_chapters = avio_r8(pb);
364 for (i = 0; i < nb_chapters; i++) {
368 start = avio_rb64(pb);
369 str_len = avio_r8(pb);
371 if ((atom.size -= 9+str_len) < 0)
374 avio_read(pb, str, str_len);
376 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
381 #define MIN_DATA_ENTRY_BOX_SIZE 12
382 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
385 MOVStreamContext *sc;
388 if (c->fc->nb_streams < 1)
390 st = c->fc->streams[c->fc->nb_streams-1];
393 avio_rb32(pb); // version + flags
394 entries = avio_rb32(pb);
395 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
396 entries >= UINT_MAX / sizeof(*sc->drefs))
397 return AVERROR_INVALIDDATA;
400 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
402 return AVERROR(ENOMEM);
403 sc->drefs_count = entries;
405 for (i = 0; i < sc->drefs_count; i++) {
406 MOVDref *dref = &sc->drefs[i];
407 uint32_t size = avio_rb32(pb);
408 int64_t next = avio_tell(pb) + size - 4;
411 return AVERROR_INVALIDDATA;
413 dref->type = avio_rl32(pb);
414 avio_rb32(pb); // version + flags
415 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
417 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
418 /* macintosh alias record */
419 uint16_t volume_len, len;
424 volume_len = avio_r8(pb);
425 volume_len = FFMIN(volume_len, 27);
426 avio_read(pb, dref->volume, 27);
427 dref->volume[volume_len] = 0;
428 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
433 len = FFMIN(len, 63);
434 avio_read(pb, dref->filename, 63);
435 dref->filename[len] = 0;
436 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
440 /* read next level up_from_alias/down_to_target */
441 dref->nlvl_from = avio_rb16(pb);
442 dref->nlvl_to = avio_rb16(pb);
443 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
444 dref->nlvl_from, dref->nlvl_to);
448 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
451 type = avio_rb16(pb);
453 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
456 if (type == 2) { // absolute path
458 dref->path = av_mallocz(len+1);
460 return AVERROR(ENOMEM);
461 avio_read(pb, dref->path, len);
462 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
464 memmove(dref->path, dref->path+volume_len, len);
467 for (j = 0; j < len; j++)
468 if (dref->path[j] == ':')
470 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
471 } else if (type == 0) { // directory name
473 dref->dir = av_malloc(len+1);
475 return AVERROR(ENOMEM);
476 if (avio_read(pb, dref->dir, len) != len)
477 return AVERROR_INVALIDDATA;
479 for (j = 0; j < len; j++)
480 if (dref->dir[j] == ':')
482 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
487 avio_seek(pb, next, SEEK_SET);
492 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
496 uint32_t av_unused ctype;
500 if (c->fc->nb_streams < 1) // meta before first trak
503 st = c->fc->streams[c->fc->nb_streams-1];
505 avio_r8(pb); /* version */
506 avio_rb24(pb); /* flags */
509 ctype = avio_rl32(pb);
510 type = avio_rl32(pb); /* component subtype */
512 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
513 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
515 if (type == MKTAG('v','i','d','e'))
516 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
517 else if (type == MKTAG('s','o','u','n'))
518 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
519 else if (type == MKTAG('m','1','a',' '))
520 st->codec->codec_id = AV_CODEC_ID_MP2;
521 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
522 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
524 avio_rb32(pb); /* component manufacture */
525 avio_rb32(pb); /* component flags */
526 avio_rb32(pb); /* component flags mask */
528 title_size = atom.size - 24;
529 if (title_size > 0) {
530 title_str = av_malloc(title_size + 1); /* Add null terminator */
532 return AVERROR(ENOMEM);
533 avio_read(pb, title_str, title_size);
534 title_str[title_size] = 0;
536 av_dict_set(&st->metadata, "handler_name", title_str +
537 (!c->isom && title_str[0] == title_size - 1), 0);
538 av_freep(&title_str);
544 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
549 if (fc->nb_streams < 1)
551 st = fc->streams[fc->nb_streams-1];
553 avio_rb32(pb); /* version + flags */
554 ff_mp4_read_descr(fc, pb, &tag);
555 if (tag == MP4ESDescrTag) {
556 ff_mp4_parse_es_descr(pb, NULL);
558 avio_rb16(pb); /* ID */
560 ff_mp4_read_descr(fc, pb, &tag);
561 if (tag == MP4DecConfigDescrTag)
562 ff_mp4_read_dec_config_descr(fc, st, pb);
566 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
568 return ff_mov_read_esds(c->fc, pb, atom);
571 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
574 int ac3info, acmod, lfeon, bsmod;
576 if (c->fc->nb_streams < 1)
578 st = c->fc->streams[c->fc->nb_streams-1];
580 ac3info = avio_rb24(pb);
581 bsmod = (ac3info >> 14) & 0x7;
582 acmod = (ac3info >> 11) & 0x7;
583 lfeon = (ac3info >> 10) & 0x1;
584 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
585 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
587 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
588 st->codec->audio_service_type = bsmod;
589 if (st->codec->channels > 1 && bsmod == 0x7)
590 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
595 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
598 int eac3info, acmod, lfeon, bsmod;
600 if (c->fc->nb_streams < 1)
602 st = c->fc->streams[c->fc->nb_streams-1];
604 /* No need to parse fields for additional independent substreams and its
605 * associated dependent substreams since libavcodec's E-AC-3 decoder
606 * does not support them yet. */
607 avio_rb16(pb); /* data_rate and num_ind_sub */
608 eac3info = avio_rb24(pb);
609 bsmod = (eac3info >> 12) & 0x1f;
610 acmod = (eac3info >> 9) & 0x7;
611 lfeon = (eac3info >> 8) & 0x1;
612 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
614 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
615 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
616 st->codec->audio_service_type = bsmod;
617 if (st->codec->channels > 1 && bsmod == 0x7)
618 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
623 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
627 if (c->fc->nb_streams < 1)
629 st = c->fc->streams[c->fc->nb_streams-1];
634 /* skip version and flags */
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 if (ff_get_wav_header(pb, st->codec, atom.size) < 0) {
651 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
657 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
659 const int num = avio_rb32(pb);
660 const int den = avio_rb32(pb);
663 if (c->fc->nb_streams < 1)
665 st = c->fc->streams[c->fc->nb_streams-1];
667 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
668 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
669 av_log(c->fc, AV_LOG_WARNING,
670 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
671 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
673 } else if (den != 0) {
674 st->sample_aspect_ratio.num = num;
675 st->sample_aspect_ratio.den = den;
680 /* this atom contains actual media data */
681 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
683 if (atom.size == 0) /* wrong one (MP4) */
686 return 0; /* now go for moov */
689 /* read major brand, minor version and compatible brands and store them as metadata */
690 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
694 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
695 char* comp_brands_str;
696 uint8_t type[5] = {0};
698 avio_read(pb, type, 4);
699 if (strcmp(type, "qt "))
701 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
702 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
703 minor_ver = avio_rb32(pb); /* minor version */
704 snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);
705 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
707 comp_brand_size = atom.size - 8;
708 if (comp_brand_size < 0)
709 return AVERROR_INVALIDDATA;
710 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
711 if (!comp_brands_str)
712 return AVERROR(ENOMEM);
713 avio_read(pb, comp_brands_str, comp_brand_size);
714 comp_brands_str[comp_brand_size] = 0;
715 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
716 av_freep(&comp_brands_str);
721 /* this atom should contain all header atoms */
722 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
727 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
728 avio_skip(pb, atom.size);
732 if ((ret = mov_read_default(c, pb, atom)) < 0)
734 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
735 /* so we don't parse the whole file if over a network */
737 return 0; /* now go for mdat */
740 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
742 c->fragment.moof_offset = avio_tell(pb) - 8;
743 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
744 return mov_read_default(c, pb, atom);
747 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
753 if(time >= 2082844800)
754 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
756 ptm = gmtime(&timet);
758 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
759 av_dict_set(metadata, "creation_time", buffer, 0);
763 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
766 MOVStreamContext *sc;
768 char language[4] = {0};
770 int64_t creation_time;
772 if (c->fc->nb_streams < 1)
774 st = c->fc->streams[c->fc->nb_streams-1];
777 if (sc->time_scale) {
778 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
779 return AVERROR_INVALIDDATA;
782 version = avio_r8(pb);
784 avpriv_request_sample(c->fc, "Version %d", version);
785 return AVERROR_PATCHWELCOME;
787 avio_rb24(pb); /* flags */
789 creation_time = avio_rb64(pb);
792 creation_time = avio_rb32(pb);
793 avio_rb32(pb); /* modification time */
795 mov_metadata_creation_time(&st->metadata, creation_time);
797 sc->time_scale = avio_rb32(pb);
798 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
800 lang = avio_rb16(pb); /* language */
801 if (ff_mov_lang_to_iso639(lang, language))
802 av_dict_set(&st->metadata, "language", language, 0);
803 avio_rb16(pb); /* quality */
808 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
810 int64_t creation_time;
811 int version = avio_r8(pb); /* version */
812 avio_rb24(pb); /* flags */
815 creation_time = avio_rb64(pb);
818 creation_time = avio_rb32(pb);
819 avio_rb32(pb); /* modification time */
821 mov_metadata_creation_time(&c->fc->metadata, creation_time);
822 c->time_scale = avio_rb32(pb); /* time scale */
824 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
826 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
827 // set the AVCodecContext duration because the duration of individual tracks
829 if (c->time_scale > 0 && !c->trex_data)
830 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
831 avio_rb32(pb); /* preferred scale */
833 avio_rb16(pb); /* preferred volume */
835 avio_skip(pb, 10); /* reserved */
837 avio_skip(pb, 36); /* display matrix */
839 avio_rb32(pb); /* preview time */
840 avio_rb32(pb); /* preview duration */
841 avio_rb32(pb); /* poster time */
842 avio_rb32(pb); /* selection time */
843 avio_rb32(pb); /* selection duration */
844 avio_rb32(pb); /* current time */
845 avio_rb32(pb); /* next track ID */
849 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
854 if (c->fc->nb_streams < 1)
856 st = c->fc->streams[c->fc->nb_streams-1];
858 little_endian = avio_rb16(pb) & 0xFF;
859 av_dlog(c->fc, "enda %d\n", little_endian);
860 if (little_endian == 1) {
861 switch (st->codec->codec_id) {
862 case AV_CODEC_ID_PCM_S24BE:
863 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
865 case AV_CODEC_ID_PCM_S32BE:
866 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
868 case AV_CODEC_ID_PCM_F32BE:
869 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
871 case AV_CODEC_ID_PCM_F64BE:
872 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
881 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
884 unsigned mov_field_order;
885 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
887 if (c->fc->nb_streams < 1) // will happen with jp2 files
889 st = c->fc->streams[c->fc->nb_streams-1];
891 return AVERROR_INVALIDDATA;
892 mov_field_order = avio_rb16(pb);
893 if ((mov_field_order & 0xFF00) == 0x0100)
894 decoded_field_order = AV_FIELD_PROGRESSIVE;
895 else if ((mov_field_order & 0xFF00) == 0x0200) {
896 switch (mov_field_order & 0xFF) {
897 case 0x01: decoded_field_order = AV_FIELD_TT;
899 case 0x06: decoded_field_order = AV_FIELD_BB;
901 case 0x09: decoded_field_order = AV_FIELD_TB;
903 case 0x0E: decoded_field_order = AV_FIELD_BT;
907 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
908 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
910 st->codec->field_order = decoded_field_order;
915 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
916 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
917 enum AVCodecID codec_id)
924 if (c->fc->nb_streams < 1) // will happen with jp2 files
926 st= c->fc->streams[c->fc->nb_streams-1];
928 if (st->codec->codec_id != codec_id)
929 return 0; /* unexpected codec_id - don't mess with extradata */
931 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
932 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
933 return AVERROR_INVALIDDATA;
934 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
935 st->codec->extradata_size = 0;
938 buf = st->codec->extradata + st->codec->extradata_size;
939 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
940 AV_WB32( buf , atom.size + 8);
941 AV_WL32( buf + 4, atom.type);
942 err = avio_read(pb, buf + 8, atom.size);
945 } else if (err < atom.size) {
946 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
947 st->codec->extradata_size -= atom.size - err;
949 memset(buf + 8 + err, 0, FF_INPUT_BUFFER_PADDING_SIZE);
953 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
954 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
956 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
959 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
961 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
964 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
966 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
969 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
971 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
974 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
976 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
978 if (!ret && c->fc->nb_streams >= 1) {
979 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
980 if (avctx->extradata_size >= 40) {
981 avctx->height = AV_RB16(&avctx->extradata[36]);
982 avctx->width = AV_RB16(&avctx->extradata[38]);
988 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
990 if (c->fc->nb_streams >= 1) {
991 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
992 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
993 codec->codec_id == AV_CODEC_ID_H264 &&
996 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
997 if (avio_rb16(pb) == 0xd4d)
1003 return mov_read_avid(c, pb, atom);
1006 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1008 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1011 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1015 if (c->fc->nb_streams < 1)
1017 st = c->fc->streams[c->fc->nb_streams-1];
1019 if ((uint64_t)atom.size > (1<<30))
1020 return AVERROR_INVALIDDATA;
1022 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1023 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1024 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1025 // pass all frma atom to codec, needed at least for QDMC and QDM2
1026 av_free(st->codec->extradata);
1027 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1028 return AVERROR(ENOMEM);
1029 } else if (atom.size > 8) { /* to read frma, esds atoms */
1031 if ((ret = mov_read_default(c, pb, atom)) < 0)
1034 avio_skip(pb, atom.size);
1039 * This function reads atom content and puts data in extradata without tag
1040 * nor size unlike mov_read_extradata.
1042 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1046 if (c->fc->nb_streams < 1)
1048 st = c->fc->streams[c->fc->nb_streams-1];
1050 if ((uint64_t)atom.size > (1<<30))
1051 return AVERROR_INVALIDDATA;
1053 if (atom.size >= 10) {
1054 // Broken files created by legacy versions of libavformat will
1055 // wrap a whole fiel atom inside of a glbl atom.
1056 unsigned size = avio_rb32(pb);
1057 unsigned type = avio_rl32(pb);
1058 avio_seek(pb, -8, SEEK_CUR);
1059 if (type == MKTAG('f','i','e','l') && size == atom.size)
1060 return mov_read_default(c, pb, atom);
1062 av_free(st->codec->extradata);
1063 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1064 return AVERROR(ENOMEM);
1069 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1072 uint8_t profile_level;
1075 if (c->fc->nb_streams < 1)
1077 st = c->fc->streams[c->fc->nb_streams-1];
1079 if (atom.size >= (1<<28) || atom.size < 7)
1080 return AVERROR_INVALIDDATA;
1082 profile_level = avio_r8(pb);
1083 if ((profile_level & 0xf0) != 0xc0)
1086 avio_seek(pb, 6, SEEK_CUR);
1087 av_free(st->codec->extradata);
1088 if ((ret = ff_get_extradata(st->codec, pb, atom.size - 7)) < 0)
1095 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1096 * but can have extradata appended at the end after the 40 bytes belonging
1099 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1103 if (c->fc->nb_streams < 1)
1105 if (atom.size <= 40)
1107 st = c->fc->streams[c->fc->nb_streams-1];
1109 if ((uint64_t)atom.size > (1<<30))
1110 return AVERROR_INVALIDDATA;
1113 av_free(st->codec->extradata);
1114 if (ff_get_extradata(st->codec, pb, atom.size - 40) < 0)
1115 return AVERROR(ENOMEM);
1119 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1122 MOVStreamContext *sc;
1123 unsigned int i, entries;
1125 if (c->fc->nb_streams < 1)
1127 st = c->fc->streams[c->fc->nb_streams-1];
1130 avio_r8(pb); /* version */
1131 avio_rb24(pb); /* flags */
1133 entries = avio_rb32(pb);
1137 if (entries >= UINT_MAX/sizeof(int64_t))
1138 return AVERROR_INVALIDDATA;
1140 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1141 if (!sc->chunk_offsets)
1142 return AVERROR(ENOMEM);
1143 sc->chunk_count = entries;
1145 if (atom.type == MKTAG('s','t','c','o'))
1146 for (i = 0; i < entries && !pb->eof_reached; i++)
1147 sc->chunk_offsets[i] = avio_rb32(pb);
1148 else if (atom.type == MKTAG('c','o','6','4'))
1149 for (i = 0; i < entries && !pb->eof_reached; i++)
1150 sc->chunk_offsets[i] = avio_rb64(pb);
1152 return AVERROR_INVALIDDATA;
1154 sc->chunk_count = i;
1156 if (pb->eof_reached)
1163 * Compute codec id for 'lpcm' tag.
1164 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1166 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1173 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1176 static int mov_codec_id(AVStream *st, uint32_t format)
1178 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1181 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1182 (format & 0xFFFF) == 'T' + ('S' << 8)))
1183 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1185 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1186 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1187 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1188 /* skip old asf mpeg4 tag */
1189 format && format != MKTAG('m','p','4','s')) {
1190 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1192 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1194 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1195 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1196 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1197 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1198 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1200 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1204 st->codec->codec_tag = format;
1209 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1210 AVStream *st, MOVStreamContext *sc)
1212 uint8_t codec_name[32];
1213 unsigned int color_depth, len, j;
1214 int color_greyscale;
1217 avio_rb16(pb); /* version */
1218 avio_rb16(pb); /* revision level */
1219 avio_rb32(pb); /* vendor */
1220 avio_rb32(pb); /* temporal quality */
1221 avio_rb32(pb); /* spatial quality */
1223 st->codec->width = avio_rb16(pb); /* width */
1224 st->codec->height = avio_rb16(pb); /* height */
1226 avio_rb32(pb); /* horiz resolution */
1227 avio_rb32(pb); /* vert resolution */
1228 avio_rb32(pb); /* data size, always 0 */
1229 avio_rb16(pb); /* frames per samples */
1231 len = avio_r8(pb); /* codec name, pascal string */
1234 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1236 avio_skip(pb, 31 - len);
1239 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1241 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1242 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1243 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1244 st->codec->width &= ~1;
1245 st->codec->height &= ~1;
1247 /* Flash Media Server uses tag H263 with Sorenson Spark */
1248 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1249 !memcmp(codec_name, "Sorenson H263", 13))
1250 st->codec->codec_id = AV_CODEC_ID_FLV1;
1252 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1253 color_table_id = avio_rb16(pb); /* colortable id */
1254 av_dlog(c->fc, "depth %d, ctab id %d\n",
1255 st->codec->bits_per_coded_sample, color_table_id);
1256 /* figure out the palette situation */
1257 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1258 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1259 /* Do not create a greyscale palette for cinepak */
1260 if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1263 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1264 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1265 /* for palette traversal */
1266 unsigned int color_start, color_count, color_end;
1267 unsigned char a, r, g, b;
1269 if (color_greyscale) {
1270 int color_index, color_dec;
1271 /* compute the greyscale palette */
1272 st->codec->bits_per_coded_sample = color_depth;
1273 color_count = 1 << color_depth;
1275 color_dec = 256 / (color_count - 1);
1276 for (j = 0; j < color_count; j++) {
1277 r = g = b = color_index;
1278 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1279 color_index -= color_dec;
1280 if (color_index < 0)
1283 } else if (color_table_id) {
1284 const uint8_t *color_table;
1285 /* if flag bit 3 is set, use the default palette */
1286 color_count = 1 << color_depth;
1287 if (color_depth == 2)
1288 color_table = ff_qt_default_palette_4;
1289 else if (color_depth == 4)
1290 color_table = ff_qt_default_palette_16;
1292 color_table = ff_qt_default_palette_256;
1294 for (j = 0; j < color_count; j++) {
1295 r = color_table[j * 3 + 0];
1296 g = color_table[j * 3 + 1];
1297 b = color_table[j * 3 + 2];
1298 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1301 /* load the palette from the file */
1302 color_start = avio_rb32(pb);
1303 color_count = avio_rb16(pb);
1304 color_end = avio_rb16(pb);
1305 if ((color_start <= 255) && (color_end <= 255)) {
1306 for (j = color_start; j <= color_end; j++) {
1307 /* each A, R, G, or B component is 16 bits;
1308 * only use the top 8 bits */
1317 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1321 sc->has_palette = 1;
1325 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1326 AVStream *st, MOVStreamContext *sc)
1328 int bits_per_sample, flags;
1329 uint16_t version = avio_rb16(pb);
1330 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1332 avio_rb16(pb); /* revision level */
1333 avio_rb32(pb); /* vendor */
1335 st->codec->channels = avio_rb16(pb); /* channel count */
1336 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1337 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1339 sc->audio_cid = avio_rb16(pb);
1340 avio_rb16(pb); /* packet size = 0 */
1342 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1344 // Read QT version 1 fields. In version 0 these do not exist.
1345 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1347 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1350 sc->samples_per_frame = avio_rb32(pb);
1351 avio_rb32(pb); /* bytes per packet */
1352 sc->bytes_per_frame = avio_rb32(pb);
1353 avio_rb32(pb); /* bytes per sample */
1354 } else if (version == 2) {
1355 avio_rb32(pb); /* sizeof struct only */
1356 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1357 st->codec->channels = avio_rb32(pb);
1358 avio_rb32(pb); /* always 0x7F000000 */
1359 st->codec->bits_per_coded_sample = avio_rb32(pb);
1361 flags = avio_rb32(pb); /* lpcm format specific flag */
1362 sc->bytes_per_frame = avio_rb32(pb);
1363 sc->samples_per_frame = avio_rb32(pb);
1364 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1365 st->codec->codec_id =
1366 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1371 switch (st->codec->codec_id) {
1372 case AV_CODEC_ID_PCM_S8:
1373 case AV_CODEC_ID_PCM_U8:
1374 if (st->codec->bits_per_coded_sample == 16)
1375 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1377 case AV_CODEC_ID_PCM_S16LE:
1378 case AV_CODEC_ID_PCM_S16BE:
1379 if (st->codec->bits_per_coded_sample == 8)
1380 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1381 else if (st->codec->bits_per_coded_sample == 24)
1382 st->codec->codec_id =
1383 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1384 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1386 /* set values for old format before stsd version 1 appeared */
1387 case AV_CODEC_ID_MACE3:
1388 sc->samples_per_frame = 6;
1389 sc->bytes_per_frame = 2 * st->codec->channels;
1391 case AV_CODEC_ID_MACE6:
1392 sc->samples_per_frame = 6;
1393 sc->bytes_per_frame = 1 * st->codec->channels;
1395 case AV_CODEC_ID_ADPCM_IMA_QT:
1396 sc->samples_per_frame = 64;
1397 sc->bytes_per_frame = 34 * st->codec->channels;
1399 case AV_CODEC_ID_GSM:
1400 sc->samples_per_frame = 160;
1401 sc->bytes_per_frame = 33;
1407 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1408 if (bits_per_sample) {
1409 st->codec->bits_per_coded_sample = bits_per_sample;
1410 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1414 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1415 AVStream *st, MOVStreamContext *sc,
1418 // ttxt stsd contains display flags, justification, background
1419 // color, fonts, and default styles, so fake an atom to read it
1420 MOVAtom fake_atom = { .size = size };
1421 // mp4s contains a regular esds atom
1422 if (st->codec->codec_tag != AV_RL32("mp4s"))
1423 mov_read_glbl(c, pb, fake_atom);
1424 st->codec->width = sc->width;
1425 st->codec->height = sc->height;
1428 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1433 y = (ycbcr >> 16) & 0xFF;
1434 cr = (ycbcr >> 8) & 0xFF;
1437 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1438 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1439 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1441 return (r << 16) | (g << 8) | b;
1444 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1446 char buf[256] = {0};
1447 uint8_t *src = st->codec->extradata;
1450 if (st->codec->extradata_size != 64)
1453 if (st->codec->width > 0 && st->codec->height > 0)
1454 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1455 st->codec->width, st->codec->height);
1456 av_strlcat(buf, "palette: ", sizeof(buf));
1458 for (i = 0; i < 16; i++) {
1459 uint32_t yuv = AV_RB32(src + i * 4);
1460 uint32_t rgba = yuv_to_rgba(yuv);
1462 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1465 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1468 av_freep(&st->codec->extradata);
1469 st->codec->extradata_size = 0;
1470 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1471 if (!st->codec->extradata)
1472 return AVERROR(ENOMEM);
1473 st->codec->extradata_size = strlen(buf);
1474 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1479 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1480 AVStream *st, MOVStreamContext *sc,
1483 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1484 if (ff_get_extradata(st->codec, pb, size) < 0)
1485 return AVERROR(ENOMEM);
1487 MOVStreamContext *tmcd_ctx = st->priv_data;
1489 val = AV_RB32(st->codec->extradata + 4);
1490 tmcd_ctx->tmcd_flags = val;
1492 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1493 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
1494 st->codec->time_base.num = 1;
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;
1530 // FIXME: Why is the following needed for some files?
1531 sc->samples_per_frame = 160;
1532 if (!sc->bytes_per_frame)
1533 sc->bytes_per_frame = 35;
1535 case AV_CODEC_ID_AMR_NB:
1536 st->codec->channels = 1;
1537 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1538 st->codec->sample_rate = 8000;
1540 case AV_CODEC_ID_AMR_WB:
1541 st->codec->channels = 1;
1542 st->codec->sample_rate = 16000;
1544 case AV_CODEC_ID_MP2:
1545 case AV_CODEC_ID_MP3:
1546 /* force type after stsd for m1a hdlr */
1547 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1548 st->need_parsing = AVSTREAM_PARSE_FULL;
1550 case AV_CODEC_ID_GSM:
1551 case AV_CODEC_ID_ADPCM_MS:
1552 case AV_CODEC_ID_ADPCM_IMA_WAV:
1553 case AV_CODEC_ID_ILBC:
1554 case AV_CODEC_ID_MACE3:
1555 case AV_CODEC_ID_MACE6:
1556 case AV_CODEC_ID_QDM2:
1557 st->codec->block_align = sc->bytes_per_frame;
1559 case AV_CODEC_ID_ALAC:
1560 if (st->codec->extradata_size == 36) {
1561 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1562 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1565 case AV_CODEC_ID_AC3:
1566 case AV_CODEC_ID_MPEG1VIDEO:
1567 case AV_CODEC_ID_VC1:
1568 st->need_parsing = AVSTREAM_PARSE_FULL;
1576 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1577 int codec_tag, int format,
1580 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1583 (codec_tag != format &&
1584 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1585 : codec_tag != MKTAG('j','p','e','g')))) {
1586 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1587 * export it as a separate AVStream but this needs a few changes
1588 * in the MOV demuxer, patch welcome. */
1590 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1591 avio_skip(pb, size);
1594 if ( codec_tag == AV_RL32("avc1") ||
1595 codec_tag == AV_RL32("hvc1") ||
1596 codec_tag == AV_RL32("hev1")
1598 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
1603 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1606 MOVStreamContext *sc;
1607 int pseudo_stream_id;
1609 if (c->fc->nb_streams < 1)
1611 st = c->fc->streams[c->fc->nb_streams-1];
1614 for (pseudo_stream_id = 0;
1615 pseudo_stream_id < entries && !pb->eof_reached;
1616 pseudo_stream_id++) {
1617 //Parsing Sample description table
1619 int ret, dref_id = 1;
1620 MOVAtom a = { AV_RL32("stsd") };
1621 int64_t start_pos = avio_tell(pb);
1622 int64_t size = avio_rb32(pb); /* size */
1623 uint32_t format = avio_rl32(pb); /* data format */
1626 avio_rb32(pb); /* reserved */
1627 avio_rb16(pb); /* reserved */
1628 dref_id = avio_rb16(pb);
1629 }else if (size <= 7){
1630 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1631 return AVERROR_INVALIDDATA;
1634 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1635 size - (avio_tell(pb) - start_pos)))
1638 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1639 sc->dref_id= dref_id;
1641 id = mov_codec_id(st, format);
1643 av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1644 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1645 (format >> 24) & 0xff, st->codec->codec_type);
1647 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1648 st->codec->codec_id = id;
1649 mov_parse_stsd_video(c, pb, st, sc);
1650 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1651 st->codec->codec_id = id;
1652 mov_parse_stsd_audio(c, pb, st, sc);
1653 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1654 st->codec->codec_id = id;
1655 mov_parse_stsd_subtitle(c, pb, st, sc,
1656 size - (avio_tell(pb) - start_pos));
1658 ret = mov_parse_stsd_data(c, pb, st, sc,
1659 size - (avio_tell(pb) - start_pos));
1663 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1664 a.size = size - (avio_tell(pb) - start_pos);
1666 if ((ret = mov_read_default(c, pb, a)) < 0)
1668 } else if (a.size > 0)
1669 avio_skip(pb, a.size);
1672 if (pb->eof_reached)
1675 return mov_finalize_stsd_codec(c, pb, st, sc);
1678 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1682 avio_r8(pb); /* version */
1683 avio_rb24(pb); /* flags */
1684 entries = avio_rb32(pb);
1686 return ff_mov_read_stsd_entries(c, pb, entries);
1689 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1692 MOVStreamContext *sc;
1693 unsigned int i, entries;
1695 if (c->fc->nb_streams < 1)
1697 st = c->fc->streams[c->fc->nb_streams-1];
1700 avio_r8(pb); /* version */
1701 avio_rb24(pb); /* flags */
1703 entries = avio_rb32(pb);
1705 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1709 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1710 return AVERROR_INVALIDDATA;
1711 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1713 return AVERROR(ENOMEM);
1715 for (i = 0; i < entries && !pb->eof_reached; i++) {
1716 sc->stsc_data[i].first = avio_rb32(pb);
1717 sc->stsc_data[i].count = avio_rb32(pb);
1718 sc->stsc_data[i].id = avio_rb32(pb);
1723 if (pb->eof_reached)
1729 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1732 MOVStreamContext *sc;
1733 unsigned i, entries;
1735 if (c->fc->nb_streams < 1)
1737 st = c->fc->streams[c->fc->nb_streams-1];
1740 avio_rb32(pb); // version + flags
1742 entries = avio_rb32(pb);
1743 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1744 return AVERROR_INVALIDDATA;
1745 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1747 return AVERROR(ENOMEM);
1749 for (i = 0; i < entries && !pb->eof_reached; i++) {
1750 sc->stps_data[i] = avio_rb32(pb);
1751 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1756 if (pb->eof_reached)
1762 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1765 MOVStreamContext *sc;
1766 unsigned int i, entries;
1768 if (c->fc->nb_streams < 1)
1770 st = c->fc->streams[c->fc->nb_streams-1];
1773 avio_r8(pb); /* version */
1774 avio_rb24(pb); /* flags */
1776 entries = avio_rb32(pb);
1778 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1782 sc->keyframe_absent = 1;
1783 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1784 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1787 if (entries >= UINT_MAX / sizeof(int))
1788 return AVERROR_INVALIDDATA;
1789 sc->keyframes = av_malloc(entries * sizeof(int));
1791 return AVERROR(ENOMEM);
1793 for (i = 0; i < entries && !pb->eof_reached; i++) {
1794 sc->keyframes[i] = avio_rb32(pb);
1795 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1798 sc->keyframe_count = i;
1800 if (pb->eof_reached)
1806 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1809 MOVStreamContext *sc;
1810 unsigned int i, entries, sample_size, field_size, num_bytes;
1814 if (c->fc->nb_streams < 1)
1816 st = c->fc->streams[c->fc->nb_streams-1];
1819 avio_r8(pb); /* version */
1820 avio_rb24(pb); /* flags */
1822 if (atom.type == MKTAG('s','t','s','z')) {
1823 sample_size = avio_rb32(pb);
1824 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1825 sc->sample_size = sample_size;
1826 sc->stsz_sample_size = sample_size;
1830 avio_rb24(pb); /* reserved */
1831 field_size = avio_r8(pb);
1833 entries = avio_rb32(pb);
1835 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1837 sc->sample_count = entries;
1841 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1842 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1843 return AVERROR_INVALIDDATA;
1848 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1849 return AVERROR_INVALIDDATA;
1850 sc->sample_sizes = av_malloc(entries * sizeof(int));
1851 if (!sc->sample_sizes)
1852 return AVERROR(ENOMEM);
1854 num_bytes = (entries*field_size+4)>>3;
1856 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1858 av_freep(&sc->sample_sizes);
1859 return AVERROR(ENOMEM);
1862 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1863 av_freep(&sc->sample_sizes);
1865 return AVERROR_INVALIDDATA;
1868 init_get_bits(&gb, buf, 8*num_bytes);
1870 for (i = 0; i < entries && !pb->eof_reached; i++) {
1871 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1872 sc->data_size += sc->sample_sizes[i];
1875 sc->sample_count = i;
1877 if (pb->eof_reached)
1884 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1887 MOVStreamContext *sc;
1888 unsigned int i, entries;
1890 int64_t total_sample_count=0;
1892 if (c->fc->nb_streams < 1)
1894 st = c->fc->streams[c->fc->nb_streams-1];
1897 avio_r8(pb); /* version */
1898 avio_rb24(pb); /* flags */
1899 entries = avio_rb32(pb);
1901 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1902 c->fc->nb_streams-1, entries);
1904 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1907 av_free(sc->stts_data);
1908 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1910 return AVERROR(ENOMEM);
1912 for (i = 0; i < entries && !pb->eof_reached; i++) {
1913 int sample_duration;
1916 sample_count=avio_rb32(pb);
1917 sample_duration = avio_rb32(pb);
1919 /* sample_duration < 0 is invalid based on the spec */
1920 if (sample_duration < 0) {
1921 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta %d in STTS, at %d st:%d\n",
1922 sample_duration, i, c->fc->nb_streams-1);
1923 sample_duration = 1;
1925 if (sample_count < 0) {
1926 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
1927 return AVERROR_INVALIDDATA;
1929 sc->stts_data[i].count= sample_count;
1930 sc->stts_data[i].duration= sample_duration;
1932 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1933 sample_count, sample_duration);
1937 && sample_count == 1
1938 && total_sample_count > 100
1939 && sample_duration/10 > duration / total_sample_count)
1940 sample_duration = duration / total_sample_count;
1941 duration+=(int64_t)sample_duration*sample_count;
1942 total_sample_count+=sample_count;
1947 sc->duration_for_fps += duration;
1948 sc->nb_frames_for_fps += total_sample_count;
1950 if (pb->eof_reached)
1953 st->nb_frames= total_sample_count;
1955 st->duration= duration;
1956 sc->track_end = duration;
1960 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
1963 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1967 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1970 MOVStreamContext *sc;
1971 unsigned int i, entries;
1973 if (c->fc->nb_streams < 1)
1975 st = c->fc->streams[c->fc->nb_streams-1];
1978 avio_r8(pb); /* version */
1979 avio_rb24(pb); /* flags */
1980 entries = avio_rb32(pb);
1982 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1986 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1987 return AVERROR_INVALIDDATA;
1988 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1990 return AVERROR(ENOMEM);
1992 for (i = 0; i < entries && !pb->eof_reached; i++) {
1993 int count =avio_rb32(pb);
1994 int duration =avio_rb32(pb);
1996 sc->ctts_data[i].count = count;
1997 sc->ctts_data[i].duration= duration;
1999 av_dlog(c->fc, "count=%d, duration=%d\n",
2002 if (FFABS(duration) > (1<<28) && i+2<entries) {
2003 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2004 av_freep(&sc->ctts_data);
2010 mov_update_dts_shift(sc, duration);
2015 if (pb->eof_reached)
2018 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
2023 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2026 MOVStreamContext *sc;
2027 unsigned int i, entries;
2029 uint32_t grouping_type;
2031 if (c->fc->nb_streams < 1)
2033 st = c->fc->streams[c->fc->nb_streams-1];
2036 version = avio_r8(pb); /* version */
2037 avio_rb24(pb); /* flags */
2038 grouping_type = avio_rl32(pb);
2039 if (grouping_type != MKTAG( 'r','a','p',' '))
2040 return 0; /* only support 'rap ' grouping */
2042 avio_rb32(pb); /* grouping_type_parameter */
2044 entries = avio_rb32(pb);
2047 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2048 return AVERROR_INVALIDDATA;
2049 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2051 return AVERROR(ENOMEM);
2053 for (i = 0; i < entries && !pb->eof_reached; i++) {
2054 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2055 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2058 sc->rap_group_count = i;
2060 return pb->eof_reached ? AVERROR_EOF : 0;
2063 static void mov_build_index(MOVContext *mov, AVStream *st)
2065 MOVStreamContext *sc = st->priv_data;
2066 int64_t current_offset;
2067 int64_t current_dts = 0;
2068 unsigned int stts_index = 0;
2069 unsigned int stsc_index = 0;
2070 unsigned int stss_index = 0;
2071 unsigned int stps_index = 0;
2073 uint64_t stream_size = 0;
2075 /* adjust first dts according to edit list */
2076 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
2077 if (sc->empty_duration)
2078 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
2079 sc->time_offset = sc->start_time - sc->empty_duration;
2080 current_dts = -sc->time_offset;
2081 if (sc->ctts_count>0 && sc->stts_count>0 &&
2082 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2083 /* more than 16 frames delay, dts are likely wrong
2084 this happens with files created by iMovie */
2086 st->codec->has_b_frames = 1;
2090 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2091 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2092 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2093 unsigned int current_sample = 0;
2094 unsigned int stts_sample = 0;
2095 unsigned int sample_size;
2096 unsigned int distance = 0;
2097 unsigned int rap_group_index = 0;
2098 unsigned int rap_group_sample = 0;
2099 int rap_group_present = sc->rap_group_count && sc->rap_group;
2100 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2102 current_dts -= sc->dts_shift;
2104 if (!sc->sample_count || st->nb_index_entries)
2106 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2108 if (av_reallocp_array(&st->index_entries,
2109 st->nb_index_entries + sc->sample_count,
2110 sizeof(*st->index_entries)) < 0) {
2111 st->nb_index_entries = 0;
2114 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2116 for (i = 0; i < sc->chunk_count; i++) {
2117 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2118 current_offset = sc->chunk_offsets[i];
2119 while (stsc_index + 1 < sc->stsc_count &&
2120 i + 1 == sc->stsc_data[stsc_index + 1].first)
2123 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2124 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2125 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2126 sc->stsz_sample_size = sc->sample_size;
2128 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2129 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2130 sc->stsz_sample_size = sc->sample_size;
2133 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2135 if (current_sample >= sc->sample_count) {
2136 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2140 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2142 if (stss_index + 1 < sc->keyframe_count)
2144 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2146 if (stps_index + 1 < sc->stps_count)
2149 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2150 if (sc->rap_group[rap_group_index].index > 0)
2152 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2153 rap_group_sample = 0;
2157 if (sc->keyframe_absent
2159 && !rap_group_present
2160 && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2164 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2165 if (sc->pseudo_stream_id == -1 ||
2166 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2167 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2168 e->pos = current_offset;
2169 e->timestamp = current_dts;
2170 e->size = sample_size;
2171 e->min_distance = distance;
2172 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2173 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2174 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2175 current_offset, current_dts, sample_size, distance, keyframe);
2176 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2177 ff_rfps_add_frame(mov->fc, st, current_dts);
2180 current_offset += sample_size;
2181 stream_size += sample_size;
2182 current_dts += sc->stts_data[stts_index].duration;
2186 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2192 if (st->duration > 0)
2193 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2195 unsigned chunk_samples, total = 0;
2197 // compute total chunk count
2198 for (i = 0; i < sc->stsc_count; i++) {
2199 unsigned count, chunk_count;
2201 chunk_samples = sc->stsc_data[i].count;
2202 if (i != sc->stsc_count - 1 &&
2203 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2204 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2208 if (sc->samples_per_frame >= 160) { // gsm
2209 count = chunk_samples / sc->samples_per_frame;
2210 } else if (sc->samples_per_frame > 1) {
2211 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2212 count = (chunk_samples+samples-1) / samples;
2214 count = (chunk_samples+1023) / 1024;
2217 if (i < sc->stsc_count - 1)
2218 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2220 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2221 total += chunk_count * count;
2224 av_dlog(mov->fc, "chunk count %d\n", total);
2225 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2227 if (av_reallocp_array(&st->index_entries,
2228 st->nb_index_entries + total,
2229 sizeof(*st->index_entries)) < 0) {
2230 st->nb_index_entries = 0;
2233 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2236 for (i = 0; i < sc->chunk_count; i++) {
2237 current_offset = sc->chunk_offsets[i];
2238 if (stsc_index + 1 < sc->stsc_count &&
2239 i + 1 == sc->stsc_data[stsc_index + 1].first)
2241 chunk_samples = sc->stsc_data[stsc_index].count;
2243 while (chunk_samples > 0) {
2245 unsigned size, samples;
2247 if (sc->samples_per_frame >= 160) { // gsm
2248 samples = sc->samples_per_frame;
2249 size = sc->bytes_per_frame;
2251 if (sc->samples_per_frame > 1) {
2252 samples = FFMIN((1024 / sc->samples_per_frame)*
2253 sc->samples_per_frame, chunk_samples);
2254 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2256 samples = FFMIN(1024, chunk_samples);
2257 size = samples * sc->sample_size;
2261 if (st->nb_index_entries >= total) {
2262 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2265 e = &st->index_entries[st->nb_index_entries++];
2266 e->pos = current_offset;
2267 e->timestamp = current_dts;
2269 e->min_distance = 0;
2270 e->flags = AVINDEX_KEYFRAME;
2271 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2272 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2275 current_offset += size;
2276 current_dts += samples;
2277 chunk_samples -= samples;
2283 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2284 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2286 /* try relative path, we do not try the absolute because it can leak information about our
2287 system to an attacker */
2288 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2289 char filename[1024];
2290 const char *src_path;
2293 /* find a source dir */
2294 src_path = strrchr(src, '/');
2300 /* find a next level down to target */
2301 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2302 if (ref->path[l] == '/') {
2303 if (i == ref->nlvl_to - 1)
2309 /* compose filename if next level down to target was found */
2310 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2311 memcpy(filename, src, src_path - src);
2312 filename[src_path - src] = 0;
2314 for (i = 1; i < ref->nlvl_from; i++)
2315 av_strlcat(filename, "../", 1024);
2317 av_strlcat(filename, ref->path + l + 1, 1024);
2319 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2322 } else if (use_absolute_path) {
2323 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2324 "this is a possible security issue\n");
2325 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2329 return AVERROR(ENOENT);
2332 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2334 if (sc->time_scale <= 0) {
2335 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2336 sc->time_scale = c->time_scale;
2337 if (sc->time_scale <= 0)
2342 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2345 MOVStreamContext *sc;
2348 st = avformat_new_stream(c->fc, NULL);
2349 if (!st) return AVERROR(ENOMEM);
2350 st->id = c->fc->nb_streams;
2351 sc = av_mallocz(sizeof(MOVStreamContext));
2352 if (!sc) return AVERROR(ENOMEM);
2355 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2356 sc->ffindex = st->index;
2358 if ((ret = mov_read_default(c, pb, atom)) < 0)
2362 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2363 (!sc->sample_size && !sc->sample_count))) {
2364 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2369 fix_timescale(c, sc);
2371 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2373 mov_build_index(c, st);
2375 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2376 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2377 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2378 c->use_absolute_path, c->fc) < 0)
2379 av_log(c->fc, AV_LOG_ERROR,
2380 "stream %d, error opening alias: path='%s', dir='%s', "
2381 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2382 st->index, dref->path, dref->dir, dref->filename,
2383 dref->volume, dref->nlvl_from, dref->nlvl_to);
2386 sc->pb_is_copied = 1;
2389 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2390 if (!st->sample_aspect_ratio.num &&
2391 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2392 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2393 ((double)st->codec->width * sc->height), INT_MAX);
2396 #if FF_API_R_FRAME_RATE
2397 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2398 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2399 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2403 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2404 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2405 TAG_IS_AVCI(st->codec->codec_tag)) {
2406 ret = ff_generate_avci_extradata(st);
2411 switch (st->codec->codec_id) {
2412 #if CONFIG_H261_DECODER
2413 case AV_CODEC_ID_H261:
2415 #if CONFIG_H263_DECODER
2416 case AV_CODEC_ID_H263:
2418 #if CONFIG_MPEG4_DECODER
2419 case AV_CODEC_ID_MPEG4:
2421 st->codec->width = 0; /* let decoder init width/height */
2422 st->codec->height= 0;
2426 /* Do not need those anymore. */
2427 av_freep(&sc->chunk_offsets);
2428 av_freep(&sc->stsc_data);
2429 av_freep(&sc->sample_sizes);
2430 av_freep(&sc->keyframes);
2431 av_freep(&sc->stts_data);
2432 av_freep(&sc->stps_data);
2433 av_freep(&sc->rap_group);
2438 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2441 c->itunes_metadata = 1;
2442 ret = mov_read_default(c, pb, atom);
2443 c->itunes_metadata = 0;
2447 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
2449 int64_t end = avio_tell(pb) + size;
2450 uint8_t *key = NULL, *val = NULL;
2453 MOVStreamContext *sc;
2455 if (c->fc->nb_streams < 1)
2457 st = c->fc->streams[c->fc->nb_streams-1];
2460 for (i = 0; i < 2; i++) {
2464 if (end - avio_tell(pb) <= 12)
2467 len = avio_rb32(pb);
2468 tag = avio_rl32(pb);
2469 avio_skip(pb, 4); // flags
2471 if (len < 12 || len - 12 > end - avio_tell(pb))
2475 if (tag == MKTAG('n', 'a', 'm', 'e'))
2477 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2484 *p = av_malloc(len + 1);
2487 avio_read(pb, *p, len);
2492 if (strcmp(key, "iTunSMPB") == 0) {
2493 int priming, remainder, samples;
2494 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
2495 if(priming>0 && priming<16384)
2496 sc->start_pad = priming;
2498 } else if (strcmp(key, "cdec") == 0) {
2500 av_dict_set(&c->fc->metadata, key, val,
2501 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2506 avio_seek(pb, end, SEEK_SET);
2512 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2514 int64_t end = avio_tell(pb) + atom.size;
2520 len = avio_rb32(pb);
2521 tag = avio_rl32(pb);
2523 if (len > atom.size)
2526 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2527 uint8_t domain[128];
2530 avio_skip(pb, 4); // flags
2533 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2534 avio_skip(pb, len - domain_len);
2535 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
2539 av_log(c->fc, AV_LOG_VERBOSE,
2540 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2544 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2546 while (atom.size > 8) {
2547 uint32_t tag = avio_rl32(pb);
2549 if (tag == MKTAG('h','d','l','r')) {
2550 avio_seek(pb, -8, SEEK_CUR);
2552 return mov_read_default(c, pb, atom);
2558 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2563 int64_t disp_transform[2];
2564 int display_matrix[3][3];
2566 MOVStreamContext *sc;
2570 if (c->fc->nb_streams < 1)
2572 st = c->fc->streams[c->fc->nb_streams-1];
2575 version = avio_r8(pb);
2576 flags = avio_rb24(pb);
2577 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2583 avio_rb32(pb); /* creation time */
2584 avio_rb32(pb); /* modification time */
2586 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2587 avio_rb32(pb); /* reserved */
2589 /* highlevel (considering edits) duration in movie timebase */
2590 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2591 avio_rb32(pb); /* reserved */
2592 avio_rb32(pb); /* reserved */
2594 avio_rb16(pb); /* layer */
2595 avio_rb16(pb); /* alternate group */
2596 avio_rb16(pb); /* volume */
2597 avio_rb16(pb); /* reserved */
2599 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2600 // they're kept in fixed point format through all calculations
2601 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2602 // side data, but the scale factor is not needed to calculate aspect ratio
2603 for (i = 0; i < 3; i++) {
2604 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2605 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2606 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2609 width = avio_rb32(pb); // 16.16 fixed point track width
2610 height = avio_rb32(pb); // 16.16 fixed point track height
2611 sc->width = width >> 16;
2612 sc->height = height >> 16;
2614 // save the matrix and add rotate metadata when it is not the default
2616 if (display_matrix[0][0] != (1 << 16) ||
2617 display_matrix[1][1] != (1 << 16) ||
2618 display_matrix[2][2] != (1 << 30) ||
2619 display_matrix[0][1] || display_matrix[0][2] ||
2620 display_matrix[1][0] || display_matrix[1][2] ||
2621 display_matrix[2][0] || display_matrix[2][1]) {
2625 av_freep(&sc->display_matrix);
2626 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2627 if (!sc->display_matrix)
2628 return AVERROR(ENOMEM);
2630 for (i = 0; i < 3; i++)
2631 for (j = 0; j < 3; j++)
2632 sc->display_matrix[i * 3 + j] = display_matrix[j][i];
2634 rotate = av_display_rotation_get(sc->display_matrix);
2635 if (!isnan(rotate)) {
2636 char rotate_buf[64];
2638 if (rotate < 0) // for backward compatibility
2640 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
2641 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
2645 // transform the display width/height according to the matrix
2646 // skip this if the display matrix is the default identity matrix
2647 // or if it is rotating the picture, ex iPhone 3GS
2648 // to keep the same scale, use [width height 1<<16]
2649 if (width && height &&
2650 ((display_matrix[0][0] != 65536 ||
2651 display_matrix[1][1] != 65536) &&
2652 !display_matrix[0][1] &&
2653 !display_matrix[1][0] &&
2654 !display_matrix[2][0] && !display_matrix[2][1])) {
2655 for (i = 0; i < 2; i++)
2657 (int64_t) width * display_matrix[0][i] +
2658 (int64_t) height * display_matrix[1][i] +
2659 ((int64_t) display_matrix[2][i] << 16);
2661 //sample aspect ratio is new width/height divided by old width/height
2662 st->sample_aspect_ratio = av_d2q(
2663 ((double) disp_transform[0] * height) /
2664 ((double) disp_transform[1] * width), INT_MAX);
2669 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2671 MOVFragment *frag = &c->fragment;
2672 MOVTrackExt *trex = NULL;
2673 int flags, track_id, i;
2675 avio_r8(pb); /* version */
2676 flags = avio_rb24(pb);
2678 track_id = avio_rb32(pb);
2680 return AVERROR_INVALIDDATA;
2681 frag->track_id = track_id;
2682 for (i = 0; i < c->trex_count; i++)
2683 if (c->trex_data[i].track_id == frag->track_id) {
2684 trex = &c->trex_data[i];
2688 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2689 return AVERROR_INVALIDDATA;
2692 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2693 avio_rb64(pb) : frag->moof_offset;
2694 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2696 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2697 avio_rb32(pb) : trex->duration;
2698 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2699 avio_rb32(pb) : trex->size;
2700 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2701 avio_rb32(pb) : trex->flags;
2702 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2706 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2708 c->chapter_track = avio_rb32(pb);
2712 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2717 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2718 return AVERROR_INVALIDDATA;
2719 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2720 sizeof(*c->trex_data))) < 0) {
2725 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2727 trex = &c->trex_data[c->trex_count++];
2728 avio_r8(pb); /* version */
2729 avio_rb24(pb); /* flags */
2730 trex->track_id = avio_rb32(pb);
2731 trex->stsd_id = avio_rb32(pb);
2732 trex->duration = avio_rb32(pb);
2733 trex->size = avio_rb32(pb);
2734 trex->flags = avio_rb32(pb);
2738 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2740 MOVFragment *frag = &c->fragment;
2741 AVStream *st = NULL;
2742 MOVStreamContext *sc;
2746 int data_offset = 0;
2747 unsigned entries, first_sample_flags = frag->flags;
2748 int flags, distance, i, found_keyframe = 0, err;
2750 for (i = 0; i < c->fc->nb_streams; i++) {
2751 if (c->fc->streams[i]->id == frag->track_id) {
2752 st = c->fc->streams[i];
2757 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2758 return AVERROR_INVALIDDATA;
2761 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
2763 avio_r8(pb); /* version */
2764 flags = avio_rb24(pb);
2765 entries = avio_rb32(pb);
2766 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2768 /* Always assume the presence of composition time offsets.
2769 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2770 * 1) in the initial movie, there are no samples.
2771 * 2) in the first movie fragment, there is only one sample without composition time offset.
2772 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2773 if (!sc->ctts_count && sc->sample_count)
2775 /* Complement ctts table if moov atom doesn't have ctts atom. */
2776 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2778 return AVERROR(ENOMEM);
2779 sc->ctts_data = ctts_data;
2780 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2781 sc->ctts_data[sc->ctts_count].duration = 0;
2784 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2785 return AVERROR_INVALIDDATA;
2786 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2787 sizeof(*sc->ctts_data))) < 0) {
2791 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2792 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2793 dts = sc->track_end - sc->time_offset;
2794 offset = frag->base_data_offset + data_offset;
2796 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2797 for (i = 0; i < entries && !pb->eof_reached; i++) {
2798 unsigned sample_size = frag->size;
2799 int sample_flags = i ? frag->flags : first_sample_flags;
2800 unsigned sample_duration = frag->duration;
2803 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2804 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2805 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2806 sc->ctts_data[sc->ctts_count].count = 1;
2807 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2809 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
2811 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2813 else if (!found_keyframe)
2814 keyframe = found_keyframe =
2815 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2816 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2819 av_add_index_entry(st, offset, dts, sample_size, distance,
2820 keyframe ? AVINDEX_KEYFRAME : 0);
2821 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2822 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2823 offset, dts, sample_size, distance, keyframe);
2825 dts += sample_duration;
2826 offset += sample_size;
2827 sc->data_size += sample_size;
2828 sc->duration_for_fps += sample_duration;
2829 sc->nb_frames_for_fps ++;
2832 if (pb->eof_reached)
2835 frag->moof_offset = offset;
2836 st->duration = sc->track_end = dts + sc->time_offset;
2840 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2841 /* like the files created with Adobe Premiere 5.0, for samples see */
2842 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2843 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2848 return 0; /* continue */
2849 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2850 avio_skip(pb, atom.size - 4);
2853 atom.type = avio_rl32(pb);
2855 if (atom.type != MKTAG('m','d','a','t')) {
2856 avio_skip(pb, atom.size);
2859 err = mov_read_mdat(c, pb, atom);
2863 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2868 uint8_t *moov_data; /* uncompressed data */
2869 long cmov_len, moov_len;
2872 avio_rb32(pb); /* dcom atom */
2873 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2874 return AVERROR_INVALIDDATA;
2875 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2876 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
2877 return AVERROR_INVALIDDATA;
2879 avio_rb32(pb); /* cmvd atom */
2880 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2881 return AVERROR_INVALIDDATA;
2882 moov_len = avio_rb32(pb); /* uncompressed size */
2883 cmov_len = atom.size - 6 * 4;
2885 cmov_data = av_malloc(cmov_len);
2887 return AVERROR(ENOMEM);
2888 moov_data = av_malloc(moov_len);
2891 return AVERROR(ENOMEM);
2893 avio_read(pb, cmov_data, cmov_len);
2894 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2895 goto free_and_return;
2896 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2897 goto free_and_return;
2898 atom.type = MKTAG('m','o','o','v');
2899 atom.size = moov_len;
2900 ret = mov_read_default(c, &ctx, atom);
2906 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2907 return AVERROR(ENOSYS);
2911 /* edit list atom */
2912 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2914 MOVStreamContext *sc;
2915 int i, edit_count, version, edit_start_index = 0;
2916 int unsupported = 0;
2918 if (c->fc->nb_streams < 1 || c->ignore_editlist)
2920 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2922 version = avio_r8(pb); /* version */
2923 avio_rb24(pb); /* flags */
2924 edit_count = avio_rb32(pb); /* entries */
2926 if ((uint64_t)edit_count*12+8 > atom.size)
2927 return AVERROR_INVALIDDATA;
2929 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2930 for (i=0; i<edit_count; i++){
2935 duration = avio_rb64(pb);
2936 time = avio_rb64(pb);
2938 duration = avio_rb32(pb); /* segment duration */
2939 time = (int32_t)avio_rb32(pb); /* media time */
2941 rate = avio_rb32(pb);
2942 if (i == 0 && time == -1) {
2943 sc->empty_duration = duration;
2944 edit_start_index = 1;
2945 } else if (i == edit_start_index && time >= 0)
2946 sc->start_time = time;
2950 av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
2951 duration, time, rate / 65536.0);
2955 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2956 "a/v desync might occur, patch welcome\n");
2961 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2963 MOVStreamContext *sc;
2965 if (c->fc->nb_streams < 1)
2966 return AVERROR_INVALIDDATA;
2967 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
2968 sc->timecode_track = avio_rb32(pb);
2972 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2976 static const uint8_t uuid_isml_manifest[] = {
2977 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2978 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2981 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
2982 return AVERROR_INVALIDDATA;
2984 ret = avio_read(pb, uuid, sizeof(uuid));
2987 } else if (ret != sizeof(uuid)) {
2988 return AVERROR_INVALIDDATA;
2990 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
2991 uint8_t *buffer, *ptr;
2993 size_t len = atom.size - sizeof(uuid);
2996 return AVERROR_INVALIDDATA;
2998 ret = avio_skip(pb, 4); // zeroes
3001 buffer = av_mallocz(len + 1);
3003 return AVERROR(ENOMEM);
3005 ret = avio_read(pb, buffer, len);
3009 } else if (ret != len) {
3011 return AVERROR_INVALIDDATA;
3015 while ((ptr = av_stristr(ptr, "systemBitrate=\"")) != NULL) {
3016 ptr += sizeof("systemBitrate=\"") - 1;
3017 c->bitrates_count++;
3018 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3020 c->bitrates_count = 0;
3022 return AVERROR(ENOMEM);
3025 ret = strtol(ptr, &endptr, 10);
3026 if (ret < 0 || errno || *endptr != '"') {
3027 c->bitrates[c->bitrates_count - 1] = 0;
3029 c->bitrates[c->bitrates_count - 1] = ret;
3038 static const MOVParseTableEntry mov_default_parse_table[] = {
3039 { MKTAG('A','C','L','R'), mov_read_avid },
3040 { MKTAG('A','P','R','G'), mov_read_avid },
3041 { MKTAG('A','A','L','P'), mov_read_avid },
3042 { MKTAG('A','R','E','S'), mov_read_ares },
3043 { MKTAG('a','v','s','s'), mov_read_avss },
3044 { MKTAG('c','h','p','l'), mov_read_chpl },
3045 { MKTAG('c','o','6','4'), mov_read_stco },
3046 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3047 { MKTAG('d','i','n','f'), mov_read_default },
3048 { MKTAG('d','r','e','f'), mov_read_dref },
3049 { MKTAG('e','d','t','s'), mov_read_default },
3050 { MKTAG('e','l','s','t'), mov_read_elst },
3051 { MKTAG('e','n','d','a'), mov_read_enda },
3052 { MKTAG('f','i','e','l'), mov_read_fiel },
3053 { MKTAG('f','t','y','p'), mov_read_ftyp },
3054 { MKTAG('g','l','b','l'), mov_read_glbl },
3055 { MKTAG('h','d','l','r'), mov_read_hdlr },
3056 { MKTAG('i','l','s','t'), mov_read_ilst },
3057 { MKTAG('j','p','2','h'), mov_read_jp2h },
3058 { MKTAG('m','d','a','t'), mov_read_mdat },
3059 { MKTAG('m','d','h','d'), mov_read_mdhd },
3060 { MKTAG('m','d','i','a'), mov_read_default },
3061 { MKTAG('m','e','t','a'), mov_read_meta },
3062 { MKTAG('m','i','n','f'), mov_read_default },
3063 { MKTAG('m','o','o','f'), mov_read_moof },
3064 { MKTAG('m','o','o','v'), mov_read_moov },
3065 { MKTAG('m','v','e','x'), mov_read_default },
3066 { MKTAG('m','v','h','d'), mov_read_mvhd },
3067 { MKTAG('S','M','I',' '), mov_read_svq3 },
3068 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
3069 { MKTAG('a','v','c','C'), mov_read_glbl },
3070 { MKTAG('p','a','s','p'), mov_read_pasp },
3071 { MKTAG('s','t','b','l'), mov_read_default },
3072 { MKTAG('s','t','c','o'), mov_read_stco },
3073 { MKTAG('s','t','p','s'), mov_read_stps },
3074 { MKTAG('s','t','r','f'), mov_read_strf },
3075 { MKTAG('s','t','s','c'), mov_read_stsc },
3076 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3077 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3078 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3079 { MKTAG('s','t','t','s'), mov_read_stts },
3080 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3081 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3082 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3083 { MKTAG('t','r','a','k'), mov_read_trak },
3084 { MKTAG('t','r','a','f'), mov_read_default },
3085 { MKTAG('t','r','e','f'), mov_read_default },
3086 { MKTAG('t','m','c','d'), mov_read_tmcd },
3087 { MKTAG('c','h','a','p'), mov_read_chap },
3088 { MKTAG('t','r','e','x'), mov_read_trex },
3089 { MKTAG('t','r','u','n'), mov_read_trun },
3090 { MKTAG('u','d','t','a'), mov_read_default },
3091 { MKTAG('w','a','v','e'), mov_read_wave },
3092 { MKTAG('e','s','d','s'), mov_read_esds },
3093 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3094 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3095 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3096 { MKTAG('w','f','e','x'), mov_read_wfex },
3097 { MKTAG('c','m','o','v'), mov_read_cmov },
3098 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3099 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3100 { MKTAG('s','b','g','p'), mov_read_sbgp },
3101 { MKTAG('h','v','c','C'), mov_read_glbl },
3102 { MKTAG('u','u','i','d'), mov_read_uuid },
3103 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
3104 { MKTAG('-','-','-','-'), mov_read_custom },
3108 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3110 int64_t total_size = 0;
3115 atom.size = INT64_MAX;
3116 while (total_size + 8 <= atom.size && !url_feof(pb)) {
3117 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3120 if (atom.size >= 8) {
3121 a.size = avio_rb32(pb);
3122 a.type = avio_rl32(pb);
3123 if (atom.type != MKTAG('r','o','o','t') &&
3124 atom.type != MKTAG('m','o','o','v'))
3126 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
3128 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
3134 if (a.size == 1) { /* 64 bit extended size */
3135 a.size = avio_rb64(pb) - 8;
3139 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3140 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3142 a.size = atom.size - total_size + 8;
3147 a.size = FFMIN(a.size, atom.size - total_size);
3149 for (i = 0; mov_default_parse_table[i].type; i++)
3150 if (mov_default_parse_table[i].type == a.type) {
3151 parse = mov_default_parse_table[i].parse;
3155 // container is user data
3156 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3157 atom.type == MKTAG('i','l','s','t')))
3158 parse = mov_read_udta_string;
3160 if (!parse) { /* skip leaf atoms data */
3161 avio_skip(pb, a.size);
3163 int64_t start_pos = avio_tell(pb);
3165 int err = parse(c, pb, a);
3168 if (c->found_moov && c->found_mdat &&
3169 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3170 start_pos + a.size == avio_size(pb))) {
3171 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3172 c->next_root_atom = start_pos + a.size;
3175 left = a.size - avio_tell(pb) + start_pos;
3176 if (left > 0) /* skip garbage at atom end */
3177 avio_skip(pb, left);
3178 else if (left < 0) {
3179 av_log(c->fc, AV_LOG_WARNING,
3180 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3181 (char*)&a.type, -left);
3182 avio_seek(pb, left, SEEK_CUR);
3186 total_size += a.size;
3189 if (total_size < atom.size && atom.size < 0x7ffff)
3190 avio_skip(pb, atom.size - total_size);
3195 static int mov_probe(AVProbeData *p)
3200 int moov_offset = -1;
3202 /* check file header */
3205 /* ignore invalid offset */
3206 if ((offset + 8) > (unsigned int)p->buf_size)
3208 tag = AV_RL32(p->buf + offset + 4);
3210 /* check for obvious tags */
3211 case MKTAG('m','o','o','v'):
3212 moov_offset = offset + 4;
3213 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
3214 case MKTAG('m','d','a','t'):
3215 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3216 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3217 case MKTAG('f','t','y','p'):
3218 if (AV_RB32(p->buf+offset) < 8 &&
3219 (AV_RB32(p->buf+offset) != 1 ||
3220 offset + 12 > (unsigned int)p->buf_size ||
3221 AV_RB64(p->buf+offset + 8) == 0)) {
3222 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3224 score = AVPROBE_SCORE_MAX;
3226 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3228 /* those are more common words, so rate then a bit less */
3229 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3230 case MKTAG('w','i','d','e'):
3231 case MKTAG('f','r','e','e'):
3232 case MKTAG('j','u','n','k'):
3233 case MKTAG('p','i','c','t'):
3234 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
3235 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3237 case MKTAG(0x82,0x82,0x7f,0x7d):
3238 case MKTAG('s','k','i','p'):
3239 case MKTAG('u','u','i','d'):
3240 case MKTAG('p','r','f','l'):
3241 /* if we only find those cause probedata is too small at least rate them */
3242 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3243 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3246 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3249 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
3250 /* moov atom in the header - we should make sure that this is not a
3251 * MOV-packed MPEG-PS */
3252 offset = moov_offset;
3254 while(offset < (p->buf_size - 16)){ /* Sufficient space */
3255 /* We found an actual hdlr atom */
3256 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
3257 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
3258 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
3259 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
3260 /* We found a media handler reference atom describing an
3261 * MPEG-PS-in-MOV, return a
3262 * low score to force expanding the probe window until
3263 * mpegps_probe finds what it needs */
3274 // must be done after parsing all trak because there's no order requirement
3275 static void mov_read_chapters(AVFormatContext *s)
3277 MOVContext *mov = s->priv_data;
3278 AVStream *st = NULL;
3279 MOVStreamContext *sc;
3283 for (i = 0; i < s->nb_streams; i++)
3284 if (s->streams[i]->id == mov->chapter_track) {
3289 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3293 st->discard = AVDISCARD_ALL;
3295 cur_pos = avio_tell(sc->pb);
3297 for (i = 0; i < st->nb_index_entries; i++) {
3298 AVIndexEntry *sample = &st->index_entries[i];
3299 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3304 if (end < sample->timestamp) {
3305 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
3306 end = AV_NOPTS_VALUE;
3309 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3310 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3314 // the first two bytes are the length of the title
3315 len = avio_rb16(sc->pb);
3316 if (len > sample->size-2)
3318 title_len = 2*len + 1;
3319 if (!(title = av_mallocz(title_len)))
3322 // The samples could theoretically be in any encoding if there's an encd
3323 // atom following, but in practice are only utf-8 or utf-16, distinguished
3324 // instead by the presence of a BOM
3328 ch = avio_rb16(sc->pb);
3330 avio_get_str16be(sc->pb, len, title, title_len);
3331 else if (ch == 0xfffe)
3332 avio_get_str16le(sc->pb, len, title, title_len);
3335 if (len == 1 || len == 2)
3338 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3342 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3346 avio_seek(sc->pb, cur_pos, SEEK_SET);
3349 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
3350 uint32_t value, int flags)
3353 char buf[AV_TIMECODE_STR_SIZE];
3354 AVRational rate = {st->codec->time_base.den,
3355 st->codec->time_base.num};
3356 int ret = av_timecode_init(&tc, rate, flags, 0, s);
3359 av_dict_set(&st->metadata, "timecode",
3360 av_timecode_make_string(&tc, buf, value), 0);
3364 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
3366 MOVStreamContext *sc = st->priv_data;
3368 int64_t cur_pos = avio_tell(sc->pb);
3371 if (!st->nb_index_entries)
3374 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3375 value = avio_rb32(s->pb);
3377 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3378 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3379 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3381 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3382 * not the case) and thus assume "frame number format" instead of QT one.
3383 * No sample with tmcd track can be found with a QT timecode at the moment,
3384 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3386 parse_timecode_in_framenum_format(s, st, value, flags);
3388 avio_seek(sc->pb, cur_pos, SEEK_SET);
3392 static int mov_read_close(AVFormatContext *s)
3394 MOVContext *mov = s->priv_data;
3397 for (i = 0; i < s->nb_streams; i++) {
3398 AVStream *st = s->streams[i];
3399 MOVStreamContext *sc = st->priv_data;
3401 av_freep(&sc->ctts_data);
3402 for (j = 0; j < sc->drefs_count; j++) {
3403 av_freep(&sc->drefs[j].path);
3404 av_freep(&sc->drefs[j].dir);
3406 av_freep(&sc->drefs);
3408 sc->drefs_count = 0;
3410 if (!sc->pb_is_copied)
3414 av_freep(&sc->chunk_offsets);
3415 av_freep(&sc->stsc_data);
3416 av_freep(&sc->sample_sizes);
3417 av_freep(&sc->keyframes);
3418 av_freep(&sc->stts_data);
3419 av_freep(&sc->stps_data);
3420 av_freep(&sc->rap_group);
3421 av_freep(&sc->display_matrix);
3424 if (mov->dv_demux) {
3425 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
3426 av_freep(&mov->dv_fctx->streams[i]->codec);
3427 av_freep(&mov->dv_fctx->streams[i]);
3429 av_freep(&mov->dv_fctx);
3430 av_freep(&mov->dv_demux);
3433 av_freep(&mov->trex_data);
3434 av_freep(&mov->bitrates);
3439 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3443 for (i = 0; i < s->nb_streams; i++) {
3444 AVStream *st = s->streams[i];
3445 MOVStreamContext *sc = st->priv_data;
3447 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3448 sc->timecode_track == tmcd_id)
3454 /* look for a tmcd track not referenced by any video track, and export it globally */
3455 static void export_orphan_timecode(AVFormatContext *s)
3459 for (i = 0; i < s->nb_streams; i++) {
3460 AVStream *st = s->streams[i];
3462 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3463 !tmcd_is_referenced(s, i + 1)) {
3464 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3466 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3473 static int mov_read_header(AVFormatContext *s)
3475 MOVContext *mov = s->priv_data;
3476 AVIOContext *pb = s->pb;
3478 MOVAtom atom = { AV_RL32("root") };
3482 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3484 atom.size = avio_size(pb);
3486 atom.size = INT64_MAX;
3488 /* check MOV header */
3489 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3490 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3494 if (!mov->found_moov) {
3495 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3497 return AVERROR_INVALIDDATA;
3499 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3502 if (mov->chapter_track > 0)
3503 mov_read_chapters(s);
3504 for (i = 0; i < s->nb_streams; i++)
3505 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3506 mov_read_timecode_track(s, s->streams[i]);
3509 /* copy timecode metadata from tmcd tracks to the related video streams */
3510 for (i = 0; i < s->nb_streams; i++) {
3511 AVStream *st = s->streams[i];
3512 MOVStreamContext *sc = st->priv_data;
3513 if (sc->timecode_track > 0) {
3514 AVDictionaryEntry *tcr;
3515 int tmcd_st_id = -1;
3517 for (j = 0; j < s->nb_streams; j++)
3518 if (s->streams[j]->id == sc->timecode_track)
3521 if (tmcd_st_id < 0 || tmcd_st_id == i)
3523 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
3525 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
3528 export_orphan_timecode(s);
3530 for (i = 0; i < s->nb_streams; i++) {
3531 AVStream *st = s->streams[i];
3532 MOVStreamContext *sc = st->priv_data;
3533 fix_timescale(mov, sc);
3534 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
3535 st->skip_samples = sc->start_pad;
3537 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
3538 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3539 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
3540 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3541 if (st->codec->width <= 0 && st->codec->height <= 0) {
3542 st->codec->width = sc->width;
3543 st->codec->height = sc->height;
3545 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3546 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3552 if (mov->trex_data) {
3553 for (i = 0; i < s->nb_streams; i++) {
3554 AVStream *st = s->streams[i];
3555 MOVStreamContext *sc = st->priv_data;
3556 if (st->duration > 0)
3557 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3561 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
3562 if (mov->bitrates[i]) {
3563 s->streams[i]->codec->bit_rate = mov->bitrates[i];
3567 ff_rfps_calculate(s);
3569 for (i = 0; i < s->nb_streams; i++) {
3570 AVStream *st = s->streams[i];
3571 MOVStreamContext *sc = st->priv_data;
3573 switch (st->codec->codec_type) {
3574 case AVMEDIA_TYPE_AUDIO:
3575 err = ff_replaygain_export(st, s->metadata);
3581 case AVMEDIA_TYPE_VIDEO:
3582 if (sc->display_matrix) {
3583 AVPacketSideData *sd, *tmp;
3585 tmp = av_realloc_array(st->side_data,
3586 st->nb_side_data + 1, sizeof(*tmp));
3588 return AVERROR(ENOMEM);
3590 st->side_data = tmp;
3593 sd = &st->side_data[st->nb_side_data - 1];
3594 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
3595 sd->size = sizeof(int32_t) * 9;
3596 sd->data = (uint8_t*)sc->display_matrix;
3597 sc->display_matrix = NULL;
3606 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3608 AVIndexEntry *sample = NULL;
3609 int64_t best_dts = INT64_MAX;
3611 for (i = 0; i < s->nb_streams; i++) {
3612 AVStream *avst = s->streams[i];
3613 MOVStreamContext *msc = avst->priv_data;
3614 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3615 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3616 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3617 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3618 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3620 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3621 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3622 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3623 sample = current_sample;
3632 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3634 MOVContext *mov = s->priv_data;
3635 MOVStreamContext *sc;
3636 AVIndexEntry *sample;
3637 AVStream *st = NULL;
3641 sample = mov_find_next_sample(s, &st);
3643 mov->found_mdat = 0;
3644 if (!mov->next_root_atom)
3646 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3647 mov->next_root_atom = 0;
3648 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3651 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3655 /* must be done just before reading, to avoid infinite loop on sample */
3656 sc->current_sample++;
3658 if (mov->next_root_atom) {
3659 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
3660 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
3663 if (st->discard != AVDISCARD_ALL) {
3664 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3665 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3666 sc->ffindex, sample->pos);
3667 return AVERROR_INVALIDDATA;
3669 ret = av_get_packet(sc->pb, pkt, sample->size);
3672 if (sc->has_palette) {
3675 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3677 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3679 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3680 sc->has_palette = 0;
3683 #if CONFIG_DV_DEMUXER
3684 if (mov->dv_demux && sc->dv_audio_container) {
3685 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
3688 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3695 pkt->stream_index = sc->ffindex;
3696 pkt->dts = sample->timestamp;
3697 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3698 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3699 /* update ctts context */
3701 if (sc->ctts_index < sc->ctts_count &&
3702 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3704 sc->ctts_sample = 0;
3707 pkt->dts = AV_NOPTS_VALUE;
3709 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3710 st->index_entries[sc->current_sample].timestamp : st->duration;
3711 pkt->duration = next_dts - pkt->dts;
3712 pkt->pts = pkt->dts;
3714 if (st->discard == AVDISCARD_ALL)
3716 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3717 pkt->pos = sample->pos;
3718 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3719 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3723 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3725 MOVStreamContext *sc = st->priv_data;
3726 int sample, time_sample;
3729 sample = av_index_search_timestamp(st, timestamp, flags);
3730 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3731 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3733 if (sample < 0) /* not sure what to do */
3734 return AVERROR_INVALIDDATA;
3735 sc->current_sample = sample;
3736 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3737 /* adjust ctts index */
3738 if (sc->ctts_data) {
3740 for (i = 0; i < sc->ctts_count; i++) {
3741 int next = time_sample + sc->ctts_data[i].count;
3742 if (next > sc->current_sample) {
3744 sc->ctts_sample = sc->current_sample - time_sample;
3753 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3756 int64_t seek_timestamp, timestamp;
3760 if (stream_index >= s->nb_streams)
3761 return AVERROR_INVALIDDATA;
3763 st = s->streams[stream_index];
3764 sample = mov_seek_stream(s, st, sample_time, flags);
3768 /* adjust seek timestamp to found sample timestamp */
3769 seek_timestamp = st->index_entries[sample].timestamp;
3771 for (i = 0; i < s->nb_streams; i++) {
3772 MOVStreamContext *sc = s->streams[i]->priv_data;
3774 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
3776 if (stream_index == i)
3779 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3780 mov_seek_stream(s, st, timestamp, flags);
3785 static const AVOption options[] = {
3786 {"use_absolute_path",
3787 "allow using absolute path when opening alias, this is a possible security issue",
3788 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
3789 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3790 {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
3791 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3795 static const AVClass mov_class = {
3796 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3797 .item_name = av_default_item_name,
3799 .version = LIBAVUTIL_VERSION_INT,
3802 AVInputFormat ff_mov_demuxer = {
3803 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3804 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3805 .priv_data_size = sizeof(MOVContext),
3806 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
3807 .read_probe = mov_probe,
3808 .read_header = mov_read_header,
3809 .read_packet = mov_read_packet,
3810 .read_close = mov_read_close,
3811 .read_seek = mov_read_seek,
3812 .priv_class = &mov_class,
3813 .flags = AVFMT_NO_BYTE_SEEK,