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/intreadwrite.h"
33 #include "libavutil/intfloat.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/time_internal.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/dict.h"
38 #include "libavutil/display.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"
58 /* those functions parse an atom */
59 /* links atom IDs to parse functions */
60 typedef struct MOVParseTableEntry {
62 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
65 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
66 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
68 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
69 unsigned len, const char *key)
73 short current, total = 0;
74 avio_rb16(pb); // unknown
75 current = avio_rb16(pb);
77 total = avio_rb16(pb);
79 snprintf(buf, sizeof(buf), "%d", current);
81 snprintf(buf, sizeof(buf), "%d/%d", current, total);
82 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
83 av_dict_set(&c->fc->metadata, key, buf, 0);
88 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
89 unsigned len, const char *key)
91 /* bypass padding bytes */
96 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
97 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
102 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
103 unsigned len, const char *key)
105 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
106 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
111 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
112 unsigned len, const char *key)
116 avio_r8(pb); // unknown
119 if (genre < 1 || genre > ID3v1_GENRE_MAX)
121 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
122 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
127 static const uint32_t mac_to_unicode[128] = {
128 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
129 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
130 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
131 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
132 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
133 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
134 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
135 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
136 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
137 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
138 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
139 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
140 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
141 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
142 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
143 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
146 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
147 char *dst, int dstlen)
150 char *end = dst+dstlen-1;
153 for (i = 0; i < len; i++) {
154 uint8_t t, c = avio_r8(pb);
155 if (c < 0x80 && p < end)
158 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
164 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
168 MOVStreamContext *sc;
173 case 0xd: id = AV_CODEC_ID_MJPEG; break;
174 case 0xe: id = AV_CODEC_ID_PNG; break;
175 case 0x1b: id = AV_CODEC_ID_BMP; break;
177 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
182 st = avformat_new_stream(c->fc, NULL);
184 return AVERROR(ENOMEM);
185 sc = av_mallocz(sizeof(*sc));
187 return AVERROR(ENOMEM);
190 ret = av_get_packet(pb, &pkt, len);
194 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
196 st->attached_pic = pkt;
197 st->attached_pic.stream_index = st->index;
198 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
200 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
201 st->codec->codec_id = id;
206 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
208 char language[4] = { 0 };
210 uint16_t langcode = 0;
211 double longitude, latitude;
212 const char *key = "location";
214 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
215 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
216 return AVERROR_INVALIDDATA;
219 avio_skip(pb, 4); // version+flags
220 langcode = avio_rb16(pb);
221 ff_mov_lang_to_iso639(langcode, language);
224 len -= avio_get_str(pb, len, buf, sizeof(buf)); // place name
226 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
227 return AVERROR_INVALIDDATA;
229 avio_skip(pb, 1); // role
233 av_log(c->fc, AV_LOG_ERROR, "no space for coordinates left (%d)\n", len);
234 return AVERROR_INVALIDDATA;
236 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
237 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
239 // Try to output in the same format as the ?xyz field
240 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f/", latitude, longitude);
241 if (*language && strcmp(language, "und")) {
243 snprintf(key2, sizeof(key2), "%s-%s", key, language);
244 av_dict_set(&c->fc->metadata, key2, buf, 0);
246 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
247 return av_dict_set(&c->fc->metadata, key, buf, 0);
250 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
253 char key2[32], language[4] = {0};
255 const char *key = NULL;
256 uint16_t langcode = 0;
257 uint32_t data_type = 0, str_size, str_size_alloc;
258 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
262 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
263 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
264 case MKTAG( 'X','M','P','_'):
265 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
266 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
267 case MKTAG( 'a','k','I','D'): key = "account_type";
268 parse = mov_metadata_int8_no_padding; break;
269 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
270 case MKTAG( 'c','a','t','g'): key = "category"; break;
271 case MKTAG( 'c','p','i','l'): key = "compilation";
272 parse = mov_metadata_int8_no_padding; break;
273 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
274 case MKTAG( 'd','e','s','c'): key = "description"; break;
275 case MKTAG( 'd','i','s','k'): key = "disc";
276 parse = mov_metadata_track_or_disc_number; break;
277 case MKTAG( 'e','g','i','d'): key = "episode_uid";
278 parse = mov_metadata_int8_no_padding; break;
279 case MKTAG( 'g','n','r','e'): key = "genre";
280 parse = mov_metadata_gnre; break;
281 case MKTAG( 'h','d','v','d'): key = "hd_video";
282 parse = mov_metadata_int8_no_padding; break;
283 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
284 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
285 case MKTAG( 'l','o','c','i'):
286 return mov_metadata_loci(c, pb, atom.size);
287 case MKTAG( 'p','c','s','t'): key = "podcast";
288 parse = mov_metadata_int8_no_padding; break;
289 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
290 parse = mov_metadata_int8_no_padding; break;
291 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
292 case MKTAG( 'r','t','n','g'): key = "rating";
293 parse = mov_metadata_int8_no_padding; break;
294 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
295 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
296 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
297 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
298 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
299 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
300 case MKTAG( 's','t','i','k'): key = "media_type";
301 parse = mov_metadata_int8_no_padding; break;
302 case MKTAG( 't','r','k','n'): key = "track";
303 parse = mov_metadata_track_or_disc_number; break;
304 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
305 case MKTAG( 't','v','e','s'): key = "episode_sort";
306 parse = mov_metadata_int8_bypass_padding; break;
307 case MKTAG( 't','v','n','n'): key = "network"; break;
308 case MKTAG( 't','v','s','h'): key = "show"; break;
309 case MKTAG( 't','v','s','n'): key = "season_number";
310 parse = mov_metadata_int8_bypass_padding; break;
311 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
312 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
313 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
314 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
315 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
316 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
317 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
318 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
319 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
320 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
321 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
322 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
323 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
324 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
325 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
326 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
327 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
328 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
329 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
330 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
331 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
332 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
333 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
334 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
335 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
336 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
337 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
338 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
339 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
340 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
341 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
342 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
343 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
344 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
345 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
348 if (c->itunes_metadata && atom.size > 8) {
349 int data_size = avio_rb32(pb);
350 int tag = avio_rl32(pb);
351 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
352 data_type = avio_rb32(pb); // type
353 avio_rb32(pb); // unknown
354 str_size = data_size - 16;
357 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
358 int ret = mov_read_covr(c, pb, data_type, str_size);
360 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
365 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
366 str_size = avio_rb16(pb); // string length
367 if (str_size > atom.size) {
369 avio_seek(pb, -2, SEEK_CUR);
370 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
373 langcode = avio_rb16(pb);
374 ff_mov_lang_to_iso639(langcode, language);
377 str_size = atom.size;
379 if (c->export_all && !key) {
380 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
386 if (atom.size < 0 || str_size >= INT_MAX/2)
387 return AVERROR_INVALIDDATA;
389 // worst-case requirement for output string in case of utf8 coded input
390 str_size_alloc = (raw ? str_size : str_size * 2) + 1;
391 str = av_mallocz(str_size_alloc);
393 return AVERROR(ENOMEM);
396 parse(c, pb, str_size, key);
398 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
399 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
401 int ret = avio_read(pb, str, str_size);
402 if (ret != str_size) {
404 return ret < 0 ? ret : AVERROR_INVALIDDATA;
408 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
409 av_dict_set(&c->fc->metadata, key, str, 0);
410 if (*language && strcmp(language, "und")) {
411 snprintf(key2, sizeof(key2), "%s-%s", key, language);
412 av_dict_set(&c->fc->metadata, key2, str, 0);
415 av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
416 av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
417 key, str, (char*)&atom.type, str_size_alloc, atom.size);
423 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
426 int i, nb_chapters, str_len, version;
429 if ((atom.size -= 5) < 0)
432 version = avio_r8(pb);
435 avio_rb32(pb); // ???
436 nb_chapters = avio_r8(pb);
438 for (i = 0; i < nb_chapters; i++) {
442 start = avio_rb64(pb);
443 str_len = avio_r8(pb);
445 if ((atom.size -= 9+str_len) < 0)
448 if (avio_read(pb, str, str_len) != str_len)
449 return AVERROR_INVALIDDATA;
451 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
456 #define MIN_DATA_ENTRY_BOX_SIZE 12
457 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
460 MOVStreamContext *sc;
463 if (c->fc->nb_streams < 1)
465 st = c->fc->streams[c->fc->nb_streams-1];
468 avio_rb32(pb); // version + flags
469 entries = avio_rb32(pb);
470 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
471 entries >= UINT_MAX / sizeof(*sc->drefs))
472 return AVERROR_INVALIDDATA;
475 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
477 return AVERROR(ENOMEM);
478 sc->drefs_count = entries;
480 for (i = 0; i < sc->drefs_count; i++) {
481 MOVDref *dref = &sc->drefs[i];
482 uint32_t size = avio_rb32(pb);
483 int64_t next = avio_tell(pb) + size - 4;
486 return AVERROR_INVALIDDATA;
488 dref->type = avio_rl32(pb);
489 avio_rb32(pb); // version + flags
490 av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
492 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
493 /* macintosh alias record */
494 uint16_t volume_len, len;
499 volume_len = avio_r8(pb);
500 volume_len = FFMIN(volume_len, 27);
501 if (avio_read(pb, dref->volume, 27) != 27)
502 return AVERROR_INVALIDDATA;
503 dref->volume[volume_len] = 0;
504 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
509 len = FFMIN(len, 63);
510 if (avio_read(pb, dref->filename, 63) != 63)
511 return AVERROR_INVALIDDATA;
512 dref->filename[len] = 0;
513 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
517 /* read next level up_from_alias/down_to_target */
518 dref->nlvl_from = avio_rb16(pb);
519 dref->nlvl_to = avio_rb16(pb);
520 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
521 dref->nlvl_from, dref->nlvl_to);
525 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
528 type = avio_rb16(pb);
530 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
533 if (type == 2 || type == 18) { // absolute path
535 dref->path = av_mallocz(len+1);
537 return AVERROR(ENOMEM);
538 if (avio_read(pb, dref->path, len) != len) {
539 av_freep(&dref->path);
540 return AVERROR_INVALIDDATA;
542 if (type == 18) // no additional processing needed
544 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
546 memmove(dref->path, dref->path+volume_len, len);
549 for (j = 0; j < len; j++)
550 if (dref->path[j] == ':')
552 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
553 } else if (type == 0) { // directory name
555 dref->dir = av_malloc(len+1);
557 return AVERROR(ENOMEM);
558 if (avio_read(pb, dref->dir, len) != len) {
559 av_freep(&dref->dir);
560 return AVERROR_INVALIDDATA;
563 for (j = 0; j < len; j++)
564 if (dref->dir[j] == ':')
566 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
571 avio_seek(pb, next, SEEK_SET);
576 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
580 uint32_t av_unused ctype;
584 if (c->fc->nb_streams < 1) // meta before first trak
587 st = c->fc->streams[c->fc->nb_streams-1];
589 avio_r8(pb); /* version */
590 avio_rb24(pb); /* flags */
593 ctype = avio_rl32(pb);
594 type = avio_rl32(pb); /* component subtype */
596 av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
597 av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
599 if (type == MKTAG('v','i','d','e'))
600 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
601 else if (type == MKTAG('s','o','u','n'))
602 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
603 else if (type == MKTAG('m','1','a',' '))
604 st->codec->codec_id = AV_CODEC_ID_MP2;
605 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
606 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
608 avio_rb32(pb); /* component manufacture */
609 avio_rb32(pb); /* component flags */
610 avio_rb32(pb); /* component flags mask */
612 title_size = atom.size - 24;
613 if (title_size > 0) {
614 title_str = av_malloc(title_size + 1); /* Add null terminator */
616 return AVERROR(ENOMEM);
617 if (avio_read(pb, title_str, title_size) != title_size) {
618 av_freep(&title_str);
619 return AVERROR_INVALIDDATA;
621 title_str[title_size] = 0;
623 int off = (!c->isom && title_str[0] == title_size - 1);
624 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
626 av_freep(&title_str);
632 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
637 if (fc->nb_streams < 1)
639 st = fc->streams[fc->nb_streams-1];
641 avio_rb32(pb); /* version + flags */
642 ff_mp4_read_descr(fc, pb, &tag);
643 if (tag == MP4ESDescrTag) {
644 ff_mp4_parse_es_descr(pb, NULL);
646 avio_rb16(pb); /* ID */
648 ff_mp4_read_descr(fc, pb, &tag);
649 if (tag == MP4DecConfigDescrTag)
650 ff_mp4_read_dec_config_descr(fc, st, pb);
654 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
656 return ff_mov_read_esds(c->fc, pb);
659 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
662 enum AVAudioServiceType *ast;
663 int ac3info, acmod, lfeon, bsmod;
665 if (c->fc->nb_streams < 1)
667 st = c->fc->streams[c->fc->nb_streams-1];
669 ast = (enum AVAudioServiceType*)ff_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
672 return AVERROR(ENOMEM);
674 ac3info = avio_rb24(pb);
675 bsmod = (ac3info >> 14) & 0x7;
676 acmod = (ac3info >> 11) & 0x7;
677 lfeon = (ac3info >> 10) & 0x1;
678 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
679 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
681 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
683 if (st->codec->channels > 1 && bsmod == 0x7)
684 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
686 st->codec->audio_service_type = *ast;
691 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
694 enum AVAudioServiceType *ast;
695 int eac3info, acmod, lfeon, bsmod;
697 if (c->fc->nb_streams < 1)
699 st = c->fc->streams[c->fc->nb_streams-1];
701 ast = (enum AVAudioServiceType*)ff_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
704 return AVERROR(ENOMEM);
706 /* No need to parse fields for additional independent substreams and its
707 * associated dependent substreams since libavcodec's E-AC-3 decoder
708 * does not support them yet. */
709 avio_rb16(pb); /* data_rate and num_ind_sub */
710 eac3info = avio_rb24(pb);
711 bsmod = (eac3info >> 12) & 0x1f;
712 acmod = (eac3info >> 9) & 0x7;
713 lfeon = (eac3info >> 8) & 0x1;
714 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
716 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
717 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
719 if (st->codec->channels > 1 && bsmod == 0x7)
720 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
722 st->codec->audio_service_type = *ast;
727 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
731 if (c->fc->nb_streams < 1)
733 st = c->fc->streams[c->fc->nb_streams-1];
738 /* skip version and flags */
741 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
746 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
751 if (c->fc->nb_streams < 1)
753 st = c->fc->streams[c->fc->nb_streams-1];
755 if ((ret = ff_get_wav_header(pb, st->codec, atom.size, 0)) < 0)
756 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
761 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
763 const int num = avio_rb32(pb);
764 const int den = avio_rb32(pb);
767 if (c->fc->nb_streams < 1)
769 st = c->fc->streams[c->fc->nb_streams-1];
771 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
772 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
773 av_log(c->fc, AV_LOG_WARNING,
774 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
775 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
777 } else if (den != 0) {
778 av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
784 /* this atom contains actual media data */
785 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
787 if (atom.size == 0) /* wrong one (MP4) */
790 return 0; /* now go for moov */
793 /* read major brand, minor version and compatible brands and store them as metadata */
794 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
798 char* comp_brands_str;
799 uint8_t type[5] = {0};
801 if (avio_read(pb, type, 4) != 4)
802 return AVERROR_INVALIDDATA;
803 if (strcmp(type, "qt "))
805 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
806 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
807 minor_ver = avio_rb32(pb); /* minor version */
808 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
810 comp_brand_size = atom.size - 8;
811 if (comp_brand_size < 0)
812 return AVERROR_INVALIDDATA;
813 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
814 if (!comp_brands_str)
815 return AVERROR(ENOMEM);
816 if (avio_read(pb, comp_brands_str, comp_brand_size) != comp_brand_size) {
817 av_freep(&comp_brands_str);
818 return AVERROR_INVALIDDATA;
820 comp_brands_str[comp_brand_size] = 0;
821 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
822 av_freep(&comp_brands_str);
827 /* this atom should contain all header atoms */
828 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
833 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
834 avio_skip(pb, atom.size);
838 if ((ret = mov_read_default(c, pb, atom)) < 0)
840 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
841 /* so we don't parse the whole file if over a network */
843 return 0; /* now go for mdat */
846 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
848 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
849 c->has_looked_for_mfra = 1;
852 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
854 if ((ret = mov_read_mfra(c, pb)) < 0) {
855 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
856 "read the mfra (may be a live ismv)\n");
859 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
860 "seekable, can not look for mfra\n");
863 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
864 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
865 return mov_read_default(c, pb, atom);
868 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
872 struct tm *ptm, tmbuf;
874 if(time >= 2082844800)
875 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
877 ptm = gmtime_r(&timet, &tmbuf);
879 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
880 av_dict_set(metadata, "creation_time", buffer, 0);
884 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
887 MOVStreamContext *sc;
889 char language[4] = {0};
891 int64_t creation_time;
893 if (c->fc->nb_streams < 1)
895 st = c->fc->streams[c->fc->nb_streams-1];
898 if (sc->time_scale) {
899 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
900 return AVERROR_INVALIDDATA;
903 version = avio_r8(pb);
905 avpriv_request_sample(c->fc, "Version %d", version);
906 return AVERROR_PATCHWELCOME;
908 avio_rb24(pb); /* flags */
910 creation_time = avio_rb64(pb);
913 creation_time = avio_rb32(pb);
914 avio_rb32(pb); /* modification time */
916 mov_metadata_creation_time(&st->metadata, creation_time);
918 sc->time_scale = avio_rb32(pb);
919 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
921 lang = avio_rb16(pb); /* language */
922 if (ff_mov_lang_to_iso639(lang, language))
923 av_dict_set(&st->metadata, "language", language, 0);
924 avio_rb16(pb); /* quality */
929 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
931 int64_t creation_time;
932 int version = avio_r8(pb); /* version */
933 avio_rb24(pb); /* flags */
936 creation_time = avio_rb64(pb);
939 creation_time = avio_rb32(pb);
940 avio_rb32(pb); /* modification time */
942 mov_metadata_creation_time(&c->fc->metadata, creation_time);
943 c->time_scale = avio_rb32(pb); /* time scale */
945 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
947 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
948 // set the AVCodecContext duration because the duration of individual tracks
950 if (c->time_scale > 0 && !c->trex_data)
951 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
952 avio_rb32(pb); /* preferred scale */
954 avio_rb16(pb); /* preferred volume */
956 avio_skip(pb, 10); /* reserved */
958 avio_skip(pb, 36); /* display matrix */
960 avio_rb32(pb); /* preview time */
961 avio_rb32(pb); /* preview duration */
962 avio_rb32(pb); /* poster time */
963 avio_rb32(pb); /* selection time */
964 avio_rb32(pb); /* selection duration */
965 avio_rb32(pb); /* current time */
966 avio_rb32(pb); /* next track ID */
970 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
975 if (c->fc->nb_streams < 1)
977 st = c->fc->streams[c->fc->nb_streams-1];
979 little_endian = avio_rb16(pb) & 0xFF;
980 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
981 if (little_endian == 1) {
982 switch (st->codec->codec_id) {
983 case AV_CODEC_ID_PCM_S24BE:
984 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
986 case AV_CODEC_ID_PCM_S32BE:
987 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
989 case AV_CODEC_ID_PCM_F32BE:
990 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
992 case AV_CODEC_ID_PCM_F64BE:
993 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
1002 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1005 char color_parameter_type[5] = { 0 };
1006 int color_primaries, color_trc, color_matrix;
1008 if (c->fc->nb_streams < 1)
1010 st = c->fc->streams[c->fc->nb_streams - 1];
1012 if (avio_read(pb, color_parameter_type, 4) != 4)
1013 return AVERROR_INVALIDDATA;
1014 if (strncmp(color_parameter_type, "nclx", 4) &&
1015 strncmp(color_parameter_type, "nclc", 4)) {
1016 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1017 color_parameter_type);
1021 color_primaries = avio_rb16(pb);
1022 color_trc = avio_rb16(pb);
1023 color_matrix = avio_rb16(pb);
1025 av_log(c->fc, AV_LOG_TRACE,
1026 "%s: pri %d trc %d matrix %d",
1027 color_parameter_type, color_primaries, color_trc, color_matrix);
1029 if (!strncmp(color_parameter_type, "nclx", 4)) {
1030 uint8_t color_range = avio_r8(pb) >> 7;
1031 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1033 st->codec->color_range = AVCOL_RANGE_JPEG;
1035 st->codec->color_range = AVCOL_RANGE_MPEG;
1036 /* 14496-12 references JPEG XR specs (rather than the more complete
1037 * 23001-8) so some adjusting is required */
1038 if (color_primaries >= AVCOL_PRI_FILM)
1039 color_primaries = AVCOL_PRI_UNSPECIFIED;
1040 if ((color_trc >= AVCOL_TRC_LINEAR &&
1041 color_trc <= AVCOL_TRC_LOG_SQRT) ||
1042 color_trc >= AVCOL_TRC_BT2020_10)
1043 color_trc = AVCOL_TRC_UNSPECIFIED;
1044 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
1045 color_matrix = AVCOL_SPC_UNSPECIFIED;
1046 st->codec->color_primaries = color_primaries;
1047 st->codec->color_trc = color_trc;
1048 st->codec->colorspace = color_matrix;
1049 } else if (!strncmp(color_parameter_type, "nclc", 4)) {
1050 /* color primaries, Table 4-4 */
1051 switch (color_primaries) {
1052 case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
1053 case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
1054 case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
1056 /* color transfer, Table 4-5 */
1057 switch (color_trc) {
1058 case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
1059 case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
1061 /* color matrix, Table 4-6 */
1062 switch (color_matrix) {
1063 case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
1064 case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
1065 case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
1068 av_log(c->fc, AV_LOG_TRACE, "\n");
1073 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1076 unsigned mov_field_order;
1077 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1079 if (c->fc->nb_streams < 1) // will happen with jp2 files
1081 st = c->fc->streams[c->fc->nb_streams-1];
1083 return AVERROR_INVALIDDATA;
1084 mov_field_order = avio_rb16(pb);
1085 if ((mov_field_order & 0xFF00) == 0x0100)
1086 decoded_field_order = AV_FIELD_PROGRESSIVE;
1087 else if ((mov_field_order & 0xFF00) == 0x0200) {
1088 switch (mov_field_order & 0xFF) {
1089 case 0x01: decoded_field_order = AV_FIELD_TT;
1091 case 0x06: decoded_field_order = AV_FIELD_BB;
1093 case 0x09: decoded_field_order = AV_FIELD_TB;
1095 case 0x0E: decoded_field_order = AV_FIELD_BT;
1099 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1100 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1102 st->codec->field_order = decoded_field_order;
1107 static int mov_realloc_extradata(AVCodecContext *codec, MOVAtom atom)
1110 uint64_t size = (uint64_t)codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
1111 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1112 return AVERROR_INVALIDDATA;
1113 if ((err = av_reallocp(&codec->extradata, size)) < 0) {
1114 codec->extradata_size = 0;
1117 codec->extradata_size = size - FF_INPUT_BUFFER_PADDING_SIZE;
1121 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1122 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1123 AVCodecContext *codec, uint8_t *buf)
1125 int64_t result = atom.size;
1128 AV_WB32(buf , atom.size + 8);
1129 AV_WL32(buf + 4, atom.type);
1130 err = avio_read(pb, buf + 8, atom.size);
1132 codec->extradata_size -= atom.size;
1134 } else if (err < atom.size) {
1135 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1136 codec->extradata_size -= atom.size - err;
1139 memset(buf + 8 + err, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1143 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
1144 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1145 enum AVCodecID codec_id)
1148 uint64_t original_size;
1151 if (c->fc->nb_streams < 1) // will happen with jp2 files
1153 st = c->fc->streams[c->fc->nb_streams-1];
1155 if (st->codec->codec_id != codec_id)
1156 return 0; /* unexpected codec_id - don't mess with extradata */
1158 original_size = st->codec->extradata_size;
1159 err = mov_realloc_extradata(st->codec, atom);
1163 err = mov_read_atom_into_extradata(c, pb, atom, st->codec, st->codec->extradata + original_size);
1166 return 0; // Note: this is the original behavior to ignore truncation.
1169 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1170 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1172 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1175 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1177 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1180 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1182 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1185 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1187 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1190 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1192 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1194 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1198 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1200 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1202 if (!ret && c->fc->nb_streams >= 1) {
1203 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
1204 if (avctx->extradata_size >= 40) {
1205 avctx->height = AV_RB16(&avctx->extradata[36]);
1206 avctx->width = AV_RB16(&avctx->extradata[38]);
1212 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1214 if (c->fc->nb_streams >= 1) {
1215 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1216 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1217 codec->codec_id == AV_CODEC_ID_H264 &&
1220 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1221 if (avio_rb16(pb) == 0xd4d)
1222 codec->width = 1440;
1227 return mov_read_avid(c, pb, atom);
1230 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1234 uint64_t original_size;
1235 if (c->fc->nb_streams >= 1) {
1236 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1237 if (codec->codec_id == AV_CODEC_ID_H264)
1239 if (atom.size == 16) {
1240 original_size = codec->extradata_size;
1241 ret = mov_realloc_extradata(codec, atom);
1243 length = mov_read_atom_into_extradata(c, pb, atom, codec, codec->extradata + original_size);
1244 if (length == atom.size) {
1245 const uint8_t range_value = codec->extradata[original_size + 19];
1246 switch (range_value) {
1248 codec->color_range = AVCOL_RANGE_MPEG;
1251 codec->color_range = AVCOL_RANGE_JPEG;
1254 av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1257 av_dlog(c, "color_range: %d\n", codec->color_range);
1259 /* For some reason the whole atom was not added to the extradata */
1260 av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1263 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1266 av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1273 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1275 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1278 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1282 if (c->fc->nb_streams < 1)
1284 st = c->fc->streams[c->fc->nb_streams-1];
1286 if ((uint64_t)atom.size > (1<<30))
1287 return AVERROR_INVALIDDATA;
1289 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1290 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1291 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1292 // pass all frma atom to codec, needed at least for QDMC and QDM2
1293 av_freep(&st->codec->extradata);
1294 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1295 return AVERROR(ENOMEM);
1296 } else if (atom.size > 8) { /* to read frma, esds atoms */
1298 if ((ret = mov_read_default(c, pb, atom)) < 0)
1301 avio_skip(pb, atom.size);
1306 * This function reads atom content and puts data in extradata without tag
1307 * nor size unlike mov_read_extradata.
1309 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1313 if (c->fc->nb_streams < 1)
1315 st = c->fc->streams[c->fc->nb_streams-1];
1317 if ((uint64_t)atom.size > (1<<30))
1318 return AVERROR_INVALIDDATA;
1320 if (atom.size >= 10) {
1321 // Broken files created by legacy versions of libavformat will
1322 // wrap a whole fiel atom inside of a glbl atom.
1323 unsigned size = avio_rb32(pb);
1324 unsigned type = avio_rl32(pb);
1325 avio_seek(pb, -8, SEEK_CUR);
1326 if (type == MKTAG('f','i','e','l') && size == atom.size)
1327 return mov_read_default(c, pb, atom);
1329 if (st->codec->extradata_size > 1 && st->codec->extradata) {
1330 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1333 av_freep(&st->codec->extradata);
1334 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1335 return AVERROR(ENOMEM);
1340 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1343 uint8_t profile_level;
1346 if (c->fc->nb_streams < 1)
1348 st = c->fc->streams[c->fc->nb_streams-1];
1350 if (atom.size >= (1<<28) || atom.size < 7)
1351 return AVERROR_INVALIDDATA;
1353 profile_level = avio_r8(pb);
1354 if ((profile_level & 0xf0) != 0xc0)
1357 avio_seek(pb, 6, SEEK_CUR);
1358 av_freep(&st->codec->extradata);
1359 if ((ret = ff_get_extradata(st->codec, pb, atom.size - 7)) < 0)
1366 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1367 * but can have extradata appended at the end after the 40 bytes belonging
1370 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1374 if (c->fc->nb_streams < 1)
1376 if (atom.size <= 40)
1378 st = c->fc->streams[c->fc->nb_streams-1];
1380 if ((uint64_t)atom.size > (1<<30))
1381 return AVERROR_INVALIDDATA;
1384 av_freep(&st->codec->extradata);
1385 if (ff_get_extradata(st->codec, pb, atom.size - 40) < 0)
1386 return AVERROR(ENOMEM);
1390 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1393 MOVStreamContext *sc;
1394 unsigned int i, entries;
1396 if (c->fc->nb_streams < 1)
1398 st = c->fc->streams[c->fc->nb_streams-1];
1401 avio_r8(pb); /* version */
1402 avio_rb24(pb); /* flags */
1404 entries = avio_rb32(pb);
1409 if (sc->chunk_offsets)
1410 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1411 av_free(sc->chunk_offsets);
1412 sc->chunk_count = 0;
1413 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1414 if (!sc->chunk_offsets)
1415 return AVERROR(ENOMEM);
1416 sc->chunk_count = entries;
1418 if (atom.type == MKTAG('s','t','c','o'))
1419 for (i = 0; i < entries && !pb->eof_reached; i++)
1420 sc->chunk_offsets[i] = avio_rb32(pb);
1421 else if (atom.type == MKTAG('c','o','6','4'))
1422 for (i = 0; i < entries && !pb->eof_reached; i++)
1423 sc->chunk_offsets[i] = avio_rb64(pb);
1425 return AVERROR_INVALIDDATA;
1427 sc->chunk_count = i;
1429 if (pb->eof_reached)
1436 * Compute codec id for 'lpcm' tag.
1437 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1439 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1446 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1449 static int mov_codec_id(AVStream *st, uint32_t format)
1451 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1454 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1455 (format & 0xFFFF) == 'T' + ('S' << 8)))
1456 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1458 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1459 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1460 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1461 /* skip old asf mpeg4 tag */
1462 format && format != MKTAG('m','p','4','s')) {
1463 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1465 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1467 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1468 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1469 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1470 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1471 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1473 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1477 st->codec->codec_tag = format;
1482 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1483 AVStream *st, MOVStreamContext *sc)
1485 uint8_t codec_name[32];
1486 unsigned int color_depth, len, j;
1487 int color_greyscale;
1490 avio_rb16(pb); /* version */
1491 avio_rb16(pb); /* revision level */
1492 avio_rb32(pb); /* vendor */
1493 avio_rb32(pb); /* temporal quality */
1494 avio_rb32(pb); /* spatial quality */
1496 st->codec->width = avio_rb16(pb); /* width */
1497 st->codec->height = avio_rb16(pb); /* height */
1499 avio_rb32(pb); /* horiz resolution */
1500 avio_rb32(pb); /* vert resolution */
1501 avio_rb32(pb); /* data size, always 0 */
1502 avio_rb16(pb); /* frames per samples */
1504 len = avio_r8(pb); /* codec name, pascal string */
1507 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1509 avio_skip(pb, 31 - len);
1512 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1514 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1515 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1516 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1517 st->codec->width &= ~1;
1518 st->codec->height &= ~1;
1520 /* Flash Media Server uses tag H263 with Sorenson Spark */
1521 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1522 !memcmp(codec_name, "Sorenson H263", 13))
1523 st->codec->codec_id = AV_CODEC_ID_FLV1;
1525 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1526 color_table_id = avio_rb16(pb); /* colortable id */
1527 av_log(c->fc, AV_LOG_TRACE, "depth %d, ctab id %d\n",
1528 st->codec->bits_per_coded_sample, color_table_id);
1529 /* figure out the palette situation */
1530 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1531 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1532 /* Do not create a greyscale palette for cinepak */
1533 if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1536 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1537 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1538 /* for palette traversal */
1539 unsigned int color_start, color_count, color_end;
1540 unsigned char a, r, g, b;
1542 if (color_greyscale) {
1543 int color_index, color_dec;
1544 /* compute the greyscale palette */
1545 st->codec->bits_per_coded_sample = color_depth;
1546 color_count = 1 << color_depth;
1548 color_dec = 256 / (color_count - 1);
1549 for (j = 0; j < color_count; j++) {
1550 r = g = b = color_index;
1551 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1552 color_index -= color_dec;
1553 if (color_index < 0)
1556 } else if (color_table_id) {
1557 const uint8_t *color_table;
1558 /* if flag bit 3 is set, use the default palette */
1559 color_count = 1 << color_depth;
1560 if (color_depth == 2)
1561 color_table = ff_qt_default_palette_4;
1562 else if (color_depth == 4)
1563 color_table = ff_qt_default_palette_16;
1565 color_table = ff_qt_default_palette_256;
1567 for (j = 0; j < color_count; j++) {
1568 r = color_table[j * 3 + 0];
1569 g = color_table[j * 3 + 1];
1570 b = color_table[j * 3 + 2];
1571 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1574 /* load the palette from the file */
1575 color_start = avio_rb32(pb);
1576 color_count = avio_rb16(pb);
1577 color_end = avio_rb16(pb);
1578 if ((color_start <= 255) && (color_end <= 255)) {
1579 for (j = color_start; j <= color_end; j++) {
1580 /* each A, R, G, or B component is 16 bits;
1581 * only use the top 8 bits */
1590 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1594 sc->has_palette = 1;
1598 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1599 AVStream *st, MOVStreamContext *sc)
1601 int bits_per_sample, flags;
1602 uint16_t version = avio_rb16(pb);
1603 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1605 avio_rb16(pb); /* revision level */
1606 avio_rb32(pb); /* vendor */
1608 st->codec->channels = avio_rb16(pb); /* channel count */
1609 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1610 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codec->channels);
1612 sc->audio_cid = avio_rb16(pb);
1613 avio_rb16(pb); /* packet size = 0 */
1615 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1617 // Read QT version 1 fields. In version 0 these do not exist.
1618 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1620 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1623 sc->samples_per_frame = avio_rb32(pb);
1624 avio_rb32(pb); /* bytes per packet */
1625 sc->bytes_per_frame = avio_rb32(pb);
1626 avio_rb32(pb); /* bytes per sample */
1627 } else if (version == 2) {
1628 avio_rb32(pb); /* sizeof struct only */
1629 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1630 st->codec->channels = avio_rb32(pb);
1631 avio_rb32(pb); /* always 0x7F000000 */
1632 st->codec->bits_per_coded_sample = avio_rb32(pb);
1634 flags = avio_rb32(pb); /* lpcm format specific flag */
1635 sc->bytes_per_frame = avio_rb32(pb);
1636 sc->samples_per_frame = avio_rb32(pb);
1637 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1638 st->codec->codec_id =
1639 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1644 switch (st->codec->codec_id) {
1645 case AV_CODEC_ID_PCM_S8:
1646 case AV_CODEC_ID_PCM_U8:
1647 if (st->codec->bits_per_coded_sample == 16)
1648 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1650 case AV_CODEC_ID_PCM_S16LE:
1651 case AV_CODEC_ID_PCM_S16BE:
1652 if (st->codec->bits_per_coded_sample == 8)
1653 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1654 else if (st->codec->bits_per_coded_sample == 24)
1655 st->codec->codec_id =
1656 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1657 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1658 else if (st->codec->bits_per_coded_sample == 32)
1659 st->codec->codec_id =
1660 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1661 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1663 /* set values for old format before stsd version 1 appeared */
1664 case AV_CODEC_ID_MACE3:
1665 sc->samples_per_frame = 6;
1666 sc->bytes_per_frame = 2 * st->codec->channels;
1668 case AV_CODEC_ID_MACE6:
1669 sc->samples_per_frame = 6;
1670 sc->bytes_per_frame = 1 * st->codec->channels;
1672 case AV_CODEC_ID_ADPCM_IMA_QT:
1673 sc->samples_per_frame = 64;
1674 sc->bytes_per_frame = 34 * st->codec->channels;
1676 case AV_CODEC_ID_GSM:
1677 sc->samples_per_frame = 160;
1678 sc->bytes_per_frame = 33;
1684 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1685 if (bits_per_sample) {
1686 st->codec->bits_per_coded_sample = bits_per_sample;
1687 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1691 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1692 AVStream *st, MOVStreamContext *sc,
1695 // ttxt stsd contains display flags, justification, background
1696 // color, fonts, and default styles, so fake an atom to read it
1697 MOVAtom fake_atom = { .size = size };
1698 // mp4s contains a regular esds atom
1699 if (st->codec->codec_tag != AV_RL32("mp4s"))
1700 mov_read_glbl(c, pb, fake_atom);
1701 st->codec->width = sc->width;
1702 st->codec->height = sc->height;
1705 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1710 y = (ycbcr >> 16) & 0xFF;
1711 cr = (ycbcr >> 8) & 0xFF;
1714 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1715 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1716 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1718 return (r << 16) | (g << 8) | b;
1721 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1723 char buf[256] = {0};
1724 uint8_t *src = st->codec->extradata;
1727 if (st->codec->extradata_size != 64)
1730 if (st->codec->width > 0 && st->codec->height > 0)
1731 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1732 st->codec->width, st->codec->height);
1733 av_strlcat(buf, "palette: ", sizeof(buf));
1735 for (i = 0; i < 16; i++) {
1736 uint32_t yuv = AV_RB32(src + i * 4);
1737 uint32_t rgba = yuv_to_rgba(yuv);
1739 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1742 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1745 av_freep(&st->codec->extradata);
1746 st->codec->extradata_size = 0;
1747 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1748 if (!st->codec->extradata)
1749 return AVERROR(ENOMEM);
1750 st->codec->extradata_size = strlen(buf);
1751 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1756 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1757 AVStream *st, MOVStreamContext *sc,
1760 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1761 if ((int)size != size || ff_get_extradata(st->codec, pb, size) < 0)
1762 return AVERROR(ENOMEM);
1764 MOVStreamContext *tmcd_ctx = st->priv_data;
1766 val = AV_RB32(st->codec->extradata + 4);
1767 tmcd_ctx->tmcd_flags = val;
1769 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1770 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
1771 st->codec->time_base.num = 1;
1772 /* adjust for per frame dur in counter mode */
1773 if (tmcd_ctx->tmcd_flags & 0x0008) {
1774 int timescale = AV_RB32(st->codec->extradata + 8);
1775 int framedur = AV_RB32(st->codec->extradata + 12);
1776 st->codec->time_base.den *= timescale;
1777 st->codec->time_base.num *= framedur;
1780 uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
1781 uint32_t format = AV_RB32(st->codec->extradata + 22);
1782 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
1783 uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
1784 if (str_size > 0 && size >= (int)str_size + 26) {
1785 char *reel_name = av_malloc(str_size + 1);
1787 return AVERROR(ENOMEM);
1788 memcpy(reel_name, st->codec->extradata + 30, str_size);
1789 reel_name[str_size] = 0; /* Add null terminator */
1790 /* don't add reel_name if emtpy string */
1791 if (*reel_name == 0) {
1794 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
1801 /* other codec type, just skip (rtp, mp4s ...) */
1802 avio_skip(pb, size);
1807 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1808 AVStream *st, MOVStreamContext *sc)
1810 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1811 !st->codec->sample_rate && sc->time_scale > 1)
1812 st->codec->sample_rate = sc->time_scale;
1814 /* special codec parameters handling */
1815 switch (st->codec->codec_id) {
1816 #if CONFIG_DV_DEMUXER
1817 case AV_CODEC_ID_DVAUDIO:
1818 c->dv_fctx = avformat_alloc_context();
1819 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1821 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1822 return AVERROR(ENOMEM);
1824 sc->dv_audio_container = 1;
1825 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1828 /* no ifdef since parameters are always those */
1829 case AV_CODEC_ID_QCELP:
1830 st->codec->channels = 1;
1831 // force sample rate for qcelp when not stored in mov
1832 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1833 st->codec->sample_rate = 8000;
1834 // FIXME: Why is the following needed for some files?
1835 sc->samples_per_frame = 160;
1836 if (!sc->bytes_per_frame)
1837 sc->bytes_per_frame = 35;
1839 case AV_CODEC_ID_AMR_NB:
1840 st->codec->channels = 1;
1841 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1842 st->codec->sample_rate = 8000;
1844 case AV_CODEC_ID_AMR_WB:
1845 st->codec->channels = 1;
1846 st->codec->sample_rate = 16000;
1848 case AV_CODEC_ID_MP2:
1849 case AV_CODEC_ID_MP3:
1850 /* force type after stsd for m1a hdlr */
1851 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1852 st->need_parsing = AVSTREAM_PARSE_FULL;
1854 case AV_CODEC_ID_GSM:
1855 case AV_CODEC_ID_ADPCM_MS:
1856 case AV_CODEC_ID_ADPCM_IMA_WAV:
1857 case AV_CODEC_ID_ILBC:
1858 case AV_CODEC_ID_MACE3:
1859 case AV_CODEC_ID_MACE6:
1860 case AV_CODEC_ID_QDM2:
1861 st->codec->block_align = sc->bytes_per_frame;
1863 case AV_CODEC_ID_ALAC:
1864 if (st->codec->extradata_size == 36) {
1865 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1866 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1869 case AV_CODEC_ID_AC3:
1870 case AV_CODEC_ID_EAC3:
1871 case AV_CODEC_ID_MPEG1VIDEO:
1872 case AV_CODEC_ID_VC1:
1873 st->need_parsing = AVSTREAM_PARSE_FULL;
1881 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1882 int codec_tag, int format,
1885 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1888 (codec_tag != format &&
1889 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1890 : codec_tag != MKTAG('j','p','e','g')))) {
1891 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1892 * export it as a separate AVStream but this needs a few changes
1893 * in the MOV demuxer, patch welcome. */
1895 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1896 avio_skip(pb, size);
1899 if ( codec_tag == AV_RL32("avc1") ||
1900 codec_tag == AV_RL32("hvc1") ||
1901 codec_tag == AV_RL32("hev1")
1903 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
1908 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1911 MOVStreamContext *sc;
1912 int pseudo_stream_id;
1914 if (c->fc->nb_streams < 1)
1916 st = c->fc->streams[c->fc->nb_streams-1];
1919 for (pseudo_stream_id = 0;
1920 pseudo_stream_id < entries && !pb->eof_reached;
1921 pseudo_stream_id++) {
1922 //Parsing Sample description table
1924 int ret, dref_id = 1;
1925 MOVAtom a = { AV_RL32("stsd") };
1926 int64_t start_pos = avio_tell(pb);
1927 int64_t size = avio_rb32(pb); /* size */
1928 uint32_t format = avio_rl32(pb); /* data format */
1931 avio_rb32(pb); /* reserved */
1932 avio_rb16(pb); /* reserved */
1933 dref_id = avio_rb16(pb);
1934 }else if (size <= 7){
1935 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1936 return AVERROR_INVALIDDATA;
1939 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1940 size - (avio_tell(pb) - start_pos)))
1943 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1944 sc->dref_id= dref_id;
1946 id = mov_codec_id(st, format);
1948 av_log(c->fc, AV_LOG_TRACE, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1949 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1950 (format >> 24) & 0xff, st->codec->codec_type);
1952 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1953 st->codec->codec_id = id;
1954 mov_parse_stsd_video(c, pb, st, sc);
1955 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1956 st->codec->codec_id = id;
1957 mov_parse_stsd_audio(c, pb, st, sc);
1958 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1959 st->codec->codec_id = id;
1960 mov_parse_stsd_subtitle(c, pb, st, sc,
1961 size - (avio_tell(pb) - start_pos));
1963 ret = mov_parse_stsd_data(c, pb, st, sc,
1964 size - (avio_tell(pb) - start_pos));
1968 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1969 a.size = size - (avio_tell(pb) - start_pos);
1971 if ((ret = mov_read_default(c, pb, a)) < 0)
1973 } else if (a.size > 0)
1974 avio_skip(pb, a.size);
1977 if (pb->eof_reached)
1980 return mov_finalize_stsd_codec(c, pb, st, sc);
1983 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1987 avio_r8(pb); /* version */
1988 avio_rb24(pb); /* flags */
1989 entries = avio_rb32(pb);
1991 return ff_mov_read_stsd_entries(c, pb, entries);
1994 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1997 MOVStreamContext *sc;
1998 unsigned int i, entries;
2000 if (c->fc->nb_streams < 1)
2002 st = c->fc->streams[c->fc->nb_streams-1];
2005 avio_r8(pb); /* version */
2006 avio_rb24(pb); /* flags */
2008 entries = avio_rb32(pb);
2010 av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
2015 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2016 av_free(sc->stsc_data);
2018 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2020 return AVERROR(ENOMEM);
2022 for (i = 0; i < entries && !pb->eof_reached; i++) {
2023 sc->stsc_data[i].first = avio_rb32(pb);
2024 sc->stsc_data[i].count = avio_rb32(pb);
2025 sc->stsc_data[i].id = avio_rb32(pb);
2030 if (pb->eof_reached)
2036 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2039 MOVStreamContext *sc;
2040 unsigned i, entries;
2042 if (c->fc->nb_streams < 1)
2044 st = c->fc->streams[c->fc->nb_streams-1];
2047 avio_rb32(pb); // version + flags
2049 entries = avio_rb32(pb);
2051 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2052 av_free(sc->stps_data);
2054 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2056 return AVERROR(ENOMEM);
2058 for (i = 0; i < entries && !pb->eof_reached; i++) {
2059 sc->stps_data[i] = avio_rb32(pb);
2060 //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
2065 if (pb->eof_reached)
2071 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2074 MOVStreamContext *sc;
2075 unsigned int i, entries;
2077 if (c->fc->nb_streams < 1)
2079 st = c->fc->streams[c->fc->nb_streams-1];
2082 avio_r8(pb); /* version */
2083 avio_rb24(pb); /* flags */
2085 entries = avio_rb32(pb);
2087 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
2091 sc->keyframe_absent = 1;
2092 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2093 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2097 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2098 if (entries >= UINT_MAX / sizeof(int))
2099 return AVERROR_INVALIDDATA;
2100 av_freep(&sc->keyframes);
2101 sc->keyframe_count = 0;
2102 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2104 return AVERROR(ENOMEM);
2106 for (i = 0; i < entries && !pb->eof_reached; i++) {
2107 sc->keyframes[i] = avio_rb32(pb);
2108 //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
2111 sc->keyframe_count = i;
2113 if (pb->eof_reached)
2119 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2122 MOVStreamContext *sc;
2123 unsigned int i, entries, sample_size, field_size, num_bytes;
2127 if (c->fc->nb_streams < 1)
2129 st = c->fc->streams[c->fc->nb_streams-1];
2132 avio_r8(pb); /* version */
2133 avio_rb24(pb); /* flags */
2135 if (atom.type == MKTAG('s','t','s','z')) {
2136 sample_size = avio_rb32(pb);
2137 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2138 sc->sample_size = sample_size;
2139 sc->stsz_sample_size = sample_size;
2143 avio_rb24(pb); /* reserved */
2144 field_size = avio_r8(pb);
2146 entries = avio_rb32(pb);
2148 av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2150 sc->sample_count = entries;
2154 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2155 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2156 return AVERROR_INVALIDDATA;
2161 if (entries >= (UINT_MAX - 4) / field_size)
2162 return AVERROR_INVALIDDATA;
2163 if (sc->sample_sizes)
2164 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2165 av_free(sc->sample_sizes);
2166 sc->sample_count = 0;
2167 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2168 if (!sc->sample_sizes)
2169 return AVERROR(ENOMEM);
2171 num_bytes = (entries*field_size+4)>>3;
2173 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
2175 av_freep(&sc->sample_sizes);
2176 return AVERROR(ENOMEM);
2179 if (avio_read(pb, buf, num_bytes) < num_bytes) {
2180 av_freep(&sc->sample_sizes);
2182 return AVERROR_INVALIDDATA;
2185 init_get_bits(&gb, buf, 8*num_bytes);
2187 for (i = 0; i < entries && !pb->eof_reached; i++) {
2188 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2189 sc->data_size += sc->sample_sizes[i];
2192 sc->sample_count = i;
2196 if (pb->eof_reached)
2202 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2205 MOVStreamContext *sc;
2206 unsigned int i, entries;
2208 int64_t total_sample_count=0;
2210 if (c->fc->nb_streams < 1)
2212 st = c->fc->streams[c->fc->nb_streams-1];
2215 avio_r8(pb); /* version */
2216 avio_rb24(pb); /* flags */
2217 entries = avio_rb32(pb);
2219 av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2220 c->fc->nb_streams-1, entries);
2223 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2224 av_free(sc->stts_data);
2226 sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2228 return AVERROR(ENOMEM);
2230 for (i = 0; i < entries && !pb->eof_reached; i++) {
2231 int sample_duration;
2234 sample_count=avio_rb32(pb);
2235 sample_duration = avio_rb32(pb);
2237 /* sample_duration < 0 is invalid based on the spec */
2238 if (sample_duration < 0) {
2239 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2240 sample_duration, i, c->fc->nb_streams-1);
2241 sample_duration = 1;
2243 if (sample_count < 0) {
2244 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2245 return AVERROR_INVALIDDATA;
2247 sc->stts_data[i].count= sample_count;
2248 sc->stts_data[i].duration= sample_duration;
2250 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2251 sample_count, sample_duration);
2255 && sample_count == 1
2256 && total_sample_count > 100
2257 && sample_duration/10 > duration / total_sample_count)
2258 sample_duration = duration / total_sample_count;
2259 duration+=(int64_t)sample_duration*sample_count;
2260 total_sample_count+=sample_count;
2265 sc->duration_for_fps += duration;
2266 sc->nb_frames_for_fps += total_sample_count;
2268 if (pb->eof_reached)
2271 st->nb_frames= total_sample_count;
2273 st->duration= duration;
2274 sc->track_end = duration;
2278 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2281 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2285 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2288 MOVStreamContext *sc;
2289 unsigned int i, entries;
2291 if (c->fc->nb_streams < 1)
2293 st = c->fc->streams[c->fc->nb_streams-1];
2296 avio_r8(pb); /* version */
2297 avio_rb24(pb); /* flags */
2298 entries = avio_rb32(pb);
2300 av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2304 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2305 return AVERROR_INVALIDDATA;
2306 av_freep(&sc->ctts_data);
2307 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
2309 return AVERROR(ENOMEM);
2311 for (i = 0; i < entries && !pb->eof_reached; i++) {
2312 int count =avio_rb32(pb);
2313 int duration =avio_rb32(pb);
2315 sc->ctts_data[i].count = count;
2316 sc->ctts_data[i].duration= duration;
2318 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2321 if (FFABS(duration) > (1<<28) && i+2<entries) {
2322 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2323 av_freep(&sc->ctts_data);
2329 mov_update_dts_shift(sc, duration);
2334 if (pb->eof_reached)
2337 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2342 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2345 MOVStreamContext *sc;
2346 unsigned int i, entries;
2348 uint32_t grouping_type;
2350 if (c->fc->nb_streams < 1)
2352 st = c->fc->streams[c->fc->nb_streams-1];
2355 version = avio_r8(pb); /* version */
2356 avio_rb24(pb); /* flags */
2357 grouping_type = avio_rl32(pb);
2358 if (grouping_type != MKTAG( 'r','a','p',' '))
2359 return 0; /* only support 'rap ' grouping */
2361 avio_rb32(pb); /* grouping_type_parameter */
2363 entries = avio_rb32(pb);
2367 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2368 av_free(sc->rap_group);
2369 sc->rap_group_count = 0;
2370 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2372 return AVERROR(ENOMEM);
2374 for (i = 0; i < entries && !pb->eof_reached; i++) {
2375 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2376 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2379 sc->rap_group_count = i;
2381 return pb->eof_reached ? AVERROR_EOF : 0;
2384 static void mov_build_index(MOVContext *mov, AVStream *st)
2386 MOVStreamContext *sc = st->priv_data;
2387 int64_t current_offset;
2388 int64_t current_dts = 0;
2389 unsigned int stts_index = 0;
2390 unsigned int stsc_index = 0;
2391 unsigned int stss_index = 0;
2392 unsigned int stps_index = 0;
2394 uint64_t stream_size = 0;
2396 if (sc->elst_count) {
2397 int i, edit_start_index = 0, unsupported = 0;
2398 int64_t empty_duration = 0; // empty duration of the first edit list entry
2399 int64_t start_time = 0; // start time of the media
2401 for (i = 0; i < sc->elst_count; i++) {
2402 const MOVElst *e = &sc->elst_data[i];
2403 if (i == 0 && e->time == -1) {
2404 /* if empty, the first entry is the start time of the stream
2405 * relative to the presentation itself */
2406 empty_duration = e->duration;
2407 edit_start_index = 1;
2408 } else if (i == edit_start_index && e->time >= 0) {
2409 start_time = e->time;
2414 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
2415 "a/v desync might occur, patch welcome\n");
2417 /* adjust first dts according to edit list */
2418 if ((empty_duration || start_time) && mov->time_scale > 0) {
2420 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
2421 sc->time_offset = start_time - empty_duration;
2422 current_dts = -sc->time_offset;
2423 if (sc->ctts_count>0 && sc->stts_count>0 &&
2424 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2425 /* more than 16 frames delay, dts are likely wrong
2426 this happens with files created by iMovie */
2428 st->codec->has_b_frames = 1;
2433 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2434 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2435 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2436 unsigned int current_sample = 0;
2437 unsigned int stts_sample = 0;
2438 unsigned int sample_size;
2439 unsigned int distance = 0;
2440 unsigned int rap_group_index = 0;
2441 unsigned int rap_group_sample = 0;
2442 int rap_group_present = sc->rap_group_count && sc->rap_group;
2443 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2445 current_dts -= sc->dts_shift;
2447 if (!sc->sample_count || st->nb_index_entries)
2449 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2451 if (av_reallocp_array(&st->index_entries,
2452 st->nb_index_entries + sc->sample_count,
2453 sizeof(*st->index_entries)) < 0) {
2454 st->nb_index_entries = 0;
2457 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2459 for (i = 0; i < sc->chunk_count; i++) {
2460 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2461 current_offset = sc->chunk_offsets[i];
2462 while (stsc_index + 1 < sc->stsc_count &&
2463 i + 1 == sc->stsc_data[stsc_index + 1].first)
2466 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2467 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2468 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2469 sc->stsz_sample_size = sc->sample_size;
2471 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2472 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2473 sc->stsz_sample_size = sc->sample_size;
2476 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2478 if (current_sample >= sc->sample_count) {
2479 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2483 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2485 if (stss_index + 1 < sc->keyframe_count)
2487 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2489 if (stps_index + 1 < sc->stps_count)
2492 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2493 if (sc->rap_group[rap_group_index].index > 0)
2495 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2496 rap_group_sample = 0;
2500 if (sc->keyframe_absent
2502 && !rap_group_present
2503 && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2507 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2508 if (sc->pseudo_stream_id == -1 ||
2509 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2510 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2511 e->pos = current_offset;
2512 e->timestamp = current_dts;
2513 e->size = sample_size;
2514 e->min_distance = distance;
2515 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2516 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2517 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2518 current_offset, current_dts, sample_size, distance, keyframe);
2519 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2520 ff_rfps_add_frame(mov->fc, st, current_dts);
2523 current_offset += sample_size;
2524 stream_size += sample_size;
2525 current_dts += sc->stts_data[stts_index].duration;
2529 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2535 if (st->duration > 0)
2536 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2538 unsigned chunk_samples, total = 0;
2540 // compute total chunk count
2541 for (i = 0; i < sc->stsc_count; i++) {
2542 unsigned count, chunk_count;
2544 chunk_samples = sc->stsc_data[i].count;
2545 if (i != sc->stsc_count - 1 &&
2546 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2547 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2551 if (sc->samples_per_frame >= 160) { // gsm
2552 count = chunk_samples / sc->samples_per_frame;
2553 } else if (sc->samples_per_frame > 1) {
2554 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2555 count = (chunk_samples+samples-1) / samples;
2557 count = (chunk_samples+1023) / 1024;
2560 if (i < sc->stsc_count - 1)
2561 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2563 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2564 total += chunk_count * count;
2567 av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2568 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2570 if (av_reallocp_array(&st->index_entries,
2571 st->nb_index_entries + total,
2572 sizeof(*st->index_entries)) < 0) {
2573 st->nb_index_entries = 0;
2576 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2579 for (i = 0; i < sc->chunk_count; i++) {
2580 current_offset = sc->chunk_offsets[i];
2581 if (stsc_index + 1 < sc->stsc_count &&
2582 i + 1 == sc->stsc_data[stsc_index + 1].first)
2584 chunk_samples = sc->stsc_data[stsc_index].count;
2586 while (chunk_samples > 0) {
2588 unsigned size, samples;
2590 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2591 avpriv_request_sample(mov->fc,
2592 "Zero bytes per frame, but %d samples per frame",
2593 sc->samples_per_frame);
2597 if (sc->samples_per_frame >= 160) { // gsm
2598 samples = sc->samples_per_frame;
2599 size = sc->bytes_per_frame;
2601 if (sc->samples_per_frame > 1) {
2602 samples = FFMIN((1024 / sc->samples_per_frame)*
2603 sc->samples_per_frame, chunk_samples);
2604 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2606 samples = FFMIN(1024, chunk_samples);
2607 size = samples * sc->sample_size;
2611 if (st->nb_index_entries >= total) {
2612 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2615 e = &st->index_entries[st->nb_index_entries++];
2616 e->pos = current_offset;
2617 e->timestamp = current_dts;
2619 e->min_distance = 0;
2620 e->flags = AVINDEX_KEYFRAME;
2621 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2622 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2625 current_offset += size;
2626 current_dts += samples;
2627 chunk_samples -= samples;
2633 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref,
2634 AVIOInterruptCB *int_cb)
2636 AVOpenCallback open_func = c->fc->open_cb;
2639 open_func = ffio_open2_wrapper;
2641 /* try relative path, we do not try the absolute because it can leak information about our
2642 system to an attacker */
2643 if (ref->nlvl_to > 0 && ref->nlvl_from > 0 && ref->path[0] != '/') {
2644 char filename[1025];
2645 const char *src_path;
2648 /* find a source dir */
2649 src_path = strrchr(src, '/');
2655 /* find a next level down to target */
2656 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2657 if (ref->path[l] == '/') {
2658 if (i == ref->nlvl_to - 1)
2664 /* compose filename if next level down to target was found */
2665 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2666 memcpy(filename, src, src_path - src);
2667 filename[src_path - src] = 0;
2669 for (i = 1; i < ref->nlvl_from; i++)
2670 av_strlcat(filename, "../", sizeof(filename));
2672 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
2673 if (!c->use_absolute_path && !c->fc->open_cb)
2674 if(strstr(ref->path + l + 1, "..") || ref->nlvl_from > 1)
2675 return AVERROR(ENOENT);
2677 if (strlen(filename) + 1 == sizeof(filename))
2678 return AVERROR(ENOENT);
2679 if (!open_func(c->fc, pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2682 } else if (c->use_absolute_path) {
2683 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
2684 "this is a possible security issue\n");
2685 if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2687 } else if (c->fc->open_cb) {
2688 if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2691 av_log(c->fc, AV_LOG_ERROR,
2692 "Absolute path %s not tried for security reasons, "
2693 "set demuxer option use_absolute_path to allow absolute paths\n",
2697 return AVERROR(ENOENT);
2700 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2702 if (sc->time_scale <= 0) {
2703 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2704 sc->time_scale = c->time_scale;
2705 if (sc->time_scale <= 0)
2710 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2713 MOVStreamContext *sc;
2716 st = avformat_new_stream(c->fc, NULL);
2717 if (!st) return AVERROR(ENOMEM);
2718 st->id = c->fc->nb_streams;
2719 sc = av_mallocz(sizeof(MOVStreamContext));
2720 if (!sc) return AVERROR(ENOMEM);
2723 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2724 sc->ffindex = st->index;
2726 if ((ret = mov_read_default(c, pb, atom)) < 0)
2730 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2731 (!sc->sample_size && !sc->sample_count))) {
2732 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2737 fix_timescale(c, sc);
2739 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2741 mov_build_index(c, st);
2743 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2744 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2745 if (mov_open_dref(c, &sc->pb, c->fc->filename, dref,
2746 &c->fc->interrupt_callback) < 0)
2747 av_log(c->fc, AV_LOG_ERROR,
2748 "stream %d, error opening alias: path='%s', dir='%s', "
2749 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2750 st->index, dref->path, dref->dir, dref->filename,
2751 dref->volume, dref->nlvl_from, dref->nlvl_to);
2754 sc->pb_is_copied = 1;
2757 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2758 if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&
2759 sc->height && sc->width &&
2760 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2761 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2762 ((double)st->codec->width * sc->height), INT_MAX);
2765 #if FF_API_R_FRAME_RATE
2766 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2767 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2768 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2772 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2773 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2774 TAG_IS_AVCI(st->codec->codec_tag)) {
2775 ret = ff_generate_avci_extradata(st);
2780 switch (st->codec->codec_id) {
2781 #if CONFIG_H261_DECODER
2782 case AV_CODEC_ID_H261:
2784 #if CONFIG_H263_DECODER
2785 case AV_CODEC_ID_H263:
2787 #if CONFIG_MPEG4_DECODER
2788 case AV_CODEC_ID_MPEG4:
2790 st->codec->width = 0; /* let decoder init width/height */
2791 st->codec->height= 0;
2795 /* Do not need those anymore. */
2796 av_freep(&sc->chunk_offsets);
2797 av_freep(&sc->stsc_data);
2798 av_freep(&sc->sample_sizes);
2799 av_freep(&sc->keyframes);
2800 av_freep(&sc->stts_data);
2801 av_freep(&sc->stps_data);
2802 av_freep(&sc->elst_data);
2803 av_freep(&sc->rap_group);
2808 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2811 c->itunes_metadata = 1;
2812 ret = mov_read_default(c, pb, atom);
2813 c->itunes_metadata = 0;
2817 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
2819 int64_t end = avio_tell(pb) + size;
2820 uint8_t *key = NULL, *val = NULL;
2823 MOVStreamContext *sc;
2825 if (c->fc->nb_streams < 1)
2827 st = c->fc->streams[c->fc->nb_streams-1];
2830 for (i = 0; i < 2; i++) {
2834 if (end - avio_tell(pb) <= 12)
2837 len = avio_rb32(pb);
2838 tag = avio_rl32(pb);
2839 avio_skip(pb, 4); // flags
2841 if (len < 12 || len - 12 > end - avio_tell(pb))
2845 if (tag == MKTAG('n', 'a', 'm', 'e'))
2847 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2854 *p = av_malloc(len + 1);
2857 if (avio_read(pb, *p, len) != len) {
2859 return AVERROR_INVALIDDATA;
2865 if (strcmp(key, "iTunSMPB") == 0) {
2866 int priming, remainder, samples;
2867 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
2868 if(priming>0 && priming<16384)
2869 sc->start_pad = priming;
2872 if (strcmp(key, "cdec") != 0) {
2873 av_dict_set(&c->fc->metadata, key, val,
2874 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2879 avio_seek(pb, end, SEEK_SET);
2885 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2887 int64_t end = avio_tell(pb) + atom.size;
2893 len = avio_rb32(pb);
2894 tag = avio_rl32(pb);
2896 if (len > atom.size)
2899 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2900 uint8_t domain[128];
2903 avio_skip(pb, 4); // flags
2906 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2907 avio_skip(pb, len - domain_len);
2908 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
2912 av_log(c->fc, AV_LOG_VERBOSE,
2913 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2917 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2919 while (atom.size > 8) {
2920 uint32_t tag = avio_rl32(pb);
2922 if (tag == MKTAG('h','d','l','r')) {
2923 avio_seek(pb, -8, SEEK_CUR);
2925 return mov_read_default(c, pb, atom);
2931 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2936 int display_matrix[3][3];
2938 MOVStreamContext *sc;
2942 if (c->fc->nb_streams < 1)
2944 st = c->fc->streams[c->fc->nb_streams-1];
2947 version = avio_r8(pb);
2948 flags = avio_rb24(pb);
2949 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2955 avio_rb32(pb); /* creation time */
2956 avio_rb32(pb); /* modification time */
2958 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2959 avio_rb32(pb); /* reserved */
2961 /* highlevel (considering edits) duration in movie timebase */
2962 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2963 avio_rb32(pb); /* reserved */
2964 avio_rb32(pb); /* reserved */
2966 avio_rb16(pb); /* layer */
2967 avio_rb16(pb); /* alternate group */
2968 avio_rb16(pb); /* volume */
2969 avio_rb16(pb); /* reserved */
2971 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2972 // they're kept in fixed point format through all calculations
2973 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2974 // side data, but the scale factor is not needed to calculate aspect ratio
2975 for (i = 0; i < 3; i++) {
2976 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2977 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2978 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2981 width = avio_rb32(pb); // 16.16 fixed point track width
2982 height = avio_rb32(pb); // 16.16 fixed point track height
2983 sc->width = width >> 16;
2984 sc->height = height >> 16;
2986 // save the matrix and add rotate metadata when it is not the default
2988 if (display_matrix[0][0] != (1 << 16) ||
2989 display_matrix[1][1] != (1 << 16) ||
2990 display_matrix[2][2] != (1 << 30) ||
2991 display_matrix[0][1] || display_matrix[0][2] ||
2992 display_matrix[1][0] || display_matrix[1][2] ||
2993 display_matrix[2][0] || display_matrix[2][1]) {
2997 av_freep(&sc->display_matrix);
2998 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2999 if (!sc->display_matrix)
3000 return AVERROR(ENOMEM);
3002 for (i = 0; i < 3; i++)
3003 for (j = 0; j < 3; j++)
3004 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
3006 rotate = av_display_rotation_get(sc->display_matrix);
3007 if (!isnan(rotate)) {
3008 char rotate_buf[64];
3010 if (rotate < 0) // for backward compatibility
3012 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
3013 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
3017 // transform the display width/height according to the matrix
3018 // to keep the same scale, use [width height 1<<16]
3019 if (width && height && sc->display_matrix) {
3020 double disp_transform[2];
3022 #define SQR(a) ((a)*(double)(a))
3023 for (i = 0; i < 2; i++)
3024 disp_transform[i] = sqrt(SQR(display_matrix[i][0]) + SQR(display_matrix[i][1]));
3026 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
3027 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
3028 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
3029 st->sample_aspect_ratio = av_d2q(
3030 disp_transform[0] / disp_transform[1],
3036 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3038 MOVFragment *frag = &c->fragment;
3039 MOVTrackExt *trex = NULL;
3040 MOVFragmentIndex* index = NULL;
3041 int flags, track_id, i;
3043 avio_r8(pb); /* version */
3044 flags = avio_rb24(pb);
3046 track_id = avio_rb32(pb);
3048 return AVERROR_INVALIDDATA;
3049 frag->track_id = track_id;
3050 for (i = 0; i < c->trex_count; i++)
3051 if (c->trex_data[i].track_id == frag->track_id) {
3052 trex = &c->trex_data[i];
3056 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
3057 return AVERROR_INVALIDDATA;
3059 for (i = 0; i < c->fragment_index_count; i++) {
3060 MOVFragmentIndex* candidate = c->fragment_index_data[i];
3061 if (candidate->track_id == frag->track_id) {
3062 av_log(c->fc, AV_LOG_DEBUG,
3063 "found fragment index for track %u\n", frag->track_id);
3069 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
3070 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
3071 frag->moof_offset : frag->implicit_offset;
3072 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
3074 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
3075 avio_rb32(pb) : trex->duration;
3076 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
3077 avio_rb32(pb) : trex->size;
3078 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
3079 avio_rb32(pb) : trex->flags;
3080 frag->time = AV_NOPTS_VALUE;
3083 for (i = index->current_item; i < index->item_count; i++) {
3084 if (frag->implicit_offset == index->items[i].moof_offset) {
3085 av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
3086 "for track %u and moof_offset %"PRId64"\n",
3087 frag->track_id, index->items[i].moof_offset);
3088 frag->time = index->items[i].time;
3089 index->current_item = i + 1;
3094 av_log(c->fc, AV_LOG_WARNING, "track %u has a fragment index "
3095 "but it doesn't have an (in-order) entry for moof_offset "
3096 "%"PRId64"\n", frag->track_id, frag->implicit_offset);
3099 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
3103 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3105 c->chapter_track = avio_rb32(pb);
3109 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3114 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
3115 return AVERROR_INVALIDDATA;
3116 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
3117 sizeof(*c->trex_data))) < 0) {
3122 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
3124 trex = &c->trex_data[c->trex_count++];
3125 avio_r8(pb); /* version */
3126 avio_rb24(pb); /* flags */
3127 trex->track_id = avio_rb32(pb);
3128 trex->stsd_id = avio_rb32(pb);
3129 trex->duration = avio_rb32(pb);
3130 trex->size = avio_rb32(pb);
3131 trex->flags = avio_rb32(pb);
3135 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3137 MOVFragment *frag = &c->fragment;
3138 AVStream *st = NULL;
3139 MOVStreamContext *sc;
3142 for (i = 0; i < c->fc->nb_streams; i++) {
3143 if (c->fc->streams[i]->id == frag->track_id) {
3144 st = c->fc->streams[i];
3149 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3150 return AVERROR_INVALIDDATA;
3153 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
3155 version = avio_r8(pb);
3156 avio_rb24(pb); /* flags */
3158 sc->track_end = avio_rb64(pb);
3160 sc->track_end = avio_rb32(pb);
3165 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3167 MOVFragment *frag = &c->fragment;
3168 AVStream *st = NULL;
3169 MOVStreamContext *sc;
3173 int data_offset = 0;
3174 unsigned entries, first_sample_flags = frag->flags;
3175 int flags, distance, i, found_keyframe = 0, err;
3177 for (i = 0; i < c->fc->nb_streams; i++) {
3178 if (c->fc->streams[i]->id == frag->track_id) {
3179 st = c->fc->streams[i];
3184 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3185 return AVERROR_INVALIDDATA;
3188 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3190 avio_r8(pb); /* version */
3191 flags = avio_rb24(pb);
3192 entries = avio_rb32(pb);
3193 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
3195 /* Always assume the presence of composition time offsets.
3196 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3197 * 1) in the initial movie, there are no samples.
3198 * 2) in the first movie fragment, there is only one sample without composition time offset.
3199 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
3200 if (!sc->ctts_count && sc->sample_count)
3202 /* Complement ctts table if moov atom doesn't have ctts atom. */
3203 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3205 return AVERROR(ENOMEM);
3206 sc->ctts_data = ctts_data;
3207 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3208 sc->ctts_data[sc->ctts_count].duration = 0;
3211 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3212 return AVERROR_INVALIDDATA;
3213 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3214 sizeof(*sc->ctts_data))) < 0) {
3218 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
3219 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3220 dts = sc->track_end - sc->time_offset;
3221 offset = frag->base_data_offset + data_offset;
3223 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3224 for (i = 0; i < entries && !pb->eof_reached; i++) {
3225 unsigned sample_size = frag->size;
3226 int sample_flags = i ? frag->flags : first_sample_flags;
3227 unsigned sample_duration = frag->duration;
3230 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3231 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
3232 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
3233 sc->ctts_data[sc->ctts_count].count = 1;
3234 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3236 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
3237 if (frag->time != AV_NOPTS_VALUE) {
3238 if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3239 int64_t pts = frag->time;
3240 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3241 " sc->dts_shift %d ctts.duration %d"
3242 " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3243 sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3244 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3245 dts = pts - sc->dts_shift;
3246 if (flags & MOV_TRUN_SAMPLE_CTS) {
3247 dts -= sc->ctts_data[sc->ctts_count].duration;
3249 dts -= sc->time_offset;
3251 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3254 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3255 ", using it for dts\n", dts);
3257 frag->time = AV_NOPTS_VALUE;
3260 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3262 else if (!found_keyframe)
3263 keyframe = found_keyframe =
3264 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3265 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3268 err = av_add_index_entry(st, offset, dts, sample_size, distance,
3269 keyframe ? AVINDEX_KEYFRAME : 0);
3271 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
3273 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3274 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3275 offset, dts, sample_size, distance, keyframe);
3277 dts += sample_duration;
3278 offset += sample_size;
3279 sc->data_size += sample_size;
3280 sc->duration_for_fps += sample_duration;
3281 sc->nb_frames_for_fps ++;
3284 if (pb->eof_reached)
3287 frag->implicit_offset = offset;
3288 st->duration = sc->track_end = dts + sc->time_offset;
3292 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3293 /* like the files created with Adobe Premiere 5.0, for samples see */
3294 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3295 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3300 return 0; /* continue */
3301 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3302 avio_skip(pb, atom.size - 4);
3305 atom.type = avio_rl32(pb);
3307 if (atom.type != MKTAG('m','d','a','t')) {
3308 avio_skip(pb, atom.size);
3311 err = mov_read_mdat(c, pb, atom);
3315 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3320 uint8_t *moov_data; /* uncompressed data */
3321 long cmov_len, moov_len;
3324 avio_rb32(pb); /* dcom atom */
3325 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3326 return AVERROR_INVALIDDATA;
3327 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3328 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3329 return AVERROR_INVALIDDATA;
3331 avio_rb32(pb); /* cmvd atom */
3332 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3333 return AVERROR_INVALIDDATA;
3334 moov_len = avio_rb32(pb); /* uncompressed size */
3335 cmov_len = atom.size - 6 * 4;
3337 cmov_data = av_malloc(cmov_len);
3339 return AVERROR(ENOMEM);
3340 moov_data = av_malloc(moov_len);
3343 return AVERROR(ENOMEM);
3345 if (avio_read(pb, cmov_data, cmov_len) != cmov_len) {
3346 av_freep(&cmov_data);
3347 av_freep(&moov_data);
3348 return AVERROR_INVALIDDATA;
3350 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3351 goto free_and_return;
3352 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3353 goto free_and_return;
3354 ctx.seekable = AVIO_SEEKABLE_NORMAL;
3355 atom.type = MKTAG('m','o','o','v');
3356 atom.size = moov_len;
3357 ret = mov_read_default(c, &ctx, atom);
3363 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3364 return AVERROR(ENOSYS);
3368 /* edit list atom */
3369 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3371 MOVStreamContext *sc;
3372 int i, edit_count, version;
3374 if (c->fc->nb_streams < 1 || c->ignore_editlist)
3376 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3378 version = avio_r8(pb); /* version */
3379 avio_rb24(pb); /* flags */
3380 edit_count = avio_rb32(pb); /* entries */
3385 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
3386 av_free(sc->elst_data);
3388 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
3390 return AVERROR(ENOMEM);
3392 av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3393 for (i = 0; i < edit_count && !pb->eof_reached; i++) {
3394 MOVElst *e = &sc->elst_data[i];
3397 e->duration = avio_rb64(pb);
3398 e->time = avio_rb64(pb);
3400 e->duration = avio_rb32(pb); /* segment duration */
3401 e->time = (int32_t)avio_rb32(pb); /* media time */
3403 e->rate = avio_rb32(pb) / 65536.0;
3404 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3405 e->duration, e->time, e->rate);
3412 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3414 MOVStreamContext *sc;
3416 if (c->fc->nb_streams < 1)
3417 return AVERROR_INVALIDDATA;
3418 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3419 sc->timecode_track = avio_rb32(pb);
3423 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3427 static const uint8_t uuid_isml_manifest[] = {
3428 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3429 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3432 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3433 return AVERROR_INVALIDDATA;
3435 ret = avio_read(pb, uuid, sizeof(uuid));
3438 } else if (ret != sizeof(uuid)) {
3439 return AVERROR_INVALIDDATA;
3441 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3442 uint8_t *buffer, *ptr;
3444 size_t len = atom.size - sizeof(uuid);
3447 return AVERROR_INVALIDDATA;
3449 ret = avio_skip(pb, 4); // zeroes
3452 buffer = av_mallocz(len + 1);
3454 return AVERROR(ENOMEM);
3456 ret = avio_read(pb, buffer, len);
3460 } else if (ret != len) {
3462 return AVERROR_INVALIDDATA;
3466 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
3467 ptr += sizeof("systemBitrate=\"") - 1;
3468 c->bitrates_count++;
3469 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3471 c->bitrates_count = 0;
3473 return AVERROR(ENOMEM);
3476 ret = strtol(ptr, &endptr, 10);
3477 if (ret < 0 || errno || *endptr != '"') {
3478 c->bitrates[c->bitrates_count - 1] = 0;
3480 c->bitrates[c->bitrates_count - 1] = ret;
3489 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3492 uint8_t content[16];
3497 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
3503 && !memcmp(content, "Anevia\x1A\x1A", 8)
3504 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
3505 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
3511 static const MOVParseTableEntry mov_default_parse_table[] = {
3512 { MKTAG('A','C','L','R'), mov_read_aclr },
3513 { MKTAG('A','P','R','G'), mov_read_avid },
3514 { MKTAG('A','A','L','P'), mov_read_avid },
3515 { MKTAG('A','R','E','S'), mov_read_ares },
3516 { MKTAG('a','v','s','s'), mov_read_avss },
3517 { MKTAG('c','h','p','l'), mov_read_chpl },
3518 { MKTAG('c','o','6','4'), mov_read_stco },
3519 { MKTAG('c','o','l','r'), mov_read_colr },
3520 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3521 { MKTAG('d','i','n','f'), mov_read_default },
3522 { MKTAG('D','p','x','E'), mov_read_dpxe },
3523 { MKTAG('d','r','e','f'), mov_read_dref },
3524 { MKTAG('e','d','t','s'), mov_read_default },
3525 { MKTAG('e','l','s','t'), mov_read_elst },
3526 { MKTAG('e','n','d','a'), mov_read_enda },
3527 { MKTAG('f','i','e','l'), mov_read_fiel },
3528 { MKTAG('f','t','y','p'), mov_read_ftyp },
3529 { MKTAG('g','l','b','l'), mov_read_glbl },
3530 { MKTAG('h','d','l','r'), mov_read_hdlr },
3531 { MKTAG('i','l','s','t'), mov_read_ilst },
3532 { MKTAG('j','p','2','h'), mov_read_jp2h },
3533 { MKTAG('m','d','a','t'), mov_read_mdat },
3534 { MKTAG('m','d','h','d'), mov_read_mdhd },
3535 { MKTAG('m','d','i','a'), mov_read_default },
3536 { MKTAG('m','e','t','a'), mov_read_meta },
3537 { MKTAG('m','i','n','f'), mov_read_default },
3538 { MKTAG('m','o','o','f'), mov_read_moof },
3539 { MKTAG('m','o','o','v'), mov_read_moov },
3540 { MKTAG('m','v','e','x'), mov_read_default },
3541 { MKTAG('m','v','h','d'), mov_read_mvhd },
3542 { MKTAG('S','M','I',' '), mov_read_svq3 },
3543 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
3544 { MKTAG('a','v','c','C'), mov_read_glbl },
3545 { MKTAG('p','a','s','p'), mov_read_pasp },
3546 { MKTAG('s','t','b','l'), mov_read_default },
3547 { MKTAG('s','t','c','o'), mov_read_stco },
3548 { MKTAG('s','t','p','s'), mov_read_stps },
3549 { MKTAG('s','t','r','f'), mov_read_strf },
3550 { MKTAG('s','t','s','c'), mov_read_stsc },
3551 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3552 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3553 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3554 { MKTAG('s','t','t','s'), mov_read_stts },
3555 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3556 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3557 { MKTAG('t','f','d','t'), mov_read_tfdt },
3558 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3559 { MKTAG('t','r','a','k'), mov_read_trak },
3560 { MKTAG('t','r','a','f'), mov_read_default },
3561 { MKTAG('t','r','e','f'), mov_read_default },
3562 { MKTAG('t','m','c','d'), mov_read_tmcd },
3563 { MKTAG('c','h','a','p'), mov_read_chap },
3564 { MKTAG('t','r','e','x'), mov_read_trex },
3565 { MKTAG('t','r','u','n'), mov_read_trun },
3566 { MKTAG('u','d','t','a'), mov_read_default },
3567 { MKTAG('w','a','v','e'), mov_read_wave },
3568 { MKTAG('e','s','d','s'), mov_read_esds },
3569 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3570 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3571 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3572 { MKTAG('w','f','e','x'), mov_read_wfex },
3573 { MKTAG('c','m','o','v'), mov_read_cmov },
3574 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3575 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3576 { MKTAG('s','b','g','p'), mov_read_sbgp },
3577 { MKTAG('h','v','c','C'), mov_read_glbl },
3578 { MKTAG('u','u','i','d'), mov_read_uuid },
3579 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
3580 { MKTAG('f','r','e','e'), mov_read_free },
3581 { MKTAG('-','-','-','-'), mov_read_custom },
3585 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3587 int64_t total_size = 0;
3591 if (c->atom_depth > 10) {
3592 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
3593 return AVERROR_INVALIDDATA;
3598 atom.size = INT64_MAX;
3599 while (total_size + 8 <= atom.size && !avio_feof(pb)) {
3600 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3603 if (atom.size >= 8) {
3604 a.size = avio_rb32(pb);
3605 a.type = avio_rl32(pb);
3606 if (a.type == MKTAG('f','r','e','e') &&
3610 uint32_t *type = (uint32_t *)buf + 1;
3611 if (avio_read(pb, buf, 8) != 8)
3612 return AVERROR_INVALIDDATA;
3613 avio_seek(pb, -8, SEEK_CUR);
3614 if (*type == MKTAG('m','v','h','d') ||
3615 *type == MKTAG('c','m','o','v')) {
3616 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
3617 a.type = MKTAG('m','o','o','v');
3620 if (atom.type != MKTAG('r','o','o','t') &&
3621 atom.type != MKTAG('m','o','o','v'))
3623 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
3625 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
3632 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
3633 a.size = avio_rb64(pb) - 8;
3637 av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3638 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3640 a.size = atom.size - total_size + 8;
3645 a.size = FFMIN(a.size, atom.size - total_size);
3647 for (i = 0; mov_default_parse_table[i].type; i++)
3648 if (mov_default_parse_table[i].type == a.type) {
3649 parse = mov_default_parse_table[i].parse;
3653 // container is user data
3654 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3655 atom.type == MKTAG('i','l','s','t')))
3656 parse = mov_read_udta_string;
3658 if (!parse) { /* skip leaf atoms data */
3659 avio_skip(pb, a.size);
3661 int64_t start_pos = avio_tell(pb);
3663 int err = parse(c, pb, a);
3668 if (c->found_moov && c->found_mdat &&
3669 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3670 start_pos + a.size == avio_size(pb))) {
3671 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3672 c->next_root_atom = start_pos + a.size;
3676 left = a.size - avio_tell(pb) + start_pos;
3677 if (left > 0) /* skip garbage at atom end */
3678 avio_skip(pb, left);
3679 else if (left < 0) {
3680 av_log(c->fc, AV_LOG_WARNING,
3681 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3682 (char*)&a.type, -left);
3683 avio_seek(pb, left, SEEK_CUR);
3687 total_size += a.size;
3690 if (total_size < atom.size && atom.size < 0x7ffff)
3691 avio_skip(pb, atom.size - total_size);
3697 static int mov_probe(AVProbeData *p)
3702 int moov_offset = -1;
3704 /* check file header */
3707 /* ignore invalid offset */
3708 if ((offset + 8) > (unsigned int)p->buf_size)
3710 tag = AV_RL32(p->buf + offset + 4);
3712 /* check for obvious tags */
3713 case MKTAG('m','o','o','v'):
3714 moov_offset = offset + 4;
3715 case MKTAG('m','d','a','t'):
3716 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3717 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3718 case MKTAG('f','t','y','p'):
3719 if (AV_RB32(p->buf+offset) < 8 &&
3720 (AV_RB32(p->buf+offset) != 1 ||
3721 offset + 12 > (unsigned int)p->buf_size ||
3722 AV_RB64(p->buf+offset + 8) == 0)) {
3723 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3724 } else if (tag == MKTAG('f','t','y','p') &&
3725 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
3726 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
3728 score = FFMAX(score, 5);
3730 score = AVPROBE_SCORE_MAX;
3732 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3734 /* those are more common words, so rate then a bit less */
3735 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3736 case MKTAG('w','i','d','e'):
3737 case MKTAG('f','r','e','e'):
3738 case MKTAG('j','u','n','k'):
3739 case MKTAG('p','i','c','t'):
3740 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
3741 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3743 case MKTAG(0x82,0x82,0x7f,0x7d):
3744 case MKTAG('s','k','i','p'):
3745 case MKTAG('u','u','i','d'):
3746 case MKTAG('p','r','f','l'):
3747 /* if we only find those cause probedata is too small at least rate them */
3748 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3749 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3752 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3755 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
3756 /* moov atom in the header - we should make sure that this is not a
3757 * MOV-packed MPEG-PS */
3758 offset = moov_offset;
3760 while(offset < (p->buf_size - 16)){ /* Sufficient space */
3761 /* We found an actual hdlr atom */
3762 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
3763 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
3764 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
3765 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
3766 /* We found a media handler reference atom describing an
3767 * MPEG-PS-in-MOV, return a
3768 * low score to force expanding the probe window until
3769 * mpegps_probe finds what it needs */
3780 // must be done after parsing all trak because there's no order requirement
3781 static void mov_read_chapters(AVFormatContext *s)
3783 MOVContext *mov = s->priv_data;
3784 AVStream *st = NULL;
3785 MOVStreamContext *sc;
3789 for (i = 0; i < s->nb_streams; i++)
3790 if (s->streams[i]->id == mov->chapter_track) {
3795 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3799 st->discard = AVDISCARD_ALL;
3801 cur_pos = avio_tell(sc->pb);
3803 for (i = 0; i < st->nb_index_entries; i++) {
3804 AVIndexEntry *sample = &st->index_entries[i];
3805 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3810 if (end < sample->timestamp) {
3811 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
3812 end = AV_NOPTS_VALUE;
3815 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3816 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3820 // the first two bytes are the length of the title
3821 len = avio_rb16(sc->pb);
3822 if (len > sample->size-2)
3824 title_len = 2*len + 1;
3825 if (!(title = av_mallocz(title_len)))
3828 // The samples could theoretically be in any encoding if there's an encd
3829 // atom following, but in practice are only utf-8 or utf-16, distinguished
3830 // instead by the presence of a BOM
3834 ch = avio_rb16(sc->pb);
3836 avio_get_str16be(sc->pb, len, title, title_len);
3837 else if (ch == 0xfffe)
3838 avio_get_str16le(sc->pb, len, title, title_len);
3841 if (len == 1 || len == 2)
3844 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3848 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3852 avio_seek(sc->pb, cur_pos, SEEK_SET);
3855 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
3856 uint32_t value, int flags)
3859 char buf[AV_TIMECODE_STR_SIZE];
3860 AVRational rate = {st->codec->time_base.den,
3861 st->codec->time_base.num};
3862 int ret = av_timecode_init(&tc, rate, flags, 0, s);
3865 av_dict_set(&st->metadata, "timecode",
3866 av_timecode_make_string(&tc, buf, value), 0);
3870 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
3872 MOVStreamContext *sc = st->priv_data;
3874 int64_t cur_pos = avio_tell(sc->pb);
3877 if (!st->nb_index_entries)
3880 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3881 value = avio_rb32(s->pb);
3883 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3884 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3885 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3887 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3888 * not the case) and thus assume "frame number format" instead of QT one.
3889 * No sample with tmcd track can be found with a QT timecode at the moment,
3890 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3892 parse_timecode_in_framenum_format(s, st, value, flags);
3894 avio_seek(sc->pb, cur_pos, SEEK_SET);
3898 static int mov_read_close(AVFormatContext *s)
3900 MOVContext *mov = s->priv_data;
3903 for (i = 0; i < s->nb_streams; i++) {
3904 AVStream *st = s->streams[i];
3905 MOVStreamContext *sc = st->priv_data;
3907 av_freep(&sc->ctts_data);
3908 for (j = 0; j < sc->drefs_count; j++) {
3909 av_freep(&sc->drefs[j].path);
3910 av_freep(&sc->drefs[j].dir);
3912 av_freep(&sc->drefs);
3914 sc->drefs_count = 0;
3916 if (!sc->pb_is_copied)
3917 avio_closep(&sc->pb);
3920 av_freep(&sc->chunk_offsets);
3921 av_freep(&sc->stsc_data);
3922 av_freep(&sc->sample_sizes);
3923 av_freep(&sc->keyframes);
3924 av_freep(&sc->stts_data);
3925 av_freep(&sc->stps_data);
3926 av_freep(&sc->elst_data);
3927 av_freep(&sc->rap_group);
3928 av_freep(&sc->display_matrix);
3931 if (mov->dv_demux) {
3932 avformat_free_context(mov->dv_fctx);
3933 mov->dv_fctx = NULL;
3936 av_freep(&mov->trex_data);
3937 av_freep(&mov->bitrates);
3939 for (i = 0; i < mov->fragment_index_count; i++) {
3940 MOVFragmentIndex* index = mov->fragment_index_data[i];
3941 av_freep(&index->items);
3942 av_freep(&mov->fragment_index_data[i]);
3944 av_freep(&mov->fragment_index_data);
3949 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3953 for (i = 0; i < s->nb_streams; i++) {
3954 AVStream *st = s->streams[i];
3955 MOVStreamContext *sc = st->priv_data;
3957 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3958 sc->timecode_track == tmcd_id)
3964 /* look for a tmcd track not referenced by any video track, and export it globally */
3965 static void export_orphan_timecode(AVFormatContext *s)
3969 for (i = 0; i < s->nb_streams; i++) {
3970 AVStream *st = s->streams[i];
3972 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3973 !tmcd_is_referenced(s, i + 1)) {
3974 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3976 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3983 static int read_tfra(MOVContext *mov, AVIOContext *f)
3985 MOVFragmentIndex* index = NULL;
3986 int version, fieldlength, i, j;
3987 int64_t pos = avio_tell(f);
3988 uint32_t size = avio_rb32(f);
3991 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
3994 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
3995 index = av_mallocz(sizeof(MOVFragmentIndex));
3997 return AVERROR(ENOMEM);
4000 tmp = av_realloc_array(mov->fragment_index_data,
4001 mov->fragment_index_count + 1,
4002 sizeof(MOVFragmentIndex*));
4005 return AVERROR(ENOMEM);
4007 mov->fragment_index_data = tmp;
4008 mov->fragment_index_data[mov->fragment_index_count++] = index;
4010 version = avio_r8(f);
4012 index->track_id = avio_rb32(f);
4013 fieldlength = avio_rb32(f);
4014 index->item_count = avio_rb32(f);
4015 index->items = av_mallocz_array(
4016 index->item_count, sizeof(MOVFragmentIndexItem));
4017 if (!index->items) {
4018 index->item_count = 0;
4019 return AVERROR(ENOMEM);
4021 for (i = 0; i < index->item_count; i++) {
4022 int64_t time, offset;
4024 time = avio_rb64(f);
4025 offset = avio_rb64(f);
4027 time = avio_rb32(f);
4028 offset = avio_rb32(f);
4030 index->items[i].time = time;
4031 index->items[i].moof_offset = offset;
4032 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
4034 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
4036 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
4040 avio_seek(f, pos + size, SEEK_SET);
4044 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
4046 int64_t stream_size = avio_size(f);
4047 int64_t original_pos = avio_tell(f);
4051 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
4055 mfra_size = avio_rb32(f);
4056 if (mfra_size < 0 || mfra_size > stream_size) {
4057 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
4060 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
4064 if (avio_rb32(f) != mfra_size) {
4065 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
4068 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
4069 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
4072 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
4074 ret = read_tfra(c, f);
4080 seek_ret = avio_seek(f, original_pos, SEEK_SET);
4082 av_log(c->fc, AV_LOG_ERROR,
4083 "failed to seek back after looking for mfra\n");
4089 static int mov_read_header(AVFormatContext *s)
4091 MOVContext *mov = s->priv_data;
4092 AVIOContext *pb = s->pb;
4094 MOVAtom atom = { AV_RL32("root") };
4098 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
4100 atom.size = avio_size(pb);
4102 atom.size = INT64_MAX;
4104 /* check MOV header */
4106 if (mov->moov_retry)
4107 avio_seek(pb, 0, SEEK_SET);
4108 if ((err = mov_read_default(mov, pb, atom)) < 0) {
4109 av_log(s, AV_LOG_ERROR, "error reading header\n");
4113 } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
4114 if (!mov->found_moov) {
4115 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
4117 return AVERROR_INVALIDDATA;
4119 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
4122 if (mov->chapter_track > 0)
4123 mov_read_chapters(s);
4124 for (i = 0; i < s->nb_streams; i++)
4125 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
4126 mov_read_timecode_track(s, s->streams[i]);
4129 /* copy timecode metadata from tmcd tracks to the related video streams */
4130 for (i = 0; i < s->nb_streams; i++) {
4131 AVStream *st = s->streams[i];
4132 MOVStreamContext *sc = st->priv_data;
4133 if (sc->timecode_track > 0) {
4134 AVDictionaryEntry *tcr;
4135 int tmcd_st_id = -1;
4137 for (j = 0; j < s->nb_streams; j++)
4138 if (s->streams[j]->id == sc->timecode_track)
4141 if (tmcd_st_id < 0 || tmcd_st_id == i)
4143 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
4145 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
4148 export_orphan_timecode(s);
4150 for (i = 0; i < s->nb_streams; i++) {
4151 AVStream *st = s->streams[i];
4152 MOVStreamContext *sc = st->priv_data;
4153 fix_timescale(mov, sc);
4154 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
4155 st->skip_samples = sc->start_pad;
4157 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
4158 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4159 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
4160 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4161 if (st->codec->width <= 0 || st->codec->height <= 0) {
4162 st->codec->width = sc->width;
4163 st->codec->height = sc->height;
4165 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
4166 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
4172 if (mov->trex_data) {
4173 for (i = 0; i < s->nb_streams; i++) {
4174 AVStream *st = s->streams[i];
4175 MOVStreamContext *sc = st->priv_data;
4176 if (st->duration > 0)
4177 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
4181 if (mov->use_mfra_for > 0) {
4182 for (i = 0; i < s->nb_streams; i++) {
4183 AVStream *st = s->streams[i];
4184 MOVStreamContext *sc = st->priv_data;
4185 if (sc->duration_for_fps > 0) {
4186 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
4187 sc->duration_for_fps;
4192 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
4193 if (mov->bitrates[i]) {
4194 s->streams[i]->codec->bit_rate = mov->bitrates[i];
4198 ff_rfps_calculate(s);
4200 for (i = 0; i < s->nb_streams; i++) {
4201 AVStream *st = s->streams[i];
4202 MOVStreamContext *sc = st->priv_data;
4204 switch (st->codec->codec_type) {
4205 case AVMEDIA_TYPE_AUDIO:
4206 err = ff_replaygain_export(st, s->metadata);
4212 case AVMEDIA_TYPE_VIDEO:
4213 if (sc->display_matrix) {
4214 AVPacketSideData *sd, *tmp;
4216 tmp = av_realloc_array(st->side_data,
4217 st->nb_side_data + 1, sizeof(*tmp));
4219 return AVERROR(ENOMEM);
4221 st->side_data = tmp;
4224 sd = &st->side_data[st->nb_side_data - 1];
4225 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
4226 sd->size = sizeof(int32_t) * 9;
4227 sd->data = (uint8_t*)sc->display_matrix;
4228 sc->display_matrix = NULL;
4237 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
4239 AVIndexEntry *sample = NULL;
4240 int64_t best_dts = INT64_MAX;
4242 for (i = 0; i < s->nb_streams; i++) {
4243 AVStream *avst = s->streams[i];
4244 MOVStreamContext *msc = avst->priv_data;
4245 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
4246 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
4247 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
4248 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
4249 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
4251 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
4252 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
4253 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
4254 sample = current_sample;
4263 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
4265 MOVContext *mov = s->priv_data;
4266 MOVStreamContext *sc;
4267 AVIndexEntry *sample;
4268 AVStream *st = NULL;
4272 sample = mov_find_next_sample(s, &st);
4274 mov->found_mdat = 0;
4275 if (!mov->next_root_atom)
4277 if (avio_seek(s->pb, mov->next_root_atom, SEEK_SET) != mov->next_root_atom) {
4278 av_log(mov->fc, AV_LOG_ERROR, "next root atom offset 0x%"PRIx64": partial file\n", mov->next_root_atom);
4279 return AVERROR_INVALIDDATA;
4281 mov->next_root_atom = 0;
4282 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
4285 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
4289 /* must be done just before reading, to avoid infinite loop on sample */
4290 sc->current_sample++;
4292 if (mov->next_root_atom) {
4293 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
4294 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
4297 if (st->discard != AVDISCARD_ALL) {
4298 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4299 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
4300 sc->ffindex, sample->pos);
4301 return AVERROR_INVALIDDATA;
4303 ret = av_get_packet(sc->pb, pkt, sample->size);
4306 if (sc->has_palette) {
4309 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
4311 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
4313 memcpy(pal, sc->palette, AVPALETTE_SIZE);
4314 sc->has_palette = 0;
4317 #if CONFIG_DV_DEMUXER
4318 if (mov->dv_demux && sc->dv_audio_container) {
4319 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
4320 av_freep(&pkt->data);
4322 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
4329 pkt->stream_index = sc->ffindex;
4330 pkt->dts = sample->timestamp;
4331 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
4332 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
4333 /* update ctts context */
4335 if (sc->ctts_index < sc->ctts_count &&
4336 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
4338 sc->ctts_sample = 0;
4341 pkt->dts = AV_NOPTS_VALUE;
4343 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
4344 st->index_entries[sc->current_sample].timestamp : st->duration;
4345 pkt->duration = next_dts - pkt->dts;
4346 pkt->pts = pkt->dts;
4348 if (st->discard == AVDISCARD_ALL)
4350 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
4351 pkt->pos = sample->pos;
4356 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
4358 MOVStreamContext *sc = st->priv_data;
4359 int sample, time_sample;
4362 sample = av_index_search_timestamp(st, timestamp, flags);
4363 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
4364 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
4366 if (sample < 0) /* not sure what to do */
4367 return AVERROR_INVALIDDATA;
4368 sc->current_sample = sample;
4369 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
4370 /* adjust ctts index */
4371 if (sc->ctts_data) {
4373 for (i = 0; i < sc->ctts_count; i++) {
4374 int next = time_sample + sc->ctts_data[i].count;
4375 if (next > sc->current_sample) {
4377 sc->ctts_sample = sc->current_sample - time_sample;
4386 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
4388 MOVContext *mc = s->priv_data;
4393 if (stream_index >= s->nb_streams)
4394 return AVERROR_INVALIDDATA;
4396 st = s->streams[stream_index];
4397 sample = mov_seek_stream(s, st, sample_time, flags);
4401 if (mc->seek_individually) {
4402 /* adjust seek timestamp to found sample timestamp */
4403 int64_t seek_timestamp = st->index_entries[sample].timestamp;
4405 for (i = 0; i < s->nb_streams; i++) {
4407 MOVStreamContext *sc = s->streams[i]->priv_data;
4409 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
4411 if (stream_index == i)
4414 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
4415 mov_seek_stream(s, st, timestamp, flags);
4418 for (i = 0; i < s->nb_streams; i++) {
4419 MOVStreamContext *sc;
4422 sc->current_sample = 0;
4425 MOVStreamContext *sc;
4426 AVIndexEntry *entry = mov_find_next_sample(s, &st);
4428 return AVERROR_INVALIDDATA;
4430 if (sc->ffindex == stream_index && sc->current_sample == sample)
4432 sc->current_sample++;
4438 #define OFFSET(x) offsetof(MOVContext, x)
4439 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
4440 static const AVOption mov_options[] = {
4441 {"use_absolute_path",
4442 "allow using absolute path when opening alias, this is a possible security issue",
4443 OFFSET(use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
4445 {"seek_streams_individually",
4446 "Seek each stream individually to the to the closest point",
4447 OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
4449 {"ignore_editlist", "", OFFSET(ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
4452 "use mfra for fragment timestamps",
4453 OFFSET(use_mfra_for), FF_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
4454 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
4456 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
4457 FLAGS, "use_mfra_for" },
4458 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
4459 FLAGS, "use_mfra_for" },
4460 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
4461 FLAGS, "use_mfra_for" },
4462 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
4463 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
4464 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
4465 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
4469 static const AVClass mov_class = {
4470 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
4471 .item_name = av_default_item_name,
4472 .option = mov_options,
4473 .version = LIBAVUTIL_VERSION_INT,
4476 AVInputFormat ff_mov_demuxer = {
4477 .name = "mov,mp4,m4a,3gp,3g2,mj2",
4478 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
4479 .priv_class = &mov_class,
4480 .priv_data_size = sizeof(MOVContext),
4481 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
4482 .read_probe = mov_probe,
4483 .read_header = mov_read_header,
4484 .read_packet = mov_read_packet,
4485 .read_close = mov_read_close,
4486 .read_seek = mov_read_seek,
4487 .flags = AVFMT_NO_BYTE_SEEK,