3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * first version by Francois Revol <revol@free.fr>
7 * seek function by Gael Chardon <gael.dev@4now.net>
9 * This file is part of FFmpeg.
11 * FFmpeg is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * FFmpeg is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with FFmpeg; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include "libavutil/attributes.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/display.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/intfloat.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/time_internal.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/timecode.h"
41 #include "libavcodec/ac3tab.h"
44 #include "avio_internal.h"
47 #include "libavcodec/get_bits.h"
50 #include "replaygain.h"
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);
70 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
72 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
73 unsigned len, const char *key)
77 short current, total = 0;
78 avio_rb16(pb); // unknown
79 current = avio_rb16(pb);
81 total = avio_rb16(pb);
83 snprintf(buf, sizeof(buf), "%d", current);
85 snprintf(buf, sizeof(buf), "%d/%d", current, total);
86 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
87 av_dict_set(&c->fc->metadata, key, buf, 0);
92 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
93 unsigned len, const char *key)
95 /* bypass padding bytes */
100 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
101 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
106 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
107 unsigned len, const char *key)
109 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
110 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
115 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
116 unsigned len, const char *key)
120 avio_r8(pb); // unknown
123 if (genre < 1 || genre > ID3v1_GENRE_MAX)
125 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
126 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
131 static const uint32_t mac_to_unicode[128] = {
132 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
133 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
134 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
135 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
136 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
137 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
138 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
139 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
140 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
141 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
142 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
143 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
144 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
145 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
146 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
147 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
150 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
151 char *dst, int dstlen)
154 char *end = dst+dstlen-1;
157 for (i = 0; i < len; i++) {
158 uint8_t t, c = avio_r8(pb);
159 if (c < 0x80 && p < end)
162 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
168 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
172 MOVStreamContext *sc;
177 case 0xd: id = AV_CODEC_ID_MJPEG; break;
178 case 0xe: id = AV_CODEC_ID_PNG; break;
179 case 0x1b: id = AV_CODEC_ID_BMP; break;
181 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
186 st = avformat_new_stream(c->fc, NULL);
188 return AVERROR(ENOMEM);
189 sc = av_mallocz(sizeof(*sc));
191 return AVERROR(ENOMEM);
194 ret = av_get_packet(pb, &pkt, len);
198 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
200 st->attached_pic = pkt;
201 st->attached_pic.stream_index = st->index;
202 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
204 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
205 st->codec->codec_id = id;
210 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
212 char language[4] = { 0 };
214 uint16_t langcode = 0;
215 double longitude, latitude;
216 const char *key = "location";
218 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4)
219 return AVERROR_INVALIDDATA;
221 avio_skip(pb, 4); // version+flags
222 langcode = avio_rb16(pb);
223 ff_mov_lang_to_iso639(langcode, language);
226 len -= avio_get_str(pb, len, buf, sizeof(buf)); // place name
228 return AVERROR_INVALIDDATA;
229 avio_skip(pb, 1); // role
233 return AVERROR_INVALIDDATA;
234 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
235 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
237 // Try to output in the same format as the ?xyz field
238 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f/", latitude, longitude);
239 if (*language && strcmp(language, "und")) {
241 snprintf(key2, sizeof(key2), "%s-%s", key, language);
242 av_dict_set(&c->fc->metadata, key2, buf, 0);
244 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
245 return av_dict_set(&c->fc->metadata, key, buf, 0);
248 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
251 char key2[32], language[4] = {0};
253 const char *key = NULL;
254 uint16_t langcode = 0;
255 uint32_t data_type = 0, str_size, str_size_alloc;
256 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
260 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
261 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
262 case MKTAG( 'X','M','P','_'):
263 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
264 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
265 case MKTAG( 'a','k','I','D'): key = "account_type";
266 parse = mov_metadata_int8_no_padding; break;
267 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
268 case MKTAG( 'c','a','t','g'): key = "category"; break;
269 case MKTAG( 'c','p','i','l'): key = "compilation";
270 parse = mov_metadata_int8_no_padding; break;
271 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
272 case MKTAG( 'd','e','s','c'): key = "description"; break;
273 case MKTAG( 'd','i','s','k'): key = "disc";
274 parse = mov_metadata_track_or_disc_number; break;
275 case MKTAG( 'e','g','i','d'): key = "episode_uid";
276 parse = mov_metadata_int8_no_padding; break;
277 case MKTAG( 'g','n','r','e'): key = "genre";
278 parse = mov_metadata_gnre; break;
279 case MKTAG( 'h','d','v','d'): key = "hd_video";
280 parse = mov_metadata_int8_no_padding; break;
281 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
282 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
283 case MKTAG( 'l','o','c','i'):
284 return mov_metadata_loci(c, pb, atom.size);
285 case MKTAG( 'p','c','s','t'): key = "podcast";
286 parse = mov_metadata_int8_no_padding; break;
287 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
288 parse = mov_metadata_int8_no_padding; break;
289 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
290 case MKTAG( 'r','t','n','g'): key = "rating";
291 parse = mov_metadata_int8_no_padding; break;
292 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
293 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
294 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
295 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
296 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
297 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
298 case MKTAG( 's','t','i','k'): key = "media_type";
299 parse = mov_metadata_int8_no_padding; break;
300 case MKTAG( 't','r','k','n'): key = "track";
301 parse = mov_metadata_track_or_disc_number; break;
302 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
303 case MKTAG( 't','v','e','s'): key = "episode_sort";
304 parse = mov_metadata_int8_bypass_padding; break;
305 case MKTAG( 't','v','n','n'): key = "network"; break;
306 case MKTAG( 't','v','s','h'): key = "show"; break;
307 case MKTAG( 't','v','s','n'): key = "season_number";
308 parse = mov_metadata_int8_bypass_padding; break;
309 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
310 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
311 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
312 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
313 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
314 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
315 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
316 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
317 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
318 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
319 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
320 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
321 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
322 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
323 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
324 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
325 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
326 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
327 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
330 if (c->itunes_metadata && atom.size > 8) {
331 int data_size = avio_rb32(pb);
332 int tag = avio_rl32(pb);
333 if (tag == MKTAG('d','a','t','a')) {
334 data_type = avio_rb32(pb); // type
335 avio_rb32(pb); // unknown
336 str_size = data_size - 16;
339 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
340 int ret = mov_read_covr(c, pb, data_type, str_size);
342 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
347 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
348 str_size = avio_rb16(pb); // string length
349 langcode = avio_rb16(pb);
350 ff_mov_lang_to_iso639(langcode, language);
353 str_size = atom.size;
355 if (c->export_all && !key) {
356 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
363 return AVERROR_INVALIDDATA;
365 // worst-case requirement for output string in case of utf8 coded input
366 str_size_alloc = raw ? str_size + 1 : str_size * 2;
367 str = av_malloc(str_size_alloc);
369 return AVERROR(ENOMEM);
372 parse(c, pb, str_size, key);
374 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
375 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
377 int ret = avio_read(pb, str, str_size);
378 if (ret != str_size) {
380 return ret < 0 ? ret : AVERROR_INVALIDDATA;
384 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
385 av_dict_set(&c->fc->metadata, key, str, 0);
386 if (*language && strcmp(language, "und")) {
387 snprintf(key2, sizeof(key2), "%s-%s", key, language);
388 av_dict_set(&c->fc->metadata, key2, str, 0);
391 av_dlog(c->fc, "lang \"%3s\" ", language);
392 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
393 key, str, (char*)&atom.type, str_size_alloc, atom.size);
399 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
402 int i, nb_chapters, str_len, version;
405 if ((atom.size -= 5) < 0)
408 version = avio_r8(pb);
411 avio_rb32(pb); // ???
412 nb_chapters = avio_r8(pb);
414 for (i = 0; i < nb_chapters; i++) {
418 start = avio_rb64(pb);
419 str_len = avio_r8(pb);
421 if ((atom.size -= 9+str_len) < 0)
424 avio_read(pb, str, str_len);
426 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
431 #define MIN_DATA_ENTRY_BOX_SIZE 12
432 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
435 MOVStreamContext *sc;
438 if (c->fc->nb_streams < 1)
440 st = c->fc->streams[c->fc->nb_streams-1];
443 avio_rb32(pb); // version + flags
444 entries = avio_rb32(pb);
445 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
446 entries >= UINT_MAX / sizeof(*sc->drefs))
447 return AVERROR_INVALIDDATA;
450 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
452 return AVERROR(ENOMEM);
453 sc->drefs_count = entries;
455 for (i = 0; i < sc->drefs_count; i++) {
456 MOVDref *dref = &sc->drefs[i];
457 uint32_t size = avio_rb32(pb);
458 int64_t next = avio_tell(pb) + size - 4;
461 return AVERROR_INVALIDDATA;
463 dref->type = avio_rl32(pb);
464 avio_rb32(pb); // version + flags
465 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
467 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
468 /* macintosh alias record */
469 uint16_t volume_len, len;
474 volume_len = avio_r8(pb);
475 volume_len = FFMIN(volume_len, 27);
476 avio_read(pb, dref->volume, 27);
477 dref->volume[volume_len] = 0;
478 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
483 len = FFMIN(len, 63);
484 avio_read(pb, dref->filename, 63);
485 dref->filename[len] = 0;
486 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
490 /* read next level up_from_alias/down_to_target */
491 dref->nlvl_from = avio_rb16(pb);
492 dref->nlvl_to = avio_rb16(pb);
493 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
494 dref->nlvl_from, dref->nlvl_to);
498 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
501 type = avio_rb16(pb);
503 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
506 if (type == 2) { // absolute path
508 dref->path = av_mallocz(len+1);
510 return AVERROR(ENOMEM);
511 avio_read(pb, dref->path, len);
512 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
514 memmove(dref->path, dref->path+volume_len, len);
517 for (j = 0; j < len; j++)
518 if (dref->path[j] == ':')
520 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
521 } else if (type == 0) { // directory name
523 dref->dir = av_malloc(len+1);
525 return AVERROR(ENOMEM);
526 if (avio_read(pb, dref->dir, len) != len)
527 return AVERROR_INVALIDDATA;
529 for (j = 0; j < len; j++)
530 if (dref->dir[j] == ':')
532 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
537 avio_seek(pb, next, SEEK_SET);
542 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
546 uint32_t av_unused ctype;
550 if (c->fc->nb_streams < 1) // meta before first trak
553 st = c->fc->streams[c->fc->nb_streams-1];
555 avio_r8(pb); /* version */
556 avio_rb24(pb); /* flags */
559 ctype = avio_rl32(pb);
560 type = avio_rl32(pb); /* component subtype */
562 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
563 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
565 if (type == MKTAG('v','i','d','e'))
566 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
567 else if (type == MKTAG('s','o','u','n'))
568 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
569 else if (type == MKTAG('m','1','a',' '))
570 st->codec->codec_id = AV_CODEC_ID_MP2;
571 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
572 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
574 avio_rb32(pb); /* component manufacture */
575 avio_rb32(pb); /* component flags */
576 avio_rb32(pb); /* component flags mask */
578 title_size = atom.size - 24;
579 if (title_size > 0) {
580 title_str = av_malloc(title_size + 1); /* Add null terminator */
582 return AVERROR(ENOMEM);
583 avio_read(pb, title_str, title_size);
584 title_str[title_size] = 0;
586 av_dict_set(&st->metadata, "handler_name", title_str +
587 (!c->isom && title_str[0] == title_size - 1), 0);
588 av_freep(&title_str);
594 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
599 if (fc->nb_streams < 1)
601 st = fc->streams[fc->nb_streams-1];
603 avio_rb32(pb); /* version + flags */
604 ff_mp4_read_descr(fc, pb, &tag);
605 if (tag == MP4ESDescrTag) {
606 ff_mp4_parse_es_descr(pb, NULL);
608 avio_rb16(pb); /* ID */
610 ff_mp4_read_descr(fc, pb, &tag);
611 if (tag == MP4DecConfigDescrTag)
612 ff_mp4_read_dec_config_descr(fc, st, pb);
616 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
618 return ff_mov_read_esds(c->fc, pb);
621 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
624 int ac3info, acmod, lfeon, bsmod;
626 if (c->fc->nb_streams < 1)
628 st = c->fc->streams[c->fc->nb_streams-1];
630 ac3info = avio_rb24(pb);
631 bsmod = (ac3info >> 14) & 0x7;
632 acmod = (ac3info >> 11) & 0x7;
633 lfeon = (ac3info >> 10) & 0x1;
634 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
635 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
637 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
638 st->codec->audio_service_type = bsmod;
639 if (st->codec->channels > 1 && bsmod == 0x7)
640 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
645 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
648 int eac3info, acmod, lfeon, bsmod;
650 if (c->fc->nb_streams < 1)
652 st = c->fc->streams[c->fc->nb_streams-1];
654 /* No need to parse fields for additional independent substreams and its
655 * associated dependent substreams since libavcodec's E-AC-3 decoder
656 * does not support them yet. */
657 avio_rb16(pb); /* data_rate and num_ind_sub */
658 eac3info = avio_rb24(pb);
659 bsmod = (eac3info >> 12) & 0x1f;
660 acmod = (eac3info >> 9) & 0x7;
661 lfeon = (eac3info >> 8) & 0x1;
662 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
664 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
665 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
666 st->codec->audio_service_type = bsmod;
667 if (st->codec->channels > 1 && bsmod == 0x7)
668 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
673 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
677 if (c->fc->nb_streams < 1)
679 st = c->fc->streams[c->fc->nb_streams-1];
684 /* skip version and flags */
687 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
692 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
697 if (c->fc->nb_streams < 1)
699 st = c->fc->streams[c->fc->nb_streams-1];
701 if ((ret = ff_get_wav_header(pb, st->codec, atom.size)) < 0)
702 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
707 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
709 const int num = avio_rb32(pb);
710 const int den = avio_rb32(pb);
713 if (c->fc->nb_streams < 1)
715 st = c->fc->streams[c->fc->nb_streams-1];
717 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
718 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
719 av_log(c->fc, AV_LOG_WARNING,
720 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
721 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
723 } else if (den != 0) {
724 st->sample_aspect_ratio.num = num;
725 st->sample_aspect_ratio.den = den;
730 /* this atom contains actual media data */
731 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
733 if (atom.size == 0) /* wrong one (MP4) */
736 return 0; /* now go for moov */
739 /* read major brand, minor version and compatible brands and store them as metadata */
740 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
744 char* comp_brands_str;
745 uint8_t type[5] = {0};
747 avio_read(pb, type, 4);
748 if (strcmp(type, "qt "))
750 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
751 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
752 minor_ver = avio_rb32(pb); /* minor version */
753 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
755 comp_brand_size = atom.size - 8;
756 if (comp_brand_size < 0)
757 return AVERROR_INVALIDDATA;
758 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
759 if (!comp_brands_str)
760 return AVERROR(ENOMEM);
761 avio_read(pb, comp_brands_str, comp_brand_size);
762 comp_brands_str[comp_brand_size] = 0;
763 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
764 av_freep(&comp_brands_str);
769 /* this atom should contain all header atoms */
770 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
775 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
776 avio_skip(pb, atom.size);
780 if ((ret = mov_read_default(c, pb, atom)) < 0)
782 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
783 /* so we don't parse the whole file if over a network */
785 return 0; /* now go for mdat */
788 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
790 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
791 c->has_looked_for_mfra = 1;
794 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
796 if ((ret = mov_read_mfra(c, pb)) < 0) {
797 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
798 "read the mfra (may be a live ismv)\n");
801 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
802 "seekable, can not look for mfra\n");
805 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
806 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
807 return mov_read_default(c, pb, atom);
810 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
814 struct tm *ptm, tmbuf;
816 if(time >= 2082844800)
817 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
819 ptm = gmtime_r(&timet, &tmbuf);
821 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
822 av_dict_set(metadata, "creation_time", buffer, 0);
826 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
829 MOVStreamContext *sc;
831 char language[4] = {0};
833 int64_t creation_time;
835 if (c->fc->nb_streams < 1)
837 st = c->fc->streams[c->fc->nb_streams-1];
840 if (sc->time_scale) {
841 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
842 return AVERROR_INVALIDDATA;
845 version = avio_r8(pb);
847 avpriv_request_sample(c->fc, "Version %d", version);
848 return AVERROR_PATCHWELCOME;
850 avio_rb24(pb); /* flags */
852 creation_time = avio_rb64(pb);
855 creation_time = avio_rb32(pb);
856 avio_rb32(pb); /* modification time */
858 mov_metadata_creation_time(&st->metadata, creation_time);
860 sc->time_scale = avio_rb32(pb);
861 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
863 lang = avio_rb16(pb); /* language */
864 if (ff_mov_lang_to_iso639(lang, language))
865 av_dict_set(&st->metadata, "language", language, 0);
866 avio_rb16(pb); /* quality */
871 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
873 int64_t creation_time;
874 int version = avio_r8(pb); /* version */
875 avio_rb24(pb); /* flags */
878 creation_time = avio_rb64(pb);
881 creation_time = avio_rb32(pb);
882 avio_rb32(pb); /* modification time */
884 mov_metadata_creation_time(&c->fc->metadata, creation_time);
885 c->time_scale = avio_rb32(pb); /* time scale */
887 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
889 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
890 // set the AVCodecContext duration because the duration of individual tracks
892 if (c->time_scale > 0 && !c->trex_data)
893 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
894 avio_rb32(pb); /* preferred scale */
896 avio_rb16(pb); /* preferred volume */
898 avio_skip(pb, 10); /* reserved */
900 avio_skip(pb, 36); /* display matrix */
902 avio_rb32(pb); /* preview time */
903 avio_rb32(pb); /* preview duration */
904 avio_rb32(pb); /* poster time */
905 avio_rb32(pb); /* selection time */
906 avio_rb32(pb); /* selection duration */
907 avio_rb32(pb); /* current time */
908 avio_rb32(pb); /* next track ID */
912 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
917 if (c->fc->nb_streams < 1)
919 st = c->fc->streams[c->fc->nb_streams-1];
921 little_endian = avio_rb16(pb) & 0xFF;
922 av_dlog(c->fc, "enda %d\n", little_endian);
923 if (little_endian == 1) {
924 switch (st->codec->codec_id) {
925 case AV_CODEC_ID_PCM_S24BE:
926 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
928 case AV_CODEC_ID_PCM_S32BE:
929 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
931 case AV_CODEC_ID_PCM_F32BE:
932 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
934 case AV_CODEC_ID_PCM_F64BE:
935 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
944 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
947 char color_parameter_type[5] = { 0 };
948 int color_primaries, color_trc, color_matrix;
950 if (c->fc->nb_streams < 1)
952 st = c->fc->streams[c->fc->nb_streams - 1];
954 avio_read(pb, color_parameter_type, 4);
955 if (strncmp(color_parameter_type, "nclx", 4) &&
956 strncmp(color_parameter_type, "nclc", 4)) {
957 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
958 color_parameter_type);
962 color_primaries = avio_rb16(pb);
963 color_trc = avio_rb16(pb);
964 color_matrix = avio_rb16(pb);
966 av_dlog(c->fc, "%s: pri %d trc %d matrix %d",
967 color_parameter_type, color_primaries, color_trc, color_matrix);
970 uint8_t color_range = avio_r8(pb) >> 7;
971 av_dlog(c->fc, " full %"PRIu8"", color_range);
973 st->codec->color_range = AVCOL_RANGE_JPEG;
975 st->codec->color_range = AVCOL_RANGE_MPEG;
976 /* 14496-12 references JPEG XR specs (rather than the more complete
977 * 23001-8) so some adjusting is required */
978 if (color_primaries >= AVCOL_PRI_FILM)
979 color_primaries = AVCOL_PRI_UNSPECIFIED;
980 if ((color_trc >= AVCOL_TRC_LINEAR &&
981 color_trc <= AVCOL_TRC_LOG_SQRT) ||
982 color_trc >= AVCOL_TRC_BT2020_10)
983 color_trc = AVCOL_TRC_UNSPECIFIED;
984 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
985 color_matrix = AVCOL_SPC_UNSPECIFIED;
986 st->codec->color_primaries = color_primaries;
987 st->codec->color_trc = color_trc;
988 st->codec->colorspace = color_matrix;
990 /* color primaries, Table 4-4 */
991 switch (color_primaries) {
992 case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
993 case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
994 case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
996 /* color transfer, Table 4-5 */
998 case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
999 case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
1001 /* color matrix, Table 4-6 */
1002 switch (color_matrix) {
1003 case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
1004 case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
1005 case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
1008 av_dlog(c->fc, "\n");
1013 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1016 unsigned mov_field_order;
1017 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1019 if (c->fc->nb_streams < 1) // will happen with jp2 files
1021 st = c->fc->streams[c->fc->nb_streams-1];
1023 return AVERROR_INVALIDDATA;
1024 mov_field_order = avio_rb16(pb);
1025 if ((mov_field_order & 0xFF00) == 0x0100)
1026 decoded_field_order = AV_FIELD_PROGRESSIVE;
1027 else if ((mov_field_order & 0xFF00) == 0x0200) {
1028 switch (mov_field_order & 0xFF) {
1029 case 0x01: decoded_field_order = AV_FIELD_TT;
1031 case 0x06: decoded_field_order = AV_FIELD_BB;
1033 case 0x09: decoded_field_order = AV_FIELD_TB;
1035 case 0x0E: decoded_field_order = AV_FIELD_BT;
1039 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1040 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1042 st->codec->field_order = decoded_field_order;
1047 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
1048 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1049 enum AVCodecID codec_id)
1056 if (c->fc->nb_streams < 1) // will happen with jp2 files
1058 st= c->fc->streams[c->fc->nb_streams-1];
1060 if (st->codec->codec_id != codec_id)
1061 return 0; /* unexpected codec_id - don't mess with extradata */
1063 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
1064 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1065 return AVERROR_INVALIDDATA;
1066 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
1067 st->codec->extradata_size = 0;
1070 buf = st->codec->extradata + st->codec->extradata_size;
1071 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
1072 AV_WB32( buf , atom.size + 8);
1073 AV_WL32( buf + 4, atom.type);
1074 err = avio_read(pb, buf + 8, atom.size);
1077 } else if (err < atom.size) {
1078 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1079 st->codec->extradata_size -= atom.size - err;
1081 memset(buf + 8 + err, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1085 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1086 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1088 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1091 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1093 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1096 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1098 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1101 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1103 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1105 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1109 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1111 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1113 if (!ret && c->fc->nb_streams >= 1) {
1114 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
1115 if (avctx->extradata_size >= 40) {
1116 avctx->height = AV_RB16(&avctx->extradata[36]);
1117 avctx->width = AV_RB16(&avctx->extradata[38]);
1123 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1125 if (c->fc->nb_streams >= 1) {
1126 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1127 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1128 codec->codec_id == AV_CODEC_ID_H264 &&
1131 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1132 if (avio_rb16(pb) == 0xd4d)
1133 codec->width = 1440;
1138 return mov_read_avid(c, pb, atom);
1141 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1143 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1146 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1150 if (c->fc->nb_streams < 1)
1152 st = c->fc->streams[c->fc->nb_streams-1];
1154 if ((uint64_t)atom.size > (1<<30))
1155 return AVERROR_INVALIDDATA;
1157 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1158 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1159 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1160 // pass all frma atom to codec, needed at least for QDMC and QDM2
1161 av_free(st->codec->extradata);
1162 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1163 return AVERROR(ENOMEM);
1164 } else if (atom.size > 8) { /* to read frma, esds atoms */
1166 if ((ret = mov_read_default(c, pb, atom)) < 0)
1169 avio_skip(pb, atom.size);
1174 * This function reads atom content and puts data in extradata without tag
1175 * nor size unlike mov_read_extradata.
1177 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1181 if (c->fc->nb_streams < 1)
1183 st = c->fc->streams[c->fc->nb_streams-1];
1185 if ((uint64_t)atom.size > (1<<30))
1186 return AVERROR_INVALIDDATA;
1188 if (atom.size >= 10) {
1189 // Broken files created by legacy versions of libavformat will
1190 // wrap a whole fiel atom inside of a glbl atom.
1191 unsigned size = avio_rb32(pb);
1192 unsigned type = avio_rl32(pb);
1193 avio_seek(pb, -8, SEEK_CUR);
1194 if (type == MKTAG('f','i','e','l') && size == atom.size)
1195 return mov_read_default(c, pb, atom);
1197 if (st->codec->extradata_size > 1 && st->codec->extradata) {
1198 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1201 av_free(st->codec->extradata);
1202 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1203 return AVERROR(ENOMEM);
1208 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1211 uint8_t profile_level;
1214 if (c->fc->nb_streams < 1)
1216 st = c->fc->streams[c->fc->nb_streams-1];
1218 if (atom.size >= (1<<28) || atom.size < 7)
1219 return AVERROR_INVALIDDATA;
1221 profile_level = avio_r8(pb);
1222 if ((profile_level & 0xf0) != 0xc0)
1225 avio_seek(pb, 6, SEEK_CUR);
1226 av_free(st->codec->extradata);
1227 if ((ret = ff_get_extradata(st->codec, pb, atom.size - 7)) < 0)
1234 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1235 * but can have extradata appended at the end after the 40 bytes belonging
1238 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1242 if (c->fc->nb_streams < 1)
1244 if (atom.size <= 40)
1246 st = c->fc->streams[c->fc->nb_streams-1];
1248 if ((uint64_t)atom.size > (1<<30))
1249 return AVERROR_INVALIDDATA;
1252 av_free(st->codec->extradata);
1253 if (ff_get_extradata(st->codec, pb, atom.size - 40) < 0)
1254 return AVERROR(ENOMEM);
1258 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1261 MOVStreamContext *sc;
1262 unsigned int i, entries;
1264 if (c->fc->nb_streams < 1)
1266 st = c->fc->streams[c->fc->nb_streams-1];
1269 avio_r8(pb); /* version */
1270 avio_rb24(pb); /* flags */
1272 entries = avio_rb32(pb);
1277 if (sc->chunk_offsets)
1278 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1279 av_free(sc->chunk_offsets);
1280 sc->chunk_count = 0;
1281 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1282 if (!sc->chunk_offsets)
1283 return AVERROR(ENOMEM);
1284 sc->chunk_count = entries;
1286 if (atom.type == MKTAG('s','t','c','o'))
1287 for (i = 0; i < entries && !pb->eof_reached; i++)
1288 sc->chunk_offsets[i] = avio_rb32(pb);
1289 else if (atom.type == MKTAG('c','o','6','4'))
1290 for (i = 0; i < entries && !pb->eof_reached; i++)
1291 sc->chunk_offsets[i] = avio_rb64(pb);
1293 return AVERROR_INVALIDDATA;
1295 sc->chunk_count = i;
1297 if (pb->eof_reached)
1304 * Compute codec id for 'lpcm' tag.
1305 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1307 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1314 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1317 static int mov_codec_id(AVStream *st, uint32_t format)
1319 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1322 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1323 (format & 0xFFFF) == 'T' + ('S' << 8)))
1324 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1326 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1327 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1328 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1329 /* skip old asf mpeg4 tag */
1330 format && format != MKTAG('m','p','4','s')) {
1331 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1333 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1335 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1336 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1337 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1338 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1339 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1341 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1345 st->codec->codec_tag = format;
1350 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1351 AVStream *st, MOVStreamContext *sc)
1353 uint8_t codec_name[32];
1354 unsigned int color_depth, len, j;
1355 int color_greyscale;
1358 avio_rb16(pb); /* version */
1359 avio_rb16(pb); /* revision level */
1360 avio_rb32(pb); /* vendor */
1361 avio_rb32(pb); /* temporal quality */
1362 avio_rb32(pb); /* spatial quality */
1364 st->codec->width = avio_rb16(pb); /* width */
1365 st->codec->height = avio_rb16(pb); /* height */
1367 avio_rb32(pb); /* horiz resolution */
1368 avio_rb32(pb); /* vert resolution */
1369 avio_rb32(pb); /* data size, always 0 */
1370 avio_rb16(pb); /* frames per samples */
1372 len = avio_r8(pb); /* codec name, pascal string */
1375 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1377 avio_skip(pb, 31 - len);
1380 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1382 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1383 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1384 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1385 st->codec->width &= ~1;
1386 st->codec->height &= ~1;
1388 /* Flash Media Server uses tag H263 with Sorenson Spark */
1389 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1390 !memcmp(codec_name, "Sorenson H263", 13))
1391 st->codec->codec_id = AV_CODEC_ID_FLV1;
1393 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1394 color_table_id = avio_rb16(pb); /* colortable id */
1395 av_dlog(c->fc, "depth %d, ctab id %d\n",
1396 st->codec->bits_per_coded_sample, color_table_id);
1397 /* figure out the palette situation */
1398 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1399 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1400 /* Do not create a greyscale palette for cinepak */
1401 if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1404 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1405 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1406 /* for palette traversal */
1407 unsigned int color_start, color_count, color_end;
1408 unsigned char a, r, g, b;
1410 if (color_greyscale) {
1411 int color_index, color_dec;
1412 /* compute the greyscale palette */
1413 st->codec->bits_per_coded_sample = color_depth;
1414 color_count = 1 << color_depth;
1416 color_dec = 256 / (color_count - 1);
1417 for (j = 0; j < color_count; j++) {
1418 r = g = b = color_index;
1419 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1420 color_index -= color_dec;
1421 if (color_index < 0)
1424 } else if (color_table_id) {
1425 const uint8_t *color_table;
1426 /* if flag bit 3 is set, use the default palette */
1427 color_count = 1 << color_depth;
1428 if (color_depth == 2)
1429 color_table = ff_qt_default_palette_4;
1430 else if (color_depth == 4)
1431 color_table = ff_qt_default_palette_16;
1433 color_table = ff_qt_default_palette_256;
1435 for (j = 0; j < color_count; j++) {
1436 r = color_table[j * 3 + 0];
1437 g = color_table[j * 3 + 1];
1438 b = color_table[j * 3 + 2];
1439 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1442 /* load the palette from the file */
1443 color_start = avio_rb32(pb);
1444 color_count = avio_rb16(pb);
1445 color_end = avio_rb16(pb);
1446 if ((color_start <= 255) && (color_end <= 255)) {
1447 for (j = color_start; j <= color_end; j++) {
1448 /* each A, R, G, or B component is 16 bits;
1449 * only use the top 8 bits */
1458 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1462 sc->has_palette = 1;
1466 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1467 AVStream *st, MOVStreamContext *sc)
1469 int bits_per_sample, flags;
1470 uint16_t version = avio_rb16(pb);
1471 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1473 avio_rb16(pb); /* revision level */
1474 avio_rb32(pb); /* vendor */
1476 st->codec->channels = avio_rb16(pb); /* channel count */
1477 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1478 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1480 sc->audio_cid = avio_rb16(pb);
1481 avio_rb16(pb); /* packet size = 0 */
1483 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1485 // Read QT version 1 fields. In version 0 these do not exist.
1486 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1488 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1491 sc->samples_per_frame = avio_rb32(pb);
1492 avio_rb32(pb); /* bytes per packet */
1493 sc->bytes_per_frame = avio_rb32(pb);
1494 avio_rb32(pb); /* bytes per sample */
1495 } else if (version == 2) {
1496 avio_rb32(pb); /* sizeof struct only */
1497 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1498 st->codec->channels = avio_rb32(pb);
1499 avio_rb32(pb); /* always 0x7F000000 */
1500 st->codec->bits_per_coded_sample = avio_rb32(pb);
1502 flags = avio_rb32(pb); /* lpcm format specific flag */
1503 sc->bytes_per_frame = avio_rb32(pb);
1504 sc->samples_per_frame = avio_rb32(pb);
1505 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1506 st->codec->codec_id =
1507 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1512 switch (st->codec->codec_id) {
1513 case AV_CODEC_ID_PCM_S8:
1514 case AV_CODEC_ID_PCM_U8:
1515 if (st->codec->bits_per_coded_sample == 16)
1516 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1518 case AV_CODEC_ID_PCM_S16LE:
1519 case AV_CODEC_ID_PCM_S16BE:
1520 if (st->codec->bits_per_coded_sample == 8)
1521 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1522 else if (st->codec->bits_per_coded_sample == 24)
1523 st->codec->codec_id =
1524 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1525 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1526 else if (st->codec->bits_per_coded_sample == 32)
1527 st->codec->codec_id =
1528 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1529 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1531 /* set values for old format before stsd version 1 appeared */
1532 case AV_CODEC_ID_MACE3:
1533 sc->samples_per_frame = 6;
1534 sc->bytes_per_frame = 2 * st->codec->channels;
1536 case AV_CODEC_ID_MACE6:
1537 sc->samples_per_frame = 6;
1538 sc->bytes_per_frame = 1 * st->codec->channels;
1540 case AV_CODEC_ID_ADPCM_IMA_QT:
1541 sc->samples_per_frame = 64;
1542 sc->bytes_per_frame = 34 * st->codec->channels;
1544 case AV_CODEC_ID_GSM:
1545 sc->samples_per_frame = 160;
1546 sc->bytes_per_frame = 33;
1552 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1553 if (bits_per_sample) {
1554 st->codec->bits_per_coded_sample = bits_per_sample;
1555 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1559 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1560 AVStream *st, MOVStreamContext *sc,
1563 // ttxt stsd contains display flags, justification, background
1564 // color, fonts, and default styles, so fake an atom to read it
1565 MOVAtom fake_atom = { .size = size };
1566 // mp4s contains a regular esds atom
1567 if (st->codec->codec_tag != AV_RL32("mp4s"))
1568 mov_read_glbl(c, pb, fake_atom);
1569 st->codec->width = sc->width;
1570 st->codec->height = sc->height;
1573 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1578 y = (ycbcr >> 16) & 0xFF;
1579 cr = (ycbcr >> 8) & 0xFF;
1582 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1583 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1584 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1586 return (r << 16) | (g << 8) | b;
1589 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1591 char buf[256] = {0};
1592 uint8_t *src = st->codec->extradata;
1595 if (st->codec->extradata_size != 64)
1598 if (st->codec->width > 0 && st->codec->height > 0)
1599 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1600 st->codec->width, st->codec->height);
1601 av_strlcat(buf, "palette: ", sizeof(buf));
1603 for (i = 0; i < 16; i++) {
1604 uint32_t yuv = AV_RB32(src + i * 4);
1605 uint32_t rgba = yuv_to_rgba(yuv);
1607 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1610 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1613 av_freep(&st->codec->extradata);
1614 st->codec->extradata_size = 0;
1615 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1616 if (!st->codec->extradata)
1617 return AVERROR(ENOMEM);
1618 st->codec->extradata_size = strlen(buf);
1619 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1624 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1625 AVStream *st, MOVStreamContext *sc,
1628 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1629 if (ff_get_extradata(st->codec, pb, size) < 0)
1630 return AVERROR(ENOMEM);
1632 MOVStreamContext *tmcd_ctx = st->priv_data;
1634 val = AV_RB32(st->codec->extradata + 4);
1635 tmcd_ctx->tmcd_flags = val;
1637 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1638 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
1639 st->codec->time_base.num = 1;
1641 uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
1642 uint32_t format = AV_RB32(st->codec->extradata + 22);
1643 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
1644 uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
1645 if (str_size > 0 && size >= (int)str_size + 26) {
1646 char *reel_name = av_malloc(str_size + 1);
1648 return AVERROR(ENOMEM);
1649 memcpy(reel_name, st->codec->extradata + 30, str_size);
1650 reel_name[str_size] = 0; /* Add null terminator */
1651 /* don't add reel_name if emtpy string */
1652 if (*reel_name == 0) {
1655 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
1662 /* other codec type, just skip (rtp, mp4s ...) */
1663 avio_skip(pb, size);
1668 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1669 AVStream *st, MOVStreamContext *sc)
1671 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1672 !st->codec->sample_rate && sc->time_scale > 1)
1673 st->codec->sample_rate = sc->time_scale;
1675 /* special codec parameters handling */
1676 switch (st->codec->codec_id) {
1677 #if CONFIG_DV_DEMUXER
1678 case AV_CODEC_ID_DVAUDIO:
1679 c->dv_fctx = avformat_alloc_context();
1680 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1682 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1683 return AVERROR(ENOMEM);
1685 sc->dv_audio_container = 1;
1686 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1689 /* no ifdef since parameters are always those */
1690 case AV_CODEC_ID_QCELP:
1691 st->codec->channels = 1;
1692 // force sample rate for qcelp when not stored in mov
1693 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1694 st->codec->sample_rate = 8000;
1695 // FIXME: Why is the following needed for some files?
1696 sc->samples_per_frame = 160;
1697 if (!sc->bytes_per_frame)
1698 sc->bytes_per_frame = 35;
1700 case AV_CODEC_ID_AMR_NB:
1701 st->codec->channels = 1;
1702 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1703 st->codec->sample_rate = 8000;
1705 case AV_CODEC_ID_AMR_WB:
1706 st->codec->channels = 1;
1707 st->codec->sample_rate = 16000;
1709 case AV_CODEC_ID_MP2:
1710 case AV_CODEC_ID_MP3:
1711 /* force type after stsd for m1a hdlr */
1712 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1713 st->need_parsing = AVSTREAM_PARSE_FULL;
1715 case AV_CODEC_ID_GSM:
1716 case AV_CODEC_ID_ADPCM_MS:
1717 case AV_CODEC_ID_ADPCM_IMA_WAV:
1718 case AV_CODEC_ID_ILBC:
1719 case AV_CODEC_ID_MACE3:
1720 case AV_CODEC_ID_MACE6:
1721 case AV_CODEC_ID_QDM2:
1722 st->codec->block_align = sc->bytes_per_frame;
1724 case AV_CODEC_ID_ALAC:
1725 if (st->codec->extradata_size == 36) {
1726 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1727 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1730 case AV_CODEC_ID_AC3:
1731 case AV_CODEC_ID_EAC3:
1732 case AV_CODEC_ID_MPEG1VIDEO:
1733 case AV_CODEC_ID_VC1:
1734 st->need_parsing = AVSTREAM_PARSE_FULL;
1742 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1743 int codec_tag, int format,
1746 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1749 (codec_tag != format &&
1750 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1751 : codec_tag != MKTAG('j','p','e','g')))) {
1752 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1753 * export it as a separate AVStream but this needs a few changes
1754 * in the MOV demuxer, patch welcome. */
1756 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1757 avio_skip(pb, size);
1760 if ( codec_tag == AV_RL32("avc1") ||
1761 codec_tag == AV_RL32("hvc1") ||
1762 codec_tag == AV_RL32("hev1")
1764 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
1769 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1772 MOVStreamContext *sc;
1773 int pseudo_stream_id;
1775 if (c->fc->nb_streams < 1)
1777 st = c->fc->streams[c->fc->nb_streams-1];
1780 for (pseudo_stream_id = 0;
1781 pseudo_stream_id < entries && !pb->eof_reached;
1782 pseudo_stream_id++) {
1783 //Parsing Sample description table
1785 int ret, dref_id = 1;
1786 MOVAtom a = { AV_RL32("stsd") };
1787 int64_t start_pos = avio_tell(pb);
1788 int64_t size = avio_rb32(pb); /* size */
1789 uint32_t format = avio_rl32(pb); /* data format */
1792 avio_rb32(pb); /* reserved */
1793 avio_rb16(pb); /* reserved */
1794 dref_id = avio_rb16(pb);
1795 }else if (size <= 7){
1796 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1797 return AVERROR_INVALIDDATA;
1800 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1801 size - (avio_tell(pb) - start_pos)))
1804 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1805 sc->dref_id= dref_id;
1807 id = mov_codec_id(st, format);
1809 av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1810 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1811 (format >> 24) & 0xff, st->codec->codec_type);
1813 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1814 st->codec->codec_id = id;
1815 mov_parse_stsd_video(c, pb, st, sc);
1816 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1817 st->codec->codec_id = id;
1818 mov_parse_stsd_audio(c, pb, st, sc);
1819 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1820 st->codec->codec_id = id;
1821 mov_parse_stsd_subtitle(c, pb, st, sc,
1822 size - (avio_tell(pb) - start_pos));
1824 ret = mov_parse_stsd_data(c, pb, st, sc,
1825 size - (avio_tell(pb) - start_pos));
1829 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1830 a.size = size - (avio_tell(pb) - start_pos);
1832 if ((ret = mov_read_default(c, pb, a)) < 0)
1834 } else if (a.size > 0)
1835 avio_skip(pb, a.size);
1838 if (pb->eof_reached)
1841 return mov_finalize_stsd_codec(c, pb, st, sc);
1844 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1848 avio_r8(pb); /* version */
1849 avio_rb24(pb); /* flags */
1850 entries = avio_rb32(pb);
1852 return ff_mov_read_stsd_entries(c, pb, entries);
1855 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1858 MOVStreamContext *sc;
1859 unsigned int i, entries;
1861 if (c->fc->nb_streams < 1)
1863 st = c->fc->streams[c->fc->nb_streams-1];
1866 avio_r8(pb); /* version */
1867 avio_rb24(pb); /* flags */
1869 entries = avio_rb32(pb);
1871 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1876 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
1877 av_free(sc->stsc_data);
1879 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
1881 return AVERROR(ENOMEM);
1883 for (i = 0; i < entries && !pb->eof_reached; i++) {
1884 sc->stsc_data[i].first = avio_rb32(pb);
1885 sc->stsc_data[i].count = avio_rb32(pb);
1886 sc->stsc_data[i].id = avio_rb32(pb);
1891 if (pb->eof_reached)
1897 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1900 MOVStreamContext *sc;
1901 unsigned i, entries;
1903 if (c->fc->nb_streams < 1)
1905 st = c->fc->streams[c->fc->nb_streams-1];
1908 avio_rb32(pb); // version + flags
1910 entries = avio_rb32(pb);
1912 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
1913 av_free(sc->stps_data);
1915 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
1917 return AVERROR(ENOMEM);
1919 for (i = 0; i < entries && !pb->eof_reached; i++) {
1920 sc->stps_data[i] = avio_rb32(pb);
1921 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1926 if (pb->eof_reached)
1932 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1935 MOVStreamContext *sc;
1936 unsigned int i, entries;
1938 if (c->fc->nb_streams < 1)
1940 st = c->fc->streams[c->fc->nb_streams-1];
1943 avio_r8(pb); /* version */
1944 avio_rb24(pb); /* flags */
1946 entries = avio_rb32(pb);
1948 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1952 sc->keyframe_absent = 1;
1953 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1954 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1958 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
1959 av_free(sc->keyframes);
1960 sc->keyframe_count = 0;
1961 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
1963 return AVERROR(ENOMEM);
1965 for (i = 0; i < entries && !pb->eof_reached; i++) {
1966 sc->keyframes[i] = avio_rb32(pb);
1967 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1970 sc->keyframe_count = i;
1972 if (pb->eof_reached)
1978 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1981 MOVStreamContext *sc;
1982 unsigned int i, entries, sample_size, field_size, num_bytes;
1986 if (c->fc->nb_streams < 1)
1988 st = c->fc->streams[c->fc->nb_streams-1];
1991 avio_r8(pb); /* version */
1992 avio_rb24(pb); /* flags */
1994 if (atom.type == MKTAG('s','t','s','z')) {
1995 sample_size = avio_rb32(pb);
1996 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1997 sc->sample_size = sample_size;
1998 sc->stsz_sample_size = sample_size;
2002 avio_rb24(pb); /* reserved */
2003 field_size = avio_r8(pb);
2005 entries = avio_rb32(pb);
2007 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2009 sc->sample_count = entries;
2013 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2014 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2015 return AVERROR_INVALIDDATA;
2020 if (entries >= (UINT_MAX - 4) / field_size)
2021 return AVERROR_INVALIDDATA;
2022 if (sc->sample_sizes)
2023 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2024 av_free(sc->sample_sizes);
2025 sc->sample_count = 0;
2026 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2027 if (!sc->sample_sizes)
2028 return AVERROR(ENOMEM);
2030 num_bytes = (entries*field_size+4)>>3;
2032 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
2034 av_freep(&sc->sample_sizes);
2035 return AVERROR(ENOMEM);
2038 if (avio_read(pb, buf, num_bytes) < num_bytes) {
2039 av_freep(&sc->sample_sizes);
2041 return AVERROR_INVALIDDATA;
2044 init_get_bits(&gb, buf, 8*num_bytes);
2046 for (i = 0; i < entries && !pb->eof_reached; i++) {
2047 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2048 sc->data_size += sc->sample_sizes[i];
2051 sc->sample_count = i;
2053 if (pb->eof_reached)
2060 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2063 MOVStreamContext *sc;
2064 unsigned int i, entries;
2066 int64_t total_sample_count=0;
2068 if (c->fc->nb_streams < 1)
2070 st = c->fc->streams[c->fc->nb_streams-1];
2073 avio_r8(pb); /* version */
2074 avio_rb24(pb); /* flags */
2075 entries = avio_rb32(pb);
2077 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
2078 c->fc->nb_streams-1, entries);
2081 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2082 av_free(sc->stts_data);
2084 sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2086 return AVERROR(ENOMEM);
2088 for (i = 0; i < entries && !pb->eof_reached; i++) {
2089 int sample_duration;
2092 sample_count=avio_rb32(pb);
2093 sample_duration = avio_rb32(pb);
2095 /* sample_duration < 0 is invalid based on the spec */
2096 if (sample_duration < 0) {
2097 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2098 sample_duration, i, c->fc->nb_streams-1);
2099 sample_duration = 1;
2101 if (sample_count < 0) {
2102 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2103 return AVERROR_INVALIDDATA;
2105 sc->stts_data[i].count= sample_count;
2106 sc->stts_data[i].duration= sample_duration;
2108 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
2109 sample_count, sample_duration);
2113 && sample_count == 1
2114 && total_sample_count > 100
2115 && sample_duration/10 > duration / total_sample_count)
2116 sample_duration = duration / total_sample_count;
2117 duration+=(int64_t)sample_duration*sample_count;
2118 total_sample_count+=sample_count;
2123 sc->duration_for_fps += duration;
2124 sc->nb_frames_for_fps += total_sample_count;
2126 if (pb->eof_reached)
2129 st->nb_frames= total_sample_count;
2131 st->duration= duration;
2132 sc->track_end = duration;
2136 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2139 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2143 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2146 MOVStreamContext *sc;
2147 unsigned int i, entries;
2149 if (c->fc->nb_streams < 1)
2151 st = c->fc->streams[c->fc->nb_streams-1];
2154 avio_r8(pb); /* version */
2155 avio_rb24(pb); /* flags */
2156 entries = avio_rb32(pb);
2158 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2162 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2163 return AVERROR_INVALIDDATA;
2164 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
2166 return AVERROR(ENOMEM);
2168 for (i = 0; i < entries && !pb->eof_reached; i++) {
2169 int count =avio_rb32(pb);
2170 int duration =avio_rb32(pb);
2172 sc->ctts_data[i].count = count;
2173 sc->ctts_data[i].duration= duration;
2175 av_dlog(c->fc, "count=%d, duration=%d\n",
2178 if (FFABS(duration) > (1<<28) && i+2<entries) {
2179 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2180 av_freep(&sc->ctts_data);
2186 mov_update_dts_shift(sc, duration);
2191 if (pb->eof_reached)
2194 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
2199 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2202 MOVStreamContext *sc;
2203 unsigned int i, entries;
2205 uint32_t grouping_type;
2207 if (c->fc->nb_streams < 1)
2209 st = c->fc->streams[c->fc->nb_streams-1];
2212 version = avio_r8(pb); /* version */
2213 avio_rb24(pb); /* flags */
2214 grouping_type = avio_rl32(pb);
2215 if (grouping_type != MKTAG( 'r','a','p',' '))
2216 return 0; /* only support 'rap ' grouping */
2218 avio_rb32(pb); /* grouping_type_parameter */
2220 entries = avio_rb32(pb);
2224 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2225 av_free(sc->rap_group);
2226 sc->rap_group_count = 0;
2227 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2229 return AVERROR(ENOMEM);
2231 for (i = 0; i < entries && !pb->eof_reached; i++) {
2232 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2233 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2236 sc->rap_group_count = i;
2238 return pb->eof_reached ? AVERROR_EOF : 0;
2241 static void mov_build_index(MOVContext *mov, AVStream *st)
2243 MOVStreamContext *sc = st->priv_data;
2244 int64_t current_offset;
2245 int64_t current_dts = 0;
2246 unsigned int stts_index = 0;
2247 unsigned int stsc_index = 0;
2248 unsigned int stss_index = 0;
2249 unsigned int stps_index = 0;
2251 uint64_t stream_size = 0;
2253 /* adjust first dts according to edit list */
2254 if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
2255 if (sc->empty_duration)
2256 sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
2257 sc->time_offset = sc->start_time - sc->empty_duration;
2258 current_dts = -sc->time_offset;
2259 if (sc->ctts_count>0 && sc->stts_count>0 &&
2260 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2261 /* more than 16 frames delay, dts are likely wrong
2262 this happens with files created by iMovie */
2264 st->codec->has_b_frames = 1;
2268 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2269 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2270 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2271 unsigned int current_sample = 0;
2272 unsigned int stts_sample = 0;
2273 unsigned int sample_size;
2274 unsigned int distance = 0;
2275 unsigned int rap_group_index = 0;
2276 unsigned int rap_group_sample = 0;
2277 int rap_group_present = sc->rap_group_count && sc->rap_group;
2278 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2280 current_dts -= sc->dts_shift;
2282 if (!sc->sample_count || st->nb_index_entries)
2284 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2286 if (av_reallocp_array(&st->index_entries,
2287 st->nb_index_entries + sc->sample_count,
2288 sizeof(*st->index_entries)) < 0) {
2289 st->nb_index_entries = 0;
2292 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2294 for (i = 0; i < sc->chunk_count; i++) {
2295 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2296 current_offset = sc->chunk_offsets[i];
2297 while (stsc_index + 1 < sc->stsc_count &&
2298 i + 1 == sc->stsc_data[stsc_index + 1].first)
2301 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2302 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2303 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2304 sc->stsz_sample_size = sc->sample_size;
2306 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2307 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2308 sc->stsz_sample_size = sc->sample_size;
2311 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2313 if (current_sample >= sc->sample_count) {
2314 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2318 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2320 if (stss_index + 1 < sc->keyframe_count)
2322 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2324 if (stps_index + 1 < sc->stps_count)
2327 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2328 if (sc->rap_group[rap_group_index].index > 0)
2330 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2331 rap_group_sample = 0;
2335 if (sc->keyframe_absent
2337 && !rap_group_present
2338 && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2342 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2343 if (sc->pseudo_stream_id == -1 ||
2344 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2345 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2346 e->pos = current_offset;
2347 e->timestamp = current_dts;
2348 e->size = sample_size;
2349 e->min_distance = distance;
2350 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2351 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2352 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2353 current_offset, current_dts, sample_size, distance, keyframe);
2354 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2355 ff_rfps_add_frame(mov->fc, st, current_dts);
2358 current_offset += sample_size;
2359 stream_size += sample_size;
2360 current_dts += sc->stts_data[stts_index].duration;
2364 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2370 if (st->duration > 0)
2371 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2373 unsigned chunk_samples, total = 0;
2375 // compute total chunk count
2376 for (i = 0; i < sc->stsc_count; i++) {
2377 unsigned count, chunk_count;
2379 chunk_samples = sc->stsc_data[i].count;
2380 if (i != sc->stsc_count - 1 &&
2381 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2382 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2386 if (sc->samples_per_frame >= 160) { // gsm
2387 count = chunk_samples / sc->samples_per_frame;
2388 } else if (sc->samples_per_frame > 1) {
2389 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2390 count = (chunk_samples+samples-1) / samples;
2392 count = (chunk_samples+1023) / 1024;
2395 if (i < sc->stsc_count - 1)
2396 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2398 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2399 total += chunk_count * count;
2402 av_dlog(mov->fc, "chunk count %d\n", total);
2403 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2405 if (av_reallocp_array(&st->index_entries,
2406 st->nb_index_entries + total,
2407 sizeof(*st->index_entries)) < 0) {
2408 st->nb_index_entries = 0;
2411 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2414 for (i = 0; i < sc->chunk_count; i++) {
2415 current_offset = sc->chunk_offsets[i];
2416 if (stsc_index + 1 < sc->stsc_count &&
2417 i + 1 == sc->stsc_data[stsc_index + 1].first)
2419 chunk_samples = sc->stsc_data[stsc_index].count;
2421 while (chunk_samples > 0) {
2423 unsigned size, samples;
2425 if (sc->samples_per_frame >= 160) { // gsm
2426 samples = sc->samples_per_frame;
2427 size = sc->bytes_per_frame;
2429 if (sc->samples_per_frame > 1) {
2430 samples = FFMIN((1024 / sc->samples_per_frame)*
2431 sc->samples_per_frame, chunk_samples);
2432 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2434 samples = FFMIN(1024, chunk_samples);
2435 size = samples * sc->sample_size;
2439 if (st->nb_index_entries >= total) {
2440 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2443 e = &st->index_entries[st->nb_index_entries++];
2444 e->pos = current_offset;
2445 e->timestamp = current_dts;
2447 e->min_distance = 0;
2448 e->flags = AVINDEX_KEYFRAME;
2449 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2450 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2453 current_offset += size;
2454 current_dts += samples;
2455 chunk_samples -= samples;
2461 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2462 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2464 /* try relative path, we do not try the absolute because it can leak information about our
2465 system to an attacker */
2466 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2467 char filename[1024];
2468 const char *src_path;
2471 /* find a source dir */
2472 src_path = strrchr(src, '/');
2478 /* find a next level down to target */
2479 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2480 if (ref->path[l] == '/') {
2481 if (i == ref->nlvl_to - 1)
2487 /* compose filename if next level down to target was found */
2488 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2489 memcpy(filename, src, src_path - src);
2490 filename[src_path - src] = 0;
2492 for (i = 1; i < ref->nlvl_from; i++)
2493 av_strlcat(filename, "../", 1024);
2495 av_strlcat(filename, ref->path + l + 1, 1024);
2497 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2500 } else if (use_absolute_path) {
2501 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2502 "this is a possible security issue\n");
2503 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2507 return AVERROR(ENOENT);
2510 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2512 if (sc->time_scale <= 0) {
2513 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2514 sc->time_scale = c->time_scale;
2515 if (sc->time_scale <= 0)
2520 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2523 MOVStreamContext *sc;
2526 st = avformat_new_stream(c->fc, NULL);
2527 if (!st) return AVERROR(ENOMEM);
2528 st->id = c->fc->nb_streams;
2529 sc = av_mallocz(sizeof(MOVStreamContext));
2530 if (!sc) return AVERROR(ENOMEM);
2533 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2534 sc->ffindex = st->index;
2536 if ((ret = mov_read_default(c, pb, atom)) < 0)
2540 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2541 (!sc->sample_size && !sc->sample_count))) {
2542 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2547 fix_timescale(c, sc);
2549 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2551 mov_build_index(c, st);
2553 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2554 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2555 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2556 c->use_absolute_path, c->fc) < 0)
2557 av_log(c->fc, AV_LOG_ERROR,
2558 "stream %d, error opening alias: path='%s', dir='%s', "
2559 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2560 st->index, dref->path, dref->dir, dref->filename,
2561 dref->volume, dref->nlvl_from, dref->nlvl_to);
2564 sc->pb_is_copied = 1;
2567 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2568 if (!st->sample_aspect_ratio.num &&
2569 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2570 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2571 ((double)st->codec->width * sc->height), INT_MAX);
2574 #if FF_API_R_FRAME_RATE
2575 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2576 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2577 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2581 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2582 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2583 TAG_IS_AVCI(st->codec->codec_tag)) {
2584 ret = ff_generate_avci_extradata(st);
2589 switch (st->codec->codec_id) {
2590 #if CONFIG_H261_DECODER
2591 case AV_CODEC_ID_H261:
2593 #if CONFIG_H263_DECODER
2594 case AV_CODEC_ID_H263:
2596 #if CONFIG_MPEG4_DECODER
2597 case AV_CODEC_ID_MPEG4:
2599 st->codec->width = 0; /* let decoder init width/height */
2600 st->codec->height= 0;
2604 /* Do not need those anymore. */
2605 av_freep(&sc->chunk_offsets);
2606 av_freep(&sc->stsc_data);
2607 av_freep(&sc->sample_sizes);
2608 av_freep(&sc->keyframes);
2609 av_freep(&sc->stts_data);
2610 av_freep(&sc->stps_data);
2611 av_freep(&sc->rap_group);
2616 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2619 c->itunes_metadata = 1;
2620 ret = mov_read_default(c, pb, atom);
2621 c->itunes_metadata = 0;
2625 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
2627 int64_t end = avio_tell(pb) + size;
2628 uint8_t *key = NULL, *val = NULL;
2631 MOVStreamContext *sc;
2633 if (c->fc->nb_streams < 1)
2635 st = c->fc->streams[c->fc->nb_streams-1];
2638 for (i = 0; i < 2; i++) {
2642 if (end - avio_tell(pb) <= 12)
2645 len = avio_rb32(pb);
2646 tag = avio_rl32(pb);
2647 avio_skip(pb, 4); // flags
2649 if (len < 12 || len - 12 > end - avio_tell(pb))
2653 if (tag == MKTAG('n', 'a', 'm', 'e'))
2655 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2662 *p = av_malloc(len + 1);
2665 avio_read(pb, *p, len);
2670 if (strcmp(key, "iTunSMPB") == 0) {
2671 int priming, remainder, samples;
2672 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
2673 if(priming>0 && priming<16384)
2674 sc->start_pad = priming;
2677 if (strcmp(key, "cdec") != 0) {
2678 av_dict_set(&c->fc->metadata, key, val,
2679 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2684 avio_seek(pb, end, SEEK_SET);
2690 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2692 int64_t end = avio_tell(pb) + atom.size;
2698 len = avio_rb32(pb);
2699 tag = avio_rl32(pb);
2701 if (len > atom.size)
2704 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2705 uint8_t domain[128];
2708 avio_skip(pb, 4); // flags
2711 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2712 avio_skip(pb, len - domain_len);
2713 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
2717 av_log(c->fc, AV_LOG_VERBOSE,
2718 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2722 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2724 while (atom.size > 8) {
2725 uint32_t tag = avio_rl32(pb);
2727 if (tag == MKTAG('h','d','l','r')) {
2728 avio_seek(pb, -8, SEEK_CUR);
2730 return mov_read_default(c, pb, atom);
2736 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2741 int64_t disp_transform[2];
2742 int display_matrix[3][3];
2744 MOVStreamContext *sc;
2748 if (c->fc->nb_streams < 1)
2750 st = c->fc->streams[c->fc->nb_streams-1];
2753 version = avio_r8(pb);
2754 flags = avio_rb24(pb);
2755 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2761 avio_rb32(pb); /* creation time */
2762 avio_rb32(pb); /* modification time */
2764 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2765 avio_rb32(pb); /* reserved */
2767 /* highlevel (considering edits) duration in movie timebase */
2768 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2769 avio_rb32(pb); /* reserved */
2770 avio_rb32(pb); /* reserved */
2772 avio_rb16(pb); /* layer */
2773 avio_rb16(pb); /* alternate group */
2774 avio_rb16(pb); /* volume */
2775 avio_rb16(pb); /* reserved */
2777 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2778 // they're kept in fixed point format through all calculations
2779 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2780 // side data, but the scale factor is not needed to calculate aspect ratio
2781 for (i = 0; i < 3; i++) {
2782 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2783 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2784 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2787 width = avio_rb32(pb); // 16.16 fixed point track width
2788 height = avio_rb32(pb); // 16.16 fixed point track height
2789 sc->width = width >> 16;
2790 sc->height = height >> 16;
2792 // save the matrix and add rotate metadata when it is not the default
2794 if (display_matrix[0][0] != (1 << 16) ||
2795 display_matrix[1][1] != (1 << 16) ||
2796 display_matrix[2][2] != (1 << 30) ||
2797 display_matrix[0][1] || display_matrix[0][2] ||
2798 display_matrix[1][0] || display_matrix[1][2] ||
2799 display_matrix[2][0] || display_matrix[2][1]) {
2803 av_freep(&sc->display_matrix);
2804 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2805 if (!sc->display_matrix)
2806 return AVERROR(ENOMEM);
2808 for (i = 0; i < 3; i++)
2809 for (j = 0; j < 3; j++)
2810 sc->display_matrix[i * 3 + j] = display_matrix[j][i];
2812 rotate = av_display_rotation_get(sc->display_matrix);
2813 if (!isnan(rotate)) {
2814 char rotate_buf[64];
2816 if (rotate < 0) // for backward compatibility
2818 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
2819 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
2823 // transform the display width/height according to the matrix
2824 // skip this if the display matrix is the default identity matrix
2825 // or if it is rotating the picture, ex iPhone 3GS
2826 // to keep the same scale, use [width height 1<<16]
2827 if (width && height &&
2828 ((display_matrix[0][0] != 65536 ||
2829 display_matrix[1][1] != 65536) &&
2830 !display_matrix[0][1] &&
2831 !display_matrix[1][0] &&
2832 !display_matrix[2][0] && !display_matrix[2][1])) {
2833 for (i = 0; i < 2; i++)
2835 (int64_t) width * display_matrix[0][i] +
2836 (int64_t) height * display_matrix[1][i] +
2837 ((int64_t) display_matrix[2][i] << 16);
2839 //sample aspect ratio is new width/height divided by old width/height
2840 st->sample_aspect_ratio = av_d2q(
2841 ((double) disp_transform[0] * height) /
2842 ((double) disp_transform[1] * width), INT_MAX);
2847 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2849 MOVFragment *frag = &c->fragment;
2850 MOVTrackExt *trex = NULL;
2851 MOVFragmentIndex* index = NULL;
2852 int flags, track_id, i;
2854 avio_r8(pb); /* version */
2855 flags = avio_rb24(pb);
2857 track_id = avio_rb32(pb);
2859 return AVERROR_INVALIDDATA;
2860 frag->track_id = track_id;
2861 for (i = 0; i < c->trex_count; i++)
2862 if (c->trex_data[i].track_id == frag->track_id) {
2863 trex = &c->trex_data[i];
2867 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2868 return AVERROR_INVALIDDATA;
2870 for (i = 0; i < c->fragment_index_count; i++) {
2871 MOVFragmentIndex* candidate = c->fragment_index_data[i];
2872 if (candidate->track_id == frag->track_id) {
2873 av_log(c->fc, AV_LOG_DEBUG,
2874 "found fragment index for track %u\n", frag->track_id);
2880 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2881 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
2882 frag->moof_offset : frag->implicit_offset;
2883 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2885 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2886 avio_rb32(pb) : trex->duration;
2887 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2888 avio_rb32(pb) : trex->size;
2889 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2890 avio_rb32(pb) : trex->flags;
2891 frag->time = AV_NOPTS_VALUE;
2894 for (i = index->current_item; i < index->item_count; i++) {
2895 if (frag->implicit_offset == index->items[i].moof_offset) {
2896 av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
2897 "for track %u and moof_offset %"PRId64"\n",
2898 frag->track_id, index->items[i].moof_offset);
2899 frag->time = index->items[i].time;
2900 index->current_item = i + 1;
2905 av_log(c->fc, AV_LOG_WARNING, "track %u has a fragment index "
2906 "but it doesn't have an (in-order) entry for moof_offset "
2907 "%"PRId64"\n", frag->track_id, frag->implicit_offset);
2910 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2914 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2916 c->chapter_track = avio_rb32(pb);
2920 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2925 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2926 return AVERROR_INVALIDDATA;
2927 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2928 sizeof(*c->trex_data))) < 0) {
2933 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2935 trex = &c->trex_data[c->trex_count++];
2936 avio_r8(pb); /* version */
2937 avio_rb24(pb); /* flags */
2938 trex->track_id = avio_rb32(pb);
2939 trex->stsd_id = avio_rb32(pb);
2940 trex->duration = avio_rb32(pb);
2941 trex->size = avio_rb32(pb);
2942 trex->flags = avio_rb32(pb);
2946 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2948 MOVFragment *frag = &c->fragment;
2949 AVStream *st = NULL;
2950 MOVStreamContext *sc;
2953 for (i = 0; i < c->fc->nb_streams; i++) {
2954 if (c->fc->streams[i]->id == frag->track_id) {
2955 st = c->fc->streams[i];
2960 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2961 return AVERROR_INVALIDDATA;
2964 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
2966 version = avio_r8(pb);
2967 avio_rb24(pb); /* flags */
2969 sc->track_end = avio_rb64(pb);
2971 sc->track_end = avio_rb32(pb);
2976 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2978 MOVFragment *frag = &c->fragment;
2979 AVStream *st = NULL;
2980 MOVStreamContext *sc;
2984 int data_offset = 0;
2985 unsigned entries, first_sample_flags = frag->flags;
2986 int flags, distance, i, found_keyframe = 0, err;
2988 for (i = 0; i < c->fc->nb_streams; i++) {
2989 if (c->fc->streams[i]->id == frag->track_id) {
2990 st = c->fc->streams[i];
2995 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2996 return AVERROR_INVALIDDATA;
2999 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3001 avio_r8(pb); /* version */
3002 flags = avio_rb24(pb);
3003 entries = avio_rb32(pb);
3004 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
3006 /* Always assume the presence of composition time offsets.
3007 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3008 * 1) in the initial movie, there are no samples.
3009 * 2) in the first movie fragment, there is only one sample without composition time offset.
3010 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
3011 if (!sc->ctts_count && sc->sample_count)
3013 /* Complement ctts table if moov atom doesn't have ctts atom. */
3014 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3016 return AVERROR(ENOMEM);
3017 sc->ctts_data = ctts_data;
3018 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3019 sc->ctts_data[sc->ctts_count].duration = 0;
3022 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3023 return AVERROR_INVALIDDATA;
3024 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3025 sizeof(*sc->ctts_data))) < 0) {
3029 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
3030 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3031 dts = sc->track_end - sc->time_offset;
3032 offset = frag->base_data_offset + data_offset;
3034 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
3035 for (i = 0; i < entries && !pb->eof_reached; i++) {
3036 unsigned sample_size = frag->size;
3037 int sample_flags = i ? frag->flags : first_sample_flags;
3038 unsigned sample_duration = frag->duration;
3041 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3042 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
3043 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
3044 sc->ctts_data[sc->ctts_count].count = 1;
3045 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3047 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
3048 if (frag->time != AV_NOPTS_VALUE) {
3049 if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3050 int64_t pts = frag->time;
3051 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3052 " sc->dts_shift %d ctts.duration %d"
3053 " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3054 sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3055 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3056 dts = pts - sc->dts_shift;
3057 if (flags & MOV_TRUN_SAMPLE_CTS) {
3058 dts -= sc->ctts_data[sc->ctts_count].duration;
3060 dts -= sc->time_offset;
3062 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3065 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3066 ", using it for dts\n", dts);
3068 frag->time = AV_NOPTS_VALUE;
3071 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3073 else if (!found_keyframe)
3074 keyframe = found_keyframe =
3075 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3076 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3079 av_add_index_entry(st, offset, dts, sample_size, distance,
3080 keyframe ? AVINDEX_KEYFRAME : 0);
3081 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3082 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3083 offset, dts, sample_size, distance, keyframe);
3085 dts += sample_duration;
3086 offset += sample_size;
3087 sc->data_size += sample_size;
3088 sc->duration_for_fps += sample_duration;
3089 sc->nb_frames_for_fps ++;
3092 if (pb->eof_reached)
3095 frag->implicit_offset = offset;
3096 st->duration = sc->track_end = dts + sc->time_offset;
3100 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3101 /* like the files created with Adobe Premiere 5.0, for samples see */
3102 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3103 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3108 return 0; /* continue */
3109 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3110 avio_skip(pb, atom.size - 4);
3113 atom.type = avio_rl32(pb);
3115 if (atom.type != MKTAG('m','d','a','t')) {
3116 avio_skip(pb, atom.size);
3119 err = mov_read_mdat(c, pb, atom);
3123 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3128 uint8_t *moov_data; /* uncompressed data */
3129 long cmov_len, moov_len;
3132 avio_rb32(pb); /* dcom atom */
3133 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3134 return AVERROR_INVALIDDATA;
3135 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3136 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3137 return AVERROR_INVALIDDATA;
3139 avio_rb32(pb); /* cmvd atom */
3140 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3141 return AVERROR_INVALIDDATA;
3142 moov_len = avio_rb32(pb); /* uncompressed size */
3143 cmov_len = atom.size - 6 * 4;
3145 cmov_data = av_malloc(cmov_len);
3147 return AVERROR(ENOMEM);
3148 moov_data = av_malloc(moov_len);
3151 return AVERROR(ENOMEM);
3153 avio_read(pb, cmov_data, cmov_len);
3154 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3155 goto free_and_return;
3156 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3157 goto free_and_return;
3158 atom.type = MKTAG('m','o','o','v');
3159 atom.size = moov_len;
3160 ret = mov_read_default(c, &ctx, atom);
3166 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3167 return AVERROR(ENOSYS);
3171 /* edit list atom */
3172 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3174 MOVStreamContext *sc;
3175 int i, edit_count, version, edit_start_index = 0;
3176 int unsupported = 0;
3178 if (c->fc->nb_streams < 1 || c->ignore_editlist)
3180 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3182 version = avio_r8(pb); /* version */
3183 avio_rb24(pb); /* flags */
3184 edit_count = avio_rb32(pb); /* entries */
3186 if ((uint64_t)edit_count*12+8 > atom.size)
3187 return AVERROR_INVALIDDATA;
3189 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3190 for (i=0; i<edit_count; i++){
3195 duration = avio_rb64(pb);
3196 time = avio_rb64(pb);
3198 duration = avio_rb32(pb); /* segment duration */
3199 time = (int32_t)avio_rb32(pb); /* media time */
3201 rate = avio_rb32(pb);
3202 if (i == 0 && time == -1) {
3203 sc->empty_duration = duration;
3204 edit_start_index = 1;
3205 } else if (i == edit_start_index && time >= 0)
3206 sc->start_time = time;
3210 av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3211 duration, time, rate / 65536.0);
3215 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
3216 "a/v desync might occur, patch welcome\n");
3221 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3223 MOVStreamContext *sc;
3225 if (c->fc->nb_streams < 1)
3226 return AVERROR_INVALIDDATA;
3227 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3228 sc->timecode_track = avio_rb32(pb);
3232 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3236 static const uint8_t uuid_isml_manifest[] = {
3237 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3238 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3241 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3242 return AVERROR_INVALIDDATA;
3244 ret = avio_read(pb, uuid, sizeof(uuid));
3247 } else if (ret != sizeof(uuid)) {
3248 return AVERROR_INVALIDDATA;
3250 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3251 uint8_t *buffer, *ptr;
3253 size_t len = atom.size - sizeof(uuid);
3256 return AVERROR_INVALIDDATA;
3258 ret = avio_skip(pb, 4); // zeroes
3261 buffer = av_mallocz(len + 1);
3263 return AVERROR(ENOMEM);
3265 ret = avio_read(pb, buffer, len);
3269 } else if (ret != len) {
3271 return AVERROR_INVALIDDATA;
3275 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
3276 ptr += sizeof("systemBitrate=\"") - 1;
3277 c->bitrates_count++;
3278 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3280 c->bitrates_count = 0;
3282 return AVERROR(ENOMEM);
3285 ret = strtol(ptr, &endptr, 10);
3286 if (ret < 0 || errno || *endptr != '"') {
3287 c->bitrates[c->bitrates_count - 1] = 0;
3289 c->bitrates[c->bitrates_count - 1] = ret;
3298 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3301 uint8_t content[16];
3306 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
3312 && !memcmp(content, "Anevia\x1A\x1A", 8)
3313 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
3314 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
3320 static const MOVParseTableEntry mov_default_parse_table[] = {
3321 { MKTAG('A','C','L','R'), mov_read_avid },
3322 { MKTAG('A','P','R','G'), mov_read_avid },
3323 { MKTAG('A','A','L','P'), mov_read_avid },
3324 { MKTAG('A','R','E','S'), mov_read_ares },
3325 { MKTAG('a','v','s','s'), mov_read_avss },
3326 { MKTAG('c','h','p','l'), mov_read_chpl },
3327 { MKTAG('c','o','6','4'), mov_read_stco },
3328 { MKTAG('c','o','l','r'), mov_read_colr },
3329 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3330 { MKTAG('d','i','n','f'), mov_read_default },
3331 { MKTAG('d','r','e','f'), mov_read_dref },
3332 { MKTAG('e','d','t','s'), mov_read_default },
3333 { MKTAG('e','l','s','t'), mov_read_elst },
3334 { MKTAG('e','n','d','a'), mov_read_enda },
3335 { MKTAG('f','i','e','l'), mov_read_fiel },
3336 { MKTAG('f','t','y','p'), mov_read_ftyp },
3337 { MKTAG('g','l','b','l'), mov_read_glbl },
3338 { MKTAG('h','d','l','r'), mov_read_hdlr },
3339 { MKTAG('i','l','s','t'), mov_read_ilst },
3340 { MKTAG('j','p','2','h'), mov_read_jp2h },
3341 { MKTAG('m','d','a','t'), mov_read_mdat },
3342 { MKTAG('m','d','h','d'), mov_read_mdhd },
3343 { MKTAG('m','d','i','a'), mov_read_default },
3344 { MKTAG('m','e','t','a'), mov_read_meta },
3345 { MKTAG('m','i','n','f'), mov_read_default },
3346 { MKTAG('m','o','o','f'), mov_read_moof },
3347 { MKTAG('m','o','o','v'), mov_read_moov },
3348 { MKTAG('m','v','e','x'), mov_read_default },
3349 { MKTAG('m','v','h','d'), mov_read_mvhd },
3350 { MKTAG('S','M','I',' '), mov_read_svq3 },
3351 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
3352 { MKTAG('a','v','c','C'), mov_read_glbl },
3353 { MKTAG('p','a','s','p'), mov_read_pasp },
3354 { MKTAG('s','t','b','l'), mov_read_default },
3355 { MKTAG('s','t','c','o'), mov_read_stco },
3356 { MKTAG('s','t','p','s'), mov_read_stps },
3357 { MKTAG('s','t','r','f'), mov_read_strf },
3358 { MKTAG('s','t','s','c'), mov_read_stsc },
3359 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3360 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3361 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3362 { MKTAG('s','t','t','s'), mov_read_stts },
3363 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3364 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3365 { MKTAG('t','f','d','t'), mov_read_tfdt },
3366 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3367 { MKTAG('t','r','a','k'), mov_read_trak },
3368 { MKTAG('t','r','a','f'), mov_read_default },
3369 { MKTAG('t','r','e','f'), mov_read_default },
3370 { MKTAG('t','m','c','d'), mov_read_tmcd },
3371 { MKTAG('c','h','a','p'), mov_read_chap },
3372 { MKTAG('t','r','e','x'), mov_read_trex },
3373 { MKTAG('t','r','u','n'), mov_read_trun },
3374 { MKTAG('u','d','t','a'), mov_read_default },
3375 { MKTAG('w','a','v','e'), mov_read_wave },
3376 { MKTAG('e','s','d','s'), mov_read_esds },
3377 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3378 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3379 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3380 { MKTAG('w','f','e','x'), mov_read_wfex },
3381 { MKTAG('c','m','o','v'), mov_read_cmov },
3382 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3383 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3384 { MKTAG('s','b','g','p'), mov_read_sbgp },
3385 { MKTAG('h','v','c','C'), mov_read_glbl },
3386 { MKTAG('u','u','i','d'), mov_read_uuid },
3387 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
3388 { MKTAG('f','r','e','e'), mov_read_free },
3389 { MKTAG('-','-','-','-'), mov_read_custom },
3393 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3395 int64_t total_size = 0;
3400 atom.size = INT64_MAX;
3401 while (total_size + 8 <= atom.size && !avio_feof(pb)) {
3402 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3405 if (atom.size >= 8) {
3406 a.size = avio_rb32(pb);
3407 a.type = avio_rl32(pb);
3408 if (a.type == MKTAG('f','r','e','e') &&
3412 uint32_t *type = (uint32_t *)buf + 1;
3413 avio_read(pb, buf, 8);
3414 avio_seek(pb, -8, SEEK_CUR);
3415 if (*type == MKTAG('m','v','h','d') ||
3416 *type == MKTAG('c','m','o','v')) {
3417 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
3418 a.type = MKTAG('m','o','o','v');
3421 if (atom.type != MKTAG('r','o','o','t') &&
3422 atom.type != MKTAG('m','o','o','v'))
3424 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
3426 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
3432 if (a.size == 1) { /* 64 bit extended size */
3433 a.size = avio_rb64(pb) - 8;
3437 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3438 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3440 a.size = atom.size - total_size + 8;
3445 a.size = FFMIN(a.size, atom.size - total_size);
3447 for (i = 0; mov_default_parse_table[i].type; i++)
3448 if (mov_default_parse_table[i].type == a.type) {
3449 parse = mov_default_parse_table[i].parse;
3453 // container is user data
3454 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3455 atom.type == MKTAG('i','l','s','t')))
3456 parse = mov_read_udta_string;
3458 if (!parse) { /* skip leaf atoms data */
3459 avio_skip(pb, a.size);
3461 int64_t start_pos = avio_tell(pb);
3463 int err = parse(c, pb, a);
3466 if (c->found_moov && c->found_mdat &&
3467 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3468 start_pos + a.size == avio_size(pb))) {
3469 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3470 c->next_root_atom = start_pos + a.size;
3473 left = a.size - avio_tell(pb) + start_pos;
3474 if (left > 0) /* skip garbage at atom end */
3475 avio_skip(pb, left);
3476 else if (left < 0) {
3477 av_log(c->fc, AV_LOG_WARNING,
3478 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3479 (char*)&a.type, -left);
3480 avio_seek(pb, left, SEEK_CUR);
3484 total_size += a.size;
3487 if (total_size < atom.size && atom.size < 0x7ffff)
3488 avio_skip(pb, atom.size - total_size);
3493 static int mov_probe(AVProbeData *p)
3498 int moov_offset = -1;
3500 /* check file header */
3503 /* ignore invalid offset */
3504 if ((offset + 8) > (unsigned int)p->buf_size)
3506 tag = AV_RL32(p->buf + offset + 4);
3508 /* check for obvious tags */
3509 case MKTAG('m','o','o','v'):
3510 moov_offset = offset + 4;
3511 case MKTAG('m','d','a','t'):
3512 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3513 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3514 case MKTAG('f','t','y','p'):
3515 if (AV_RB32(p->buf+offset) < 8 &&
3516 (AV_RB32(p->buf+offset) != 1 ||
3517 offset + 12 > (unsigned int)p->buf_size ||
3518 AV_RB64(p->buf+offset + 8) == 0)) {
3519 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3520 } else if (tag == MKTAG('f','t','y','p') &&
3521 AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')) {
3522 score = FFMAX(score, 5);
3524 score = AVPROBE_SCORE_MAX;
3526 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3528 /* those are more common words, so rate then a bit less */
3529 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3530 case MKTAG('w','i','d','e'):
3531 case MKTAG('f','r','e','e'):
3532 case MKTAG('j','u','n','k'):
3533 case MKTAG('p','i','c','t'):
3534 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
3535 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3537 case MKTAG(0x82,0x82,0x7f,0x7d):
3538 case MKTAG('s','k','i','p'):
3539 case MKTAG('u','u','i','d'):
3540 case MKTAG('p','r','f','l'):
3541 /* if we only find those cause probedata is too small at least rate them */
3542 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3543 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3546 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3549 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
3550 /* moov atom in the header - we should make sure that this is not a
3551 * MOV-packed MPEG-PS */
3552 offset = moov_offset;
3554 while(offset < (p->buf_size - 16)){ /* Sufficient space */
3555 /* We found an actual hdlr atom */
3556 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
3557 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
3558 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
3559 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
3560 /* We found a media handler reference atom describing an
3561 * MPEG-PS-in-MOV, return a
3562 * low score to force expanding the probe window until
3563 * mpegps_probe finds what it needs */
3574 // must be done after parsing all trak because there's no order requirement
3575 static void mov_read_chapters(AVFormatContext *s)
3577 MOVContext *mov = s->priv_data;
3578 AVStream *st = NULL;
3579 MOVStreamContext *sc;
3583 for (i = 0; i < s->nb_streams; i++)
3584 if (s->streams[i]->id == mov->chapter_track) {
3589 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3593 st->discard = AVDISCARD_ALL;
3595 cur_pos = avio_tell(sc->pb);
3597 for (i = 0; i < st->nb_index_entries; i++) {
3598 AVIndexEntry *sample = &st->index_entries[i];
3599 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3604 if (end < sample->timestamp) {
3605 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
3606 end = AV_NOPTS_VALUE;
3609 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3610 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3614 // the first two bytes are the length of the title
3615 len = avio_rb16(sc->pb);
3616 if (len > sample->size-2)
3618 title_len = 2*len + 1;
3619 if (!(title = av_mallocz(title_len)))
3622 // The samples could theoretically be in any encoding if there's an encd
3623 // atom following, but in practice are only utf-8 or utf-16, distinguished
3624 // instead by the presence of a BOM
3628 ch = avio_rb16(sc->pb);
3630 avio_get_str16be(sc->pb, len, title, title_len);
3631 else if (ch == 0xfffe)
3632 avio_get_str16le(sc->pb, len, title, title_len);
3635 if (len == 1 || len == 2)
3638 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3642 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3646 avio_seek(sc->pb, cur_pos, SEEK_SET);
3649 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
3650 uint32_t value, int flags)
3653 char buf[AV_TIMECODE_STR_SIZE];
3654 AVRational rate = {st->codec->time_base.den,
3655 st->codec->time_base.num};
3656 int ret = av_timecode_init(&tc, rate, flags, 0, s);
3659 av_dict_set(&st->metadata, "timecode",
3660 av_timecode_make_string(&tc, buf, value), 0);
3664 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
3666 MOVStreamContext *sc = st->priv_data;
3668 int64_t cur_pos = avio_tell(sc->pb);
3671 if (!st->nb_index_entries)
3674 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3675 value = avio_rb32(s->pb);
3677 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3678 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3679 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3681 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3682 * not the case) and thus assume "frame number format" instead of QT one.
3683 * No sample with tmcd track can be found with a QT timecode at the moment,
3684 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3686 parse_timecode_in_framenum_format(s, st, value, flags);
3688 avio_seek(sc->pb, cur_pos, SEEK_SET);
3692 static int mov_read_close(AVFormatContext *s)
3694 MOVContext *mov = s->priv_data;
3697 for (i = 0; i < s->nb_streams; i++) {
3698 AVStream *st = s->streams[i];
3699 MOVStreamContext *sc = st->priv_data;
3701 av_freep(&sc->ctts_data);
3702 for (j = 0; j < sc->drefs_count; j++) {
3703 av_freep(&sc->drefs[j].path);
3704 av_freep(&sc->drefs[j].dir);
3706 av_freep(&sc->drefs);
3708 sc->drefs_count = 0;
3710 if (!sc->pb_is_copied)
3714 av_freep(&sc->chunk_offsets);
3715 av_freep(&sc->stsc_data);
3716 av_freep(&sc->sample_sizes);
3717 av_freep(&sc->keyframes);
3718 av_freep(&sc->stts_data);
3719 av_freep(&sc->stps_data);
3720 av_freep(&sc->rap_group);
3721 av_freep(&sc->display_matrix);
3724 if (mov->dv_demux) {
3725 avformat_free_context(mov->dv_fctx);
3726 mov->dv_fctx = NULL;
3729 av_freep(&mov->trex_data);
3730 av_freep(&mov->bitrates);
3732 for (i = 0; i < mov->fragment_index_count; i++) {
3733 MOVFragmentIndex* index = mov->fragment_index_data[i];
3734 av_freep(&index->items);
3735 av_freep(&mov->fragment_index_data[i]);
3737 av_freep(&mov->fragment_index_data);
3742 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3746 for (i = 0; i < s->nb_streams; i++) {
3747 AVStream *st = s->streams[i];
3748 MOVStreamContext *sc = st->priv_data;
3750 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3751 sc->timecode_track == tmcd_id)
3757 /* look for a tmcd track not referenced by any video track, and export it globally */
3758 static void export_orphan_timecode(AVFormatContext *s)
3762 for (i = 0; i < s->nb_streams; i++) {
3763 AVStream *st = s->streams[i];
3765 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3766 !tmcd_is_referenced(s, i + 1)) {
3767 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3769 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3776 static int read_tfra(MOVContext *mov, AVIOContext *f)
3778 MOVFragmentIndex* index = NULL;
3779 int version, fieldlength, i, j, err;
3780 int64_t pos = avio_tell(f);
3781 uint32_t size = avio_rb32(f);
3782 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
3785 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
3786 index = av_mallocz(sizeof(MOVFragmentIndex));
3788 return AVERROR(ENOMEM);
3790 mov->fragment_index_count++;
3791 if ((err = av_reallocp(&mov->fragment_index_data,
3792 mov->fragment_index_count *
3793 sizeof(MOVFragmentIndex*))) < 0) {
3797 mov->fragment_index_data[mov->fragment_index_count - 1] =
3800 version = avio_r8(f);
3802 index->track_id = avio_rb32(f);
3803 fieldlength = avio_rb32(f);
3804 index->item_count = avio_rb32(f);
3805 index->items = av_mallocz(
3806 index->item_count * sizeof(MOVFragmentIndexItem));
3807 if (!index->items) {
3808 return AVERROR(ENOMEM);
3810 for (i = 0; i < index->item_count; i++) {
3811 int64_t time, offset;
3813 time = avio_rb64(f);
3814 offset = avio_rb64(f);
3816 time = avio_rb32(f);
3817 offset = avio_rb32(f);
3819 index->items[i].time = time;
3820 index->items[i].moof_offset = offset;
3821 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
3823 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
3825 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
3829 avio_seek(f, pos + size, SEEK_SET);
3833 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
3835 int64_t stream_size = avio_size(f);
3836 int64_t original_pos = avio_tell(f);
3840 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
3844 mfra_size = avio_rb32(f);
3845 if (mfra_size < 0 || mfra_size > stream_size) {
3846 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
3849 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
3853 if (avio_rb32(f) != mfra_size) {
3854 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
3857 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
3858 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
3862 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
3863 while (!read_tfra(c, f)) {
3867 seek_ret = avio_seek(f, original_pos, SEEK_SET);
3869 av_log(c->fc, AV_LOG_ERROR,
3870 "failed to seek back after looking for mfra\n");
3876 static int mov_read_header(AVFormatContext *s)
3878 MOVContext *mov = s->priv_data;
3879 AVIOContext *pb = s->pb;
3881 MOVAtom atom = { AV_RL32("root") };
3885 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3887 atom.size = avio_size(pb);
3889 atom.size = INT64_MAX;
3891 /* check MOV header */
3893 if (mov->moov_retry)
3894 avio_seek(pb, 0, SEEK_SET);
3895 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3896 av_log(s, AV_LOG_ERROR, "error reading header\n");
3900 } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
3901 if (!mov->found_moov) {
3902 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3904 return AVERROR_INVALIDDATA;
3906 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3909 if (mov->chapter_track > 0)
3910 mov_read_chapters(s);
3911 for (i = 0; i < s->nb_streams; i++)
3912 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3913 mov_read_timecode_track(s, s->streams[i]);
3916 /* copy timecode metadata from tmcd tracks to the related video streams */
3917 for (i = 0; i < s->nb_streams; i++) {
3918 AVStream *st = s->streams[i];
3919 MOVStreamContext *sc = st->priv_data;
3920 if (sc->timecode_track > 0) {
3921 AVDictionaryEntry *tcr;
3922 int tmcd_st_id = -1;
3924 for (j = 0; j < s->nb_streams; j++)
3925 if (s->streams[j]->id == sc->timecode_track)
3928 if (tmcd_st_id < 0 || tmcd_st_id == i)
3930 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
3932 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
3935 export_orphan_timecode(s);
3937 for (i = 0; i < s->nb_streams; i++) {
3938 AVStream *st = s->streams[i];
3939 MOVStreamContext *sc = st->priv_data;
3940 fix_timescale(mov, sc);
3941 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
3942 st->skip_samples = sc->start_pad;
3944 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
3945 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3946 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
3947 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3948 if (st->codec->width <= 0 || st->codec->height <= 0) {
3949 st->codec->width = sc->width;
3950 st->codec->height = sc->height;
3952 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3953 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3959 if (mov->trex_data) {
3960 for (i = 0; i < s->nb_streams; i++) {
3961 AVStream *st = s->streams[i];
3962 MOVStreamContext *sc = st->priv_data;
3963 if (st->duration > 0)
3964 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3968 if (mov->use_mfra_for > 0) {
3969 for (i = 0; i < s->nb_streams; i++) {
3970 AVStream *st = s->streams[i];
3971 MOVStreamContext *sc = st->priv_data;
3972 if (sc->duration_for_fps > 0) {
3973 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
3974 sc->duration_for_fps;
3979 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
3980 if (mov->bitrates[i]) {
3981 s->streams[i]->codec->bit_rate = mov->bitrates[i];
3985 ff_rfps_calculate(s);
3987 for (i = 0; i < s->nb_streams; i++) {
3988 AVStream *st = s->streams[i];
3989 MOVStreamContext *sc = st->priv_data;
3991 switch (st->codec->codec_type) {
3992 case AVMEDIA_TYPE_AUDIO:
3993 err = ff_replaygain_export(st, s->metadata);
3999 case AVMEDIA_TYPE_VIDEO:
4000 if (sc->display_matrix) {
4001 AVPacketSideData *sd, *tmp;
4003 tmp = av_realloc_array(st->side_data,
4004 st->nb_side_data + 1, sizeof(*tmp));
4006 return AVERROR(ENOMEM);
4008 st->side_data = tmp;
4011 sd = &st->side_data[st->nb_side_data - 1];
4012 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
4013 sd->size = sizeof(int32_t) * 9;
4014 sd->data = (uint8_t*)sc->display_matrix;
4015 sc->display_matrix = NULL;
4024 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
4026 AVIndexEntry *sample = NULL;
4027 int64_t best_dts = INT64_MAX;
4029 for (i = 0; i < s->nb_streams; i++) {
4030 AVStream *avst = s->streams[i];
4031 MOVStreamContext *msc = avst->priv_data;
4032 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
4033 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
4034 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
4035 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
4036 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
4038 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
4039 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
4040 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
4041 sample = current_sample;
4050 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
4052 MOVContext *mov = s->priv_data;
4053 MOVStreamContext *sc;
4054 AVIndexEntry *sample;
4055 AVStream *st = NULL;
4059 sample = mov_find_next_sample(s, &st);
4061 mov->found_mdat = 0;
4062 if (!mov->next_root_atom)
4064 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
4065 mov->next_root_atom = 0;
4066 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
4069 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
4073 /* must be done just before reading, to avoid infinite loop on sample */
4074 sc->current_sample++;
4076 if (mov->next_root_atom) {
4077 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
4078 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
4081 if (st->discard != AVDISCARD_ALL) {
4082 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4083 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
4084 sc->ffindex, sample->pos);
4085 return AVERROR_INVALIDDATA;
4087 ret = av_get_packet(sc->pb, pkt, sample->size);
4090 if (sc->has_palette) {
4093 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
4095 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
4097 memcpy(pal, sc->palette, AVPALETTE_SIZE);
4098 sc->has_palette = 0;
4101 #if CONFIG_DV_DEMUXER
4102 if (mov->dv_demux && sc->dv_audio_container) {
4103 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
4106 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
4113 pkt->stream_index = sc->ffindex;
4114 pkt->dts = sample->timestamp;
4115 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
4116 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
4117 /* update ctts context */
4119 if (sc->ctts_index < sc->ctts_count &&
4120 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
4122 sc->ctts_sample = 0;
4125 pkt->dts = AV_NOPTS_VALUE;
4127 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
4128 st->index_entries[sc->current_sample].timestamp : st->duration;
4129 pkt->duration = next_dts - pkt->dts;
4130 pkt->pts = pkt->dts;
4132 if (st->discard == AVDISCARD_ALL)
4134 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
4135 pkt->pos = sample->pos;
4136 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
4137 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
4141 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
4143 MOVStreamContext *sc = st->priv_data;
4144 int sample, time_sample;
4147 sample = av_index_search_timestamp(st, timestamp, flags);
4148 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
4149 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
4151 if (sample < 0) /* not sure what to do */
4152 return AVERROR_INVALIDDATA;
4153 sc->current_sample = sample;
4154 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
4155 /* adjust ctts index */
4156 if (sc->ctts_data) {
4158 for (i = 0; i < sc->ctts_count; i++) {
4159 int next = time_sample + sc->ctts_data[i].count;
4160 if (next > sc->current_sample) {
4162 sc->ctts_sample = sc->current_sample - time_sample;
4171 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
4174 int64_t seek_timestamp, timestamp;
4178 if (stream_index >= s->nb_streams)
4179 return AVERROR_INVALIDDATA;
4181 st = s->streams[stream_index];
4182 sample = mov_seek_stream(s, st, sample_time, flags);
4186 /* adjust seek timestamp to found sample timestamp */
4187 seek_timestamp = st->index_entries[sample].timestamp;
4189 for (i = 0; i < s->nb_streams; i++) {
4190 MOVStreamContext *sc = s->streams[i]->priv_data;
4192 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
4194 if (stream_index == i)
4197 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
4198 mov_seek_stream(s, st, timestamp, flags);
4203 #define OFFSET(x) offsetof(MOVContext, x)
4204 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
4205 static const AVOption mov_options[] = {
4206 {"use_absolute_path",
4207 "allow using absolute path when opening alias, this is a possible security issue",
4208 offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
4209 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
4210 {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
4211 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
4213 "use mfra for fragment timestamps",
4214 offsetof(MOVContext, use_mfra_for), FF_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
4215 -1, FF_MOV_FLAG_MFRA_PTS, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM,
4217 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
4218 AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM, "use_mfra_for" },
4219 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
4220 AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM, "use_mfra_for" },
4221 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
4222 AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM, "use_mfra_for" },
4223 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
4224 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
4225 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
4226 AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, .flags = FLAGS },
4230 static const AVClass mov_class = {
4231 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
4232 .item_name = av_default_item_name,
4233 .option = mov_options,
4234 .version = LIBAVUTIL_VERSION_INT,
4237 AVInputFormat ff_mov_demuxer = {
4238 .name = "mov,mp4,m4a,3gp,3g2,mj2",
4239 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
4240 .priv_class = &mov_class,
4241 .priv_data_size = sizeof(MOVContext),
4242 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
4243 .read_probe = mov_probe,
4244 .read_header = mov_read_header,
4245 .read_packet = mov_read_packet,
4246 .read_close = mov_read_close,
4247 .read_seek = mov_read_seek,
4248 .flags = AVFMT_NO_BYTE_SEEK,