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/audioconvert.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/intfloat.h"
31 #include "libavutil/mathematics.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/dict.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/timecode.h"
36 #include "libavcodec/ac3tab.h"
39 #include "avio_internal.h"
42 #include "libavcodec/get_bits.h"
51 * First version by Francois Revol revol@free.fr
52 * Seek function by Gael Chardon gael.dev@4now.net
55 #include "qtpalette.h"
61 /* those functions parse an atom */
62 /* links atom IDs to parse functions */
63 typedef struct MOVParseTableEntry {
65 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
68 static const MOVParseTableEntry mov_default_parse_table[];
70 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
71 unsigned len, const char *key)
75 short current, total = 0;
76 avio_rb16(pb); // unknown
77 current = avio_rb16(pb);
79 total = avio_rb16(pb);
81 snprintf(buf, sizeof(buf), "%d", current);
83 snprintf(buf, sizeof(buf), "%d/%d", current, total);
84 av_dict_set(&c->fc->metadata, key, buf, 0);
89 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
90 unsigned len, const char *key)
94 /* bypass padding bytes */
99 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
100 av_dict_set(&c->fc->metadata, key, buf, 0);
105 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
106 unsigned len, const char *key)
110 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
111 av_dict_set(&c->fc->metadata, key, buf, 0);
116 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
117 unsigned len, const char *key)
122 avio_r8(pb); // unknown
125 if (genre < 1 || genre > ID3v1_GENRE_MAX)
127 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
128 av_dict_set(&c->fc->metadata, key, buf, 0);
133 static const uint32_t mac_to_unicode[128] = {
134 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
135 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
136 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
137 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
138 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
139 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
140 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
141 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
142 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
143 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
144 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
145 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
146 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
147 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
148 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
149 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
152 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
153 char *dst, int dstlen)
156 char *end = dst+dstlen-1;
159 for (i = 0; i < len; i++) {
160 uint8_t t, c = avio_r8(pb);
161 if (c < 0x80 && p < end)
164 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
170 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
172 #ifdef MOV_EXPORT_ALL_METADATA
175 char str[1024], key2[16], language[4] = {0};
176 const char *key = NULL;
177 uint16_t str_size, langcode = 0;
178 uint32_t data_type = 0;
179 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
182 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
183 case MKTAG(0xa9,'a','u','t'):
184 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
185 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
186 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
187 case MKTAG( 'c','p','r','t'):
188 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
189 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
190 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
191 case MKTAG(0xa9,'c','m','t'):
192 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
193 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
194 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
195 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
196 case MKTAG( 'g','n','r','e'): key = "genre";
197 parse = mov_metadata_gnre; break;
198 case MKTAG(0xa9,'t','o','o'):
199 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
200 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
201 case MKTAG( 'd','e','s','c'): key = "description";break;
202 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
203 case MKTAG( 't','v','s','h'): key = "show"; break;
204 case MKTAG( 't','v','e','n'): key = "episode_id";break;
205 case MKTAG( 't','v','n','n'): key = "network"; break;
206 case MKTAG( 't','r','k','n'): key = "track";
207 parse = mov_metadata_track_or_disc_number; break;
208 case MKTAG( 'd','i','s','k'): key = "disc";
209 parse = mov_metadata_track_or_disc_number; break;
210 case MKTAG( 't','v','e','s'): key = "episode_sort";
211 parse = mov_metadata_int8_bypass_padding; break;
212 case MKTAG( 't','v','s','n'): key = "season_number";
213 parse = mov_metadata_int8_bypass_padding; break;
214 case MKTAG( 's','t','i','k'): key = "media_type";
215 parse = mov_metadata_int8_no_padding; break;
216 case MKTAG( 'h','d','v','d'): key = "hd_video";
217 parse = mov_metadata_int8_no_padding; break;
218 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
219 parse = mov_metadata_int8_no_padding; break;
222 if (c->itunes_metadata && atom.size > 8) {
223 int data_size = avio_rb32(pb);
224 int tag = avio_rl32(pb);
225 if (tag == MKTAG('d','a','t','a')) {
226 data_type = avio_rb32(pb); // type
227 avio_rb32(pb); // unknown
228 str_size = data_size - 16;
231 } else if (atom.size > 4 && key && !c->itunes_metadata) {
232 str_size = avio_rb16(pb); // string length
233 langcode = avio_rb16(pb);
234 ff_mov_lang_to_iso639(langcode, language);
237 str_size = atom.size;
239 #ifdef MOV_EXPORT_ALL_METADATA
241 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
249 return AVERROR_INVALIDDATA;
251 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
254 parse(c, pb, str_size, key);
256 if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
257 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
259 avio_read(pb, str, str_size);
262 av_dict_set(&c->fc->metadata, key, str, 0);
263 if (*language && strcmp(language, "und")) {
264 snprintf(key2, sizeof(key2), "%s-%s", key, language);
265 av_dict_set(&c->fc->metadata, key2, str, 0);
268 av_dlog(c->fc, "lang \"%3s\" ", language);
269 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
270 key, str, (char*)&atom.type, str_size, atom.size);
275 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
278 int i, nb_chapters, str_len, version;
281 if ((atom.size -= 5) < 0)
284 version = avio_r8(pb);
287 avio_rb32(pb); // ???
288 nb_chapters = avio_r8(pb);
290 for (i = 0; i < nb_chapters; i++) {
294 start = avio_rb64(pb);
295 str_len = avio_r8(pb);
297 if ((atom.size -= 9+str_len) < 0)
300 avio_read(pb, str, str_len);
302 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
307 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
309 int64_t total_size = 0;
314 atom.size = INT64_MAX;
315 while (total_size + 8 <= atom.size && !url_feof(pb)) {
316 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
319 if (atom.size >= 8) {
320 a.size = avio_rb32(pb);
321 a.type = avio_rl32(pb);
323 if (a.size == 1) { /* 64 bit extended size */
324 a.size = avio_rb64(pb) - 8;
328 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
329 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
331 a.size = atom.size - total_size + 8;
336 a.size = FFMIN(a.size, atom.size - total_size);
338 for (i = 0; mov_default_parse_table[i].type; i++)
339 if (mov_default_parse_table[i].type == a.type) {
340 parse = mov_default_parse_table[i].parse;
344 // container is user data
345 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
346 atom.type == MKTAG('i','l','s','t')))
347 parse = mov_read_udta_string;
349 if (!parse) { /* skip leaf atoms data */
350 avio_skip(pb, a.size);
352 int64_t start_pos = avio_tell(pb);
354 int err = parse(c, pb, a);
357 if (c->found_moov && c->found_mdat &&
358 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
359 start_pos + a.size == avio_size(pb))) {
360 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
361 c->next_root_atom = start_pos + a.size;
364 left = a.size - avio_tell(pb) + start_pos;
365 if (left > 0) /* skip garbage at atom end */
369 total_size += a.size;
372 if (total_size < atom.size && atom.size < 0x7ffff)
373 avio_skip(pb, atom.size - total_size);
378 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
381 MOVStreamContext *sc;
384 if (c->fc->nb_streams < 1)
386 st = c->fc->streams[c->fc->nb_streams-1];
389 avio_rb32(pb); // version + flags
390 entries = avio_rb32(pb);
391 if (entries >= UINT_MAX / sizeof(*sc->drefs))
392 return AVERROR_INVALIDDATA;
393 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
395 return AVERROR(ENOMEM);
396 sc->drefs_count = entries;
398 for (i = 0; i < sc->drefs_count; i++) {
399 MOVDref *dref = &sc->drefs[i];
400 uint32_t size = avio_rb32(pb);
401 int64_t next = avio_tell(pb) + size - 4;
404 return AVERROR_INVALIDDATA;
406 dref->type = avio_rl32(pb);
407 avio_rb32(pb); // version + flags
408 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
410 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
411 /* macintosh alias record */
412 uint16_t volume_len, len;
417 volume_len = avio_r8(pb);
418 volume_len = FFMIN(volume_len, 27);
419 avio_read(pb, dref->volume, 27);
420 dref->volume[volume_len] = 0;
421 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
426 len = FFMIN(len, 63);
427 avio_read(pb, dref->filename, 63);
428 dref->filename[len] = 0;
429 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
433 /* read next level up_from_alias/down_to_target */
434 dref->nlvl_from = avio_rb16(pb);
435 dref->nlvl_to = avio_rb16(pb);
436 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
437 dref->nlvl_from, dref->nlvl_to);
441 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
444 type = avio_rb16(pb);
446 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
449 if (type == 2) { // absolute path
451 dref->path = av_mallocz(len+1);
453 return AVERROR(ENOMEM);
454 avio_read(pb, dref->path, len);
455 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
457 memmove(dref->path, dref->path+volume_len, len);
460 for (j = 0; j < len; j++)
461 if (dref->path[j] == ':')
463 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
464 } else if (type == 0) { // directory name
466 dref->dir = av_malloc(len+1);
468 return AVERROR(ENOMEM);
469 avio_read(pb, dref->dir, len);
471 for (j = 0; j < len; j++)
472 if (dref->dir[j] == ':')
474 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
479 avio_seek(pb, next, SEEK_SET);
484 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
488 uint32_t av_unused ctype;
492 if (c->fc->nb_streams < 1) // meta before first trak
495 st = c->fc->streams[c->fc->nb_streams-1];
497 avio_r8(pb); /* version */
498 avio_rb24(pb); /* flags */
501 ctype = avio_rl32(pb);
502 type = avio_rl32(pb); /* component subtype */
504 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
505 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
507 if (type == MKTAG('v','i','d','e'))
508 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
509 else if (type == MKTAG('s','o','u','n'))
510 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
511 else if (type == MKTAG('m','1','a',' '))
512 st->codec->codec_id = CODEC_ID_MP2;
513 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
514 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
516 avio_rb32(pb); /* component manufacture */
517 avio_rb32(pb); /* component flags */
518 avio_rb32(pb); /* component flags mask */
520 title_size = atom.size - 24;
521 if (title_size > 0) {
522 title_str = av_malloc(title_size + 1); /* Add null terminator */
524 return AVERROR(ENOMEM);
525 avio_read(pb, title_str, title_size);
526 title_str[title_size] = 0;
527 av_dict_set(&st->metadata, "handler_name", title_str, 0);
528 av_freep(&title_str);
534 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
539 if (fc->nb_streams < 1)
541 st = fc->streams[fc->nb_streams-1];
543 avio_rb32(pb); /* version + flags */
544 ff_mp4_read_descr(fc, pb, &tag);
545 if (tag == MP4ESDescrTag) {
546 ff_mp4_parse_es_descr(pb, NULL);
548 avio_rb16(pb); /* ID */
550 ff_mp4_read_descr(fc, pb, &tag);
551 if (tag == MP4DecConfigDescrTag)
552 ff_mp4_read_dec_config_descr(fc, st, pb);
556 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
558 return ff_mov_read_esds(c->fc, pb, atom);
561 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
564 int ac3info, acmod, lfeon, bsmod;
566 if (c->fc->nb_streams < 1)
568 st = c->fc->streams[c->fc->nb_streams-1];
570 ac3info = avio_rb24(pb);
571 bsmod = (ac3info >> 14) & 0x7;
572 acmod = (ac3info >> 11) & 0x7;
573 lfeon = (ac3info >> 10) & 0x1;
574 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
575 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
577 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
578 st->codec->audio_service_type = bsmod;
579 if (st->codec->channels > 1 && bsmod == 0x7)
580 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
585 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
589 uint32_t flags, layout_tag, bitmap, num_descr, label_mask;
592 if (c->fc->nb_streams < 1)
594 st = c->fc->streams[c->fc->nb_streams-1];
599 version = avio_r8(pb);
600 flags = avio_rb24(pb);
602 layout_tag = avio_rb32(pb);
603 bitmap = avio_rb32(pb);
604 num_descr = avio_rb32(pb);
606 if (atom.size < 16ULL + num_descr * 20ULL)
609 av_dlog(c->fc, "chan: size=%" PRId64 " version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
610 atom.size, version, flags, layout_tag, bitmap, num_descr);
613 for (i = 0; i < num_descr; i++) {
614 uint32_t av_unused label, cflags;
615 label = avio_rb32(pb); // mChannelLabel
616 cflags = avio_rb32(pb); // mChannelFlags
617 avio_rl32(pb); // mCoordinates[0]
618 avio_rl32(pb); // mCoordinates[1]
619 avio_rl32(pb); // mCoordinates[2]
620 if (layout_tag == 0) {
621 uint32_t mask_incr = ff_mov_get_channel_label(label);
622 if (mask_incr == 0) {
626 label_mask |= mask_incr;
630 st->codec->channel_layout = label_mask;
632 st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
637 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
641 if (c->fc->nb_streams < 1)
643 st = c->fc->streams[c->fc->nb_streams-1];
645 ff_get_wav_header(pb, st->codec, atom.size);
650 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
652 const int num = avio_rb32(pb);
653 const int den = avio_rb32(pb);
656 if (c->fc->nb_streams < 1)
658 st = c->fc->streams[c->fc->nb_streams-1];
660 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
661 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
662 av_log(c->fc, AV_LOG_WARNING,
663 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
664 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
666 } else if (den != 0) {
667 st->sample_aspect_ratio.num = num;
668 st->sample_aspect_ratio.den = den;
673 /* this atom contains actual media data */
674 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
676 if (atom.size == 0) /* wrong one (MP4) */
679 return 0; /* now go for moov */
682 /* read major brand, minor version and compatible brands and store them as metadata */
683 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
687 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
688 char* comp_brands_str;
689 uint8_t type[5] = {0};
691 avio_read(pb, type, 4);
692 if (strcmp(type, "qt "))
694 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
695 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
696 minor_ver = avio_rb32(pb); /* minor version */
697 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
698 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
700 comp_brand_size = atom.size - 8;
701 if (comp_brand_size < 0)
702 return AVERROR_INVALIDDATA;
703 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
704 if (!comp_brands_str)
705 return AVERROR(ENOMEM);
706 avio_read(pb, comp_brands_str, comp_brand_size);
707 comp_brands_str[comp_brand_size] = 0;
708 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
709 av_freep(&comp_brands_str);
714 /* this atom should contain all header atoms */
715 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
719 if ((ret = mov_read_default(c, pb, atom)) < 0)
721 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
722 /* so we don't parse the whole file if over a network */
724 return 0; /* now go for mdat */
727 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
729 c->fragment.moof_offset = avio_tell(pb) - 8;
730 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
731 return mov_read_default(c, pb, atom);
734 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
739 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
742 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
743 av_dict_set(metadata, "creation_time", buffer, 0);
747 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
750 MOVStreamContext *sc;
752 char language[4] = {0};
754 time_t creation_time;
756 if (c->fc->nb_streams < 1)
758 st = c->fc->streams[c->fc->nb_streams-1];
761 version = avio_r8(pb);
763 av_log_ask_for_sample(c, "unsupported version %d\n", version);
764 return AVERROR_PATCHWELCOME;
766 avio_rb24(pb); /* flags */
768 creation_time = avio_rb64(pb);
771 creation_time = avio_rb32(pb);
772 avio_rb32(pb); /* modification time */
774 mov_metadata_creation_time(&st->metadata, creation_time);
776 sc->time_scale = avio_rb32(pb);
777 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
779 lang = avio_rb16(pb); /* language */
780 if (ff_mov_lang_to_iso639(lang, language))
781 av_dict_set(&st->metadata, "language", language, 0);
782 avio_rb16(pb); /* quality */
787 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
789 time_t creation_time;
790 int version = avio_r8(pb); /* version */
791 avio_rb24(pb); /* flags */
794 creation_time = avio_rb64(pb);
797 creation_time = avio_rb32(pb);
798 avio_rb32(pb); /* modification time */
800 mov_metadata_creation_time(&c->fc->metadata, creation_time);
801 c->time_scale = avio_rb32(pb); /* time scale */
803 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
805 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
806 // set the AVCodecContext duration because the duration of individual tracks
808 if (c->time_scale > 0)
809 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
810 avio_rb32(pb); /* preferred scale */
812 avio_rb16(pb); /* preferred volume */
814 avio_skip(pb, 10); /* reserved */
816 avio_skip(pb, 36); /* display matrix */
818 avio_rb32(pb); /* preview time */
819 avio_rb32(pb); /* preview duration */
820 avio_rb32(pb); /* poster time */
821 avio_rb32(pb); /* selection time */
822 avio_rb32(pb); /* selection duration */
823 avio_rb32(pb); /* current time */
824 avio_rb32(pb); /* next track ID */
828 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
832 if (c->fc->nb_streams < 1)
834 st = c->fc->streams[c->fc->nb_streams-1];
836 if ((uint64_t)atom.size > (1<<30))
837 return AVERROR_INVALIDDATA;
839 // currently SVQ3 decoder expect full STSD header - so let's fake it
840 // this should be fixed and just SMI header should be passed
841 av_free(st->codec->extradata);
842 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
843 if (!st->codec->extradata)
844 return AVERROR(ENOMEM);
845 st->codec->extradata_size = 0x5a + atom.size;
846 memcpy(st->codec->extradata, "SVQ3", 4); // fake
847 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
848 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
852 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
857 if (c->fc->nb_streams < 1)
859 st = c->fc->streams[c->fc->nb_streams-1];
861 little_endian = avio_rb16(pb) & 0xFF;
862 av_dlog(c->fc, "enda %d\n", little_endian);
863 if (little_endian == 1) {
864 switch (st->codec->codec_id) {
865 case CODEC_ID_PCM_S24BE:
866 st->codec->codec_id = CODEC_ID_PCM_S24LE;
868 case CODEC_ID_PCM_S32BE:
869 st->codec->codec_id = CODEC_ID_PCM_S32LE;
871 case CODEC_ID_PCM_F32BE:
872 st->codec->codec_id = CODEC_ID_PCM_F32LE;
874 case CODEC_ID_PCM_F64BE:
875 st->codec->codec_id = CODEC_ID_PCM_F64LE;
884 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
887 unsigned mov_field_order;
888 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
890 if (c->fc->nb_streams < 1) // will happen with jp2 files
892 st = c->fc->streams[c->fc->nb_streams-1];
894 return AVERROR_INVALIDDATA;
895 mov_field_order = avio_rb16(pb);
896 if ((mov_field_order & 0xFF00) == 0x0100)
897 decoded_field_order = AV_FIELD_PROGRESSIVE;
898 else if ((mov_field_order & 0xFF00) == 0x0200) {
899 switch (mov_field_order & 0xFF) {
900 case 0x01: decoded_field_order = AV_FIELD_TT;
902 case 0x06: decoded_field_order = AV_FIELD_BB;
904 case 0x09: decoded_field_order = AV_FIELD_TB;
906 case 0x0E: decoded_field_order = AV_FIELD_BT;
910 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
911 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
913 st->codec->field_order = decoded_field_order;
918 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
919 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
920 enum CodecID codec_id)
926 if (c->fc->nb_streams < 1) // will happen with jp2 files
928 st= c->fc->streams[c->fc->nb_streams-1];
930 if (st->codec->codec_id != codec_id)
931 return 0; /* unexpected codec_id - don't mess with extradata */
933 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
934 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
935 return AVERROR_INVALIDDATA;
936 buf= av_realloc(st->codec->extradata, size);
938 return AVERROR(ENOMEM);
939 st->codec->extradata= buf;
940 buf+= st->codec->extradata_size;
941 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
942 AV_WB32( buf , atom.size + 8);
943 AV_WL32( buf + 4, atom.type);
944 avio_read(pb, buf + 8, atom.size);
948 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
949 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
951 return mov_read_extradata(c, pb, atom, CODEC_ID_ALAC);
954 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
956 return mov_read_extradata(c, pb, atom, CODEC_ID_AVS);
959 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
961 return mov_read_extradata(c, pb, atom, CODEC_ID_JPEG2000);
964 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
968 if (c->fc->nb_streams < 1)
970 st = c->fc->streams[c->fc->nb_streams-1];
972 if ((uint64_t)atom.size > (1<<30))
973 return AVERROR_INVALIDDATA;
975 if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
976 // pass all frma atom to codec, needed at least for QDMC and QDM2
977 av_free(st->codec->extradata);
978 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
979 if (!st->codec->extradata)
980 return AVERROR(ENOMEM);
981 st->codec->extradata_size = atom.size;
982 avio_read(pb, st->codec->extradata, atom.size);
983 } else if (atom.size > 8) { /* to read frma, esds atoms */
985 if ((ret = mov_read_default(c, pb, atom)) < 0)
988 avio_skip(pb, atom.size);
993 * This function reads atom content and puts data in extradata without tag
994 * nor size unlike mov_read_extradata.
996 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1000 if (c->fc->nb_streams < 1)
1002 st = c->fc->streams[c->fc->nb_streams-1];
1004 if ((uint64_t)atom.size > (1<<30))
1005 return AVERROR_INVALIDDATA;
1007 if (atom.size >= 10) {
1008 // Broken files created by legacy versions of Libav and FFmpeg will
1009 // wrap a whole fiel atom inside of a glbl atom.
1010 unsigned size = avio_rb32(pb);
1011 unsigned type = avio_rl32(pb);
1012 avio_seek(pb, -8, SEEK_CUR);
1013 if (type == MKTAG('f','i','e','l') && size == atom.size)
1014 return mov_read_default(c, pb, atom);
1016 av_free(st->codec->extradata);
1017 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1018 if (!st->codec->extradata)
1019 return AVERROR(ENOMEM);
1020 st->codec->extradata_size = atom.size;
1021 avio_read(pb, st->codec->extradata, atom.size);
1025 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1028 uint8_t profile_level;
1030 if (c->fc->nb_streams < 1)
1032 st = c->fc->streams[c->fc->nb_streams-1];
1034 if (atom.size >= (1<<28) || atom.size < 7)
1035 return AVERROR_INVALIDDATA;
1037 profile_level = avio_r8(pb);
1038 if (profile_level & 0xf0 != 0xc0)
1041 av_free(st->codec->extradata);
1042 st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
1043 if (!st->codec->extradata)
1044 return AVERROR(ENOMEM);
1045 st->codec->extradata_size = atom.size - 7;
1046 avio_seek(pb, 6, SEEK_CUR);
1047 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
1052 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1053 * but can have extradata appended at the end after the 40 bytes belonging
1056 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1060 if (c->fc->nb_streams < 1)
1062 if (atom.size <= 40)
1064 st = c->fc->streams[c->fc->nb_streams-1];
1066 if ((uint64_t)atom.size > (1<<30))
1067 return AVERROR_INVALIDDATA;
1069 av_free(st->codec->extradata);
1070 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1071 if (!st->codec->extradata)
1072 return AVERROR(ENOMEM);
1073 st->codec->extradata_size = atom.size - 40;
1075 avio_read(pb, st->codec->extradata, atom.size - 40);
1079 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1082 MOVStreamContext *sc;
1083 unsigned int i, entries;
1085 if (c->fc->nb_streams < 1)
1087 st = c->fc->streams[c->fc->nb_streams-1];
1090 avio_r8(pb); /* version */
1091 avio_rb24(pb); /* flags */
1093 entries = avio_rb32(pb);
1097 if (entries >= UINT_MAX/sizeof(int64_t))
1098 return AVERROR_INVALIDDATA;
1100 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1101 if (!sc->chunk_offsets)
1102 return AVERROR(ENOMEM);
1103 sc->chunk_count = entries;
1105 if (atom.type == MKTAG('s','t','c','o'))
1106 for (i=0; i<entries; i++)
1107 sc->chunk_offsets[i] = avio_rb32(pb);
1108 else if (atom.type == MKTAG('c','o','6','4'))
1109 for (i=0; i<entries; i++)
1110 sc->chunk_offsets[i] = avio_rb64(pb);
1112 return AVERROR_INVALIDDATA;
1118 * Compute codec id for 'lpcm' tag.
1119 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1121 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1123 if (flags & 1) { // floating point
1124 if (flags & 2) { // big endian
1125 if (bps == 32) return CODEC_ID_PCM_F32BE;
1126 else if (bps == 64) return CODEC_ID_PCM_F64BE;
1128 if (bps == 32) return CODEC_ID_PCM_F32LE;
1129 else if (bps == 64) return CODEC_ID_PCM_F64LE;
1135 if (flags & 4) return CODEC_ID_PCM_S8;
1136 else return CODEC_ID_PCM_U8;
1137 else if (bps == 16) return CODEC_ID_PCM_S16BE;
1138 else if (bps == 24) return CODEC_ID_PCM_S24BE;
1139 else if (bps == 32) return CODEC_ID_PCM_S32BE;
1142 if (flags & 4) return CODEC_ID_PCM_S8;
1143 else return CODEC_ID_PCM_U8;
1144 else if (bps == 16) return CODEC_ID_PCM_S16LE;
1145 else if (bps == 24) return CODEC_ID_PCM_S24LE;
1146 else if (bps == 32) return CODEC_ID_PCM_S32LE;
1149 return CODEC_ID_NONE;
1152 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1155 MOVStreamContext *sc;
1156 int j, pseudo_stream_id;
1158 if (c->fc->nb_streams < 1)
1160 st = c->fc->streams[c->fc->nb_streams-1];
1163 for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
1164 //Parsing Sample description table
1167 MOVAtom a = { AV_RL32("stsd") };
1168 int64_t start_pos = avio_tell(pb);
1169 int size = avio_rb32(pb); /* size */
1170 uint32_t format = avio_rl32(pb); /* data format */
1173 avio_rb32(pb); /* reserved */
1174 avio_rb16(pb); /* reserved */
1175 dref_id = avio_rb16(pb);
1176 }else if (size <= 0){
1177 av_log(c->fc, AV_LOG_ERROR, "invalid size %d in stsd\n", size);
1181 if (st->codec->codec_tag &&
1182 st->codec->codec_tag != format &&
1183 (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
1184 : st->codec->codec_tag != MKTAG('j','p','e','g'))
1186 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1187 * export it as a separate AVStream but this needs a few changes
1188 * in the MOV demuxer, patch welcome. */
1189 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1190 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1193 /* we cannot demux concatenated h264 streams because of different extradata */
1194 if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1195 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 might not play corrently.\n");
1196 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1197 sc->dref_id= dref_id;
1199 st->codec->codec_tag = format;
1200 id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1201 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1202 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1204 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1205 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1206 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1207 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1208 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1210 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1212 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1213 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){
1214 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1216 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1220 av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1221 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1222 (format >> 24) & 0xff, st->codec->codec_type);
1224 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1225 unsigned int color_depth, len;
1226 int color_greyscale;
1229 st->codec->codec_id = id;
1230 avio_rb16(pb); /* version */
1231 avio_rb16(pb); /* revision level */
1232 avio_rb32(pb); /* vendor */
1233 avio_rb32(pb); /* temporal quality */
1234 avio_rb32(pb); /* spatial quality */
1236 st->codec->width = avio_rb16(pb); /* width */
1237 st->codec->height = avio_rb16(pb); /* height */
1239 avio_rb32(pb); /* horiz resolution */
1240 avio_rb32(pb); /* vert resolution */
1241 avio_rb32(pb); /* data size, always 0 */
1242 avio_rb16(pb); /* frames per samples */
1244 len = avio_r8(pb); /* codec name, pascal string */
1247 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1249 avio_skip(pb, 31 - len);
1250 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1251 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1252 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1254 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1255 color_table_id = avio_rb16(pb); /* colortable id */
1256 av_dlog(c->fc, "depth %d, ctab id %d\n",
1257 st->codec->bits_per_coded_sample, color_table_id);
1258 /* figure out the palette situation */
1259 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1260 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1262 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1263 if ((color_depth == 2) || (color_depth == 4) ||
1264 (color_depth == 8)) {
1265 /* for palette traversal */
1266 unsigned int color_start, color_count, color_end;
1267 unsigned char a, r, g, b;
1269 if (color_greyscale) {
1270 int color_index, color_dec;
1271 /* compute the greyscale palette */
1272 st->codec->bits_per_coded_sample = color_depth;
1273 color_count = 1 << color_depth;
1275 color_dec = 256 / (color_count - 1);
1276 for (j = 0; j < color_count; j++) {
1277 if (id == CODEC_ID_CINEPAK){
1278 r = g = b = color_count - 1 - color_index;
1280 r = g = b = color_index;
1282 (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1283 color_index -= color_dec;
1284 if (color_index < 0)
1287 } else if (color_table_id) {
1288 const uint8_t *color_table;
1289 /* if flag bit 3 is set, use the default palette */
1290 color_count = 1 << color_depth;
1291 if (color_depth == 2)
1292 color_table = ff_qt_default_palette_4;
1293 else if (color_depth == 4)
1294 color_table = ff_qt_default_palette_16;
1296 color_table = ff_qt_default_palette_256;
1298 for (j = 0; j < color_count; j++) {
1299 r = color_table[j * 3 + 0];
1300 g = color_table[j * 3 + 1];
1301 b = color_table[j * 3 + 2];
1303 (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1306 /* load the palette from the file */
1307 color_start = avio_rb32(pb);
1308 color_count = avio_rb16(pb);
1309 color_end = avio_rb16(pb);
1310 if ((color_start <= 255) &&
1311 (color_end <= 255)) {
1312 for (j = color_start; j <= color_end; j++) {
1313 /* each A, R, G, or B component is 16 bits;
1314 * only use the top 8 bits */
1324 (a << 24 ) | (r << 16) | (g << 8) | (b);
1328 sc->has_palette = 1;
1330 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1331 int bits_per_sample, flags;
1332 uint16_t version = avio_rb16(pb);
1334 st->codec->codec_id = id;
1335 avio_rb16(pb); /* revision level */
1336 avio_rb32(pb); /* vendor */
1338 st->codec->channels = avio_rb16(pb); /* channel count */
1339 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1340 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1342 sc->audio_cid = avio_rb16(pb);
1343 avio_rb16(pb); /* packet size = 0 */
1345 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1347 //Read QT version 1 fields. In version 0 these do not exist.
1348 av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1351 sc->samples_per_frame = avio_rb32(pb);
1352 avio_rb32(pb); /* bytes per packet */
1353 sc->bytes_per_frame = avio_rb32(pb);
1354 avio_rb32(pb); /* bytes per sample */
1355 } else if (version==2) {
1356 avio_rb32(pb); /* sizeof struct only */
1357 st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
1358 st->codec->channels = avio_rb32(pb);
1359 avio_rb32(pb); /* always 0x7F000000 */
1360 st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1361 flags = avio_rb32(pb); /* lpcm format specific flag */
1362 sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1363 sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1364 if (format == MKTAG('l','p','c','m'))
1365 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1369 switch (st->codec->codec_id) {
1370 case CODEC_ID_PCM_S8:
1371 case CODEC_ID_PCM_U8:
1372 if (st->codec->bits_per_coded_sample == 16)
1373 st->codec->codec_id = CODEC_ID_PCM_S16BE;
1375 case CODEC_ID_PCM_S16LE:
1376 case CODEC_ID_PCM_S16BE:
1377 if (st->codec->bits_per_coded_sample == 8)
1378 st->codec->codec_id = CODEC_ID_PCM_S8;
1379 else if (st->codec->bits_per_coded_sample == 24)
1380 st->codec->codec_id =
1381 st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1382 CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1384 /* set values for old format before stsd version 1 appeared */
1385 case CODEC_ID_MACE3:
1386 sc->samples_per_frame = 6;
1387 sc->bytes_per_frame = 2*st->codec->channels;
1389 case CODEC_ID_MACE6:
1390 sc->samples_per_frame = 6;
1391 sc->bytes_per_frame = 1*st->codec->channels;
1393 case CODEC_ID_ADPCM_IMA_QT:
1394 sc->samples_per_frame = 64;
1395 sc->bytes_per_frame = 34*st->codec->channels;
1398 sc->samples_per_frame = 160;
1399 sc->bytes_per_frame = 33;
1405 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1406 if (bits_per_sample) {
1407 st->codec->bits_per_coded_sample = bits_per_sample;
1408 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1410 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1411 // ttxt stsd contains display flags, justification, background
1412 // color, fonts, and default styles, so fake an atom to read it
1413 MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1414 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1415 mov_read_glbl(c, pb, fake_atom);
1416 st->codec->codec_id= id;
1417 st->codec->width = sc->width;
1418 st->codec->height = sc->height;
1420 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1421 MOVStreamContext *tmcd_ctx = st->priv_data;
1423 avio_rb32(pb); /* reserved */
1424 val = avio_rb32(pb); /* flags */
1425 tmcd_ctx->tmcd_flags = val;
1427 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1428 avio_rb32(pb); /* time scale */
1429 avio_rb32(pb); /* frame duration */
1430 st->codec->time_base.den = avio_r8(pb); /* number of frame */
1431 st->codec->time_base.num = 1;
1433 /* other codec type, just skip (rtp, mp4s, ...) */
1434 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1436 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1437 a.size = size - (avio_tell(pb) - start_pos);
1440 if ((ret = mov_read_default(c, pb, a)) < 0)
1442 } else if (a.size > 0)
1443 avio_skip(pb, a.size);
1446 if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1447 st->codec->sample_rate= sc->time_scale;
1449 /* special codec parameters handling */
1450 switch (st->codec->codec_id) {
1451 #if CONFIG_DV_DEMUXER
1452 case CODEC_ID_DVAUDIO:
1453 c->dv_fctx = avformat_alloc_context();
1454 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1456 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1457 return AVERROR(ENOMEM);
1459 sc->dv_audio_container = 1;
1460 st->codec->codec_id = CODEC_ID_PCM_S16LE;
1463 /* no ifdef since parameters are always those */
1464 case CODEC_ID_QCELP:
1465 // force sample rate for qcelp when not stored in mov
1466 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1467 st->codec->sample_rate = 8000;
1468 st->codec->channels= 1; /* really needed */
1470 case CODEC_ID_AMR_NB:
1471 st->codec->channels= 1; /* really needed */
1472 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1473 st->codec->sample_rate = 8000;
1475 case CODEC_ID_AMR_WB:
1476 st->codec->channels = 1;
1477 st->codec->sample_rate = 16000;
1481 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1482 st->need_parsing = AVSTREAM_PARSE_FULL;
1485 case CODEC_ID_ADPCM_MS:
1486 case CODEC_ID_ADPCM_IMA_WAV:
1487 st->codec->block_align = sc->bytes_per_frame;
1490 if (st->codec->extradata_size == 36) {
1491 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1492 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1496 st->need_parsing = AVSTREAM_PARSE_FULL;
1498 case CODEC_ID_MPEG1VIDEO:
1499 st->need_parsing = AVSTREAM_PARSE_FULL;
1508 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1512 avio_r8(pb); /* version */
1513 avio_rb24(pb); /* flags */
1514 entries = avio_rb32(pb);
1516 return ff_mov_read_stsd_entries(c, pb, entries);
1519 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1522 MOVStreamContext *sc;
1523 unsigned int i, entries;
1525 if (c->fc->nb_streams < 1)
1527 st = c->fc->streams[c->fc->nb_streams-1];
1530 avio_r8(pb); /* version */
1531 avio_rb24(pb); /* flags */
1533 entries = avio_rb32(pb);
1535 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1539 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1540 return AVERROR_INVALIDDATA;
1541 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1543 return AVERROR(ENOMEM);
1544 sc->stsc_count = entries;
1546 for (i=0; i<entries; i++) {
1547 sc->stsc_data[i].first = avio_rb32(pb);
1548 sc->stsc_data[i].count = avio_rb32(pb);
1549 sc->stsc_data[i].id = avio_rb32(pb);
1554 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1557 MOVStreamContext *sc;
1558 unsigned i, entries;
1560 if (c->fc->nb_streams < 1)
1562 st = c->fc->streams[c->fc->nb_streams-1];
1565 avio_rb32(pb); // version + flags
1567 entries = avio_rb32(pb);
1568 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1569 return AVERROR_INVALIDDATA;
1570 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1572 return AVERROR(ENOMEM);
1573 sc->stps_count = entries;
1575 for (i = 0; i < entries; i++) {
1576 sc->stps_data[i] = avio_rb32(pb);
1577 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1583 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1586 MOVStreamContext *sc;
1587 unsigned int i, entries;
1589 if (c->fc->nb_streams < 1)
1591 st = c->fc->streams[c->fc->nb_streams-1];
1594 avio_r8(pb); /* version */
1595 avio_rb24(pb); /* flags */
1597 entries = avio_rb32(pb);
1599 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1603 if (entries >= UINT_MAX / sizeof(int))
1604 return AVERROR_INVALIDDATA;
1605 sc->keyframes = av_malloc(entries * sizeof(int));
1607 return AVERROR(ENOMEM);
1608 sc->keyframe_count = entries;
1610 for (i=0; i<entries; i++) {
1611 sc->keyframes[i] = avio_rb32(pb);
1612 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1617 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1620 MOVStreamContext *sc;
1621 unsigned int i, entries, sample_size, field_size, num_bytes;
1625 if (c->fc->nb_streams < 1)
1627 st = c->fc->streams[c->fc->nb_streams-1];
1630 avio_r8(pb); /* version */
1631 avio_rb24(pb); /* flags */
1633 if (atom.type == MKTAG('s','t','s','z')) {
1634 sample_size = avio_rb32(pb);
1635 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1636 sc->sample_size = sample_size;
1640 avio_rb24(pb); /* reserved */
1641 field_size = avio_r8(pb);
1643 entries = avio_rb32(pb);
1645 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1647 sc->sample_count = entries;
1651 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1652 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1653 return AVERROR_INVALIDDATA;
1658 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1659 return AVERROR_INVALIDDATA;
1660 sc->sample_sizes = av_malloc(entries * sizeof(int));
1661 if (!sc->sample_sizes)
1662 return AVERROR(ENOMEM);
1664 num_bytes = (entries*field_size+4)>>3;
1666 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1668 av_freep(&sc->sample_sizes);
1669 return AVERROR(ENOMEM);
1672 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1673 av_freep(&sc->sample_sizes);
1675 return AVERROR_INVALIDDATA;
1678 init_get_bits(&gb, buf, 8*num_bytes);
1680 for (i = 0; i < entries; i++) {
1681 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1682 sc->data_size += sc->sample_sizes[i];
1689 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1692 MOVStreamContext *sc;
1693 unsigned int i, entries;
1695 int64_t total_sample_count=0;
1697 if (c->fc->nb_streams < 1)
1699 st = c->fc->streams[c->fc->nb_streams-1];
1702 avio_r8(pb); /* version */
1703 avio_rb24(pb); /* flags */
1704 entries = avio_rb32(pb);
1706 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1707 c->fc->nb_streams-1, entries);
1709 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1712 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1714 return AVERROR(ENOMEM);
1716 sc->stts_count = entries;
1718 for (i=0; i<entries; i++) {
1719 int sample_duration;
1722 sample_count=avio_rb32(pb);
1723 sample_duration = avio_rb32(pb);
1724 /* sample_duration < 0 is invalid based on the spec */
1725 if (sample_duration < 0) {
1726 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
1727 sample_duration = 1;
1729 sc->stts_data[i].count= sample_count;
1730 sc->stts_data[i].duration= sample_duration;
1732 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1733 sample_count, sample_duration);
1735 duration+=(int64_t)sample_duration*sample_count;
1736 total_sample_count+=sample_count;
1739 st->nb_frames= total_sample_count;
1741 st->duration= duration;
1742 sc->track_end = duration;
1746 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1749 MOVStreamContext *sc;
1750 unsigned int i, entries;
1752 if (c->fc->nb_streams < 1)
1754 st = c->fc->streams[c->fc->nb_streams-1];
1757 avio_r8(pb); /* version */
1758 avio_rb24(pb); /* flags */
1759 entries = avio_rb32(pb);
1761 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1765 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1766 return AVERROR_INVALIDDATA;
1767 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1769 return AVERROR(ENOMEM);
1770 sc->ctts_count = entries;
1772 for (i=0; i<entries; i++) {
1773 int count =avio_rb32(pb);
1774 int duration =avio_rb32(pb);
1776 sc->ctts_data[i].count = count;
1777 sc->ctts_data[i].duration= duration;
1779 if (FFABS(duration) > (1<<28) && i+2<entries) {
1780 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
1781 av_freep(&sc->ctts_data);
1786 if (duration < 0 && i+2<entries)
1787 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1790 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1795 static void mov_build_index(MOVContext *mov, AVStream *st)
1797 MOVStreamContext *sc = st->priv_data;
1798 int64_t current_offset;
1799 int64_t current_dts = 0;
1800 unsigned int stts_index = 0;
1801 unsigned int stsc_index = 0;
1802 unsigned int stss_index = 0;
1803 unsigned int stps_index = 0;
1805 uint64_t stream_size = 0;
1807 /* adjust first dts according to edit list */
1808 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
1809 if (sc->empty_duration)
1810 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
1811 sc->time_offset = sc->start_time - sc->empty_duration;
1812 current_dts = -sc->time_offset;
1813 if (sc->ctts_data && sc->stts_data &&
1814 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1815 /* more than 16 frames delay, dts are likely wrong
1816 this happens with files created by iMovie */
1818 st->codec->has_b_frames = 1;
1822 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1823 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1824 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1825 unsigned int current_sample = 0;
1826 unsigned int stts_sample = 0;
1827 unsigned int sample_size;
1828 unsigned int distance = 0;
1829 int key_off = sc->keyframes && sc->keyframes[0] == 1;
1831 current_dts -= sc->dts_shift;
1833 if (!sc->sample_count || st->nb_index_entries)
1835 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
1837 st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
1838 if (!st->index_entries)
1840 st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
1842 for (i = 0; i < sc->chunk_count; i++) {
1843 current_offset = sc->chunk_offsets[i];
1844 while (stsc_index + 1 < sc->stsc_count &&
1845 i + 1 == sc->stsc_data[stsc_index + 1].first)
1847 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1849 if (current_sample >= sc->sample_count) {
1850 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1854 if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1856 if (stss_index + 1 < sc->keyframe_count)
1858 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1860 if (stps_index + 1 < sc->stps_count)
1865 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1866 if (sc->pseudo_stream_id == -1 ||
1867 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1868 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1869 e->pos = current_offset;
1870 e->timestamp = current_dts;
1871 e->size = sample_size;
1872 e->min_distance = distance;
1873 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1874 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1875 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1876 current_offset, current_dts, sample_size, distance, keyframe);
1879 current_offset += sample_size;
1880 stream_size += sample_size;
1881 current_dts += sc->stts_data[stts_index].duration;
1885 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1891 if (st->duration > 0)
1892 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1894 unsigned chunk_samples, total = 0;
1896 // compute total chunk count
1897 for (i = 0; i < sc->stsc_count; i++) {
1898 unsigned count, chunk_count;
1900 chunk_samples = sc->stsc_data[i].count;
1901 if (i != sc->stsc_count - 1 &&
1902 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1903 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1907 if (sc->samples_per_frame >= 160) { // gsm
1908 count = chunk_samples / sc->samples_per_frame;
1909 } else if (sc->samples_per_frame > 1) {
1910 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1911 count = (chunk_samples+samples-1) / samples;
1913 count = (chunk_samples+1023) / 1024;
1916 if (i < sc->stsc_count - 1)
1917 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1919 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1920 total += chunk_count * count;
1923 av_dlog(mov->fc, "chunk count %d\n", total);
1924 if (total >= UINT_MAX / sizeof(*st->index_entries))
1926 st->index_entries = av_malloc(total*sizeof(*st->index_entries));
1927 if (!st->index_entries)
1929 st->index_entries_allocated_size = total*sizeof(*st->index_entries);
1932 for (i = 0; i < sc->chunk_count; i++) {
1933 current_offset = sc->chunk_offsets[i];
1934 if (stsc_index + 1 < sc->stsc_count &&
1935 i + 1 == sc->stsc_data[stsc_index + 1].first)
1937 chunk_samples = sc->stsc_data[stsc_index].count;
1939 while (chunk_samples > 0) {
1941 unsigned size, samples;
1943 if (sc->samples_per_frame >= 160) { // gsm
1944 samples = sc->samples_per_frame;
1945 size = sc->bytes_per_frame;
1947 if (sc->samples_per_frame > 1) {
1948 samples = FFMIN((1024 / sc->samples_per_frame)*
1949 sc->samples_per_frame, chunk_samples);
1950 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1952 samples = FFMIN(1024, chunk_samples);
1953 size = samples * sc->sample_size;
1957 if (st->nb_index_entries >= total) {
1958 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1961 e = &st->index_entries[st->nb_index_entries++];
1962 e->pos = current_offset;
1963 e->timestamp = current_dts;
1965 e->min_distance = 0;
1966 e->flags = AVINDEX_KEYFRAME;
1967 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1968 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1971 current_offset += size;
1972 current_dts += samples;
1973 chunk_samples -= samples;
1979 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
1980 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
1982 /* try relative path, we do not try the absolute because it can leak information about our
1983 system to an attacker */
1984 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1985 char filename[1024];
1986 const char *src_path;
1989 /* find a source dir */
1990 src_path = strrchr(src, '/');
1996 /* find a next level down to target */
1997 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1998 if (ref->path[l] == '/') {
1999 if (i == ref->nlvl_to - 1)
2005 /* compose filename if next level down to target was found */
2006 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2007 memcpy(filename, src, src_path - src);
2008 filename[src_path - src] = 0;
2010 for (i = 1; i < ref->nlvl_from; i++)
2011 av_strlcat(filename, "../", 1024);
2013 av_strlcat(filename, ref->path + l + 1, 1024);
2015 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2018 } else if (use_absolute_path) {
2019 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2020 "this is a possible security issue\n");
2021 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2025 return AVERROR(ENOENT);
2028 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2031 MOVStreamContext *sc;
2034 st = avformat_new_stream(c->fc, NULL);
2035 if (!st) return AVERROR(ENOMEM);
2036 st->id = c->fc->nb_streams;
2037 sc = av_mallocz(sizeof(MOVStreamContext));
2038 if (!sc) return AVERROR(ENOMEM);
2041 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2042 sc->ffindex = st->index;
2044 if ((ret = mov_read_default(c, pb, atom)) < 0)
2048 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2049 (!sc->sample_size && !sc->sample_count))) {
2050 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2055 if (sc->time_scale <= 0) {
2056 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2057 sc->time_scale = c->time_scale;
2058 if (sc->time_scale <= 0)
2062 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2064 mov_build_index(c, st);
2066 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2067 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2068 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2069 c->use_absolute_path, c->fc) < 0)
2070 av_log(c->fc, AV_LOG_ERROR,
2071 "stream %d, error opening alias: path='%s', dir='%s', "
2072 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2073 st->index, dref->path, dref->dir, dref->filename,
2074 dref->volume, dref->nlvl_from, dref->nlvl_to);
2078 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2079 if (!st->sample_aspect_ratio.num &&
2080 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2081 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2082 ((double)st->codec->width * sc->height), INT_MAX);
2085 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2086 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2088 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2089 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2090 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2093 switch (st->codec->codec_id) {
2094 #if CONFIG_H261_DECODER
2097 #if CONFIG_H263_DECODER
2100 #if CONFIG_H264_DECODER
2103 #if CONFIG_MPEG4_DECODER
2104 case CODEC_ID_MPEG4:
2106 st->codec->width = 0; /* let decoder init width/height */
2107 st->codec->height= 0;
2111 /* Do not need those anymore. */
2112 av_freep(&sc->chunk_offsets);
2113 av_freep(&sc->stsc_data);
2114 av_freep(&sc->sample_sizes);
2115 av_freep(&sc->keyframes);
2116 av_freep(&sc->stts_data);
2117 av_freep(&sc->stps_data);
2122 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2125 c->itunes_metadata = 1;
2126 ret = mov_read_default(c, pb, atom);
2127 c->itunes_metadata = 0;
2131 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2133 while (atom.size > 8) {
2134 uint32_t tag = avio_rl32(pb);
2136 if (tag == MKTAG('h','d','l','r')) {
2137 avio_seek(pb, -8, SEEK_CUR);
2139 return mov_read_default(c, pb, atom);
2145 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2150 int64_t disp_transform[2];
2151 int display_matrix[3][2];
2153 MOVStreamContext *sc;
2156 if (c->fc->nb_streams < 1)
2158 st = c->fc->streams[c->fc->nb_streams-1];
2161 version = avio_r8(pb);
2162 avio_rb24(pb); /* flags */
2164 MOV_TRACK_ENABLED 0x0001
2165 MOV_TRACK_IN_MOVIE 0x0002
2166 MOV_TRACK_IN_PREVIEW 0x0004
2167 MOV_TRACK_IN_POSTER 0x0008
2174 avio_rb32(pb); /* creation time */
2175 avio_rb32(pb); /* modification time */
2177 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2178 avio_rb32(pb); /* reserved */
2180 /* highlevel (considering edits) duration in movie timebase */
2181 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2182 avio_rb32(pb); /* reserved */
2183 avio_rb32(pb); /* reserved */
2185 avio_rb16(pb); /* layer */
2186 avio_rb16(pb); /* alternate group */
2187 avio_rb16(pb); /* volume */
2188 avio_rb16(pb); /* reserved */
2190 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2191 // they're kept in fixed point format through all calculations
2192 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2193 for (i = 0; i < 3; i++) {
2194 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2195 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2196 avio_rb32(pb); // 2.30 fixed point (not used)
2199 width = avio_rb32(pb); // 16.16 fixed point track width
2200 height = avio_rb32(pb); // 16.16 fixed point track height
2201 sc->width = width >> 16;
2202 sc->height = height >> 16;
2204 //Assign clockwise rotate values based on transform matrix so that
2205 //we can compensate for iPhone orientation during capture.
2207 if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2208 av_dict_set(&st->metadata, "rotate", "90", 0);
2211 if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2212 av_dict_set(&st->metadata, "rotate", "180", 0);
2215 if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2216 av_dict_set(&st->metadata, "rotate", "270", 0);
2219 // transform the display width/height according to the matrix
2220 // skip this if the display matrix is the default identity matrix
2221 // or if it is rotating the picture, ex iPhone 3GS
2222 // to keep the same scale, use [width height 1<<16]
2223 if (width && height &&
2224 ((display_matrix[0][0] != 65536 ||
2225 display_matrix[1][1] != 65536) &&
2226 !display_matrix[0][1] &&
2227 !display_matrix[1][0] &&
2228 !display_matrix[2][0] && !display_matrix[2][1])) {
2229 for (i = 0; i < 2; i++)
2231 (int64_t) width * display_matrix[0][i] +
2232 (int64_t) height * display_matrix[1][i] +
2233 ((int64_t) display_matrix[2][i] << 16);
2235 //sample aspect ratio is new width/height divided by old width/height
2236 st->sample_aspect_ratio = av_d2q(
2237 ((double) disp_transform[0] * height) /
2238 ((double) disp_transform[1] * width), INT_MAX);
2243 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2245 MOVFragment *frag = &c->fragment;
2246 MOVTrackExt *trex = NULL;
2247 int flags, track_id, i;
2249 avio_r8(pb); /* version */
2250 flags = avio_rb24(pb);
2252 track_id = avio_rb32(pb);
2254 return AVERROR_INVALIDDATA;
2255 frag->track_id = track_id;
2256 for (i = 0; i < c->trex_count; i++)
2257 if (c->trex_data[i].track_id == frag->track_id) {
2258 trex = &c->trex_data[i];
2262 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2263 return AVERROR_INVALIDDATA;
2266 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2267 avio_rb64(pb) : frag->moof_offset;
2268 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2270 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2271 avio_rb32(pb) : trex->duration;
2272 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2273 avio_rb32(pb) : trex->size;
2274 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2275 avio_rb32(pb) : trex->flags;
2276 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2280 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2282 c->chapter_track = avio_rb32(pb);
2286 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2290 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2291 return AVERROR_INVALIDDATA;
2292 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2294 return AVERROR(ENOMEM);
2296 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2298 c->trex_data = trex;
2299 trex = &c->trex_data[c->trex_count++];
2300 avio_r8(pb); /* version */
2301 avio_rb24(pb); /* flags */
2302 trex->track_id = avio_rb32(pb);
2303 trex->stsd_id = avio_rb32(pb);
2304 trex->duration = avio_rb32(pb);
2305 trex->size = avio_rb32(pb);
2306 trex->flags = avio_rb32(pb);
2310 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2312 MOVFragment *frag = &c->fragment;
2313 AVStream *st = NULL;
2314 MOVStreamContext *sc;
2318 int data_offset = 0;
2319 unsigned entries, first_sample_flags = frag->flags;
2320 int flags, distance, i, found_keyframe = 0;
2322 for (i = 0; i < c->fc->nb_streams; i++) {
2323 if (c->fc->streams[i]->id == frag->track_id) {
2324 st = c->fc->streams[i];
2329 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2330 return AVERROR_INVALIDDATA;
2333 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2335 avio_r8(pb); /* version */
2336 flags = avio_rb24(pb);
2337 entries = avio_rb32(pb);
2338 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2340 /* Always assume the presence of composition time offsets.
2341 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2342 * 1) in the initial movie, there are no samples.
2343 * 2) in the first movie fragment, there is only one sample without composition time offset.
2344 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2345 if (!sc->ctts_count && sc->sample_count)
2347 /* Complement ctts table if moov atom doesn't have ctts atom. */
2348 ctts_data = av_malloc(sizeof(*sc->ctts_data));
2350 return AVERROR(ENOMEM);
2351 sc->ctts_data = ctts_data;
2352 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2353 sc->ctts_data[sc->ctts_count].duration = 0;
2356 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2357 return AVERROR_INVALIDDATA;
2358 ctts_data = av_realloc(sc->ctts_data,
2359 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2361 return AVERROR(ENOMEM);
2362 sc->ctts_data = ctts_data;
2364 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2365 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2366 dts = sc->track_end - sc->time_offset;
2367 offset = frag->base_data_offset + data_offset;
2369 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2370 for (i = 0; i < entries; i++) {
2371 unsigned sample_size = frag->size;
2372 int sample_flags = i ? frag->flags : first_sample_flags;
2373 unsigned sample_duration = frag->duration;
2376 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2377 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2378 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2379 sc->ctts_data[sc->ctts_count].count = 1;
2380 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2383 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2385 else if (!found_keyframe)
2386 keyframe = found_keyframe =
2387 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2388 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2391 av_add_index_entry(st, offset, dts, sample_size, distance,
2392 keyframe ? AVINDEX_KEYFRAME : 0);
2393 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2394 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2395 offset, dts, sample_size, distance, keyframe);
2397 dts += sample_duration;
2398 offset += sample_size;
2399 sc->data_size += sample_size;
2401 frag->moof_offset = offset;
2402 st->duration = sc->track_end = dts + sc->time_offset;
2406 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2407 /* like the files created with Adobe Premiere 5.0, for samples see */
2408 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2409 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2414 return 0; /* continue */
2415 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2416 avio_skip(pb, atom.size - 4);
2419 atom.type = avio_rl32(pb);
2421 if (atom.type != MKTAG('m','d','a','t')) {
2422 avio_skip(pb, atom.size);
2425 err = mov_read_mdat(c, pb, atom);
2429 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2434 uint8_t *moov_data; /* uncompressed data */
2435 long cmov_len, moov_len;
2438 avio_rb32(pb); /* dcom atom */
2439 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2440 return AVERROR_INVALIDDATA;
2441 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2442 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2443 return AVERROR_INVALIDDATA;
2445 avio_rb32(pb); /* cmvd atom */
2446 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2447 return AVERROR_INVALIDDATA;
2448 moov_len = avio_rb32(pb); /* uncompressed size */
2449 cmov_len = atom.size - 6 * 4;
2451 cmov_data = av_malloc(cmov_len);
2453 return AVERROR(ENOMEM);
2454 moov_data = av_malloc(moov_len);
2457 return AVERROR(ENOMEM);
2459 avio_read(pb, cmov_data, cmov_len);
2460 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2461 goto free_and_return;
2462 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2463 goto free_and_return;
2464 atom.type = MKTAG('m','o','o','v');
2465 atom.size = moov_len;
2466 ret = mov_read_default(c, &ctx, atom);
2472 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2473 return AVERROR(ENOSYS);
2477 /* edit list atom */
2478 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2480 MOVStreamContext *sc;
2481 int i, edit_count, version, edit_start_index = 0;
2483 if (c->fc->nb_streams < 1)
2485 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2487 version = avio_r8(pb); /* version */
2488 avio_rb24(pb); /* flags */
2489 edit_count = avio_rb32(pb); /* entries */
2491 if ((uint64_t)edit_count*12+8 > atom.size)
2492 return AVERROR_INVALIDDATA;
2494 for (i=0; i<edit_count; i++){
2498 duration = avio_rb64(pb);
2499 time = avio_rb64(pb);
2501 duration = avio_rb32(pb); /* segment duration */
2502 time = (int32_t)avio_rb32(pb); /* media time */
2504 avio_rb32(pb); /* Media rate */
2505 if (i == 0 && time == -1) {
2506 sc->empty_duration = duration;
2507 edit_start_index = 1;
2508 } else if (i == edit_start_index && time >= 0)
2509 sc->start_time = time;
2513 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2514 "a/v desync might occur, patch welcome\n");
2516 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2520 static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2525 ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
2529 static const MOVParseTableEntry mov_default_parse_table[] = {
2530 { MKTAG('a','v','s','s'), mov_read_avss },
2531 { MKTAG('c','h','p','l'), mov_read_chpl },
2532 { MKTAG('c','o','6','4'), mov_read_stco },
2533 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2534 { MKTAG('d','i','n','f'), mov_read_default },
2535 { MKTAG('d','r','e','f'), mov_read_dref },
2536 { MKTAG('e','d','t','s'), mov_read_default },
2537 { MKTAG('e','l','s','t'), mov_read_elst },
2538 { MKTAG('e','n','d','a'), mov_read_enda },
2539 { MKTAG('f','i','e','l'), mov_read_fiel },
2540 { MKTAG('f','t','y','p'), mov_read_ftyp },
2541 { MKTAG('g','l','b','l'), mov_read_glbl },
2542 { MKTAG('h','d','l','r'), mov_read_hdlr },
2543 { MKTAG('i','l','s','t'), mov_read_ilst },
2544 { MKTAG('j','p','2','h'), mov_read_jp2h },
2545 { MKTAG('m','d','a','t'), mov_read_mdat },
2546 { MKTAG('m','d','h','d'), mov_read_mdhd },
2547 { MKTAG('m','d','i','a'), mov_read_default },
2548 { MKTAG('m','e','t','a'), mov_read_meta },
2549 { MKTAG('m','i','n','f'), mov_read_default },
2550 { MKTAG('m','o','o','f'), mov_read_moof },
2551 { MKTAG('m','o','o','v'), mov_read_moov },
2552 { MKTAG('m','v','e','x'), mov_read_default },
2553 { MKTAG('m','v','h','d'), mov_read_mvhd },
2554 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2555 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
2556 { MKTAG('a','v','c','C'), mov_read_glbl },
2557 { MKTAG('p','a','s','p'), mov_read_pasp },
2558 { MKTAG('s','t','b','l'), mov_read_default },
2559 { MKTAG('s','t','c','o'), mov_read_stco },
2560 { MKTAG('s','t','p','s'), mov_read_stps },
2561 { MKTAG('s','t','r','f'), mov_read_strf },
2562 { MKTAG('s','t','s','c'), mov_read_stsc },
2563 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2564 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2565 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2566 { MKTAG('s','t','t','s'), mov_read_stts },
2567 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2568 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2569 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2570 { MKTAG('t','r','a','k'), mov_read_trak },
2571 { MKTAG('t','r','a','f'), mov_read_default },
2572 { MKTAG('t','r','e','f'), mov_read_default },
2573 { MKTAG('c','h','a','p'), mov_read_chap },
2574 { MKTAG('t','r','e','x'), mov_read_trex },
2575 { MKTAG('t','r','u','n'), mov_read_trun },
2576 { MKTAG('u','d','t','a'), mov_read_default },
2577 { MKTAG('w','a','v','e'), mov_read_wave },
2578 { MKTAG('e','s','d','s'), mov_read_esds },
2579 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2580 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2581 { MKTAG('w','f','e','x'), mov_read_wfex },
2582 { MKTAG('c','m','o','v'), mov_read_cmov },
2583 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2584 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2588 static int mov_probe(AVProbeData *p)
2590 unsigned int offset;
2594 /* check file header */
2597 /* ignore invalid offset */
2598 if ((offset + 8) > (unsigned int)p->buf_size)
2600 tag = AV_RL32(p->buf + offset + 4);
2602 /* check for obvious tags */
2603 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2604 case MKTAG('m','o','o','v'):
2605 case MKTAG('m','d','a','t'):
2606 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2607 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2608 case MKTAG('f','t','y','p'):
2609 return AVPROBE_SCORE_MAX;
2610 /* those are more common words, so rate then a bit less */
2611 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2612 case MKTAG('w','i','d','e'):
2613 case MKTAG('f','r','e','e'):
2614 case MKTAG('j','u','n','k'):
2615 case MKTAG('p','i','c','t'):
2616 return AVPROBE_SCORE_MAX - 5;
2617 case MKTAG(0x82,0x82,0x7f,0x7d):
2618 case MKTAG('s','k','i','p'):
2619 case MKTAG('u','u','i','d'):
2620 case MKTAG('p','r','f','l'):
2621 offset = AV_RB32(p->buf+offset) + offset;
2622 /* if we only find those cause probedata is too small at least rate them */
2623 score = AVPROBE_SCORE_MAX - 50;
2626 /* unrecognized tag */
2632 // must be done after parsing all trak because there's no order requirement
2633 static void mov_read_chapters(AVFormatContext *s)
2635 MOVContext *mov = s->priv_data;
2636 AVStream *st = NULL;
2637 MOVStreamContext *sc;
2641 for (i = 0; i < s->nb_streams; i++)
2642 if (s->streams[i]->id == mov->chapter_track) {
2647 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2651 st->discard = AVDISCARD_ALL;
2653 cur_pos = avio_tell(sc->pb);
2655 for (i = 0; i < st->nb_index_entries; i++) {
2656 AVIndexEntry *sample = &st->index_entries[i];
2657 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2662 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2663 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2667 // the first two bytes are the length of the title
2668 len = avio_rb16(sc->pb);
2669 if (len > sample->size-2)
2671 title_len = 2*len + 1;
2672 if (!(title = av_mallocz(title_len)))
2675 // The samples could theoretically be in any encoding if there's an encd
2676 // atom following, but in practice are only utf-8 or utf-16, distinguished
2677 // instead by the presence of a BOM
2681 ch = avio_rb16(sc->pb);
2683 avio_get_str16be(sc->pb, len, title, title_len);
2684 else if (ch == 0xfffe)
2685 avio_get_str16le(sc->pb, len, title, title_len);
2688 if (len == 1 || len == 2)
2691 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
2695 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2699 avio_seek(sc->pb, cur_pos, SEEK_SET);
2702 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
2703 uint32_t value, int flags)
2706 char buf[AV_TIMECODE_STR_SIZE];
2707 AVRational rate = {st->codec->time_base.den,
2708 st->codec->time_base.num};
2709 int ret = av_timecode_init(&tc, rate, flags, 0, s);
2712 av_dict_set(&st->metadata, "timecode",
2713 av_timecode_make_string(&tc, buf, value), 0);
2717 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
2719 MOVStreamContext *sc = st->priv_data;
2721 int64_t cur_pos = avio_tell(sc->pb);
2724 if (!st->nb_index_entries)
2727 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
2728 value = avio_rb32(s->pb);
2730 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
2731 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
2732 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
2734 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
2735 * not the case) and thus assume "frame number format" instead of QT one.
2736 * No sample with tmcd track can be found with a QT timecode at the moment,
2737 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
2739 parse_timecode_in_framenum_format(s, st, value, flags);
2741 avio_seek(sc->pb, cur_pos, SEEK_SET);
2745 static int mov_read_header(AVFormatContext *s)
2747 MOVContext *mov = s->priv_data;
2748 AVIOContext *pb = s->pb;
2750 MOVAtom atom = { AV_RL32("root") };
2753 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2755 atom.size = avio_size(pb);
2757 atom.size = INT64_MAX;
2759 /* check MOV header */
2760 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2761 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2764 if (!mov->found_moov) {
2765 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2766 return AVERROR_INVALIDDATA;
2768 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2772 if (mov->chapter_track > 0)
2773 mov_read_chapters(s);
2774 for (i = 0; i < s->nb_streams; i++)
2775 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
2776 mov_read_timecode_track(s, s->streams[i]);
2779 if (mov->trex_data) {
2781 for (i = 0; i < s->nb_streams; i++) {
2782 AVStream *st = s->streams[i];
2783 MOVStreamContext *sc = st->priv_data;
2785 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
2792 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2794 AVIndexEntry *sample = NULL;
2795 int64_t best_dts = INT64_MAX;
2797 for (i = 0; i < s->nb_streams; i++) {
2798 AVStream *avst = s->streams[i];
2799 MOVStreamContext *msc = avst->priv_data;
2800 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2801 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2802 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2803 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2804 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2806 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2807 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2808 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2809 sample = current_sample;
2818 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2820 MOVContext *mov = s->priv_data;
2821 MOVStreamContext *sc;
2822 AVIndexEntry *sample;
2823 AVStream *st = NULL;
2827 sample = mov_find_next_sample(s, &st);
2829 mov->found_mdat = 0;
2830 if (!mov->next_root_atom)
2832 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
2833 mov->next_root_atom = 0;
2834 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2837 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2841 /* must be done just before reading, to avoid infinite loop on sample */
2842 sc->current_sample++;
2844 if (st->discard != AVDISCARD_ALL) {
2845 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2846 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2847 sc->ffindex, sample->pos);
2848 return AVERROR_INVALIDDATA;
2850 ret = av_get_packet(sc->pb, pkt, sample->size);
2853 if (sc->has_palette) {
2856 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2858 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2860 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2861 sc->has_palette = 0;
2864 #if CONFIG_DV_DEMUXER
2865 if (mov->dv_demux && sc->dv_audio_container) {
2866 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
2869 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
2876 pkt->stream_index = sc->ffindex;
2877 pkt->dts = sample->timestamp;
2878 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
2879 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2880 /* update ctts context */
2882 if (sc->ctts_index < sc->ctts_count &&
2883 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2885 sc->ctts_sample = 0;
2888 pkt->dts = AV_NOPTS_VALUE;
2890 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2891 st->index_entries[sc->current_sample].timestamp : st->duration;
2892 pkt->duration = next_dts - pkt->dts;
2893 pkt->pts = pkt->dts;
2895 if (st->discard == AVDISCARD_ALL)
2897 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2898 pkt->pos = sample->pos;
2899 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2900 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2904 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2906 MOVStreamContext *sc = st->priv_data;
2907 int sample, time_sample;
2910 sample = av_index_search_timestamp(st, timestamp, flags);
2911 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2912 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2914 if (sample < 0) /* not sure what to do */
2915 return AVERROR_INVALIDDATA;
2916 sc->current_sample = sample;
2917 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2918 /* adjust ctts index */
2919 if (sc->ctts_data) {
2921 for (i = 0; i < sc->ctts_count; i++) {
2922 int next = time_sample + sc->ctts_data[i].count;
2923 if (next > sc->current_sample) {
2925 sc->ctts_sample = sc->current_sample - time_sample;
2934 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2937 int64_t seek_timestamp, timestamp;
2941 if (stream_index >= s->nb_streams)
2942 return AVERROR_INVALIDDATA;
2943 if (sample_time < 0)
2946 st = s->streams[stream_index];
2947 sample = mov_seek_stream(s, st, sample_time, flags);
2951 /* adjust seek timestamp to found sample timestamp */
2952 seek_timestamp = st->index_entries[sample].timestamp;
2954 for (i = 0; i < s->nb_streams; i++) {
2956 if (stream_index == i)
2959 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2960 mov_seek_stream(s, st, timestamp, flags);
2965 static int mov_read_close(AVFormatContext *s)
2967 MOVContext *mov = s->priv_data;
2970 for (i = 0; i < s->nb_streams; i++) {
2971 AVStream *st = s->streams[i];
2972 MOVStreamContext *sc = st->priv_data;
2974 av_freep(&sc->ctts_data);
2975 for (j = 0; j < sc->drefs_count; j++) {
2976 av_freep(&sc->drefs[j].path);
2977 av_freep(&sc->drefs[j].dir);
2979 av_freep(&sc->drefs);
2980 if (sc->pb && sc->pb != s->pb)
2984 if (mov->dv_demux) {
2985 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2986 av_freep(&mov->dv_fctx->streams[i]->codec);
2987 av_freep(&mov->dv_fctx->streams[i]);
2989 av_freep(&mov->dv_fctx);
2990 av_freep(&mov->dv_demux);
2993 av_freep(&mov->trex_data);
2998 static const AVOption options[] = {
2999 {"use_absolute_path",
3000 "allow using absolute path when opening alias, this is a possible security issue",
3001 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.dbl = 0},
3002 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3005 static const AVClass class = {"mov,mp4,m4a,3gp,3g2,mj2", av_default_item_name, options, LIBAVUTIL_VERSION_INT};
3007 AVInputFormat ff_mov_demuxer = {
3008 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3009 .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
3010 .priv_data_size = sizeof(MOVContext),
3011 .read_probe = mov_probe,
3012 .read_header = mov_read_header,
3013 .read_packet = mov_read_packet,
3014 .read_close = mov_read_close,
3015 .read_seek = mov_read_seek,
3016 .priv_class = &class,