3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 //#define MOV_EXPORT_ALL_METADATA
28 #include "libavutil/attributes.h"
29 #include "libavutil/channel_layout.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/intfloat.h"
32 #include "libavutil/mathematics.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/dict.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/timecode.h"
37 #include "libavcodec/ac3tab.h"
40 #include "avio_internal.h"
43 #include "libavcodec/get_bits.h"
52 * First version by Francois Revol revol@free.fr
53 * Seek function by Gael Chardon gael.dev@4now.net
56 #include "qtpalette.h"
62 /* those functions parse an atom */
63 /* links atom IDs to parse functions */
64 typedef struct MOVParseTableEntry {
66 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
69 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
71 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
72 unsigned len, const char *key)
76 short current, total = 0;
77 avio_rb16(pb); // unknown
78 current = avio_rb16(pb);
80 total = avio_rb16(pb);
82 snprintf(buf, sizeof(buf), "%d", current);
84 snprintf(buf, sizeof(buf), "%d/%d", current, total);
85 av_dict_set(&c->fc->metadata, key, buf, 0);
90 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
91 unsigned len, const char *key)
95 /* bypass padding bytes */
100 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
101 av_dict_set(&c->fc->metadata, key, buf, 0);
106 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
107 unsigned len, const char *key)
111 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
112 av_dict_set(&c->fc->metadata, key, buf, 0);
117 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
118 unsigned len, const char *key)
123 avio_r8(pb); // unknown
126 if (genre < 1 || genre > ID3v1_GENRE_MAX)
128 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
129 av_dict_set(&c->fc->metadata, key, buf, 0);
134 static int mov_read_custom_metadata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
136 char key[1024]={0}, data[1024]={0};
139 MOVStreamContext *sc;
141 if (c->fc->nb_streams < 1)
143 st = c->fc->streams[c->fc->nb_streams-1];
146 if (atom.size <= 8) return 0;
148 for (i = 0; i < 3; i++) { // Parse up to three sub-atoms looking for name and data.
149 int data_size = avio_rb32(pb);
150 int tag = avio_rl32(pb);
151 int str_size = 0, skip_size = 0;
155 case MKTAG('n','a','m','e'):
156 avio_rb32(pb); // version/flags
157 str_size = skip_size = data_size - 12;
161 case MKTAG('d','a','t','a'):
162 avio_rb32(pb); // version/flags
163 avio_rb32(pb); // reserved (zero)
164 str_size = skip_size = data_size - 16;
169 skip_size = data_size - 8;
175 str_size = FFMIN3(sizeof(data)-1, str_size, atom.size);
176 avio_read(pb, target, str_size);
177 target[str_size] = 0;
179 atom.size -= skip_size;
181 // If we didn't read the full data chunk for the sub-atom, skip to the end of it.
182 if (skip_size > str_size) avio_skip(pb, skip_size - str_size);
186 if (strcmp(key, "iTunSMPB") == 0) {
187 int priming, remainder, samples;
188 if(sscanf(data, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
189 if(priming>0 && priming<16384)
190 sc->start_pad = priming;
194 if (strcmp(key, "cdec") == 0) {
195 // av_dict_set(&st->metadata, key, data, 0);
202 static const uint32_t mac_to_unicode[128] = {
203 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
204 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
205 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
206 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
207 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
208 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
209 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
210 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
211 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
212 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
213 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
214 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
215 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
216 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
217 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
218 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
221 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
222 char *dst, int dstlen)
225 char *end = dst+dstlen-1;
228 for (i = 0; i < len; i++) {
229 uint8_t t, c = avio_r8(pb);
230 if (c < 0x80 && p < end)
233 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
239 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
243 MOVStreamContext *sc;
248 case 0xd: id = AV_CODEC_ID_MJPEG; break;
249 case 0xe: id = AV_CODEC_ID_PNG; break;
250 case 0x1b: id = AV_CODEC_ID_BMP; break;
252 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
257 st = avformat_new_stream(c->fc, NULL);
259 return AVERROR(ENOMEM);
260 sc = av_mallocz(sizeof(*sc));
262 return AVERROR(ENOMEM);
265 ret = av_get_packet(pb, &pkt, len);
269 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
271 st->attached_pic = pkt;
272 st->attached_pic.stream_index = st->index;
273 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
275 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
276 st->codec->codec_id = id;
281 static int mov_metadata_raw(MOVContext *c, AVIOContext *pb,
282 unsigned len, const char *key)
284 char *value = av_malloc(len + 1);
286 return AVERROR(ENOMEM);
287 avio_read(pb, value, len);
289 return av_dict_set(&c->fc->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);
292 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
294 #ifdef MOV_EXPORT_ALL_METADATA
297 char str[1024], key2[16], language[4] = {0};
298 const char *key = NULL;
299 uint16_t langcode = 0;
300 uint32_t data_type = 0, str_size;
301 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
303 if (c->itunes_metadata && atom.type == MKTAG('-','-','-','-'))
304 return mov_read_custom_metadata(c, pb, atom);
307 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
308 case MKTAG(0xa9,'a','u','t'):
309 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
310 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
311 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
312 case MKTAG( 'c','p','r','t'):
313 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
314 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
315 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
316 case MKTAG(0xa9,'c','m','t'):
317 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
318 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
319 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
320 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
321 case MKTAG( 'g','n','r','e'): key = "genre";
322 parse = mov_metadata_gnre; break;
323 case MKTAG(0xa9,'t','o','o'):
324 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
325 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
326 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
327 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
328 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
329 case MKTAG( 'd','e','s','c'): key = "description";break;
330 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
331 case MKTAG( 't','v','s','h'): key = "show"; break;
332 case MKTAG( 't','v','e','n'): key = "episode_id";break;
333 case MKTAG( 't','v','n','n'): key = "network"; break;
334 case MKTAG( 't','r','k','n'): key = "track";
335 parse = mov_metadata_track_or_disc_number; break;
336 case MKTAG( 'd','i','s','k'): key = "disc";
337 parse = mov_metadata_track_or_disc_number; break;
338 case MKTAG( 't','v','e','s'): key = "episode_sort";
339 parse = mov_metadata_int8_bypass_padding; break;
340 case MKTAG( 't','v','s','n'): key = "season_number";
341 parse = mov_metadata_int8_bypass_padding; break;
342 case MKTAG( 's','t','i','k'): key = "media_type";
343 parse = mov_metadata_int8_no_padding; break;
344 case MKTAG( 'h','d','v','d'): key = "hd_video";
345 parse = mov_metadata_int8_no_padding; break;
346 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
347 parse = mov_metadata_int8_no_padding; break;
348 case MKTAG( '@','P','R','M'):
349 return mov_metadata_raw(c, pb, atom.size, "premiere_version");
350 case MKTAG( '@','P','R','Q'):
351 return mov_metadata_raw(c, pb, atom.size, "quicktime_version");
354 if (c->itunes_metadata && atom.size > 8) {
355 int data_size = avio_rb32(pb);
356 int tag = avio_rl32(pb);
357 if (tag == MKTAG('d','a','t','a')) {
358 data_type = avio_rb32(pb); // type
359 avio_rb32(pb); // unknown
360 str_size = data_size - 16;
363 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
364 int ret = mov_read_covr(c, pb, data_type, str_size);
366 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
371 } else if (atom.size > 4 && key && !c->itunes_metadata) {
372 str_size = avio_rb16(pb); // string length
373 langcode = avio_rb16(pb);
374 ff_mov_lang_to_iso639(langcode, language);
377 str_size = atom.size;
379 #ifdef MOV_EXPORT_ALL_METADATA
381 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
389 return AVERROR_INVALIDDATA;
391 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
394 parse(c, pb, str_size, key);
396 if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
397 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
399 avio_read(pb, str, str_size);
402 av_dict_set(&c->fc->metadata, key, str, 0);
403 if (*language && strcmp(language, "und")) {
404 snprintf(key2, sizeof(key2), "%s-%s", key, language);
405 av_dict_set(&c->fc->metadata, key2, str, 0);
408 av_dlog(c->fc, "lang \"%3s\" ", language);
409 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
410 key, str, (char*)&atom.type, str_size, atom.size);
415 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
418 int i, nb_chapters, str_len, version;
421 if ((atom.size -= 5) < 0)
424 version = avio_r8(pb);
427 avio_rb32(pb); // ???
428 nb_chapters = avio_r8(pb);
430 for (i = 0; i < nb_chapters; i++) {
434 start = avio_rb64(pb);
435 str_len = avio_r8(pb);
437 if ((atom.size -= 9+str_len) < 0)
440 avio_read(pb, str, str_len);
442 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
447 #define MIN_DATA_ENTRY_BOX_SIZE 12
448 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
451 MOVStreamContext *sc;
454 if (c->fc->nb_streams < 1)
456 st = c->fc->streams[c->fc->nb_streams-1];
459 avio_rb32(pb); // version + flags
460 entries = avio_rb32(pb);
461 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
462 entries >= UINT_MAX / sizeof(*sc->drefs))
463 return AVERROR_INVALIDDATA;
466 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
468 return AVERROR(ENOMEM);
469 sc->drefs_count = entries;
471 for (i = 0; i < sc->drefs_count; i++) {
472 MOVDref *dref = &sc->drefs[i];
473 uint32_t size = avio_rb32(pb);
474 int64_t next = avio_tell(pb) + size - 4;
477 return AVERROR_INVALIDDATA;
479 dref->type = avio_rl32(pb);
480 avio_rb32(pb); // version + flags
481 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
483 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
484 /* macintosh alias record */
485 uint16_t volume_len, len;
490 volume_len = avio_r8(pb);
491 volume_len = FFMIN(volume_len, 27);
492 avio_read(pb, dref->volume, 27);
493 dref->volume[volume_len] = 0;
494 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
499 len = FFMIN(len, 63);
500 avio_read(pb, dref->filename, 63);
501 dref->filename[len] = 0;
502 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
506 /* read next level up_from_alias/down_to_target */
507 dref->nlvl_from = avio_rb16(pb);
508 dref->nlvl_to = avio_rb16(pb);
509 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
510 dref->nlvl_from, dref->nlvl_to);
514 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
517 type = avio_rb16(pb);
519 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
522 if (type == 2) { // absolute path
524 dref->path = av_mallocz(len+1);
526 return AVERROR(ENOMEM);
527 avio_read(pb, dref->path, len);
528 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
530 memmove(dref->path, dref->path+volume_len, len);
533 for (j = 0; j < len; j++)
534 if (dref->path[j] == ':')
536 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
537 } else if (type == 0) { // directory name
539 dref->dir = av_malloc(len+1);
541 return AVERROR(ENOMEM);
542 avio_read(pb, dref->dir, len);
544 for (j = 0; j < len; j++)
545 if (dref->dir[j] == ':')
547 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
552 avio_seek(pb, next, SEEK_SET);
557 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
561 uint32_t av_unused ctype;
565 if (c->fc->nb_streams < 1) // meta before first trak
568 st = c->fc->streams[c->fc->nb_streams-1];
570 avio_r8(pb); /* version */
571 avio_rb24(pb); /* flags */
574 ctype = avio_rl32(pb);
575 type = avio_rl32(pb); /* component subtype */
577 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
578 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
580 if (type == MKTAG('v','i','d','e'))
581 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
582 else if (type == MKTAG('s','o','u','n'))
583 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
584 else if (type == MKTAG('m','1','a',' '))
585 st->codec->codec_id = AV_CODEC_ID_MP2;
586 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
587 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
589 avio_rb32(pb); /* component manufacture */
590 avio_rb32(pb); /* component flags */
591 avio_rb32(pb); /* component flags mask */
593 title_size = atom.size - 24;
594 if (title_size > 0) {
595 title_str = av_malloc(title_size + 1); /* Add null terminator */
597 return AVERROR(ENOMEM);
598 avio_read(pb, title_str, title_size);
599 title_str[title_size] = 0;
601 av_dict_set(&st->metadata, "handler_name", title_str +
602 (!c->isom && title_str[0] == title_size - 1), 0);
603 av_freep(&title_str);
609 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
614 if (fc->nb_streams < 1)
616 st = fc->streams[fc->nb_streams-1];
618 avio_rb32(pb); /* version + flags */
619 ff_mp4_read_descr(fc, pb, &tag);
620 if (tag == MP4ESDescrTag) {
621 ff_mp4_parse_es_descr(pb, NULL);
623 avio_rb16(pb); /* ID */
625 ff_mp4_read_descr(fc, pb, &tag);
626 if (tag == MP4DecConfigDescrTag)
627 ff_mp4_read_dec_config_descr(fc, st, pb);
631 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
633 return ff_mov_read_esds(c->fc, pb, atom);
636 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
639 int ac3info, acmod, lfeon, bsmod;
641 if (c->fc->nb_streams < 1)
643 st = c->fc->streams[c->fc->nb_streams-1];
645 ac3info = avio_rb24(pb);
646 bsmod = (ac3info >> 14) & 0x7;
647 acmod = (ac3info >> 11) & 0x7;
648 lfeon = (ac3info >> 10) & 0x1;
649 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
650 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
652 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
653 st->codec->audio_service_type = bsmod;
654 if (st->codec->channels > 1 && bsmod == 0x7)
655 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
660 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
663 int eac3info, acmod, lfeon, bsmod;
665 if (c->fc->nb_streams < 1)
667 st = c->fc->streams[c->fc->nb_streams-1];
669 /* No need to parse fields for additional independent substreams and its
670 * associated dependent substreams since libavcodec's E-AC-3 decoder
671 * does not support them yet. */
672 avio_rb16(pb); /* data_rate and num_ind_sub */
673 eac3info = avio_rb24(pb);
674 bsmod = (eac3info >> 12) & 0x1f;
675 acmod = (eac3info >> 9) & 0x7;
676 lfeon = (eac3info >> 8) & 0x1;
677 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
679 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
680 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
681 st->codec->audio_service_type = bsmod;
682 if (st->codec->channels > 1 && bsmod == 0x7)
683 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
688 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
692 if (c->fc->nb_streams < 1)
694 st = c->fc->streams[c->fc->nb_streams-1];
699 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
704 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
708 if (c->fc->nb_streams < 1)
710 st = c->fc->streams[c->fc->nb_streams-1];
712 if (ff_get_wav_header(pb, st->codec, atom.size) < 0) {
713 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
719 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
721 const int num = avio_rb32(pb);
722 const int den = avio_rb32(pb);
725 if (c->fc->nb_streams < 1)
727 st = c->fc->streams[c->fc->nb_streams-1];
729 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
730 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
731 av_log(c->fc, AV_LOG_WARNING,
732 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
733 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
735 } else if (den != 0) {
736 st->sample_aspect_ratio.num = num;
737 st->sample_aspect_ratio.den = den;
742 /* this atom contains actual media data */
743 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
745 if (atom.size == 0) /* wrong one (MP4) */
748 return 0; /* now go for moov */
751 /* read major brand, minor version and compatible brands and store them as metadata */
752 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
756 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
757 char* comp_brands_str;
758 uint8_t type[5] = {0};
760 avio_read(pb, type, 4);
761 if (strcmp(type, "qt "))
763 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
764 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
765 minor_ver = avio_rb32(pb); /* minor version */
766 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
767 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
769 comp_brand_size = atom.size - 8;
770 if (comp_brand_size < 0)
771 return AVERROR_INVALIDDATA;
772 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
773 if (!comp_brands_str)
774 return AVERROR(ENOMEM);
775 avio_read(pb, comp_brands_str, comp_brand_size);
776 comp_brands_str[comp_brand_size] = 0;
777 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
778 av_freep(&comp_brands_str);
783 /* this atom should contain all header atoms */
784 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
788 if ((ret = mov_read_default(c, pb, atom)) < 0)
790 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
791 /* so we don't parse the whole file if over a network */
793 return 0; /* now go for mdat */
796 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
798 c->fragment.moof_offset = avio_tell(pb) - 8;
799 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
800 return mov_read_default(c, pb, atom);
803 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
809 if(time >= 2082844800)
810 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
812 ptm = gmtime(&timet);
814 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
815 av_dict_set(metadata, "creation_time", buffer, 0);
819 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
822 MOVStreamContext *sc;
824 char language[4] = {0};
826 int64_t creation_time;
828 if (c->fc->nb_streams < 1)
830 st = c->fc->streams[c->fc->nb_streams-1];
833 version = avio_r8(pb);
835 av_log_ask_for_sample(c, "unsupported version %d\n", version);
836 return AVERROR_PATCHWELCOME;
838 avio_rb24(pb); /* flags */
840 creation_time = avio_rb64(pb);
843 creation_time = avio_rb32(pb);
844 avio_rb32(pb); /* modification time */
846 mov_metadata_creation_time(&st->metadata, creation_time);
848 sc->time_scale = avio_rb32(pb);
849 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
851 lang = avio_rb16(pb); /* language */
852 if (ff_mov_lang_to_iso639(lang, language))
853 av_dict_set(&st->metadata, "language", language, 0);
854 avio_rb16(pb); /* quality */
859 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
861 int64_t creation_time;
862 int version = avio_r8(pb); /* version */
863 avio_rb24(pb); /* flags */
866 creation_time = avio_rb64(pb);
869 creation_time = avio_rb32(pb);
870 avio_rb32(pb); /* modification time */
872 mov_metadata_creation_time(&c->fc->metadata, creation_time);
873 c->time_scale = avio_rb32(pb); /* time scale */
875 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
877 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
878 // set the AVCodecContext duration because the duration of individual tracks
880 if (c->time_scale > 0)
881 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
882 avio_rb32(pb); /* preferred scale */
884 avio_rb16(pb); /* preferred volume */
886 avio_skip(pb, 10); /* reserved */
888 avio_skip(pb, 36); /* display matrix */
890 avio_rb32(pb); /* preview time */
891 avio_rb32(pb); /* preview duration */
892 avio_rb32(pb); /* poster time */
893 avio_rb32(pb); /* selection time */
894 avio_rb32(pb); /* selection duration */
895 avio_rb32(pb); /* current time */
896 avio_rb32(pb); /* next track ID */
900 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
905 if (c->fc->nb_streams < 1)
907 st = c->fc->streams[c->fc->nb_streams-1];
909 little_endian = avio_rb16(pb) & 0xFF;
910 av_dlog(c->fc, "enda %d\n", little_endian);
911 if (little_endian == 1) {
912 switch (st->codec->codec_id) {
913 case AV_CODEC_ID_PCM_S24BE:
914 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
916 case AV_CODEC_ID_PCM_S32BE:
917 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
919 case AV_CODEC_ID_PCM_F32BE:
920 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
922 case AV_CODEC_ID_PCM_F64BE:
923 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
932 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
935 unsigned mov_field_order;
936 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
938 if (c->fc->nb_streams < 1) // will happen with jp2 files
940 st = c->fc->streams[c->fc->nb_streams-1];
942 return AVERROR_INVALIDDATA;
943 mov_field_order = avio_rb16(pb);
944 if ((mov_field_order & 0xFF00) == 0x0100)
945 decoded_field_order = AV_FIELD_PROGRESSIVE;
946 else if ((mov_field_order & 0xFF00) == 0x0200) {
947 switch (mov_field_order & 0xFF) {
948 case 0x01: decoded_field_order = AV_FIELD_TT;
950 case 0x06: decoded_field_order = AV_FIELD_BB;
952 case 0x09: decoded_field_order = AV_FIELD_TB;
954 case 0x0E: decoded_field_order = AV_FIELD_BT;
958 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
959 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
961 st->codec->field_order = decoded_field_order;
966 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
967 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
968 enum AVCodecID codec_id)
974 if (c->fc->nb_streams < 1) // will happen with jp2 files
976 st= c->fc->streams[c->fc->nb_streams-1];
978 if (st->codec->codec_id != codec_id)
979 return 0; /* unexpected codec_id - don't mess with extradata */
981 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
982 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
983 return AVERROR_INVALIDDATA;
984 buf= av_realloc(st->codec->extradata, size);
986 return AVERROR(ENOMEM);
987 st->codec->extradata= buf;
988 buf+= st->codec->extradata_size;
989 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
990 AV_WB32( buf , atom.size + 8);
991 AV_WL32( buf + 4, atom.type);
992 avio_read(pb, buf + 8, atom.size);
996 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
997 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
999 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1002 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1004 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1007 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1009 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1012 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1014 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1017 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1019 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1022 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1026 if (c->fc->nb_streams < 1)
1028 st = c->fc->streams[c->fc->nb_streams-1];
1030 if ((uint64_t)atom.size > (1<<30))
1031 return AVERROR_INVALIDDATA;
1033 if (st->codec->codec_id == AV_CODEC_ID_QDM2 || st->codec->codec_id == AV_CODEC_ID_QDMC) {
1034 // pass all frma atom to codec, needed at least for QDMC and QDM2
1035 av_free(st->codec->extradata);
1036 st->codec->extradata_size = 0;
1037 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1038 if (!st->codec->extradata)
1039 return AVERROR(ENOMEM);
1040 st->codec->extradata_size = atom.size;
1041 avio_read(pb, st->codec->extradata, atom.size);
1042 } else if (atom.size > 8) { /* to read frma, esds atoms */
1044 if ((ret = mov_read_default(c, pb, atom)) < 0)
1047 avio_skip(pb, atom.size);
1052 * This function reads atom content and puts data in extradata without tag
1053 * nor size unlike mov_read_extradata.
1055 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1059 if (c->fc->nb_streams < 1)
1061 st = c->fc->streams[c->fc->nb_streams-1];
1063 if ((uint64_t)atom.size > (1<<30))
1064 return AVERROR_INVALIDDATA;
1066 if (atom.size >= 10) {
1067 // Broken files created by legacy versions of libavformat will
1068 // wrap a whole fiel atom inside of a glbl atom.
1069 unsigned size = avio_rb32(pb);
1070 unsigned type = avio_rl32(pb);
1071 avio_seek(pb, -8, SEEK_CUR);
1072 if (type == MKTAG('f','i','e','l') && size == atom.size)
1073 return mov_read_default(c, pb, atom);
1075 av_free(st->codec->extradata);
1076 st->codec->extradata_size = 0;
1077 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1078 if (!st->codec->extradata)
1079 return AVERROR(ENOMEM);
1080 st->codec->extradata_size = atom.size;
1081 avio_read(pb, st->codec->extradata, atom.size);
1085 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1088 uint8_t profile_level;
1090 if (c->fc->nb_streams < 1)
1092 st = c->fc->streams[c->fc->nb_streams-1];
1094 if (atom.size >= (1<<28) || atom.size < 7)
1095 return AVERROR_INVALIDDATA;
1097 profile_level = avio_r8(pb);
1098 if ((profile_level & 0xf0) != 0xc0)
1101 av_free(st->codec->extradata);
1102 st->codec->extradata_size = 0;
1103 st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
1104 if (!st->codec->extradata)
1105 return AVERROR(ENOMEM);
1106 st->codec->extradata_size = atom.size - 7;
1107 avio_seek(pb, 6, SEEK_CUR);
1108 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
1113 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1114 * but can have extradata appended at the end after the 40 bytes belonging
1117 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1121 if (c->fc->nb_streams < 1)
1123 if (atom.size <= 40)
1125 st = c->fc->streams[c->fc->nb_streams-1];
1127 if ((uint64_t)atom.size > (1<<30))
1128 return AVERROR_INVALIDDATA;
1130 av_free(st->codec->extradata);
1131 st->codec->extradata_size = 0;
1132 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1133 if (!st->codec->extradata)
1134 return AVERROR(ENOMEM);
1135 st->codec->extradata_size = atom.size - 40;
1137 avio_read(pb, st->codec->extradata, atom.size - 40);
1141 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1144 MOVStreamContext *sc;
1145 unsigned int i, entries;
1147 if (c->fc->nb_streams < 1)
1149 st = c->fc->streams[c->fc->nb_streams-1];
1152 avio_r8(pb); /* version */
1153 avio_rb24(pb); /* flags */
1155 entries = avio_rb32(pb);
1159 if (entries >= UINT_MAX/sizeof(int64_t))
1160 return AVERROR_INVALIDDATA;
1162 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1163 if (!sc->chunk_offsets)
1164 return AVERROR(ENOMEM);
1165 sc->chunk_count = entries;
1167 if (atom.type == MKTAG('s','t','c','o'))
1168 for (i = 0; i < entries && !pb->eof_reached; i++)
1169 sc->chunk_offsets[i] = avio_rb32(pb);
1170 else if (atom.type == MKTAG('c','o','6','4'))
1171 for (i = 0; i < entries && !pb->eof_reached; i++)
1172 sc->chunk_offsets[i] = avio_rb64(pb);
1174 return AVERROR_INVALIDDATA;
1176 sc->chunk_count = i;
1178 if (pb->eof_reached)
1185 * Compute codec id for 'lpcm' tag.
1186 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1188 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1195 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1198 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1201 MOVStreamContext *sc;
1202 int j, pseudo_stream_id;
1204 if (c->fc->nb_streams < 1)
1206 st = c->fc->streams[c->fc->nb_streams-1];
1209 for (pseudo_stream_id = 0;
1210 pseudo_stream_id < entries && !pb->eof_reached;
1211 pseudo_stream_id++) {
1212 //Parsing Sample description table
1215 MOVAtom a = { AV_RL32("stsd") };
1216 int64_t start_pos = avio_tell(pb);
1217 int64_t size = avio_rb32(pb); /* size */
1218 uint32_t format = avio_rl32(pb); /* data format */
1221 avio_rb32(pb); /* reserved */
1222 avio_rb16(pb); /* reserved */
1223 dref_id = avio_rb16(pb);
1224 }else if (size <= 7){
1225 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1226 return AVERROR_INVALIDDATA;
1229 if (st->codec->codec_tag &&
1230 st->codec->codec_tag != format &&
1231 (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
1232 : st->codec->codec_tag != MKTAG('j','p','e','g'))
1234 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1235 * export it as a separate AVStream but this needs a few changes
1236 * in the MOV demuxer, patch welcome. */
1237 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1238 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1241 /* we cannot demux concatenated h264 streams because of different extradata */
1242 if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1243 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 might not play corrently.\n");
1244 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1245 sc->dref_id= dref_id;
1247 st->codec->codec_tag = format;
1248 id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1249 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1250 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1252 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1253 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1254 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1255 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1256 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1258 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1260 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1261 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1262 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1263 st->codec->codec_id == AV_CODEC_ID_NONE)){
1264 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1266 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1270 av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1271 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1272 (format >> 24) & 0xff, st->codec->codec_type);
1274 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1275 unsigned int color_depth, len;
1276 int color_greyscale;
1279 st->codec->codec_id = id;
1280 avio_rb16(pb); /* version */
1281 avio_rb16(pb); /* revision level */
1282 avio_rb32(pb); /* vendor */
1283 avio_rb32(pb); /* temporal quality */
1284 avio_rb32(pb); /* spatial quality */
1286 st->codec->width = avio_rb16(pb); /* width */
1287 st->codec->height = avio_rb16(pb); /* height */
1289 avio_rb32(pb); /* horiz resolution */
1290 avio_rb32(pb); /* vert resolution */
1291 avio_rb32(pb); /* data size, always 0 */
1292 avio_rb16(pb); /* frames per samples */
1294 len = avio_r8(pb); /* codec name, pascal string */
1297 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1299 avio_skip(pb, 31 - len);
1300 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1301 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1302 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1303 /* Flash Media Server uses tag H263 with Sorenson Spark */
1304 if (format == MKTAG('H','2','6','3') &&
1305 !memcmp(st->codec->codec_name, "Sorenson H263", 13))
1306 st->codec->codec_id = AV_CODEC_ID_FLV1;
1308 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1309 color_table_id = avio_rb16(pb); /* colortable id */
1310 av_dlog(c->fc, "depth %d, ctab id %d\n",
1311 st->codec->bits_per_coded_sample, color_table_id);
1312 /* figure out the palette situation */
1313 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1314 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1316 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1317 if ((color_depth == 2) || (color_depth == 4) ||
1318 (color_depth == 8)) {
1319 /* for palette traversal */
1320 unsigned int color_start, color_count, color_end;
1321 unsigned char a, r, g, b;
1323 if (color_greyscale) {
1324 int color_index, color_dec;
1325 /* compute the greyscale palette */
1326 st->codec->bits_per_coded_sample = color_depth;
1327 color_count = 1 << color_depth;
1329 color_dec = 256 / (color_count - 1);
1330 for (j = 0; j < color_count; j++) {
1331 if (id == AV_CODEC_ID_CINEPAK){
1332 r = g = b = color_count - 1 - color_index;
1334 r = g = b = color_index;
1336 (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1337 color_index -= color_dec;
1338 if (color_index < 0)
1341 } else if (color_table_id) {
1342 const uint8_t *color_table;
1343 /* if flag bit 3 is set, use the default palette */
1344 color_count = 1 << color_depth;
1345 if (color_depth == 2)
1346 color_table = ff_qt_default_palette_4;
1347 else if (color_depth == 4)
1348 color_table = ff_qt_default_palette_16;
1350 color_table = ff_qt_default_palette_256;
1352 for (j = 0; j < color_count; j++) {
1353 r = color_table[j * 3 + 0];
1354 g = color_table[j * 3 + 1];
1355 b = color_table[j * 3 + 2];
1357 (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1360 /* load the palette from the file */
1361 color_start = avio_rb32(pb);
1362 color_count = avio_rb16(pb);
1363 color_end = avio_rb16(pb);
1364 if ((color_start <= 255) &&
1365 (color_end <= 255)) {
1366 for (j = color_start; j <= color_end; j++) {
1367 /* each A, R, G, or B component is 16 bits;
1368 * only use the top 8 bits */
1378 (a << 24 ) | (r << 16) | (g << 8) | (b);
1382 sc->has_palette = 1;
1384 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1385 int bits_per_sample, flags;
1386 uint16_t version = avio_rb16(pb);
1387 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1389 st->codec->codec_id = id;
1390 avio_rb16(pb); /* revision level */
1391 avio_rb32(pb); /* vendor */
1393 st->codec->channels = avio_rb16(pb); /* channel count */
1394 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1395 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1397 sc->audio_cid = avio_rb16(pb);
1398 avio_rb16(pb); /* packet size = 0 */
1400 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1402 //Read QT version 1 fields. In version 0 these do not exist.
1403 av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1405 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1407 sc->samples_per_frame = avio_rb32(pb);
1408 avio_rb32(pb); /* bytes per packet */
1409 sc->bytes_per_frame = avio_rb32(pb);
1410 avio_rb32(pb); /* bytes per sample */
1411 } else if (version==2) {
1412 avio_rb32(pb); /* sizeof struct only */
1413 st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
1414 st->codec->channels = avio_rb32(pb);
1415 avio_rb32(pb); /* always 0x7F000000 */
1416 st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1417 flags = avio_rb32(pb); /* lpcm format specific flag */
1418 sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1419 sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1420 if (format == MKTAG('l','p','c','m'))
1421 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1425 switch (st->codec->codec_id) {
1426 case AV_CODEC_ID_PCM_S8:
1427 case AV_CODEC_ID_PCM_U8:
1428 if (st->codec->bits_per_coded_sample == 16)
1429 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1431 case AV_CODEC_ID_PCM_S16LE:
1432 case AV_CODEC_ID_PCM_S16BE:
1433 if (st->codec->bits_per_coded_sample == 8)
1434 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1435 else if (st->codec->bits_per_coded_sample == 24)
1436 st->codec->codec_id =
1437 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1438 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1440 /* set values for old format before stsd version 1 appeared */
1441 case AV_CODEC_ID_MACE3:
1442 sc->samples_per_frame = 6;
1443 sc->bytes_per_frame = 2*st->codec->channels;
1445 case AV_CODEC_ID_MACE6:
1446 sc->samples_per_frame = 6;
1447 sc->bytes_per_frame = 1*st->codec->channels;
1449 case AV_CODEC_ID_ADPCM_IMA_QT:
1450 sc->samples_per_frame = 64;
1451 sc->bytes_per_frame = 34*st->codec->channels;
1453 case AV_CODEC_ID_GSM:
1454 sc->samples_per_frame = 160;
1455 sc->bytes_per_frame = 33;
1461 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1462 if (bits_per_sample) {
1463 st->codec->bits_per_coded_sample = bits_per_sample;
1464 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1466 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1467 // ttxt stsd contains display flags, justification, background
1468 // color, fonts, and default styles, so fake an atom to read it
1469 MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1470 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1471 mov_read_glbl(c, pb, fake_atom);
1472 st->codec->codec_id= id;
1473 st->codec->width = sc->width;
1474 st->codec->height = sc->height;
1476 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1477 MOVStreamContext *tmcd_ctx = st->priv_data;
1479 avio_rb32(pb); /* reserved */
1480 val = avio_rb32(pb); /* flags */
1481 tmcd_ctx->tmcd_flags = val;
1483 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1484 avio_rb32(pb); /* time scale */
1485 avio_rb32(pb); /* frame duration */
1486 st->codec->time_base.den = avio_r8(pb); /* number of frame */
1487 st->codec->time_base.num = 1;
1489 /* other codec type, just skip (rtp, mp4s, ...) */
1490 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1492 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1493 a.size = size - (avio_tell(pb) - start_pos);
1496 if ((ret = mov_read_default(c, pb, a)) < 0)
1498 } else if (a.size > 0)
1499 avio_skip(pb, a.size);
1502 if (pb->eof_reached)
1505 if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1506 st->codec->sample_rate= sc->time_scale;
1508 /* special codec parameters handling */
1509 switch (st->codec->codec_id) {
1510 #if CONFIG_DV_DEMUXER
1511 case AV_CODEC_ID_DVAUDIO:
1512 c->dv_fctx = avformat_alloc_context();
1513 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1515 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1516 return AVERROR(ENOMEM);
1518 sc->dv_audio_container = 1;
1519 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1522 /* no ifdef since parameters are always those */
1523 case AV_CODEC_ID_QCELP:
1524 // force sample rate for qcelp when not stored in mov
1525 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1526 st->codec->sample_rate = 8000;
1527 st->codec->channels= 1; /* really needed */
1529 case AV_CODEC_ID_AMR_NB:
1530 st->codec->channels= 1; /* really needed */
1531 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1532 st->codec->sample_rate = 8000;
1534 case AV_CODEC_ID_AMR_WB:
1535 st->codec->channels = 1;
1536 st->codec->sample_rate = 16000;
1538 case AV_CODEC_ID_MP2:
1539 case AV_CODEC_ID_MP3:
1540 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1541 st->need_parsing = AVSTREAM_PARSE_FULL;
1543 case AV_CODEC_ID_GSM:
1544 case AV_CODEC_ID_ADPCM_MS:
1545 case AV_CODEC_ID_ADPCM_IMA_WAV:
1546 case AV_CODEC_ID_ILBC:
1547 st->codec->block_align = sc->bytes_per_frame;
1549 case AV_CODEC_ID_ALAC:
1550 if (st->codec->extradata_size == 36) {
1551 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1552 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1555 case AV_CODEC_ID_AC3:
1556 st->need_parsing = AVSTREAM_PARSE_FULL;
1558 case AV_CODEC_ID_MPEG1VIDEO:
1559 st->need_parsing = AVSTREAM_PARSE_FULL;
1561 case AV_CODEC_ID_VC1:
1562 st->need_parsing = AVSTREAM_PARSE_FULL;
1571 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1575 avio_r8(pb); /* version */
1576 avio_rb24(pb); /* flags */
1577 entries = avio_rb32(pb);
1579 return ff_mov_read_stsd_entries(c, pb, entries);
1582 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1585 MOVStreamContext *sc;
1586 unsigned int i, entries;
1588 if (c->fc->nb_streams < 1)
1590 st = c->fc->streams[c->fc->nb_streams-1];
1593 avio_r8(pb); /* version */
1594 avio_rb24(pb); /* flags */
1596 entries = avio_rb32(pb);
1598 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1602 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1603 return AVERROR_INVALIDDATA;
1604 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1606 return AVERROR(ENOMEM);
1608 for (i = 0; i < entries && !pb->eof_reached; i++) {
1609 sc->stsc_data[i].first = avio_rb32(pb);
1610 sc->stsc_data[i].count = avio_rb32(pb);
1611 sc->stsc_data[i].id = avio_rb32(pb);
1616 if (pb->eof_reached)
1622 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1625 MOVStreamContext *sc;
1626 unsigned i, entries;
1628 if (c->fc->nb_streams < 1)
1630 st = c->fc->streams[c->fc->nb_streams-1];
1633 avio_rb32(pb); // version + flags
1635 entries = avio_rb32(pb);
1636 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1637 return AVERROR_INVALIDDATA;
1638 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1640 return AVERROR(ENOMEM);
1642 for (i = 0; i < entries && !pb->eof_reached; i++) {
1643 sc->stps_data[i] = avio_rb32(pb);
1644 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1649 if (pb->eof_reached)
1655 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1658 MOVStreamContext *sc;
1659 unsigned int i, entries;
1661 if (c->fc->nb_streams < 1)
1663 st = c->fc->streams[c->fc->nb_streams-1];
1666 avio_r8(pb); /* version */
1667 avio_rb24(pb); /* flags */
1669 entries = avio_rb32(pb);
1671 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1675 sc->keyframe_absent = 1;
1678 if (entries >= UINT_MAX / sizeof(int))
1679 return AVERROR_INVALIDDATA;
1680 sc->keyframes = av_malloc(entries * sizeof(int));
1682 return AVERROR(ENOMEM);
1684 for (i = 0; i < entries && !pb->eof_reached; i++) {
1685 sc->keyframes[i] = avio_rb32(pb);
1686 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1689 sc->keyframe_count = i;
1691 if (pb->eof_reached)
1697 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1700 MOVStreamContext *sc;
1701 unsigned int i, entries, sample_size, field_size, num_bytes;
1705 if (c->fc->nb_streams < 1)
1707 st = c->fc->streams[c->fc->nb_streams-1];
1710 avio_r8(pb); /* version */
1711 avio_rb24(pb); /* flags */
1713 if (atom.type == MKTAG('s','t','s','z')) {
1714 sample_size = avio_rb32(pb);
1715 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1716 sc->sample_size = sample_size;
1717 sc->alt_sample_size = sample_size;
1721 avio_rb24(pb); /* reserved */
1722 field_size = avio_r8(pb);
1724 entries = avio_rb32(pb);
1726 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1728 sc->sample_count = entries;
1732 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1733 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1734 return AVERROR_INVALIDDATA;
1739 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1740 return AVERROR_INVALIDDATA;
1741 sc->sample_sizes = av_malloc(entries * sizeof(int));
1742 if (!sc->sample_sizes)
1743 return AVERROR(ENOMEM);
1745 num_bytes = (entries*field_size+4)>>3;
1747 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1749 av_freep(&sc->sample_sizes);
1750 return AVERROR(ENOMEM);
1753 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1754 av_freep(&sc->sample_sizes);
1756 return AVERROR_INVALIDDATA;
1759 init_get_bits(&gb, buf, 8*num_bytes);
1761 for (i = 0; i < entries && !pb->eof_reached; i++) {
1762 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1763 sc->data_size += sc->sample_sizes[i];
1766 sc->sample_count = i;
1768 if (pb->eof_reached)
1775 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1778 MOVStreamContext *sc;
1779 unsigned int i, entries;
1781 int64_t total_sample_count=0;
1783 if (c->fc->nb_streams < 1)
1785 st = c->fc->streams[c->fc->nb_streams-1];
1788 avio_r8(pb); /* version */
1789 avio_rb24(pb); /* flags */
1790 entries = avio_rb32(pb);
1792 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1793 c->fc->nb_streams-1, entries);
1795 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1798 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1800 return AVERROR(ENOMEM);
1802 for (i = 0; i < entries && !pb->eof_reached; i++) {
1803 int sample_duration;
1806 sample_count=avio_rb32(pb);
1807 sample_duration = avio_rb32(pb);
1808 /* sample_duration < 0 is invalid based on the spec */
1809 if (sample_duration < 0) {
1810 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
1811 sample_duration = 1;
1813 sc->stts_data[i].count= sample_count;
1814 sc->stts_data[i].duration= sample_duration;
1816 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1817 sample_count, sample_duration);
1819 duration+=(int64_t)sample_duration*sample_count;
1820 total_sample_count+=sample_count;
1825 if (pb->eof_reached)
1828 st->nb_frames= total_sample_count;
1830 st->duration= duration;
1831 sc->track_end = duration;
1835 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1838 MOVStreamContext *sc;
1839 unsigned int i, entries;
1841 if (c->fc->nb_streams < 1)
1843 st = c->fc->streams[c->fc->nb_streams-1];
1846 avio_r8(pb); /* version */
1847 avio_rb24(pb); /* flags */
1848 entries = avio_rb32(pb);
1850 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1854 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1855 return AVERROR_INVALIDDATA;
1856 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1858 return AVERROR(ENOMEM);
1860 for (i = 0; i < entries && !pb->eof_reached; i++) {
1861 int count =avio_rb32(pb);
1862 int duration =avio_rb32(pb);
1864 sc->ctts_data[i].count = count;
1865 sc->ctts_data[i].duration= duration;
1867 av_dlog(c->fc, "count=%d, duration=%d\n",
1870 if (FFABS(duration) > (1<<28) && i+2<entries) {
1871 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
1872 av_freep(&sc->ctts_data);
1877 if (duration < 0 && i+2<entries)
1878 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1883 if (pb->eof_reached)
1886 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1891 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1894 MOVStreamContext *sc;
1895 unsigned int i, entries;
1897 uint32_t grouping_type;
1899 if (c->fc->nb_streams < 1)
1901 st = c->fc->streams[c->fc->nb_streams-1];
1904 version = avio_r8(pb); /* version */
1905 avio_rb24(pb); /* flags */
1906 grouping_type = avio_rl32(pb);
1907 if (grouping_type != MKTAG( 'r','a','p',' '))
1908 return 0; /* only support 'rap ' grouping */
1910 avio_rb32(pb); /* grouping_type_parameter */
1912 entries = avio_rb32(pb);
1915 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
1916 return AVERROR_INVALIDDATA;
1917 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
1919 return AVERROR(ENOMEM);
1921 for (i = 0; i < entries && !pb->eof_reached; i++) {
1922 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
1923 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
1926 sc->rap_group_count = i;
1928 return pb->eof_reached ? AVERROR_EOF : 0;
1931 static void mov_build_index(MOVContext *mov, AVStream *st)
1933 MOVStreamContext *sc = st->priv_data;
1934 int64_t current_offset;
1935 int64_t current_dts = 0;
1936 unsigned int stts_index = 0;
1937 unsigned int stsc_index = 0;
1938 unsigned int stss_index = 0;
1939 unsigned int stps_index = 0;
1941 uint64_t stream_size = 0;
1944 /* adjust first dts according to edit list */
1945 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
1946 if (sc->empty_duration)
1947 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
1948 sc->time_offset = sc->start_time - sc->empty_duration;
1949 current_dts = -sc->time_offset;
1950 if (sc->ctts_count>0 && sc->stts_count>0 &&
1951 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1952 /* more than 16 frames delay, dts are likely wrong
1953 this happens with files created by iMovie */
1955 st->codec->has_b_frames = 1;
1959 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1960 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1961 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1962 unsigned int current_sample = 0;
1963 unsigned int stts_sample = 0;
1964 unsigned int sample_size;
1965 unsigned int distance = 0;
1966 unsigned int rap_group_index = 0;
1967 unsigned int rap_group_sample = 0;
1968 int rap_group_present = sc->rap_group_count && sc->rap_group;
1969 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
1971 current_dts -= sc->dts_shift;
1973 if (!sc->sample_count || st->nb_index_entries)
1975 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1977 mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1980 st->index_entries = mem;
1981 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
1983 for (i = 0; i < sc->chunk_count; i++) {
1984 current_offset = sc->chunk_offsets[i];
1985 while (stsc_index + 1 < sc->stsc_count &&
1986 i + 1 == sc->stsc_data[stsc_index + 1].first)
1988 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1990 if (current_sample >= sc->sample_count) {
1991 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1995 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
1997 if (stss_index + 1 < sc->keyframe_count)
1999 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2001 if (stps_index + 1 < sc->stps_count)
2004 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2005 if (sc->rap_group[rap_group_index].index > 0)
2007 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2008 rap_group_sample = 0;
2014 sample_size = sc->alt_sample_size > 0 ? sc->alt_sample_size : sc->sample_sizes[current_sample];
2015 if (sc->pseudo_stream_id == -1 ||
2016 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2017 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2018 e->pos = current_offset;
2019 e->timestamp = current_dts;
2020 e->size = sample_size;
2021 e->min_distance = distance;
2022 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2023 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2024 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2025 current_offset, current_dts, sample_size, distance, keyframe);
2028 current_offset += sample_size;
2029 stream_size += sample_size;
2030 current_dts += sc->stts_data[stts_index].duration;
2034 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2040 if (st->duration > 0)
2041 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2043 unsigned chunk_samples, total = 0;
2045 // compute total chunk count
2046 for (i = 0; i < sc->stsc_count; i++) {
2047 unsigned count, chunk_count;
2049 chunk_samples = sc->stsc_data[i].count;
2050 if (i != sc->stsc_count - 1 &&
2051 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2052 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2056 if (sc->samples_per_frame >= 160) { // gsm
2057 count = chunk_samples / sc->samples_per_frame;
2058 } else if (sc->samples_per_frame > 1) {
2059 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2060 count = (chunk_samples+samples-1) / samples;
2062 count = (chunk_samples+1023) / 1024;
2065 if (i < sc->stsc_count - 1)
2066 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2068 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2069 total += chunk_count * count;
2072 av_dlog(mov->fc, "chunk count %d\n", total);
2073 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2075 mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
2078 st->index_entries = mem;
2079 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2082 for (i = 0; i < sc->chunk_count; i++) {
2083 current_offset = sc->chunk_offsets[i];
2084 if (stsc_index + 1 < sc->stsc_count &&
2085 i + 1 == sc->stsc_data[stsc_index + 1].first)
2087 chunk_samples = sc->stsc_data[stsc_index].count;
2089 while (chunk_samples > 0) {
2091 unsigned size, samples;
2093 if (sc->samples_per_frame >= 160) { // gsm
2094 samples = sc->samples_per_frame;
2095 size = sc->bytes_per_frame;
2097 if (sc->samples_per_frame > 1) {
2098 samples = FFMIN((1024 / sc->samples_per_frame)*
2099 sc->samples_per_frame, chunk_samples);
2100 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2102 samples = FFMIN(1024, chunk_samples);
2103 size = samples * sc->sample_size;
2107 if (st->nb_index_entries >= total) {
2108 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2111 e = &st->index_entries[st->nb_index_entries++];
2112 e->pos = current_offset;
2113 e->timestamp = current_dts;
2115 e->min_distance = 0;
2116 e->flags = AVINDEX_KEYFRAME;
2117 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2118 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2121 current_offset += size;
2122 current_dts += samples;
2123 chunk_samples -= samples;
2129 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2130 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2132 /* try relative path, we do not try the absolute because it can leak information about our
2133 system to an attacker */
2134 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2135 char filename[1024];
2136 const char *src_path;
2139 /* find a source dir */
2140 src_path = strrchr(src, '/');
2146 /* find a next level down to target */
2147 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2148 if (ref->path[l] == '/') {
2149 if (i == ref->nlvl_to - 1)
2155 /* compose filename if next level down to target was found */
2156 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2157 memcpy(filename, src, src_path - src);
2158 filename[src_path - src] = 0;
2160 for (i = 1; i < ref->nlvl_from; i++)
2161 av_strlcat(filename, "../", 1024);
2163 av_strlcat(filename, ref->path + l + 1, 1024);
2165 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2168 } else if (use_absolute_path) {
2169 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2170 "this is a possible security issue\n");
2171 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2175 return AVERROR(ENOENT);
2178 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2180 if (sc->time_scale <= 0) {
2181 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2182 sc->time_scale = c->time_scale;
2183 if (sc->time_scale <= 0)
2188 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2191 MOVStreamContext *sc;
2194 st = avformat_new_stream(c->fc, NULL);
2195 if (!st) return AVERROR(ENOMEM);
2196 st->id = c->fc->nb_streams;
2197 sc = av_mallocz(sizeof(MOVStreamContext));
2198 if (!sc) return AVERROR(ENOMEM);
2201 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2202 sc->ffindex = st->index;
2204 if ((ret = mov_read_default(c, pb, atom)) < 0)
2208 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2209 (!sc->sample_size && !sc->sample_count))) {
2210 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2215 fix_timescale(c, sc);
2217 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2219 mov_build_index(c, st);
2221 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2222 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2223 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2224 c->use_absolute_path, c->fc) < 0)
2225 av_log(c->fc, AV_LOG_ERROR,
2226 "stream %d, error opening alias: path='%s', dir='%s', "
2227 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2228 st->index, dref->path, dref->dir, dref->filename,
2229 dref->volume, dref->nlvl_from, dref->nlvl_to);
2233 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2234 if (!st->sample_aspect_ratio.num &&
2235 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2236 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2237 ((double)st->codec->width * sc->height), INT_MAX);
2240 if (st->duration > 0)
2241 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2242 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2244 #if FF_API_R_FRAME_RATE
2245 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2246 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2247 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2251 switch (st->codec->codec_id) {
2252 #if CONFIG_H261_DECODER
2253 case AV_CODEC_ID_H261:
2255 #if CONFIG_H263_DECODER
2256 case AV_CODEC_ID_H263:
2258 #if CONFIG_MPEG4_DECODER
2259 case AV_CODEC_ID_MPEG4:
2261 st->codec->width = 0; /* let decoder init width/height */
2262 st->codec->height= 0;
2266 /* Do not need those anymore. */
2267 av_freep(&sc->chunk_offsets);
2268 av_freep(&sc->stsc_data);
2269 av_freep(&sc->sample_sizes);
2270 av_freep(&sc->keyframes);
2271 av_freep(&sc->stts_data);
2272 av_freep(&sc->stps_data);
2273 av_freep(&sc->rap_group);
2278 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2281 c->itunes_metadata = 1;
2282 ret = mov_read_default(c, pb, atom);
2283 c->itunes_metadata = 0;
2287 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2289 while (atom.size > 8) {
2290 uint32_t tag = avio_rl32(pb);
2292 if (tag == MKTAG('h','d','l','r')) {
2293 avio_seek(pb, -8, SEEK_CUR);
2295 return mov_read_default(c, pb, atom);
2301 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2306 int64_t disp_transform[2];
2307 int display_matrix[3][2];
2309 MOVStreamContext *sc;
2312 if (c->fc->nb_streams < 1)
2314 st = c->fc->streams[c->fc->nb_streams-1];
2317 version = avio_r8(pb);
2318 avio_rb24(pb); /* flags */
2320 MOV_TRACK_ENABLED 0x0001
2321 MOV_TRACK_IN_MOVIE 0x0002
2322 MOV_TRACK_IN_PREVIEW 0x0004
2323 MOV_TRACK_IN_POSTER 0x0008
2330 avio_rb32(pb); /* creation time */
2331 avio_rb32(pb); /* modification time */
2333 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2334 avio_rb32(pb); /* reserved */
2336 /* highlevel (considering edits) duration in movie timebase */
2337 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2338 avio_rb32(pb); /* reserved */
2339 avio_rb32(pb); /* reserved */
2341 avio_rb16(pb); /* layer */
2342 avio_rb16(pb); /* alternate group */
2343 avio_rb16(pb); /* volume */
2344 avio_rb16(pb); /* reserved */
2346 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2347 // they're kept in fixed point format through all calculations
2348 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2349 for (i = 0; i < 3; i++) {
2350 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2351 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2352 avio_rb32(pb); // 2.30 fixed point (not used)
2355 width = avio_rb32(pb); // 16.16 fixed point track width
2356 height = avio_rb32(pb); // 16.16 fixed point track height
2357 sc->width = width >> 16;
2358 sc->height = height >> 16;
2360 //Assign clockwise rotate values based on transform matrix so that
2361 //we can compensate for iPhone orientation during capture.
2363 if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2364 av_dict_set(&st->metadata, "rotate", "90", 0);
2367 if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2368 av_dict_set(&st->metadata, "rotate", "180", 0);
2371 if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2372 av_dict_set(&st->metadata, "rotate", "270", 0);
2375 // transform the display width/height according to the matrix
2376 // skip this if the display matrix is the default identity matrix
2377 // or if it is rotating the picture, ex iPhone 3GS
2378 // to keep the same scale, use [width height 1<<16]
2379 if (width && height &&
2380 ((display_matrix[0][0] != 65536 ||
2381 display_matrix[1][1] != 65536) &&
2382 !display_matrix[0][1] &&
2383 !display_matrix[1][0] &&
2384 !display_matrix[2][0] && !display_matrix[2][1])) {
2385 for (i = 0; i < 2; i++)
2387 (int64_t) width * display_matrix[0][i] +
2388 (int64_t) height * display_matrix[1][i] +
2389 ((int64_t) display_matrix[2][i] << 16);
2391 //sample aspect ratio is new width/height divided by old width/height
2392 st->sample_aspect_ratio = av_d2q(
2393 ((double) disp_transform[0] * height) /
2394 ((double) disp_transform[1] * width), INT_MAX);
2399 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2401 MOVFragment *frag = &c->fragment;
2402 MOVTrackExt *trex = NULL;
2403 int flags, track_id, i;
2405 avio_r8(pb); /* version */
2406 flags = avio_rb24(pb);
2408 track_id = avio_rb32(pb);
2410 return AVERROR_INVALIDDATA;
2411 frag->track_id = track_id;
2412 for (i = 0; i < c->trex_count; i++)
2413 if (c->trex_data[i].track_id == frag->track_id) {
2414 trex = &c->trex_data[i];
2418 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2419 return AVERROR_INVALIDDATA;
2422 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2423 avio_rb64(pb) : frag->moof_offset;
2424 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2426 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2427 avio_rb32(pb) : trex->duration;
2428 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2429 avio_rb32(pb) : trex->size;
2430 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2431 avio_rb32(pb) : trex->flags;
2432 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2436 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2438 c->chapter_track = avio_rb32(pb);
2442 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2446 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2447 return AVERROR_INVALIDDATA;
2448 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2450 return AVERROR(ENOMEM);
2452 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2454 c->trex_data = trex;
2455 trex = &c->trex_data[c->trex_count++];
2456 avio_r8(pb); /* version */
2457 avio_rb24(pb); /* flags */
2458 trex->track_id = avio_rb32(pb);
2459 trex->stsd_id = avio_rb32(pb);
2460 trex->duration = avio_rb32(pb);
2461 trex->size = avio_rb32(pb);
2462 trex->flags = avio_rb32(pb);
2466 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2468 MOVFragment *frag = &c->fragment;
2469 AVStream *st = NULL;
2470 MOVStreamContext *sc;
2474 int data_offset = 0;
2475 unsigned entries, first_sample_flags = frag->flags;
2476 int flags, distance, i, found_keyframe = 0;
2478 for (i = 0; i < c->fc->nb_streams; i++) {
2479 if (c->fc->streams[i]->id == frag->track_id) {
2480 st = c->fc->streams[i];
2485 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2486 return AVERROR_INVALIDDATA;
2489 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2491 avio_r8(pb); /* version */
2492 flags = avio_rb24(pb);
2493 entries = avio_rb32(pb);
2494 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2496 /* Always assume the presence of composition time offsets.
2497 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2498 * 1) in the initial movie, there are no samples.
2499 * 2) in the first movie fragment, there is only one sample without composition time offset.
2500 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2501 if (!sc->ctts_count && sc->sample_count)
2503 /* Complement ctts table if moov atom doesn't have ctts atom. */
2504 ctts_data = av_malloc(sizeof(*sc->ctts_data));
2506 return AVERROR(ENOMEM);
2507 sc->ctts_data = ctts_data;
2508 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2509 sc->ctts_data[sc->ctts_count].duration = 0;
2512 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2513 return AVERROR_INVALIDDATA;
2514 ctts_data = av_realloc(sc->ctts_data,
2515 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2517 return AVERROR(ENOMEM);
2518 sc->ctts_data = ctts_data;
2520 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2521 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2522 dts = sc->track_end - sc->time_offset;
2523 offset = frag->base_data_offset + data_offset;
2525 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2526 for (i = 0; i < entries && !pb->eof_reached; i++) {
2527 unsigned sample_size = frag->size;
2528 int sample_flags = i ? frag->flags : first_sample_flags;
2529 unsigned sample_duration = frag->duration;
2532 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2533 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2534 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2535 sc->ctts_data[sc->ctts_count].count = 1;
2536 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2539 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2541 else if (!found_keyframe)
2542 keyframe = found_keyframe =
2543 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2544 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2547 av_add_index_entry(st, offset, dts, sample_size, distance,
2548 keyframe ? AVINDEX_KEYFRAME : 0);
2549 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2550 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2551 offset, dts, sample_size, distance, keyframe);
2553 dts += sample_duration;
2554 offset += sample_size;
2555 sc->data_size += sample_size;
2558 if (pb->eof_reached)
2561 frag->moof_offset = offset;
2562 st->duration = sc->track_end = dts + sc->time_offset;
2566 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2567 /* like the files created with Adobe Premiere 5.0, for samples see */
2568 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2569 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2574 return 0; /* continue */
2575 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2576 avio_skip(pb, atom.size - 4);
2579 atom.type = avio_rl32(pb);
2581 if (atom.type != MKTAG('m','d','a','t')) {
2582 avio_skip(pb, atom.size);
2585 err = mov_read_mdat(c, pb, atom);
2589 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2594 uint8_t *moov_data; /* uncompressed data */
2595 long cmov_len, moov_len;
2598 avio_rb32(pb); /* dcom atom */
2599 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2600 return AVERROR_INVALIDDATA;
2601 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2602 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
2603 return AVERROR_INVALIDDATA;
2605 avio_rb32(pb); /* cmvd atom */
2606 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2607 return AVERROR_INVALIDDATA;
2608 moov_len = avio_rb32(pb); /* uncompressed size */
2609 cmov_len = atom.size - 6 * 4;
2611 cmov_data = av_malloc(cmov_len);
2613 return AVERROR(ENOMEM);
2614 moov_data = av_malloc(moov_len);
2617 return AVERROR(ENOMEM);
2619 avio_read(pb, cmov_data, cmov_len);
2620 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2621 goto free_and_return;
2622 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2623 goto free_and_return;
2624 atom.type = MKTAG('m','o','o','v');
2625 atom.size = moov_len;
2626 ret = mov_read_default(c, &ctx, atom);
2632 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2633 return AVERROR(ENOSYS);
2637 /* edit list atom */
2638 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2640 MOVStreamContext *sc;
2641 int i, edit_count, version, edit_start_index = 0;
2642 int unsupported = 0;
2644 if (c->fc->nb_streams < 1 || c->ignore_editlist)
2646 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2648 version = avio_r8(pb); /* version */
2649 avio_rb24(pb); /* flags */
2650 edit_count = avio_rb32(pb); /* entries */
2652 if ((uint64_t)edit_count*12+8 > atom.size)
2653 return AVERROR_INVALIDDATA;
2655 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2656 for (i=0; i<edit_count; i++){
2661 duration = avio_rb64(pb);
2662 time = avio_rb64(pb);
2664 duration = avio_rb32(pb); /* segment duration */
2665 time = (int32_t)avio_rb32(pb); /* media time */
2667 rate = avio_rb32(pb);
2668 if (i == 0 && time == -1) {
2669 sc->empty_duration = duration;
2670 edit_start_index = 1;
2671 } else if (i == edit_start_index && time >= 0)
2672 sc->start_time = time;
2676 av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
2677 duration, time, rate / 65536.0);
2681 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2682 "a/v desync might occur, patch welcome\n");
2687 static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2692 ff_mov_read_chan(c->fc, pb, c->fc->streams[0], atom.size - 4);
2696 static int mov_read_tref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2699 MOVStreamContext *sc;
2701 if (c->fc->nb_streams < 1)
2702 return AVERROR_INVALIDDATA;
2703 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
2705 size = avio_rb32(pb);
2709 sc->trefs_count = (size - 4) / 8;
2710 sc->trefs = av_malloc(sc->trefs_count * sizeof(*sc->trefs));
2712 return AVERROR(ENOMEM);
2714 sc->tref_type = avio_rl32(pb);
2715 for (i = 0; i < sc->trefs_count; i++)
2716 sc->trefs[i] = avio_rb32(pb);
2720 static const MOVParseTableEntry mov_default_parse_table[] = {
2721 { MKTAG('A','C','L','R'), mov_read_avid },
2722 { MKTAG('A','P','R','G'), mov_read_avid },
2723 { MKTAG('A','A','L','P'), mov_read_avid },
2724 { MKTAG('A','R','E','S'), mov_read_avid },
2725 { MKTAG('a','v','s','s'), mov_read_avss },
2726 { MKTAG('c','h','p','l'), mov_read_chpl },
2727 { MKTAG('c','o','6','4'), mov_read_stco },
2728 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2729 { MKTAG('d','i','n','f'), mov_read_default },
2730 { MKTAG('d','r','e','f'), mov_read_dref },
2731 { MKTAG('e','d','t','s'), mov_read_default },
2732 { MKTAG('e','l','s','t'), mov_read_elst },
2733 { MKTAG('e','n','d','a'), mov_read_enda },
2734 { MKTAG('f','i','e','l'), mov_read_fiel },
2735 { MKTAG('f','t','y','p'), mov_read_ftyp },
2736 { MKTAG('g','l','b','l'), mov_read_glbl },
2737 { MKTAG('h','d','l','r'), mov_read_hdlr },
2738 { MKTAG('i','l','s','t'), mov_read_ilst },
2739 { MKTAG('j','p','2','h'), mov_read_jp2h },
2740 { MKTAG('m','d','a','t'), mov_read_mdat },
2741 { MKTAG('m','d','h','d'), mov_read_mdhd },
2742 { MKTAG('m','d','i','a'), mov_read_default },
2743 { MKTAG('m','e','t','a'), mov_read_meta },
2744 { MKTAG('m','i','n','f'), mov_read_default },
2745 { MKTAG('m','o','o','f'), mov_read_moof },
2746 { MKTAG('m','o','o','v'), mov_read_moov },
2747 { MKTAG('m','v','e','x'), mov_read_default },
2748 { MKTAG('m','v','h','d'), mov_read_mvhd },
2749 { MKTAG('S','M','I',' '), mov_read_svq3 },
2750 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
2751 { MKTAG('a','v','c','C'), mov_read_glbl },
2752 { MKTAG('p','a','s','p'), mov_read_pasp },
2753 { MKTAG('s','t','b','l'), mov_read_default },
2754 { MKTAG('s','t','c','o'), mov_read_stco },
2755 { MKTAG('s','t','p','s'), mov_read_stps },
2756 { MKTAG('s','t','r','f'), mov_read_strf },
2757 { MKTAG('s','t','s','c'), mov_read_stsc },
2758 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2759 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2760 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2761 { MKTAG('s','t','t','s'), mov_read_stts },
2762 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2763 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2764 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2765 { MKTAG('t','r','a','k'), mov_read_trak },
2766 { MKTAG('t','r','a','f'), mov_read_default },
2767 { MKTAG('t','r','e','f'), mov_read_tref },
2768 { MKTAG('c','h','a','p'), mov_read_chap },
2769 { MKTAG('t','r','e','x'), mov_read_trex },
2770 { MKTAG('t','r','u','n'), mov_read_trun },
2771 { MKTAG('u','d','t','a'), mov_read_default },
2772 { MKTAG('w','a','v','e'), mov_read_wave },
2773 { MKTAG('e','s','d','s'), mov_read_esds },
2774 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2775 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2776 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2777 { MKTAG('w','f','e','x'), mov_read_wfex },
2778 { MKTAG('c','m','o','v'), mov_read_cmov },
2779 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2780 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2781 { MKTAG('s','b','g','p'), mov_read_sbgp },
2785 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2787 int64_t total_size = 0;
2792 atom.size = INT64_MAX;
2793 while (total_size + 8 <= atom.size && !url_feof(pb)) {
2794 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
2797 if (atom.size >= 8) {
2798 a.size = avio_rb32(pb);
2799 a.type = avio_rl32(pb);
2800 if (atom.type != MKTAG('r','o','o','t') &&
2801 atom.type != MKTAG('m','o','o','v'))
2803 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
2805 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
2811 if (a.size == 1) { /* 64 bit extended size */
2812 a.size = avio_rb64(pb) - 8;
2816 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
2817 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
2819 a.size = atom.size - total_size + 8;
2824 a.size = FFMIN(a.size, atom.size - total_size);
2826 for (i = 0; mov_default_parse_table[i].type; i++)
2827 if (mov_default_parse_table[i].type == a.type) {
2828 parse = mov_default_parse_table[i].parse;
2832 // container is user data
2833 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
2834 atom.type == MKTAG('i','l','s','t')))
2835 parse = mov_read_udta_string;
2837 if (!parse) { /* skip leaf atoms data */
2838 avio_skip(pb, a.size);
2840 int64_t start_pos = avio_tell(pb);
2842 int err = parse(c, pb, a);
2845 if (c->found_moov && c->found_mdat &&
2846 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
2847 start_pos + a.size == avio_size(pb))) {
2848 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
2849 c->next_root_atom = start_pos + a.size;
2852 left = a.size - avio_tell(pb) + start_pos;
2853 if (left > 0) /* skip garbage at atom end */
2854 avio_skip(pb, left);
2856 av_log(c->fc, AV_LOG_DEBUG, "undoing overread of %"PRId64" in '%.4s'\n", -left, (char*)&a.type);
2857 avio_seek(pb, left, SEEK_CUR);
2861 total_size += a.size;
2864 if (total_size < atom.size && atom.size < 0x7ffff)
2865 avio_skip(pb, atom.size - total_size);
2870 static int mov_probe(AVProbeData *p)
2875 int moov_offset = -1;
2877 /* check file header */
2880 /* ignore invalid offset */
2881 if ((offset + 8) > (unsigned int)p->buf_size)
2883 tag = AV_RL32(p->buf + offset + 4);
2885 /* check for obvious tags */
2886 case MKTAG('m','o','o','v'):
2887 moov_offset = offset + 4;
2888 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2889 case MKTAG('m','d','a','t'):
2890 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2891 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2892 case MKTAG('f','t','y','p'):
2893 if (AV_RB32(p->buf+offset) < 8 &&
2894 (AV_RB32(p->buf+offset) != 1 ||
2895 offset + 12 > (unsigned int)p->buf_size ||
2896 AV_RB64(p->buf+offset + 8) == 0)) {
2897 score = FFMAX(score, AVPROBE_SCORE_MAX - 50);
2899 score = AVPROBE_SCORE_MAX;
2901 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2903 /* those are more common words, so rate then a bit less */
2904 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2905 case MKTAG('w','i','d','e'):
2906 case MKTAG('f','r','e','e'):
2907 case MKTAG('j','u','n','k'):
2908 case MKTAG('p','i','c','t'):
2909 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
2910 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2912 case MKTAG(0x82,0x82,0x7f,0x7d):
2913 case MKTAG('s','k','i','p'):
2914 case MKTAG('u','u','i','d'):
2915 case MKTAG('p','r','f','l'):
2916 /* if we only find those cause probedata is too small at least rate them */
2917 score = FFMAX(score, AVPROBE_SCORE_MAX - 50);
2918 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2921 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2924 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
2925 /* moov atom in the header - we should make sure that this is not a
2926 * MOV-packed MPEG-PS */
2927 offset = moov_offset;
2929 while(offset < (p->buf_size - 16)){ /* Sufficient space */
2930 /* We found an actual hdlr atom */
2931 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
2932 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
2933 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
2934 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
2935 /* We found a media handler reference atom describing an
2936 * MPEG-PS-in-MOV, return a
2937 * low score to force expanding the probe window until
2938 * mpegps_probe finds what it needs */
2949 // must be done after parsing all trak because there's no order requirement
2950 static void mov_read_chapters(AVFormatContext *s)
2952 MOVContext *mov = s->priv_data;
2953 AVStream *st = NULL;
2954 MOVStreamContext *sc;
2958 for (i = 0; i < s->nb_streams; i++)
2959 if (s->streams[i]->id == mov->chapter_track) {
2964 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2968 st->discard = AVDISCARD_ALL;
2970 cur_pos = avio_tell(sc->pb);
2972 for (i = 0; i < st->nb_index_entries; i++) {
2973 AVIndexEntry *sample = &st->index_entries[i];
2974 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2979 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2980 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2984 // the first two bytes are the length of the title
2985 len = avio_rb16(sc->pb);
2986 if (len > sample->size-2)
2988 title_len = 2*len + 1;
2989 if (!(title = av_mallocz(title_len)))
2992 // The samples could theoretically be in any encoding if there's an encd
2993 // atom following, but in practice are only utf-8 or utf-16, distinguished
2994 // instead by the presence of a BOM
2998 ch = avio_rb16(sc->pb);
3000 avio_get_str16be(sc->pb, len, title, title_len);
3001 else if (ch == 0xfffe)
3002 avio_get_str16le(sc->pb, len, title, title_len);
3005 if (len == 1 || len == 2)
3008 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3012 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3016 avio_seek(sc->pb, cur_pos, SEEK_SET);
3019 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
3020 uint32_t value, int flags)
3023 char buf[AV_TIMECODE_STR_SIZE];
3024 AVRational rate = {st->codec->time_base.den,
3025 st->codec->time_base.num};
3026 int ret = av_timecode_init(&tc, rate, flags, 0, s);
3029 av_dict_set(&st->metadata, "timecode",
3030 av_timecode_make_string(&tc, buf, value), 0);
3034 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
3036 MOVStreamContext *sc = st->priv_data;
3038 int64_t cur_pos = avio_tell(sc->pb);
3041 if (!st->nb_index_entries)
3044 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3045 value = avio_rb32(s->pb);
3047 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3048 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3049 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3051 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3052 * not the case) and thus assume "frame number format" instead of QT one.
3053 * No sample with tmcd track can be found with a QT timecode at the moment,
3054 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3056 parse_timecode_in_framenum_format(s, st, value, flags);
3058 avio_seek(sc->pb, cur_pos, SEEK_SET);
3062 static int mov_read_close(AVFormatContext *s)
3064 MOVContext *mov = s->priv_data;
3067 for (i = 0; i < s->nb_streams; i++) {
3068 AVStream *st = s->streams[i];
3069 MOVStreamContext *sc = st->priv_data;
3071 av_freep(&sc->ctts_data);
3072 for (j = 0; j < sc->drefs_count; j++) {
3073 av_freep(&sc->drefs[j].path);
3074 av_freep(&sc->drefs[j].dir);
3076 av_freep(&sc->drefs);
3077 av_freep(&sc->trefs);
3078 if (sc->pb && sc->pb != s->pb)
3081 av_freep(&sc->chunk_offsets);
3082 av_freep(&sc->keyframes);
3083 av_freep(&sc->sample_sizes);
3084 av_freep(&sc->stps_data);
3085 av_freep(&sc->stsc_data);
3086 av_freep(&sc->stts_data);
3089 if (mov->dv_demux) {
3090 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
3091 av_freep(&mov->dv_fctx->streams[i]->codec);
3092 av_freep(&mov->dv_fctx->streams[i]);
3094 av_freep(&mov->dv_fctx);
3095 av_freep(&mov->dv_demux);
3098 av_freep(&mov->trex_data);
3103 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3107 for (i = 0; i < s->nb_streams; i++) {
3108 AVStream *st = s->streams[i];
3109 MOVStreamContext *sc = st->priv_data;
3111 if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
3113 for (j = 0; j < sc->trefs_count; j++)
3114 if (tmcd_id == sc->trefs[j])
3120 /* look for a tmcd track not referenced by any video track, and export it globally */
3121 static void export_orphan_timecode(AVFormatContext *s)
3125 for (i = 0; i < s->nb_streams; i++) {
3126 AVStream *st = s->streams[i];
3128 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3129 !tmcd_is_referenced(s, i + 1)) {
3130 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3132 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3139 static int mov_read_header(AVFormatContext *s)
3141 MOVContext *mov = s->priv_data;
3142 AVIOContext *pb = s->pb;
3144 MOVAtom atom = { AV_RL32("root") };
3147 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3149 atom.size = avio_size(pb);
3151 atom.size = INT64_MAX;
3153 /* check MOV header */
3154 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3155 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3159 if (!mov->found_moov) {
3160 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3162 return AVERROR_INVALIDDATA;
3164 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3167 if (mov->chapter_track > 0)
3168 mov_read_chapters(s);
3169 for (i = 0; i < s->nb_streams; i++)
3170 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3171 mov_read_timecode_track(s, s->streams[i]);
3174 /* copy timecode metadata from tmcd tracks to the related video streams */
3175 for (i = 0; i < s->nb_streams; i++) {
3176 AVStream *st = s->streams[i];
3177 MOVStreamContext *sc = st->priv_data;
3178 if (sc->tref_type == AV_RL32("tmcd") && sc->trefs_count) {
3179 AVDictionaryEntry *tcr;
3180 int tmcd_st_id = sc->trefs[0] - 1;
3182 if (tmcd_st_id < 0 || tmcd_st_id >= s->nb_streams)
3184 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
3186 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
3189 export_orphan_timecode(s);
3191 for (i = 0; i < s->nb_streams; i++) {
3192 AVStream *st = s->streams[i];
3193 MOVStreamContext *sc = st->priv_data;
3194 fix_timescale(mov, sc);
3195 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
3196 st->skip_samples = sc->start_pad;
3200 if (mov->trex_data) {
3201 for (i = 0; i < s->nb_streams; i++) {
3202 AVStream *st = s->streams[i];
3203 MOVStreamContext *sc = st->priv_data;
3205 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3212 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3214 AVIndexEntry *sample = NULL;
3215 int64_t best_dts = INT64_MAX;
3217 for (i = 0; i < s->nb_streams; i++) {
3218 AVStream *avst = s->streams[i];
3219 MOVStreamContext *msc = avst->priv_data;
3220 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3221 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3222 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3223 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3224 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3226 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3227 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3228 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3229 sample = current_sample;
3238 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3240 MOVContext *mov = s->priv_data;
3241 MOVStreamContext *sc;
3242 AVIndexEntry *sample;
3243 AVStream *st = NULL;
3247 sample = mov_find_next_sample(s, &st);
3249 mov->found_mdat = 0;
3250 if (!mov->next_root_atom)
3252 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3253 mov->next_root_atom = 0;
3254 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3257 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3261 /* must be done just before reading, to avoid infinite loop on sample */
3262 sc->current_sample++;
3264 if (st->discard != AVDISCARD_ALL) {
3265 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3266 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3267 sc->ffindex, sample->pos);
3268 return AVERROR_INVALIDDATA;
3270 ret = av_get_packet(sc->pb, pkt, sample->size);
3273 if (sc->has_palette) {
3276 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3278 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3280 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3281 sc->has_palette = 0;
3284 #if CONFIG_DV_DEMUXER
3285 if (mov->dv_demux && sc->dv_audio_container) {
3286 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
3289 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3296 pkt->stream_index = sc->ffindex;
3297 pkt->dts = sample->timestamp;
3298 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3299 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3300 /* update ctts context */
3302 if (sc->ctts_index < sc->ctts_count &&
3303 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3305 sc->ctts_sample = 0;
3308 pkt->dts = AV_NOPTS_VALUE;
3310 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3311 st->index_entries[sc->current_sample].timestamp : st->duration;
3312 pkt->duration = next_dts - pkt->dts;
3313 pkt->pts = pkt->dts;
3315 if (st->discard == AVDISCARD_ALL)
3317 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3318 pkt->pos = sample->pos;
3319 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3320 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3324 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3326 MOVStreamContext *sc = st->priv_data;
3327 int sample, time_sample;
3330 sample = av_index_search_timestamp(st, timestamp, flags);
3331 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3332 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3334 if (sample < 0) /* not sure what to do */
3335 return AVERROR_INVALIDDATA;
3336 sc->current_sample = sample;
3337 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3338 /* adjust ctts index */
3339 if (sc->ctts_data) {
3341 for (i = 0; i < sc->ctts_count; i++) {
3342 int next = time_sample + sc->ctts_data[i].count;
3343 if (next > sc->current_sample) {
3345 sc->ctts_sample = sc->current_sample - time_sample;
3354 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3357 int64_t seek_timestamp, timestamp;
3361 if (stream_index >= s->nb_streams)
3362 return AVERROR_INVALIDDATA;
3364 st = s->streams[stream_index];
3365 sample = mov_seek_stream(s, st, sample_time, flags);
3369 /* adjust seek timestamp to found sample timestamp */
3370 seek_timestamp = st->index_entries[sample].timestamp;
3372 for (i = 0; i < s->nb_streams; i++) {
3373 MOVStreamContext *sc = s->streams[i]->priv_data;
3375 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
3377 if (stream_index == i)
3380 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3381 mov_seek_stream(s, st, timestamp, flags);
3386 static const AVOption options[] = {
3387 {"use_absolute_path",
3388 "allow using absolute path when opening alias, this is a possible security issue",
3389 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
3390 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3391 {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
3392 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3396 static const AVClass class = {
3397 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3398 .item_name = av_default_item_name,
3400 .version = LIBAVUTIL_VERSION_INT,
3403 AVInputFormat ff_mov_demuxer = {
3404 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3405 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3406 .priv_data_size = sizeof(MOVContext),
3407 .read_probe = mov_probe,
3408 .read_header = mov_read_header,
3409 .read_packet = mov_read_packet,
3410 .read_close = mov_read_close,
3411 .read_seek = mov_read_seek,
3412 .priv_class = &class,
3413 .flags = AVFMT_NO_BYTE_SEEK,