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 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
87 av_dict_set(&c->fc->metadata, key, buf, 0);
92 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
93 unsigned len, const char *key)
97 /* bypass padding bytes */
102 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
103 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
104 av_dict_set(&c->fc->metadata, key, buf, 0);
109 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
110 unsigned len, const char *key)
114 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
115 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
116 av_dict_set(&c->fc->metadata, key, buf, 0);
121 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
122 unsigned len, const char *key)
126 avio_r8(pb); // unknown
129 if (genre < 1 || genre > ID3v1_GENRE_MAX)
131 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
132 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
137 static const uint32_t mac_to_unicode[128] = {
138 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
139 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
140 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
141 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
142 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
143 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
144 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
145 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
146 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
147 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
148 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
149 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
150 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
151 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
152 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
153 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
156 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
157 char *dst, int dstlen)
160 char *end = dst+dstlen-1;
163 for (i = 0; i < len; i++) {
164 uint8_t t, c = avio_r8(pb);
165 if (c < 0x80 && p < end)
168 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
174 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
178 MOVStreamContext *sc;
183 case 0xd: id = AV_CODEC_ID_MJPEG; break;
184 case 0xe: id = AV_CODEC_ID_PNG; break;
185 case 0x1b: id = AV_CODEC_ID_BMP; break;
187 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
192 st = avformat_new_stream(c->fc, NULL);
194 return AVERROR(ENOMEM);
195 sc = av_mallocz(sizeof(*sc));
197 return AVERROR(ENOMEM);
200 ret = av_get_packet(pb, &pkt, len);
204 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
206 st->attached_pic = pkt;
207 st->attached_pic.stream_index = st->index;
208 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
210 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
211 st->codec->codec_id = id;
216 static int mov_metadata_raw(MOVContext *c, AVIOContext *pb,
217 unsigned len, const char *key)
219 char *value = av_malloc(len + 1);
221 return AVERROR(ENOMEM);
222 avio_read(pb, value, len);
224 return av_dict_set(&c->fc->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);
227 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
229 char language[4] = { 0 };
231 uint16_t langcode = 0;
232 double longitude, latitude;
233 const char *key = "location";
235 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4)
236 return AVERROR_INVALIDDATA;
238 avio_skip(pb, 4); // version+flags
239 langcode = avio_rb16(pb);
240 ff_mov_lang_to_iso639(langcode, language);
243 len -= avio_get_str(pb, len, buf, sizeof(buf)); // place name
245 return AVERROR_INVALIDDATA;
246 avio_skip(pb, 1); // role
250 return AVERROR_INVALIDDATA;
251 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
252 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
254 // Try to output in the same format as the ?xyz field
255 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f/", latitude, longitude);
256 if (*language && strcmp(language, "und")) {
258 snprintf(key2, sizeof(key2), "%s-%s", key, language);
259 av_dict_set(&c->fc->metadata, key2, buf, 0);
261 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
262 return av_dict_set(&c->fc->metadata, key, buf, 0);
265 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
267 #ifdef MOV_EXPORT_ALL_METADATA
270 char str[1024], key2[16], language[4] = {0};
271 const char *key = NULL;
272 uint16_t langcode = 0;
273 uint32_t data_type = 0, str_size;
274 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
277 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
278 case MKTAG(0xa9,'a','u','t'):
279 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
280 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
281 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
282 case MKTAG( 'c','p','i','l'): key = "compilation";
283 parse = mov_metadata_int8_no_padding; break;
284 case MKTAG( 'c','p','r','t'):
285 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
286 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
287 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
288 case MKTAG(0xa9,'c','m','t'):
289 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
290 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
291 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
292 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
293 case MKTAG( 'g','n','r','e'): key = "genre";
294 parse = mov_metadata_gnre; break;
295 case MKTAG(0xa9,'t','o','o'):
296 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
297 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
298 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
299 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
300 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
301 case MKTAG( 'd','e','s','c'): key = "description";break;
302 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
303 case MKTAG( 't','v','s','h'): key = "show"; break;
304 case MKTAG( 't','v','e','n'): key = "episode_id";break;
305 case MKTAG( 't','v','n','n'): key = "network"; break;
306 case MKTAG( 't','r','k','n'): key = "track";
307 parse = mov_metadata_track_or_disc_number; break;
308 case MKTAG( 'd','i','s','k'): key = "disc";
309 parse = mov_metadata_track_or_disc_number; break;
310 case MKTAG( 't','v','e','s'): key = "episode_sort";
311 parse = mov_metadata_int8_bypass_padding; break;
312 case MKTAG( 't','v','s','n'): key = "season_number";
313 parse = mov_metadata_int8_bypass_padding; break;
314 case MKTAG( 's','t','i','k'): key = "media_type";
315 parse = mov_metadata_int8_no_padding; break;
316 case MKTAG( 'h','d','v','d'): key = "hd_video";
317 parse = mov_metadata_int8_no_padding; break;
318 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
319 parse = mov_metadata_int8_no_padding; break;
320 case MKTAG( '@','P','R','M'):
321 return mov_metadata_raw(c, pb, atom.size, "premiere_version");
322 case MKTAG( '@','P','R','Q'):
323 return mov_metadata_raw(c, pb, atom.size, "quicktime_version");
324 case MKTAG( 'l','o','c','i'):
325 return mov_metadata_loci(c, pb, atom.size);
326 case MKTAG( 'X','M','P','_'):
327 return mov_metadata_raw(c, pb, atom.size, "xmp");
330 if (c->itunes_metadata && atom.size > 8) {
331 int data_size = avio_rb32(pb);
332 int tag = avio_rl32(pb);
333 if (tag == MKTAG('d','a','t','a')) {
334 data_type = avio_rb32(pb); // type
335 avio_rb32(pb); // unknown
336 str_size = data_size - 16;
339 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
340 int ret = mov_read_covr(c, pb, data_type, str_size);
342 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
347 } else if (atom.size > 4 && key && !c->itunes_metadata) {
348 str_size = avio_rb16(pb); // string length
349 langcode = avio_rb16(pb);
350 ff_mov_lang_to_iso639(langcode, language);
353 str_size = atom.size;
355 #ifdef MOV_EXPORT_ALL_METADATA
357 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
365 return AVERROR_INVALIDDATA;
367 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
370 parse(c, pb, str_size, key);
372 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
373 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
375 int ret = avio_read(pb, str, str_size);
377 return ret < 0 ? ret : AVERROR_INVALIDDATA;
380 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
381 av_dict_set(&c->fc->metadata, key, str, 0);
382 if (*language && strcmp(language, "und")) {
383 snprintf(key2, sizeof(key2), "%s-%s", key, language);
384 av_dict_set(&c->fc->metadata, key2, str, 0);
387 av_dlog(c->fc, "lang \"%3s\" ", language);
388 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
389 key, str, (char*)&atom.type, str_size, atom.size);
394 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
397 int i, nb_chapters, str_len, version;
400 if ((atom.size -= 5) < 0)
403 version = avio_r8(pb);
406 avio_rb32(pb); // ???
407 nb_chapters = avio_r8(pb);
409 for (i = 0; i < nb_chapters; i++) {
413 start = avio_rb64(pb);
414 str_len = avio_r8(pb);
416 if ((atom.size -= 9+str_len) < 0)
419 avio_read(pb, str, str_len);
421 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
426 #define MIN_DATA_ENTRY_BOX_SIZE 12
427 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
430 MOVStreamContext *sc;
433 if (c->fc->nb_streams < 1)
435 st = c->fc->streams[c->fc->nb_streams-1];
438 avio_rb32(pb); // version + flags
439 entries = avio_rb32(pb);
440 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
441 entries >= UINT_MAX / sizeof(*sc->drefs))
442 return AVERROR_INVALIDDATA;
445 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
447 return AVERROR(ENOMEM);
448 sc->drefs_count = entries;
450 for (i = 0; i < sc->drefs_count; i++) {
451 MOVDref *dref = &sc->drefs[i];
452 uint32_t size = avio_rb32(pb);
453 int64_t next = avio_tell(pb) + size - 4;
456 return AVERROR_INVALIDDATA;
458 dref->type = avio_rl32(pb);
459 avio_rb32(pb); // version + flags
460 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
462 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
463 /* macintosh alias record */
464 uint16_t volume_len, len;
469 volume_len = avio_r8(pb);
470 volume_len = FFMIN(volume_len, 27);
471 avio_read(pb, dref->volume, 27);
472 dref->volume[volume_len] = 0;
473 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
478 len = FFMIN(len, 63);
479 avio_read(pb, dref->filename, 63);
480 dref->filename[len] = 0;
481 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
485 /* read next level up_from_alias/down_to_target */
486 dref->nlvl_from = avio_rb16(pb);
487 dref->nlvl_to = avio_rb16(pb);
488 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
489 dref->nlvl_from, dref->nlvl_to);
493 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
496 type = avio_rb16(pb);
498 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
501 if (type == 2) { // absolute path
503 dref->path = av_mallocz(len+1);
505 return AVERROR(ENOMEM);
506 avio_read(pb, dref->path, len);
507 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
509 memmove(dref->path, dref->path+volume_len, len);
512 for (j = 0; j < len; j++)
513 if (dref->path[j] == ':')
515 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
516 } else if (type == 0) { // directory name
518 dref->dir = av_malloc(len+1);
520 return AVERROR(ENOMEM);
521 if (avio_read(pb, dref->dir, len) != len)
522 return AVERROR_INVALIDDATA;
524 for (j = 0; j < len; j++)
525 if (dref->dir[j] == ':')
527 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
532 avio_seek(pb, next, SEEK_SET);
537 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
541 uint32_t av_unused ctype;
545 if (c->fc->nb_streams < 1) // meta before first trak
548 st = c->fc->streams[c->fc->nb_streams-1];
550 avio_r8(pb); /* version */
551 avio_rb24(pb); /* flags */
554 ctype = avio_rl32(pb);
555 type = avio_rl32(pb); /* component subtype */
557 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
558 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
560 if (type == MKTAG('v','i','d','e'))
561 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
562 else if (type == MKTAG('s','o','u','n'))
563 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
564 else if (type == MKTAG('m','1','a',' '))
565 st->codec->codec_id = AV_CODEC_ID_MP2;
566 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
567 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
569 avio_rb32(pb); /* component manufacture */
570 avio_rb32(pb); /* component flags */
571 avio_rb32(pb); /* component flags mask */
573 title_size = atom.size - 24;
574 if (title_size > 0) {
575 title_str = av_malloc(title_size + 1); /* Add null terminator */
577 return AVERROR(ENOMEM);
578 avio_read(pb, title_str, title_size);
579 title_str[title_size] = 0;
581 av_dict_set(&st->metadata, "handler_name", title_str +
582 (!c->isom && title_str[0] == title_size - 1), 0);
583 av_freep(&title_str);
589 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
594 if (fc->nb_streams < 1)
596 st = fc->streams[fc->nb_streams-1];
598 avio_rb32(pb); /* version + flags */
599 ff_mp4_read_descr(fc, pb, &tag);
600 if (tag == MP4ESDescrTag) {
601 ff_mp4_parse_es_descr(pb, NULL);
603 avio_rb16(pb); /* ID */
605 ff_mp4_read_descr(fc, pb, &tag);
606 if (tag == MP4DecConfigDescrTag)
607 ff_mp4_read_dec_config_descr(fc, st, pb);
611 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
613 return ff_mov_read_esds(c->fc, pb, atom);
616 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
619 int ac3info, acmod, lfeon, bsmod;
621 if (c->fc->nb_streams < 1)
623 st = c->fc->streams[c->fc->nb_streams-1];
625 ac3info = avio_rb24(pb);
626 bsmod = (ac3info >> 14) & 0x7;
627 acmod = (ac3info >> 11) & 0x7;
628 lfeon = (ac3info >> 10) & 0x1;
629 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
630 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
632 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
633 st->codec->audio_service_type = bsmod;
634 if (st->codec->channels > 1 && bsmod == 0x7)
635 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
640 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
643 int eac3info, acmod, lfeon, bsmod;
645 if (c->fc->nb_streams < 1)
647 st = c->fc->streams[c->fc->nb_streams-1];
649 /* No need to parse fields for additional independent substreams and its
650 * associated dependent substreams since libavcodec's E-AC-3 decoder
651 * does not support them yet. */
652 avio_rb16(pb); /* data_rate and num_ind_sub */
653 eac3info = avio_rb24(pb);
654 bsmod = (eac3info >> 12) & 0x1f;
655 acmod = (eac3info >> 9) & 0x7;
656 lfeon = (eac3info >> 8) & 0x1;
657 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
659 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
660 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
661 st->codec->audio_service_type = bsmod;
662 if (st->codec->channels > 1 && bsmod == 0x7)
663 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
668 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
672 if (c->fc->nb_streams < 1)
674 st = c->fc->streams[c->fc->nb_streams-1];
679 /* skip version and flags */
682 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
687 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
691 if (c->fc->nb_streams < 1)
693 st = c->fc->streams[c->fc->nb_streams-1];
695 if (ff_get_wav_header(pb, st->codec, atom.size) < 0) {
696 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
702 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
704 const int num = avio_rb32(pb);
705 const int den = avio_rb32(pb);
708 if (c->fc->nb_streams < 1)
710 st = c->fc->streams[c->fc->nb_streams-1];
712 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
713 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
714 av_log(c->fc, AV_LOG_WARNING,
715 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
716 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
718 } else if (den != 0) {
719 st->sample_aspect_ratio.num = num;
720 st->sample_aspect_ratio.den = den;
725 /* this atom contains actual media data */
726 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
728 if (atom.size == 0) /* wrong one (MP4) */
731 return 0; /* now go for moov */
734 /* read major brand, minor version and compatible brands and store them as metadata */
735 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
739 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
740 char* comp_brands_str;
741 uint8_t type[5] = {0};
743 avio_read(pb, type, 4);
744 if (strcmp(type, "qt "))
746 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
747 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
748 minor_ver = avio_rb32(pb); /* minor version */
749 snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);
750 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
752 comp_brand_size = atom.size - 8;
753 if (comp_brand_size < 0)
754 return AVERROR_INVALIDDATA;
755 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
756 if (!comp_brands_str)
757 return AVERROR(ENOMEM);
758 avio_read(pb, comp_brands_str, comp_brand_size);
759 comp_brands_str[comp_brand_size] = 0;
760 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
761 av_freep(&comp_brands_str);
766 /* this atom should contain all header atoms */
767 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
772 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
773 avio_skip(pb, atom.size);
777 if ((ret = mov_read_default(c, pb, atom)) < 0)
779 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
780 /* so we don't parse the whole file if over a network */
782 return 0; /* now go for mdat */
785 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
787 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
788 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
789 return mov_read_default(c, pb, atom);
792 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
798 if(time >= 2082844800)
799 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
801 ptm = gmtime(&timet);
803 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
804 av_dict_set(metadata, "creation_time", buffer, 0);
808 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
811 MOVStreamContext *sc;
813 char language[4] = {0};
815 int64_t creation_time;
817 if (c->fc->nb_streams < 1)
819 st = c->fc->streams[c->fc->nb_streams-1];
822 if (sc->time_scale) {
823 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
824 return AVERROR_INVALIDDATA;
827 version = avio_r8(pb);
829 avpriv_request_sample(c->fc, "Version %d", version);
830 return AVERROR_PATCHWELCOME;
832 avio_rb24(pb); /* flags */
834 creation_time = avio_rb64(pb);
837 creation_time = avio_rb32(pb);
838 avio_rb32(pb); /* modification time */
840 mov_metadata_creation_time(&st->metadata, creation_time);
842 sc->time_scale = avio_rb32(pb);
843 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
845 lang = avio_rb16(pb); /* language */
846 if (ff_mov_lang_to_iso639(lang, language))
847 av_dict_set(&st->metadata, "language", language, 0);
848 avio_rb16(pb); /* quality */
853 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
855 int64_t creation_time;
856 int version = avio_r8(pb); /* version */
857 avio_rb24(pb); /* flags */
860 creation_time = avio_rb64(pb);
863 creation_time = avio_rb32(pb);
864 avio_rb32(pb); /* modification time */
866 mov_metadata_creation_time(&c->fc->metadata, creation_time);
867 c->time_scale = avio_rb32(pb); /* time scale */
869 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
871 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
872 // set the AVCodecContext duration because the duration of individual tracks
874 if (c->time_scale > 0 && !c->trex_data)
875 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
876 avio_rb32(pb); /* preferred scale */
878 avio_rb16(pb); /* preferred volume */
880 avio_skip(pb, 10); /* reserved */
882 avio_skip(pb, 36); /* display matrix */
884 avio_rb32(pb); /* preview time */
885 avio_rb32(pb); /* preview duration */
886 avio_rb32(pb); /* poster time */
887 avio_rb32(pb); /* selection time */
888 avio_rb32(pb); /* selection duration */
889 avio_rb32(pb); /* current time */
890 avio_rb32(pb); /* next track ID */
894 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
899 if (c->fc->nb_streams < 1)
901 st = c->fc->streams[c->fc->nb_streams-1];
903 little_endian = avio_rb16(pb) & 0xFF;
904 av_dlog(c->fc, "enda %d\n", little_endian);
905 if (little_endian == 1) {
906 switch (st->codec->codec_id) {
907 case AV_CODEC_ID_PCM_S24BE:
908 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
910 case AV_CODEC_ID_PCM_S32BE:
911 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
913 case AV_CODEC_ID_PCM_F32BE:
914 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
916 case AV_CODEC_ID_PCM_F64BE:
917 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
926 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
929 unsigned mov_field_order;
930 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
932 if (c->fc->nb_streams < 1) // will happen with jp2 files
934 st = c->fc->streams[c->fc->nb_streams-1];
936 return AVERROR_INVALIDDATA;
937 mov_field_order = avio_rb16(pb);
938 if ((mov_field_order & 0xFF00) == 0x0100)
939 decoded_field_order = AV_FIELD_PROGRESSIVE;
940 else if ((mov_field_order & 0xFF00) == 0x0200) {
941 switch (mov_field_order & 0xFF) {
942 case 0x01: decoded_field_order = AV_FIELD_TT;
944 case 0x06: decoded_field_order = AV_FIELD_BB;
946 case 0x09: decoded_field_order = AV_FIELD_TB;
948 case 0x0E: decoded_field_order = AV_FIELD_BT;
952 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
953 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
955 st->codec->field_order = decoded_field_order;
960 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
961 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
962 enum AVCodecID codec_id)
969 if (c->fc->nb_streams < 1) // will happen with jp2 files
971 st= c->fc->streams[c->fc->nb_streams-1];
973 if (st->codec->codec_id != codec_id)
974 return 0; /* unexpected codec_id - don't mess with extradata */
976 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
977 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
978 return AVERROR_INVALIDDATA;
979 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
980 st->codec->extradata_size = 0;
983 buf = st->codec->extradata + st->codec->extradata_size;
984 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
985 AV_WB32( buf , atom.size + 8);
986 AV_WL32( buf + 4, atom.type);
987 err = avio_read(pb, buf + 8, atom.size);
990 } else if (err < atom.size) {
991 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
992 st->codec->extradata_size -= atom.size - err;
994 memset(buf + 8 + err, 0, FF_INPUT_BUFFER_PADDING_SIZE);
998 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
999 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1001 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1004 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1006 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1009 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1011 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1014 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1016 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1018 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1022 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1024 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1026 if (!ret && c->fc->nb_streams >= 1) {
1027 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
1028 if (avctx->extradata_size >= 40) {
1029 avctx->height = AV_RB16(&avctx->extradata[36]);
1030 avctx->width = AV_RB16(&avctx->extradata[38]);
1036 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1038 if (c->fc->nb_streams >= 1) {
1039 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1040 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1041 codec->codec_id == AV_CODEC_ID_H264 &&
1044 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1045 if (avio_rb16(pb) == 0xd4d)
1046 codec->width = 1440;
1051 return mov_read_avid(c, pb, atom);
1054 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1056 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1059 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1063 if (c->fc->nb_streams < 1)
1065 st = c->fc->streams[c->fc->nb_streams-1];
1067 if ((uint64_t)atom.size > (1<<30))
1068 return AVERROR_INVALIDDATA;
1070 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1071 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1072 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1073 // pass all frma atom to codec, needed at least for QDMC and QDM2
1074 av_free(st->codec->extradata);
1075 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1076 return AVERROR(ENOMEM);
1077 } else if (atom.size > 8) { /* to read frma, esds atoms */
1079 if ((ret = mov_read_default(c, pb, atom)) < 0)
1082 avio_skip(pb, atom.size);
1087 * This function reads atom content and puts data in extradata without tag
1088 * nor size unlike mov_read_extradata.
1090 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1094 if (c->fc->nb_streams < 1)
1096 st = c->fc->streams[c->fc->nb_streams-1];
1098 if ((uint64_t)atom.size > (1<<30))
1099 return AVERROR_INVALIDDATA;
1101 if (atom.size >= 10) {
1102 // Broken files created by legacy versions of libavformat will
1103 // wrap a whole fiel atom inside of a glbl atom.
1104 unsigned size = avio_rb32(pb);
1105 unsigned type = avio_rl32(pb);
1106 avio_seek(pb, -8, SEEK_CUR);
1107 if (type == MKTAG('f','i','e','l') && size == atom.size)
1108 return mov_read_default(c, pb, atom);
1110 av_free(st->codec->extradata);
1111 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1112 return AVERROR(ENOMEM);
1117 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1120 uint8_t profile_level;
1123 if (c->fc->nb_streams < 1)
1125 st = c->fc->streams[c->fc->nb_streams-1];
1127 if (atom.size >= (1<<28) || atom.size < 7)
1128 return AVERROR_INVALIDDATA;
1130 profile_level = avio_r8(pb);
1131 if ((profile_level & 0xf0) != 0xc0)
1134 avio_seek(pb, 6, SEEK_CUR);
1135 av_free(st->codec->extradata);
1136 if ((ret = ff_get_extradata(st->codec, pb, atom.size - 7)) < 0)
1143 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1144 * but can have extradata appended at the end after the 40 bytes belonging
1147 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1151 if (c->fc->nb_streams < 1)
1153 if (atom.size <= 40)
1155 st = c->fc->streams[c->fc->nb_streams-1];
1157 if ((uint64_t)atom.size > (1<<30))
1158 return AVERROR_INVALIDDATA;
1161 av_free(st->codec->extradata);
1162 if (ff_get_extradata(st->codec, pb, atom.size - 40) < 0)
1163 return AVERROR(ENOMEM);
1167 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1170 MOVStreamContext *sc;
1171 unsigned int i, entries;
1173 if (c->fc->nb_streams < 1)
1175 st = c->fc->streams[c->fc->nb_streams-1];
1178 avio_r8(pb); /* version */
1179 avio_rb24(pb); /* flags */
1181 entries = avio_rb32(pb);
1185 if (entries >= UINT_MAX/sizeof(int64_t))
1186 return AVERROR_INVALIDDATA;
1188 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1189 if (!sc->chunk_offsets)
1190 return AVERROR(ENOMEM);
1191 sc->chunk_count = entries;
1193 if (atom.type == MKTAG('s','t','c','o'))
1194 for (i = 0; i < entries && !pb->eof_reached; i++)
1195 sc->chunk_offsets[i] = avio_rb32(pb);
1196 else if (atom.type == MKTAG('c','o','6','4'))
1197 for (i = 0; i < entries && !pb->eof_reached; i++)
1198 sc->chunk_offsets[i] = avio_rb64(pb);
1200 return AVERROR_INVALIDDATA;
1202 sc->chunk_count = i;
1204 if (pb->eof_reached)
1211 * Compute codec id for 'lpcm' tag.
1212 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1214 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1221 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1224 static int mov_codec_id(AVStream *st, uint32_t format)
1226 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1229 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1230 (format & 0xFFFF) == 'T' + ('S' << 8)))
1231 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1233 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1234 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1235 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1236 /* skip old asf mpeg4 tag */
1237 format && format != MKTAG('m','p','4','s')) {
1238 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1240 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1242 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1243 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1244 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1245 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1246 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1248 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1252 st->codec->codec_tag = format;
1257 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1258 AVStream *st, MOVStreamContext *sc)
1260 uint8_t codec_name[32];
1261 unsigned int color_depth, len, j;
1262 int color_greyscale;
1265 avio_rb16(pb); /* version */
1266 avio_rb16(pb); /* revision level */
1267 avio_rb32(pb); /* vendor */
1268 avio_rb32(pb); /* temporal quality */
1269 avio_rb32(pb); /* spatial quality */
1271 st->codec->width = avio_rb16(pb); /* width */
1272 st->codec->height = avio_rb16(pb); /* height */
1274 avio_rb32(pb); /* horiz resolution */
1275 avio_rb32(pb); /* vert resolution */
1276 avio_rb32(pb); /* data size, always 0 */
1277 avio_rb16(pb); /* frames per samples */
1279 len = avio_r8(pb); /* codec name, pascal string */
1282 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1284 avio_skip(pb, 31 - len);
1287 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1289 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1290 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1291 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1292 st->codec->width &= ~1;
1293 st->codec->height &= ~1;
1295 /* Flash Media Server uses tag H263 with Sorenson Spark */
1296 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1297 !memcmp(codec_name, "Sorenson H263", 13))
1298 st->codec->codec_id = AV_CODEC_ID_FLV1;
1300 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1301 color_table_id = avio_rb16(pb); /* colortable id */
1302 av_dlog(c->fc, "depth %d, ctab id %d\n",
1303 st->codec->bits_per_coded_sample, color_table_id);
1304 /* figure out the palette situation */
1305 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1306 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1307 /* Do not create a greyscale palette for cinepak */
1308 if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1311 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1312 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1313 /* for palette traversal */
1314 unsigned int color_start, color_count, color_end;
1315 unsigned char a, r, g, b;
1317 if (color_greyscale) {
1318 int color_index, color_dec;
1319 /* compute the greyscale palette */
1320 st->codec->bits_per_coded_sample = color_depth;
1321 color_count = 1 << color_depth;
1323 color_dec = 256 / (color_count - 1);
1324 for (j = 0; j < color_count; j++) {
1325 r = g = b = color_index;
1326 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1327 color_index -= color_dec;
1328 if (color_index < 0)
1331 } else if (color_table_id) {
1332 const uint8_t *color_table;
1333 /* if flag bit 3 is set, use the default palette */
1334 color_count = 1 << color_depth;
1335 if (color_depth == 2)
1336 color_table = ff_qt_default_palette_4;
1337 else if (color_depth == 4)
1338 color_table = ff_qt_default_palette_16;
1340 color_table = ff_qt_default_palette_256;
1342 for (j = 0; j < color_count; j++) {
1343 r = color_table[j * 3 + 0];
1344 g = color_table[j * 3 + 1];
1345 b = color_table[j * 3 + 2];
1346 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1349 /* load the palette from the file */
1350 color_start = avio_rb32(pb);
1351 color_count = avio_rb16(pb);
1352 color_end = avio_rb16(pb);
1353 if ((color_start <= 255) && (color_end <= 255)) {
1354 for (j = color_start; j <= color_end; j++) {
1355 /* each A, R, G, or B component is 16 bits;
1356 * only use the top 8 bits */
1365 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1369 sc->has_palette = 1;
1373 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1374 AVStream *st, MOVStreamContext *sc)
1376 int bits_per_sample, flags;
1377 uint16_t version = avio_rb16(pb);
1378 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1380 avio_rb16(pb); /* revision level */
1381 avio_rb32(pb); /* vendor */
1383 st->codec->channels = avio_rb16(pb); /* channel count */
1384 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1385 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1387 sc->audio_cid = avio_rb16(pb);
1388 avio_rb16(pb); /* packet size = 0 */
1390 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1392 // Read QT version 1 fields. In version 0 these do not exist.
1393 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1395 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1398 sc->samples_per_frame = avio_rb32(pb);
1399 avio_rb32(pb); /* bytes per packet */
1400 sc->bytes_per_frame = avio_rb32(pb);
1401 avio_rb32(pb); /* bytes per sample */
1402 } else if (version == 2) {
1403 avio_rb32(pb); /* sizeof struct only */
1404 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1405 st->codec->channels = avio_rb32(pb);
1406 avio_rb32(pb); /* always 0x7F000000 */
1407 st->codec->bits_per_coded_sample = avio_rb32(pb);
1409 flags = avio_rb32(pb); /* lpcm format specific flag */
1410 sc->bytes_per_frame = avio_rb32(pb);
1411 sc->samples_per_frame = avio_rb32(pb);
1412 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1413 st->codec->codec_id =
1414 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1419 switch (st->codec->codec_id) {
1420 case AV_CODEC_ID_PCM_S8:
1421 case AV_CODEC_ID_PCM_U8:
1422 if (st->codec->bits_per_coded_sample == 16)
1423 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1425 case AV_CODEC_ID_PCM_S16LE:
1426 case AV_CODEC_ID_PCM_S16BE:
1427 if (st->codec->bits_per_coded_sample == 8)
1428 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1429 else if (st->codec->bits_per_coded_sample == 24)
1430 st->codec->codec_id =
1431 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1432 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1434 /* set values for old format before stsd version 1 appeared */
1435 case AV_CODEC_ID_MACE3:
1436 sc->samples_per_frame = 6;
1437 sc->bytes_per_frame = 2 * st->codec->channels;
1439 case AV_CODEC_ID_MACE6:
1440 sc->samples_per_frame = 6;
1441 sc->bytes_per_frame = 1 * st->codec->channels;
1443 case AV_CODEC_ID_ADPCM_IMA_QT:
1444 sc->samples_per_frame = 64;
1445 sc->bytes_per_frame = 34 * st->codec->channels;
1447 case AV_CODEC_ID_GSM:
1448 sc->samples_per_frame = 160;
1449 sc->bytes_per_frame = 33;
1455 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1456 if (bits_per_sample) {
1457 st->codec->bits_per_coded_sample = bits_per_sample;
1458 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1462 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1463 AVStream *st, MOVStreamContext *sc,
1466 // ttxt stsd contains display flags, justification, background
1467 // color, fonts, and default styles, so fake an atom to read it
1468 MOVAtom fake_atom = { .size = size };
1469 // mp4s contains a regular esds atom
1470 if (st->codec->codec_tag != AV_RL32("mp4s"))
1471 mov_read_glbl(c, pb, fake_atom);
1472 st->codec->width = sc->width;
1473 st->codec->height = sc->height;
1476 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1481 y = (ycbcr >> 16) & 0xFF;
1482 cr = (ycbcr >> 8) & 0xFF;
1485 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1486 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1487 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1489 return (r << 16) | (g << 8) | b;
1492 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1494 char buf[256] = {0};
1495 uint8_t *src = st->codec->extradata;
1498 if (st->codec->extradata_size != 64)
1501 if (st->codec->width > 0 && st->codec->height > 0)
1502 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1503 st->codec->width, st->codec->height);
1504 av_strlcat(buf, "palette: ", sizeof(buf));
1506 for (i = 0; i < 16; i++) {
1507 uint32_t yuv = AV_RB32(src + i * 4);
1508 uint32_t rgba = yuv_to_rgba(yuv);
1510 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1513 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1516 av_freep(&st->codec->extradata);
1517 st->codec->extradata_size = 0;
1518 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1519 if (!st->codec->extradata)
1520 return AVERROR(ENOMEM);
1521 st->codec->extradata_size = strlen(buf);
1522 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1527 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1528 AVStream *st, MOVStreamContext *sc,
1531 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1532 if (ff_get_extradata(st->codec, pb, size) < 0)
1533 return AVERROR(ENOMEM);
1535 MOVStreamContext *tmcd_ctx = st->priv_data;
1537 val = AV_RB32(st->codec->extradata + 4);
1538 tmcd_ctx->tmcd_flags = val;
1540 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1541 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
1542 st->codec->time_base.num = 1;
1544 uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
1545 uint32_t format = AV_RB32(st->codec->extradata + 22);
1546 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
1547 uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
1548 if (str_size > 0 && size >= (int)str_size + 26) {
1549 char *reel_name = av_malloc(str_size + 1);
1551 return AVERROR(ENOMEM);
1552 memcpy(reel_name, st->codec->extradata + 30, str_size);
1553 reel_name[str_size] = 0; /* Add null terminator */
1554 /* don't add reel_name if emtpy string */
1555 if (*reel_name == 0) {
1558 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
1565 /* other codec type, just skip (rtp, mp4s ...) */
1566 avio_skip(pb, size);
1571 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1572 AVStream *st, MOVStreamContext *sc)
1574 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1575 !st->codec->sample_rate && sc->time_scale > 1)
1576 st->codec->sample_rate = sc->time_scale;
1578 /* special codec parameters handling */
1579 switch (st->codec->codec_id) {
1580 #if CONFIG_DV_DEMUXER
1581 case AV_CODEC_ID_DVAUDIO:
1582 c->dv_fctx = avformat_alloc_context();
1583 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1585 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1586 return AVERROR(ENOMEM);
1588 sc->dv_audio_container = 1;
1589 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1592 /* no ifdef since parameters are always those */
1593 case AV_CODEC_ID_QCELP:
1594 st->codec->channels = 1;
1595 // force sample rate for qcelp when not stored in mov
1596 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1597 st->codec->sample_rate = 8000;
1598 // FIXME: Why is the following needed for some files?
1599 sc->samples_per_frame = 160;
1600 if (!sc->bytes_per_frame)
1601 sc->bytes_per_frame = 35;
1603 case AV_CODEC_ID_AMR_NB:
1604 st->codec->channels = 1;
1605 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1606 st->codec->sample_rate = 8000;
1608 case AV_CODEC_ID_AMR_WB:
1609 st->codec->channels = 1;
1610 st->codec->sample_rate = 16000;
1612 case AV_CODEC_ID_MP2:
1613 case AV_CODEC_ID_MP3:
1614 /* force type after stsd for m1a hdlr */
1615 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1616 st->need_parsing = AVSTREAM_PARSE_FULL;
1618 case AV_CODEC_ID_GSM:
1619 case AV_CODEC_ID_ADPCM_MS:
1620 case AV_CODEC_ID_ADPCM_IMA_WAV:
1621 case AV_CODEC_ID_ILBC:
1622 case AV_CODEC_ID_MACE3:
1623 case AV_CODEC_ID_MACE6:
1624 case AV_CODEC_ID_QDM2:
1625 st->codec->block_align = sc->bytes_per_frame;
1627 case AV_CODEC_ID_ALAC:
1628 if (st->codec->extradata_size == 36) {
1629 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1630 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1633 case AV_CODEC_ID_AC3:
1634 case AV_CODEC_ID_MPEG1VIDEO:
1635 case AV_CODEC_ID_VC1:
1636 st->need_parsing = AVSTREAM_PARSE_FULL;
1644 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1645 int codec_tag, int format,
1648 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1651 (codec_tag != format &&
1652 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1653 : codec_tag != MKTAG('j','p','e','g')))) {
1654 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1655 * export it as a separate AVStream but this needs a few changes
1656 * in the MOV demuxer, patch welcome. */
1658 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1659 avio_skip(pb, size);
1662 if ( codec_tag == AV_RL32("avc1") ||
1663 codec_tag == AV_RL32("hvc1") ||
1664 codec_tag == AV_RL32("hev1")
1666 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
1671 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1674 MOVStreamContext *sc;
1675 int pseudo_stream_id;
1677 if (c->fc->nb_streams < 1)
1679 st = c->fc->streams[c->fc->nb_streams-1];
1682 for (pseudo_stream_id = 0;
1683 pseudo_stream_id < entries && !pb->eof_reached;
1684 pseudo_stream_id++) {
1685 //Parsing Sample description table
1687 int ret, dref_id = 1;
1688 MOVAtom a = { AV_RL32("stsd") };
1689 int64_t start_pos = avio_tell(pb);
1690 int64_t size = avio_rb32(pb); /* size */
1691 uint32_t format = avio_rl32(pb); /* data format */
1694 avio_rb32(pb); /* reserved */
1695 avio_rb16(pb); /* reserved */
1696 dref_id = avio_rb16(pb);
1697 }else if (size <= 7){
1698 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1699 return AVERROR_INVALIDDATA;
1702 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1703 size - (avio_tell(pb) - start_pos)))
1706 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1707 sc->dref_id= dref_id;
1709 id = mov_codec_id(st, format);
1711 av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1712 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1713 (format >> 24) & 0xff, st->codec->codec_type);
1715 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1716 st->codec->codec_id = id;
1717 mov_parse_stsd_video(c, pb, st, sc);
1718 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1719 st->codec->codec_id = id;
1720 mov_parse_stsd_audio(c, pb, st, sc);
1721 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1722 st->codec->codec_id = id;
1723 mov_parse_stsd_subtitle(c, pb, st, sc,
1724 size - (avio_tell(pb) - start_pos));
1726 ret = mov_parse_stsd_data(c, pb, st, sc,
1727 size - (avio_tell(pb) - start_pos));
1731 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1732 a.size = size - (avio_tell(pb) - start_pos);
1734 if ((ret = mov_read_default(c, pb, a)) < 0)
1736 } else if (a.size > 0)
1737 avio_skip(pb, a.size);
1740 if (pb->eof_reached)
1743 return mov_finalize_stsd_codec(c, pb, st, sc);
1746 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1750 avio_r8(pb); /* version */
1751 avio_rb24(pb); /* flags */
1752 entries = avio_rb32(pb);
1754 return ff_mov_read_stsd_entries(c, pb, entries);
1757 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1760 MOVStreamContext *sc;
1761 unsigned int i, entries;
1763 if (c->fc->nb_streams < 1)
1765 st = c->fc->streams[c->fc->nb_streams-1];
1768 avio_r8(pb); /* version */
1769 avio_rb24(pb); /* flags */
1771 entries = avio_rb32(pb);
1773 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1777 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1778 return AVERROR_INVALIDDATA;
1779 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1781 return AVERROR(ENOMEM);
1783 for (i = 0; i < entries && !pb->eof_reached; i++) {
1784 sc->stsc_data[i].first = avio_rb32(pb);
1785 sc->stsc_data[i].count = avio_rb32(pb);
1786 sc->stsc_data[i].id = avio_rb32(pb);
1791 if (pb->eof_reached)
1797 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1800 MOVStreamContext *sc;
1801 unsigned i, entries;
1803 if (c->fc->nb_streams < 1)
1805 st = c->fc->streams[c->fc->nb_streams-1];
1808 avio_rb32(pb); // version + flags
1810 entries = avio_rb32(pb);
1811 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1812 return AVERROR_INVALIDDATA;
1813 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1815 return AVERROR(ENOMEM);
1817 for (i = 0; i < entries && !pb->eof_reached; i++) {
1818 sc->stps_data[i] = avio_rb32(pb);
1819 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1824 if (pb->eof_reached)
1830 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1833 MOVStreamContext *sc;
1834 unsigned int i, entries;
1836 if (c->fc->nb_streams < 1)
1838 st = c->fc->streams[c->fc->nb_streams-1];
1841 avio_r8(pb); /* version */
1842 avio_rb24(pb); /* flags */
1844 entries = avio_rb32(pb);
1846 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1850 sc->keyframe_absent = 1;
1851 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1852 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1855 if (entries >= UINT_MAX / sizeof(int))
1856 return AVERROR_INVALIDDATA;
1857 sc->keyframes = av_malloc(entries * sizeof(int));
1859 return AVERROR(ENOMEM);
1861 for (i = 0; i < entries && !pb->eof_reached; i++) {
1862 sc->keyframes[i] = avio_rb32(pb);
1863 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1866 sc->keyframe_count = i;
1868 if (pb->eof_reached)
1874 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1877 MOVStreamContext *sc;
1878 unsigned int i, entries, sample_size, field_size, num_bytes;
1882 if (c->fc->nb_streams < 1)
1884 st = c->fc->streams[c->fc->nb_streams-1];
1887 avio_r8(pb); /* version */
1888 avio_rb24(pb); /* flags */
1890 if (atom.type == MKTAG('s','t','s','z')) {
1891 sample_size = avio_rb32(pb);
1892 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1893 sc->sample_size = sample_size;
1894 sc->stsz_sample_size = sample_size;
1898 avio_rb24(pb); /* reserved */
1899 field_size = avio_r8(pb);
1901 entries = avio_rb32(pb);
1903 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1905 sc->sample_count = entries;
1909 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1910 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1911 return AVERROR_INVALIDDATA;
1916 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1917 return AVERROR_INVALIDDATA;
1918 sc->sample_sizes = av_malloc(entries * sizeof(int));
1919 if (!sc->sample_sizes)
1920 return AVERROR(ENOMEM);
1922 num_bytes = (entries*field_size+4)>>3;
1924 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1926 av_freep(&sc->sample_sizes);
1927 return AVERROR(ENOMEM);
1930 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1931 av_freep(&sc->sample_sizes);
1933 return AVERROR_INVALIDDATA;
1936 init_get_bits(&gb, buf, 8*num_bytes);
1938 for (i = 0; i < entries && !pb->eof_reached; i++) {
1939 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1940 sc->data_size += sc->sample_sizes[i];
1943 sc->sample_count = i;
1945 if (pb->eof_reached)
1952 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1955 MOVStreamContext *sc;
1956 unsigned int i, entries;
1958 int64_t total_sample_count=0;
1960 if (c->fc->nb_streams < 1)
1962 st = c->fc->streams[c->fc->nb_streams-1];
1965 avio_r8(pb); /* version */
1966 avio_rb24(pb); /* flags */
1967 entries = avio_rb32(pb);
1969 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1970 c->fc->nb_streams-1, entries);
1972 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1975 av_free(sc->stts_data);
1976 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1978 return AVERROR(ENOMEM);
1980 for (i = 0; i < entries && !pb->eof_reached; i++) {
1981 int sample_duration;
1984 sample_count=avio_rb32(pb);
1985 sample_duration = avio_rb32(pb);
1987 /* sample_duration < 0 is invalid based on the spec */
1988 if (sample_duration < 0) {
1989 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta %d in STTS, at %d st:%d\n",
1990 sample_duration, i, c->fc->nb_streams-1);
1991 sample_duration = 1;
1993 if (sample_count < 0) {
1994 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
1995 return AVERROR_INVALIDDATA;
1997 sc->stts_data[i].count= sample_count;
1998 sc->stts_data[i].duration= sample_duration;
2000 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
2001 sample_count, sample_duration);
2005 && sample_count == 1
2006 && total_sample_count > 100
2007 && sample_duration/10 > duration / total_sample_count)
2008 sample_duration = duration / total_sample_count;
2009 duration+=(int64_t)sample_duration*sample_count;
2010 total_sample_count+=sample_count;
2015 sc->duration_for_fps += duration;
2016 sc->nb_frames_for_fps += total_sample_count;
2018 if (pb->eof_reached)
2021 st->nb_frames= total_sample_count;
2023 st->duration= duration;
2024 sc->track_end = duration;
2028 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2031 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2035 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2038 MOVStreamContext *sc;
2039 unsigned int i, entries;
2041 if (c->fc->nb_streams < 1)
2043 st = c->fc->streams[c->fc->nb_streams-1];
2046 avio_r8(pb); /* version */
2047 avio_rb24(pb); /* flags */
2048 entries = avio_rb32(pb);
2050 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2054 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2055 return AVERROR_INVALIDDATA;
2056 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
2058 return AVERROR(ENOMEM);
2060 for (i = 0; i < entries && !pb->eof_reached; i++) {
2061 int count =avio_rb32(pb);
2062 int duration =avio_rb32(pb);
2064 sc->ctts_data[i].count = count;
2065 sc->ctts_data[i].duration= duration;
2067 av_dlog(c->fc, "count=%d, duration=%d\n",
2070 if (FFABS(duration) > (1<<28) && i+2<entries) {
2071 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2072 av_freep(&sc->ctts_data);
2078 mov_update_dts_shift(sc, duration);
2083 if (pb->eof_reached)
2086 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
2091 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2094 MOVStreamContext *sc;
2095 unsigned int i, entries;
2097 uint32_t grouping_type;
2099 if (c->fc->nb_streams < 1)
2101 st = c->fc->streams[c->fc->nb_streams-1];
2104 version = avio_r8(pb); /* version */
2105 avio_rb24(pb); /* flags */
2106 grouping_type = avio_rl32(pb);
2107 if (grouping_type != MKTAG( 'r','a','p',' '))
2108 return 0; /* only support 'rap ' grouping */
2110 avio_rb32(pb); /* grouping_type_parameter */
2112 entries = avio_rb32(pb);
2115 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2116 return AVERROR_INVALIDDATA;
2117 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2119 return AVERROR(ENOMEM);
2121 for (i = 0; i < entries && !pb->eof_reached; i++) {
2122 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2123 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2126 sc->rap_group_count = i;
2128 return pb->eof_reached ? AVERROR_EOF : 0;
2131 static void mov_build_index(MOVContext *mov, AVStream *st)
2133 MOVStreamContext *sc = st->priv_data;
2134 int64_t current_offset;
2135 int64_t current_dts = 0;
2136 unsigned int stts_index = 0;
2137 unsigned int stsc_index = 0;
2138 unsigned int stss_index = 0;
2139 unsigned int stps_index = 0;
2141 uint64_t stream_size = 0;
2143 /* adjust first dts according to edit list */
2144 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
2145 if (sc->empty_duration)
2146 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
2147 sc->time_offset = sc->start_time - sc->empty_duration;
2148 current_dts = -sc->time_offset;
2149 if (sc->ctts_count>0 && sc->stts_count>0 &&
2150 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2151 /* more than 16 frames delay, dts are likely wrong
2152 this happens with files created by iMovie */
2154 st->codec->has_b_frames = 1;
2158 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2159 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2160 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2161 unsigned int current_sample = 0;
2162 unsigned int stts_sample = 0;
2163 unsigned int sample_size;
2164 unsigned int distance = 0;
2165 unsigned int rap_group_index = 0;
2166 unsigned int rap_group_sample = 0;
2167 int rap_group_present = sc->rap_group_count && sc->rap_group;
2168 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2170 current_dts -= sc->dts_shift;
2172 if (!sc->sample_count || st->nb_index_entries)
2174 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2176 if (av_reallocp_array(&st->index_entries,
2177 st->nb_index_entries + sc->sample_count,
2178 sizeof(*st->index_entries)) < 0) {
2179 st->nb_index_entries = 0;
2182 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2184 for (i = 0; i < sc->chunk_count; i++) {
2185 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2186 current_offset = sc->chunk_offsets[i];
2187 while (stsc_index + 1 < sc->stsc_count &&
2188 i + 1 == sc->stsc_data[stsc_index + 1].first)
2191 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2192 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2193 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2194 sc->stsz_sample_size = sc->sample_size;
2196 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2197 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2198 sc->stsz_sample_size = sc->sample_size;
2201 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2203 if (current_sample >= sc->sample_count) {
2204 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2208 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2210 if (stss_index + 1 < sc->keyframe_count)
2212 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2214 if (stps_index + 1 < sc->stps_count)
2217 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2218 if (sc->rap_group[rap_group_index].index > 0)
2220 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2221 rap_group_sample = 0;
2225 if (sc->keyframe_absent
2227 && !rap_group_present
2228 && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2232 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2233 if (sc->pseudo_stream_id == -1 ||
2234 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2235 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2236 e->pos = current_offset;
2237 e->timestamp = current_dts;
2238 e->size = sample_size;
2239 e->min_distance = distance;
2240 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2241 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2242 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2243 current_offset, current_dts, sample_size, distance, keyframe);
2244 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2245 ff_rfps_add_frame(mov->fc, st, current_dts);
2248 current_offset += sample_size;
2249 stream_size += sample_size;
2250 current_dts += sc->stts_data[stts_index].duration;
2254 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2260 if (st->duration > 0)
2261 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2263 unsigned chunk_samples, total = 0;
2265 // compute total chunk count
2266 for (i = 0; i < sc->stsc_count; i++) {
2267 unsigned count, chunk_count;
2269 chunk_samples = sc->stsc_data[i].count;
2270 if (i != sc->stsc_count - 1 &&
2271 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2272 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2276 if (sc->samples_per_frame >= 160) { // gsm
2277 count = chunk_samples / sc->samples_per_frame;
2278 } else if (sc->samples_per_frame > 1) {
2279 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2280 count = (chunk_samples+samples-1) / samples;
2282 count = (chunk_samples+1023) / 1024;
2285 if (i < sc->stsc_count - 1)
2286 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2288 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2289 total += chunk_count * count;
2292 av_dlog(mov->fc, "chunk count %d\n", total);
2293 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2295 if (av_reallocp_array(&st->index_entries,
2296 st->nb_index_entries + total,
2297 sizeof(*st->index_entries)) < 0) {
2298 st->nb_index_entries = 0;
2301 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2304 for (i = 0; i < sc->chunk_count; i++) {
2305 current_offset = sc->chunk_offsets[i];
2306 if (stsc_index + 1 < sc->stsc_count &&
2307 i + 1 == sc->stsc_data[stsc_index + 1].first)
2309 chunk_samples = sc->stsc_data[stsc_index].count;
2311 while (chunk_samples > 0) {
2313 unsigned size, samples;
2315 if (sc->samples_per_frame >= 160) { // gsm
2316 samples = sc->samples_per_frame;
2317 size = sc->bytes_per_frame;
2319 if (sc->samples_per_frame > 1) {
2320 samples = FFMIN((1024 / sc->samples_per_frame)*
2321 sc->samples_per_frame, chunk_samples);
2322 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2324 samples = FFMIN(1024, chunk_samples);
2325 size = samples * sc->sample_size;
2329 if (st->nb_index_entries >= total) {
2330 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2333 e = &st->index_entries[st->nb_index_entries++];
2334 e->pos = current_offset;
2335 e->timestamp = current_dts;
2337 e->min_distance = 0;
2338 e->flags = AVINDEX_KEYFRAME;
2339 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2340 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2343 current_offset += size;
2344 current_dts += samples;
2345 chunk_samples -= samples;
2351 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2352 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2354 /* try relative path, we do not try the absolute because it can leak information about our
2355 system to an attacker */
2356 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2357 char filename[1024];
2358 const char *src_path;
2361 /* find a source dir */
2362 src_path = strrchr(src, '/');
2368 /* find a next level down to target */
2369 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2370 if (ref->path[l] == '/') {
2371 if (i == ref->nlvl_to - 1)
2377 /* compose filename if next level down to target was found */
2378 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2379 memcpy(filename, src, src_path - src);
2380 filename[src_path - src] = 0;
2382 for (i = 1; i < ref->nlvl_from; i++)
2383 av_strlcat(filename, "../", 1024);
2385 av_strlcat(filename, ref->path + l + 1, 1024);
2387 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2390 } else if (use_absolute_path) {
2391 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2392 "this is a possible security issue\n");
2393 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2397 return AVERROR(ENOENT);
2400 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2402 if (sc->time_scale <= 0) {
2403 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2404 sc->time_scale = c->time_scale;
2405 if (sc->time_scale <= 0)
2410 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2413 MOVStreamContext *sc;
2416 st = avformat_new_stream(c->fc, NULL);
2417 if (!st) return AVERROR(ENOMEM);
2418 st->id = c->fc->nb_streams;
2419 sc = av_mallocz(sizeof(MOVStreamContext));
2420 if (!sc) return AVERROR(ENOMEM);
2423 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2424 sc->ffindex = st->index;
2426 if ((ret = mov_read_default(c, pb, atom)) < 0)
2430 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2431 (!sc->sample_size && !sc->sample_count))) {
2432 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2437 fix_timescale(c, sc);
2439 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2441 mov_build_index(c, st);
2443 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2444 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2445 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2446 c->use_absolute_path, c->fc) < 0)
2447 av_log(c->fc, AV_LOG_ERROR,
2448 "stream %d, error opening alias: path='%s', dir='%s', "
2449 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2450 st->index, dref->path, dref->dir, dref->filename,
2451 dref->volume, dref->nlvl_from, dref->nlvl_to);
2454 sc->pb_is_copied = 1;
2457 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2458 if (!st->sample_aspect_ratio.num &&
2459 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2460 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2461 ((double)st->codec->width * sc->height), INT_MAX);
2464 #if FF_API_R_FRAME_RATE
2465 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2466 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2467 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2471 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2472 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2473 TAG_IS_AVCI(st->codec->codec_tag)) {
2474 ret = ff_generate_avci_extradata(st);
2479 switch (st->codec->codec_id) {
2480 #if CONFIG_H261_DECODER
2481 case AV_CODEC_ID_H261:
2483 #if CONFIG_H263_DECODER
2484 case AV_CODEC_ID_H263:
2486 #if CONFIG_MPEG4_DECODER
2487 case AV_CODEC_ID_MPEG4:
2489 st->codec->width = 0; /* let decoder init width/height */
2490 st->codec->height= 0;
2494 /* Do not need those anymore. */
2495 av_freep(&sc->chunk_offsets);
2496 av_freep(&sc->stsc_data);
2497 av_freep(&sc->sample_sizes);
2498 av_freep(&sc->keyframes);
2499 av_freep(&sc->stts_data);
2500 av_freep(&sc->stps_data);
2501 av_freep(&sc->rap_group);
2506 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2509 c->itunes_metadata = 1;
2510 ret = mov_read_default(c, pb, atom);
2511 c->itunes_metadata = 0;
2515 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
2517 int64_t end = avio_tell(pb) + size;
2518 uint8_t *key = NULL, *val = NULL;
2521 MOVStreamContext *sc;
2523 if (c->fc->nb_streams < 1)
2525 st = c->fc->streams[c->fc->nb_streams-1];
2528 for (i = 0; i < 2; i++) {
2532 if (end - avio_tell(pb) <= 12)
2535 len = avio_rb32(pb);
2536 tag = avio_rl32(pb);
2537 avio_skip(pb, 4); // flags
2539 if (len < 12 || len - 12 > end - avio_tell(pb))
2543 if (tag == MKTAG('n', 'a', 'm', 'e'))
2545 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2552 *p = av_malloc(len + 1);
2555 avio_read(pb, *p, len);
2560 if (strcmp(key, "iTunSMPB") == 0) {
2561 int priming, remainder, samples;
2562 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
2563 if(priming>0 && priming<16384)
2564 sc->start_pad = priming;
2567 if (strcmp(key, "cdec") != 0) {
2568 av_dict_set(&c->fc->metadata, key, val,
2569 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2574 avio_seek(pb, end, SEEK_SET);
2580 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2582 int64_t end = avio_tell(pb) + atom.size;
2588 len = avio_rb32(pb);
2589 tag = avio_rl32(pb);
2591 if (len > atom.size)
2594 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2595 uint8_t domain[128];
2598 avio_skip(pb, 4); // flags
2601 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2602 avio_skip(pb, len - domain_len);
2603 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
2607 av_log(c->fc, AV_LOG_VERBOSE,
2608 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2612 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2614 while (atom.size > 8) {
2615 uint32_t tag = avio_rl32(pb);
2617 if (tag == MKTAG('h','d','l','r')) {
2618 avio_seek(pb, -8, SEEK_CUR);
2620 return mov_read_default(c, pb, atom);
2626 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2631 int64_t disp_transform[2];
2632 int display_matrix[3][3];
2634 MOVStreamContext *sc;
2638 if (c->fc->nb_streams < 1)
2640 st = c->fc->streams[c->fc->nb_streams-1];
2643 version = avio_r8(pb);
2644 flags = avio_rb24(pb);
2645 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2651 avio_rb32(pb); /* creation time */
2652 avio_rb32(pb); /* modification time */
2654 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2655 avio_rb32(pb); /* reserved */
2657 /* highlevel (considering edits) duration in movie timebase */
2658 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2659 avio_rb32(pb); /* reserved */
2660 avio_rb32(pb); /* reserved */
2662 avio_rb16(pb); /* layer */
2663 avio_rb16(pb); /* alternate group */
2664 avio_rb16(pb); /* volume */
2665 avio_rb16(pb); /* reserved */
2667 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2668 // they're kept in fixed point format through all calculations
2669 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2670 // side data, but the scale factor is not needed to calculate aspect ratio
2671 for (i = 0; i < 3; i++) {
2672 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2673 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2674 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2677 width = avio_rb32(pb); // 16.16 fixed point track width
2678 height = avio_rb32(pb); // 16.16 fixed point track height
2679 sc->width = width >> 16;
2680 sc->height = height >> 16;
2682 // save the matrix and add rotate metadata when it is not the default
2684 if (display_matrix[0][0] != (1 << 16) ||
2685 display_matrix[1][1] != (1 << 16) ||
2686 display_matrix[2][2] != (1 << 30) ||
2687 display_matrix[0][1] || display_matrix[0][2] ||
2688 display_matrix[1][0] || display_matrix[1][2] ||
2689 display_matrix[2][0] || display_matrix[2][1]) {
2693 av_freep(&sc->display_matrix);
2694 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2695 if (!sc->display_matrix)
2696 return AVERROR(ENOMEM);
2698 for (i = 0; i < 3; i++)
2699 for (j = 0; j < 3; j++)
2700 sc->display_matrix[i * 3 + j] = display_matrix[j][i];
2702 rotate = av_display_rotation_get(sc->display_matrix);
2703 if (!isnan(rotate)) {
2704 char rotate_buf[64];
2706 if (rotate < 0) // for backward compatibility
2708 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
2709 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
2713 // transform the display width/height according to the matrix
2714 // skip this if the display matrix is the default identity matrix
2715 // or if it is rotating the picture, ex iPhone 3GS
2716 // to keep the same scale, use [width height 1<<16]
2717 if (width && height &&
2718 ((display_matrix[0][0] != 65536 ||
2719 display_matrix[1][1] != 65536) &&
2720 !display_matrix[0][1] &&
2721 !display_matrix[1][0] &&
2722 !display_matrix[2][0] && !display_matrix[2][1])) {
2723 for (i = 0; i < 2; i++)
2725 (int64_t) width * display_matrix[0][i] +
2726 (int64_t) height * display_matrix[1][i] +
2727 ((int64_t) display_matrix[2][i] << 16);
2729 //sample aspect ratio is new width/height divided by old width/height
2730 st->sample_aspect_ratio = av_d2q(
2731 ((double) disp_transform[0] * height) /
2732 ((double) disp_transform[1] * width), INT_MAX);
2737 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2739 MOVFragment *frag = &c->fragment;
2740 MOVTrackExt *trex = NULL;
2741 int flags, track_id, i;
2743 avio_r8(pb); /* version */
2744 flags = avio_rb24(pb);
2746 track_id = avio_rb32(pb);
2748 return AVERROR_INVALIDDATA;
2749 frag->track_id = track_id;
2750 for (i = 0; i < c->trex_count; i++)
2751 if (c->trex_data[i].track_id == frag->track_id) {
2752 trex = &c->trex_data[i];
2756 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2757 return AVERROR_INVALIDDATA;
2760 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2761 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
2762 frag->moof_offset : frag->implicit_offset;
2763 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2765 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2766 avio_rb32(pb) : trex->duration;
2767 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2768 avio_rb32(pb) : trex->size;
2769 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2770 avio_rb32(pb) : trex->flags;
2771 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2775 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2777 c->chapter_track = avio_rb32(pb);
2781 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2786 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2787 return AVERROR_INVALIDDATA;
2788 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2789 sizeof(*c->trex_data))) < 0) {
2794 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2796 trex = &c->trex_data[c->trex_count++];
2797 avio_r8(pb); /* version */
2798 avio_rb24(pb); /* flags */
2799 trex->track_id = avio_rb32(pb);
2800 trex->stsd_id = avio_rb32(pb);
2801 trex->duration = avio_rb32(pb);
2802 trex->size = avio_rb32(pb);
2803 trex->flags = avio_rb32(pb);
2807 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2809 MOVFragment *frag = &c->fragment;
2810 AVStream *st = NULL;
2811 MOVStreamContext *sc;
2815 int data_offset = 0;
2816 unsigned entries, first_sample_flags = frag->flags;
2817 int flags, distance, i, found_keyframe = 0, err;
2819 for (i = 0; i < c->fc->nb_streams; i++) {
2820 if (c->fc->streams[i]->id == frag->track_id) {
2821 st = c->fc->streams[i];
2826 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2827 return AVERROR_INVALIDDATA;
2830 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
2832 avio_r8(pb); /* version */
2833 flags = avio_rb24(pb);
2834 entries = avio_rb32(pb);
2835 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2837 /* Always assume the presence of composition time offsets.
2838 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2839 * 1) in the initial movie, there are no samples.
2840 * 2) in the first movie fragment, there is only one sample without composition time offset.
2841 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2842 if (!sc->ctts_count && sc->sample_count)
2844 /* Complement ctts table if moov atom doesn't have ctts atom. */
2845 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2847 return AVERROR(ENOMEM);
2848 sc->ctts_data = ctts_data;
2849 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2850 sc->ctts_data[sc->ctts_count].duration = 0;
2853 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2854 return AVERROR_INVALIDDATA;
2855 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2856 sizeof(*sc->ctts_data))) < 0) {
2860 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2861 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2862 dts = sc->track_end - sc->time_offset;
2863 offset = frag->base_data_offset + data_offset;
2865 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2866 for (i = 0; i < entries && !pb->eof_reached; i++) {
2867 unsigned sample_size = frag->size;
2868 int sample_flags = i ? frag->flags : first_sample_flags;
2869 unsigned sample_duration = frag->duration;
2872 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2873 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2874 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2875 sc->ctts_data[sc->ctts_count].count = 1;
2876 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2878 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
2880 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2882 else if (!found_keyframe)
2883 keyframe = found_keyframe =
2884 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2885 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2888 av_add_index_entry(st, offset, dts, sample_size, distance,
2889 keyframe ? AVINDEX_KEYFRAME : 0);
2890 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2891 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2892 offset, dts, sample_size, distance, keyframe);
2894 dts += sample_duration;
2895 offset += sample_size;
2896 sc->data_size += sample_size;
2897 sc->duration_for_fps += sample_duration;
2898 sc->nb_frames_for_fps ++;
2901 if (pb->eof_reached)
2904 frag->implicit_offset = offset;
2905 st->duration = sc->track_end = dts + sc->time_offset;
2909 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2910 /* like the files created with Adobe Premiere 5.0, for samples see */
2911 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2912 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2917 return 0; /* continue */
2918 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2919 avio_skip(pb, atom.size - 4);
2922 atom.type = avio_rl32(pb);
2924 if (atom.type != MKTAG('m','d','a','t')) {
2925 avio_skip(pb, atom.size);
2928 err = mov_read_mdat(c, pb, atom);
2932 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2937 uint8_t *moov_data; /* uncompressed data */
2938 long cmov_len, moov_len;
2941 avio_rb32(pb); /* dcom atom */
2942 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2943 return AVERROR_INVALIDDATA;
2944 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2945 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
2946 return AVERROR_INVALIDDATA;
2948 avio_rb32(pb); /* cmvd atom */
2949 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2950 return AVERROR_INVALIDDATA;
2951 moov_len = avio_rb32(pb); /* uncompressed size */
2952 cmov_len = atom.size - 6 * 4;
2954 cmov_data = av_malloc(cmov_len);
2956 return AVERROR(ENOMEM);
2957 moov_data = av_malloc(moov_len);
2960 return AVERROR(ENOMEM);
2962 avio_read(pb, cmov_data, cmov_len);
2963 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2964 goto free_and_return;
2965 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2966 goto free_and_return;
2967 atom.type = MKTAG('m','o','o','v');
2968 atom.size = moov_len;
2969 ret = mov_read_default(c, &ctx, atom);
2975 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2976 return AVERROR(ENOSYS);
2980 /* edit list atom */
2981 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2983 MOVStreamContext *sc;
2984 int i, edit_count, version, edit_start_index = 0;
2985 int unsupported = 0;
2987 if (c->fc->nb_streams < 1 || c->ignore_editlist)
2989 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2991 version = avio_r8(pb); /* version */
2992 avio_rb24(pb); /* flags */
2993 edit_count = avio_rb32(pb); /* entries */
2995 if ((uint64_t)edit_count*12+8 > atom.size)
2996 return AVERROR_INVALIDDATA;
2998 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2999 for (i=0; i<edit_count; i++){
3004 duration = avio_rb64(pb);
3005 time = avio_rb64(pb);
3007 duration = avio_rb32(pb); /* segment duration */
3008 time = (int32_t)avio_rb32(pb); /* media time */
3010 rate = avio_rb32(pb);
3011 if (i == 0 && time == -1) {
3012 sc->empty_duration = duration;
3013 edit_start_index = 1;
3014 } else if (i == edit_start_index && time >= 0)
3015 sc->start_time = time;
3019 av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3020 duration, time, rate / 65536.0);
3024 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
3025 "a/v desync might occur, patch welcome\n");
3030 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3032 MOVStreamContext *sc;
3034 if (c->fc->nb_streams < 1)
3035 return AVERROR_INVALIDDATA;
3036 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3037 sc->timecode_track = avio_rb32(pb);
3041 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3045 static const uint8_t uuid_isml_manifest[] = {
3046 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3047 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3050 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3051 return AVERROR_INVALIDDATA;
3053 ret = avio_read(pb, uuid, sizeof(uuid));
3056 } else if (ret != sizeof(uuid)) {
3057 return AVERROR_INVALIDDATA;
3059 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3060 uint8_t *buffer, *ptr;
3062 size_t len = atom.size - sizeof(uuid);
3065 return AVERROR_INVALIDDATA;
3067 ret = avio_skip(pb, 4); // zeroes
3070 buffer = av_mallocz(len + 1);
3072 return AVERROR(ENOMEM);
3074 ret = avio_read(pb, buffer, len);
3078 } else if (ret != len) {
3080 return AVERROR_INVALIDDATA;
3084 while ((ptr = av_stristr(ptr, "systemBitrate=\"")) != NULL) {
3085 ptr += sizeof("systemBitrate=\"") - 1;
3086 c->bitrates_count++;
3087 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3089 c->bitrates_count = 0;
3091 return AVERROR(ENOMEM);
3094 ret = strtol(ptr, &endptr, 10);
3095 if (ret < 0 || errno || *endptr != '"') {
3096 c->bitrates[c->bitrates_count - 1] = 0;
3098 c->bitrates[c->bitrates_count - 1] = ret;
3107 static const MOVParseTableEntry mov_default_parse_table[] = {
3108 { MKTAG('A','C','L','R'), mov_read_avid },
3109 { MKTAG('A','P','R','G'), mov_read_avid },
3110 { MKTAG('A','A','L','P'), mov_read_avid },
3111 { MKTAG('A','R','E','S'), mov_read_ares },
3112 { MKTAG('a','v','s','s'), mov_read_avss },
3113 { MKTAG('c','h','p','l'), mov_read_chpl },
3114 { MKTAG('c','o','6','4'), mov_read_stco },
3115 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3116 { MKTAG('d','i','n','f'), mov_read_default },
3117 { MKTAG('d','r','e','f'), mov_read_dref },
3118 { MKTAG('e','d','t','s'), mov_read_default },
3119 { MKTAG('e','l','s','t'), mov_read_elst },
3120 { MKTAG('e','n','d','a'), mov_read_enda },
3121 { MKTAG('f','i','e','l'), mov_read_fiel },
3122 { MKTAG('f','t','y','p'), mov_read_ftyp },
3123 { MKTAG('g','l','b','l'), mov_read_glbl },
3124 { MKTAG('h','d','l','r'), mov_read_hdlr },
3125 { MKTAG('i','l','s','t'), mov_read_ilst },
3126 { MKTAG('j','p','2','h'), mov_read_jp2h },
3127 { MKTAG('m','d','a','t'), mov_read_mdat },
3128 { MKTAG('m','d','h','d'), mov_read_mdhd },
3129 { MKTAG('m','d','i','a'), mov_read_default },
3130 { MKTAG('m','e','t','a'), mov_read_meta },
3131 { MKTAG('m','i','n','f'), mov_read_default },
3132 { MKTAG('m','o','o','f'), mov_read_moof },
3133 { MKTAG('m','o','o','v'), mov_read_moov },
3134 { MKTAG('m','v','e','x'), mov_read_default },
3135 { MKTAG('m','v','h','d'), mov_read_mvhd },
3136 { MKTAG('S','M','I',' '), mov_read_svq3 },
3137 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
3138 { MKTAG('a','v','c','C'), mov_read_glbl },
3139 { MKTAG('p','a','s','p'), mov_read_pasp },
3140 { MKTAG('s','t','b','l'), mov_read_default },
3141 { MKTAG('s','t','c','o'), mov_read_stco },
3142 { MKTAG('s','t','p','s'), mov_read_stps },
3143 { MKTAG('s','t','r','f'), mov_read_strf },
3144 { MKTAG('s','t','s','c'), mov_read_stsc },
3145 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3146 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3147 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3148 { MKTAG('s','t','t','s'), mov_read_stts },
3149 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3150 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3151 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3152 { MKTAG('t','r','a','k'), mov_read_trak },
3153 { MKTAG('t','r','a','f'), mov_read_default },
3154 { MKTAG('t','r','e','f'), mov_read_default },
3155 { MKTAG('t','m','c','d'), mov_read_tmcd },
3156 { MKTAG('c','h','a','p'), mov_read_chap },
3157 { MKTAG('t','r','e','x'), mov_read_trex },
3158 { MKTAG('t','r','u','n'), mov_read_trun },
3159 { MKTAG('u','d','t','a'), mov_read_default },
3160 { MKTAG('w','a','v','e'), mov_read_wave },
3161 { MKTAG('e','s','d','s'), mov_read_esds },
3162 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3163 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3164 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3165 { MKTAG('w','f','e','x'), mov_read_wfex },
3166 { MKTAG('c','m','o','v'), mov_read_cmov },
3167 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3168 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3169 { MKTAG('s','b','g','p'), mov_read_sbgp },
3170 { MKTAG('h','v','c','C'), mov_read_glbl },
3171 { MKTAG('u','u','i','d'), mov_read_uuid },
3172 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
3173 { MKTAG('-','-','-','-'), mov_read_custom },
3177 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3179 int64_t total_size = 0;
3184 atom.size = INT64_MAX;
3185 while (total_size + 8 <= atom.size && !avio_feof(pb)) {
3186 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3189 if (atom.size >= 8) {
3190 a.size = avio_rb32(pb);
3191 a.type = avio_rl32(pb);
3192 if (a.type == MKTAG('f','r','e','e') &&
3196 uint32_t *type = (uint32_t *)buf + 1;
3197 avio_read(pb, buf, 8);
3198 avio_seek(pb, -8, SEEK_CUR);
3199 if (*type == MKTAG('m','v','h','d') ||
3200 *type == MKTAG('c','m','o','v')) {
3201 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
3202 a.type = MKTAG('m','o','o','v');
3205 if (atom.type != MKTAG('r','o','o','t') &&
3206 atom.type != MKTAG('m','o','o','v'))
3208 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
3210 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
3216 if (a.size == 1) { /* 64 bit extended size */
3217 a.size = avio_rb64(pb) - 8;
3221 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3222 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3224 a.size = atom.size - total_size + 8;
3229 a.size = FFMIN(a.size, atom.size - total_size);
3231 for (i = 0; mov_default_parse_table[i].type; i++)
3232 if (mov_default_parse_table[i].type == a.type) {
3233 parse = mov_default_parse_table[i].parse;
3237 // container is user data
3238 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3239 atom.type == MKTAG('i','l','s','t')))
3240 parse = mov_read_udta_string;
3242 if (!parse) { /* skip leaf atoms data */
3243 avio_skip(pb, a.size);
3245 int64_t start_pos = avio_tell(pb);
3247 int err = parse(c, pb, a);
3250 if (c->found_moov && c->found_mdat &&
3251 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3252 start_pos + a.size == avio_size(pb))) {
3253 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3254 c->next_root_atom = start_pos + a.size;
3257 left = a.size - avio_tell(pb) + start_pos;
3258 if (left > 0) /* skip garbage at atom end */
3259 avio_skip(pb, left);
3260 else if (left < 0) {
3261 av_log(c->fc, AV_LOG_WARNING,
3262 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3263 (char*)&a.type, -left);
3264 avio_seek(pb, left, SEEK_CUR);
3268 total_size += a.size;
3271 if (total_size < atom.size && atom.size < 0x7ffff)
3272 avio_skip(pb, atom.size - total_size);
3277 static int mov_probe(AVProbeData *p)
3282 int moov_offset = -1;
3284 /* check file header */
3287 /* ignore invalid offset */
3288 if ((offset + 8) > (unsigned int)p->buf_size)
3290 tag = AV_RL32(p->buf + offset + 4);
3292 /* check for obvious tags */
3293 case MKTAG('m','o','o','v'):
3294 moov_offset = offset + 4;
3295 case MKTAG('m','d','a','t'):
3296 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3297 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3298 case MKTAG('f','t','y','p'):
3299 if (AV_RB32(p->buf+offset) < 8 &&
3300 (AV_RB32(p->buf+offset) != 1 ||
3301 offset + 12 > (unsigned int)p->buf_size ||
3302 AV_RB64(p->buf+offset + 8) == 0)) {
3303 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3304 } else if (tag == MKTAG('f','t','y','p') &&
3305 AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')) {
3306 score = FFMAX(score, 5);
3308 score = AVPROBE_SCORE_MAX;
3310 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3312 /* those are more common words, so rate then a bit less */
3313 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3314 case MKTAG('w','i','d','e'):
3315 case MKTAG('f','r','e','e'):
3316 case MKTAG('j','u','n','k'):
3317 case MKTAG('p','i','c','t'):
3318 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
3319 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3321 case MKTAG(0x82,0x82,0x7f,0x7d):
3322 case MKTAG('s','k','i','p'):
3323 case MKTAG('u','u','i','d'):
3324 case MKTAG('p','r','f','l'):
3325 /* if we only find those cause probedata is too small at least rate them */
3326 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3327 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3330 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3333 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
3334 /* moov atom in the header - we should make sure that this is not a
3335 * MOV-packed MPEG-PS */
3336 offset = moov_offset;
3338 while(offset < (p->buf_size - 16)){ /* Sufficient space */
3339 /* We found an actual hdlr atom */
3340 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
3341 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
3342 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
3343 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
3344 /* We found a media handler reference atom describing an
3345 * MPEG-PS-in-MOV, return a
3346 * low score to force expanding the probe window until
3347 * mpegps_probe finds what it needs */
3358 // must be done after parsing all trak because there's no order requirement
3359 static void mov_read_chapters(AVFormatContext *s)
3361 MOVContext *mov = s->priv_data;
3362 AVStream *st = NULL;
3363 MOVStreamContext *sc;
3367 for (i = 0; i < s->nb_streams; i++)
3368 if (s->streams[i]->id == mov->chapter_track) {
3373 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3377 st->discard = AVDISCARD_ALL;
3379 cur_pos = avio_tell(sc->pb);
3381 for (i = 0; i < st->nb_index_entries; i++) {
3382 AVIndexEntry *sample = &st->index_entries[i];
3383 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3388 if (end < sample->timestamp) {
3389 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
3390 end = AV_NOPTS_VALUE;
3393 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3394 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3398 // the first two bytes are the length of the title
3399 len = avio_rb16(sc->pb);
3400 if (len > sample->size-2)
3402 title_len = 2*len + 1;
3403 if (!(title = av_mallocz(title_len)))
3406 // The samples could theoretically be in any encoding if there's an encd
3407 // atom following, but in practice are only utf-8 or utf-16, distinguished
3408 // instead by the presence of a BOM
3412 ch = avio_rb16(sc->pb);
3414 avio_get_str16be(sc->pb, len, title, title_len);
3415 else if (ch == 0xfffe)
3416 avio_get_str16le(sc->pb, len, title, title_len);
3419 if (len == 1 || len == 2)
3422 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3426 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3430 avio_seek(sc->pb, cur_pos, SEEK_SET);
3433 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
3434 uint32_t value, int flags)
3437 char buf[AV_TIMECODE_STR_SIZE];
3438 AVRational rate = {st->codec->time_base.den,
3439 st->codec->time_base.num};
3440 int ret = av_timecode_init(&tc, rate, flags, 0, s);
3443 av_dict_set(&st->metadata, "timecode",
3444 av_timecode_make_string(&tc, buf, value), 0);
3448 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
3450 MOVStreamContext *sc = st->priv_data;
3452 int64_t cur_pos = avio_tell(sc->pb);
3455 if (!st->nb_index_entries)
3458 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3459 value = avio_rb32(s->pb);
3461 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3462 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3463 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3465 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3466 * not the case) and thus assume "frame number format" instead of QT one.
3467 * No sample with tmcd track can be found with a QT timecode at the moment,
3468 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3470 parse_timecode_in_framenum_format(s, st, value, flags);
3472 avio_seek(sc->pb, cur_pos, SEEK_SET);
3476 static int mov_read_close(AVFormatContext *s)
3478 MOVContext *mov = s->priv_data;
3481 for (i = 0; i < s->nb_streams; i++) {
3482 AVStream *st = s->streams[i];
3483 MOVStreamContext *sc = st->priv_data;
3485 av_freep(&sc->ctts_data);
3486 for (j = 0; j < sc->drefs_count; j++) {
3487 av_freep(&sc->drefs[j].path);
3488 av_freep(&sc->drefs[j].dir);
3490 av_freep(&sc->drefs);
3492 sc->drefs_count = 0;
3494 if (!sc->pb_is_copied)
3498 av_freep(&sc->chunk_offsets);
3499 av_freep(&sc->stsc_data);
3500 av_freep(&sc->sample_sizes);
3501 av_freep(&sc->keyframes);
3502 av_freep(&sc->stts_data);
3503 av_freep(&sc->stps_data);
3504 av_freep(&sc->rap_group);
3505 av_freep(&sc->display_matrix);
3508 if (mov->dv_demux) {
3509 avformat_free_context(mov->dv_fctx);
3510 mov->dv_fctx = NULL;
3513 av_freep(&mov->trex_data);
3514 av_freep(&mov->bitrates);
3519 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3523 for (i = 0; i < s->nb_streams; i++) {
3524 AVStream *st = s->streams[i];
3525 MOVStreamContext *sc = st->priv_data;
3527 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3528 sc->timecode_track == tmcd_id)
3534 /* look for a tmcd track not referenced by any video track, and export it globally */
3535 static void export_orphan_timecode(AVFormatContext *s)
3539 for (i = 0; i < s->nb_streams; i++) {
3540 AVStream *st = s->streams[i];
3542 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3543 !tmcd_is_referenced(s, i + 1)) {
3544 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3546 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3553 static int mov_read_header(AVFormatContext *s)
3555 MOVContext *mov = s->priv_data;
3556 AVIOContext *pb = s->pb;
3558 MOVAtom atom = { AV_RL32("root") };
3562 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3564 atom.size = avio_size(pb);
3566 atom.size = INT64_MAX;
3568 /* check MOV header */
3570 if (mov->moov_retry)
3571 avio_seek(pb, 0, SEEK_SET);
3572 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3573 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3577 } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
3578 if (!mov->found_moov) {
3579 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3581 return AVERROR_INVALIDDATA;
3583 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3586 if (mov->chapter_track > 0)
3587 mov_read_chapters(s);
3588 for (i = 0; i < s->nb_streams; i++)
3589 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3590 mov_read_timecode_track(s, s->streams[i]);
3593 /* copy timecode metadata from tmcd tracks to the related video streams */
3594 for (i = 0; i < s->nb_streams; i++) {
3595 AVStream *st = s->streams[i];
3596 MOVStreamContext *sc = st->priv_data;
3597 if (sc->timecode_track > 0) {
3598 AVDictionaryEntry *tcr;
3599 int tmcd_st_id = -1;
3601 for (j = 0; j < s->nb_streams; j++)
3602 if (s->streams[j]->id == sc->timecode_track)
3605 if (tmcd_st_id < 0 || tmcd_st_id == i)
3607 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
3609 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
3612 export_orphan_timecode(s);
3614 for (i = 0; i < s->nb_streams; i++) {
3615 AVStream *st = s->streams[i];
3616 MOVStreamContext *sc = st->priv_data;
3617 fix_timescale(mov, sc);
3618 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
3619 st->skip_samples = sc->start_pad;
3621 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
3622 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3623 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
3624 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3625 if (st->codec->width <= 0 && st->codec->height <= 0) {
3626 st->codec->width = sc->width;
3627 st->codec->height = sc->height;
3629 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3630 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3636 if (mov->trex_data) {
3637 for (i = 0; i < s->nb_streams; i++) {
3638 AVStream *st = s->streams[i];
3639 MOVStreamContext *sc = st->priv_data;
3640 if (st->duration > 0)
3641 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3645 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
3646 if (mov->bitrates[i]) {
3647 s->streams[i]->codec->bit_rate = mov->bitrates[i];
3651 ff_rfps_calculate(s);
3653 for (i = 0; i < s->nb_streams; i++) {
3654 AVStream *st = s->streams[i];
3655 MOVStreamContext *sc = st->priv_data;
3657 switch (st->codec->codec_type) {
3658 case AVMEDIA_TYPE_AUDIO:
3659 err = ff_replaygain_export(st, s->metadata);
3665 case AVMEDIA_TYPE_VIDEO:
3666 if (sc->display_matrix) {
3667 AVPacketSideData *sd, *tmp;
3669 tmp = av_realloc_array(st->side_data,
3670 st->nb_side_data + 1, sizeof(*tmp));
3672 return AVERROR(ENOMEM);
3674 st->side_data = tmp;
3677 sd = &st->side_data[st->nb_side_data - 1];
3678 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
3679 sd->size = sizeof(int32_t) * 9;
3680 sd->data = (uint8_t*)sc->display_matrix;
3681 sc->display_matrix = NULL;
3690 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3692 AVIndexEntry *sample = NULL;
3693 int64_t best_dts = INT64_MAX;
3695 for (i = 0; i < s->nb_streams; i++) {
3696 AVStream *avst = s->streams[i];
3697 MOVStreamContext *msc = avst->priv_data;
3698 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3699 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3700 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3701 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3702 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3704 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3705 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3706 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3707 sample = current_sample;
3716 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3718 MOVContext *mov = s->priv_data;
3719 MOVStreamContext *sc;
3720 AVIndexEntry *sample;
3721 AVStream *st = NULL;
3725 sample = mov_find_next_sample(s, &st);
3727 mov->found_mdat = 0;
3728 if (!mov->next_root_atom)
3730 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3731 mov->next_root_atom = 0;
3732 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3735 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3739 /* must be done just before reading, to avoid infinite loop on sample */
3740 sc->current_sample++;
3742 if (mov->next_root_atom) {
3743 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
3744 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
3747 if (st->discard != AVDISCARD_ALL) {
3748 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3749 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3750 sc->ffindex, sample->pos);
3751 return AVERROR_INVALIDDATA;
3753 ret = av_get_packet(sc->pb, pkt, sample->size);
3756 if (sc->has_palette) {
3759 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3761 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3763 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3764 sc->has_palette = 0;
3767 #if CONFIG_DV_DEMUXER
3768 if (mov->dv_demux && sc->dv_audio_container) {
3769 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
3772 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3779 pkt->stream_index = sc->ffindex;
3780 pkt->dts = sample->timestamp;
3781 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3782 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3783 /* update ctts context */
3785 if (sc->ctts_index < sc->ctts_count &&
3786 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3788 sc->ctts_sample = 0;
3791 pkt->dts = AV_NOPTS_VALUE;
3793 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3794 st->index_entries[sc->current_sample].timestamp : st->duration;
3795 pkt->duration = next_dts - pkt->dts;
3796 pkt->pts = pkt->dts;
3798 if (st->discard == AVDISCARD_ALL)
3800 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3801 pkt->pos = sample->pos;
3802 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3803 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3807 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3809 MOVStreamContext *sc = st->priv_data;
3810 int sample, time_sample;
3813 sample = av_index_search_timestamp(st, timestamp, flags);
3814 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3815 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3817 if (sample < 0) /* not sure what to do */
3818 return AVERROR_INVALIDDATA;
3819 sc->current_sample = sample;
3820 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3821 /* adjust ctts index */
3822 if (sc->ctts_data) {
3824 for (i = 0; i < sc->ctts_count; i++) {
3825 int next = time_sample + sc->ctts_data[i].count;
3826 if (next > sc->current_sample) {
3828 sc->ctts_sample = sc->current_sample - time_sample;
3837 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3840 int64_t seek_timestamp, timestamp;
3844 if (stream_index >= s->nb_streams)
3845 return AVERROR_INVALIDDATA;
3847 st = s->streams[stream_index];
3848 sample = mov_seek_stream(s, st, sample_time, flags);
3852 /* adjust seek timestamp to found sample timestamp */
3853 seek_timestamp = st->index_entries[sample].timestamp;
3855 for (i = 0; i < s->nb_streams; i++) {
3856 MOVStreamContext *sc = s->streams[i]->priv_data;
3858 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
3860 if (stream_index == i)
3863 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3864 mov_seek_stream(s, st, timestamp, flags);
3869 static const AVOption options[] = {
3870 {"use_absolute_path",
3871 "allow using absolute path when opening alias, this is a possible security issue",
3872 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
3873 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3874 {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
3875 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3879 static const AVClass mov_class = {
3880 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3881 .item_name = av_default_item_name,
3883 .version = LIBAVUTIL_VERSION_INT,
3886 AVInputFormat ff_mov_demuxer = {
3887 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3888 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3889 .priv_data_size = sizeof(MOVContext),
3890 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
3891 .read_probe = mov_probe,
3892 .read_header = mov_read_header,
3893 .read_packet = mov_read_packet,
3894 .read_close = mov_read_close,
3895 .read_seek = mov_read_seek,
3896 .priv_class = &mov_class,
3897 .flags = AVFMT_NO_BYTE_SEEK,