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)
123 avio_r8(pb); // unknown
126 if (genre < 1 || genre > ID3v1_GENRE_MAX)
128 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
133 static const uint32_t mac_to_unicode[128] = {
134 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
135 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
136 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
137 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
138 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
139 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
140 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
141 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
142 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
143 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
144 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
145 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
146 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
147 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
148 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
149 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
152 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
153 char *dst, int dstlen)
156 char *end = dst+dstlen-1;
159 for (i = 0; i < len; i++) {
160 uint8_t t, c = avio_r8(pb);
161 if (c < 0x80 && p < end)
164 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
170 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
174 MOVStreamContext *sc;
179 case 0xd: id = AV_CODEC_ID_MJPEG; break;
180 case 0xe: id = AV_CODEC_ID_PNG; break;
181 case 0x1b: id = AV_CODEC_ID_BMP; break;
183 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
188 st = avformat_new_stream(c->fc, NULL);
190 return AVERROR(ENOMEM);
191 sc = av_mallocz(sizeof(*sc));
193 return AVERROR(ENOMEM);
196 ret = av_get_packet(pb, &pkt, len);
200 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
202 st->attached_pic = pkt;
203 st->attached_pic.stream_index = st->index;
204 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
206 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
207 st->codec->codec_id = id;
212 static int mov_metadata_raw(MOVContext *c, AVIOContext *pb,
213 unsigned len, const char *key)
215 char *value = av_malloc(len + 1);
217 return AVERROR(ENOMEM);
218 avio_read(pb, value, len);
220 return av_dict_set(&c->fc->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);
223 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
225 char language[4] = { 0 };
227 uint16_t langcode = 0;
228 double longitude, latitude;
229 const char *key = "location";
231 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4)
232 return AVERROR_INVALIDDATA;
234 avio_skip(pb, 4); // version+flags
235 langcode = avio_rb16(pb);
236 ff_mov_lang_to_iso639(langcode, language);
239 len -= avio_get_str(pb, len, buf, sizeof(buf)); // place name
241 return AVERROR_INVALIDDATA;
242 avio_skip(pb, 1); // role
246 return AVERROR_INVALIDDATA;
247 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
248 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
250 // Try to output in the same format as the ?xyz field
251 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f/", latitude, longitude);
252 if (*language && strcmp(language, "und")) {
254 snprintf(key2, sizeof(key2), "%s-%s", key, language);
255 av_dict_set(&c->fc->metadata, key2, buf, 0);
257 return av_dict_set(&c->fc->metadata, key, buf, 0);
260 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
262 #ifdef MOV_EXPORT_ALL_METADATA
265 char str[1024], key2[16], language[4] = {0};
266 const char *key = NULL;
267 uint16_t langcode = 0;
268 uint32_t data_type = 0, str_size;
269 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
272 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
273 case MKTAG(0xa9,'a','u','t'):
274 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
275 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
276 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
277 case MKTAG( 'c','p','i','l'): key = "compilation";
278 parse = mov_metadata_int8_no_padding; break;
279 case MKTAG( 'c','p','r','t'):
280 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
281 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
282 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
283 case MKTAG(0xa9,'c','m','t'):
284 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
285 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
286 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
287 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
288 case MKTAG( 'g','n','r','e'): key = "genre";
289 parse = mov_metadata_gnre; break;
290 case MKTAG(0xa9,'t','o','o'):
291 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
292 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
293 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
294 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
295 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
296 case MKTAG( 'd','e','s','c'): key = "description";break;
297 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
298 case MKTAG( 't','v','s','h'): key = "show"; break;
299 case MKTAG( 't','v','e','n'): key = "episode_id";break;
300 case MKTAG( 't','v','n','n'): key = "network"; break;
301 case MKTAG( 't','r','k','n'): key = "track";
302 parse = mov_metadata_track_or_disc_number; break;
303 case MKTAG( 'd','i','s','k'): key = "disc";
304 parse = mov_metadata_track_or_disc_number; break;
305 case MKTAG( 't','v','e','s'): key = "episode_sort";
306 parse = mov_metadata_int8_bypass_padding; break;
307 case MKTAG( 't','v','s','n'): key = "season_number";
308 parse = mov_metadata_int8_bypass_padding; break;
309 case MKTAG( 's','t','i','k'): key = "media_type";
310 parse = mov_metadata_int8_no_padding; break;
311 case MKTAG( 'h','d','v','d'): key = "hd_video";
312 parse = mov_metadata_int8_no_padding; break;
313 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
314 parse = mov_metadata_int8_no_padding; break;
315 case MKTAG( '@','P','R','M'):
316 return mov_metadata_raw(c, pb, atom.size, "premiere_version");
317 case MKTAG( '@','P','R','Q'):
318 return mov_metadata_raw(c, pb, atom.size, "quicktime_version");
319 case MKTAG( 'l','o','c','i'):
320 return mov_metadata_loci(c, pb, atom.size);
323 if (c->itunes_metadata && atom.size > 8) {
324 int data_size = avio_rb32(pb);
325 int tag = avio_rl32(pb);
326 if (tag == MKTAG('d','a','t','a')) {
327 data_type = avio_rb32(pb); // type
328 avio_rb32(pb); // unknown
329 str_size = data_size - 16;
332 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
333 int ret = mov_read_covr(c, pb, data_type, str_size);
335 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
340 } else if (atom.size > 4 && key && !c->itunes_metadata) {
341 str_size = avio_rb16(pb); // string length
342 langcode = avio_rb16(pb);
343 ff_mov_lang_to_iso639(langcode, language);
346 str_size = atom.size;
348 #ifdef MOV_EXPORT_ALL_METADATA
350 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
358 return AVERROR_INVALIDDATA;
360 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
363 parse(c, pb, str_size, key);
365 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
366 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
368 int ret = avio_read(pb, str, str_size);
370 return ret < 0 ? ret : AVERROR_INVALIDDATA;
373 av_dict_set(&c->fc->metadata, key, str, 0);
374 if (*language && strcmp(language, "und")) {
375 snprintf(key2, sizeof(key2), "%s-%s", key, language);
376 av_dict_set(&c->fc->metadata, key2, str, 0);
379 av_dlog(c->fc, "lang \"%3s\" ", language);
380 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
381 key, str, (char*)&atom.type, str_size, atom.size);
386 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
389 int i, nb_chapters, str_len, version;
392 if ((atom.size -= 5) < 0)
395 version = avio_r8(pb);
398 avio_rb32(pb); // ???
399 nb_chapters = avio_r8(pb);
401 for (i = 0; i < nb_chapters; i++) {
405 start = avio_rb64(pb);
406 str_len = avio_r8(pb);
408 if ((atom.size -= 9+str_len) < 0)
411 avio_read(pb, str, str_len);
413 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
418 #define MIN_DATA_ENTRY_BOX_SIZE 12
419 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
422 MOVStreamContext *sc;
425 if (c->fc->nb_streams < 1)
427 st = c->fc->streams[c->fc->nb_streams-1];
430 avio_rb32(pb); // version + flags
431 entries = avio_rb32(pb);
432 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
433 entries >= UINT_MAX / sizeof(*sc->drefs))
434 return AVERROR_INVALIDDATA;
437 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
439 return AVERROR(ENOMEM);
440 sc->drefs_count = entries;
442 for (i = 0; i < sc->drefs_count; i++) {
443 MOVDref *dref = &sc->drefs[i];
444 uint32_t size = avio_rb32(pb);
445 int64_t next = avio_tell(pb) + size - 4;
448 return AVERROR_INVALIDDATA;
450 dref->type = avio_rl32(pb);
451 avio_rb32(pb); // version + flags
452 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
454 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
455 /* macintosh alias record */
456 uint16_t volume_len, len;
461 volume_len = avio_r8(pb);
462 volume_len = FFMIN(volume_len, 27);
463 avio_read(pb, dref->volume, 27);
464 dref->volume[volume_len] = 0;
465 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
470 len = FFMIN(len, 63);
471 avio_read(pb, dref->filename, 63);
472 dref->filename[len] = 0;
473 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
477 /* read next level up_from_alias/down_to_target */
478 dref->nlvl_from = avio_rb16(pb);
479 dref->nlvl_to = avio_rb16(pb);
480 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
481 dref->nlvl_from, dref->nlvl_to);
485 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
488 type = avio_rb16(pb);
490 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
493 if (type == 2) { // absolute path
495 dref->path = av_mallocz(len+1);
497 return AVERROR(ENOMEM);
498 avio_read(pb, dref->path, len);
499 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
501 memmove(dref->path, dref->path+volume_len, len);
504 for (j = 0; j < len; j++)
505 if (dref->path[j] == ':')
507 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
508 } else if (type == 0) { // directory name
510 dref->dir = av_malloc(len+1);
512 return AVERROR(ENOMEM);
513 if (avio_read(pb, dref->dir, len) != len)
514 return AVERROR_INVALIDDATA;
516 for (j = 0; j < len; j++)
517 if (dref->dir[j] == ':')
519 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
524 avio_seek(pb, next, SEEK_SET);
529 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
533 uint32_t av_unused ctype;
537 if (c->fc->nb_streams < 1) // meta before first trak
540 st = c->fc->streams[c->fc->nb_streams-1];
542 avio_r8(pb); /* version */
543 avio_rb24(pb); /* flags */
546 ctype = avio_rl32(pb);
547 type = avio_rl32(pb); /* component subtype */
549 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
550 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
552 if (type == MKTAG('v','i','d','e'))
553 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
554 else if (type == MKTAG('s','o','u','n'))
555 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
556 else if (type == MKTAG('m','1','a',' '))
557 st->codec->codec_id = AV_CODEC_ID_MP2;
558 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
559 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
561 avio_rb32(pb); /* component manufacture */
562 avio_rb32(pb); /* component flags */
563 avio_rb32(pb); /* component flags mask */
565 title_size = atom.size - 24;
566 if (title_size > 0) {
567 title_str = av_malloc(title_size + 1); /* Add null terminator */
569 return AVERROR(ENOMEM);
570 avio_read(pb, title_str, title_size);
571 title_str[title_size] = 0;
573 av_dict_set(&st->metadata, "handler_name", title_str +
574 (!c->isom && title_str[0] == title_size - 1), 0);
575 av_freep(&title_str);
581 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
586 if (fc->nb_streams < 1)
588 st = fc->streams[fc->nb_streams-1];
590 avio_rb32(pb); /* version + flags */
591 ff_mp4_read_descr(fc, pb, &tag);
592 if (tag == MP4ESDescrTag) {
593 ff_mp4_parse_es_descr(pb, NULL);
595 avio_rb16(pb); /* ID */
597 ff_mp4_read_descr(fc, pb, &tag);
598 if (tag == MP4DecConfigDescrTag)
599 ff_mp4_read_dec_config_descr(fc, st, pb);
603 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
605 return ff_mov_read_esds(c->fc, pb, atom);
608 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
611 int ac3info, acmod, lfeon, bsmod;
613 if (c->fc->nb_streams < 1)
615 st = c->fc->streams[c->fc->nb_streams-1];
617 ac3info = avio_rb24(pb);
618 bsmod = (ac3info >> 14) & 0x7;
619 acmod = (ac3info >> 11) & 0x7;
620 lfeon = (ac3info >> 10) & 0x1;
621 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
622 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
624 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
625 st->codec->audio_service_type = bsmod;
626 if (st->codec->channels > 1 && bsmod == 0x7)
627 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
632 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
635 int eac3info, acmod, lfeon, bsmod;
637 if (c->fc->nb_streams < 1)
639 st = c->fc->streams[c->fc->nb_streams-1];
641 /* No need to parse fields for additional independent substreams and its
642 * associated dependent substreams since libavcodec's E-AC-3 decoder
643 * does not support them yet. */
644 avio_rb16(pb); /* data_rate and num_ind_sub */
645 eac3info = avio_rb24(pb);
646 bsmod = (eac3info >> 12) & 0x1f;
647 acmod = (eac3info >> 9) & 0x7;
648 lfeon = (eac3info >> 8) & 0x1;
649 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
651 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
652 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
653 st->codec->audio_service_type = bsmod;
654 if (st->codec->channels > 1 && bsmod == 0x7)
655 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
660 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
664 if (c->fc->nb_streams < 1)
666 st = c->fc->streams[c->fc->nb_streams-1];
671 /* skip version and flags */
674 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
679 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
683 if (c->fc->nb_streams < 1)
685 st = c->fc->streams[c->fc->nb_streams-1];
687 if (ff_get_wav_header(pb, st->codec, atom.size) < 0) {
688 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
694 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
696 const int num = avio_rb32(pb);
697 const int den = avio_rb32(pb);
700 if (c->fc->nb_streams < 1)
702 st = c->fc->streams[c->fc->nb_streams-1];
704 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
705 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
706 av_log(c->fc, AV_LOG_WARNING,
707 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
708 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
710 } else if (den != 0) {
711 st->sample_aspect_ratio.num = num;
712 st->sample_aspect_ratio.den = den;
717 /* this atom contains actual media data */
718 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
720 if (atom.size == 0) /* wrong one (MP4) */
723 return 0; /* now go for moov */
726 /* read major brand, minor version and compatible brands and store them as metadata */
727 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
731 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
732 char* comp_brands_str;
733 uint8_t type[5] = {0};
735 avio_read(pb, type, 4);
736 if (strcmp(type, "qt "))
738 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
739 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
740 minor_ver = avio_rb32(pb); /* minor version */
741 snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);
742 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
744 comp_brand_size = atom.size - 8;
745 if (comp_brand_size < 0)
746 return AVERROR_INVALIDDATA;
747 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
748 if (!comp_brands_str)
749 return AVERROR(ENOMEM);
750 avio_read(pb, comp_brands_str, comp_brand_size);
751 comp_brands_str[comp_brand_size] = 0;
752 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
753 av_freep(&comp_brands_str);
758 /* this atom should contain all header atoms */
759 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
764 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
765 avio_skip(pb, atom.size);
769 if ((ret = mov_read_default(c, pb, atom)) < 0)
771 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
772 /* so we don't parse the whole file if over a network */
774 return 0; /* now go for mdat */
777 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
779 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
780 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
781 return mov_read_default(c, pb, atom);
784 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
790 if(time >= 2082844800)
791 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
793 ptm = gmtime(&timet);
795 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
796 av_dict_set(metadata, "creation_time", buffer, 0);
800 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
803 MOVStreamContext *sc;
805 char language[4] = {0};
807 int64_t creation_time;
809 if (c->fc->nb_streams < 1)
811 st = c->fc->streams[c->fc->nb_streams-1];
814 if (sc->time_scale) {
815 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
816 return AVERROR_INVALIDDATA;
819 version = avio_r8(pb);
821 avpriv_request_sample(c->fc, "Version %d", version);
822 return AVERROR_PATCHWELCOME;
824 avio_rb24(pb); /* flags */
826 creation_time = avio_rb64(pb);
829 creation_time = avio_rb32(pb);
830 avio_rb32(pb); /* modification time */
832 mov_metadata_creation_time(&st->metadata, creation_time);
834 sc->time_scale = avio_rb32(pb);
835 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
837 lang = avio_rb16(pb); /* language */
838 if (ff_mov_lang_to_iso639(lang, language))
839 av_dict_set(&st->metadata, "language", language, 0);
840 avio_rb16(pb); /* quality */
845 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
847 int64_t creation_time;
848 int version = avio_r8(pb); /* version */
849 avio_rb24(pb); /* flags */
852 creation_time = avio_rb64(pb);
855 creation_time = avio_rb32(pb);
856 avio_rb32(pb); /* modification time */
858 mov_metadata_creation_time(&c->fc->metadata, creation_time);
859 c->time_scale = avio_rb32(pb); /* time scale */
861 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
863 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
864 // set the AVCodecContext duration because the duration of individual tracks
866 if (c->time_scale > 0 && !c->trex_data)
867 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
868 avio_rb32(pb); /* preferred scale */
870 avio_rb16(pb); /* preferred volume */
872 avio_skip(pb, 10); /* reserved */
874 avio_skip(pb, 36); /* display matrix */
876 avio_rb32(pb); /* preview time */
877 avio_rb32(pb); /* preview duration */
878 avio_rb32(pb); /* poster time */
879 avio_rb32(pb); /* selection time */
880 avio_rb32(pb); /* selection duration */
881 avio_rb32(pb); /* current time */
882 avio_rb32(pb); /* next track ID */
886 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
891 if (c->fc->nb_streams < 1)
893 st = c->fc->streams[c->fc->nb_streams-1];
895 little_endian = avio_rb16(pb) & 0xFF;
896 av_dlog(c->fc, "enda %d\n", little_endian);
897 if (little_endian == 1) {
898 switch (st->codec->codec_id) {
899 case AV_CODEC_ID_PCM_S24BE:
900 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
902 case AV_CODEC_ID_PCM_S32BE:
903 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
905 case AV_CODEC_ID_PCM_F32BE:
906 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
908 case AV_CODEC_ID_PCM_F64BE:
909 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
918 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
921 unsigned mov_field_order;
922 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
924 if (c->fc->nb_streams < 1) // will happen with jp2 files
926 st = c->fc->streams[c->fc->nb_streams-1];
928 return AVERROR_INVALIDDATA;
929 mov_field_order = avio_rb16(pb);
930 if ((mov_field_order & 0xFF00) == 0x0100)
931 decoded_field_order = AV_FIELD_PROGRESSIVE;
932 else if ((mov_field_order & 0xFF00) == 0x0200) {
933 switch (mov_field_order & 0xFF) {
934 case 0x01: decoded_field_order = AV_FIELD_TT;
936 case 0x06: decoded_field_order = AV_FIELD_BB;
938 case 0x09: decoded_field_order = AV_FIELD_TB;
940 case 0x0E: decoded_field_order = AV_FIELD_BT;
944 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
945 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
947 st->codec->field_order = decoded_field_order;
952 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
953 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
954 enum AVCodecID codec_id)
961 if (c->fc->nb_streams < 1) // will happen with jp2 files
963 st= c->fc->streams[c->fc->nb_streams-1];
965 if (st->codec->codec_id != codec_id)
966 return 0; /* unexpected codec_id - don't mess with extradata */
968 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
969 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
970 return AVERROR_INVALIDDATA;
971 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
972 st->codec->extradata_size = 0;
975 buf = st->codec->extradata + st->codec->extradata_size;
976 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
977 AV_WB32( buf , atom.size + 8);
978 AV_WL32( buf + 4, atom.type);
979 err = avio_read(pb, buf + 8, atom.size);
982 } else if (err < atom.size) {
983 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
984 st->codec->extradata_size -= atom.size - err;
986 memset(buf + 8 + err, 0, FF_INPUT_BUFFER_PADDING_SIZE);
990 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
991 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
993 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
996 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
998 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1001 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1003 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1006 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1008 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1011 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1013 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1015 if (!ret && c->fc->nb_streams >= 1) {
1016 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
1017 if (avctx->extradata_size >= 40) {
1018 avctx->height = AV_RB16(&avctx->extradata[36]);
1019 avctx->width = AV_RB16(&avctx->extradata[38]);
1025 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1027 if (c->fc->nb_streams >= 1) {
1028 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1029 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1030 codec->codec_id == AV_CODEC_ID_H264 &&
1033 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1034 if (avio_rb16(pb) == 0xd4d)
1035 codec->width = 1440;
1040 return mov_read_avid(c, pb, atom);
1043 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1045 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1048 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1052 if (c->fc->nb_streams < 1)
1054 st = c->fc->streams[c->fc->nb_streams-1];
1056 if ((uint64_t)atom.size > (1<<30))
1057 return AVERROR_INVALIDDATA;
1059 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1060 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1061 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1062 // pass all frma atom to codec, needed at least for QDMC and QDM2
1063 av_free(st->codec->extradata);
1064 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1065 return AVERROR(ENOMEM);
1066 } else if (atom.size > 8) { /* to read frma, esds atoms */
1068 if ((ret = mov_read_default(c, pb, atom)) < 0)
1071 avio_skip(pb, atom.size);
1076 * This function reads atom content and puts data in extradata without tag
1077 * nor size unlike mov_read_extradata.
1079 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1083 if (c->fc->nb_streams < 1)
1085 st = c->fc->streams[c->fc->nb_streams-1];
1087 if ((uint64_t)atom.size > (1<<30))
1088 return AVERROR_INVALIDDATA;
1090 if (atom.size >= 10) {
1091 // Broken files created by legacy versions of libavformat will
1092 // wrap a whole fiel atom inside of a glbl atom.
1093 unsigned size = avio_rb32(pb);
1094 unsigned type = avio_rl32(pb);
1095 avio_seek(pb, -8, SEEK_CUR);
1096 if (type == MKTAG('f','i','e','l') && size == atom.size)
1097 return mov_read_default(c, pb, atom);
1099 av_free(st->codec->extradata);
1100 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1101 return AVERROR(ENOMEM);
1106 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1109 uint8_t profile_level;
1112 if (c->fc->nb_streams < 1)
1114 st = c->fc->streams[c->fc->nb_streams-1];
1116 if (atom.size >= (1<<28) || atom.size < 7)
1117 return AVERROR_INVALIDDATA;
1119 profile_level = avio_r8(pb);
1120 if ((profile_level & 0xf0) != 0xc0)
1123 avio_seek(pb, 6, SEEK_CUR);
1124 av_free(st->codec->extradata);
1125 if ((ret = ff_get_extradata(st->codec, pb, atom.size - 7)) < 0)
1132 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1133 * but can have extradata appended at the end after the 40 bytes belonging
1136 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1140 if (c->fc->nb_streams < 1)
1142 if (atom.size <= 40)
1144 st = c->fc->streams[c->fc->nb_streams-1];
1146 if ((uint64_t)atom.size > (1<<30))
1147 return AVERROR_INVALIDDATA;
1150 av_free(st->codec->extradata);
1151 if (ff_get_extradata(st->codec, pb, atom.size - 40) < 0)
1152 return AVERROR(ENOMEM);
1156 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1159 MOVStreamContext *sc;
1160 unsigned int i, entries;
1162 if (c->fc->nb_streams < 1)
1164 st = c->fc->streams[c->fc->nb_streams-1];
1167 avio_r8(pb); /* version */
1168 avio_rb24(pb); /* flags */
1170 entries = avio_rb32(pb);
1174 if (entries >= UINT_MAX/sizeof(int64_t))
1175 return AVERROR_INVALIDDATA;
1177 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1178 if (!sc->chunk_offsets)
1179 return AVERROR(ENOMEM);
1180 sc->chunk_count = entries;
1182 if (atom.type == MKTAG('s','t','c','o'))
1183 for (i = 0; i < entries && !pb->eof_reached; i++)
1184 sc->chunk_offsets[i] = avio_rb32(pb);
1185 else if (atom.type == MKTAG('c','o','6','4'))
1186 for (i = 0; i < entries && !pb->eof_reached; i++)
1187 sc->chunk_offsets[i] = avio_rb64(pb);
1189 return AVERROR_INVALIDDATA;
1191 sc->chunk_count = i;
1193 if (pb->eof_reached)
1200 * Compute codec id for 'lpcm' tag.
1201 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1203 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1210 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1213 static int mov_codec_id(AVStream *st, uint32_t format)
1215 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1218 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1219 (format & 0xFFFF) == 'T' + ('S' << 8)))
1220 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1222 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1223 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1224 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1225 /* skip old asf mpeg4 tag */
1226 format && format != MKTAG('m','p','4','s')) {
1227 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1229 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1231 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1232 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1233 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1234 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1235 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1237 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1241 st->codec->codec_tag = format;
1246 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1247 AVStream *st, MOVStreamContext *sc)
1249 uint8_t codec_name[32];
1250 unsigned int color_depth, len, j;
1251 int color_greyscale;
1254 avio_rb16(pb); /* version */
1255 avio_rb16(pb); /* revision level */
1256 avio_rb32(pb); /* vendor */
1257 avio_rb32(pb); /* temporal quality */
1258 avio_rb32(pb); /* spatial quality */
1260 st->codec->width = avio_rb16(pb); /* width */
1261 st->codec->height = avio_rb16(pb); /* height */
1263 avio_rb32(pb); /* horiz resolution */
1264 avio_rb32(pb); /* vert resolution */
1265 avio_rb32(pb); /* data size, always 0 */
1266 avio_rb16(pb); /* frames per samples */
1268 len = avio_r8(pb); /* codec name, pascal string */
1271 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1273 avio_skip(pb, 31 - len);
1276 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1278 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1279 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1280 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1281 st->codec->width &= ~1;
1282 st->codec->height &= ~1;
1284 /* Flash Media Server uses tag H263 with Sorenson Spark */
1285 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1286 !memcmp(codec_name, "Sorenson H263", 13))
1287 st->codec->codec_id = AV_CODEC_ID_FLV1;
1289 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1290 color_table_id = avio_rb16(pb); /* colortable id */
1291 av_dlog(c->fc, "depth %d, ctab id %d\n",
1292 st->codec->bits_per_coded_sample, color_table_id);
1293 /* figure out the palette situation */
1294 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1295 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1296 /* Do not create a greyscale palette for cinepak */
1297 if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1300 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1301 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1302 /* for palette traversal */
1303 unsigned int color_start, color_count, color_end;
1304 unsigned char a, r, g, b;
1306 if (color_greyscale) {
1307 int color_index, color_dec;
1308 /* compute the greyscale palette */
1309 st->codec->bits_per_coded_sample = color_depth;
1310 color_count = 1 << color_depth;
1312 color_dec = 256 / (color_count - 1);
1313 for (j = 0; j < color_count; j++) {
1314 r = g = b = color_index;
1315 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1316 color_index -= color_dec;
1317 if (color_index < 0)
1320 } else if (color_table_id) {
1321 const uint8_t *color_table;
1322 /* if flag bit 3 is set, use the default palette */
1323 color_count = 1 << color_depth;
1324 if (color_depth == 2)
1325 color_table = ff_qt_default_palette_4;
1326 else if (color_depth == 4)
1327 color_table = ff_qt_default_palette_16;
1329 color_table = ff_qt_default_palette_256;
1331 for (j = 0; j < color_count; j++) {
1332 r = color_table[j * 3 + 0];
1333 g = color_table[j * 3 + 1];
1334 b = color_table[j * 3 + 2];
1335 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1338 /* load the palette from the file */
1339 color_start = avio_rb32(pb);
1340 color_count = avio_rb16(pb);
1341 color_end = avio_rb16(pb);
1342 if ((color_start <= 255) && (color_end <= 255)) {
1343 for (j = color_start; j <= color_end; j++) {
1344 /* each A, R, G, or B component is 16 bits;
1345 * only use the top 8 bits */
1354 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1358 sc->has_palette = 1;
1362 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1363 AVStream *st, MOVStreamContext *sc)
1365 int bits_per_sample, flags;
1366 uint16_t version = avio_rb16(pb);
1367 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1369 avio_rb16(pb); /* revision level */
1370 avio_rb32(pb); /* vendor */
1372 st->codec->channels = avio_rb16(pb); /* channel count */
1373 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1374 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1376 sc->audio_cid = avio_rb16(pb);
1377 avio_rb16(pb); /* packet size = 0 */
1379 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1381 // Read QT version 1 fields. In version 0 these do not exist.
1382 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1384 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1387 sc->samples_per_frame = avio_rb32(pb);
1388 avio_rb32(pb); /* bytes per packet */
1389 sc->bytes_per_frame = avio_rb32(pb);
1390 avio_rb32(pb); /* bytes per sample */
1391 } else if (version == 2) {
1392 avio_rb32(pb); /* sizeof struct only */
1393 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1394 st->codec->channels = avio_rb32(pb);
1395 avio_rb32(pb); /* always 0x7F000000 */
1396 st->codec->bits_per_coded_sample = avio_rb32(pb);
1398 flags = avio_rb32(pb); /* lpcm format specific flag */
1399 sc->bytes_per_frame = avio_rb32(pb);
1400 sc->samples_per_frame = avio_rb32(pb);
1401 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1402 st->codec->codec_id =
1403 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1408 switch (st->codec->codec_id) {
1409 case AV_CODEC_ID_PCM_S8:
1410 case AV_CODEC_ID_PCM_U8:
1411 if (st->codec->bits_per_coded_sample == 16)
1412 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1414 case AV_CODEC_ID_PCM_S16LE:
1415 case AV_CODEC_ID_PCM_S16BE:
1416 if (st->codec->bits_per_coded_sample == 8)
1417 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1418 else if (st->codec->bits_per_coded_sample == 24)
1419 st->codec->codec_id =
1420 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1421 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1423 /* set values for old format before stsd version 1 appeared */
1424 case AV_CODEC_ID_MACE3:
1425 sc->samples_per_frame = 6;
1426 sc->bytes_per_frame = 2 * st->codec->channels;
1428 case AV_CODEC_ID_MACE6:
1429 sc->samples_per_frame = 6;
1430 sc->bytes_per_frame = 1 * st->codec->channels;
1432 case AV_CODEC_ID_ADPCM_IMA_QT:
1433 sc->samples_per_frame = 64;
1434 sc->bytes_per_frame = 34 * st->codec->channels;
1436 case AV_CODEC_ID_GSM:
1437 sc->samples_per_frame = 160;
1438 sc->bytes_per_frame = 33;
1444 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1445 if (bits_per_sample) {
1446 st->codec->bits_per_coded_sample = bits_per_sample;
1447 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1451 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1452 AVStream *st, MOVStreamContext *sc,
1455 // ttxt stsd contains display flags, justification, background
1456 // color, fonts, and default styles, so fake an atom to read it
1457 MOVAtom fake_atom = { .size = size };
1458 // mp4s contains a regular esds atom
1459 if (st->codec->codec_tag != AV_RL32("mp4s"))
1460 mov_read_glbl(c, pb, fake_atom);
1461 st->codec->width = sc->width;
1462 st->codec->height = sc->height;
1465 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1470 y = (ycbcr >> 16) & 0xFF;
1471 cr = (ycbcr >> 8) & 0xFF;
1474 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1475 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1476 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1478 return (r << 16) | (g << 8) | b;
1481 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1483 char buf[256] = {0};
1484 uint8_t *src = st->codec->extradata;
1487 if (st->codec->extradata_size != 64)
1490 if (st->codec->width > 0 && st->codec->height > 0)
1491 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1492 st->codec->width, st->codec->height);
1493 av_strlcat(buf, "palette: ", sizeof(buf));
1495 for (i = 0; i < 16; i++) {
1496 uint32_t yuv = AV_RB32(src + i * 4);
1497 uint32_t rgba = yuv_to_rgba(yuv);
1499 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1502 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1505 av_freep(&st->codec->extradata);
1506 st->codec->extradata_size = 0;
1507 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1508 if (!st->codec->extradata)
1509 return AVERROR(ENOMEM);
1510 st->codec->extradata_size = strlen(buf);
1511 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1516 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1517 AVStream *st, MOVStreamContext *sc,
1520 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1521 if (ff_get_extradata(st->codec, pb, size) < 0)
1522 return AVERROR(ENOMEM);
1524 MOVStreamContext *tmcd_ctx = st->priv_data;
1526 val = AV_RB32(st->codec->extradata + 4);
1527 tmcd_ctx->tmcd_flags = val;
1529 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1530 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
1531 st->codec->time_base.num = 1;
1534 /* other codec type, just skip (rtp, mp4s ...) */
1535 avio_skip(pb, size);
1540 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1541 AVStream *st, MOVStreamContext *sc)
1543 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1544 !st->codec->sample_rate && sc->time_scale > 1)
1545 st->codec->sample_rate = sc->time_scale;
1547 /* special codec parameters handling */
1548 switch (st->codec->codec_id) {
1549 #if CONFIG_DV_DEMUXER
1550 case AV_CODEC_ID_DVAUDIO:
1551 c->dv_fctx = avformat_alloc_context();
1552 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1554 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1555 return AVERROR(ENOMEM);
1557 sc->dv_audio_container = 1;
1558 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1561 /* no ifdef since parameters are always those */
1562 case AV_CODEC_ID_QCELP:
1563 st->codec->channels = 1;
1564 // force sample rate for qcelp when not stored in mov
1565 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1566 st->codec->sample_rate = 8000;
1567 // FIXME: Why is the following needed for some files?
1568 sc->samples_per_frame = 160;
1569 if (!sc->bytes_per_frame)
1570 sc->bytes_per_frame = 35;
1572 case AV_CODEC_ID_AMR_NB:
1573 st->codec->channels = 1;
1574 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1575 st->codec->sample_rate = 8000;
1577 case AV_CODEC_ID_AMR_WB:
1578 st->codec->channels = 1;
1579 st->codec->sample_rate = 16000;
1581 case AV_CODEC_ID_MP2:
1582 case AV_CODEC_ID_MP3:
1583 /* force type after stsd for m1a hdlr */
1584 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1585 st->need_parsing = AVSTREAM_PARSE_FULL;
1587 case AV_CODEC_ID_GSM:
1588 case AV_CODEC_ID_ADPCM_MS:
1589 case AV_CODEC_ID_ADPCM_IMA_WAV:
1590 case AV_CODEC_ID_ILBC:
1591 case AV_CODEC_ID_MACE3:
1592 case AV_CODEC_ID_MACE6:
1593 case AV_CODEC_ID_QDM2:
1594 st->codec->block_align = sc->bytes_per_frame;
1596 case AV_CODEC_ID_ALAC:
1597 if (st->codec->extradata_size == 36) {
1598 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1599 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1602 case AV_CODEC_ID_AC3:
1603 case AV_CODEC_ID_MPEG1VIDEO:
1604 case AV_CODEC_ID_VC1:
1605 st->need_parsing = AVSTREAM_PARSE_FULL;
1613 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1614 int codec_tag, int format,
1617 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1620 (codec_tag != format &&
1621 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1622 : codec_tag != MKTAG('j','p','e','g')))) {
1623 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1624 * export it as a separate AVStream but this needs a few changes
1625 * in the MOV demuxer, patch welcome. */
1627 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1628 avio_skip(pb, size);
1631 if ( codec_tag == AV_RL32("avc1") ||
1632 codec_tag == AV_RL32("hvc1") ||
1633 codec_tag == AV_RL32("hev1")
1635 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
1640 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1643 MOVStreamContext *sc;
1644 int pseudo_stream_id;
1646 if (c->fc->nb_streams < 1)
1648 st = c->fc->streams[c->fc->nb_streams-1];
1651 for (pseudo_stream_id = 0;
1652 pseudo_stream_id < entries && !pb->eof_reached;
1653 pseudo_stream_id++) {
1654 //Parsing Sample description table
1656 int ret, dref_id = 1;
1657 MOVAtom a = { AV_RL32("stsd") };
1658 int64_t start_pos = avio_tell(pb);
1659 int64_t size = avio_rb32(pb); /* size */
1660 uint32_t format = avio_rl32(pb); /* data format */
1663 avio_rb32(pb); /* reserved */
1664 avio_rb16(pb); /* reserved */
1665 dref_id = avio_rb16(pb);
1666 }else if (size <= 7){
1667 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1668 return AVERROR_INVALIDDATA;
1671 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1672 size - (avio_tell(pb) - start_pos)))
1675 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1676 sc->dref_id= dref_id;
1678 id = mov_codec_id(st, format);
1680 av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1681 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1682 (format >> 24) & 0xff, st->codec->codec_type);
1684 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1685 st->codec->codec_id = id;
1686 mov_parse_stsd_video(c, pb, st, sc);
1687 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1688 st->codec->codec_id = id;
1689 mov_parse_stsd_audio(c, pb, st, sc);
1690 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1691 st->codec->codec_id = id;
1692 mov_parse_stsd_subtitle(c, pb, st, sc,
1693 size - (avio_tell(pb) - start_pos));
1695 ret = mov_parse_stsd_data(c, pb, st, sc,
1696 size - (avio_tell(pb) - start_pos));
1700 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1701 a.size = size - (avio_tell(pb) - start_pos);
1703 if ((ret = mov_read_default(c, pb, a)) < 0)
1705 } else if (a.size > 0)
1706 avio_skip(pb, a.size);
1709 if (pb->eof_reached)
1712 return mov_finalize_stsd_codec(c, pb, st, sc);
1715 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1719 avio_r8(pb); /* version */
1720 avio_rb24(pb); /* flags */
1721 entries = avio_rb32(pb);
1723 return ff_mov_read_stsd_entries(c, pb, entries);
1726 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1729 MOVStreamContext *sc;
1730 unsigned int i, entries;
1732 if (c->fc->nb_streams < 1)
1734 st = c->fc->streams[c->fc->nb_streams-1];
1737 avio_r8(pb); /* version */
1738 avio_rb24(pb); /* flags */
1740 entries = avio_rb32(pb);
1742 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1746 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1747 return AVERROR_INVALIDDATA;
1748 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1750 return AVERROR(ENOMEM);
1752 for (i = 0; i < entries && !pb->eof_reached; i++) {
1753 sc->stsc_data[i].first = avio_rb32(pb);
1754 sc->stsc_data[i].count = avio_rb32(pb);
1755 sc->stsc_data[i].id = avio_rb32(pb);
1760 if (pb->eof_reached)
1766 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1769 MOVStreamContext *sc;
1770 unsigned i, entries;
1772 if (c->fc->nb_streams < 1)
1774 st = c->fc->streams[c->fc->nb_streams-1];
1777 avio_rb32(pb); // version + flags
1779 entries = avio_rb32(pb);
1780 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1781 return AVERROR_INVALIDDATA;
1782 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1784 return AVERROR(ENOMEM);
1786 for (i = 0; i < entries && !pb->eof_reached; i++) {
1787 sc->stps_data[i] = avio_rb32(pb);
1788 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1793 if (pb->eof_reached)
1799 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1802 MOVStreamContext *sc;
1803 unsigned int i, entries;
1805 if (c->fc->nb_streams < 1)
1807 st = c->fc->streams[c->fc->nb_streams-1];
1810 avio_r8(pb); /* version */
1811 avio_rb24(pb); /* flags */
1813 entries = avio_rb32(pb);
1815 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1819 sc->keyframe_absent = 1;
1820 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1821 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1824 if (entries >= UINT_MAX / sizeof(int))
1825 return AVERROR_INVALIDDATA;
1826 sc->keyframes = av_malloc(entries * sizeof(int));
1828 return AVERROR(ENOMEM);
1830 for (i = 0; i < entries && !pb->eof_reached; i++) {
1831 sc->keyframes[i] = avio_rb32(pb);
1832 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1835 sc->keyframe_count = i;
1837 if (pb->eof_reached)
1843 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1846 MOVStreamContext *sc;
1847 unsigned int i, entries, sample_size, field_size, num_bytes;
1851 if (c->fc->nb_streams < 1)
1853 st = c->fc->streams[c->fc->nb_streams-1];
1856 avio_r8(pb); /* version */
1857 avio_rb24(pb); /* flags */
1859 if (atom.type == MKTAG('s','t','s','z')) {
1860 sample_size = avio_rb32(pb);
1861 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1862 sc->sample_size = sample_size;
1863 sc->stsz_sample_size = sample_size;
1867 avio_rb24(pb); /* reserved */
1868 field_size = avio_r8(pb);
1870 entries = avio_rb32(pb);
1872 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1874 sc->sample_count = entries;
1878 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1879 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1880 return AVERROR_INVALIDDATA;
1885 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1886 return AVERROR_INVALIDDATA;
1887 sc->sample_sizes = av_malloc(entries * sizeof(int));
1888 if (!sc->sample_sizes)
1889 return AVERROR(ENOMEM);
1891 num_bytes = (entries*field_size+4)>>3;
1893 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1895 av_freep(&sc->sample_sizes);
1896 return AVERROR(ENOMEM);
1899 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1900 av_freep(&sc->sample_sizes);
1902 return AVERROR_INVALIDDATA;
1905 init_get_bits(&gb, buf, 8*num_bytes);
1907 for (i = 0; i < entries && !pb->eof_reached; i++) {
1908 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1909 sc->data_size += sc->sample_sizes[i];
1912 sc->sample_count = i;
1914 if (pb->eof_reached)
1921 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1924 MOVStreamContext *sc;
1925 unsigned int i, entries;
1927 int64_t total_sample_count=0;
1929 if (c->fc->nb_streams < 1)
1931 st = c->fc->streams[c->fc->nb_streams-1];
1934 avio_r8(pb); /* version */
1935 avio_rb24(pb); /* flags */
1936 entries = avio_rb32(pb);
1938 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1939 c->fc->nb_streams-1, entries);
1941 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1944 av_free(sc->stts_data);
1945 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1947 return AVERROR(ENOMEM);
1949 for (i = 0; i < entries && !pb->eof_reached; i++) {
1950 int sample_duration;
1953 sample_count=avio_rb32(pb);
1954 sample_duration = avio_rb32(pb);
1956 /* sample_duration < 0 is invalid based on the spec */
1957 if (sample_duration < 0) {
1958 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta %d in STTS, at %d st:%d\n",
1959 sample_duration, i, c->fc->nb_streams-1);
1960 sample_duration = 1;
1962 if (sample_count < 0) {
1963 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
1964 return AVERROR_INVALIDDATA;
1966 sc->stts_data[i].count= sample_count;
1967 sc->stts_data[i].duration= sample_duration;
1969 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1970 sample_count, sample_duration);
1974 && sample_count == 1
1975 && total_sample_count > 100
1976 && sample_duration/10 > duration / total_sample_count)
1977 sample_duration = duration / total_sample_count;
1978 duration+=(int64_t)sample_duration*sample_count;
1979 total_sample_count+=sample_count;
1984 sc->duration_for_fps += duration;
1985 sc->nb_frames_for_fps += total_sample_count;
1987 if (pb->eof_reached)
1990 st->nb_frames= total_sample_count;
1992 st->duration= duration;
1993 sc->track_end = duration;
1997 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2000 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2004 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2007 MOVStreamContext *sc;
2008 unsigned int i, entries;
2010 if (c->fc->nb_streams < 1)
2012 st = c->fc->streams[c->fc->nb_streams-1];
2015 avio_r8(pb); /* version */
2016 avio_rb24(pb); /* flags */
2017 entries = avio_rb32(pb);
2019 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2023 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2024 return AVERROR_INVALIDDATA;
2025 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
2027 return AVERROR(ENOMEM);
2029 for (i = 0; i < entries && !pb->eof_reached; i++) {
2030 int count =avio_rb32(pb);
2031 int duration =avio_rb32(pb);
2033 sc->ctts_data[i].count = count;
2034 sc->ctts_data[i].duration= duration;
2036 av_dlog(c->fc, "count=%d, duration=%d\n",
2039 if (FFABS(duration) > (1<<28) && i+2<entries) {
2040 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2041 av_freep(&sc->ctts_data);
2047 mov_update_dts_shift(sc, duration);
2052 if (pb->eof_reached)
2055 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
2060 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2063 MOVStreamContext *sc;
2064 unsigned int i, entries;
2066 uint32_t grouping_type;
2068 if (c->fc->nb_streams < 1)
2070 st = c->fc->streams[c->fc->nb_streams-1];
2073 version = avio_r8(pb); /* version */
2074 avio_rb24(pb); /* flags */
2075 grouping_type = avio_rl32(pb);
2076 if (grouping_type != MKTAG( 'r','a','p',' '))
2077 return 0; /* only support 'rap ' grouping */
2079 avio_rb32(pb); /* grouping_type_parameter */
2081 entries = avio_rb32(pb);
2084 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2085 return AVERROR_INVALIDDATA;
2086 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2088 return AVERROR(ENOMEM);
2090 for (i = 0; i < entries && !pb->eof_reached; i++) {
2091 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2092 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2095 sc->rap_group_count = i;
2097 return pb->eof_reached ? AVERROR_EOF : 0;
2100 static void mov_build_index(MOVContext *mov, AVStream *st)
2102 MOVStreamContext *sc = st->priv_data;
2103 int64_t current_offset;
2104 int64_t current_dts = 0;
2105 unsigned int stts_index = 0;
2106 unsigned int stsc_index = 0;
2107 unsigned int stss_index = 0;
2108 unsigned int stps_index = 0;
2110 uint64_t stream_size = 0;
2112 /* adjust first dts according to edit list */
2113 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
2114 if (sc->empty_duration)
2115 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
2116 sc->time_offset = sc->start_time - sc->empty_duration;
2117 current_dts = -sc->time_offset;
2118 if (sc->ctts_count>0 && sc->stts_count>0 &&
2119 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2120 /* more than 16 frames delay, dts are likely wrong
2121 this happens with files created by iMovie */
2123 st->codec->has_b_frames = 1;
2127 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2128 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2129 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2130 unsigned int current_sample = 0;
2131 unsigned int stts_sample = 0;
2132 unsigned int sample_size;
2133 unsigned int distance = 0;
2134 unsigned int rap_group_index = 0;
2135 unsigned int rap_group_sample = 0;
2136 int rap_group_present = sc->rap_group_count && sc->rap_group;
2137 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2139 current_dts -= sc->dts_shift;
2141 if (!sc->sample_count || st->nb_index_entries)
2143 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2145 if (av_reallocp_array(&st->index_entries,
2146 st->nb_index_entries + sc->sample_count,
2147 sizeof(*st->index_entries)) < 0) {
2148 st->nb_index_entries = 0;
2151 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2153 for (i = 0; i < sc->chunk_count; i++) {
2154 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2155 current_offset = sc->chunk_offsets[i];
2156 while (stsc_index + 1 < sc->stsc_count &&
2157 i + 1 == sc->stsc_data[stsc_index + 1].first)
2160 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2161 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2162 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2163 sc->stsz_sample_size = sc->sample_size;
2165 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2166 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2167 sc->stsz_sample_size = sc->sample_size;
2170 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2172 if (current_sample >= sc->sample_count) {
2173 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2177 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2179 if (stss_index + 1 < sc->keyframe_count)
2181 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2183 if (stps_index + 1 < sc->stps_count)
2186 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2187 if (sc->rap_group[rap_group_index].index > 0)
2189 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2190 rap_group_sample = 0;
2194 if (sc->keyframe_absent
2196 && !rap_group_present
2197 && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2201 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2202 if (sc->pseudo_stream_id == -1 ||
2203 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2204 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2205 e->pos = current_offset;
2206 e->timestamp = current_dts;
2207 e->size = sample_size;
2208 e->min_distance = distance;
2209 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2210 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2211 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2212 current_offset, current_dts, sample_size, distance, keyframe);
2213 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2214 ff_rfps_add_frame(mov->fc, st, current_dts);
2217 current_offset += sample_size;
2218 stream_size += sample_size;
2219 current_dts += sc->stts_data[stts_index].duration;
2223 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2229 if (st->duration > 0)
2230 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2232 unsigned chunk_samples, total = 0;
2234 // compute total chunk count
2235 for (i = 0; i < sc->stsc_count; i++) {
2236 unsigned count, chunk_count;
2238 chunk_samples = sc->stsc_data[i].count;
2239 if (i != sc->stsc_count - 1 &&
2240 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2241 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2245 if (sc->samples_per_frame >= 160) { // gsm
2246 count = chunk_samples / sc->samples_per_frame;
2247 } else if (sc->samples_per_frame > 1) {
2248 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2249 count = (chunk_samples+samples-1) / samples;
2251 count = (chunk_samples+1023) / 1024;
2254 if (i < sc->stsc_count - 1)
2255 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2257 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2258 total += chunk_count * count;
2261 av_dlog(mov->fc, "chunk count %d\n", total);
2262 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2264 if (av_reallocp_array(&st->index_entries,
2265 st->nb_index_entries + total,
2266 sizeof(*st->index_entries)) < 0) {
2267 st->nb_index_entries = 0;
2270 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2273 for (i = 0; i < sc->chunk_count; i++) {
2274 current_offset = sc->chunk_offsets[i];
2275 if (stsc_index + 1 < sc->stsc_count &&
2276 i + 1 == sc->stsc_data[stsc_index + 1].first)
2278 chunk_samples = sc->stsc_data[stsc_index].count;
2280 while (chunk_samples > 0) {
2282 unsigned size, samples;
2284 if (sc->samples_per_frame >= 160) { // gsm
2285 samples = sc->samples_per_frame;
2286 size = sc->bytes_per_frame;
2288 if (sc->samples_per_frame > 1) {
2289 samples = FFMIN((1024 / sc->samples_per_frame)*
2290 sc->samples_per_frame, chunk_samples);
2291 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2293 samples = FFMIN(1024, chunk_samples);
2294 size = samples * sc->sample_size;
2298 if (st->nb_index_entries >= total) {
2299 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2302 e = &st->index_entries[st->nb_index_entries++];
2303 e->pos = current_offset;
2304 e->timestamp = current_dts;
2306 e->min_distance = 0;
2307 e->flags = AVINDEX_KEYFRAME;
2308 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2309 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2312 current_offset += size;
2313 current_dts += samples;
2314 chunk_samples -= samples;
2320 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2321 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2323 /* try relative path, we do not try the absolute because it can leak information about our
2324 system to an attacker */
2325 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2326 char filename[1024];
2327 const char *src_path;
2330 /* find a source dir */
2331 src_path = strrchr(src, '/');
2337 /* find a next level down to target */
2338 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2339 if (ref->path[l] == '/') {
2340 if (i == ref->nlvl_to - 1)
2346 /* compose filename if next level down to target was found */
2347 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2348 memcpy(filename, src, src_path - src);
2349 filename[src_path - src] = 0;
2351 for (i = 1; i < ref->nlvl_from; i++)
2352 av_strlcat(filename, "../", 1024);
2354 av_strlcat(filename, ref->path + l + 1, 1024);
2356 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2359 } else if (use_absolute_path) {
2360 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2361 "this is a possible security issue\n");
2362 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2366 return AVERROR(ENOENT);
2369 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2371 if (sc->time_scale <= 0) {
2372 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2373 sc->time_scale = c->time_scale;
2374 if (sc->time_scale <= 0)
2379 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2382 MOVStreamContext *sc;
2385 st = avformat_new_stream(c->fc, NULL);
2386 if (!st) return AVERROR(ENOMEM);
2387 st->id = c->fc->nb_streams;
2388 sc = av_mallocz(sizeof(MOVStreamContext));
2389 if (!sc) return AVERROR(ENOMEM);
2392 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2393 sc->ffindex = st->index;
2395 if ((ret = mov_read_default(c, pb, atom)) < 0)
2399 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2400 (!sc->sample_size && !sc->sample_count))) {
2401 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2406 fix_timescale(c, sc);
2408 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2410 mov_build_index(c, st);
2412 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2413 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2414 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2415 c->use_absolute_path, c->fc) < 0)
2416 av_log(c->fc, AV_LOG_ERROR,
2417 "stream %d, error opening alias: path='%s', dir='%s', "
2418 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2419 st->index, dref->path, dref->dir, dref->filename,
2420 dref->volume, dref->nlvl_from, dref->nlvl_to);
2423 sc->pb_is_copied = 1;
2426 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2427 if (!st->sample_aspect_ratio.num &&
2428 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2429 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2430 ((double)st->codec->width * sc->height), INT_MAX);
2433 #if FF_API_R_FRAME_RATE
2434 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2435 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2436 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2440 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2441 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2442 TAG_IS_AVCI(st->codec->codec_tag)) {
2443 ret = ff_generate_avci_extradata(st);
2448 switch (st->codec->codec_id) {
2449 #if CONFIG_H261_DECODER
2450 case AV_CODEC_ID_H261:
2452 #if CONFIG_H263_DECODER
2453 case AV_CODEC_ID_H263:
2455 #if CONFIG_MPEG4_DECODER
2456 case AV_CODEC_ID_MPEG4:
2458 st->codec->width = 0; /* let decoder init width/height */
2459 st->codec->height= 0;
2463 /* Do not need those anymore. */
2464 av_freep(&sc->chunk_offsets);
2465 av_freep(&sc->stsc_data);
2466 av_freep(&sc->sample_sizes);
2467 av_freep(&sc->keyframes);
2468 av_freep(&sc->stts_data);
2469 av_freep(&sc->stps_data);
2470 av_freep(&sc->rap_group);
2475 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2478 c->itunes_metadata = 1;
2479 ret = mov_read_default(c, pb, atom);
2480 c->itunes_metadata = 0;
2484 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
2486 int64_t end = avio_tell(pb) + size;
2487 uint8_t *key = NULL, *val = NULL;
2490 MOVStreamContext *sc;
2492 if (c->fc->nb_streams < 1)
2494 st = c->fc->streams[c->fc->nb_streams-1];
2497 for (i = 0; i < 2; i++) {
2501 if (end - avio_tell(pb) <= 12)
2504 len = avio_rb32(pb);
2505 tag = avio_rl32(pb);
2506 avio_skip(pb, 4); // flags
2508 if (len < 12 || len - 12 > end - avio_tell(pb))
2512 if (tag == MKTAG('n', 'a', 'm', 'e'))
2514 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2521 *p = av_malloc(len + 1);
2524 avio_read(pb, *p, len);
2529 if (strcmp(key, "iTunSMPB") == 0) {
2530 int priming, remainder, samples;
2531 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
2532 if(priming>0 && priming<16384)
2533 sc->start_pad = priming;
2536 if (strcmp(key, "cdec") != 0) {
2537 av_dict_set(&c->fc->metadata, key, val,
2538 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2543 avio_seek(pb, end, SEEK_SET);
2549 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2551 int64_t end = avio_tell(pb) + atom.size;
2557 len = avio_rb32(pb);
2558 tag = avio_rl32(pb);
2560 if (len > atom.size)
2563 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2564 uint8_t domain[128];
2567 avio_skip(pb, 4); // flags
2570 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2571 avio_skip(pb, len - domain_len);
2572 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
2576 av_log(c->fc, AV_LOG_VERBOSE,
2577 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2581 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2583 while (atom.size > 8) {
2584 uint32_t tag = avio_rl32(pb);
2586 if (tag == MKTAG('h','d','l','r')) {
2587 avio_seek(pb, -8, SEEK_CUR);
2589 return mov_read_default(c, pb, atom);
2595 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2600 int64_t disp_transform[2];
2601 int display_matrix[3][3];
2603 MOVStreamContext *sc;
2607 if (c->fc->nb_streams < 1)
2609 st = c->fc->streams[c->fc->nb_streams-1];
2612 version = avio_r8(pb);
2613 flags = avio_rb24(pb);
2614 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2620 avio_rb32(pb); /* creation time */
2621 avio_rb32(pb); /* modification time */
2623 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2624 avio_rb32(pb); /* reserved */
2626 /* highlevel (considering edits) duration in movie timebase */
2627 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2628 avio_rb32(pb); /* reserved */
2629 avio_rb32(pb); /* reserved */
2631 avio_rb16(pb); /* layer */
2632 avio_rb16(pb); /* alternate group */
2633 avio_rb16(pb); /* volume */
2634 avio_rb16(pb); /* reserved */
2636 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2637 // they're kept in fixed point format through all calculations
2638 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2639 // side data, but the scale factor is not needed to calculate aspect ratio
2640 for (i = 0; i < 3; i++) {
2641 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2642 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2643 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2646 width = avio_rb32(pb); // 16.16 fixed point track width
2647 height = avio_rb32(pb); // 16.16 fixed point track height
2648 sc->width = width >> 16;
2649 sc->height = height >> 16;
2651 // save the matrix and add rotate metadata when it is not the default
2653 if (display_matrix[0][0] != (1 << 16) ||
2654 display_matrix[1][1] != (1 << 16) ||
2655 display_matrix[2][2] != (1 << 30) ||
2656 display_matrix[0][1] || display_matrix[0][2] ||
2657 display_matrix[1][0] || display_matrix[1][2] ||
2658 display_matrix[2][0] || display_matrix[2][1]) {
2662 av_freep(&sc->display_matrix);
2663 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2664 if (!sc->display_matrix)
2665 return AVERROR(ENOMEM);
2667 for (i = 0; i < 3; i++)
2668 for (j = 0; j < 3; j++)
2669 sc->display_matrix[i * 3 + j] = display_matrix[j][i];
2671 rotate = av_display_rotation_get(sc->display_matrix);
2672 if (!isnan(rotate)) {
2673 char rotate_buf[64];
2675 if (rotate < 0) // for backward compatibility
2677 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
2678 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
2682 // transform the display width/height according to the matrix
2683 // skip this if the display matrix is the default identity matrix
2684 // or if it is rotating the picture, ex iPhone 3GS
2685 // to keep the same scale, use [width height 1<<16]
2686 if (width && height &&
2687 ((display_matrix[0][0] != 65536 ||
2688 display_matrix[1][1] != 65536) &&
2689 !display_matrix[0][1] &&
2690 !display_matrix[1][0] &&
2691 !display_matrix[2][0] && !display_matrix[2][1])) {
2692 for (i = 0; i < 2; i++)
2694 (int64_t) width * display_matrix[0][i] +
2695 (int64_t) height * display_matrix[1][i] +
2696 ((int64_t) display_matrix[2][i] << 16);
2698 //sample aspect ratio is new width/height divided by old width/height
2699 st->sample_aspect_ratio = av_d2q(
2700 ((double) disp_transform[0] * height) /
2701 ((double) disp_transform[1] * width), INT_MAX);
2706 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2708 MOVFragment *frag = &c->fragment;
2709 MOVTrackExt *trex = NULL;
2710 int flags, track_id, i;
2712 avio_r8(pb); /* version */
2713 flags = avio_rb24(pb);
2715 track_id = avio_rb32(pb);
2717 return AVERROR_INVALIDDATA;
2718 frag->track_id = track_id;
2719 for (i = 0; i < c->trex_count; i++)
2720 if (c->trex_data[i].track_id == frag->track_id) {
2721 trex = &c->trex_data[i];
2725 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2726 return AVERROR_INVALIDDATA;
2729 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2730 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
2731 frag->moof_offset : frag->implicit_offset;
2732 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2734 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2735 avio_rb32(pb) : trex->duration;
2736 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2737 avio_rb32(pb) : trex->size;
2738 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2739 avio_rb32(pb) : trex->flags;
2740 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2744 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2746 c->chapter_track = avio_rb32(pb);
2750 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2755 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2756 return AVERROR_INVALIDDATA;
2757 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2758 sizeof(*c->trex_data))) < 0) {
2763 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2765 trex = &c->trex_data[c->trex_count++];
2766 avio_r8(pb); /* version */
2767 avio_rb24(pb); /* flags */
2768 trex->track_id = avio_rb32(pb);
2769 trex->stsd_id = avio_rb32(pb);
2770 trex->duration = avio_rb32(pb);
2771 trex->size = avio_rb32(pb);
2772 trex->flags = avio_rb32(pb);
2776 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2778 MOVFragment *frag = &c->fragment;
2779 AVStream *st = NULL;
2780 MOVStreamContext *sc;
2784 int data_offset = 0;
2785 unsigned entries, first_sample_flags = frag->flags;
2786 int flags, distance, i, found_keyframe = 0, err;
2788 for (i = 0; i < c->fc->nb_streams; i++) {
2789 if (c->fc->streams[i]->id == frag->track_id) {
2790 st = c->fc->streams[i];
2795 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2796 return AVERROR_INVALIDDATA;
2799 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
2801 avio_r8(pb); /* version */
2802 flags = avio_rb24(pb);
2803 entries = avio_rb32(pb);
2804 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2806 /* Always assume the presence of composition time offsets.
2807 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2808 * 1) in the initial movie, there are no samples.
2809 * 2) in the first movie fragment, there is only one sample without composition time offset.
2810 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2811 if (!sc->ctts_count && sc->sample_count)
2813 /* Complement ctts table if moov atom doesn't have ctts atom. */
2814 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2816 return AVERROR(ENOMEM);
2817 sc->ctts_data = ctts_data;
2818 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2819 sc->ctts_data[sc->ctts_count].duration = 0;
2822 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2823 return AVERROR_INVALIDDATA;
2824 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2825 sizeof(*sc->ctts_data))) < 0) {
2829 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2830 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2831 dts = sc->track_end - sc->time_offset;
2832 offset = frag->base_data_offset + data_offset;
2834 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2835 for (i = 0; i < entries && !pb->eof_reached; i++) {
2836 unsigned sample_size = frag->size;
2837 int sample_flags = i ? frag->flags : first_sample_flags;
2838 unsigned sample_duration = frag->duration;
2841 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2842 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2843 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2844 sc->ctts_data[sc->ctts_count].count = 1;
2845 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2847 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
2849 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2851 else if (!found_keyframe)
2852 keyframe = found_keyframe =
2853 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2854 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2857 av_add_index_entry(st, offset, dts, sample_size, distance,
2858 keyframe ? AVINDEX_KEYFRAME : 0);
2859 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2860 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2861 offset, dts, sample_size, distance, keyframe);
2863 dts += sample_duration;
2864 offset += sample_size;
2865 sc->data_size += sample_size;
2866 sc->duration_for_fps += sample_duration;
2867 sc->nb_frames_for_fps ++;
2870 if (pb->eof_reached)
2873 frag->implicit_offset = offset;
2874 st->duration = sc->track_end = dts + sc->time_offset;
2878 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2879 /* like the files created with Adobe Premiere 5.0, for samples see */
2880 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2881 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2886 return 0; /* continue */
2887 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2888 avio_skip(pb, atom.size - 4);
2891 atom.type = avio_rl32(pb);
2893 if (atom.type != MKTAG('m','d','a','t')) {
2894 avio_skip(pb, atom.size);
2897 err = mov_read_mdat(c, pb, atom);
2901 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2906 uint8_t *moov_data; /* uncompressed data */
2907 long cmov_len, moov_len;
2910 avio_rb32(pb); /* dcom atom */
2911 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2912 return AVERROR_INVALIDDATA;
2913 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2914 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
2915 return AVERROR_INVALIDDATA;
2917 avio_rb32(pb); /* cmvd atom */
2918 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2919 return AVERROR_INVALIDDATA;
2920 moov_len = avio_rb32(pb); /* uncompressed size */
2921 cmov_len = atom.size - 6 * 4;
2923 cmov_data = av_malloc(cmov_len);
2925 return AVERROR(ENOMEM);
2926 moov_data = av_malloc(moov_len);
2929 return AVERROR(ENOMEM);
2931 avio_read(pb, cmov_data, cmov_len);
2932 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2933 goto free_and_return;
2934 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2935 goto free_and_return;
2936 atom.type = MKTAG('m','o','o','v');
2937 atom.size = moov_len;
2938 ret = mov_read_default(c, &ctx, atom);
2944 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2945 return AVERROR(ENOSYS);
2949 /* edit list atom */
2950 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2952 MOVStreamContext *sc;
2953 int i, edit_count, version, edit_start_index = 0;
2954 int unsupported = 0;
2956 if (c->fc->nb_streams < 1 || c->ignore_editlist)
2958 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2960 version = avio_r8(pb); /* version */
2961 avio_rb24(pb); /* flags */
2962 edit_count = avio_rb32(pb); /* entries */
2964 if ((uint64_t)edit_count*12+8 > atom.size)
2965 return AVERROR_INVALIDDATA;
2967 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2968 for (i=0; i<edit_count; i++){
2973 duration = avio_rb64(pb);
2974 time = avio_rb64(pb);
2976 duration = avio_rb32(pb); /* segment duration */
2977 time = (int32_t)avio_rb32(pb); /* media time */
2979 rate = avio_rb32(pb);
2980 if (i == 0 && time == -1) {
2981 sc->empty_duration = duration;
2982 edit_start_index = 1;
2983 } else if (i == edit_start_index && time >= 0)
2984 sc->start_time = time;
2988 av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
2989 duration, time, rate / 65536.0);
2993 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2994 "a/v desync might occur, patch welcome\n");
2999 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3001 MOVStreamContext *sc;
3003 if (c->fc->nb_streams < 1)
3004 return AVERROR_INVALIDDATA;
3005 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3006 sc->timecode_track = avio_rb32(pb);
3010 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3014 static const uint8_t uuid_isml_manifest[] = {
3015 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3016 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3019 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3020 return AVERROR_INVALIDDATA;
3022 ret = avio_read(pb, uuid, sizeof(uuid));
3025 } else if (ret != sizeof(uuid)) {
3026 return AVERROR_INVALIDDATA;
3028 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3029 uint8_t *buffer, *ptr;
3031 size_t len = atom.size - sizeof(uuid);
3034 return AVERROR_INVALIDDATA;
3036 ret = avio_skip(pb, 4); // zeroes
3039 buffer = av_mallocz(len + 1);
3041 return AVERROR(ENOMEM);
3043 ret = avio_read(pb, buffer, len);
3047 } else if (ret != len) {
3049 return AVERROR_INVALIDDATA;
3053 while ((ptr = av_stristr(ptr, "systemBitrate=\"")) != NULL) {
3054 ptr += sizeof("systemBitrate=\"") - 1;
3055 c->bitrates_count++;
3056 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3058 c->bitrates_count = 0;
3060 return AVERROR(ENOMEM);
3063 ret = strtol(ptr, &endptr, 10);
3064 if (ret < 0 || errno || *endptr != '"') {
3065 c->bitrates[c->bitrates_count - 1] = 0;
3067 c->bitrates[c->bitrates_count - 1] = ret;
3076 static const MOVParseTableEntry mov_default_parse_table[] = {
3077 { MKTAG('A','C','L','R'), mov_read_avid },
3078 { MKTAG('A','P','R','G'), mov_read_avid },
3079 { MKTAG('A','A','L','P'), mov_read_avid },
3080 { MKTAG('A','R','E','S'), mov_read_ares },
3081 { MKTAG('a','v','s','s'), mov_read_avss },
3082 { MKTAG('c','h','p','l'), mov_read_chpl },
3083 { MKTAG('c','o','6','4'), mov_read_stco },
3084 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3085 { MKTAG('d','i','n','f'), mov_read_default },
3086 { MKTAG('d','r','e','f'), mov_read_dref },
3087 { MKTAG('e','d','t','s'), mov_read_default },
3088 { MKTAG('e','l','s','t'), mov_read_elst },
3089 { MKTAG('e','n','d','a'), mov_read_enda },
3090 { MKTAG('f','i','e','l'), mov_read_fiel },
3091 { MKTAG('f','t','y','p'), mov_read_ftyp },
3092 { MKTAG('g','l','b','l'), mov_read_glbl },
3093 { MKTAG('h','d','l','r'), mov_read_hdlr },
3094 { MKTAG('i','l','s','t'), mov_read_ilst },
3095 { MKTAG('j','p','2','h'), mov_read_jp2h },
3096 { MKTAG('m','d','a','t'), mov_read_mdat },
3097 { MKTAG('m','d','h','d'), mov_read_mdhd },
3098 { MKTAG('m','d','i','a'), mov_read_default },
3099 { MKTAG('m','e','t','a'), mov_read_meta },
3100 { MKTAG('m','i','n','f'), mov_read_default },
3101 { MKTAG('m','o','o','f'), mov_read_moof },
3102 { MKTAG('m','o','o','v'), mov_read_moov },
3103 { MKTAG('m','v','e','x'), mov_read_default },
3104 { MKTAG('m','v','h','d'), mov_read_mvhd },
3105 { MKTAG('S','M','I',' '), mov_read_svq3 },
3106 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
3107 { MKTAG('a','v','c','C'), mov_read_glbl },
3108 { MKTAG('p','a','s','p'), mov_read_pasp },
3109 { MKTAG('s','t','b','l'), mov_read_default },
3110 { MKTAG('s','t','c','o'), mov_read_stco },
3111 { MKTAG('s','t','p','s'), mov_read_stps },
3112 { MKTAG('s','t','r','f'), mov_read_strf },
3113 { MKTAG('s','t','s','c'), mov_read_stsc },
3114 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3115 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3116 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3117 { MKTAG('s','t','t','s'), mov_read_stts },
3118 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3119 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3120 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3121 { MKTAG('t','r','a','k'), mov_read_trak },
3122 { MKTAG('t','r','a','f'), mov_read_default },
3123 { MKTAG('t','r','e','f'), mov_read_default },
3124 { MKTAG('t','m','c','d'), mov_read_tmcd },
3125 { MKTAG('c','h','a','p'), mov_read_chap },
3126 { MKTAG('t','r','e','x'), mov_read_trex },
3127 { MKTAG('t','r','u','n'), mov_read_trun },
3128 { MKTAG('u','d','t','a'), mov_read_default },
3129 { MKTAG('w','a','v','e'), mov_read_wave },
3130 { MKTAG('e','s','d','s'), mov_read_esds },
3131 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3132 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3133 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3134 { MKTAG('w','f','e','x'), mov_read_wfex },
3135 { MKTAG('c','m','o','v'), mov_read_cmov },
3136 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3137 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3138 { MKTAG('s','b','g','p'), mov_read_sbgp },
3139 { MKTAG('h','v','c','C'), mov_read_glbl },
3140 { MKTAG('u','u','i','d'), mov_read_uuid },
3141 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
3142 { MKTAG('-','-','-','-'), mov_read_custom },
3146 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3148 int64_t total_size = 0;
3153 atom.size = INT64_MAX;
3154 while (total_size + 8 <= atom.size && !url_feof(pb)) {
3155 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3158 if (atom.size >= 8) {
3159 a.size = avio_rb32(pb);
3160 a.type = avio_rl32(pb);
3161 if (a.type == MKTAG('f','r','e','e') &&
3165 uint32_t *type = (uint32_t *)buf + 1;
3166 avio_read(pb, buf, 8);
3167 avio_seek(pb, -8, SEEK_CUR);
3168 if (*type == MKTAG('m','v','h','d') ||
3169 *type == MKTAG('c','m','o','v')) {
3170 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
3171 a.type = MKTAG('m','o','o','v');
3174 if (atom.type != MKTAG('r','o','o','t') &&
3175 atom.type != MKTAG('m','o','o','v'))
3177 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
3179 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
3185 if (a.size == 1) { /* 64 bit extended size */
3186 a.size = avio_rb64(pb) - 8;
3190 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3191 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3193 a.size = atom.size - total_size + 8;
3198 a.size = FFMIN(a.size, atom.size - total_size);
3200 for (i = 0; mov_default_parse_table[i].type; i++)
3201 if (mov_default_parse_table[i].type == a.type) {
3202 parse = mov_default_parse_table[i].parse;
3206 // container is user data
3207 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3208 atom.type == MKTAG('i','l','s','t')))
3209 parse = mov_read_udta_string;
3211 if (!parse) { /* skip leaf atoms data */
3212 avio_skip(pb, a.size);
3214 int64_t start_pos = avio_tell(pb);
3216 int err = parse(c, pb, a);
3219 if (c->found_moov && c->found_mdat &&
3220 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3221 start_pos + a.size == avio_size(pb))) {
3222 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3223 c->next_root_atom = start_pos + a.size;
3226 left = a.size - avio_tell(pb) + start_pos;
3227 if (left > 0) /* skip garbage at atom end */
3228 avio_skip(pb, left);
3229 else if (left < 0) {
3230 av_log(c->fc, AV_LOG_WARNING,
3231 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3232 (char*)&a.type, -left);
3233 avio_seek(pb, left, SEEK_CUR);
3237 total_size += a.size;
3240 if (total_size < atom.size && atom.size < 0x7ffff)
3241 avio_skip(pb, atom.size - total_size);
3246 static int mov_probe(AVProbeData *p)
3251 int moov_offset = -1;
3253 /* check file header */
3256 /* ignore invalid offset */
3257 if ((offset + 8) > (unsigned int)p->buf_size)
3259 tag = AV_RL32(p->buf + offset + 4);
3261 /* check for obvious tags */
3262 case MKTAG('m','o','o','v'):
3263 moov_offset = offset + 4;
3264 case MKTAG('m','d','a','t'):
3265 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3266 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3267 case MKTAG('f','t','y','p'):
3268 if (AV_RB32(p->buf+offset) < 8 &&
3269 (AV_RB32(p->buf+offset) != 1 ||
3270 offset + 12 > (unsigned int)p->buf_size ||
3271 AV_RB64(p->buf+offset + 8) == 0)) {
3272 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3273 } else if (tag == MKTAG('f','t','y','p') &&
3274 AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')) {
3275 score = FFMAX(score, 5);
3277 score = AVPROBE_SCORE_MAX;
3279 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3281 /* those are more common words, so rate then a bit less */
3282 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3283 case MKTAG('w','i','d','e'):
3284 case MKTAG('f','r','e','e'):
3285 case MKTAG('j','u','n','k'):
3286 case MKTAG('p','i','c','t'):
3287 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
3288 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3290 case MKTAG(0x82,0x82,0x7f,0x7d):
3291 case MKTAG('s','k','i','p'):
3292 case MKTAG('u','u','i','d'):
3293 case MKTAG('p','r','f','l'):
3294 /* if we only find those cause probedata is too small at least rate them */
3295 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3296 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3299 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3302 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
3303 /* moov atom in the header - we should make sure that this is not a
3304 * MOV-packed MPEG-PS */
3305 offset = moov_offset;
3307 while(offset < (p->buf_size - 16)){ /* Sufficient space */
3308 /* We found an actual hdlr atom */
3309 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
3310 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
3311 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
3312 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
3313 /* We found a media handler reference atom describing an
3314 * MPEG-PS-in-MOV, return a
3315 * low score to force expanding the probe window until
3316 * mpegps_probe finds what it needs */
3327 // must be done after parsing all trak because there's no order requirement
3328 static void mov_read_chapters(AVFormatContext *s)
3330 MOVContext *mov = s->priv_data;
3331 AVStream *st = NULL;
3332 MOVStreamContext *sc;
3336 for (i = 0; i < s->nb_streams; i++)
3337 if (s->streams[i]->id == mov->chapter_track) {
3342 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3346 st->discard = AVDISCARD_ALL;
3348 cur_pos = avio_tell(sc->pb);
3350 for (i = 0; i < st->nb_index_entries; i++) {
3351 AVIndexEntry *sample = &st->index_entries[i];
3352 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3357 if (end < sample->timestamp) {
3358 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
3359 end = AV_NOPTS_VALUE;
3362 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3363 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3367 // the first two bytes are the length of the title
3368 len = avio_rb16(sc->pb);
3369 if (len > sample->size-2)
3371 title_len = 2*len + 1;
3372 if (!(title = av_mallocz(title_len)))
3375 // The samples could theoretically be in any encoding if there's an encd
3376 // atom following, but in practice are only utf-8 or utf-16, distinguished
3377 // instead by the presence of a BOM
3381 ch = avio_rb16(sc->pb);
3383 avio_get_str16be(sc->pb, len, title, title_len);
3384 else if (ch == 0xfffe)
3385 avio_get_str16le(sc->pb, len, title, title_len);
3388 if (len == 1 || len == 2)
3391 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3395 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3399 avio_seek(sc->pb, cur_pos, SEEK_SET);
3402 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
3403 uint32_t value, int flags)
3406 char buf[AV_TIMECODE_STR_SIZE];
3407 AVRational rate = {st->codec->time_base.den,
3408 st->codec->time_base.num};
3409 int ret = av_timecode_init(&tc, rate, flags, 0, s);
3412 av_dict_set(&st->metadata, "timecode",
3413 av_timecode_make_string(&tc, buf, value), 0);
3417 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
3419 MOVStreamContext *sc = st->priv_data;
3421 int64_t cur_pos = avio_tell(sc->pb);
3424 if (!st->nb_index_entries)
3427 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3428 value = avio_rb32(s->pb);
3430 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3431 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3432 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3434 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3435 * not the case) and thus assume "frame number format" instead of QT one.
3436 * No sample with tmcd track can be found with a QT timecode at the moment,
3437 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3439 parse_timecode_in_framenum_format(s, st, value, flags);
3441 avio_seek(sc->pb, cur_pos, SEEK_SET);
3445 static int mov_read_close(AVFormatContext *s)
3447 MOVContext *mov = s->priv_data;
3450 for (i = 0; i < s->nb_streams; i++) {
3451 AVStream *st = s->streams[i];
3452 MOVStreamContext *sc = st->priv_data;
3454 av_freep(&sc->ctts_data);
3455 for (j = 0; j < sc->drefs_count; j++) {
3456 av_freep(&sc->drefs[j].path);
3457 av_freep(&sc->drefs[j].dir);
3459 av_freep(&sc->drefs);
3461 sc->drefs_count = 0;
3463 if (!sc->pb_is_copied)
3467 av_freep(&sc->chunk_offsets);
3468 av_freep(&sc->stsc_data);
3469 av_freep(&sc->sample_sizes);
3470 av_freep(&sc->keyframes);
3471 av_freep(&sc->stts_data);
3472 av_freep(&sc->stps_data);
3473 av_freep(&sc->rap_group);
3474 av_freep(&sc->display_matrix);
3477 if (mov->dv_demux) {
3478 avformat_free_context(mov->dv_fctx);
3479 mov->dv_fctx = NULL;
3482 av_freep(&mov->trex_data);
3483 av_freep(&mov->bitrates);
3488 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3492 for (i = 0; i < s->nb_streams; i++) {
3493 AVStream *st = s->streams[i];
3494 MOVStreamContext *sc = st->priv_data;
3496 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3497 sc->timecode_track == tmcd_id)
3503 /* look for a tmcd track not referenced by any video track, and export it globally */
3504 static void export_orphan_timecode(AVFormatContext *s)
3508 for (i = 0; i < s->nb_streams; i++) {
3509 AVStream *st = s->streams[i];
3511 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3512 !tmcd_is_referenced(s, i + 1)) {
3513 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3515 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3522 static int mov_read_header(AVFormatContext *s)
3524 MOVContext *mov = s->priv_data;
3525 AVIOContext *pb = s->pb;
3527 MOVAtom atom = { AV_RL32("root") };
3531 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3533 atom.size = avio_size(pb);
3535 atom.size = INT64_MAX;
3537 /* check MOV header */
3539 if (mov->moov_retry)
3540 avio_seek(pb, 0, SEEK_SET);
3541 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3542 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3546 } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
3547 if (!mov->found_moov) {
3548 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3550 return AVERROR_INVALIDDATA;
3552 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3555 if (mov->chapter_track > 0)
3556 mov_read_chapters(s);
3557 for (i = 0; i < s->nb_streams; i++)
3558 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3559 mov_read_timecode_track(s, s->streams[i]);
3562 /* copy timecode metadata from tmcd tracks to the related video streams */
3563 for (i = 0; i < s->nb_streams; i++) {
3564 AVStream *st = s->streams[i];
3565 MOVStreamContext *sc = st->priv_data;
3566 if (sc->timecode_track > 0) {
3567 AVDictionaryEntry *tcr;
3568 int tmcd_st_id = -1;
3570 for (j = 0; j < s->nb_streams; j++)
3571 if (s->streams[j]->id == sc->timecode_track)
3574 if (tmcd_st_id < 0 || tmcd_st_id == i)
3576 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
3578 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
3581 export_orphan_timecode(s);
3583 for (i = 0; i < s->nb_streams; i++) {
3584 AVStream *st = s->streams[i];
3585 MOVStreamContext *sc = st->priv_data;
3586 fix_timescale(mov, sc);
3587 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
3588 st->skip_samples = sc->start_pad;
3590 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
3591 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3592 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
3593 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3594 if (st->codec->width <= 0 && st->codec->height <= 0) {
3595 st->codec->width = sc->width;
3596 st->codec->height = sc->height;
3598 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3599 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3605 if (mov->trex_data) {
3606 for (i = 0; i < s->nb_streams; i++) {
3607 AVStream *st = s->streams[i];
3608 MOVStreamContext *sc = st->priv_data;
3609 if (st->duration > 0)
3610 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3614 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
3615 if (mov->bitrates[i]) {
3616 s->streams[i]->codec->bit_rate = mov->bitrates[i];
3620 ff_rfps_calculate(s);
3622 for (i = 0; i < s->nb_streams; i++) {
3623 AVStream *st = s->streams[i];
3624 MOVStreamContext *sc = st->priv_data;
3626 switch (st->codec->codec_type) {
3627 case AVMEDIA_TYPE_AUDIO:
3628 err = ff_replaygain_export(st, s->metadata);
3634 case AVMEDIA_TYPE_VIDEO:
3635 if (sc->display_matrix) {
3636 AVPacketSideData *sd, *tmp;
3638 tmp = av_realloc_array(st->side_data,
3639 st->nb_side_data + 1, sizeof(*tmp));
3641 return AVERROR(ENOMEM);
3643 st->side_data = tmp;
3646 sd = &st->side_data[st->nb_side_data - 1];
3647 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
3648 sd->size = sizeof(int32_t) * 9;
3649 sd->data = (uint8_t*)sc->display_matrix;
3650 sc->display_matrix = NULL;
3659 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3661 AVIndexEntry *sample = NULL;
3662 int64_t best_dts = INT64_MAX;
3664 for (i = 0; i < s->nb_streams; i++) {
3665 AVStream *avst = s->streams[i];
3666 MOVStreamContext *msc = avst->priv_data;
3667 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3668 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3669 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3670 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3671 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3673 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3674 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3675 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3676 sample = current_sample;
3685 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3687 MOVContext *mov = s->priv_data;
3688 MOVStreamContext *sc;
3689 AVIndexEntry *sample;
3690 AVStream *st = NULL;
3694 sample = mov_find_next_sample(s, &st);
3696 mov->found_mdat = 0;
3697 if (!mov->next_root_atom)
3699 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3700 mov->next_root_atom = 0;
3701 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3704 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3708 /* must be done just before reading, to avoid infinite loop on sample */
3709 sc->current_sample++;
3711 if (mov->next_root_atom) {
3712 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
3713 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
3716 if (st->discard != AVDISCARD_ALL) {
3717 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3718 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3719 sc->ffindex, sample->pos);
3720 return AVERROR_INVALIDDATA;
3722 ret = av_get_packet(sc->pb, pkt, sample->size);
3725 if (sc->has_palette) {
3728 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3730 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3732 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3733 sc->has_palette = 0;
3736 #if CONFIG_DV_DEMUXER
3737 if (mov->dv_demux && sc->dv_audio_container) {
3738 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
3741 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3748 pkt->stream_index = sc->ffindex;
3749 pkt->dts = sample->timestamp;
3750 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3751 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3752 /* update ctts context */
3754 if (sc->ctts_index < sc->ctts_count &&
3755 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3757 sc->ctts_sample = 0;
3760 pkt->dts = AV_NOPTS_VALUE;
3762 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3763 st->index_entries[sc->current_sample].timestamp : st->duration;
3764 pkt->duration = next_dts - pkt->dts;
3765 pkt->pts = pkt->dts;
3767 if (st->discard == AVDISCARD_ALL)
3769 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3770 pkt->pos = sample->pos;
3771 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3772 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3776 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3778 MOVStreamContext *sc = st->priv_data;
3779 int sample, time_sample;
3782 sample = av_index_search_timestamp(st, timestamp, flags);
3783 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3784 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3786 if (sample < 0) /* not sure what to do */
3787 return AVERROR_INVALIDDATA;
3788 sc->current_sample = sample;
3789 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3790 /* adjust ctts index */
3791 if (sc->ctts_data) {
3793 for (i = 0; i < sc->ctts_count; i++) {
3794 int next = time_sample + sc->ctts_data[i].count;
3795 if (next > sc->current_sample) {
3797 sc->ctts_sample = sc->current_sample - time_sample;
3806 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3809 int64_t seek_timestamp, timestamp;
3813 if (stream_index >= s->nb_streams)
3814 return AVERROR_INVALIDDATA;
3816 st = s->streams[stream_index];
3817 sample = mov_seek_stream(s, st, sample_time, flags);
3821 /* adjust seek timestamp to found sample timestamp */
3822 seek_timestamp = st->index_entries[sample].timestamp;
3824 for (i = 0; i < s->nb_streams; i++) {
3825 MOVStreamContext *sc = s->streams[i]->priv_data;
3827 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
3829 if (stream_index == i)
3832 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3833 mov_seek_stream(s, st, timestamp, flags);
3838 static const AVOption options[] = {
3839 {"use_absolute_path",
3840 "allow using absolute path when opening alias, this is a possible security issue",
3841 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
3842 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3843 {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
3844 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3848 static const AVClass mov_class = {
3849 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3850 .item_name = av_default_item_name,
3852 .version = LIBAVUTIL_VERSION_INT,
3855 AVInputFormat ff_mov_demuxer = {
3856 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3857 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3858 .priv_data_size = sizeof(MOVContext),
3859 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
3860 .read_probe = mov_probe,
3861 .read_header = mov_read_header,
3862 .read_packet = mov_read_packet,
3863 .read_close = mov_read_close,
3864 .read_seek = mov_read_seek,
3865 .priv_class = &mov_class,
3866 .flags = AVFMT_NO_BYTE_SEEK,