3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 //#define MOV_EXPORT_ALL_METADATA
28 #include "libavutil/attributes.h"
29 #include "libavutil/audioconvert.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/intfloat.h"
32 #include "libavutil/mathematics.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/dict.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/timecode.h"
37 #include "libavcodec/ac3tab.h"
40 #include "avio_internal.h"
43 #include "libavcodec/get_bits.h"
52 * First version by Francois Revol revol@free.fr
53 * Seek function by Gael Chardon gael.dev@4now.net
56 #include "qtpalette.h"
62 /* those functions parse an atom */
63 /* links atom IDs to parse functions */
64 typedef struct MOVParseTableEntry {
66 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
69 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
71 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
72 unsigned len, const char *key)
76 short current, total = 0;
77 avio_rb16(pb); // unknown
78 current = avio_rb16(pb);
80 total = avio_rb16(pb);
82 snprintf(buf, sizeof(buf), "%d", current);
84 snprintf(buf, sizeof(buf), "%d/%d", current, total);
85 av_dict_set(&c->fc->metadata, key, buf, 0);
90 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
91 unsigned len, const char *key)
95 /* bypass padding bytes */
100 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
101 av_dict_set(&c->fc->metadata, key, buf, 0);
106 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
107 unsigned len, const char *key)
111 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
112 av_dict_set(&c->fc->metadata, key, buf, 0);
117 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
118 unsigned len, const char *key)
123 avio_r8(pb); // unknown
126 if (genre < 1 || genre > ID3v1_GENRE_MAX)
128 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
129 av_dict_set(&c->fc->metadata, key, buf, 0);
134 static int mov_read_custom_metadata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
136 char key[1024]={0}, data[1024]={0};
139 MOVStreamContext *sc;
141 if (c->fc->nb_streams < 1)
143 st = c->fc->streams[c->fc->nb_streams-1];
146 if (atom.size <= 8) return 0;
148 for (i = 0; i < 3; i++) { // Parse up to three sub-atoms looking for name and data.
149 int data_size = avio_rb32(pb);
150 int tag = avio_rl32(pb);
151 int str_size = 0, skip_size = 0;
155 case MKTAG('n','a','m','e'):
156 avio_rb32(pb); // version/flags
157 str_size = skip_size = data_size - 12;
161 case MKTAG('d','a','t','a'):
162 avio_rb32(pb); // version/flags
163 avio_rb32(pb); // reserved (zero)
164 str_size = skip_size = data_size - 16;
169 skip_size = data_size - 8;
175 str_size = FFMIN3(sizeof(data)-1, str_size, atom.size);
176 avio_read(pb, target, str_size);
177 target[str_size] = 0;
179 atom.size -= skip_size;
181 // If we didn't read the full data chunk for the sub-atom, skip to the end of it.
182 if (skip_size > str_size) avio_skip(pb, skip_size - str_size);
186 if (strcmp(key, "iTunSMPB") == 0) {
187 int priming, remainder, samples;
188 if(sscanf(data, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
189 if(priming>0 && priming<16384)
190 sc->start_pad = priming;
194 if (strcmp(key, "cdec") == 0) {
195 // av_dict_set(&st->metadata, key, data, 0);
202 static const uint32_t mac_to_unicode[128] = {
203 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
204 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
205 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
206 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
207 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
208 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
209 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
210 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
211 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
212 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
213 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
214 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
215 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
216 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
217 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
218 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
221 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
222 char *dst, int dstlen)
225 char *end = dst+dstlen-1;
228 for (i = 0; i < len; i++) {
229 uint8_t t, c = avio_r8(pb);
230 if (c < 0x80 && p < end)
233 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
239 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
243 MOVStreamContext *sc;
248 case 0xd: id = AV_CODEC_ID_MJPEG; break;
249 case 0xe: id = AV_CODEC_ID_PNG; break;
250 case 0x1b: id = AV_CODEC_ID_BMP; break;
252 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
257 st = avformat_new_stream(c->fc, NULL);
259 return AVERROR(ENOMEM);
260 sc = av_mallocz(sizeof(*sc));
262 return AVERROR(ENOMEM);
265 ret = av_get_packet(pb, &pkt, len);
269 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
271 st->attached_pic = pkt;
272 st->attached_pic.stream_index = st->index;
273 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
275 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
276 st->codec->codec_id = id;
281 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
283 #ifdef MOV_EXPORT_ALL_METADATA
286 char str[1024], key2[16], language[4] = {0};
287 const char *key = NULL;
288 uint16_t langcode = 0;
289 uint32_t data_type = 0, str_size;
290 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
292 if (c->itunes_metadata && atom.type == MKTAG('-','-','-','-'))
293 return mov_read_custom_metadata(c, pb, atom);
296 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
297 case MKTAG(0xa9,'a','u','t'):
298 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
299 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
300 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
301 case MKTAG( 'c','p','r','t'):
302 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
303 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
304 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
305 case MKTAG(0xa9,'c','m','t'):
306 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
307 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
308 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
309 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
310 case MKTAG( 'g','n','r','e'): key = "genre";
311 parse = mov_metadata_gnre; break;
312 case MKTAG(0xa9,'t','o','o'):
313 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
314 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
315 case MKTAG( 'd','e','s','c'): key = "description";break;
316 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
317 case MKTAG( 't','v','s','h'): key = "show"; break;
318 case MKTAG( 't','v','e','n'): key = "episode_id";break;
319 case MKTAG( 't','v','n','n'): key = "network"; break;
320 case MKTAG( 't','r','k','n'): key = "track";
321 parse = mov_metadata_track_or_disc_number; break;
322 case MKTAG( 'd','i','s','k'): key = "disc";
323 parse = mov_metadata_track_or_disc_number; break;
324 case MKTAG( 't','v','e','s'): key = "episode_sort";
325 parse = mov_metadata_int8_bypass_padding; break;
326 case MKTAG( 't','v','s','n'): key = "season_number";
327 parse = mov_metadata_int8_bypass_padding; break;
328 case MKTAG( 's','t','i','k'): key = "media_type";
329 parse = mov_metadata_int8_no_padding; break;
330 case MKTAG( 'h','d','v','d'): key = "hd_video";
331 parse = mov_metadata_int8_no_padding; break;
332 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
333 parse = mov_metadata_int8_no_padding; break;
336 if (c->itunes_metadata && atom.size > 8) {
337 int data_size = avio_rb32(pb);
338 int tag = avio_rl32(pb);
339 if (tag == MKTAG('d','a','t','a')) {
340 data_type = avio_rb32(pb); // type
341 avio_rb32(pb); // unknown
342 str_size = data_size - 16;
345 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
346 int ret = mov_read_covr(c, pb, data_type, str_size);
348 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
353 } else if (atom.size > 4 && key && !c->itunes_metadata) {
354 str_size = avio_rb16(pb); // string length
355 langcode = avio_rb16(pb);
356 ff_mov_lang_to_iso639(langcode, language);
359 str_size = atom.size;
361 #ifdef MOV_EXPORT_ALL_METADATA
363 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
371 return AVERROR_INVALIDDATA;
373 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
376 parse(c, pb, str_size, key);
378 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
379 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
381 avio_read(pb, str, str_size);
384 av_dict_set(&c->fc->metadata, key, str, 0);
385 if (*language && strcmp(language, "und")) {
386 snprintf(key2, sizeof(key2), "%s-%s", key, language);
387 av_dict_set(&c->fc->metadata, key2, str, 0);
390 av_dlog(c->fc, "lang \"%3s\" ", language);
391 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
392 key, str, (char*)&atom.type, str_size, atom.size);
397 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
400 int i, nb_chapters, str_len, version;
403 if ((atom.size -= 5) < 0)
406 version = avio_r8(pb);
409 avio_rb32(pb); // ???
410 nb_chapters = avio_r8(pb);
412 for (i = 0; i < nb_chapters; i++) {
416 start = avio_rb64(pb);
417 str_len = avio_r8(pb);
419 if ((atom.size -= 9+str_len) < 0)
422 avio_read(pb, str, str_len);
424 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
429 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
432 MOVStreamContext *sc;
435 if (c->fc->nb_streams < 1)
437 st = c->fc->streams[c->fc->nb_streams-1];
440 avio_rb32(pb); // version + flags
441 entries = avio_rb32(pb);
442 if (entries >= UINT_MAX / sizeof(*sc->drefs))
443 return AVERROR_INVALIDDATA;
446 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
448 return AVERROR(ENOMEM);
449 sc->drefs_count = entries;
451 for (i = 0; i < sc->drefs_count; i++) {
452 MOVDref *dref = &sc->drefs[i];
453 uint32_t size = avio_rb32(pb);
454 int64_t next = avio_tell(pb) + size - 4;
457 return AVERROR_INVALIDDATA;
459 dref->type = avio_rl32(pb);
460 avio_rb32(pb); // version + flags
461 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
463 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
464 /* macintosh alias record */
465 uint16_t volume_len, len;
470 volume_len = avio_r8(pb);
471 volume_len = FFMIN(volume_len, 27);
472 avio_read(pb, dref->volume, 27);
473 dref->volume[volume_len] = 0;
474 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
479 len = FFMIN(len, 63);
480 avio_read(pb, dref->filename, 63);
481 dref->filename[len] = 0;
482 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
486 /* read next level up_from_alias/down_to_target */
487 dref->nlvl_from = avio_rb16(pb);
488 dref->nlvl_to = avio_rb16(pb);
489 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
490 dref->nlvl_from, dref->nlvl_to);
494 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
497 type = avio_rb16(pb);
499 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
502 if (type == 2) { // absolute path
504 dref->path = av_mallocz(len+1);
506 return AVERROR(ENOMEM);
507 avio_read(pb, dref->path, len);
508 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
510 memmove(dref->path, dref->path+volume_len, len);
513 for (j = 0; j < len; j++)
514 if (dref->path[j] == ':')
516 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
517 } else if (type == 0) { // directory name
519 dref->dir = av_malloc(len+1);
521 return AVERROR(ENOMEM);
522 avio_read(pb, dref->dir, len);
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 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
684 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
688 if (c->fc->nb_streams < 1)
690 st = c->fc->streams[c->fc->nb_streams-1];
692 ff_get_wav_header(pb, st->codec, atom.size);
697 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
699 const int num = avio_rb32(pb);
700 const int den = avio_rb32(pb);
703 if (c->fc->nb_streams < 1)
705 st = c->fc->streams[c->fc->nb_streams-1];
707 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
708 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
709 av_log(c->fc, AV_LOG_WARNING,
710 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
711 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
713 } else if (den != 0) {
714 st->sample_aspect_ratio.num = num;
715 st->sample_aspect_ratio.den = den;
720 /* this atom contains actual media data */
721 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
723 if (atom.size == 0) /* wrong one (MP4) */
726 return 0; /* now go for moov */
729 /* read major brand, minor version and compatible brands and store them as metadata */
730 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
734 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
735 char* comp_brands_str;
736 uint8_t type[5] = {0};
738 avio_read(pb, type, 4);
739 if (strcmp(type, "qt "))
741 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
742 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
743 minor_ver = avio_rb32(pb); /* minor version */
744 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
745 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
747 comp_brand_size = atom.size - 8;
748 if (comp_brand_size < 0)
749 return AVERROR_INVALIDDATA;
750 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
751 if (!comp_brands_str)
752 return AVERROR(ENOMEM);
753 avio_read(pb, comp_brands_str, comp_brand_size);
754 comp_brands_str[comp_brand_size] = 0;
755 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
756 av_freep(&comp_brands_str);
761 /* this atom should contain all header atoms */
762 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
766 if ((ret = mov_read_default(c, pb, atom)) < 0)
768 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
769 /* so we don't parse the whole file if over a network */
771 return 0; /* now go for mdat */
774 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
776 c->fragment.moof_offset = avio_tell(pb) - 8;
777 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
778 return mov_read_default(c, pb, atom);
781 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
786 if(time >= 2082844800)
787 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
790 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
791 av_dict_set(metadata, "creation_time", buffer, 0);
795 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
798 MOVStreamContext *sc;
800 char language[4] = {0};
802 time_t creation_time;
804 if (c->fc->nb_streams < 1)
806 st = c->fc->streams[c->fc->nb_streams-1];
809 version = avio_r8(pb);
811 av_log_ask_for_sample(c, "unsupported version %d\n", version);
812 return AVERROR_PATCHWELCOME;
814 avio_rb24(pb); /* flags */
816 creation_time = avio_rb64(pb);
819 creation_time = avio_rb32(pb);
820 avio_rb32(pb); /* modification time */
822 mov_metadata_creation_time(&st->metadata, creation_time);
824 sc->time_scale = avio_rb32(pb);
825 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
827 lang = avio_rb16(pb); /* language */
828 if (ff_mov_lang_to_iso639(lang, language))
829 av_dict_set(&st->metadata, "language", language, 0);
830 avio_rb16(pb); /* quality */
835 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
837 time_t creation_time;
838 int version = avio_r8(pb); /* version */
839 avio_rb24(pb); /* flags */
842 creation_time = avio_rb64(pb);
845 creation_time = avio_rb32(pb);
846 avio_rb32(pb); /* modification time */
848 mov_metadata_creation_time(&c->fc->metadata, creation_time);
849 c->time_scale = avio_rb32(pb); /* time scale */
851 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
853 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
854 // set the AVCodecContext duration because the duration of individual tracks
856 if (c->time_scale > 0)
857 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
858 avio_rb32(pb); /* preferred scale */
860 avio_rb16(pb); /* preferred volume */
862 avio_skip(pb, 10); /* reserved */
864 avio_skip(pb, 36); /* display matrix */
866 avio_rb32(pb); /* preview time */
867 avio_rb32(pb); /* preview duration */
868 avio_rb32(pb); /* poster time */
869 avio_rb32(pb); /* selection time */
870 avio_rb32(pb); /* selection duration */
871 avio_rb32(pb); /* current time */
872 avio_rb32(pb); /* next track ID */
876 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
881 if (c->fc->nb_streams < 1)
883 st = c->fc->streams[c->fc->nb_streams-1];
885 little_endian = avio_rb16(pb) & 0xFF;
886 av_dlog(c->fc, "enda %d\n", little_endian);
887 if (little_endian == 1) {
888 switch (st->codec->codec_id) {
889 case AV_CODEC_ID_PCM_S24BE:
890 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
892 case AV_CODEC_ID_PCM_S32BE:
893 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
895 case AV_CODEC_ID_PCM_F32BE:
896 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
898 case AV_CODEC_ID_PCM_F64BE:
899 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
908 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
911 unsigned mov_field_order;
912 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
914 if (c->fc->nb_streams < 1) // will happen with jp2 files
916 st = c->fc->streams[c->fc->nb_streams-1];
918 return AVERROR_INVALIDDATA;
919 mov_field_order = avio_rb16(pb);
920 if ((mov_field_order & 0xFF00) == 0x0100)
921 decoded_field_order = AV_FIELD_PROGRESSIVE;
922 else if ((mov_field_order & 0xFF00) == 0x0200) {
923 switch (mov_field_order & 0xFF) {
924 case 0x01: decoded_field_order = AV_FIELD_TT;
926 case 0x06: decoded_field_order = AV_FIELD_BB;
928 case 0x09: decoded_field_order = AV_FIELD_TB;
930 case 0x0E: decoded_field_order = AV_FIELD_BT;
934 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
935 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
937 st->codec->field_order = decoded_field_order;
942 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
943 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
944 enum AVCodecID codec_id)
950 if (c->fc->nb_streams < 1) // will happen with jp2 files
952 st= c->fc->streams[c->fc->nb_streams-1];
954 if (st->codec->codec_id != codec_id)
955 return 0; /* unexpected codec_id - don't mess with extradata */
957 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
958 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
959 return AVERROR_INVALIDDATA;
960 buf= av_realloc(st->codec->extradata, size);
962 return AVERROR(ENOMEM);
963 st->codec->extradata= buf;
964 buf+= st->codec->extradata_size;
965 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
966 AV_WB32( buf , atom.size + 8);
967 AV_WL32( buf + 4, atom.type);
968 avio_read(pb, buf + 8, atom.size);
972 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
973 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
975 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
978 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
980 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
983 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
985 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
988 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
990 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
993 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
995 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
998 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1002 if (c->fc->nb_streams < 1)
1004 st = c->fc->streams[c->fc->nb_streams-1];
1006 if ((uint64_t)atom.size > (1<<30))
1007 return AVERROR_INVALIDDATA;
1009 if (st->codec->codec_id == AV_CODEC_ID_QDM2 || st->codec->codec_id == AV_CODEC_ID_QDMC) {
1010 // pass all frma atom to codec, needed at least for QDMC and QDM2
1011 av_free(st->codec->extradata);
1012 st->codec->extradata_size = 0;
1013 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1014 if (!st->codec->extradata)
1015 return AVERROR(ENOMEM);
1016 st->codec->extradata_size = atom.size;
1017 avio_read(pb, st->codec->extradata, atom.size);
1018 } else if (atom.size > 8) { /* to read frma, esds atoms */
1020 if ((ret = mov_read_default(c, pb, atom)) < 0)
1023 avio_skip(pb, atom.size);
1028 * This function reads atom content and puts data in extradata without tag
1029 * nor size unlike mov_read_extradata.
1031 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1035 if (c->fc->nb_streams < 1)
1037 st = c->fc->streams[c->fc->nb_streams-1];
1039 if ((uint64_t)atom.size > (1<<30))
1040 return AVERROR_INVALIDDATA;
1042 if (atom.size >= 10) {
1043 // Broken files created by legacy versions of libavformat will
1044 // wrap a whole fiel atom inside of a glbl atom.
1045 unsigned size = avio_rb32(pb);
1046 unsigned type = avio_rl32(pb);
1047 avio_seek(pb, -8, SEEK_CUR);
1048 if (type == MKTAG('f','i','e','l') && size == atom.size)
1049 return mov_read_default(c, pb, atom);
1051 av_free(st->codec->extradata);
1052 st->codec->extradata_size = 0;
1053 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1054 if (!st->codec->extradata)
1055 return AVERROR(ENOMEM);
1056 st->codec->extradata_size = atom.size;
1057 avio_read(pb, st->codec->extradata, atom.size);
1061 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1064 uint8_t profile_level;
1066 if (c->fc->nb_streams < 1)
1068 st = c->fc->streams[c->fc->nb_streams-1];
1070 if (atom.size >= (1<<28) || atom.size < 7)
1071 return AVERROR_INVALIDDATA;
1073 profile_level = avio_r8(pb);
1074 if ((profile_level & 0xf0) != 0xc0)
1077 av_free(st->codec->extradata);
1078 st->codec->extradata_size = 0;
1079 st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
1080 if (!st->codec->extradata)
1081 return AVERROR(ENOMEM);
1082 st->codec->extradata_size = atom.size - 7;
1083 avio_seek(pb, 6, SEEK_CUR);
1084 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
1089 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1090 * but can have extradata appended at the end after the 40 bytes belonging
1093 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1097 if (c->fc->nb_streams < 1)
1099 if (atom.size <= 40)
1101 st = c->fc->streams[c->fc->nb_streams-1];
1103 if ((uint64_t)atom.size > (1<<30))
1104 return AVERROR_INVALIDDATA;
1106 av_free(st->codec->extradata);
1107 st->codec->extradata_size = 0;
1108 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1109 if (!st->codec->extradata)
1110 return AVERROR(ENOMEM);
1111 st->codec->extradata_size = atom.size - 40;
1113 avio_read(pb, st->codec->extradata, atom.size - 40);
1117 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1120 MOVStreamContext *sc;
1121 unsigned int i, entries;
1123 if (c->fc->nb_streams < 1)
1125 st = c->fc->streams[c->fc->nb_streams-1];
1128 avio_r8(pb); /* version */
1129 avio_rb24(pb); /* flags */
1131 entries = avio_rb32(pb);
1135 if (entries >= UINT_MAX/sizeof(int64_t))
1136 return AVERROR_INVALIDDATA;
1138 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1139 if (!sc->chunk_offsets)
1140 return AVERROR(ENOMEM);
1141 sc->chunk_count = entries;
1143 if (atom.type == MKTAG('s','t','c','o'))
1144 for (i = 0; i < entries && !pb->eof_reached; i++)
1145 sc->chunk_offsets[i] = avio_rb32(pb);
1146 else if (atom.type == MKTAG('c','o','6','4'))
1147 for (i = 0; i < entries && !pb->eof_reached; i++)
1148 sc->chunk_offsets[i] = avio_rb64(pb);
1150 return AVERROR_INVALIDDATA;
1152 sc->chunk_count = i;
1154 if (pb->eof_reached)
1161 * Compute codec id for 'lpcm' tag.
1162 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1164 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1166 if (flags & 1) { // floating point
1167 if (flags & 2) { // big endian
1168 if (bps == 32) return AV_CODEC_ID_PCM_F32BE;
1169 else if (bps == 64) return AV_CODEC_ID_PCM_F64BE;
1171 if (bps == 32) return AV_CODEC_ID_PCM_F32LE;
1172 else if (bps == 64) return AV_CODEC_ID_PCM_F64LE;
1178 if (flags & 4) return AV_CODEC_ID_PCM_S8;
1179 else return AV_CODEC_ID_PCM_U8;
1180 else if (bps == 16) return AV_CODEC_ID_PCM_S16BE;
1181 else if (bps == 24) return AV_CODEC_ID_PCM_S24BE;
1182 else if (bps == 32) return AV_CODEC_ID_PCM_S32BE;
1185 if (flags & 4) return AV_CODEC_ID_PCM_S8;
1186 else return AV_CODEC_ID_PCM_U8;
1187 else if (bps == 16) return AV_CODEC_ID_PCM_S16LE;
1188 else if (bps == 24) return AV_CODEC_ID_PCM_S24LE;
1189 else if (bps == 32) return AV_CODEC_ID_PCM_S32LE;
1192 return AV_CODEC_ID_NONE;
1195 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1198 MOVStreamContext *sc;
1199 int j, pseudo_stream_id;
1201 if (c->fc->nb_streams < 1)
1203 st = c->fc->streams[c->fc->nb_streams-1];
1206 for (pseudo_stream_id = 0;
1207 pseudo_stream_id < entries && !pb->eof_reached;
1208 pseudo_stream_id++) {
1209 //Parsing Sample description table
1212 MOVAtom a = { AV_RL32("stsd") };
1213 int64_t start_pos = avio_tell(pb);
1214 int64_t size = avio_rb32(pb); /* size */
1215 uint32_t format = avio_rl32(pb); /* data format */
1218 avio_rb32(pb); /* reserved */
1219 avio_rb16(pb); /* reserved */
1220 dref_id = avio_rb16(pb);
1221 }else if (size <= 7){
1222 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1223 return AVERROR_INVALIDDATA;
1226 if (st->codec->codec_tag &&
1227 st->codec->codec_tag != format &&
1228 (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
1229 : st->codec->codec_tag != MKTAG('j','p','e','g'))
1231 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1232 * export it as a separate AVStream but this needs a few changes
1233 * in the MOV demuxer, patch welcome. */
1234 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1235 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1238 /* we cannot demux concatenated h264 streams because of different extradata */
1239 if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1240 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 might not play corrently.\n");
1241 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1242 sc->dref_id= dref_id;
1244 st->codec->codec_tag = format;
1245 id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1246 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1247 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1249 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1250 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1251 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1252 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1253 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1255 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1257 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1258 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1259 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1260 st->codec->codec_id == AV_CODEC_ID_NONE)){
1261 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1263 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1267 av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1268 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1269 (format >> 24) & 0xff, st->codec->codec_type);
1271 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1272 unsigned int color_depth, len;
1273 int color_greyscale;
1276 st->codec->codec_id = id;
1277 avio_rb16(pb); /* version */
1278 avio_rb16(pb); /* revision level */
1279 avio_rb32(pb); /* vendor */
1280 avio_rb32(pb); /* temporal quality */
1281 avio_rb32(pb); /* spatial quality */
1283 st->codec->width = avio_rb16(pb); /* width */
1284 st->codec->height = avio_rb16(pb); /* height */
1286 avio_rb32(pb); /* horiz resolution */
1287 avio_rb32(pb); /* vert resolution */
1288 avio_rb32(pb); /* data size, always 0 */
1289 avio_rb16(pb); /* frames per samples */
1291 len = avio_r8(pb); /* codec name, pascal string */
1294 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1296 avio_skip(pb, 31 - len);
1297 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1298 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1299 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1301 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1302 color_table_id = avio_rb16(pb); /* colortable id */
1303 av_dlog(c->fc, "depth %d, ctab id %d\n",
1304 st->codec->bits_per_coded_sample, color_table_id);
1305 /* figure out the palette situation */
1306 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1307 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1309 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1310 if ((color_depth == 2) || (color_depth == 4) ||
1311 (color_depth == 8)) {
1312 /* for palette traversal */
1313 unsigned int color_start, color_count, color_end;
1314 unsigned char a, r, g, b;
1316 if (color_greyscale) {
1317 int color_index, color_dec;
1318 /* compute the greyscale palette */
1319 st->codec->bits_per_coded_sample = color_depth;
1320 color_count = 1 << color_depth;
1322 color_dec = 256 / (color_count - 1);
1323 for (j = 0; j < color_count; j++) {
1324 if (id == AV_CODEC_ID_CINEPAK){
1325 r = g = b = color_count - 1 - color_index;
1327 r = g = b = color_index;
1329 (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1330 color_index -= color_dec;
1331 if (color_index < 0)
1334 } else if (color_table_id) {
1335 const uint8_t *color_table;
1336 /* if flag bit 3 is set, use the default palette */
1337 color_count = 1 << color_depth;
1338 if (color_depth == 2)
1339 color_table = ff_qt_default_palette_4;
1340 else if (color_depth == 4)
1341 color_table = ff_qt_default_palette_16;
1343 color_table = ff_qt_default_palette_256;
1345 for (j = 0; j < color_count; j++) {
1346 r = color_table[j * 3 + 0];
1347 g = color_table[j * 3 + 1];
1348 b = color_table[j * 3 + 2];
1350 (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1353 /* load the palette from the file */
1354 color_start = avio_rb32(pb);
1355 color_count = avio_rb16(pb);
1356 color_end = avio_rb16(pb);
1357 if ((color_start <= 255) &&
1358 (color_end <= 255)) {
1359 for (j = color_start; j <= color_end; j++) {
1360 /* each A, R, G, or B component is 16 bits;
1361 * only use the top 8 bits */
1371 (a << 24 ) | (r << 16) | (g << 8) | (b);
1375 sc->has_palette = 1;
1377 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1378 int bits_per_sample, flags;
1379 uint16_t version = avio_rb16(pb);
1381 st->codec->codec_id = id;
1382 avio_rb16(pb); /* revision level */
1383 avio_rb32(pb); /* vendor */
1385 st->codec->channels = avio_rb16(pb); /* channel count */
1386 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1387 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1389 sc->audio_cid = avio_rb16(pb);
1390 avio_rb16(pb); /* packet size = 0 */
1392 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1394 //Read QT version 1 fields. In version 0 these do not exist.
1395 av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
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)); /* float 64 */
1405 st->codec->channels = avio_rb32(pb);
1406 avio_rb32(pb); /* always 0x7F000000 */
1407 st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1408 flags = avio_rb32(pb); /* lpcm format specific flag */
1409 sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1410 sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1411 if (format == MKTAG('l','p','c','m'))
1412 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1416 switch (st->codec->codec_id) {
1417 case AV_CODEC_ID_PCM_S8:
1418 case AV_CODEC_ID_PCM_U8:
1419 if (st->codec->bits_per_coded_sample == 16)
1420 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1422 case AV_CODEC_ID_PCM_S16LE:
1423 case AV_CODEC_ID_PCM_S16BE:
1424 if (st->codec->bits_per_coded_sample == 8)
1425 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1426 else if (st->codec->bits_per_coded_sample == 24)
1427 st->codec->codec_id =
1428 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1429 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1431 /* set values for old format before stsd version 1 appeared */
1432 case AV_CODEC_ID_MACE3:
1433 sc->samples_per_frame = 6;
1434 sc->bytes_per_frame = 2*st->codec->channels;
1436 case AV_CODEC_ID_MACE6:
1437 sc->samples_per_frame = 6;
1438 sc->bytes_per_frame = 1*st->codec->channels;
1440 case AV_CODEC_ID_ADPCM_IMA_QT:
1441 sc->samples_per_frame = 64;
1442 sc->bytes_per_frame = 34*st->codec->channels;
1444 case AV_CODEC_ID_GSM:
1445 sc->samples_per_frame = 160;
1446 sc->bytes_per_frame = 33;
1452 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1453 if (bits_per_sample) {
1454 st->codec->bits_per_coded_sample = bits_per_sample;
1455 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1457 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1458 // ttxt stsd contains display flags, justification, background
1459 // color, fonts, and default styles, so fake an atom to read it
1460 MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1461 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1462 mov_read_glbl(c, pb, fake_atom);
1463 st->codec->codec_id= id;
1464 st->codec->width = sc->width;
1465 st->codec->height = sc->height;
1467 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1468 MOVStreamContext *tmcd_ctx = st->priv_data;
1470 avio_rb32(pb); /* reserved */
1471 val = avio_rb32(pb); /* flags */
1472 tmcd_ctx->tmcd_flags = val;
1474 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1475 avio_rb32(pb); /* time scale */
1476 avio_rb32(pb); /* frame duration */
1477 st->codec->time_base.den = avio_r8(pb); /* number of frame */
1478 st->codec->time_base.num = 1;
1480 /* other codec type, just skip (rtp, mp4s, ...) */
1481 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1483 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1484 a.size = size - (avio_tell(pb) - start_pos);
1487 if ((ret = mov_read_default(c, pb, a)) < 0)
1489 } else if (a.size > 0)
1490 avio_skip(pb, a.size);
1493 if (pb->eof_reached)
1496 if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1497 st->codec->sample_rate= sc->time_scale;
1499 /* special codec parameters handling */
1500 switch (st->codec->codec_id) {
1501 #if CONFIG_DV_DEMUXER
1502 case AV_CODEC_ID_DVAUDIO:
1503 c->dv_fctx = avformat_alloc_context();
1504 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1506 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1507 return AVERROR(ENOMEM);
1509 sc->dv_audio_container = 1;
1510 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1513 /* no ifdef since parameters are always those */
1514 case AV_CODEC_ID_QCELP:
1515 // force sample rate for qcelp when not stored in mov
1516 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1517 st->codec->sample_rate = 8000;
1518 st->codec->channels= 1; /* really needed */
1520 case AV_CODEC_ID_AMR_NB:
1521 st->codec->channels= 1; /* really needed */
1522 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1523 st->codec->sample_rate = 8000;
1525 case AV_CODEC_ID_AMR_WB:
1526 st->codec->channels = 1;
1527 st->codec->sample_rate = 16000;
1529 case AV_CODEC_ID_MP2:
1530 case AV_CODEC_ID_MP3:
1531 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1532 st->need_parsing = AVSTREAM_PARSE_FULL;
1534 case AV_CODEC_ID_GSM:
1535 case AV_CODEC_ID_ADPCM_MS:
1536 case AV_CODEC_ID_ADPCM_IMA_WAV:
1537 case AV_CODEC_ID_ILBC:
1538 st->codec->block_align = sc->bytes_per_frame;
1540 case AV_CODEC_ID_ALAC:
1541 if (st->codec->extradata_size == 36) {
1542 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1543 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1546 case AV_CODEC_ID_AC3:
1547 st->need_parsing = AVSTREAM_PARSE_FULL;
1549 case AV_CODEC_ID_MPEG1VIDEO:
1550 st->need_parsing = AVSTREAM_PARSE_FULL;
1552 case AV_CODEC_ID_VC1:
1553 st->need_parsing = AVSTREAM_PARSE_FULL;
1562 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1566 avio_r8(pb); /* version */
1567 avio_rb24(pb); /* flags */
1568 entries = avio_rb32(pb);
1570 return ff_mov_read_stsd_entries(c, pb, entries);
1573 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1576 MOVStreamContext *sc;
1577 unsigned int i, entries;
1579 if (c->fc->nb_streams < 1)
1581 st = c->fc->streams[c->fc->nb_streams-1];
1584 avio_r8(pb); /* version */
1585 avio_rb24(pb); /* flags */
1587 entries = avio_rb32(pb);
1589 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1593 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1594 return AVERROR_INVALIDDATA;
1595 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1597 return AVERROR(ENOMEM);
1599 for (i = 0; i < entries && !pb->eof_reached; i++) {
1600 sc->stsc_data[i].first = avio_rb32(pb);
1601 sc->stsc_data[i].count = avio_rb32(pb);
1602 sc->stsc_data[i].id = avio_rb32(pb);
1607 if (pb->eof_reached)
1613 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1616 MOVStreamContext *sc;
1617 unsigned i, entries;
1619 if (c->fc->nb_streams < 1)
1621 st = c->fc->streams[c->fc->nb_streams-1];
1624 avio_rb32(pb); // version + flags
1626 entries = avio_rb32(pb);
1627 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1628 return AVERROR_INVALIDDATA;
1629 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1631 return AVERROR(ENOMEM);
1633 for (i = 0; i < entries && !pb->eof_reached; i++) {
1634 sc->stps_data[i] = avio_rb32(pb);
1635 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1640 if (pb->eof_reached)
1646 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1649 MOVStreamContext *sc;
1650 unsigned int i, entries;
1652 if (c->fc->nb_streams < 1)
1654 st = c->fc->streams[c->fc->nb_streams-1];
1657 avio_r8(pb); /* version */
1658 avio_rb24(pb); /* flags */
1660 entries = avio_rb32(pb);
1662 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1666 sc->keyframe_absent = 1;
1669 if (entries >= UINT_MAX / sizeof(int))
1670 return AVERROR_INVALIDDATA;
1671 sc->keyframes = av_malloc(entries * sizeof(int));
1673 return AVERROR(ENOMEM);
1675 for (i = 0; i < entries && !pb->eof_reached; i++) {
1676 sc->keyframes[i] = avio_rb32(pb);
1677 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1680 sc->keyframe_count = i;
1682 if (pb->eof_reached)
1688 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1691 MOVStreamContext *sc;
1692 unsigned int i, entries, sample_size, field_size, num_bytes;
1696 if (c->fc->nb_streams < 1)
1698 st = c->fc->streams[c->fc->nb_streams-1];
1701 avio_r8(pb); /* version */
1702 avio_rb24(pb); /* flags */
1704 if (atom.type == MKTAG('s','t','s','z')) {
1705 sample_size = avio_rb32(pb);
1706 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1707 sc->sample_size = sample_size;
1708 sc->alt_sample_size = sample_size;
1712 avio_rb24(pb); /* reserved */
1713 field_size = avio_r8(pb);
1715 entries = avio_rb32(pb);
1717 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1719 sc->sample_count = entries;
1723 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1724 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1725 return AVERROR_INVALIDDATA;
1730 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1731 return AVERROR_INVALIDDATA;
1732 sc->sample_sizes = av_malloc(entries * sizeof(int));
1733 if (!sc->sample_sizes)
1734 return AVERROR(ENOMEM);
1736 num_bytes = (entries*field_size+4)>>3;
1738 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1740 av_freep(&sc->sample_sizes);
1741 return AVERROR(ENOMEM);
1744 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1745 av_freep(&sc->sample_sizes);
1747 return AVERROR_INVALIDDATA;
1750 init_get_bits(&gb, buf, 8*num_bytes);
1752 for (i = 0; i < entries && !pb->eof_reached; i++) {
1753 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1754 sc->data_size += sc->sample_sizes[i];
1757 sc->sample_count = i;
1759 if (pb->eof_reached)
1766 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1769 MOVStreamContext *sc;
1770 unsigned int i, entries;
1772 int64_t total_sample_count=0;
1774 if (c->fc->nb_streams < 1)
1776 st = c->fc->streams[c->fc->nb_streams-1];
1779 avio_r8(pb); /* version */
1780 avio_rb24(pb); /* flags */
1781 entries = avio_rb32(pb);
1783 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1784 c->fc->nb_streams-1, entries);
1786 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1789 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1791 return AVERROR(ENOMEM);
1793 for (i = 0; i < entries && !pb->eof_reached; i++) {
1794 int sample_duration;
1797 sample_count=avio_rb32(pb);
1798 sample_duration = avio_rb32(pb);
1799 /* sample_duration < 0 is invalid based on the spec */
1800 if (sample_duration < 0) {
1801 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
1802 sample_duration = 1;
1804 sc->stts_data[i].count= sample_count;
1805 sc->stts_data[i].duration= sample_duration;
1807 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1808 sample_count, sample_duration);
1810 duration+=(int64_t)sample_duration*sample_count;
1811 total_sample_count+=sample_count;
1816 if (pb->eof_reached)
1819 st->nb_frames= total_sample_count;
1821 st->duration= duration;
1822 sc->track_end = duration;
1826 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1829 MOVStreamContext *sc;
1830 unsigned int i, entries;
1832 if (c->fc->nb_streams < 1)
1834 st = c->fc->streams[c->fc->nb_streams-1];
1837 avio_r8(pb); /* version */
1838 avio_rb24(pb); /* flags */
1839 entries = avio_rb32(pb);
1841 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1845 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1846 return AVERROR_INVALIDDATA;
1847 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1849 return AVERROR(ENOMEM);
1851 for (i = 0; i < entries && !pb->eof_reached; i++) {
1852 int count =avio_rb32(pb);
1853 int duration =avio_rb32(pb);
1855 sc->ctts_data[i].count = count;
1856 sc->ctts_data[i].duration= duration;
1858 av_dlog(c->fc, "count=%d, duration=%d\n",
1861 if (FFABS(duration) > (1<<28) && i+2<entries) {
1862 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
1863 av_freep(&sc->ctts_data);
1868 if (duration < 0 && i+2<entries)
1869 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1874 if (pb->eof_reached)
1877 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1882 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1885 MOVStreamContext *sc;
1886 unsigned int i, entries;
1888 uint32_t grouping_type;
1890 if (c->fc->nb_streams < 1)
1892 st = c->fc->streams[c->fc->nb_streams-1];
1895 version = avio_r8(pb); /* version */
1896 avio_rb24(pb); /* flags */
1897 grouping_type = avio_rl32(pb);
1898 if (grouping_type != MKTAG( 'r','a','p',' '))
1899 return 0; /* only support 'rap ' grouping */
1901 avio_rb32(pb); /* grouping_type_parameter */
1903 entries = avio_rb32(pb);
1906 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
1907 return AVERROR_INVALIDDATA;
1908 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
1910 return AVERROR(ENOMEM);
1912 for (i = 0; i < entries && !pb->eof_reached; i++) {
1913 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
1914 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
1917 sc->rap_group_count = i;
1919 return pb->eof_reached ? AVERROR_EOF : 0;
1922 static void mov_build_index(MOVContext *mov, AVStream *st)
1924 MOVStreamContext *sc = st->priv_data;
1925 int64_t current_offset;
1926 int64_t current_dts = 0;
1927 unsigned int stts_index = 0;
1928 unsigned int stsc_index = 0;
1929 unsigned int stss_index = 0;
1930 unsigned int stps_index = 0;
1932 uint64_t stream_size = 0;
1935 /* adjust first dts according to edit list */
1936 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
1937 if (sc->empty_duration)
1938 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
1939 sc->time_offset = sc->start_time - sc->empty_duration;
1940 current_dts = -sc->time_offset;
1941 if (sc->ctts_count>0 && sc->stts_count>0 &&
1942 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1943 /* more than 16 frames delay, dts are likely wrong
1944 this happens with files created by iMovie */
1946 st->codec->has_b_frames = 1;
1950 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1951 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1952 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1953 unsigned int current_sample = 0;
1954 unsigned int stts_sample = 0;
1955 unsigned int sample_size;
1956 unsigned int distance = 0;
1957 unsigned int rap_group_index = 0;
1958 unsigned int rap_group_sample = 0;
1959 int rap_group_present = sc->rap_group_count && sc->rap_group;
1960 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
1962 current_dts -= sc->dts_shift;
1964 if (!sc->sample_count || st->nb_index_entries)
1966 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1968 mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1971 st->index_entries = mem;
1972 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
1974 for (i = 0; i < sc->chunk_count; i++) {
1975 current_offset = sc->chunk_offsets[i];
1976 while (stsc_index + 1 < sc->stsc_count &&
1977 i + 1 == sc->stsc_data[stsc_index + 1].first)
1979 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1981 if (current_sample >= sc->sample_count) {
1982 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1986 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
1988 if (stss_index + 1 < sc->keyframe_count)
1990 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1992 if (stps_index + 1 < sc->stps_count)
1995 if (rap_group_present && rap_group_index < sc->rap_group_count) {
1996 if (sc->rap_group[rap_group_index].index > 0)
1998 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
1999 rap_group_sample = 0;
2005 sample_size = sc->alt_sample_size > 0 ? sc->alt_sample_size : sc->sample_sizes[current_sample];
2006 if (sc->pseudo_stream_id == -1 ||
2007 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2008 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2009 e->pos = current_offset;
2010 e->timestamp = current_dts;
2011 e->size = sample_size;
2012 e->min_distance = distance;
2013 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2014 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2015 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2016 current_offset, current_dts, sample_size, distance, keyframe);
2019 current_offset += sample_size;
2020 stream_size += sample_size;
2021 current_dts += sc->stts_data[stts_index].duration;
2025 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2031 if (st->duration > 0)
2032 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2034 unsigned chunk_samples, total = 0;
2036 // compute total chunk count
2037 for (i = 0; i < sc->stsc_count; i++) {
2038 unsigned count, chunk_count;
2040 chunk_samples = sc->stsc_data[i].count;
2041 if (i != sc->stsc_count - 1 &&
2042 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2043 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2047 if (sc->samples_per_frame >= 160) { // gsm
2048 count = chunk_samples / sc->samples_per_frame;
2049 } else if (sc->samples_per_frame > 1) {
2050 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2051 count = (chunk_samples+samples-1) / samples;
2053 count = (chunk_samples+1023) / 1024;
2056 if (i < sc->stsc_count - 1)
2057 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2059 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2060 total += chunk_count * count;
2063 av_dlog(mov->fc, "chunk count %d\n", total);
2064 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2066 mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
2069 st->index_entries = mem;
2070 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2073 for (i = 0; i < sc->chunk_count; i++) {
2074 current_offset = sc->chunk_offsets[i];
2075 if (stsc_index + 1 < sc->stsc_count &&
2076 i + 1 == sc->stsc_data[stsc_index + 1].first)
2078 chunk_samples = sc->stsc_data[stsc_index].count;
2080 while (chunk_samples > 0) {
2082 unsigned size, samples;
2084 if (sc->samples_per_frame >= 160) { // gsm
2085 samples = sc->samples_per_frame;
2086 size = sc->bytes_per_frame;
2088 if (sc->samples_per_frame > 1) {
2089 samples = FFMIN((1024 / sc->samples_per_frame)*
2090 sc->samples_per_frame, chunk_samples);
2091 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2093 samples = FFMIN(1024, chunk_samples);
2094 size = samples * sc->sample_size;
2098 if (st->nb_index_entries >= total) {
2099 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2102 e = &st->index_entries[st->nb_index_entries++];
2103 e->pos = current_offset;
2104 e->timestamp = current_dts;
2106 e->min_distance = 0;
2107 e->flags = AVINDEX_KEYFRAME;
2108 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2109 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2112 current_offset += size;
2113 current_dts += samples;
2114 chunk_samples -= samples;
2120 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2121 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2123 /* try relative path, we do not try the absolute because it can leak information about our
2124 system to an attacker */
2125 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2126 char filename[1024];
2127 const char *src_path;
2130 /* find a source dir */
2131 src_path = strrchr(src, '/');
2137 /* find a next level down to target */
2138 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2139 if (ref->path[l] == '/') {
2140 if (i == ref->nlvl_to - 1)
2146 /* compose filename if next level down to target was found */
2147 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2148 memcpy(filename, src, src_path - src);
2149 filename[src_path - src] = 0;
2151 for (i = 1; i < ref->nlvl_from; i++)
2152 av_strlcat(filename, "../", 1024);
2154 av_strlcat(filename, ref->path + l + 1, 1024);
2156 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2159 } else if (use_absolute_path) {
2160 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2161 "this is a possible security issue\n");
2162 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2166 return AVERROR(ENOENT);
2169 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2172 MOVStreamContext *sc;
2175 st = avformat_new_stream(c->fc, NULL);
2176 if (!st) return AVERROR(ENOMEM);
2177 st->id = c->fc->nb_streams;
2178 sc = av_mallocz(sizeof(MOVStreamContext));
2179 if (!sc) return AVERROR(ENOMEM);
2182 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2183 sc->ffindex = st->index;
2185 if ((ret = mov_read_default(c, pb, atom)) < 0)
2189 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2190 (!sc->sample_size && !sc->sample_count))) {
2191 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2196 if (sc->time_scale <= 0) {
2197 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2198 sc->time_scale = c->time_scale;
2199 if (sc->time_scale <= 0)
2203 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2205 mov_build_index(c, st);
2207 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2208 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2209 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2210 c->use_absolute_path, c->fc) < 0)
2211 av_log(c->fc, AV_LOG_ERROR,
2212 "stream %d, error opening alias: path='%s', dir='%s', "
2213 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2214 st->index, dref->path, dref->dir, dref->filename,
2215 dref->volume, dref->nlvl_from, dref->nlvl_to);
2219 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2220 if (!st->sample_aspect_ratio.num &&
2221 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2222 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2223 ((double)st->codec->width * sc->height), INT_MAX);
2226 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2227 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2229 #if FF_API_R_FRAME_RATE
2230 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2231 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2232 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2236 switch (st->codec->codec_id) {
2237 #if CONFIG_H261_DECODER
2238 case AV_CODEC_ID_H261:
2240 #if CONFIG_H263_DECODER
2241 case AV_CODEC_ID_H263:
2243 #if CONFIG_MPEG4_DECODER
2244 case AV_CODEC_ID_MPEG4:
2246 st->codec->width = 0; /* let decoder init width/height */
2247 st->codec->height= 0;
2251 /* Do not need those anymore. */
2252 av_freep(&sc->chunk_offsets);
2253 av_freep(&sc->stsc_data);
2254 av_freep(&sc->sample_sizes);
2255 av_freep(&sc->keyframes);
2256 av_freep(&sc->stts_data);
2257 av_freep(&sc->stps_data);
2258 av_freep(&sc->rap_group);
2263 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2266 c->itunes_metadata = 1;
2267 ret = mov_read_default(c, pb, atom);
2268 c->itunes_metadata = 0;
2272 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2274 while (atom.size > 8) {
2275 uint32_t tag = avio_rl32(pb);
2277 if (tag == MKTAG('h','d','l','r')) {
2278 avio_seek(pb, -8, SEEK_CUR);
2280 return mov_read_default(c, pb, atom);
2286 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2291 int64_t disp_transform[2];
2292 int display_matrix[3][2];
2294 MOVStreamContext *sc;
2297 if (c->fc->nb_streams < 1)
2299 st = c->fc->streams[c->fc->nb_streams-1];
2302 version = avio_r8(pb);
2303 avio_rb24(pb); /* flags */
2305 MOV_TRACK_ENABLED 0x0001
2306 MOV_TRACK_IN_MOVIE 0x0002
2307 MOV_TRACK_IN_PREVIEW 0x0004
2308 MOV_TRACK_IN_POSTER 0x0008
2315 avio_rb32(pb); /* creation time */
2316 avio_rb32(pb); /* modification time */
2318 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2319 avio_rb32(pb); /* reserved */
2321 /* highlevel (considering edits) duration in movie timebase */
2322 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2323 avio_rb32(pb); /* reserved */
2324 avio_rb32(pb); /* reserved */
2326 avio_rb16(pb); /* layer */
2327 avio_rb16(pb); /* alternate group */
2328 avio_rb16(pb); /* volume */
2329 avio_rb16(pb); /* reserved */
2331 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2332 // they're kept in fixed point format through all calculations
2333 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2334 for (i = 0; i < 3; i++) {
2335 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2336 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2337 avio_rb32(pb); // 2.30 fixed point (not used)
2340 width = avio_rb32(pb); // 16.16 fixed point track width
2341 height = avio_rb32(pb); // 16.16 fixed point track height
2342 sc->width = width >> 16;
2343 sc->height = height >> 16;
2345 //Assign clockwise rotate values based on transform matrix so that
2346 //we can compensate for iPhone orientation during capture.
2348 if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2349 av_dict_set(&st->metadata, "rotate", "90", 0);
2352 if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2353 av_dict_set(&st->metadata, "rotate", "180", 0);
2356 if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2357 av_dict_set(&st->metadata, "rotate", "270", 0);
2360 // transform the display width/height according to the matrix
2361 // skip this if the display matrix is the default identity matrix
2362 // or if it is rotating the picture, ex iPhone 3GS
2363 // to keep the same scale, use [width height 1<<16]
2364 if (width && height &&
2365 ((display_matrix[0][0] != 65536 ||
2366 display_matrix[1][1] != 65536) &&
2367 !display_matrix[0][1] &&
2368 !display_matrix[1][0] &&
2369 !display_matrix[2][0] && !display_matrix[2][1])) {
2370 for (i = 0; i < 2; i++)
2372 (int64_t) width * display_matrix[0][i] +
2373 (int64_t) height * display_matrix[1][i] +
2374 ((int64_t) display_matrix[2][i] << 16);
2376 //sample aspect ratio is new width/height divided by old width/height
2377 st->sample_aspect_ratio = av_d2q(
2378 ((double) disp_transform[0] * height) /
2379 ((double) disp_transform[1] * width), INT_MAX);
2384 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2386 MOVFragment *frag = &c->fragment;
2387 MOVTrackExt *trex = NULL;
2388 int flags, track_id, i;
2390 avio_r8(pb); /* version */
2391 flags = avio_rb24(pb);
2393 track_id = avio_rb32(pb);
2395 return AVERROR_INVALIDDATA;
2396 frag->track_id = track_id;
2397 for (i = 0; i < c->trex_count; i++)
2398 if (c->trex_data[i].track_id == frag->track_id) {
2399 trex = &c->trex_data[i];
2403 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2404 return AVERROR_INVALIDDATA;
2407 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2408 avio_rb64(pb) : frag->moof_offset;
2409 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2411 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2412 avio_rb32(pb) : trex->duration;
2413 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2414 avio_rb32(pb) : trex->size;
2415 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2416 avio_rb32(pb) : trex->flags;
2417 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2421 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2423 c->chapter_track = avio_rb32(pb);
2427 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2431 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2432 return AVERROR_INVALIDDATA;
2433 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2435 return AVERROR(ENOMEM);
2437 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2439 c->trex_data = trex;
2440 trex = &c->trex_data[c->trex_count++];
2441 avio_r8(pb); /* version */
2442 avio_rb24(pb); /* flags */
2443 trex->track_id = avio_rb32(pb);
2444 trex->stsd_id = avio_rb32(pb);
2445 trex->duration = avio_rb32(pb);
2446 trex->size = avio_rb32(pb);
2447 trex->flags = avio_rb32(pb);
2451 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2453 MOVFragment *frag = &c->fragment;
2454 AVStream *st = NULL;
2455 MOVStreamContext *sc;
2459 int data_offset = 0;
2460 unsigned entries, first_sample_flags = frag->flags;
2461 int flags, distance, i, found_keyframe = 0;
2463 for (i = 0; i < c->fc->nb_streams; i++) {
2464 if (c->fc->streams[i]->id == frag->track_id) {
2465 st = c->fc->streams[i];
2470 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2471 return AVERROR_INVALIDDATA;
2474 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2476 avio_r8(pb); /* version */
2477 flags = avio_rb24(pb);
2478 entries = avio_rb32(pb);
2479 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2481 /* Always assume the presence of composition time offsets.
2482 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2483 * 1) in the initial movie, there are no samples.
2484 * 2) in the first movie fragment, there is only one sample without composition time offset.
2485 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2486 if (!sc->ctts_count && sc->sample_count)
2488 /* Complement ctts table if moov atom doesn't have ctts atom. */
2489 ctts_data = av_malloc(sizeof(*sc->ctts_data));
2491 return AVERROR(ENOMEM);
2492 sc->ctts_data = ctts_data;
2493 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2494 sc->ctts_data[sc->ctts_count].duration = 0;
2497 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2498 return AVERROR_INVALIDDATA;
2499 ctts_data = av_realloc(sc->ctts_data,
2500 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2502 return AVERROR(ENOMEM);
2503 sc->ctts_data = ctts_data;
2505 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2506 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2507 dts = sc->track_end - sc->time_offset;
2508 offset = frag->base_data_offset + data_offset;
2510 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2511 for (i = 0; i < entries && !pb->eof_reached; i++) {
2512 unsigned sample_size = frag->size;
2513 int sample_flags = i ? frag->flags : first_sample_flags;
2514 unsigned sample_duration = frag->duration;
2517 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2518 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2519 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2520 sc->ctts_data[sc->ctts_count].count = 1;
2521 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2524 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2526 else if (!found_keyframe)
2527 keyframe = found_keyframe =
2528 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2529 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2532 av_add_index_entry(st, offset, dts, sample_size, distance,
2533 keyframe ? AVINDEX_KEYFRAME : 0);
2534 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2535 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2536 offset, dts, sample_size, distance, keyframe);
2538 dts += sample_duration;
2539 offset += sample_size;
2540 sc->data_size += sample_size;
2543 if (pb->eof_reached)
2546 frag->moof_offset = offset;
2547 st->duration = sc->track_end = dts + sc->time_offset;
2551 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2552 /* like the files created with Adobe Premiere 5.0, for samples see */
2553 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2554 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2559 return 0; /* continue */
2560 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2561 avio_skip(pb, atom.size - 4);
2564 atom.type = avio_rl32(pb);
2566 if (atom.type != MKTAG('m','d','a','t')) {
2567 avio_skip(pb, atom.size);
2570 err = mov_read_mdat(c, pb, atom);
2574 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2579 uint8_t *moov_data; /* uncompressed data */
2580 long cmov_len, moov_len;
2583 avio_rb32(pb); /* dcom atom */
2584 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2585 return AVERROR_INVALIDDATA;
2586 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2587 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
2588 return AVERROR_INVALIDDATA;
2590 avio_rb32(pb); /* cmvd atom */
2591 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2592 return AVERROR_INVALIDDATA;
2593 moov_len = avio_rb32(pb); /* uncompressed size */
2594 cmov_len = atom.size - 6 * 4;
2596 cmov_data = av_malloc(cmov_len);
2598 return AVERROR(ENOMEM);
2599 moov_data = av_malloc(moov_len);
2602 return AVERROR(ENOMEM);
2604 avio_read(pb, cmov_data, cmov_len);
2605 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2606 goto free_and_return;
2607 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2608 goto free_and_return;
2609 atom.type = MKTAG('m','o','o','v');
2610 atom.size = moov_len;
2611 ret = mov_read_default(c, &ctx, atom);
2617 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2618 return AVERROR(ENOSYS);
2622 /* edit list atom */
2623 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2625 MOVStreamContext *sc;
2626 int i, edit_count, version, edit_start_index = 0;
2627 int unsupported = 0;
2629 if (c->fc->nb_streams < 1 || c->ignore_editlist)
2631 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2633 version = avio_r8(pb); /* version */
2634 avio_rb24(pb); /* flags */
2635 edit_count = avio_rb32(pb); /* entries */
2637 if ((uint64_t)edit_count*12+8 > atom.size)
2638 return AVERROR_INVALIDDATA;
2640 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2641 for (i=0; i<edit_count; i++){
2646 duration = avio_rb64(pb);
2647 time = avio_rb64(pb);
2649 duration = avio_rb32(pb); /* segment duration */
2650 time = (int32_t)avio_rb32(pb); /* media time */
2652 rate = avio_rb32(pb);
2653 if (i == 0 && time == -1) {
2654 sc->empty_duration = duration;
2655 edit_start_index = 1;
2656 } else if (i == edit_start_index && time >= 0)
2657 sc->start_time = time;
2661 av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
2662 duration, time, rate / 65536.0);
2666 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2667 "a/v desync might occur, patch welcome\n");
2672 static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2677 ff_mov_read_chan(c->fc, pb, c->fc->streams[0], atom.size - 4);
2681 static int mov_read_tref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2684 MOVStreamContext *sc;
2686 if (c->fc->nb_streams < 1)
2687 return AVERROR_INVALIDDATA;
2688 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
2690 size = avio_rb32(pb);
2694 sc->trefs_count = (size - 4) / 8;
2695 sc->trefs = av_malloc(sc->trefs_count * sizeof(*sc->trefs));
2697 return AVERROR(ENOMEM);
2699 sc->tref_type = avio_rl32(pb);
2700 for (i = 0; i < sc->trefs_count; i++)
2701 sc->trefs[i] = avio_rb32(pb);
2705 static const MOVParseTableEntry mov_default_parse_table[] = {
2706 { MKTAG('A','C','L','R'), mov_read_avid },
2707 { MKTAG('A','P','R','G'), mov_read_avid },
2708 { MKTAG('A','A','L','P'), mov_read_avid },
2709 { MKTAG('A','R','E','S'), mov_read_avid },
2710 { MKTAG('a','v','s','s'), mov_read_avss },
2711 { MKTAG('c','h','p','l'), mov_read_chpl },
2712 { MKTAG('c','o','6','4'), mov_read_stco },
2713 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2714 { MKTAG('d','i','n','f'), mov_read_default },
2715 { MKTAG('d','r','e','f'), mov_read_dref },
2716 { MKTAG('e','d','t','s'), mov_read_default },
2717 { MKTAG('e','l','s','t'), mov_read_elst },
2718 { MKTAG('e','n','d','a'), mov_read_enda },
2719 { MKTAG('f','i','e','l'), mov_read_fiel },
2720 { MKTAG('f','t','y','p'), mov_read_ftyp },
2721 { MKTAG('g','l','b','l'), mov_read_glbl },
2722 { MKTAG('h','d','l','r'), mov_read_hdlr },
2723 { MKTAG('i','l','s','t'), mov_read_ilst },
2724 { MKTAG('j','p','2','h'), mov_read_jp2h },
2725 { MKTAG('m','d','a','t'), mov_read_mdat },
2726 { MKTAG('m','d','h','d'), mov_read_mdhd },
2727 { MKTAG('m','d','i','a'), mov_read_default },
2728 { MKTAG('m','e','t','a'), mov_read_meta },
2729 { MKTAG('m','i','n','f'), mov_read_default },
2730 { MKTAG('m','o','o','f'), mov_read_moof },
2731 { MKTAG('m','o','o','v'), mov_read_moov },
2732 { MKTAG('m','v','e','x'), mov_read_default },
2733 { MKTAG('m','v','h','d'), mov_read_mvhd },
2734 { MKTAG('S','M','I',' '), mov_read_svq3 },
2735 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
2736 { MKTAG('a','v','c','C'), mov_read_glbl },
2737 { MKTAG('p','a','s','p'), mov_read_pasp },
2738 { MKTAG('s','t','b','l'), mov_read_default },
2739 { MKTAG('s','t','c','o'), mov_read_stco },
2740 { MKTAG('s','t','p','s'), mov_read_stps },
2741 { MKTAG('s','t','r','f'), mov_read_strf },
2742 { MKTAG('s','t','s','c'), mov_read_stsc },
2743 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2744 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2745 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2746 { MKTAG('s','t','t','s'), mov_read_stts },
2747 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2748 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2749 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2750 { MKTAG('t','r','a','k'), mov_read_trak },
2751 { MKTAG('t','r','a','f'), mov_read_default },
2752 { MKTAG('t','r','e','f'), mov_read_tref },
2753 { MKTAG('c','h','a','p'), mov_read_chap },
2754 { MKTAG('t','r','e','x'), mov_read_trex },
2755 { MKTAG('t','r','u','n'), mov_read_trun },
2756 { MKTAG('u','d','t','a'), mov_read_default },
2757 { MKTAG('w','a','v','e'), mov_read_wave },
2758 { MKTAG('e','s','d','s'), mov_read_esds },
2759 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2760 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2761 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2762 { MKTAG('w','f','e','x'), mov_read_wfex },
2763 { MKTAG('c','m','o','v'), mov_read_cmov },
2764 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2765 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2766 { MKTAG('s','b','g','p'), mov_read_sbgp },
2770 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2772 int64_t total_size = 0;
2777 atom.size = INT64_MAX;
2778 while (total_size + 8 <= atom.size && !url_feof(pb)) {
2779 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
2782 if (atom.size >= 8) {
2783 a.size = avio_rb32(pb);
2784 a.type = avio_rl32(pb);
2785 if (atom.type != MKTAG('r','o','o','t') &&
2786 atom.type != MKTAG('m','o','o','v'))
2788 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
2790 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
2796 if (a.size == 1) { /* 64 bit extended size */
2797 a.size = avio_rb64(pb) - 8;
2801 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
2802 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
2804 a.size = atom.size - total_size + 8;
2809 a.size = FFMIN(a.size, atom.size - total_size);
2811 for (i = 0; mov_default_parse_table[i].type; i++)
2812 if (mov_default_parse_table[i].type == a.type) {
2813 parse = mov_default_parse_table[i].parse;
2817 // container is user data
2818 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
2819 atom.type == MKTAG('i','l','s','t')))
2820 parse = mov_read_udta_string;
2822 if (!parse) { /* skip leaf atoms data */
2823 avio_skip(pb, a.size);
2825 int64_t start_pos = avio_tell(pb);
2827 int err = parse(c, pb, a);
2830 if (c->found_moov && c->found_mdat &&
2831 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
2832 start_pos + a.size == avio_size(pb))) {
2833 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
2834 c->next_root_atom = start_pos + a.size;
2837 left = a.size - avio_tell(pb) + start_pos;
2838 if (left > 0) /* skip garbage at atom end */
2839 avio_skip(pb, left);
2841 av_log(c->fc, AV_LOG_DEBUG, "undoing overread of %"PRId64" in '%.4s'\n", -left, (char*)&a.type);
2842 avio_seek(pb, left, SEEK_CUR);
2846 total_size += a.size;
2849 if (total_size < atom.size && atom.size < 0x7ffff)
2850 avio_skip(pb, atom.size - total_size);
2855 static int mov_probe(AVProbeData *p)
2857 unsigned int offset;
2861 /* check file header */
2864 /* ignore invalid offset */
2865 if ((offset + 8) > (unsigned int)p->buf_size)
2867 tag = AV_RL32(p->buf + offset + 4);
2869 /* check for obvious tags */
2870 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2871 case MKTAG('m','o','o','v'):
2872 case MKTAG('m','d','a','t'):
2873 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2874 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2875 case MKTAG('f','t','y','p'):
2876 return AVPROBE_SCORE_MAX;
2877 /* those are more common words, so rate then a bit less */
2878 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2879 case MKTAG('w','i','d','e'):
2880 case MKTAG('f','r','e','e'):
2881 case MKTAG('j','u','n','k'):
2882 case MKTAG('p','i','c','t'):
2883 return AVPROBE_SCORE_MAX - 5;
2884 case MKTAG(0x82,0x82,0x7f,0x7d):
2885 case MKTAG('s','k','i','p'):
2886 case MKTAG('u','u','i','d'):
2887 case MKTAG('p','r','f','l'):
2888 offset = AV_RB32(p->buf+offset) + offset;
2889 /* if we only find those cause probedata is too small at least rate them */
2890 score = AVPROBE_SCORE_MAX - 50;
2893 /* unrecognized tag */
2899 // must be done after parsing all trak because there's no order requirement
2900 static void mov_read_chapters(AVFormatContext *s)
2902 MOVContext *mov = s->priv_data;
2903 AVStream *st = NULL;
2904 MOVStreamContext *sc;
2908 for (i = 0; i < s->nb_streams; i++)
2909 if (s->streams[i]->id == mov->chapter_track) {
2914 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2918 st->discard = AVDISCARD_ALL;
2920 cur_pos = avio_tell(sc->pb);
2922 for (i = 0; i < st->nb_index_entries; i++) {
2923 AVIndexEntry *sample = &st->index_entries[i];
2924 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2929 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2930 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2934 // the first two bytes are the length of the title
2935 len = avio_rb16(sc->pb);
2936 if (len > sample->size-2)
2938 title_len = 2*len + 1;
2939 if (!(title = av_mallocz(title_len)))
2942 // The samples could theoretically be in any encoding if there's an encd
2943 // atom following, but in practice are only utf-8 or utf-16, distinguished
2944 // instead by the presence of a BOM
2948 ch = avio_rb16(sc->pb);
2950 avio_get_str16be(sc->pb, len, title, title_len);
2951 else if (ch == 0xfffe)
2952 avio_get_str16le(sc->pb, len, title, title_len);
2955 if (len == 1 || len == 2)
2958 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
2962 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2966 avio_seek(sc->pb, cur_pos, SEEK_SET);
2969 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
2970 uint32_t value, int flags)
2973 char buf[AV_TIMECODE_STR_SIZE];
2974 AVRational rate = {st->codec->time_base.den,
2975 st->codec->time_base.num};
2976 int ret = av_timecode_init(&tc, rate, flags, 0, s);
2979 av_dict_set(&st->metadata, "timecode",
2980 av_timecode_make_string(&tc, buf, value), 0);
2984 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
2986 MOVStreamContext *sc = st->priv_data;
2988 int64_t cur_pos = avio_tell(sc->pb);
2991 if (!st->nb_index_entries)
2994 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
2995 value = avio_rb32(s->pb);
2997 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
2998 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
2999 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3001 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3002 * not the case) and thus assume "frame number format" instead of QT one.
3003 * No sample with tmcd track can be found with a QT timecode at the moment,
3004 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3006 parse_timecode_in_framenum_format(s, st, value, flags);
3008 avio_seek(sc->pb, cur_pos, SEEK_SET);
3012 static int mov_read_close(AVFormatContext *s)
3014 MOVContext *mov = s->priv_data;
3017 for (i = 0; i < s->nb_streams; i++) {
3018 AVStream *st = s->streams[i];
3019 MOVStreamContext *sc = st->priv_data;
3021 av_freep(&sc->ctts_data);
3022 for (j = 0; j < sc->drefs_count; j++) {
3023 av_freep(&sc->drefs[j].path);
3024 av_freep(&sc->drefs[j].dir);
3026 av_freep(&sc->drefs);
3027 av_freep(&sc->trefs);
3028 if (sc->pb && sc->pb != s->pb)
3031 av_freep(&sc->chunk_offsets);
3032 av_freep(&sc->keyframes);
3033 av_freep(&sc->sample_sizes);
3034 av_freep(&sc->stps_data);
3035 av_freep(&sc->stsc_data);
3036 av_freep(&sc->stts_data);
3039 if (mov->dv_demux) {
3040 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
3041 av_freep(&mov->dv_fctx->streams[i]->codec);
3042 av_freep(&mov->dv_fctx->streams[i]);
3044 av_freep(&mov->dv_fctx);
3045 av_freep(&mov->dv_demux);
3048 av_freep(&mov->trex_data);
3053 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3057 for (i = 0; i < s->nb_streams; i++) {
3058 AVStream *st = s->streams[i];
3059 MOVStreamContext *sc = st->priv_data;
3061 if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
3063 for (j = 0; j < sc->trefs_count; j++)
3064 if (tmcd_id == sc->trefs[j])
3070 /* look for a tmcd track not referenced by any video track, and export it globally */
3071 static void export_orphan_timecode(AVFormatContext *s)
3075 for (i = 0; i < s->nb_streams; i++) {
3076 AVStream *st = s->streams[i];
3078 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3079 !tmcd_is_referenced(s, i + 1)) {
3080 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3082 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3089 static int mov_read_header(AVFormatContext *s)
3091 MOVContext *mov = s->priv_data;
3092 AVIOContext *pb = s->pb;
3094 MOVAtom atom = { AV_RL32("root") };
3097 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3099 atom.size = avio_size(pb);
3101 atom.size = INT64_MAX;
3103 /* check MOV header */
3104 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3105 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3109 if (!mov->found_moov) {
3110 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3112 return AVERROR_INVALIDDATA;
3114 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3117 if (mov->chapter_track > 0)
3118 mov_read_chapters(s);
3119 for (i = 0; i < s->nb_streams; i++)
3120 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3121 mov_read_timecode_track(s, s->streams[i]);
3124 /* copy timecode metadata from tmcd tracks to the related video streams */
3125 for (i = 0; i < s->nb_streams; i++) {
3126 AVStream *st = s->streams[i];
3127 MOVStreamContext *sc = st->priv_data;
3128 if (sc->tref_type == AV_RL32("tmcd") && sc->trefs_count) {
3129 AVDictionaryEntry *tcr;
3130 int tmcd_st_id = sc->trefs[0] - 1;
3132 if (tmcd_st_id < 0 || tmcd_st_id >= s->nb_streams)
3134 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
3136 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
3139 export_orphan_timecode(s);
3141 for (i = 0; i < s->nb_streams; i++) {
3142 AVStream *st = s->streams[i];
3143 MOVStreamContext *sc = st->priv_data;
3144 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
3145 st->skip_samples = sc->start_pad;
3149 if (mov->trex_data) {
3150 for (i = 0; i < s->nb_streams; i++) {
3151 AVStream *st = s->streams[i];
3152 MOVStreamContext *sc = st->priv_data;
3154 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3161 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3163 AVIndexEntry *sample = NULL;
3164 int64_t best_dts = INT64_MAX;
3166 for (i = 0; i < s->nb_streams; i++) {
3167 AVStream *avst = s->streams[i];
3168 MOVStreamContext *msc = avst->priv_data;
3169 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3170 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3171 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3172 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3173 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3175 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3176 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3177 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3178 sample = current_sample;
3187 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3189 MOVContext *mov = s->priv_data;
3190 MOVStreamContext *sc;
3191 AVIndexEntry *sample;
3192 AVStream *st = NULL;
3196 sample = mov_find_next_sample(s, &st);
3198 mov->found_mdat = 0;
3199 if (!mov->next_root_atom)
3201 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3202 mov->next_root_atom = 0;
3203 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3206 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3210 /* must be done just before reading, to avoid infinite loop on sample */
3211 sc->current_sample++;
3213 if (st->discard != AVDISCARD_ALL) {
3214 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3215 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3216 sc->ffindex, sample->pos);
3217 return AVERROR_INVALIDDATA;
3219 ret = av_get_packet(sc->pb, pkt, sample->size);
3222 if (sc->has_palette) {
3225 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3227 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3229 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3230 sc->has_palette = 0;
3233 #if CONFIG_DV_DEMUXER
3234 if (mov->dv_demux && sc->dv_audio_container) {
3235 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
3238 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3245 pkt->stream_index = sc->ffindex;
3246 pkt->dts = sample->timestamp;
3247 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3248 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3249 /* update ctts context */
3251 if (sc->ctts_index < sc->ctts_count &&
3252 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3254 sc->ctts_sample = 0;
3257 pkt->dts = AV_NOPTS_VALUE;
3259 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3260 st->index_entries[sc->current_sample].timestamp : st->duration;
3261 pkt->duration = next_dts - pkt->dts;
3262 pkt->pts = pkt->dts;
3264 if (st->discard == AVDISCARD_ALL)
3266 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3267 pkt->pos = sample->pos;
3268 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3269 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3273 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3275 MOVStreamContext *sc = st->priv_data;
3276 int sample, time_sample;
3279 sample = av_index_search_timestamp(st, timestamp, flags);
3280 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3281 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3283 if (sample < 0) /* not sure what to do */
3284 return AVERROR_INVALIDDATA;
3285 sc->current_sample = sample;
3286 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3287 /* adjust ctts index */
3288 if (sc->ctts_data) {
3290 for (i = 0; i < sc->ctts_count; i++) {
3291 int next = time_sample + sc->ctts_data[i].count;
3292 if (next > sc->current_sample) {
3294 sc->ctts_sample = sc->current_sample - time_sample;
3303 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3306 int64_t seek_timestamp, timestamp;
3310 if (stream_index >= s->nb_streams)
3311 return AVERROR_INVALIDDATA;
3313 st = s->streams[stream_index];
3314 sample = mov_seek_stream(s, st, sample_time, flags);
3318 /* adjust seek timestamp to found sample timestamp */
3319 seek_timestamp = st->index_entries[sample].timestamp;
3321 for (i = 0; i < s->nb_streams; i++) {
3322 MOVStreamContext *sc = s->streams[i]->priv_data;
3324 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
3326 if (stream_index == i)
3329 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3330 mov_seek_stream(s, st, timestamp, flags);
3335 static const AVOption options[] = {
3336 {"use_absolute_path",
3337 "allow using absolute path when opening alias, this is a possible security issue",
3338 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
3339 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3340 {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
3341 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3345 static const AVClass class = {
3346 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3347 .item_name = av_default_item_name,
3349 .version = LIBAVUTIL_VERSION_INT,
3352 AVInputFormat ff_mov_demuxer = {
3353 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3354 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3355 .priv_data_size = sizeof(MOVContext),
3356 .read_probe = mov_probe,
3357 .read_header = mov_read_header,
3358 .read_packet = mov_read_packet,
3359 .read_close = mov_read_close,
3360 .read_seek = mov_read_seek,
3361 .priv_class = &class,