3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * first version by Francois Revol <revol@free.fr>
7 * seek function by Gael Chardon <gael.dev@4now.net>
9 * This file is part of Libav.
11 * Libav is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * Libav is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with Libav; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 //#define MOV_EXPORT_ALL_METADATA
30 #include "libavutil/attributes.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/intfloat.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/dict.h"
37 #include "libavcodec/ac3tab.h"
40 #include "avio_internal.h"
43 #include "libavcodec/get_bits.h"
51 #include "qtpalette.h"
57 /* those functions parse an atom */
58 /* links atom IDs to parse functions */
59 typedef struct MOVParseTableEntry {
61 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
64 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
66 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
67 unsigned len, const char *key)
71 short current, total = 0;
72 avio_rb16(pb); // unknown
73 current = avio_rb16(pb);
75 total = avio_rb16(pb);
77 snprintf(buf, sizeof(buf), "%d", current);
79 snprintf(buf, sizeof(buf), "%d/%d", current, total);
80 av_dict_set(&c->fc->metadata, key, buf, 0);
85 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
86 unsigned len, const char *key)
90 /* bypass padding bytes */
95 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
96 av_dict_set(&c->fc->metadata, key, buf, 0);
101 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
102 unsigned len, const char *key)
106 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
107 av_dict_set(&c->fc->metadata, key, buf, 0);
112 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
113 unsigned len, const char *key)
118 avio_r8(pb); // unknown
121 if (genre < 1 || genre > ID3v1_GENRE_MAX)
123 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
124 av_dict_set(&c->fc->metadata, key, buf, 0);
129 static const uint32_t mac_to_unicode[128] = {
130 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
131 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
132 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
133 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
134 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
135 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
136 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
137 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
138 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
139 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
140 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
141 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
142 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
143 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
144 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
145 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
148 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
149 char *dst, int dstlen)
152 char *end = dst+dstlen-1;
155 for (i = 0; i < len; i++) {
156 uint8_t t, c = avio_r8(pb);
157 if (c < 0x80 && p < end)
160 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
166 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
170 MOVStreamContext *sc;
175 case 0xd: id = AV_CODEC_ID_MJPEG; break;
176 case 0xe: id = AV_CODEC_ID_PNG; break;
177 case 0x1b: id = AV_CODEC_ID_BMP; break;
179 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
184 st = avformat_new_stream(c->fc, NULL);
186 return AVERROR(ENOMEM);
187 sc = av_mallocz(sizeof(*sc));
189 return AVERROR(ENOMEM);
192 ret = av_get_packet(pb, &pkt, len);
196 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
198 st->attached_pic = pkt;
199 st->attached_pic.stream_index = st->index;
200 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
202 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
203 st->codec->codec_id = id;
208 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
210 #ifdef MOV_EXPORT_ALL_METADATA
213 char str[1024], key2[16], language[4] = {0};
214 const char *key = NULL;
215 uint16_t langcode = 0;
216 uint32_t data_type = 0, str_size;
217 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
220 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
221 case MKTAG(0xa9,'a','u','t'):
222 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
223 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
224 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
225 case MKTAG( 'c','p','r','t'):
226 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
227 case MKTAG(0xa9,'c','m','t'):
228 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
229 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
230 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
231 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
232 case MKTAG( 'g','n','r','e'): key = "genre";
233 parse = mov_metadata_gnre; break;
234 case MKTAG(0xa9,'t','o','o'):
235 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
236 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
237 case MKTAG( 'd','e','s','c'): key = "description";break;
238 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
239 case MKTAG( 't','v','s','h'): key = "show"; break;
240 case MKTAG( 't','v','e','n'): key = "episode_id";break;
241 case MKTAG( 't','v','n','n'): key = "network"; break;
242 case MKTAG( 't','r','k','n'): key = "track";
243 parse = mov_metadata_track_or_disc_number; break;
244 case MKTAG( 'd','i','s','k'): key = "disc";
245 parse = mov_metadata_track_or_disc_number; break;
246 case MKTAG( 't','v','e','s'): key = "episode_sort";
247 parse = mov_metadata_int8_bypass_padding; break;
248 case MKTAG( 't','v','s','n'): key = "season_number";
249 parse = mov_metadata_int8_bypass_padding; break;
250 case MKTAG( 's','t','i','k'): key = "media_type";
251 parse = mov_metadata_int8_no_padding; break;
252 case MKTAG( 'h','d','v','d'): key = "hd_video";
253 parse = mov_metadata_int8_no_padding; break;
254 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
255 parse = mov_metadata_int8_no_padding; break;
258 if (c->itunes_metadata && atom.size > 8) {
259 int data_size = avio_rb32(pb);
260 int tag = avio_rl32(pb);
261 if (tag == MKTAG('d','a','t','a')) {
262 data_type = avio_rb32(pb); // type
263 avio_rb32(pb); // unknown
264 str_size = data_size - 16;
267 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
268 int ret = mov_read_covr(c, pb, data_type, str_size);
270 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
275 } else if (atom.size > 4 && key && !c->itunes_metadata) {
276 str_size = avio_rb16(pb); // string length
277 langcode = avio_rb16(pb);
278 ff_mov_lang_to_iso639(langcode, language);
281 str_size = atom.size;
283 #ifdef MOV_EXPORT_ALL_METADATA
285 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
293 return AVERROR_INVALIDDATA;
295 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
298 parse(c, pb, str_size, key);
300 if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
301 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
303 avio_read(pb, str, str_size);
306 av_dict_set(&c->fc->metadata, key, str, 0);
307 if (*language && strcmp(language, "und")) {
308 snprintf(key2, sizeof(key2), "%s-%s", key, language);
309 av_dict_set(&c->fc->metadata, key2, str, 0);
312 av_dlog(c->fc, "lang \"%3s\" ", language);
313 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
314 key, str, (char*)&atom.type, str_size, atom.size);
319 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
322 int i, nb_chapters, str_len, version;
325 if ((atom.size -= 5) < 0)
328 version = avio_r8(pb);
331 avio_rb32(pb); // ???
332 nb_chapters = avio_r8(pb);
334 for (i = 0; i < nb_chapters; i++) {
338 start = avio_rb64(pb);
339 str_len = avio_r8(pb);
341 if ((atom.size -= 9+str_len) < 0)
344 avio_read(pb, str, str_len);
346 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
351 #define MIN_DATA_ENTRY_BOX_SIZE 12
352 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
355 MOVStreamContext *sc;
358 if (c->fc->nb_streams < 1)
360 st = c->fc->streams[c->fc->nb_streams-1];
363 avio_rb32(pb); // version + flags
364 entries = avio_rb32(pb);
365 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
366 entries >= UINT_MAX / sizeof(*sc->drefs))
367 return AVERROR_INVALIDDATA;
369 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
371 return AVERROR(ENOMEM);
372 sc->drefs_count = entries;
374 for (i = 0; i < sc->drefs_count; i++) {
375 MOVDref *dref = &sc->drefs[i];
376 uint32_t size = avio_rb32(pb);
377 int64_t next = avio_tell(pb) + size - 4;
380 return AVERROR_INVALIDDATA;
382 dref->type = avio_rl32(pb);
383 avio_rb32(pb); // version + flags
384 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
386 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
387 /* macintosh alias record */
388 uint16_t volume_len, len;
393 volume_len = avio_r8(pb);
394 volume_len = FFMIN(volume_len, 27);
395 avio_read(pb, dref->volume, 27);
396 dref->volume[volume_len] = 0;
397 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
402 len = FFMIN(len, 63);
403 avio_read(pb, dref->filename, 63);
404 dref->filename[len] = 0;
405 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
409 /* read next level up_from_alias/down_to_target */
410 dref->nlvl_from = avio_rb16(pb);
411 dref->nlvl_to = avio_rb16(pb);
412 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
413 dref->nlvl_from, dref->nlvl_to);
417 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
420 type = avio_rb16(pb);
422 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
425 if (type == 2) { // absolute path
427 dref->path = av_mallocz(len+1);
429 return AVERROR(ENOMEM);
430 avio_read(pb, dref->path, len);
431 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
433 memmove(dref->path, dref->path+volume_len, len);
436 for (j = 0; j < len; j++)
437 if (dref->path[j] == ':')
439 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
440 } else if (type == 0) { // directory name
442 dref->dir = av_malloc(len+1);
444 return AVERROR(ENOMEM);
445 avio_read(pb, dref->dir, len);
447 for (j = 0; j < len; j++)
448 if (dref->dir[j] == ':')
450 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
455 avio_seek(pb, next, SEEK_SET);
460 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
464 uint32_t av_unused ctype;
466 if (c->fc->nb_streams < 1) // meta before first trak
469 st = c->fc->streams[c->fc->nb_streams-1];
471 avio_r8(pb); /* version */
472 avio_rb24(pb); /* flags */
475 ctype = avio_rl32(pb);
476 type = avio_rl32(pb); /* component subtype */
478 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
479 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
481 if (type == MKTAG('v','i','d','e'))
482 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
483 else if (type == MKTAG('s','o','u','n'))
484 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
485 else if (type == MKTAG('m','1','a',' '))
486 st->codec->codec_id = AV_CODEC_ID_MP2;
487 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
488 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
490 avio_rb32(pb); /* component manufacture */
491 avio_rb32(pb); /* component flags */
492 avio_rb32(pb); /* component flags mask */
497 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
502 if (fc->nb_streams < 1)
504 st = fc->streams[fc->nb_streams-1];
506 avio_rb32(pb); /* version + flags */
507 ff_mp4_read_descr(fc, pb, &tag);
508 if (tag == MP4ESDescrTag) {
509 ff_mp4_parse_es_descr(pb, NULL);
511 avio_rb16(pb); /* ID */
513 ff_mp4_read_descr(fc, pb, &tag);
514 if (tag == MP4DecConfigDescrTag)
515 ff_mp4_read_dec_config_descr(fc, st, pb);
519 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
521 return ff_mov_read_esds(c->fc, pb, atom);
524 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
527 int ac3info, acmod, lfeon, bsmod;
529 if (c->fc->nb_streams < 1)
531 st = c->fc->streams[c->fc->nb_streams-1];
533 ac3info = avio_rb24(pb);
534 bsmod = (ac3info >> 14) & 0x7;
535 acmod = (ac3info >> 11) & 0x7;
536 lfeon = (ac3info >> 10) & 0x1;
537 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
538 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
540 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
541 st->codec->audio_service_type = bsmod;
542 if (st->codec->channels > 1 && bsmod == 0x7)
543 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
548 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
551 int eac3info, acmod, lfeon, bsmod;
553 if (c->fc->nb_streams < 1)
555 st = c->fc->streams[c->fc->nb_streams-1];
557 /* No need to parse fields for additional independent substreams and its
558 * associated dependent substreams since libavcodec's E-AC-3 decoder
559 * does not support them yet. */
560 avio_rb16(pb); /* data_rate and num_ind_sub */
561 eac3info = avio_rb24(pb);
562 bsmod = (eac3info >> 12) & 0x1f;
563 acmod = (eac3info >> 9) & 0x7;
564 lfeon = (eac3info >> 8) & 0x1;
565 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
567 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
568 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
569 st->codec->audio_service_type = bsmod;
570 if (st->codec->channels > 1 && bsmod == 0x7)
571 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
576 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
580 if (c->fc->nb_streams < 1)
582 st = c->fc->streams[c->fc->nb_streams-1];
587 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
592 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
596 if (c->fc->nb_streams < 1)
598 st = c->fc->streams[c->fc->nb_streams-1];
600 ff_get_wav_header(pb, st->codec, atom.size);
605 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
607 const int num = avio_rb32(pb);
608 const int den = avio_rb32(pb);
611 if (c->fc->nb_streams < 1)
613 st = c->fc->streams[c->fc->nb_streams-1];
615 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
616 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
617 av_log(c->fc, AV_LOG_WARNING,
618 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
619 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
621 } else if (den != 0) {
622 st->sample_aspect_ratio.num = num;
623 st->sample_aspect_ratio.den = den;
628 /* this atom contains actual media data */
629 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
631 if (atom.size == 0) /* wrong one (MP4) */
634 return 0; /* now go for moov */
637 /* read major brand, minor version and compatible brands and store them as metadata */
638 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
642 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
643 char* comp_brands_str;
644 uint8_t type[5] = {0};
646 avio_read(pb, type, 4);
647 if (strcmp(type, "qt "))
649 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
650 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
651 minor_ver = avio_rb32(pb); /* minor version */
652 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
653 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
655 comp_brand_size = atom.size - 8;
656 if (comp_brand_size < 0)
657 return AVERROR_INVALIDDATA;
658 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
659 if (!comp_brands_str)
660 return AVERROR(ENOMEM);
661 avio_read(pb, comp_brands_str, comp_brand_size);
662 comp_brands_str[comp_brand_size] = 0;
663 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
664 av_freep(&comp_brands_str);
669 /* this atom should contain all header atoms */
670 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
674 if ((ret = mov_read_default(c, pb, atom)) < 0)
676 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
677 /* so we don't parse the whole file if over a network */
679 return 0; /* now go for mdat */
682 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
684 c->fragment.moof_offset = avio_tell(pb) - 8;
685 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
686 return mov_read_default(c, pb, atom);
689 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
694 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
697 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
698 av_dict_set(metadata, "creation_time", buffer, 0);
702 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
705 MOVStreamContext *sc;
707 char language[4] = {0};
709 time_t creation_time;
711 if (c->fc->nb_streams < 1)
713 st = c->fc->streams[c->fc->nb_streams-1];
716 if (sc->time_scale) {
717 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
718 return AVERROR_INVALIDDATA;
721 version = avio_r8(pb);
723 avpriv_request_sample(c->fc, "Version %d", version);
724 return AVERROR_PATCHWELCOME;
726 avio_rb24(pb); /* flags */
728 creation_time = avio_rb64(pb);
731 creation_time = avio_rb32(pb);
732 avio_rb32(pb); /* modification time */
734 mov_metadata_creation_time(&st->metadata, creation_time);
736 sc->time_scale = avio_rb32(pb);
737 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
739 lang = avio_rb16(pb); /* language */
740 if (ff_mov_lang_to_iso639(lang, language))
741 av_dict_set(&st->metadata, "language", language, 0);
742 avio_rb16(pb); /* quality */
747 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
749 time_t creation_time;
750 int version = avio_r8(pb); /* version */
751 avio_rb24(pb); /* flags */
754 creation_time = avio_rb64(pb);
757 creation_time = avio_rb32(pb);
758 avio_rb32(pb); /* modification time */
760 mov_metadata_creation_time(&c->fc->metadata, creation_time);
761 c->time_scale = avio_rb32(pb); /* time scale */
763 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
765 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
766 avio_rb32(pb); /* preferred scale */
768 avio_rb16(pb); /* preferred volume */
770 avio_skip(pb, 10); /* reserved */
772 avio_skip(pb, 36); /* display matrix */
774 avio_rb32(pb); /* preview time */
775 avio_rb32(pb); /* preview duration */
776 avio_rb32(pb); /* poster time */
777 avio_rb32(pb); /* selection time */
778 avio_rb32(pb); /* selection duration */
779 avio_rb32(pb); /* current time */
780 avio_rb32(pb); /* next track ID */
785 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
789 if (c->fc->nb_streams < 1)
791 st = c->fc->streams[c->fc->nb_streams-1];
793 if ((uint64_t)atom.size > (1<<30))
794 return AVERROR_INVALIDDATA;
796 // currently SVQ3 decoder expect full STSD header - so let's fake it
797 // this should be fixed and just SMI header should be passed
798 av_free(st->codec->extradata);
799 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
800 if (!st->codec->extradata)
801 return AVERROR(ENOMEM);
802 st->codec->extradata_size = 0x5a + atom.size;
803 memcpy(st->codec->extradata, "SVQ3", 4); // fake
804 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
805 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
809 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
814 if (c->fc->nb_streams < 1)
816 st = c->fc->streams[c->fc->nb_streams-1];
818 little_endian = avio_rb16(pb);
819 av_dlog(c->fc, "enda %d\n", little_endian);
820 if (little_endian == 1) {
821 switch (st->codec->codec_id) {
822 case AV_CODEC_ID_PCM_S24BE:
823 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
825 case AV_CODEC_ID_PCM_S32BE:
826 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
828 case AV_CODEC_ID_PCM_F32BE:
829 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
831 case AV_CODEC_ID_PCM_F64BE:
832 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
841 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
844 unsigned mov_field_order;
845 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
847 if (c->fc->nb_streams < 1) // will happen with jp2 files
849 st = c->fc->streams[c->fc->nb_streams-1];
851 return AVERROR_INVALIDDATA;
852 mov_field_order = avio_rb16(pb);
853 if ((mov_field_order & 0xFF00) == 0x0100)
854 decoded_field_order = AV_FIELD_PROGRESSIVE;
855 else if ((mov_field_order & 0xFF00) == 0x0200) {
856 switch (mov_field_order & 0xFF) {
857 case 0x01: decoded_field_order = AV_FIELD_TT;
859 case 0x06: decoded_field_order = AV_FIELD_BB;
861 case 0x09: decoded_field_order = AV_FIELD_TB;
863 case 0x0E: decoded_field_order = AV_FIELD_BT;
867 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
868 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
870 st->codec->field_order = decoded_field_order;
875 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
876 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
883 if (c->fc->nb_streams < 1) // will happen with jp2 files
885 st= c->fc->streams[c->fc->nb_streams-1];
886 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
887 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
888 return AVERROR_INVALIDDATA;
889 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
890 st->codec->extradata_size = 0;
893 buf = st->codec->extradata + st->codec->extradata_size;
894 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
895 AV_WB32( buf , atom.size + 8);
896 AV_WL32( buf + 4, atom.type);
897 avio_read(pb, buf + 8, atom.size);
901 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
905 if (c->fc->nb_streams < 1)
907 st = c->fc->streams[c->fc->nb_streams-1];
909 if ((uint64_t)atom.size > (1<<30))
910 return AVERROR_INVALIDDATA;
912 if (st->codec->codec_id == AV_CODEC_ID_QDM2 || st->codec->codec_id == AV_CODEC_ID_QDMC) {
913 // pass all frma atom to codec, needed at least for QDMC and QDM2
914 av_free(st->codec->extradata);
915 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
916 if (!st->codec->extradata)
917 return AVERROR(ENOMEM);
918 st->codec->extradata_size = atom.size;
919 avio_read(pb, st->codec->extradata, atom.size);
920 } else if (atom.size > 8) { /* to read frma, esds atoms */
922 if ((ret = mov_read_default(c, pb, atom)) < 0)
925 avio_skip(pb, atom.size);
930 * This function reads atom content and puts data in extradata without tag
931 * nor size unlike mov_read_extradata.
933 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
937 if (c->fc->nb_streams < 1)
939 st = c->fc->streams[c->fc->nb_streams-1];
941 if ((uint64_t)atom.size > (1<<30))
942 return AVERROR_INVALIDDATA;
944 if (atom.size >= 10) {
945 // Broken files created by legacy versions of libavformat will
946 // wrap a whole fiel atom inside of a glbl atom.
947 unsigned size = avio_rb32(pb);
948 unsigned type = avio_rl32(pb);
949 avio_seek(pb, -8, SEEK_CUR);
950 if (type == MKTAG('f','i','e','l') && size == atom.size)
951 return mov_read_default(c, pb, atom);
953 av_free(st->codec->extradata);
954 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
955 if (!st->codec->extradata)
956 return AVERROR(ENOMEM);
957 st->codec->extradata_size = atom.size;
958 avio_read(pb, st->codec->extradata, atom.size);
962 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
965 uint8_t profile_level;
967 if (c->fc->nb_streams < 1)
969 st = c->fc->streams[c->fc->nb_streams-1];
971 if (atom.size >= (1<<28) || atom.size < 7)
972 return AVERROR_INVALIDDATA;
974 profile_level = avio_r8(pb);
975 if ((profile_level & 0xf0) != 0xc0)
978 av_free(st->codec->extradata);
979 st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
980 if (!st->codec->extradata)
981 return AVERROR(ENOMEM);
982 st->codec->extradata_size = atom.size - 7;
983 avio_seek(pb, 6, SEEK_CUR);
984 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
989 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
990 * but can have extradata appended at the end after the 40 bytes belonging
993 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
997 if (c->fc->nb_streams < 1)
1001 st = c->fc->streams[c->fc->nb_streams-1];
1003 if ((uint64_t)atom.size > (1<<30))
1004 return AVERROR_INVALIDDATA;
1006 av_free(st->codec->extradata);
1007 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1008 if (!st->codec->extradata)
1009 return AVERROR(ENOMEM);
1010 st->codec->extradata_size = atom.size - 40;
1012 avio_read(pb, st->codec->extradata, atom.size - 40);
1016 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1019 MOVStreamContext *sc;
1020 unsigned int i, entries;
1022 if (c->fc->nb_streams < 1)
1024 st = c->fc->streams[c->fc->nb_streams-1];
1027 avio_r8(pb); /* version */
1028 avio_rb24(pb); /* flags */
1030 entries = avio_rb32(pb);
1034 if (entries >= UINT_MAX/sizeof(int64_t))
1035 return AVERROR_INVALIDDATA;
1037 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1038 if (!sc->chunk_offsets)
1039 return AVERROR(ENOMEM);
1040 sc->chunk_count = entries;
1042 if (atom.type == MKTAG('s','t','c','o'))
1043 for (i = 0; i < entries && !pb->eof_reached; i++)
1044 sc->chunk_offsets[i] = avio_rb32(pb);
1045 else if (atom.type == MKTAG('c','o','6','4'))
1046 for (i = 0; i < entries && !pb->eof_reached; i++)
1047 sc->chunk_offsets[i] = avio_rb64(pb);
1049 return AVERROR_INVALIDDATA;
1051 sc->chunk_count = i;
1053 if (pb->eof_reached)
1060 * Compute codec id for 'lpcm' tag.
1061 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1063 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1070 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1073 static int mov_codec_id(AVStream *st, uint32_t format)
1075 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1078 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1079 (format & 0xFFFF) == 'T' + ('S' << 8)))
1080 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1082 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1083 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1084 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1085 /* skip old asf mpeg4 tag */
1086 format && format != MKTAG('m','p','4','s')) {
1087 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1089 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1091 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1092 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
1093 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1095 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1099 st->codec->codec_tag = format;
1104 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1105 AVStream *st, MOVStreamContext *sc)
1107 unsigned int color_depth, len, j;
1108 int color_greyscale;
1111 avio_rb16(pb); /* version */
1112 avio_rb16(pb); /* revision level */
1113 avio_rb32(pb); /* vendor */
1114 avio_rb32(pb); /* temporal quality */
1115 avio_rb32(pb); /* spatial quality */
1117 st->codec->width = avio_rb16(pb); /* width */
1118 st->codec->height = avio_rb16(pb); /* height */
1120 avio_rb32(pb); /* horiz resolution */
1121 avio_rb32(pb); /* vert resolution */
1122 avio_rb32(pb); /* data size, always 0 */
1123 avio_rb16(pb); /* frames per samples */
1125 len = avio_r8(pb); /* codec name, pascal string */
1128 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1130 avio_skip(pb, 31 - len);
1131 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1132 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1133 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1134 /* Flash Media Server uses tag H263 with Sorenson Spark */
1135 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1136 !memcmp(st->codec->codec_name, "Sorenson H263", 13))
1137 st->codec->codec_id = AV_CODEC_ID_FLV1;
1139 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1140 color_table_id = avio_rb16(pb); /* colortable id */
1141 av_dlog(c->fc, "depth %d, ctab id %d\n",
1142 st->codec->bits_per_coded_sample, color_table_id);
1143 /* figure out the palette situation */
1144 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1145 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1147 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1148 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1149 /* for palette traversal */
1150 unsigned int color_start, color_count, color_end;
1151 unsigned char r, g, b;
1153 if (color_greyscale) {
1154 int color_index, color_dec;
1155 /* compute the greyscale palette */
1156 st->codec->bits_per_coded_sample = color_depth;
1157 color_count = 1 << color_depth;
1159 color_dec = 256 / (color_count - 1);
1160 for (j = 0; j < color_count; j++) {
1161 r = g = b = color_index;
1162 sc->palette[j] = (r << 16) | (g << 8) | (b);
1163 color_index -= color_dec;
1164 if (color_index < 0)
1167 } else if (color_table_id) {
1168 const uint8_t *color_table;
1169 /* if flag bit 3 is set, use the default palette */
1170 color_count = 1 << color_depth;
1171 if (color_depth == 2)
1172 color_table = ff_qt_default_palette_4;
1173 else if (color_depth == 4)
1174 color_table = ff_qt_default_palette_16;
1176 color_table = ff_qt_default_palette_256;
1178 for (j = 0; j < color_count; j++) {
1179 r = color_table[j * 3 + 0];
1180 g = color_table[j * 3 + 1];
1181 b = color_table[j * 3 + 2];
1182 sc->palette[j] = (r << 16) | (g << 8) | (b);
1185 /* load the palette from the file */
1186 color_start = avio_rb32(pb);
1187 color_count = avio_rb16(pb);
1188 color_end = avio_rb16(pb);
1189 if ((color_start <= 255) && (color_end <= 255)) {
1190 for (j = color_start; j <= color_end; j++) {
1191 /* each R, G, or B component is 16 bits;
1192 * only use the top 8 bits; skip alpha bytes
1202 sc->palette[j] = (r << 16) | (g << 8) | (b);
1206 sc->has_palette = 1;
1210 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1211 AVStream *st, MOVStreamContext *sc)
1213 int bits_per_sample, flags;
1214 uint16_t version = avio_rb16(pb);
1216 avio_rb16(pb); /* revision level */
1217 avio_rb32(pb); /* vendor */
1219 st->codec->channels = avio_rb16(pb); /* channel count */
1220 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1221 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1223 sc->audio_cid = avio_rb16(pb);
1224 avio_rb16(pb); /* packet size = 0 */
1226 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1228 // Read QT version 1 fields. In version 0 these do not exist.
1229 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1232 sc->samples_per_frame = avio_rb32(pb);
1233 avio_rb32(pb); /* bytes per packet */
1234 sc->bytes_per_frame = avio_rb32(pb);
1235 avio_rb32(pb); /* bytes per sample */
1236 } else if (version == 2) {
1237 avio_rb32(pb); /* sizeof struct only */
1238 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1239 st->codec->channels = avio_rb32(pb);
1240 avio_rb32(pb); /* always 0x7F000000 */
1241 st->codec->bits_per_coded_sample = avio_rb32(pb);
1243 flags = avio_rb32(pb); /* lpcm format specific flag */
1244 sc->bytes_per_frame = avio_rb32(pb);
1245 sc->samples_per_frame = avio_rb32(pb);
1246 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1247 st->codec->codec_id =
1248 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1253 switch (st->codec->codec_id) {
1254 case AV_CODEC_ID_PCM_S8:
1255 case AV_CODEC_ID_PCM_U8:
1256 if (st->codec->bits_per_coded_sample == 16)
1257 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1259 case AV_CODEC_ID_PCM_S16LE:
1260 case AV_CODEC_ID_PCM_S16BE:
1261 if (st->codec->bits_per_coded_sample == 8)
1262 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1263 else if (st->codec->bits_per_coded_sample == 24)
1264 st->codec->codec_id =
1265 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1266 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1268 /* set values for old format before stsd version 1 appeared */
1269 case AV_CODEC_ID_MACE3:
1270 sc->samples_per_frame = 6;
1271 sc->bytes_per_frame = 2 * st->codec->channels;
1273 case AV_CODEC_ID_MACE6:
1274 sc->samples_per_frame = 6;
1275 sc->bytes_per_frame = 1 * st->codec->channels;
1277 case AV_CODEC_ID_ADPCM_IMA_QT:
1278 sc->samples_per_frame = 64;
1279 sc->bytes_per_frame = 34 * st->codec->channels;
1281 case AV_CODEC_ID_GSM:
1282 sc->samples_per_frame = 160;
1283 sc->bytes_per_frame = 33;
1289 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1290 if (bits_per_sample) {
1291 st->codec->bits_per_coded_sample = bits_per_sample;
1292 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1296 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1297 AVStream *st, MOVStreamContext *sc,
1300 // ttxt stsd contains display flags, justification, background
1301 // color, fonts, and default styles, so fake an atom to read it
1302 MOVAtom fake_atom = { .size = size };
1303 // mp4s contains a regular esds atom
1304 if (st->codec->codec_tag != AV_RL32("mp4s"))
1305 mov_read_glbl(c, pb, fake_atom);
1306 st->codec->width = sc->width;
1307 st->codec->height = sc->height;
1310 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1311 AVStream *st, MOVStreamContext *sc,
1314 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1315 st->codec->extradata_size = size;
1316 st->codec->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
1317 if (!st->codec->extradata)
1318 return AVERROR(ENOMEM);
1319 avio_read(pb, st->codec->extradata, size);
1321 /* other codec type, just skip (rtp, mp4s ...) */
1322 avio_skip(pb, size);
1327 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1328 AVStream *st, MOVStreamContext *sc)
1330 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1331 !st->codec->sample_rate && sc->time_scale > 1)
1332 st->codec->sample_rate = sc->time_scale;
1334 /* special codec parameters handling */
1335 switch (st->codec->codec_id) {
1336 #if CONFIG_DV_DEMUXER
1337 case AV_CODEC_ID_DVAUDIO:
1338 c->dv_fctx = avformat_alloc_context();
1339 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1341 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1342 return AVERROR(ENOMEM);
1344 sc->dv_audio_container = 1;
1345 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1348 /* no ifdef since parameters are always those */
1349 case AV_CODEC_ID_QCELP:
1350 st->codec->channels = 1;
1351 // force sample rate for qcelp when not stored in mov
1352 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1353 st->codec->sample_rate = 8000;
1355 case AV_CODEC_ID_AMR_NB:
1356 st->codec->channels = 1;
1357 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1358 st->codec->sample_rate = 8000;
1360 case AV_CODEC_ID_AMR_WB:
1361 st->codec->channels = 1;
1362 st->codec->sample_rate = 16000;
1364 case AV_CODEC_ID_MP2:
1365 case AV_CODEC_ID_MP3:
1366 /* force type after stsd for m1a hdlr */
1367 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1368 st->need_parsing = AVSTREAM_PARSE_FULL;
1370 case AV_CODEC_ID_GSM:
1371 case AV_CODEC_ID_ADPCM_MS:
1372 case AV_CODEC_ID_ADPCM_IMA_WAV:
1373 case AV_CODEC_ID_ILBC:
1374 st->codec->block_align = sc->bytes_per_frame;
1376 case AV_CODEC_ID_ALAC:
1377 if (st->codec->extradata_size == 36) {
1378 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1379 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1382 case AV_CODEC_ID_VC1:
1383 st->need_parsing = AVSTREAM_PARSE_FULL;
1391 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1392 int codec_tag, int format,
1395 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1398 (codec_tag == AV_RL32("avc1") ||
1399 (codec_tag != format &&
1400 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1401 : codec_tag != MKTAG('j','p','e','g'))))) {
1402 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1403 * export it as a separate AVStream but this needs a few changes
1404 * in the MOV demuxer, patch welcome. */
1406 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1407 avio_skip(pb, size);
1414 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1417 MOVStreamContext *sc;
1418 int pseudo_stream_id;
1420 if (c->fc->nb_streams < 1)
1422 st = c->fc->streams[c->fc->nb_streams-1];
1425 for (pseudo_stream_id = 0;
1426 pseudo_stream_id < entries && !pb->eof_reached;
1427 pseudo_stream_id++) {
1428 //Parsing Sample description table
1430 int ret, dref_id = 1;
1431 MOVAtom a = { AV_RL32("stsd") };
1432 int64_t start_pos = avio_tell(pb);
1433 uint32_t size = avio_rb32(pb); /* size */
1434 uint32_t format = avio_rl32(pb); /* data format */
1437 avio_rb32(pb); /* reserved */
1438 avio_rb16(pb); /* reserved */
1439 dref_id = avio_rb16(pb);
1441 av_log(c->fc, AV_LOG_ERROR, "invalid size %d in stsd\n", size);
1442 return AVERROR_INVALIDDATA;
1445 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1446 size - (avio_tell(pb) - start_pos)))
1449 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1450 sc->dref_id= dref_id;
1452 id = mov_codec_id(st, format);
1454 av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1455 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1456 (format >> 24) & 0xff, st->codec->codec_type);
1458 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1459 st->codec->codec_id = id;
1460 mov_parse_stsd_video(c, pb, st, sc);
1461 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1462 st->codec->codec_id = id;
1463 mov_parse_stsd_audio(c, pb, st, sc);
1464 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1465 st->codec->codec_id = id;
1466 mov_parse_stsd_subtitle(c, pb, st, sc,
1467 size - (avio_tell(pb) - start_pos));
1469 ret = mov_parse_stsd_data(c, pb, st, sc,
1470 size - (avio_tell(pb) - start_pos));
1474 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1475 a.size = size - (avio_tell(pb) - start_pos);
1477 if ((ret = mov_read_default(c, pb, a)) < 0)
1479 } else if (a.size > 0)
1480 avio_skip(pb, a.size);
1483 if (pb->eof_reached)
1486 return mov_finalize_stsd_codec(c, pb, st, sc);
1489 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1493 avio_r8(pb); /* version */
1494 avio_rb24(pb); /* flags */
1495 entries = avio_rb32(pb);
1497 return ff_mov_read_stsd_entries(c, pb, entries);
1500 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1503 MOVStreamContext *sc;
1504 unsigned int i, entries;
1506 if (c->fc->nb_streams < 1)
1508 st = c->fc->streams[c->fc->nb_streams-1];
1511 avio_r8(pb); /* version */
1512 avio_rb24(pb); /* flags */
1514 entries = avio_rb32(pb);
1516 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1520 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1521 return AVERROR_INVALIDDATA;
1522 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1524 return AVERROR(ENOMEM);
1526 for (i = 0; i < entries && !pb->eof_reached; i++) {
1527 sc->stsc_data[i].first = avio_rb32(pb);
1528 sc->stsc_data[i].count = avio_rb32(pb);
1529 sc->stsc_data[i].id = avio_rb32(pb);
1534 if (pb->eof_reached)
1540 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1543 MOVStreamContext *sc;
1544 unsigned i, entries;
1546 if (c->fc->nb_streams < 1)
1548 st = c->fc->streams[c->fc->nb_streams-1];
1551 avio_rb32(pb); // version + flags
1553 entries = avio_rb32(pb);
1554 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1555 return AVERROR_INVALIDDATA;
1556 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1558 return AVERROR(ENOMEM);
1560 for (i = 0; i < entries && !pb->eof_reached; i++) {
1561 sc->stps_data[i] = avio_rb32(pb);
1562 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1567 if (pb->eof_reached)
1573 static int mov_read_stss(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, "keyframe_count = %d\n", entries);
1593 sc->keyframe_absent = 1;
1596 if (entries >= UINT_MAX / sizeof(int))
1597 return AVERROR_INVALIDDATA;
1598 sc->keyframes = av_malloc(entries * sizeof(int));
1600 return AVERROR(ENOMEM);
1602 for (i = 0; i < entries && !pb->eof_reached; i++) {
1603 sc->keyframes[i] = avio_rb32(pb);
1604 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1607 sc->keyframe_count = i;
1609 if (pb->eof_reached)
1615 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1618 MOVStreamContext *sc;
1619 unsigned int i, entries, sample_size, field_size, num_bytes;
1623 if (c->fc->nb_streams < 1)
1625 st = c->fc->streams[c->fc->nb_streams-1];
1628 avio_r8(pb); /* version */
1629 avio_rb24(pb); /* flags */
1631 if (atom.type == MKTAG('s','t','s','z')) {
1632 sample_size = avio_rb32(pb);
1633 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1634 sc->sample_size = sample_size;
1638 avio_rb24(pb); /* reserved */
1639 field_size = avio_r8(pb);
1641 entries = avio_rb32(pb);
1643 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1645 sc->sample_count = entries;
1649 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1650 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1651 return AVERROR_INVALIDDATA;
1656 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1657 return AVERROR_INVALIDDATA;
1658 sc->sample_sizes = av_malloc(entries * sizeof(int));
1659 if (!sc->sample_sizes)
1660 return AVERROR(ENOMEM);
1662 num_bytes = (entries*field_size+4)>>3;
1664 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1666 av_freep(&sc->sample_sizes);
1667 return AVERROR(ENOMEM);
1670 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1671 av_freep(&sc->sample_sizes);
1673 return AVERROR_INVALIDDATA;
1676 init_get_bits(&gb, buf, 8*num_bytes);
1678 for (i = 0; i < entries && !pb->eof_reached; i++) {
1679 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1680 sc->data_size += sc->sample_sizes[i];
1683 sc->sample_count = i;
1685 if (pb->eof_reached)
1692 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1695 MOVStreamContext *sc;
1696 unsigned int i, entries;
1698 int64_t total_sample_count=0;
1700 if (c->fc->nb_streams < 1)
1702 st = c->fc->streams[c->fc->nb_streams-1];
1705 avio_r8(pb); /* version */
1706 avio_rb24(pb); /* flags */
1707 entries = avio_rb32(pb);
1709 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1710 c->fc->nb_streams-1, entries);
1714 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1715 return AVERROR(EINVAL);
1717 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1719 return AVERROR(ENOMEM);
1721 for (i = 0; i < entries && !pb->eof_reached; i++) {
1722 int sample_duration;
1725 sample_count=avio_rb32(pb);
1726 sample_duration = avio_rb32(pb);
1727 if (sample_count < 0) {
1728 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
1729 return AVERROR_INVALIDDATA;
1731 sc->stts_data[i].count= sample_count;
1732 sc->stts_data[i].duration= sample_duration;
1734 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1735 sample_count, sample_duration);
1737 duration+=(int64_t)sample_duration*sample_count;
1738 total_sample_count+=sample_count;
1743 if (pb->eof_reached)
1746 st->nb_frames= total_sample_count;
1748 st->duration= duration;
1749 sc->track_end = duration;
1753 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1756 MOVStreamContext *sc;
1757 unsigned int i, entries;
1759 if (c->fc->nb_streams < 1)
1761 st = c->fc->streams[c->fc->nb_streams-1];
1764 avio_r8(pb); /* version */
1765 avio_rb24(pb); /* flags */
1766 entries = avio_rb32(pb);
1768 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1772 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1773 return AVERROR_INVALIDDATA;
1774 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1776 return AVERROR(ENOMEM);
1778 for (i = 0; i < entries && !pb->eof_reached; i++) {
1779 int count =avio_rb32(pb);
1780 int duration =avio_rb32(pb);
1782 sc->ctts_data[i].count = count;
1783 sc->ctts_data[i].duration= duration;
1785 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1790 if (pb->eof_reached)
1793 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1798 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1801 MOVStreamContext *sc;
1802 unsigned int i, entries;
1804 uint32_t grouping_type;
1806 if (c->fc->nb_streams < 1)
1808 st = c->fc->streams[c->fc->nb_streams-1];
1811 version = avio_r8(pb); /* version */
1812 avio_rb24(pb); /* flags */
1813 grouping_type = avio_rl32(pb);
1814 if (grouping_type != MKTAG( 'r','a','p',' '))
1815 return 0; /* only support 'rap ' grouping */
1817 avio_rb32(pb); /* grouping_type_parameter */
1819 entries = avio_rb32(pb);
1822 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
1823 return AVERROR_INVALIDDATA;
1824 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
1826 return AVERROR(ENOMEM);
1828 for (i = 0; i < entries && !pb->eof_reached; i++) {
1829 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
1830 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
1833 sc->rap_group_count = i;
1835 return pb->eof_reached ? AVERROR_EOF : 0;
1838 static void mov_build_index(MOVContext *mov, AVStream *st)
1840 MOVStreamContext *sc = st->priv_data;
1841 int64_t current_offset;
1842 int64_t current_dts = 0;
1843 unsigned int stts_index = 0;
1844 unsigned int stsc_index = 0;
1845 unsigned int stss_index = 0;
1846 unsigned int stps_index = 0;
1848 uint64_t stream_size = 0;
1850 /* adjust first dts according to edit list */
1851 if (sc->time_offset && mov->time_scale > 0) {
1852 if (sc->time_offset < 0)
1853 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
1854 current_dts = -sc->time_offset;
1855 if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
1856 sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1857 /* more than 16 frames delay, dts are likely wrong
1858 this happens with files created by iMovie */
1860 st->codec->has_b_frames = 1;
1864 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1865 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1866 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1867 unsigned int current_sample = 0;
1868 unsigned int stts_sample = 0;
1869 unsigned int sample_size;
1870 unsigned int distance = 0;
1871 unsigned int rap_group_index = 0;
1872 unsigned int rap_group_sample = 0;
1873 int rap_group_present = sc->rap_group_count && sc->rap_group;
1874 int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
1876 current_dts -= sc->dts_shift;
1878 if (!sc->sample_count)
1880 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1882 if (av_reallocp_array(&st->index_entries,
1883 st->nb_index_entries + sc->sample_count,
1884 sizeof(*st->index_entries)) < 0) {
1885 st->nb_index_entries = 0;
1888 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
1890 for (i = 0; i < sc->chunk_count; i++) {
1891 current_offset = sc->chunk_offsets[i];
1892 while (stsc_index + 1 < sc->stsc_count &&
1893 i + 1 == sc->stsc_data[stsc_index + 1].first)
1895 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1897 if (current_sample >= sc->sample_count) {
1898 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1902 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
1904 if (stss_index + 1 < sc->keyframe_count)
1906 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1908 if (stps_index + 1 < sc->stps_count)
1911 if (rap_group_present && rap_group_index < sc->rap_group_count) {
1912 if (sc->rap_group[rap_group_index].index > 0)
1914 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
1915 rap_group_sample = 0;
1921 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1922 if (sc->pseudo_stream_id == -1 ||
1923 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1924 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1925 e->pos = current_offset;
1926 e->timestamp = current_dts;
1927 e->size = sample_size;
1928 e->min_distance = distance;
1929 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1930 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1931 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1932 current_offset, current_dts, sample_size, distance, keyframe);
1935 current_offset += sample_size;
1936 stream_size += sample_size;
1937 current_dts += sc->stts_data[stts_index].duration;
1941 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1947 if (st->duration > 0)
1948 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1950 unsigned chunk_samples, total = 0;
1952 // compute total chunk count
1953 for (i = 0; i < sc->stsc_count; i++) {
1954 unsigned count, chunk_count;
1956 chunk_samples = sc->stsc_data[i].count;
1957 if (i != sc->stsc_count - 1 &&
1958 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1959 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1963 if (sc->samples_per_frame >= 160) { // gsm
1964 count = chunk_samples / sc->samples_per_frame;
1965 } else if (sc->samples_per_frame > 1) {
1966 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1967 count = (chunk_samples+samples-1) / samples;
1969 count = (chunk_samples+1023) / 1024;
1972 if (i < sc->stsc_count - 1)
1973 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1975 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1976 total += chunk_count * count;
1979 av_dlog(mov->fc, "chunk count %d\n", total);
1980 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1982 if (av_reallocp_array(&st->index_entries,
1983 st->nb_index_entries + total,
1984 sizeof(*st->index_entries)) < 0) {
1985 st->nb_index_entries = 0;
1988 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
1991 for (i = 0; i < sc->chunk_count; i++) {
1992 current_offset = sc->chunk_offsets[i];
1993 if (stsc_index + 1 < sc->stsc_count &&
1994 i + 1 == sc->stsc_data[stsc_index + 1].first)
1996 chunk_samples = sc->stsc_data[stsc_index].count;
1998 while (chunk_samples > 0) {
2000 unsigned size, samples;
2002 if (sc->samples_per_frame >= 160) { // gsm
2003 samples = sc->samples_per_frame;
2004 size = sc->bytes_per_frame;
2006 if (sc->samples_per_frame > 1) {
2007 samples = FFMIN((1024 / sc->samples_per_frame)*
2008 sc->samples_per_frame, chunk_samples);
2009 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2011 samples = FFMIN(1024, chunk_samples);
2012 size = samples * sc->sample_size;
2016 if (st->nb_index_entries >= total) {
2017 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2020 e = &st->index_entries[st->nb_index_entries++];
2021 e->pos = current_offset;
2022 e->timestamp = current_dts;
2024 e->min_distance = 0;
2025 e->flags = AVINDEX_KEYFRAME;
2026 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2027 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2030 current_offset += size;
2031 current_dts += samples;
2032 chunk_samples -= samples;
2038 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
2039 AVIOInterruptCB *int_cb)
2041 /* try relative path, we do not try the absolute because it can leak information about our
2042 system to an attacker */
2043 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2044 char filename[1024];
2048 /* find a source dir */
2049 src_path = strrchr(src, '/');
2055 /* find a next level down to target */
2056 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2057 if (ref->path[l] == '/') {
2058 if (i == ref->nlvl_to - 1)
2064 /* compose filename if next level down to target was found */
2065 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2066 memcpy(filename, src, src_path - src);
2067 filename[src_path - src] = 0;
2069 for (i = 1; i < ref->nlvl_from; i++)
2070 av_strlcat(filename, "../", 1024);
2072 av_strlcat(filename, ref->path + l + 1, 1024);
2074 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2079 return AVERROR(ENOENT);
2082 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2085 MOVStreamContext *sc;
2088 st = avformat_new_stream(c->fc, NULL);
2089 if (!st) return AVERROR(ENOMEM);
2090 st->id = c->fc->nb_streams;
2091 sc = av_mallocz(sizeof(MOVStreamContext));
2092 if (!sc) return AVERROR(ENOMEM);
2095 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2096 sc->ffindex = st->index;
2098 if ((ret = mov_read_default(c, pb, atom)) < 0)
2102 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2103 (!sc->sample_size && !sc->sample_count))) {
2104 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2109 if (sc->time_scale <= 0) {
2110 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2111 sc->time_scale = c->time_scale;
2112 if (sc->time_scale <= 0)
2116 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2118 mov_build_index(c, st);
2120 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2121 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2122 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
2123 av_log(c->fc, AV_LOG_ERROR,
2124 "stream %d, error opening alias: path='%s', dir='%s', "
2125 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2126 st->index, dref->path, dref->dir, dref->filename,
2127 dref->volume, dref->nlvl_from, dref->nlvl_to);
2131 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2132 if (!st->sample_aspect_ratio.num &&
2133 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2134 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2135 ((double)st->codec->width * sc->height), INT_MAX);
2138 if (st->duration != AV_NOPTS_VALUE && st->duration > 0)
2139 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2140 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2143 switch (st->codec->codec_id) {
2144 #if CONFIG_H261_DECODER
2145 case AV_CODEC_ID_H261:
2147 #if CONFIG_H263_DECODER
2148 case AV_CODEC_ID_H263:
2150 #if CONFIG_MPEG4_DECODER
2151 case AV_CODEC_ID_MPEG4:
2153 st->codec->width = 0; /* let decoder init width/height */
2154 st->codec->height= 0;
2158 /* Do not need those anymore. */
2159 av_freep(&sc->chunk_offsets);
2160 av_freep(&sc->stsc_data);
2161 av_freep(&sc->sample_sizes);
2162 av_freep(&sc->keyframes);
2163 av_freep(&sc->stts_data);
2164 av_freep(&sc->stps_data);
2165 av_freep(&sc->rap_group);
2170 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2173 c->itunes_metadata = 1;
2174 ret = mov_read_default(c, pb, atom);
2175 c->itunes_metadata = 0;
2179 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2181 while (atom.size > 8) {
2182 uint32_t tag = avio_rl32(pb);
2184 if (tag == MKTAG('h','d','l','r')) {
2185 avio_seek(pb, -8, SEEK_CUR);
2187 return mov_read_default(c, pb, atom);
2193 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2198 int64_t disp_transform[2];
2199 int display_matrix[3][2];
2201 MOVStreamContext *sc;
2205 if (c->fc->nb_streams < 1)
2207 st = c->fc->streams[c->fc->nb_streams-1];
2210 version = avio_r8(pb);
2211 flags = avio_rb24(pb);
2212 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2218 avio_rb32(pb); /* creation time */
2219 avio_rb32(pb); /* modification time */
2221 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2222 avio_rb32(pb); /* reserved */
2224 /* highlevel (considering edits) duration in movie timebase */
2225 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2226 avio_rb32(pb); /* reserved */
2227 avio_rb32(pb); /* reserved */
2229 avio_rb16(pb); /* layer */
2230 avio_rb16(pb); /* alternate group */
2231 avio_rb16(pb); /* volume */
2232 avio_rb16(pb); /* reserved */
2234 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2235 // they're kept in fixed point format through all calculations
2236 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2237 for (i = 0; i < 3; i++) {
2238 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2239 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2240 avio_rb32(pb); // 2.30 fixed point (not used)
2243 width = avio_rb32(pb); // 16.16 fixed point track width
2244 height = avio_rb32(pb); // 16.16 fixed point track height
2245 sc->width = width >> 16;
2246 sc->height = height >> 16;
2248 // transform the display width/height according to the matrix
2249 // skip this if the display matrix is the default identity matrix
2250 // or if it is rotating the picture, ex iPhone 3GS
2251 // to keep the same scale, use [width height 1<<16]
2252 if (width && height &&
2253 ((display_matrix[0][0] != 65536 ||
2254 display_matrix[1][1] != 65536) &&
2255 !display_matrix[0][1] &&
2256 !display_matrix[1][0] &&
2257 !display_matrix[2][0] && !display_matrix[2][1])) {
2258 for (i = 0; i < 2; i++)
2260 (int64_t) width * display_matrix[0][i] +
2261 (int64_t) height * display_matrix[1][i] +
2262 ((int64_t) display_matrix[2][i] << 16);
2264 //sample aspect ratio is new width/height divided by old width/height
2265 st->sample_aspect_ratio = av_d2q(
2266 ((double) disp_transform[0] * height) /
2267 ((double) disp_transform[1] * width), INT_MAX);
2272 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2274 MOVFragment *frag = &c->fragment;
2275 MOVTrackExt *trex = NULL;
2276 int flags, track_id, i;
2278 avio_r8(pb); /* version */
2279 flags = avio_rb24(pb);
2281 track_id = avio_rb32(pb);
2283 return AVERROR_INVALIDDATA;
2284 frag->track_id = track_id;
2285 for (i = 0; i < c->trex_count; i++)
2286 if (c->trex_data[i].track_id == frag->track_id) {
2287 trex = &c->trex_data[i];
2291 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2292 return AVERROR_INVALIDDATA;
2295 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2296 avio_rb64(pb) : frag->moof_offset;
2297 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2299 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2300 avio_rb32(pb) : trex->duration;
2301 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2302 avio_rb32(pb) : trex->size;
2303 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2304 avio_rb32(pb) : trex->flags;
2305 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2309 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2311 c->chapter_track = avio_rb32(pb);
2315 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2320 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2321 return AVERROR_INVALIDDATA;
2322 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2323 sizeof(*c->trex_data))) < 0) {
2327 trex = &c->trex_data[c->trex_count++];
2328 avio_r8(pb); /* version */
2329 avio_rb24(pb); /* flags */
2330 trex->track_id = avio_rb32(pb);
2331 trex->stsd_id = avio_rb32(pb);
2332 trex->duration = avio_rb32(pb);
2333 trex->size = avio_rb32(pb);
2334 trex->flags = avio_rb32(pb);
2338 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2340 MOVFragment *frag = &c->fragment;
2341 AVStream *st = NULL;
2342 MOVStreamContext *sc;
2346 int data_offset = 0;
2347 unsigned entries, first_sample_flags = frag->flags;
2348 int flags, distance, i, found_keyframe = 0, err;
2350 for (i = 0; i < c->fc->nb_streams; i++) {
2351 if (c->fc->streams[i]->id == frag->track_id) {
2352 st = c->fc->streams[i];
2357 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2358 return AVERROR_INVALIDDATA;
2361 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2363 avio_r8(pb); /* version */
2364 flags = avio_rb24(pb);
2365 entries = avio_rb32(pb);
2366 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2368 /* Always assume the presence of composition time offsets.
2369 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2370 * 1) in the initial movie, there are no samples.
2371 * 2) in the first movie fragment, there is only one sample without composition time offset.
2372 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2373 if (!sc->ctts_count && sc->sample_count)
2375 /* Complement ctts table if moov atom doesn't have ctts atom. */
2376 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2378 return AVERROR(ENOMEM);
2379 sc->ctts_data = ctts_data;
2380 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2381 sc->ctts_data[sc->ctts_count].duration = 0;
2384 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2385 return AVERROR_INVALIDDATA;
2386 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2387 sizeof(*sc->ctts_data))) < 0) {
2391 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2392 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2393 dts = sc->track_end - sc->time_offset;
2394 offset = frag->base_data_offset + data_offset;
2396 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2397 for (i = 0; i < entries && !pb->eof_reached; i++) {
2398 unsigned sample_size = frag->size;
2399 int sample_flags = i ? frag->flags : first_sample_flags;
2400 unsigned sample_duration = frag->duration;
2403 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2404 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2405 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2406 sc->ctts_data[sc->ctts_count].count = 1;
2407 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2410 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2412 else if (!found_keyframe)
2413 keyframe = found_keyframe =
2414 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2415 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2418 av_add_index_entry(st, offset, dts, sample_size, distance,
2419 keyframe ? AVINDEX_KEYFRAME : 0);
2420 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2421 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2422 offset, dts, sample_size, distance, keyframe);
2424 dts += sample_duration;
2425 offset += sample_size;
2426 sc->data_size += sample_size;
2429 if (pb->eof_reached)
2432 frag->moof_offset = offset;
2433 st->duration = sc->track_end = dts + sc->time_offset;
2437 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2438 /* like the files created with Adobe Premiere 5.0, for samples see */
2439 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2440 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2445 return 0; /* continue */
2446 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2447 avio_skip(pb, atom.size - 4);
2450 atom.type = avio_rl32(pb);
2452 if (atom.type != MKTAG('m','d','a','t')) {
2453 avio_skip(pb, atom.size);
2456 err = mov_read_mdat(c, pb, atom);
2460 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2465 uint8_t *moov_data; /* uncompressed data */
2466 long cmov_len, moov_len;
2469 avio_rb32(pb); /* dcom atom */
2470 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2471 return AVERROR_INVALIDDATA;
2472 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2473 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2474 return AVERROR_INVALIDDATA;
2476 avio_rb32(pb); /* cmvd atom */
2477 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2478 return AVERROR_INVALIDDATA;
2479 moov_len = avio_rb32(pb); /* uncompressed size */
2480 cmov_len = atom.size - 6 * 4;
2482 cmov_data = av_malloc(cmov_len);
2484 return AVERROR(ENOMEM);
2485 moov_data = av_malloc(moov_len);
2488 return AVERROR(ENOMEM);
2490 avio_read(pb, cmov_data, cmov_len);
2491 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2492 goto free_and_return;
2493 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2494 goto free_and_return;
2495 atom.type = MKTAG('m','o','o','v');
2496 atom.size = moov_len;
2497 ret = mov_read_default(c, &ctx, atom);
2503 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2504 return AVERROR(ENOSYS);
2508 /* edit list atom */
2509 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2511 MOVStreamContext *sc;
2512 int i, edit_count, version;
2514 if (c->fc->nb_streams < 1)
2516 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2518 version = avio_r8(pb); /* version */
2519 avio_rb24(pb); /* flags */
2520 edit_count = avio_rb32(pb); /* entries */
2522 if ((uint64_t)edit_count*12+8 > atom.size)
2523 return AVERROR_INVALIDDATA;
2525 for (i=0; i<edit_count; i++){
2529 duration = avio_rb64(pb);
2530 time = avio_rb64(pb);
2532 duration = avio_rb32(pb); /* segment duration */
2533 time = (int32_t)avio_rb32(pb); /* media time */
2535 avio_rb32(pb); /* Media rate */
2536 if (i == 0 && time >= -1) {
2537 sc->time_offset = time != -1 ? time : -duration;
2542 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2543 "a/v desync might occur, patch welcome\n");
2545 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2549 static const MOVParseTableEntry mov_default_parse_table[] = {
2550 { MKTAG('a','v','s','s'), mov_read_extradata },
2551 { MKTAG('c','h','p','l'), mov_read_chpl },
2552 { MKTAG('c','o','6','4'), mov_read_stco },
2553 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2554 { MKTAG('d','i','n','f'), mov_read_default },
2555 { MKTAG('d','r','e','f'), mov_read_dref },
2556 { MKTAG('e','d','t','s'), mov_read_default },
2557 { MKTAG('e','l','s','t'), mov_read_elst },
2558 { MKTAG('e','n','d','a'), mov_read_enda },
2559 { MKTAG('f','i','e','l'), mov_read_fiel },
2560 { MKTAG('f','t','y','p'), mov_read_ftyp },
2561 { MKTAG('g','l','b','l'), mov_read_glbl },
2562 { MKTAG('h','d','l','r'), mov_read_hdlr },
2563 { MKTAG('i','l','s','t'), mov_read_ilst },
2564 { MKTAG('j','p','2','h'), mov_read_extradata },
2565 { MKTAG('m','d','a','t'), mov_read_mdat },
2566 { MKTAG('m','d','h','d'), mov_read_mdhd },
2567 { MKTAG('m','d','i','a'), mov_read_default },
2568 { MKTAG('m','e','t','a'), mov_read_meta },
2569 { MKTAG('m','i','n','f'), mov_read_default },
2570 { MKTAG('m','o','o','f'), mov_read_moof },
2571 { MKTAG('m','o','o','v'), mov_read_moov },
2572 { MKTAG('m','v','e','x'), mov_read_default },
2573 { MKTAG('m','v','h','d'), mov_read_mvhd },
2574 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2575 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2576 { MKTAG('a','v','c','C'), mov_read_glbl },
2577 { MKTAG('p','a','s','p'), mov_read_pasp },
2578 { MKTAG('s','t','b','l'), mov_read_default },
2579 { MKTAG('s','t','c','o'), mov_read_stco },
2580 { MKTAG('s','t','p','s'), mov_read_stps },
2581 { MKTAG('s','t','r','f'), mov_read_strf },
2582 { MKTAG('s','t','s','c'), mov_read_stsc },
2583 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2584 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2585 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2586 { MKTAG('s','t','t','s'), mov_read_stts },
2587 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2588 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2589 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2590 { MKTAG('t','r','a','k'), mov_read_trak },
2591 { MKTAG('t','r','a','f'), mov_read_default },
2592 { MKTAG('t','r','e','f'), mov_read_default },
2593 { MKTAG('c','h','a','p'), mov_read_chap },
2594 { MKTAG('t','r','e','x'), mov_read_trex },
2595 { MKTAG('t','r','u','n'), mov_read_trun },
2596 { MKTAG('u','d','t','a'), mov_read_default },
2597 { MKTAG('w','a','v','e'), mov_read_wave },
2598 { MKTAG('e','s','d','s'), mov_read_esds },
2599 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2600 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2601 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2602 { MKTAG('w','f','e','x'), mov_read_wfex },
2603 { MKTAG('c','m','o','v'), mov_read_cmov },
2604 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2605 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2606 { MKTAG('s','b','g','p'), mov_read_sbgp },
2610 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2612 int64_t total_size = 0;
2617 atom.size = INT64_MAX;
2618 while (total_size + 8 < atom.size && !pb->eof_reached) {
2619 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
2622 if (atom.size >= 8) {
2623 a.size = avio_rb32(pb);
2624 a.type = avio_rl32(pb);
2626 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
2627 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
2629 if (a.size == 1) { /* 64 bit extended size */
2630 a.size = avio_rb64(pb) - 8;
2634 a.size = atom.size - total_size;
2641 a.size = FFMIN(a.size, atom.size - total_size);
2643 for (i = 0; mov_default_parse_table[i].type; i++)
2644 if (mov_default_parse_table[i].type == a.type) {
2645 parse = mov_default_parse_table[i].parse;
2649 // container is user data
2650 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
2651 atom.type == MKTAG('i','l','s','t')))
2652 parse = mov_read_udta_string;
2654 if (!parse) { /* skip leaf atoms data */
2655 avio_skip(pb, a.size);
2657 int64_t start_pos = avio_tell(pb);
2659 int err = parse(c, pb, a);
2662 if (c->found_moov && c->found_mdat &&
2663 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
2664 start_pos + a.size == avio_size(pb))) {
2665 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
2666 c->next_root_atom = start_pos + a.size;
2669 left = a.size - avio_tell(pb) + start_pos;
2670 if (left > 0) /* skip garbage at atom end */
2671 avio_skip(pb, left);
2672 else if (left < 0) {
2673 av_log(c->fc, AV_LOG_WARNING,
2674 "overread end of atom '%.4s' by %"PRId64" bytes\n",
2675 (char*)&a.type, -left);
2676 avio_seek(pb, left, SEEK_CUR);
2680 total_size += a.size;
2683 if (total_size < atom.size && atom.size < 0x7ffff)
2684 avio_skip(pb, atom.size - total_size);
2689 static int mov_probe(AVProbeData *p)
2691 unsigned int offset;
2695 /* check file header */
2698 /* ignore invalid offset */
2699 if ((offset + 8) > (unsigned int)p->buf_size)
2701 tag = AV_RL32(p->buf + offset + 4);
2703 /* check for obvious tags */
2704 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2705 case MKTAG('m','o','o','v'):
2706 case MKTAG('m','d','a','t'):
2707 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2708 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2709 case MKTAG('f','t','y','p'):
2710 return AVPROBE_SCORE_MAX;
2711 /* those are more common words, so rate then a bit less */
2712 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2713 case MKTAG('w','i','d','e'):
2714 case MKTAG('f','r','e','e'):
2715 case MKTAG('j','u','n','k'):
2716 case MKTAG('p','i','c','t'):
2717 return AVPROBE_SCORE_MAX - 5;
2718 case MKTAG(0x82,0x82,0x7f,0x7d):
2719 case MKTAG('s','k','i','p'):
2720 case MKTAG('u','u','i','d'):
2721 case MKTAG('p','r','f','l'):
2722 offset = AV_RB32(p->buf+offset) + offset;
2723 /* if we only find those cause probedata is too small at least rate them */
2724 score = AVPROBE_SCORE_EXTENSION;
2727 /* unrecognized tag */
2733 // must be done after parsing all trak because there's no order requirement
2734 static void mov_read_chapters(AVFormatContext *s)
2736 MOVContext *mov = s->priv_data;
2737 AVStream *st = NULL;
2738 MOVStreamContext *sc;
2742 for (i = 0; i < s->nb_streams; i++)
2743 if (s->streams[i]->id == mov->chapter_track) {
2748 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2752 st->discard = AVDISCARD_ALL;
2754 cur_pos = avio_tell(sc->pb);
2756 for (i = 0; i < st->nb_index_entries; i++) {
2757 AVIndexEntry *sample = &st->index_entries[i];
2758 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2763 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2764 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2768 // the first two bytes are the length of the title
2769 len = avio_rb16(sc->pb);
2770 if (len > sample->size-2)
2772 title_len = 2*len + 1;
2773 if (!(title = av_mallocz(title_len)))
2776 // The samples could theoretically be in any encoding if there's an encd
2777 // atom following, but in practice are only utf-8 or utf-16, distinguished
2778 // instead by the presence of a BOM
2782 ch = avio_rb16(sc->pb);
2784 avio_get_str16be(sc->pb, len, title, title_len);
2785 else if (ch == 0xfffe)
2786 avio_get_str16le(sc->pb, len, title, title_len);
2789 if (len == 1 || len == 2)
2792 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
2796 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2800 avio_seek(sc->pb, cur_pos, SEEK_SET);
2803 static int mov_read_close(AVFormatContext *s)
2805 MOVContext *mov = s->priv_data;
2808 for (i = 0; i < s->nb_streams; i++) {
2809 AVStream *st = s->streams[i];
2810 MOVStreamContext *sc = st->priv_data;
2812 av_freep(&sc->ctts_data);
2813 for (j = 0; j < sc->drefs_count; j++) {
2814 av_freep(&sc->drefs[j].path);
2815 av_freep(&sc->drefs[j].dir);
2817 av_freep(&sc->drefs);
2818 if (sc->pb && sc->pb != s->pb)
2822 if (mov->dv_demux) {
2823 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2824 av_freep(&mov->dv_fctx->streams[i]->codec);
2825 av_freep(&mov->dv_fctx->streams[i]);
2827 av_freep(&mov->dv_fctx);
2828 av_freep(&mov->dv_demux);
2831 av_freep(&mov->trex_data);
2836 static int mov_read_header(AVFormatContext *s)
2838 MOVContext *mov = s->priv_data;
2839 AVIOContext *pb = s->pb;
2841 MOVAtom atom = { AV_RL32("root") };
2844 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2846 atom.size = avio_size(pb);
2848 atom.size = INT64_MAX;
2850 /* check MOV header */
2851 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2852 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2856 if (!mov->found_moov) {
2857 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2859 return AVERROR_INVALIDDATA;
2861 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2863 if (pb->seekable && mov->chapter_track > 0)
2864 mov_read_chapters(s);
2866 if (mov->trex_data) {
2868 for (i = 0; i < s->nb_streams; i++) {
2869 AVStream *st = s->streams[i];
2870 MOVStreamContext *sc = st->priv_data;
2871 if (st->duration > 0)
2872 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
2879 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2881 AVIndexEntry *sample = NULL;
2882 int64_t best_dts = INT64_MAX;
2884 for (i = 0; i < s->nb_streams; i++) {
2885 AVStream *avst = s->streams[i];
2886 MOVStreamContext *msc = avst->priv_data;
2887 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2888 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2889 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2890 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2891 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2893 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2894 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2895 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2896 sample = current_sample;
2905 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2907 MOVContext *mov = s->priv_data;
2908 MOVStreamContext *sc;
2909 AVIndexEntry *sample;
2910 AVStream *st = NULL;
2913 sample = mov_find_next_sample(s, &st);
2915 mov->found_mdat = 0;
2916 if (!mov->next_root_atom)
2918 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
2919 mov->next_root_atom = 0;
2920 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2923 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2927 /* must be done just before reading, to avoid infinite loop on sample */
2928 sc->current_sample++;
2930 if (st->discard != AVDISCARD_ALL) {
2931 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2932 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2933 sc->ffindex, sample->pos);
2934 return AVERROR_INVALIDDATA;
2936 ret = av_get_packet(sc->pb, pkt, sample->size);
2939 if (sc->has_palette) {
2942 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2944 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2946 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2947 sc->has_palette = 0;
2950 #if CONFIG_DV_DEMUXER
2951 if (mov->dv_demux && sc->dv_audio_container) {
2952 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2955 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
2962 pkt->stream_index = sc->ffindex;
2963 pkt->dts = sample->timestamp;
2964 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
2965 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2966 /* update ctts context */
2968 if (sc->ctts_index < sc->ctts_count &&
2969 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2971 sc->ctts_sample = 0;
2974 pkt->dts = AV_NOPTS_VALUE;
2976 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2977 st->index_entries[sc->current_sample].timestamp : st->duration;
2978 pkt->duration = next_dts - pkt->dts;
2979 pkt->pts = pkt->dts;
2981 if (st->discard == AVDISCARD_ALL)
2983 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2984 pkt->pos = sample->pos;
2985 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2986 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2990 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2992 MOVStreamContext *sc = st->priv_data;
2993 int sample, time_sample;
2996 sample = av_index_search_timestamp(st, timestamp, flags);
2997 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2998 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3000 if (sample < 0) /* not sure what to do */
3001 return AVERROR_INVALIDDATA;
3002 sc->current_sample = sample;
3003 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3004 /* adjust ctts index */
3005 if (sc->ctts_data) {
3007 for (i = 0; i < sc->ctts_count; i++) {
3008 int next = time_sample + sc->ctts_data[i].count;
3009 if (next > sc->current_sample) {
3011 sc->ctts_sample = sc->current_sample - time_sample;
3020 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3023 int64_t seek_timestamp, timestamp;
3027 if (stream_index >= s->nb_streams)
3028 return AVERROR_INVALIDDATA;
3029 if (sample_time < 0)
3032 st = s->streams[stream_index];
3033 sample = mov_seek_stream(s, st, sample_time, flags);
3037 /* adjust seek timestamp to found sample timestamp */
3038 seek_timestamp = st->index_entries[sample].timestamp;
3040 for (i = 0; i < s->nb_streams; i++) {
3042 if (stream_index == i)
3045 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3046 mov_seek_stream(s, st, timestamp, flags);
3051 AVInputFormat ff_mov_demuxer = {
3052 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3053 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3054 .priv_data_size = sizeof(MOVContext),
3055 .read_probe = mov_probe,
3056 .read_header = mov_read_header,
3057 .read_packet = mov_read_packet,
3058 .read_close = mov_read_close,
3059 .read_seek = mov_read_seek,