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"
62 /* those functions parse an atom */
63 /* links atom IDs to parse functions */
64 typedef struct MOVParseTableEntry {
66 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
69 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
70 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
72 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
73 unsigned len, const char *key)
77 short current, total = 0;
78 avio_rb16(pb); // unknown
79 current = avio_rb16(pb);
81 total = avio_rb16(pb);
83 snprintf(buf, sizeof(buf), "%d", current);
85 snprintf(buf, sizeof(buf), "%d/%d", current, total);
86 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
87 av_dict_set(&c->fc->metadata, key, buf, 0);
92 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
93 unsigned len, const char *key)
95 /* bypass padding bytes */
100 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
101 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
106 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
107 unsigned len, const char *key)
109 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
110 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
115 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
116 unsigned len, const char *key)
120 avio_r8(pb); // unknown
123 if (genre < 1 || genre > ID3v1_GENRE_MAX)
125 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
126 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
131 static const uint32_t mac_to_unicode[128] = {
132 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
133 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
134 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
135 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
136 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
137 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
138 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
139 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
140 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
141 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
142 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
143 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
144 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
145 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
146 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
147 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
150 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
151 char *dst, int dstlen)
154 char *end = dst+dstlen-1;
157 for (i = 0; i < len; i++) {
158 uint8_t t, c = avio_r8(pb);
159 if (c < 0x80 && p < end)
162 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
168 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
172 MOVStreamContext *sc;
177 case 0xd: id = AV_CODEC_ID_MJPEG; break;
178 case 0xe: id = AV_CODEC_ID_PNG; break;
179 case 0x1b: id = AV_CODEC_ID_BMP; break;
181 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
186 st = avformat_new_stream(c->fc, NULL);
188 return AVERROR(ENOMEM);
189 sc = av_mallocz(sizeof(*sc));
191 return AVERROR(ENOMEM);
194 ret = av_get_packet(pb, &pkt, len);
198 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
200 st->attached_pic = pkt;
201 st->attached_pic.stream_index = st->index;
202 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
204 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
205 st->codec->codec_id = id;
210 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
212 char language[4] = { 0 };
214 uint16_t langcode = 0;
215 double longitude, latitude;
216 const char *key = "location";
218 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4)
219 return AVERROR_INVALIDDATA;
221 avio_skip(pb, 4); // version+flags
222 langcode = avio_rb16(pb);
223 ff_mov_lang_to_iso639(langcode, language);
226 len -= avio_get_str(pb, len, buf, sizeof(buf)); // place name
228 return AVERROR_INVALIDDATA;
229 avio_skip(pb, 1); // role
233 return AVERROR_INVALIDDATA;
234 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
235 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
237 // Try to output in the same format as the ?xyz field
238 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f/", latitude, longitude);
239 if (*language && strcmp(language, "und")) {
241 snprintf(key2, sizeof(key2), "%s-%s", key, language);
242 av_dict_set(&c->fc->metadata, key2, buf, 0);
244 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
245 return av_dict_set(&c->fc->metadata, key, buf, 0);
248 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
251 char key2[32], language[4] = {0};
253 const char *key = NULL;
254 uint16_t langcode = 0;
255 uint32_t data_type = 0, str_size, str_size_alloc;
256 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
260 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
261 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
262 case MKTAG( 'X','M','P','_'):
263 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
264 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
265 case MKTAG( 'a','k','I','D'): key = "account_type";
266 parse = mov_metadata_int8_no_padding; break;
267 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
268 case MKTAG( 'c','a','t','g'): key = "category"; break;
269 case MKTAG( 'c','p','i','l'): key = "compilation";
270 parse = mov_metadata_int8_no_padding; break;
271 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
272 case MKTAG( 'd','e','s','c'): key = "description"; break;
273 case MKTAG( 'd','i','s','k'): key = "disc";
274 parse = mov_metadata_track_or_disc_number; break;
275 case MKTAG( 'e','g','i','d'): key = "episode_uid";
276 parse = mov_metadata_int8_no_padding; break;
277 case MKTAG( 'g','n','r','e'): key = "genre";
278 parse = mov_metadata_gnre; break;
279 case MKTAG( 'h','d','v','d'): key = "hd_video";
280 parse = mov_metadata_int8_no_padding; break;
281 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
282 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
283 case MKTAG( 'l','o','c','i'):
284 return mov_metadata_loci(c, pb, atom.size);
285 case MKTAG( 'p','c','s','t'): key = "podcast";
286 parse = mov_metadata_int8_no_padding; break;
287 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
288 parse = mov_metadata_int8_no_padding; break;
289 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
290 case MKTAG( 'r','t','n','g'): key = "rating";
291 parse = mov_metadata_int8_no_padding; break;
292 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
293 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
294 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
295 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
296 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
297 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
298 case MKTAG( 's','t','i','k'): key = "media_type";
299 parse = mov_metadata_int8_no_padding; break;
300 case MKTAG( 't','r','k','n'): key = "track";
301 parse = mov_metadata_track_or_disc_number; break;
302 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
303 case MKTAG( 't','v','e','s'): key = "episode_sort";
304 parse = mov_metadata_int8_bypass_padding; break;
305 case MKTAG( 't','v','n','n'): key = "network"; break;
306 case MKTAG( 't','v','s','h'): key = "show"; break;
307 case MKTAG( 't','v','s','n'): key = "season_number";
308 parse = mov_metadata_int8_bypass_padding; break;
309 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
310 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
311 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
312 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
313 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
314 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
315 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
316 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
317 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
318 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
319 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
320 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
321 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
322 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
323 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
324 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
325 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
326 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
327 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
328 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
329 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
330 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
331 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
332 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
333 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
334 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
335 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
336 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
337 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
338 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
339 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
340 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
341 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
342 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
343 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
346 if (c->itunes_metadata && atom.size > 8) {
347 int data_size = avio_rb32(pb);
348 int tag = avio_rl32(pb);
349 if (tag == MKTAG('d','a','t','a')) {
350 data_type = avio_rb32(pb); // type
351 avio_rb32(pb); // unknown
352 str_size = data_size - 16;
355 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
356 int ret = mov_read_covr(c, pb, data_type, str_size);
358 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
363 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
364 str_size = avio_rb16(pb); // string length
365 langcode = avio_rb16(pb);
366 ff_mov_lang_to_iso639(langcode, language);
369 str_size = atom.size;
371 if (c->export_all && !key) {
372 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
378 if (atom.size < 0 || str_size >= INT_MAX/2)
379 return AVERROR_INVALIDDATA;
381 // worst-case requirement for output string in case of utf8 coded input
382 str_size_alloc = (raw ? str_size : str_size * 2) + 1;
383 str = av_mallocz(str_size_alloc);
385 return AVERROR(ENOMEM);
388 parse(c, pb, str_size, key);
390 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
391 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
393 int ret = avio_read(pb, str, str_size);
394 if (ret != str_size) {
396 return ret < 0 ? ret : AVERROR_INVALIDDATA;
400 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
401 av_dict_set(&c->fc->metadata, key, str, 0);
402 if (*language && strcmp(language, "und")) {
403 snprintf(key2, sizeof(key2), "%s-%s", key, language);
404 av_dict_set(&c->fc->metadata, key2, str, 0);
407 av_dlog(c->fc, "lang \"%3s\" ", language);
408 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
409 key, str, (char*)&atom.type, str_size_alloc, atom.size);
415 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
418 int i, nb_chapters, str_len, version;
421 if ((atom.size -= 5) < 0)
424 version = avio_r8(pb);
427 avio_rb32(pb); // ???
428 nb_chapters = avio_r8(pb);
430 for (i = 0; i < nb_chapters; i++) {
434 start = avio_rb64(pb);
435 str_len = avio_r8(pb);
437 if ((atom.size -= 9+str_len) < 0)
440 avio_read(pb, str, str_len);
442 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
447 #define MIN_DATA_ENTRY_BOX_SIZE 12
448 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
451 MOVStreamContext *sc;
454 if (c->fc->nb_streams < 1)
456 st = c->fc->streams[c->fc->nb_streams-1];
459 avio_rb32(pb); // version + flags
460 entries = avio_rb32(pb);
461 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
462 entries >= UINT_MAX / sizeof(*sc->drefs))
463 return AVERROR_INVALIDDATA;
466 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
468 return AVERROR(ENOMEM);
469 sc->drefs_count = entries;
471 for (i = 0; i < sc->drefs_count; i++) {
472 MOVDref *dref = &sc->drefs[i];
473 uint32_t size = avio_rb32(pb);
474 int64_t next = avio_tell(pb) + size - 4;
477 return AVERROR_INVALIDDATA;
479 dref->type = avio_rl32(pb);
480 avio_rb32(pb); // version + flags
481 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
483 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
484 /* macintosh alias record */
485 uint16_t volume_len, len;
490 volume_len = avio_r8(pb);
491 volume_len = FFMIN(volume_len, 27);
492 avio_read(pb, dref->volume, 27);
493 dref->volume[volume_len] = 0;
494 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
499 len = FFMIN(len, 63);
500 avio_read(pb, dref->filename, 63);
501 dref->filename[len] = 0;
502 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
506 /* read next level up_from_alias/down_to_target */
507 dref->nlvl_from = avio_rb16(pb);
508 dref->nlvl_to = avio_rb16(pb);
509 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
510 dref->nlvl_from, dref->nlvl_to);
514 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
517 type = avio_rb16(pb);
519 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
522 if (type == 2) { // absolute path
524 dref->path = av_mallocz(len+1);
526 return AVERROR(ENOMEM);
527 avio_read(pb, dref->path, len);
528 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
530 memmove(dref->path, dref->path+volume_len, len);
533 for (j = 0; j < len; j++)
534 if (dref->path[j] == ':')
536 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
537 } else if (type == 0) { // directory name
539 dref->dir = av_malloc(len+1);
541 return AVERROR(ENOMEM);
542 if (avio_read(pb, dref->dir, len) != len)
543 return AVERROR_INVALIDDATA;
545 for (j = 0; j < len; j++)
546 if (dref->dir[j] == ':')
548 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
553 avio_seek(pb, next, SEEK_SET);
558 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
562 uint32_t av_unused ctype;
566 if (c->fc->nb_streams < 1) // meta before first trak
569 st = c->fc->streams[c->fc->nb_streams-1];
571 avio_r8(pb); /* version */
572 avio_rb24(pb); /* flags */
575 ctype = avio_rl32(pb);
576 type = avio_rl32(pb); /* component subtype */
578 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
579 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
581 if (type == MKTAG('v','i','d','e'))
582 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
583 else if (type == MKTAG('s','o','u','n'))
584 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
585 else if (type == MKTAG('m','1','a',' '))
586 st->codec->codec_id = AV_CODEC_ID_MP2;
587 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
588 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
590 avio_rb32(pb); /* component manufacture */
591 avio_rb32(pb); /* component flags */
592 avio_rb32(pb); /* component flags mask */
594 title_size = atom.size - 24;
595 if (title_size > 0) {
596 title_str = av_malloc(title_size + 1); /* Add null terminator */
598 return AVERROR(ENOMEM);
599 avio_read(pb, title_str, title_size);
600 title_str[title_size] = 0;
602 av_dict_set(&st->metadata, "handler_name", title_str +
603 (!c->isom && title_str[0] == title_size - 1), 0);
604 av_freep(&title_str);
610 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
615 if (fc->nb_streams < 1)
617 st = fc->streams[fc->nb_streams-1];
619 avio_rb32(pb); /* version + flags */
620 ff_mp4_read_descr(fc, pb, &tag);
621 if (tag == MP4ESDescrTag) {
622 ff_mp4_parse_es_descr(pb, NULL);
624 avio_rb16(pb); /* ID */
626 ff_mp4_read_descr(fc, pb, &tag);
627 if (tag == MP4DecConfigDescrTag)
628 ff_mp4_read_dec_config_descr(fc, st, pb);
632 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
634 return ff_mov_read_esds(c->fc, pb);
637 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
640 enum AVAudioServiceType *ast;
641 int ac3info, acmod, lfeon, bsmod;
643 if (c->fc->nb_streams < 1)
645 st = c->fc->streams[c->fc->nb_streams-1];
647 ast = (enum AVAudioServiceType*)ff_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
650 return AVERROR(ENOMEM);
652 ac3info = avio_rb24(pb);
653 bsmod = (ac3info >> 14) & 0x7;
654 acmod = (ac3info >> 11) & 0x7;
655 lfeon = (ac3info >> 10) & 0x1;
656 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
657 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
659 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
661 if (st->codec->channels > 1 && bsmod == 0x7)
662 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
664 st->codec->audio_service_type = *ast;
669 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
672 enum AVAudioServiceType *ast;
673 int eac3info, acmod, lfeon, bsmod;
675 if (c->fc->nb_streams < 1)
677 st = c->fc->streams[c->fc->nb_streams-1];
679 ast = (enum AVAudioServiceType*)ff_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
682 return AVERROR(ENOMEM);
684 /* No need to parse fields for additional independent substreams and its
685 * associated dependent substreams since libavcodec's E-AC-3 decoder
686 * does not support them yet. */
687 avio_rb16(pb); /* data_rate and num_ind_sub */
688 eac3info = avio_rb24(pb);
689 bsmod = (eac3info >> 12) & 0x1f;
690 acmod = (eac3info >> 9) & 0x7;
691 lfeon = (eac3info >> 8) & 0x1;
692 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
694 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
695 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
697 if (st->codec->channels > 1 && bsmod == 0x7)
698 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
700 st->codec->audio_service_type = *ast;
705 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
709 if (c->fc->nb_streams < 1)
711 st = c->fc->streams[c->fc->nb_streams-1];
716 /* skip version and flags */
719 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
724 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
729 if (c->fc->nb_streams < 1)
731 st = c->fc->streams[c->fc->nb_streams-1];
733 if ((ret = ff_get_wav_header(pb, st->codec, atom.size, 0)) < 0)
734 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
739 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
741 const int num = avio_rb32(pb);
742 const int den = avio_rb32(pb);
745 if (c->fc->nb_streams < 1)
747 st = c->fc->streams[c->fc->nb_streams-1];
749 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
750 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
751 av_log(c->fc, AV_LOG_WARNING,
752 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
753 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
755 } else if (den != 0) {
756 st->sample_aspect_ratio.num = num;
757 st->sample_aspect_ratio.den = den;
762 /* this atom contains actual media data */
763 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
765 if (atom.size == 0) /* wrong one (MP4) */
768 return 0; /* now go for moov */
771 /* read major brand, minor version and compatible brands and store them as metadata */
772 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
776 char* comp_brands_str;
777 uint8_t type[5] = {0};
779 avio_read(pb, type, 4);
780 if (strcmp(type, "qt "))
782 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
783 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
784 minor_ver = avio_rb32(pb); /* minor version */
785 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
787 comp_brand_size = atom.size - 8;
788 if (comp_brand_size < 0)
789 return AVERROR_INVALIDDATA;
790 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
791 if (!comp_brands_str)
792 return AVERROR(ENOMEM);
793 avio_read(pb, comp_brands_str, comp_brand_size);
794 comp_brands_str[comp_brand_size] = 0;
795 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
796 av_freep(&comp_brands_str);
801 /* this atom should contain all header atoms */
802 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
807 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
808 avio_skip(pb, atom.size);
812 if ((ret = mov_read_default(c, pb, atom)) < 0)
814 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
815 /* so we don't parse the whole file if over a network */
817 return 0; /* now go for mdat */
820 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
822 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
823 c->has_looked_for_mfra = 1;
826 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
828 if ((ret = mov_read_mfra(c, pb)) < 0) {
829 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
830 "read the mfra (may be a live ismv)\n");
833 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
834 "seekable, can not look for mfra\n");
837 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
838 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
839 return mov_read_default(c, pb, atom);
842 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
846 struct tm *ptm, tmbuf;
848 if(time >= 2082844800)
849 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
851 ptm = gmtime_r(&timet, &tmbuf);
853 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
854 av_dict_set(metadata, "creation_time", buffer, 0);
858 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
861 MOVStreamContext *sc;
863 char language[4] = {0};
865 int64_t creation_time;
867 if (c->fc->nb_streams < 1)
869 st = c->fc->streams[c->fc->nb_streams-1];
872 if (sc->time_scale) {
873 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
874 return AVERROR_INVALIDDATA;
877 version = avio_r8(pb);
879 avpriv_request_sample(c->fc, "Version %d", version);
880 return AVERROR_PATCHWELCOME;
882 avio_rb24(pb); /* flags */
884 creation_time = avio_rb64(pb);
887 creation_time = avio_rb32(pb);
888 avio_rb32(pb); /* modification time */
890 mov_metadata_creation_time(&st->metadata, creation_time);
892 sc->time_scale = avio_rb32(pb);
893 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
895 lang = avio_rb16(pb); /* language */
896 if (ff_mov_lang_to_iso639(lang, language))
897 av_dict_set(&st->metadata, "language", language, 0);
898 avio_rb16(pb); /* quality */
903 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
905 int64_t creation_time;
906 int version = avio_r8(pb); /* version */
907 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(&c->fc->metadata, creation_time);
917 c->time_scale = avio_rb32(pb); /* time scale */
919 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
921 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
922 // set the AVCodecContext duration because the duration of individual tracks
924 if (c->time_scale > 0 && !c->trex_data)
925 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
926 avio_rb32(pb); /* preferred scale */
928 avio_rb16(pb); /* preferred volume */
930 avio_skip(pb, 10); /* reserved */
932 avio_skip(pb, 36); /* display matrix */
934 avio_rb32(pb); /* preview time */
935 avio_rb32(pb); /* preview duration */
936 avio_rb32(pb); /* poster time */
937 avio_rb32(pb); /* selection time */
938 avio_rb32(pb); /* selection duration */
939 avio_rb32(pb); /* current time */
940 avio_rb32(pb); /* next track ID */
944 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
949 if (c->fc->nb_streams < 1)
951 st = c->fc->streams[c->fc->nb_streams-1];
953 little_endian = avio_rb16(pb) & 0xFF;
954 av_dlog(c->fc, "enda %d\n", little_endian);
955 if (little_endian == 1) {
956 switch (st->codec->codec_id) {
957 case AV_CODEC_ID_PCM_S24BE:
958 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
960 case AV_CODEC_ID_PCM_S32BE:
961 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
963 case AV_CODEC_ID_PCM_F32BE:
964 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
966 case AV_CODEC_ID_PCM_F64BE:
967 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
976 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
979 char color_parameter_type[5] = { 0 };
980 int color_primaries, color_trc, color_matrix;
982 if (c->fc->nb_streams < 1)
984 st = c->fc->streams[c->fc->nb_streams - 1];
986 avio_read(pb, color_parameter_type, 4);
987 if (strncmp(color_parameter_type, "nclx", 4) &&
988 strncmp(color_parameter_type, "nclc", 4)) {
989 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
990 color_parameter_type);
994 color_primaries = avio_rb16(pb);
995 color_trc = avio_rb16(pb);
996 color_matrix = avio_rb16(pb);
998 av_dlog(c->fc, "%s: pri %d trc %d matrix %d",
999 color_parameter_type, color_primaries, color_trc, color_matrix);
1002 uint8_t color_range = avio_r8(pb) >> 7;
1003 av_dlog(c->fc, " full %"PRIu8"", color_range);
1005 st->codec->color_range = AVCOL_RANGE_JPEG;
1007 st->codec->color_range = AVCOL_RANGE_MPEG;
1008 /* 14496-12 references JPEG XR specs (rather than the more complete
1009 * 23001-8) so some adjusting is required */
1010 if (color_primaries >= AVCOL_PRI_FILM)
1011 color_primaries = AVCOL_PRI_UNSPECIFIED;
1012 if ((color_trc >= AVCOL_TRC_LINEAR &&
1013 color_trc <= AVCOL_TRC_LOG_SQRT) ||
1014 color_trc >= AVCOL_TRC_BT2020_10)
1015 color_trc = AVCOL_TRC_UNSPECIFIED;
1016 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
1017 color_matrix = AVCOL_SPC_UNSPECIFIED;
1018 st->codec->color_primaries = color_primaries;
1019 st->codec->color_trc = color_trc;
1020 st->codec->colorspace = color_matrix;
1022 /* color primaries, Table 4-4 */
1023 switch (color_primaries) {
1024 case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
1025 case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
1026 case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
1028 /* color transfer, Table 4-5 */
1029 switch (color_trc) {
1030 case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
1031 case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
1033 /* color matrix, Table 4-6 */
1034 switch (color_matrix) {
1035 case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
1036 case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
1037 case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
1040 av_dlog(c->fc, "\n");
1045 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1048 unsigned mov_field_order;
1049 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1051 if (c->fc->nb_streams < 1) // will happen with jp2 files
1053 st = c->fc->streams[c->fc->nb_streams-1];
1055 return AVERROR_INVALIDDATA;
1056 mov_field_order = avio_rb16(pb);
1057 if ((mov_field_order & 0xFF00) == 0x0100)
1058 decoded_field_order = AV_FIELD_PROGRESSIVE;
1059 else if ((mov_field_order & 0xFF00) == 0x0200) {
1060 switch (mov_field_order & 0xFF) {
1061 case 0x01: decoded_field_order = AV_FIELD_TT;
1063 case 0x06: decoded_field_order = AV_FIELD_BB;
1065 case 0x09: decoded_field_order = AV_FIELD_TB;
1067 case 0x0E: decoded_field_order = AV_FIELD_BT;
1071 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1072 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1074 st->codec->field_order = decoded_field_order;
1079 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
1080 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1081 enum AVCodecID codec_id)
1088 if (c->fc->nb_streams < 1) // will happen with jp2 files
1090 st= c->fc->streams[c->fc->nb_streams-1];
1092 if (st->codec->codec_id != codec_id)
1093 return 0; /* unexpected codec_id - don't mess with extradata */
1095 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
1096 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1097 return AVERROR_INVALIDDATA;
1098 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
1099 st->codec->extradata_size = 0;
1102 buf = st->codec->extradata + st->codec->extradata_size;
1103 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
1104 AV_WB32( buf , atom.size + 8);
1105 AV_WL32( buf + 4, atom.type);
1106 err = avio_read(pb, buf + 8, atom.size);
1109 } else if (err < atom.size) {
1110 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1111 st->codec->extradata_size -= atom.size - err;
1113 memset(buf + 8 + err, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1117 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1118 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1120 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1123 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1125 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1128 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1130 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1133 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1135 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1138 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1140 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1142 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1146 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1148 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1150 if (!ret && c->fc->nb_streams >= 1) {
1151 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
1152 if (avctx->extradata_size >= 40) {
1153 avctx->height = AV_RB16(&avctx->extradata[36]);
1154 avctx->width = AV_RB16(&avctx->extradata[38]);
1160 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1162 if (c->fc->nb_streams >= 1) {
1163 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1164 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1165 codec->codec_id == AV_CODEC_ID_H264 &&
1168 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1169 if (avio_rb16(pb) == 0xd4d)
1170 codec->width = 1440;
1175 return mov_read_avid(c, pb, atom);
1178 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1180 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1183 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1187 if (c->fc->nb_streams < 1)
1189 st = c->fc->streams[c->fc->nb_streams-1];
1191 if ((uint64_t)atom.size > (1<<30))
1192 return AVERROR_INVALIDDATA;
1194 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1195 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1196 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1197 // pass all frma atom to codec, needed at least for QDMC and QDM2
1198 av_freep(&st->codec->extradata);
1199 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1200 return AVERROR(ENOMEM);
1201 } else if (atom.size > 8) { /* to read frma, esds atoms */
1203 if ((ret = mov_read_default(c, pb, atom)) < 0)
1206 avio_skip(pb, atom.size);
1211 * This function reads atom content and puts data in extradata without tag
1212 * nor size unlike mov_read_extradata.
1214 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1218 if (c->fc->nb_streams < 1)
1220 st = c->fc->streams[c->fc->nb_streams-1];
1222 if ((uint64_t)atom.size > (1<<30))
1223 return AVERROR_INVALIDDATA;
1225 if (atom.size >= 10) {
1226 // Broken files created by legacy versions of libavformat will
1227 // wrap a whole fiel atom inside of a glbl atom.
1228 unsigned size = avio_rb32(pb);
1229 unsigned type = avio_rl32(pb);
1230 avio_seek(pb, -8, SEEK_CUR);
1231 if (type == MKTAG('f','i','e','l') && size == atom.size)
1232 return mov_read_default(c, pb, atom);
1234 if (st->codec->extradata_size > 1 && st->codec->extradata) {
1235 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1238 av_freep(&st->codec->extradata);
1239 if (ff_get_extradata(st->codec, pb, atom.size) < 0)
1240 return AVERROR(ENOMEM);
1245 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1248 uint8_t profile_level;
1251 if (c->fc->nb_streams < 1)
1253 st = c->fc->streams[c->fc->nb_streams-1];
1255 if (atom.size >= (1<<28) || atom.size < 7)
1256 return AVERROR_INVALIDDATA;
1258 profile_level = avio_r8(pb);
1259 if ((profile_level & 0xf0) != 0xc0)
1262 avio_seek(pb, 6, SEEK_CUR);
1263 av_freep(&st->codec->extradata);
1264 if ((ret = ff_get_extradata(st->codec, pb, atom.size - 7)) < 0)
1271 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1272 * but can have extradata appended at the end after the 40 bytes belonging
1275 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1279 if (c->fc->nb_streams < 1)
1281 if (atom.size <= 40)
1283 st = c->fc->streams[c->fc->nb_streams-1];
1285 if ((uint64_t)atom.size > (1<<30))
1286 return AVERROR_INVALIDDATA;
1289 av_freep(&st->codec->extradata);
1290 if (ff_get_extradata(st->codec, pb, atom.size - 40) < 0)
1291 return AVERROR(ENOMEM);
1295 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1298 MOVStreamContext *sc;
1299 unsigned int i, entries;
1301 if (c->fc->nb_streams < 1)
1303 st = c->fc->streams[c->fc->nb_streams-1];
1306 avio_r8(pb); /* version */
1307 avio_rb24(pb); /* flags */
1309 entries = avio_rb32(pb);
1314 if (sc->chunk_offsets)
1315 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1316 av_free(sc->chunk_offsets);
1317 sc->chunk_count = 0;
1318 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1319 if (!sc->chunk_offsets)
1320 return AVERROR(ENOMEM);
1321 sc->chunk_count = entries;
1323 if (atom.type == MKTAG('s','t','c','o'))
1324 for (i = 0; i < entries && !pb->eof_reached; i++)
1325 sc->chunk_offsets[i] = avio_rb32(pb);
1326 else if (atom.type == MKTAG('c','o','6','4'))
1327 for (i = 0; i < entries && !pb->eof_reached; i++)
1328 sc->chunk_offsets[i] = avio_rb64(pb);
1330 return AVERROR_INVALIDDATA;
1332 sc->chunk_count = i;
1334 if (pb->eof_reached)
1341 * Compute codec id for 'lpcm' tag.
1342 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1344 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1351 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1354 static int mov_codec_id(AVStream *st, uint32_t format)
1356 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1359 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1360 (format & 0xFFFF) == 'T' + ('S' << 8)))
1361 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1363 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1364 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1365 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1366 /* skip old asf mpeg4 tag */
1367 format && format != MKTAG('m','p','4','s')) {
1368 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1370 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1372 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1373 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1374 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1375 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1376 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1378 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1382 st->codec->codec_tag = format;
1387 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1388 AVStream *st, MOVStreamContext *sc)
1390 uint8_t codec_name[32];
1391 unsigned int color_depth, len, j;
1392 int color_greyscale;
1395 avio_rb16(pb); /* version */
1396 avio_rb16(pb); /* revision level */
1397 avio_rb32(pb); /* vendor */
1398 avio_rb32(pb); /* temporal quality */
1399 avio_rb32(pb); /* spatial quality */
1401 st->codec->width = avio_rb16(pb); /* width */
1402 st->codec->height = avio_rb16(pb); /* height */
1404 avio_rb32(pb); /* horiz resolution */
1405 avio_rb32(pb); /* vert resolution */
1406 avio_rb32(pb); /* data size, always 0 */
1407 avio_rb16(pb); /* frames per samples */
1409 len = avio_r8(pb); /* codec name, pascal string */
1412 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1414 avio_skip(pb, 31 - len);
1417 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1419 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1420 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1421 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1422 st->codec->width &= ~1;
1423 st->codec->height &= ~1;
1425 /* Flash Media Server uses tag H263 with Sorenson Spark */
1426 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1427 !memcmp(codec_name, "Sorenson H263", 13))
1428 st->codec->codec_id = AV_CODEC_ID_FLV1;
1430 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1431 color_table_id = avio_rb16(pb); /* colortable id */
1432 av_dlog(c->fc, "depth %d, ctab id %d\n",
1433 st->codec->bits_per_coded_sample, color_table_id);
1434 /* figure out the palette situation */
1435 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1436 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1437 /* Do not create a greyscale palette for cinepak */
1438 if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1441 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1442 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1443 /* for palette traversal */
1444 unsigned int color_start, color_count, color_end;
1445 unsigned char a, r, g, b;
1447 if (color_greyscale) {
1448 int color_index, color_dec;
1449 /* compute the greyscale palette */
1450 st->codec->bits_per_coded_sample = color_depth;
1451 color_count = 1 << color_depth;
1453 color_dec = 256 / (color_count - 1);
1454 for (j = 0; j < color_count; j++) {
1455 r = g = b = color_index;
1456 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1457 color_index -= color_dec;
1458 if (color_index < 0)
1461 } else if (color_table_id) {
1462 const uint8_t *color_table;
1463 /* if flag bit 3 is set, use the default palette */
1464 color_count = 1 << color_depth;
1465 if (color_depth == 2)
1466 color_table = ff_qt_default_palette_4;
1467 else if (color_depth == 4)
1468 color_table = ff_qt_default_palette_16;
1470 color_table = ff_qt_default_palette_256;
1472 for (j = 0; j < color_count; j++) {
1473 r = color_table[j * 3 + 0];
1474 g = color_table[j * 3 + 1];
1475 b = color_table[j * 3 + 2];
1476 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1479 /* load the palette from the file */
1480 color_start = avio_rb32(pb);
1481 color_count = avio_rb16(pb);
1482 color_end = avio_rb16(pb);
1483 if ((color_start <= 255) && (color_end <= 255)) {
1484 for (j = color_start; j <= color_end; j++) {
1485 /* each A, R, G, or B component is 16 bits;
1486 * only use the top 8 bits */
1495 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1499 sc->has_palette = 1;
1503 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1504 AVStream *st, MOVStreamContext *sc)
1506 int bits_per_sample, flags;
1507 uint16_t version = avio_rb16(pb);
1508 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1510 avio_rb16(pb); /* revision level */
1511 avio_rb32(pb); /* vendor */
1513 st->codec->channels = avio_rb16(pb); /* channel count */
1514 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1515 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1517 sc->audio_cid = avio_rb16(pb);
1518 avio_rb16(pb); /* packet size = 0 */
1520 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1522 // Read QT version 1 fields. In version 0 these do not exist.
1523 av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
1525 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1528 sc->samples_per_frame = avio_rb32(pb);
1529 avio_rb32(pb); /* bytes per packet */
1530 sc->bytes_per_frame = avio_rb32(pb);
1531 avio_rb32(pb); /* bytes per sample */
1532 } else if (version == 2) {
1533 avio_rb32(pb); /* sizeof struct only */
1534 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1535 st->codec->channels = avio_rb32(pb);
1536 avio_rb32(pb); /* always 0x7F000000 */
1537 st->codec->bits_per_coded_sample = avio_rb32(pb);
1539 flags = avio_rb32(pb); /* lpcm format specific flag */
1540 sc->bytes_per_frame = avio_rb32(pb);
1541 sc->samples_per_frame = avio_rb32(pb);
1542 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1543 st->codec->codec_id =
1544 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1549 switch (st->codec->codec_id) {
1550 case AV_CODEC_ID_PCM_S8:
1551 case AV_CODEC_ID_PCM_U8:
1552 if (st->codec->bits_per_coded_sample == 16)
1553 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1555 case AV_CODEC_ID_PCM_S16LE:
1556 case AV_CODEC_ID_PCM_S16BE:
1557 if (st->codec->bits_per_coded_sample == 8)
1558 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1559 else if (st->codec->bits_per_coded_sample == 24)
1560 st->codec->codec_id =
1561 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1562 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1563 else if (st->codec->bits_per_coded_sample == 32)
1564 st->codec->codec_id =
1565 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1566 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1568 /* set values for old format before stsd version 1 appeared */
1569 case AV_CODEC_ID_MACE3:
1570 sc->samples_per_frame = 6;
1571 sc->bytes_per_frame = 2 * st->codec->channels;
1573 case AV_CODEC_ID_MACE6:
1574 sc->samples_per_frame = 6;
1575 sc->bytes_per_frame = 1 * st->codec->channels;
1577 case AV_CODEC_ID_ADPCM_IMA_QT:
1578 sc->samples_per_frame = 64;
1579 sc->bytes_per_frame = 34 * st->codec->channels;
1581 case AV_CODEC_ID_GSM:
1582 sc->samples_per_frame = 160;
1583 sc->bytes_per_frame = 33;
1589 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1590 if (bits_per_sample) {
1591 st->codec->bits_per_coded_sample = bits_per_sample;
1592 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1596 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1597 AVStream *st, MOVStreamContext *sc,
1600 // ttxt stsd contains display flags, justification, background
1601 // color, fonts, and default styles, so fake an atom to read it
1602 MOVAtom fake_atom = { .size = size };
1603 // mp4s contains a regular esds atom
1604 if (st->codec->codec_tag != AV_RL32("mp4s"))
1605 mov_read_glbl(c, pb, fake_atom);
1606 st->codec->width = sc->width;
1607 st->codec->height = sc->height;
1610 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1615 y = (ycbcr >> 16) & 0xFF;
1616 cr = (ycbcr >> 8) & 0xFF;
1619 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1620 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1621 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1623 return (r << 16) | (g << 8) | b;
1626 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1628 char buf[256] = {0};
1629 uint8_t *src = st->codec->extradata;
1632 if (st->codec->extradata_size != 64)
1635 if (st->codec->width > 0 && st->codec->height > 0)
1636 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1637 st->codec->width, st->codec->height);
1638 av_strlcat(buf, "palette: ", sizeof(buf));
1640 for (i = 0; i < 16; i++) {
1641 uint32_t yuv = AV_RB32(src + i * 4);
1642 uint32_t rgba = yuv_to_rgba(yuv);
1644 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1647 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1650 av_freep(&st->codec->extradata);
1651 st->codec->extradata_size = 0;
1652 st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
1653 if (!st->codec->extradata)
1654 return AVERROR(ENOMEM);
1655 st->codec->extradata_size = strlen(buf);
1656 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1661 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1662 AVStream *st, MOVStreamContext *sc,
1665 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1666 if ((int)size != size || ff_get_extradata(st->codec, pb, size) < 0)
1667 return AVERROR(ENOMEM);
1669 MOVStreamContext *tmcd_ctx = st->priv_data;
1671 val = AV_RB32(st->codec->extradata + 4);
1672 tmcd_ctx->tmcd_flags = val;
1674 st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1675 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
1676 st->codec->time_base.num = 1;
1677 /* adjust for per frame dur in counter mode */
1678 if (tmcd_ctx->tmcd_flags & 0x0008) {
1679 int timescale = AV_RB32(st->codec->extradata + 8);
1680 int framedur = AV_RB32(st->codec->extradata + 12);
1681 st->codec->time_base.den *= timescale;
1682 st->codec->time_base.num *= framedur;
1685 uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
1686 uint32_t format = AV_RB32(st->codec->extradata + 22);
1687 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
1688 uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
1689 if (str_size > 0 && size >= (int)str_size + 26) {
1690 char *reel_name = av_malloc(str_size + 1);
1692 return AVERROR(ENOMEM);
1693 memcpy(reel_name, st->codec->extradata + 30, str_size);
1694 reel_name[str_size] = 0; /* Add null terminator */
1695 /* don't add reel_name if emtpy string */
1696 if (*reel_name == 0) {
1699 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
1706 /* other codec type, just skip (rtp, mp4s ...) */
1707 avio_skip(pb, size);
1712 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1713 AVStream *st, MOVStreamContext *sc)
1715 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1716 !st->codec->sample_rate && sc->time_scale > 1)
1717 st->codec->sample_rate = sc->time_scale;
1719 /* special codec parameters handling */
1720 switch (st->codec->codec_id) {
1721 #if CONFIG_DV_DEMUXER
1722 case AV_CODEC_ID_DVAUDIO:
1723 c->dv_fctx = avformat_alloc_context();
1724 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1726 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1727 return AVERROR(ENOMEM);
1729 sc->dv_audio_container = 1;
1730 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1733 /* no ifdef since parameters are always those */
1734 case AV_CODEC_ID_QCELP:
1735 st->codec->channels = 1;
1736 // force sample rate for qcelp when not stored in mov
1737 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1738 st->codec->sample_rate = 8000;
1739 // FIXME: Why is the following needed for some files?
1740 sc->samples_per_frame = 160;
1741 if (!sc->bytes_per_frame)
1742 sc->bytes_per_frame = 35;
1744 case AV_CODEC_ID_AMR_NB:
1745 st->codec->channels = 1;
1746 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1747 st->codec->sample_rate = 8000;
1749 case AV_CODEC_ID_AMR_WB:
1750 st->codec->channels = 1;
1751 st->codec->sample_rate = 16000;
1753 case AV_CODEC_ID_MP2:
1754 case AV_CODEC_ID_MP3:
1755 /* force type after stsd for m1a hdlr */
1756 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1757 st->need_parsing = AVSTREAM_PARSE_FULL;
1759 case AV_CODEC_ID_GSM:
1760 case AV_CODEC_ID_ADPCM_MS:
1761 case AV_CODEC_ID_ADPCM_IMA_WAV:
1762 case AV_CODEC_ID_ILBC:
1763 case AV_CODEC_ID_MACE3:
1764 case AV_CODEC_ID_MACE6:
1765 case AV_CODEC_ID_QDM2:
1766 st->codec->block_align = sc->bytes_per_frame;
1768 case AV_CODEC_ID_ALAC:
1769 if (st->codec->extradata_size == 36) {
1770 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1771 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1774 case AV_CODEC_ID_AC3:
1775 case AV_CODEC_ID_EAC3:
1776 case AV_CODEC_ID_MPEG1VIDEO:
1777 case AV_CODEC_ID_VC1:
1778 st->need_parsing = AVSTREAM_PARSE_FULL;
1786 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1787 int codec_tag, int format,
1790 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1793 (codec_tag != format &&
1794 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1795 : codec_tag != MKTAG('j','p','e','g')))) {
1796 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1797 * export it as a separate AVStream but this needs a few changes
1798 * in the MOV demuxer, patch welcome. */
1800 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1801 avio_skip(pb, size);
1804 if ( codec_tag == AV_RL32("avc1") ||
1805 codec_tag == AV_RL32("hvc1") ||
1806 codec_tag == AV_RL32("hev1")
1808 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
1813 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1816 MOVStreamContext *sc;
1817 int pseudo_stream_id;
1819 if (c->fc->nb_streams < 1)
1821 st = c->fc->streams[c->fc->nb_streams-1];
1824 for (pseudo_stream_id = 0;
1825 pseudo_stream_id < entries && !pb->eof_reached;
1826 pseudo_stream_id++) {
1827 //Parsing Sample description table
1829 int ret, dref_id = 1;
1830 MOVAtom a = { AV_RL32("stsd") };
1831 int64_t start_pos = avio_tell(pb);
1832 int64_t size = avio_rb32(pb); /* size */
1833 uint32_t format = avio_rl32(pb); /* data format */
1836 avio_rb32(pb); /* reserved */
1837 avio_rb16(pb); /* reserved */
1838 dref_id = avio_rb16(pb);
1839 }else if (size <= 7){
1840 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1841 return AVERROR_INVALIDDATA;
1844 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1845 size - (avio_tell(pb) - start_pos)))
1848 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1849 sc->dref_id= dref_id;
1851 id = mov_codec_id(st, format);
1853 av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1854 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1855 (format >> 24) & 0xff, st->codec->codec_type);
1857 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1858 st->codec->codec_id = id;
1859 mov_parse_stsd_video(c, pb, st, sc);
1860 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1861 st->codec->codec_id = id;
1862 mov_parse_stsd_audio(c, pb, st, sc);
1863 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1864 st->codec->codec_id = id;
1865 mov_parse_stsd_subtitle(c, pb, st, sc,
1866 size - (avio_tell(pb) - start_pos));
1868 ret = mov_parse_stsd_data(c, pb, st, sc,
1869 size - (avio_tell(pb) - start_pos));
1873 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1874 a.size = size - (avio_tell(pb) - start_pos);
1876 if ((ret = mov_read_default(c, pb, a)) < 0)
1878 } else if (a.size > 0)
1879 avio_skip(pb, a.size);
1882 if (pb->eof_reached)
1885 return mov_finalize_stsd_codec(c, pb, st, sc);
1888 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1892 avio_r8(pb); /* version */
1893 avio_rb24(pb); /* flags */
1894 entries = avio_rb32(pb);
1896 return ff_mov_read_stsd_entries(c, pb, entries);
1899 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1902 MOVStreamContext *sc;
1903 unsigned int i, entries;
1905 if (c->fc->nb_streams < 1)
1907 st = c->fc->streams[c->fc->nb_streams-1];
1910 avio_r8(pb); /* version */
1911 avio_rb24(pb); /* flags */
1913 entries = avio_rb32(pb);
1915 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1920 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
1921 av_free(sc->stsc_data);
1923 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
1925 return AVERROR(ENOMEM);
1927 for (i = 0; i < entries && !pb->eof_reached; i++) {
1928 sc->stsc_data[i].first = avio_rb32(pb);
1929 sc->stsc_data[i].count = avio_rb32(pb);
1930 sc->stsc_data[i].id = avio_rb32(pb);
1935 if (pb->eof_reached)
1941 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1944 MOVStreamContext *sc;
1945 unsigned i, entries;
1947 if (c->fc->nb_streams < 1)
1949 st = c->fc->streams[c->fc->nb_streams-1];
1952 avio_rb32(pb); // version + flags
1954 entries = avio_rb32(pb);
1956 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
1957 av_free(sc->stps_data);
1959 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
1961 return AVERROR(ENOMEM);
1963 for (i = 0; i < entries && !pb->eof_reached; i++) {
1964 sc->stps_data[i] = avio_rb32(pb);
1965 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1970 if (pb->eof_reached)
1976 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1979 MOVStreamContext *sc;
1980 unsigned int i, entries;
1982 if (c->fc->nb_streams < 1)
1984 st = c->fc->streams[c->fc->nb_streams-1];
1987 avio_r8(pb); /* version */
1988 avio_rb24(pb); /* flags */
1990 entries = avio_rb32(pb);
1992 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1996 sc->keyframe_absent = 1;
1997 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1998 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2002 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2003 if (entries >= UINT_MAX / sizeof(int))
2004 return AVERROR_INVALIDDATA;
2005 av_freep(&sc->keyframes);
2006 sc->keyframe_count = 0;
2007 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2009 return AVERROR(ENOMEM);
2011 for (i = 0; i < entries && !pb->eof_reached; i++) {
2012 sc->keyframes[i] = avio_rb32(pb);
2013 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
2016 sc->keyframe_count = i;
2018 if (pb->eof_reached)
2024 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2027 MOVStreamContext *sc;
2028 unsigned int i, entries, sample_size, field_size, num_bytes;
2032 if (c->fc->nb_streams < 1)
2034 st = c->fc->streams[c->fc->nb_streams-1];
2037 avio_r8(pb); /* version */
2038 avio_rb24(pb); /* flags */
2040 if (atom.type == MKTAG('s','t','s','z')) {
2041 sample_size = avio_rb32(pb);
2042 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2043 sc->sample_size = sample_size;
2044 sc->stsz_sample_size = sample_size;
2048 avio_rb24(pb); /* reserved */
2049 field_size = avio_r8(pb);
2051 entries = avio_rb32(pb);
2053 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2055 sc->sample_count = entries;
2059 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2060 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2061 return AVERROR_INVALIDDATA;
2066 if (entries >= (UINT_MAX - 4) / field_size)
2067 return AVERROR_INVALIDDATA;
2068 if (sc->sample_sizes)
2069 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2070 av_free(sc->sample_sizes);
2071 sc->sample_count = 0;
2072 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2073 if (!sc->sample_sizes)
2074 return AVERROR(ENOMEM);
2076 num_bytes = (entries*field_size+4)>>3;
2078 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
2080 av_freep(&sc->sample_sizes);
2081 return AVERROR(ENOMEM);
2084 if (avio_read(pb, buf, num_bytes) < num_bytes) {
2085 av_freep(&sc->sample_sizes);
2087 return AVERROR_INVALIDDATA;
2090 init_get_bits(&gb, buf, 8*num_bytes);
2092 for (i = 0; i < entries && !pb->eof_reached; i++) {
2093 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2094 sc->data_size += sc->sample_sizes[i];
2097 sc->sample_count = i;
2099 if (pb->eof_reached)
2106 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2109 MOVStreamContext *sc;
2110 unsigned int i, entries;
2112 int64_t total_sample_count=0;
2114 if (c->fc->nb_streams < 1)
2116 st = c->fc->streams[c->fc->nb_streams-1];
2119 avio_r8(pb); /* version */
2120 avio_rb24(pb); /* flags */
2121 entries = avio_rb32(pb);
2123 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
2124 c->fc->nb_streams-1, entries);
2127 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2128 av_free(sc->stts_data);
2130 sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2132 return AVERROR(ENOMEM);
2134 for (i = 0; i < entries && !pb->eof_reached; i++) {
2135 int sample_duration;
2138 sample_count=avio_rb32(pb);
2139 sample_duration = avio_rb32(pb);
2141 /* sample_duration < 0 is invalid based on the spec */
2142 if (sample_duration < 0) {
2143 av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2144 sample_duration, i, c->fc->nb_streams-1);
2145 sample_duration = 1;
2147 if (sample_count < 0) {
2148 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2149 return AVERROR_INVALIDDATA;
2151 sc->stts_data[i].count= sample_count;
2152 sc->stts_data[i].duration= sample_duration;
2154 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
2155 sample_count, sample_duration);
2159 && sample_count == 1
2160 && total_sample_count > 100
2161 && sample_duration/10 > duration / total_sample_count)
2162 sample_duration = duration / total_sample_count;
2163 duration+=(int64_t)sample_duration*sample_count;
2164 total_sample_count+=sample_count;
2169 sc->duration_for_fps += duration;
2170 sc->nb_frames_for_fps += total_sample_count;
2172 if (pb->eof_reached)
2175 st->nb_frames= total_sample_count;
2177 st->duration= duration;
2178 sc->track_end = duration;
2182 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2185 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2189 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2192 MOVStreamContext *sc;
2193 unsigned int i, entries;
2195 if (c->fc->nb_streams < 1)
2197 st = c->fc->streams[c->fc->nb_streams-1];
2200 avio_r8(pb); /* version */
2201 avio_rb24(pb); /* flags */
2202 entries = avio_rb32(pb);
2204 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2208 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2209 return AVERROR_INVALIDDATA;
2210 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
2212 return AVERROR(ENOMEM);
2214 for (i = 0; i < entries && !pb->eof_reached; i++) {
2215 int count =avio_rb32(pb);
2216 int duration =avio_rb32(pb);
2218 sc->ctts_data[i].count = count;
2219 sc->ctts_data[i].duration= duration;
2221 av_dlog(c->fc, "count=%d, duration=%d\n",
2224 if (FFABS(duration) > (1<<28) && i+2<entries) {
2225 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2226 av_freep(&sc->ctts_data);
2232 mov_update_dts_shift(sc, duration);
2237 if (pb->eof_reached)
2240 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
2245 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2248 MOVStreamContext *sc;
2249 unsigned int i, entries;
2251 uint32_t grouping_type;
2253 if (c->fc->nb_streams < 1)
2255 st = c->fc->streams[c->fc->nb_streams-1];
2258 version = avio_r8(pb); /* version */
2259 avio_rb24(pb); /* flags */
2260 grouping_type = avio_rl32(pb);
2261 if (grouping_type != MKTAG( 'r','a','p',' '))
2262 return 0; /* only support 'rap ' grouping */
2264 avio_rb32(pb); /* grouping_type_parameter */
2266 entries = avio_rb32(pb);
2270 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2271 av_free(sc->rap_group);
2272 sc->rap_group_count = 0;
2273 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2275 return AVERROR(ENOMEM);
2277 for (i = 0; i < entries && !pb->eof_reached; i++) {
2278 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2279 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2282 sc->rap_group_count = i;
2284 return pb->eof_reached ? AVERROR_EOF : 0;
2287 static void mov_build_index(MOVContext *mov, AVStream *st)
2289 MOVStreamContext *sc = st->priv_data;
2290 int64_t current_offset;
2291 int64_t current_dts = 0;
2292 unsigned int stts_index = 0;
2293 unsigned int stsc_index = 0;
2294 unsigned int stss_index = 0;
2295 unsigned int stps_index = 0;
2297 uint64_t stream_size = 0;
2299 if (sc->elst_count) {
2300 int i, edit_start_index = 0, unsupported = 0;
2301 int64_t empty_duration = 0; // empty duration of the first edit list entry
2302 int64_t start_time = 0; // start time of the media
2304 for (i = 0; i < sc->elst_count; i++) {
2305 const MOVElst *e = &sc->elst_data[i];
2306 if (i == 0 && e->time == -1) {
2307 /* if empty, the first entry is the start time of the stream
2308 * relative to the presentation itself */
2309 empty_duration = e->duration;
2310 edit_start_index = 1;
2311 } else if (i == edit_start_index && e->time >= 0) {
2312 start_time = e->time;
2317 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
2318 "a/v desync might occur, patch welcome\n");
2320 /* adjust first dts according to edit list */
2321 if ((empty_duration || start_time) && mov->time_scale > 0) {
2323 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
2324 sc->time_offset = start_time - empty_duration;
2325 current_dts = -sc->time_offset;
2326 if (sc->ctts_count>0 && sc->stts_count>0 &&
2327 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2328 /* more than 16 frames delay, dts are likely wrong
2329 this happens with files created by iMovie */
2331 st->codec->has_b_frames = 1;
2336 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2337 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2338 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2339 unsigned int current_sample = 0;
2340 unsigned int stts_sample = 0;
2341 unsigned int sample_size;
2342 unsigned int distance = 0;
2343 unsigned int rap_group_index = 0;
2344 unsigned int rap_group_sample = 0;
2345 int rap_group_present = sc->rap_group_count && sc->rap_group;
2346 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2348 current_dts -= sc->dts_shift;
2350 if (!sc->sample_count || st->nb_index_entries)
2352 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2354 if (av_reallocp_array(&st->index_entries,
2355 st->nb_index_entries + sc->sample_count,
2356 sizeof(*st->index_entries)) < 0) {
2357 st->nb_index_entries = 0;
2360 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2362 for (i = 0; i < sc->chunk_count; i++) {
2363 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2364 current_offset = sc->chunk_offsets[i];
2365 while (stsc_index + 1 < sc->stsc_count &&
2366 i + 1 == sc->stsc_data[stsc_index + 1].first)
2369 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2370 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2371 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2372 sc->stsz_sample_size = sc->sample_size;
2374 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2375 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2376 sc->stsz_sample_size = sc->sample_size;
2379 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2381 if (current_sample >= sc->sample_count) {
2382 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2386 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2388 if (stss_index + 1 < sc->keyframe_count)
2390 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2392 if (stps_index + 1 < sc->stps_count)
2395 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2396 if (sc->rap_group[rap_group_index].index > 0)
2398 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2399 rap_group_sample = 0;
2403 if (sc->keyframe_absent
2405 && !rap_group_present
2406 && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2410 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2411 if (sc->pseudo_stream_id == -1 ||
2412 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2413 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2414 e->pos = current_offset;
2415 e->timestamp = current_dts;
2416 e->size = sample_size;
2417 e->min_distance = distance;
2418 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2419 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2420 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2421 current_offset, current_dts, sample_size, distance, keyframe);
2422 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2423 ff_rfps_add_frame(mov->fc, st, current_dts);
2426 current_offset += sample_size;
2427 stream_size += sample_size;
2428 current_dts += sc->stts_data[stts_index].duration;
2432 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2438 if (st->duration > 0)
2439 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2441 unsigned chunk_samples, total = 0;
2443 // compute total chunk count
2444 for (i = 0; i < sc->stsc_count; i++) {
2445 unsigned count, chunk_count;
2447 chunk_samples = sc->stsc_data[i].count;
2448 if (i != sc->stsc_count - 1 &&
2449 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2450 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2454 if (sc->samples_per_frame >= 160) { // gsm
2455 count = chunk_samples / sc->samples_per_frame;
2456 } else if (sc->samples_per_frame > 1) {
2457 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2458 count = (chunk_samples+samples-1) / samples;
2460 count = (chunk_samples+1023) / 1024;
2463 if (i < sc->stsc_count - 1)
2464 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2466 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2467 total += chunk_count * count;
2470 av_dlog(mov->fc, "chunk count %d\n", total);
2471 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2473 if (av_reallocp_array(&st->index_entries,
2474 st->nb_index_entries + total,
2475 sizeof(*st->index_entries)) < 0) {
2476 st->nb_index_entries = 0;
2479 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2482 for (i = 0; i < sc->chunk_count; i++) {
2483 current_offset = sc->chunk_offsets[i];
2484 if (stsc_index + 1 < sc->stsc_count &&
2485 i + 1 == sc->stsc_data[stsc_index + 1].first)
2487 chunk_samples = sc->stsc_data[stsc_index].count;
2489 while (chunk_samples > 0) {
2491 unsigned size, samples;
2493 if (sc->samples_per_frame >= 160) { // gsm
2494 samples = sc->samples_per_frame;
2495 size = sc->bytes_per_frame;
2497 if (sc->samples_per_frame > 1) {
2498 samples = FFMIN((1024 / sc->samples_per_frame)*
2499 sc->samples_per_frame, chunk_samples);
2500 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2502 samples = FFMIN(1024, chunk_samples);
2503 size = samples * sc->sample_size;
2507 if (st->nb_index_entries >= total) {
2508 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2511 e = &st->index_entries[st->nb_index_entries++];
2512 e->pos = current_offset;
2513 e->timestamp = current_dts;
2515 e->min_distance = 0;
2516 e->flags = AVINDEX_KEYFRAME;
2517 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2518 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2521 current_offset += size;
2522 current_dts += samples;
2523 chunk_samples -= samples;
2529 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2530 AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2532 /* try relative path, we do not try the absolute because it can leak information about our
2533 system to an attacker */
2534 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2535 char filename[1024];
2536 const char *src_path;
2539 /* find a source dir */
2540 src_path = strrchr(src, '/');
2546 /* find a next level down to target */
2547 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2548 if (ref->path[l] == '/') {
2549 if (i == ref->nlvl_to - 1)
2555 /* compose filename if next level down to target was found */
2556 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2557 memcpy(filename, src, src_path - src);
2558 filename[src_path - src] = 0;
2560 for (i = 1; i < ref->nlvl_from; i++)
2561 av_strlcat(filename, "../", 1024);
2563 av_strlcat(filename, ref->path + l + 1, 1024);
2565 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2568 } else if (use_absolute_path) {
2569 av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2570 "this is a possible security issue\n");
2571 if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2575 return AVERROR(ENOENT);
2578 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2580 if (sc->time_scale <= 0) {
2581 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2582 sc->time_scale = c->time_scale;
2583 if (sc->time_scale <= 0)
2588 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2591 MOVStreamContext *sc;
2594 st = avformat_new_stream(c->fc, NULL);
2595 if (!st) return AVERROR(ENOMEM);
2596 st->id = c->fc->nb_streams;
2597 sc = av_mallocz(sizeof(MOVStreamContext));
2598 if (!sc) return AVERROR(ENOMEM);
2601 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2602 sc->ffindex = st->index;
2604 if ((ret = mov_read_default(c, pb, atom)) < 0)
2608 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2609 (!sc->sample_size && !sc->sample_count))) {
2610 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2615 fix_timescale(c, sc);
2617 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2619 mov_build_index(c, st);
2621 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2622 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2623 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2624 c->use_absolute_path, c->fc) < 0)
2625 av_log(c->fc, AV_LOG_ERROR,
2626 "stream %d, error opening alias: path='%s', dir='%s', "
2627 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2628 st->index, dref->path, dref->dir, dref->filename,
2629 dref->volume, dref->nlvl_from, dref->nlvl_to);
2632 sc->pb_is_copied = 1;
2635 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2636 if (!st->sample_aspect_ratio.num &&
2637 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2638 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2639 ((double)st->codec->width * sc->height), INT_MAX);
2642 #if FF_API_R_FRAME_RATE
2643 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2644 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2645 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2649 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2650 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2651 TAG_IS_AVCI(st->codec->codec_tag)) {
2652 ret = ff_generate_avci_extradata(st);
2657 switch (st->codec->codec_id) {
2658 #if CONFIG_H261_DECODER
2659 case AV_CODEC_ID_H261:
2661 #if CONFIG_H263_DECODER
2662 case AV_CODEC_ID_H263:
2664 #if CONFIG_MPEG4_DECODER
2665 case AV_CODEC_ID_MPEG4:
2667 st->codec->width = 0; /* let decoder init width/height */
2668 st->codec->height= 0;
2672 /* Do not need those anymore. */
2673 av_freep(&sc->chunk_offsets);
2674 av_freep(&sc->stsc_data);
2675 av_freep(&sc->sample_sizes);
2676 av_freep(&sc->keyframes);
2677 av_freep(&sc->stts_data);
2678 av_freep(&sc->stps_data);
2679 av_freep(&sc->elst_data);
2680 av_freep(&sc->rap_group);
2685 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2688 c->itunes_metadata = 1;
2689 ret = mov_read_default(c, pb, atom);
2690 c->itunes_metadata = 0;
2694 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
2696 int64_t end = avio_tell(pb) + size;
2697 uint8_t *key = NULL, *val = NULL;
2700 MOVStreamContext *sc;
2702 if (c->fc->nb_streams < 1)
2704 st = c->fc->streams[c->fc->nb_streams-1];
2707 for (i = 0; i < 2; i++) {
2711 if (end - avio_tell(pb) <= 12)
2714 len = avio_rb32(pb);
2715 tag = avio_rl32(pb);
2716 avio_skip(pb, 4); // flags
2718 if (len < 12 || len - 12 > end - avio_tell(pb))
2722 if (tag == MKTAG('n', 'a', 'm', 'e'))
2724 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2731 *p = av_malloc(len + 1);
2734 avio_read(pb, *p, len);
2739 if (strcmp(key, "iTunSMPB") == 0) {
2740 int priming, remainder, samples;
2741 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
2742 if(priming>0 && priming<16384)
2743 sc->start_pad = priming;
2746 if (strcmp(key, "cdec") != 0) {
2747 av_dict_set(&c->fc->metadata, key, val,
2748 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2753 avio_seek(pb, end, SEEK_SET);
2759 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2761 int64_t end = avio_tell(pb) + atom.size;
2767 len = avio_rb32(pb);
2768 tag = avio_rl32(pb);
2770 if (len > atom.size)
2773 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2774 uint8_t domain[128];
2777 avio_skip(pb, 4); // flags
2780 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2781 avio_skip(pb, len - domain_len);
2782 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
2786 av_log(c->fc, AV_LOG_VERBOSE,
2787 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2791 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2793 while (atom.size > 8) {
2794 uint32_t tag = avio_rl32(pb);
2796 if (tag == MKTAG('h','d','l','r')) {
2797 avio_seek(pb, -8, SEEK_CUR);
2799 return mov_read_default(c, pb, atom);
2805 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2810 int display_matrix[3][3];
2812 MOVStreamContext *sc;
2816 if (c->fc->nb_streams < 1)
2818 st = c->fc->streams[c->fc->nb_streams-1];
2821 version = avio_r8(pb);
2822 flags = avio_rb24(pb);
2823 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2829 avio_rb32(pb); /* creation time */
2830 avio_rb32(pb); /* modification time */
2832 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2833 avio_rb32(pb); /* reserved */
2835 /* highlevel (considering edits) duration in movie timebase */
2836 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2837 avio_rb32(pb); /* reserved */
2838 avio_rb32(pb); /* reserved */
2840 avio_rb16(pb); /* layer */
2841 avio_rb16(pb); /* alternate group */
2842 avio_rb16(pb); /* volume */
2843 avio_rb16(pb); /* reserved */
2845 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2846 // they're kept in fixed point format through all calculations
2847 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2848 // side data, but the scale factor is not needed to calculate aspect ratio
2849 for (i = 0; i < 3; i++) {
2850 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2851 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2852 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2855 width = avio_rb32(pb); // 16.16 fixed point track width
2856 height = avio_rb32(pb); // 16.16 fixed point track height
2857 sc->width = width >> 16;
2858 sc->height = height >> 16;
2860 // save the matrix and add rotate metadata when it is not the default
2862 if (display_matrix[0][0] != (1 << 16) ||
2863 display_matrix[1][1] != (1 << 16) ||
2864 display_matrix[2][2] != (1 << 30) ||
2865 display_matrix[0][1] || display_matrix[0][2] ||
2866 display_matrix[1][0] || display_matrix[1][2] ||
2867 display_matrix[2][0] || display_matrix[2][1]) {
2871 av_freep(&sc->display_matrix);
2872 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2873 if (!sc->display_matrix)
2874 return AVERROR(ENOMEM);
2876 for (i = 0; i < 3; i++)
2877 for (j = 0; j < 3; j++)
2878 sc->display_matrix[i * 3 + j] = display_matrix[j][i];
2880 rotate = av_display_rotation_get(sc->display_matrix);
2881 if (!isnan(rotate)) {
2882 char rotate_buf[64];
2884 if (rotate < 0) // for backward compatibility
2886 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
2887 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
2891 // transform the display width/height according to the matrix
2892 // to keep the same scale, use [width height 1<<16]
2893 if (width && height && sc->display_matrix) {
2894 double disp_transform[2];
2896 #define SQR(a) ((a)*(double)(a))
2897 for (i = 0; i < 2; i++)
2898 disp_transform[i] = sqrt(SQR(display_matrix[i][0]) + SQR(display_matrix[i][1]));
2900 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
2901 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
2902 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
2903 st->sample_aspect_ratio = av_d2q(
2904 disp_transform[0] / disp_transform[1],
2910 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2912 MOVFragment *frag = &c->fragment;
2913 MOVTrackExt *trex = NULL;
2914 MOVFragmentIndex* index = NULL;
2915 int flags, track_id, i;
2917 avio_r8(pb); /* version */
2918 flags = avio_rb24(pb);
2920 track_id = avio_rb32(pb);
2922 return AVERROR_INVALIDDATA;
2923 frag->track_id = track_id;
2924 for (i = 0; i < c->trex_count; i++)
2925 if (c->trex_data[i].track_id == frag->track_id) {
2926 trex = &c->trex_data[i];
2930 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2931 return AVERROR_INVALIDDATA;
2933 for (i = 0; i < c->fragment_index_count; i++) {
2934 MOVFragmentIndex* candidate = c->fragment_index_data[i];
2935 if (candidate->track_id == frag->track_id) {
2936 av_log(c->fc, AV_LOG_DEBUG,
2937 "found fragment index for track %u\n", frag->track_id);
2943 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2944 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
2945 frag->moof_offset : frag->implicit_offset;
2946 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2948 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2949 avio_rb32(pb) : trex->duration;
2950 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2951 avio_rb32(pb) : trex->size;
2952 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2953 avio_rb32(pb) : trex->flags;
2954 frag->time = AV_NOPTS_VALUE;
2957 for (i = index->current_item; i < index->item_count; i++) {
2958 if (frag->implicit_offset == index->items[i].moof_offset) {
2959 av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
2960 "for track %u and moof_offset %"PRId64"\n",
2961 frag->track_id, index->items[i].moof_offset);
2962 frag->time = index->items[i].time;
2963 index->current_item = i + 1;
2968 av_log(c->fc, AV_LOG_WARNING, "track %u has a fragment index "
2969 "but it doesn't have an (in-order) entry for moof_offset "
2970 "%"PRId64"\n", frag->track_id, frag->implicit_offset);
2973 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2977 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2979 c->chapter_track = avio_rb32(pb);
2983 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2988 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2989 return AVERROR_INVALIDDATA;
2990 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2991 sizeof(*c->trex_data))) < 0) {
2996 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2998 trex = &c->trex_data[c->trex_count++];
2999 avio_r8(pb); /* version */
3000 avio_rb24(pb); /* flags */
3001 trex->track_id = avio_rb32(pb);
3002 trex->stsd_id = avio_rb32(pb);
3003 trex->duration = avio_rb32(pb);
3004 trex->size = avio_rb32(pb);
3005 trex->flags = avio_rb32(pb);
3009 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3011 MOVFragment *frag = &c->fragment;
3012 AVStream *st = NULL;
3013 MOVStreamContext *sc;
3016 for (i = 0; i < c->fc->nb_streams; i++) {
3017 if (c->fc->streams[i]->id == frag->track_id) {
3018 st = c->fc->streams[i];
3023 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3024 return AVERROR_INVALIDDATA;
3027 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
3029 version = avio_r8(pb);
3030 avio_rb24(pb); /* flags */
3032 sc->track_end = avio_rb64(pb);
3034 sc->track_end = avio_rb32(pb);
3039 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3041 MOVFragment *frag = &c->fragment;
3042 AVStream *st = NULL;
3043 MOVStreamContext *sc;
3047 int data_offset = 0;
3048 unsigned entries, first_sample_flags = frag->flags;
3049 int flags, distance, i, found_keyframe = 0, err;
3051 for (i = 0; i < c->fc->nb_streams; i++) {
3052 if (c->fc->streams[i]->id == frag->track_id) {
3053 st = c->fc->streams[i];
3058 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3059 return AVERROR_INVALIDDATA;
3062 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3064 avio_r8(pb); /* version */
3065 flags = avio_rb24(pb);
3066 entries = avio_rb32(pb);
3067 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
3069 /* Always assume the presence of composition time offsets.
3070 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3071 * 1) in the initial movie, there are no samples.
3072 * 2) in the first movie fragment, there is only one sample without composition time offset.
3073 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
3074 if (!sc->ctts_count && sc->sample_count)
3076 /* Complement ctts table if moov atom doesn't have ctts atom. */
3077 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3079 return AVERROR(ENOMEM);
3080 sc->ctts_data = ctts_data;
3081 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3082 sc->ctts_data[sc->ctts_count].duration = 0;
3085 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3086 return AVERROR_INVALIDDATA;
3087 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3088 sizeof(*sc->ctts_data))) < 0) {
3092 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
3093 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3094 dts = sc->track_end - sc->time_offset;
3095 offset = frag->base_data_offset + data_offset;
3097 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
3098 for (i = 0; i < entries && !pb->eof_reached; i++) {
3099 unsigned sample_size = frag->size;
3100 int sample_flags = i ? frag->flags : first_sample_flags;
3101 unsigned sample_duration = frag->duration;
3104 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3105 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
3106 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
3107 sc->ctts_data[sc->ctts_count].count = 1;
3108 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3110 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
3111 if (frag->time != AV_NOPTS_VALUE) {
3112 if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3113 int64_t pts = frag->time;
3114 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3115 " sc->dts_shift %d ctts.duration %d"
3116 " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3117 sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3118 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3119 dts = pts - sc->dts_shift;
3120 if (flags & MOV_TRUN_SAMPLE_CTS) {
3121 dts -= sc->ctts_data[sc->ctts_count].duration;
3123 dts -= sc->time_offset;
3125 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3128 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3129 ", using it for dts\n", dts);
3131 frag->time = AV_NOPTS_VALUE;
3134 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3136 else if (!found_keyframe)
3137 keyframe = found_keyframe =
3138 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3139 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3142 av_add_index_entry(st, offset, dts, sample_size, distance,
3143 keyframe ? AVINDEX_KEYFRAME : 0);
3144 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3145 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3146 offset, dts, sample_size, distance, keyframe);
3148 dts += sample_duration;
3149 offset += sample_size;
3150 sc->data_size += sample_size;
3151 sc->duration_for_fps += sample_duration;
3152 sc->nb_frames_for_fps ++;
3155 if (pb->eof_reached)
3158 frag->implicit_offset = offset;
3159 st->duration = sc->track_end = dts + sc->time_offset;
3163 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3164 /* like the files created with Adobe Premiere 5.0, for samples see */
3165 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3166 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3171 return 0; /* continue */
3172 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3173 avio_skip(pb, atom.size - 4);
3176 atom.type = avio_rl32(pb);
3178 if (atom.type != MKTAG('m','d','a','t')) {
3179 avio_skip(pb, atom.size);
3182 err = mov_read_mdat(c, pb, atom);
3186 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3191 uint8_t *moov_data; /* uncompressed data */
3192 long cmov_len, moov_len;
3195 avio_rb32(pb); /* dcom atom */
3196 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3197 return AVERROR_INVALIDDATA;
3198 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3199 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3200 return AVERROR_INVALIDDATA;
3202 avio_rb32(pb); /* cmvd atom */
3203 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3204 return AVERROR_INVALIDDATA;
3205 moov_len = avio_rb32(pb); /* uncompressed size */
3206 cmov_len = atom.size - 6 * 4;
3208 cmov_data = av_malloc(cmov_len);
3210 return AVERROR(ENOMEM);
3211 moov_data = av_malloc(moov_len);
3214 return AVERROR(ENOMEM);
3216 avio_read(pb, cmov_data, cmov_len);
3217 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3218 goto free_and_return;
3219 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3220 goto free_and_return;
3221 atom.type = MKTAG('m','o','o','v');
3222 atom.size = moov_len;
3223 ret = mov_read_default(c, &ctx, atom);
3229 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3230 return AVERROR(ENOSYS);
3234 /* edit list atom */
3235 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3237 MOVStreamContext *sc;
3238 int i, edit_count, version;
3240 if (c->fc->nb_streams < 1 || c->ignore_editlist)
3242 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3244 version = avio_r8(pb); /* version */
3245 avio_rb24(pb); /* flags */
3246 edit_count = avio_rb32(pb); /* entries */
3251 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
3252 av_free(sc->elst_data);
3254 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
3256 return AVERROR(ENOMEM);
3258 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3259 for (i = 0; i < edit_count && !pb->eof_reached; i++) {
3260 MOVElst *e = &sc->elst_data[i];
3263 e->duration = avio_rb64(pb);
3264 e->time = avio_rb64(pb);
3266 e->duration = avio_rb32(pb); /* segment duration */
3267 e->time = (int32_t)avio_rb32(pb); /* media time */
3269 e->rate = avio_rb32(pb) / 65536.0;
3270 av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3271 e->duration, e->time, e->rate);
3278 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3280 MOVStreamContext *sc;
3282 if (c->fc->nb_streams < 1)
3283 return AVERROR_INVALIDDATA;
3284 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3285 sc->timecode_track = avio_rb32(pb);
3289 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3293 static const uint8_t uuid_isml_manifest[] = {
3294 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3295 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3298 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3299 return AVERROR_INVALIDDATA;
3301 ret = avio_read(pb, uuid, sizeof(uuid));
3304 } else if (ret != sizeof(uuid)) {
3305 return AVERROR_INVALIDDATA;
3307 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3308 uint8_t *buffer, *ptr;
3310 size_t len = atom.size - sizeof(uuid);
3313 return AVERROR_INVALIDDATA;
3315 ret = avio_skip(pb, 4); // zeroes
3318 buffer = av_mallocz(len + 1);
3320 return AVERROR(ENOMEM);
3322 ret = avio_read(pb, buffer, len);
3326 } else if (ret != len) {
3328 return AVERROR_INVALIDDATA;
3332 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
3333 ptr += sizeof("systemBitrate=\"") - 1;
3334 c->bitrates_count++;
3335 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3337 c->bitrates_count = 0;
3339 return AVERROR(ENOMEM);
3342 ret = strtol(ptr, &endptr, 10);
3343 if (ret < 0 || errno || *endptr != '"') {
3344 c->bitrates[c->bitrates_count - 1] = 0;
3346 c->bitrates[c->bitrates_count - 1] = ret;
3355 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3358 uint8_t content[16];
3363 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
3369 && !memcmp(content, "Anevia\x1A\x1A", 8)
3370 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
3371 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
3377 static const MOVParseTableEntry mov_default_parse_table[] = {
3378 { MKTAG('A','C','L','R'), mov_read_avid },
3379 { MKTAG('A','P','R','G'), mov_read_avid },
3380 { MKTAG('A','A','L','P'), mov_read_avid },
3381 { MKTAG('A','R','E','S'), mov_read_ares },
3382 { MKTAG('a','v','s','s'), mov_read_avss },
3383 { MKTAG('c','h','p','l'), mov_read_chpl },
3384 { MKTAG('c','o','6','4'), mov_read_stco },
3385 { MKTAG('c','o','l','r'), mov_read_colr },
3386 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3387 { MKTAG('d','i','n','f'), mov_read_default },
3388 { MKTAG('D','p','x','E'), mov_read_dpxe },
3389 { MKTAG('d','r','e','f'), mov_read_dref },
3390 { MKTAG('e','d','t','s'), mov_read_default },
3391 { MKTAG('e','l','s','t'), mov_read_elst },
3392 { MKTAG('e','n','d','a'), mov_read_enda },
3393 { MKTAG('f','i','e','l'), mov_read_fiel },
3394 { MKTAG('f','t','y','p'), mov_read_ftyp },
3395 { MKTAG('g','l','b','l'), mov_read_glbl },
3396 { MKTAG('h','d','l','r'), mov_read_hdlr },
3397 { MKTAG('i','l','s','t'), mov_read_ilst },
3398 { MKTAG('j','p','2','h'), mov_read_jp2h },
3399 { MKTAG('m','d','a','t'), mov_read_mdat },
3400 { MKTAG('m','d','h','d'), mov_read_mdhd },
3401 { MKTAG('m','d','i','a'), mov_read_default },
3402 { MKTAG('m','e','t','a'), mov_read_meta },
3403 { MKTAG('m','i','n','f'), mov_read_default },
3404 { MKTAG('m','o','o','f'), mov_read_moof },
3405 { MKTAG('m','o','o','v'), mov_read_moov },
3406 { MKTAG('m','v','e','x'), mov_read_default },
3407 { MKTAG('m','v','h','d'), mov_read_mvhd },
3408 { MKTAG('S','M','I',' '), mov_read_svq3 },
3409 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
3410 { MKTAG('a','v','c','C'), mov_read_glbl },
3411 { MKTAG('p','a','s','p'), mov_read_pasp },
3412 { MKTAG('s','t','b','l'), mov_read_default },
3413 { MKTAG('s','t','c','o'), mov_read_stco },
3414 { MKTAG('s','t','p','s'), mov_read_stps },
3415 { MKTAG('s','t','r','f'), mov_read_strf },
3416 { MKTAG('s','t','s','c'), mov_read_stsc },
3417 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3418 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3419 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3420 { MKTAG('s','t','t','s'), mov_read_stts },
3421 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3422 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3423 { MKTAG('t','f','d','t'), mov_read_tfdt },
3424 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3425 { MKTAG('t','r','a','k'), mov_read_trak },
3426 { MKTAG('t','r','a','f'), mov_read_default },
3427 { MKTAG('t','r','e','f'), mov_read_default },
3428 { MKTAG('t','m','c','d'), mov_read_tmcd },
3429 { MKTAG('c','h','a','p'), mov_read_chap },
3430 { MKTAG('t','r','e','x'), mov_read_trex },
3431 { MKTAG('t','r','u','n'), mov_read_trun },
3432 { MKTAG('u','d','t','a'), mov_read_default },
3433 { MKTAG('w','a','v','e'), mov_read_wave },
3434 { MKTAG('e','s','d','s'), mov_read_esds },
3435 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3436 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3437 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3438 { MKTAG('w','f','e','x'), mov_read_wfex },
3439 { MKTAG('c','m','o','v'), mov_read_cmov },
3440 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3441 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3442 { MKTAG('s','b','g','p'), mov_read_sbgp },
3443 { MKTAG('h','v','c','C'), mov_read_glbl },
3444 { MKTAG('u','u','i','d'), mov_read_uuid },
3445 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
3446 { MKTAG('f','r','e','e'), mov_read_free },
3447 { MKTAG('-','-','-','-'), mov_read_custom },
3451 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3453 int64_t total_size = 0;
3457 if (c->atom_depth > 10) {
3458 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
3459 return AVERROR_INVALIDDATA;
3464 atom.size = INT64_MAX;
3465 while (total_size + 8 <= atom.size && !avio_feof(pb)) {
3466 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3469 if (atom.size >= 8) {
3470 a.size = avio_rb32(pb);
3471 a.type = avio_rl32(pb);
3472 if (a.type == MKTAG('f','r','e','e') &&
3476 uint32_t *type = (uint32_t *)buf + 1;
3477 avio_read(pb, buf, 8);
3478 avio_seek(pb, -8, SEEK_CUR);
3479 if (*type == MKTAG('m','v','h','d') ||
3480 *type == MKTAG('c','m','o','v')) {
3481 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
3482 a.type = MKTAG('m','o','o','v');
3485 if (atom.type != MKTAG('r','o','o','t') &&
3486 atom.type != MKTAG('m','o','o','v'))
3488 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
3490 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
3497 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
3498 a.size = avio_rb64(pb) - 8;
3502 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3503 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3505 a.size = atom.size - total_size + 8;
3510 a.size = FFMIN(a.size, atom.size - total_size);
3512 for (i = 0; mov_default_parse_table[i].type; i++)
3513 if (mov_default_parse_table[i].type == a.type) {
3514 parse = mov_default_parse_table[i].parse;
3518 // container is user data
3519 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3520 atom.type == MKTAG('i','l','s','t')))
3521 parse = mov_read_udta_string;
3523 if (!parse) { /* skip leaf atoms data */
3524 avio_skip(pb, a.size);
3526 int64_t start_pos = avio_tell(pb);
3528 int err = parse(c, pb, a);
3533 if (c->found_moov && c->found_mdat &&
3534 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3535 start_pos + a.size == avio_size(pb))) {
3536 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3537 c->next_root_atom = start_pos + a.size;
3541 left = a.size - avio_tell(pb) + start_pos;
3542 if (left > 0) /* skip garbage at atom end */
3543 avio_skip(pb, left);
3544 else if (left < 0) {
3545 av_log(c->fc, AV_LOG_WARNING,
3546 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3547 (char*)&a.type, -left);
3548 avio_seek(pb, left, SEEK_CUR);
3552 total_size += a.size;
3555 if (total_size < atom.size && atom.size < 0x7ffff)
3556 avio_skip(pb, atom.size - total_size);
3562 static int mov_probe(AVProbeData *p)
3567 int moov_offset = -1;
3569 /* check file header */
3572 /* ignore invalid offset */
3573 if ((offset + 8) > (unsigned int)p->buf_size)
3575 tag = AV_RL32(p->buf + offset + 4);
3577 /* check for obvious tags */
3578 case MKTAG('m','o','o','v'):
3579 moov_offset = offset + 4;
3580 case MKTAG('m','d','a','t'):
3581 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3582 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3583 case MKTAG('f','t','y','p'):
3584 if (AV_RB32(p->buf+offset) < 8 &&
3585 (AV_RB32(p->buf+offset) != 1 ||
3586 offset + 12 > (unsigned int)p->buf_size ||
3587 AV_RB64(p->buf+offset + 8) == 0)) {
3588 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3589 } else if (tag == MKTAG('f','t','y','p') &&
3590 AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')) {
3591 score = FFMAX(score, 5);
3593 score = AVPROBE_SCORE_MAX;
3595 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3597 /* those are more common words, so rate then a bit less */
3598 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3599 case MKTAG('w','i','d','e'):
3600 case MKTAG('f','r','e','e'):
3601 case MKTAG('j','u','n','k'):
3602 case MKTAG('p','i','c','t'):
3603 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
3604 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3606 case MKTAG(0x82,0x82,0x7f,0x7d):
3607 case MKTAG('s','k','i','p'):
3608 case MKTAG('u','u','i','d'):
3609 case MKTAG('p','r','f','l'):
3610 /* if we only find those cause probedata is too small at least rate them */
3611 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3612 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3615 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3618 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
3619 /* moov atom in the header - we should make sure that this is not a
3620 * MOV-packed MPEG-PS */
3621 offset = moov_offset;
3623 while(offset < (p->buf_size - 16)){ /* Sufficient space */
3624 /* We found an actual hdlr atom */
3625 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
3626 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
3627 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
3628 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
3629 /* We found a media handler reference atom describing an
3630 * MPEG-PS-in-MOV, return a
3631 * low score to force expanding the probe window until
3632 * mpegps_probe finds what it needs */
3643 // must be done after parsing all trak because there's no order requirement
3644 static void mov_read_chapters(AVFormatContext *s)
3646 MOVContext *mov = s->priv_data;
3647 AVStream *st = NULL;
3648 MOVStreamContext *sc;
3652 for (i = 0; i < s->nb_streams; i++)
3653 if (s->streams[i]->id == mov->chapter_track) {
3658 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3662 st->discard = AVDISCARD_ALL;
3664 cur_pos = avio_tell(sc->pb);
3666 for (i = 0; i < st->nb_index_entries; i++) {
3667 AVIndexEntry *sample = &st->index_entries[i];
3668 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3673 if (end < sample->timestamp) {
3674 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
3675 end = AV_NOPTS_VALUE;
3678 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3679 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3683 // the first two bytes are the length of the title
3684 len = avio_rb16(sc->pb);
3685 if (len > sample->size-2)
3687 title_len = 2*len + 1;
3688 if (!(title = av_mallocz(title_len)))
3691 // The samples could theoretically be in any encoding if there's an encd
3692 // atom following, but in practice are only utf-8 or utf-16, distinguished
3693 // instead by the presence of a BOM
3697 ch = avio_rb16(sc->pb);
3699 avio_get_str16be(sc->pb, len, title, title_len);
3700 else if (ch == 0xfffe)
3701 avio_get_str16le(sc->pb, len, title, title_len);
3704 if (len == 1 || len == 2)
3707 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3711 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3715 avio_seek(sc->pb, cur_pos, SEEK_SET);
3718 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
3719 uint32_t value, int flags)
3722 char buf[AV_TIMECODE_STR_SIZE];
3723 AVRational rate = {st->codec->time_base.den,
3724 st->codec->time_base.num};
3725 int ret = av_timecode_init(&tc, rate, flags, 0, s);
3728 av_dict_set(&st->metadata, "timecode",
3729 av_timecode_make_string(&tc, buf, value), 0);
3733 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
3735 MOVStreamContext *sc = st->priv_data;
3737 int64_t cur_pos = avio_tell(sc->pb);
3740 if (!st->nb_index_entries)
3743 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3744 value = avio_rb32(s->pb);
3746 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3747 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3748 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3750 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3751 * not the case) and thus assume "frame number format" instead of QT one.
3752 * No sample with tmcd track can be found with a QT timecode at the moment,
3753 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3755 parse_timecode_in_framenum_format(s, st, value, flags);
3757 avio_seek(sc->pb, cur_pos, SEEK_SET);
3761 static int mov_read_close(AVFormatContext *s)
3763 MOVContext *mov = s->priv_data;
3766 for (i = 0; i < s->nb_streams; i++) {
3767 AVStream *st = s->streams[i];
3768 MOVStreamContext *sc = st->priv_data;
3770 av_freep(&sc->ctts_data);
3771 for (j = 0; j < sc->drefs_count; j++) {
3772 av_freep(&sc->drefs[j].path);
3773 av_freep(&sc->drefs[j].dir);
3775 av_freep(&sc->drefs);
3777 sc->drefs_count = 0;
3779 if (!sc->pb_is_copied)
3780 avio_closep(&sc->pb);
3783 av_freep(&sc->chunk_offsets);
3784 av_freep(&sc->stsc_data);
3785 av_freep(&sc->sample_sizes);
3786 av_freep(&sc->keyframes);
3787 av_freep(&sc->stts_data);
3788 av_freep(&sc->stps_data);
3789 av_freep(&sc->elst_data);
3790 av_freep(&sc->rap_group);
3791 av_freep(&sc->display_matrix);
3794 if (mov->dv_demux) {
3795 avformat_free_context(mov->dv_fctx);
3796 mov->dv_fctx = NULL;
3799 av_freep(&mov->trex_data);
3800 av_freep(&mov->bitrates);
3802 for (i = 0; i < mov->fragment_index_count; i++) {
3803 MOVFragmentIndex* index = mov->fragment_index_data[i];
3804 av_freep(&index->items);
3805 av_freep(&mov->fragment_index_data[i]);
3807 av_freep(&mov->fragment_index_data);
3812 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3816 for (i = 0; i < s->nb_streams; i++) {
3817 AVStream *st = s->streams[i];
3818 MOVStreamContext *sc = st->priv_data;
3820 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3821 sc->timecode_track == tmcd_id)
3827 /* look for a tmcd track not referenced by any video track, and export it globally */
3828 static void export_orphan_timecode(AVFormatContext *s)
3832 for (i = 0; i < s->nb_streams; i++) {
3833 AVStream *st = s->streams[i];
3835 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3836 !tmcd_is_referenced(s, i + 1)) {
3837 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3839 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3846 static int read_tfra(MOVContext *mov, AVIOContext *f)
3848 MOVFragmentIndex* index = NULL;
3849 int version, fieldlength, i, j;
3850 int64_t pos = avio_tell(f);
3851 uint32_t size = avio_rb32(f);
3854 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
3857 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
3858 index = av_mallocz(sizeof(MOVFragmentIndex));
3860 return AVERROR(ENOMEM);
3863 tmp = av_realloc_array(mov->fragment_index_data,
3864 mov->fragment_index_count + 1,
3865 sizeof(MOVFragmentIndex*));
3868 return AVERROR(ENOMEM);
3870 mov->fragment_index_data = tmp;
3871 mov->fragment_index_data[mov->fragment_index_count++] = index;
3873 version = avio_r8(f);
3875 index->track_id = avio_rb32(f);
3876 fieldlength = avio_rb32(f);
3877 index->item_count = avio_rb32(f);
3878 index->items = av_mallocz_array(
3879 index->item_count, sizeof(MOVFragmentIndexItem));
3880 if (!index->items) {
3881 index->item_count = 0;
3882 return AVERROR(ENOMEM);
3884 for (i = 0; i < index->item_count; i++) {
3885 int64_t time, offset;
3887 time = avio_rb64(f);
3888 offset = avio_rb64(f);
3890 time = avio_rb32(f);
3891 offset = avio_rb32(f);
3893 index->items[i].time = time;
3894 index->items[i].moof_offset = offset;
3895 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
3897 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
3899 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
3903 avio_seek(f, pos + size, SEEK_SET);
3907 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
3909 int64_t stream_size = avio_size(f);
3910 int64_t original_pos = avio_tell(f);
3914 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
3918 mfra_size = avio_rb32(f);
3919 if (mfra_size < 0 || mfra_size > stream_size) {
3920 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
3923 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
3927 if (avio_rb32(f) != mfra_size) {
3928 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
3931 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
3932 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
3935 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
3937 ret = read_tfra(c, f);
3943 seek_ret = avio_seek(f, original_pos, SEEK_SET);
3945 av_log(c->fc, AV_LOG_ERROR,
3946 "failed to seek back after looking for mfra\n");
3952 static int mov_read_header(AVFormatContext *s)
3954 MOVContext *mov = s->priv_data;
3955 AVIOContext *pb = s->pb;
3957 MOVAtom atom = { AV_RL32("root") };
3961 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3963 atom.size = avio_size(pb);
3965 atom.size = INT64_MAX;
3967 /* check MOV header */
3969 if (mov->moov_retry)
3970 avio_seek(pb, 0, SEEK_SET);
3971 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3972 av_log(s, AV_LOG_ERROR, "error reading header\n");
3976 } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
3977 if (!mov->found_moov) {
3978 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3980 return AVERROR_INVALIDDATA;
3982 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3985 if (mov->chapter_track > 0)
3986 mov_read_chapters(s);
3987 for (i = 0; i < s->nb_streams; i++)
3988 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3989 mov_read_timecode_track(s, s->streams[i]);
3992 /* copy timecode metadata from tmcd tracks to the related video streams */
3993 for (i = 0; i < s->nb_streams; i++) {
3994 AVStream *st = s->streams[i];
3995 MOVStreamContext *sc = st->priv_data;
3996 if (sc->timecode_track > 0) {
3997 AVDictionaryEntry *tcr;
3998 int tmcd_st_id = -1;
4000 for (j = 0; j < s->nb_streams; j++)
4001 if (s->streams[j]->id == sc->timecode_track)
4004 if (tmcd_st_id < 0 || tmcd_st_id == i)
4006 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
4008 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
4011 export_orphan_timecode(s);
4013 for (i = 0; i < s->nb_streams; i++) {
4014 AVStream *st = s->streams[i];
4015 MOVStreamContext *sc = st->priv_data;
4016 fix_timescale(mov, sc);
4017 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
4018 st->skip_samples = sc->start_pad;
4020 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
4021 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4022 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
4023 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4024 if (st->codec->width <= 0 || st->codec->height <= 0) {
4025 st->codec->width = sc->width;
4026 st->codec->height = sc->height;
4028 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
4029 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
4035 if (mov->trex_data) {
4036 for (i = 0; i < s->nb_streams; i++) {
4037 AVStream *st = s->streams[i];
4038 MOVStreamContext *sc = st->priv_data;
4039 if (st->duration > 0)
4040 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
4044 if (mov->use_mfra_for > 0) {
4045 for (i = 0; i < s->nb_streams; i++) {
4046 AVStream *st = s->streams[i];
4047 MOVStreamContext *sc = st->priv_data;
4048 if (sc->duration_for_fps > 0) {
4049 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
4050 sc->duration_for_fps;
4055 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
4056 if (mov->bitrates[i]) {
4057 s->streams[i]->codec->bit_rate = mov->bitrates[i];
4061 ff_rfps_calculate(s);
4063 for (i = 0; i < s->nb_streams; i++) {
4064 AVStream *st = s->streams[i];
4065 MOVStreamContext *sc = st->priv_data;
4067 switch (st->codec->codec_type) {
4068 case AVMEDIA_TYPE_AUDIO:
4069 err = ff_replaygain_export(st, s->metadata);
4075 case AVMEDIA_TYPE_VIDEO:
4076 if (sc->display_matrix) {
4077 AVPacketSideData *sd, *tmp;
4079 tmp = av_realloc_array(st->side_data,
4080 st->nb_side_data + 1, sizeof(*tmp));
4082 return AVERROR(ENOMEM);
4084 st->side_data = tmp;
4087 sd = &st->side_data[st->nb_side_data - 1];
4088 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
4089 sd->size = sizeof(int32_t) * 9;
4090 sd->data = (uint8_t*)sc->display_matrix;
4091 sc->display_matrix = NULL;
4100 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
4102 AVIndexEntry *sample = NULL;
4103 int64_t best_dts = INT64_MAX;
4105 for (i = 0; i < s->nb_streams; i++) {
4106 AVStream *avst = s->streams[i];
4107 MOVStreamContext *msc = avst->priv_data;
4108 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
4109 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
4110 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
4111 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
4112 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
4114 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
4115 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
4116 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
4117 sample = current_sample;
4126 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
4128 MOVContext *mov = s->priv_data;
4129 MOVStreamContext *sc;
4130 AVIndexEntry *sample;
4131 AVStream *st = NULL;
4135 sample = mov_find_next_sample(s, &st);
4137 mov->found_mdat = 0;
4138 if (!mov->next_root_atom)
4140 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
4141 mov->next_root_atom = 0;
4142 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
4145 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
4149 /* must be done just before reading, to avoid infinite loop on sample */
4150 sc->current_sample++;
4152 if (mov->next_root_atom) {
4153 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
4154 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
4157 if (st->discard != AVDISCARD_ALL) {
4158 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4159 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
4160 sc->ffindex, sample->pos);
4161 return AVERROR_INVALIDDATA;
4163 ret = av_get_packet(sc->pb, pkt, sample->size);
4166 if (sc->has_palette) {
4169 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
4171 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
4173 memcpy(pal, sc->palette, AVPALETTE_SIZE);
4174 sc->has_palette = 0;
4177 #if CONFIG_DV_DEMUXER
4178 if (mov->dv_demux && sc->dv_audio_container) {
4179 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
4180 av_freep(&pkt->data);
4182 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
4189 pkt->stream_index = sc->ffindex;
4190 pkt->dts = sample->timestamp;
4191 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
4192 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
4193 /* update ctts context */
4195 if (sc->ctts_index < sc->ctts_count &&
4196 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
4198 sc->ctts_sample = 0;
4201 pkt->dts = AV_NOPTS_VALUE;
4203 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
4204 st->index_entries[sc->current_sample].timestamp : st->duration;
4205 pkt->duration = next_dts - pkt->dts;
4206 pkt->pts = pkt->dts;
4208 if (st->discard == AVDISCARD_ALL)
4210 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
4211 pkt->pos = sample->pos;
4212 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
4213 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
4217 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
4219 MOVStreamContext *sc = st->priv_data;
4220 int sample, time_sample;
4223 sample = av_index_search_timestamp(st, timestamp, flags);
4224 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
4225 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
4227 if (sample < 0) /* not sure what to do */
4228 return AVERROR_INVALIDDATA;
4229 sc->current_sample = sample;
4230 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
4231 /* adjust ctts index */
4232 if (sc->ctts_data) {
4234 for (i = 0; i < sc->ctts_count; i++) {
4235 int next = time_sample + sc->ctts_data[i].count;
4236 if (next > sc->current_sample) {
4238 sc->ctts_sample = sc->current_sample - time_sample;
4247 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
4250 int64_t seek_timestamp, timestamp;
4254 if (stream_index >= s->nb_streams)
4255 return AVERROR_INVALIDDATA;
4257 st = s->streams[stream_index];
4258 sample = mov_seek_stream(s, st, sample_time, flags);
4262 /* adjust seek timestamp to found sample timestamp */
4263 seek_timestamp = st->index_entries[sample].timestamp;
4265 for (i = 0; i < s->nb_streams; i++) {
4266 MOVStreamContext *sc = s->streams[i]->priv_data;
4268 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
4270 if (stream_index == i)
4273 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
4274 mov_seek_stream(s, st, timestamp, flags);
4279 #define OFFSET(x) offsetof(MOVContext, x)
4280 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
4281 static const AVOption mov_options[] = {
4282 {"use_absolute_path",
4283 "allow using absolute path when opening alias, this is a possible security issue",
4284 OFFSET(use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
4286 {"ignore_editlist", "", OFFSET(ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
4289 "use mfra for fragment timestamps",
4290 OFFSET(use_mfra_for), FF_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
4291 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
4293 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
4294 FLAGS, "use_mfra_for" },
4295 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
4296 FLAGS, "use_mfra_for" },
4297 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
4298 FLAGS, "use_mfra_for" },
4299 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
4300 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
4301 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
4302 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
4306 static const AVClass mov_class = {
4307 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
4308 .item_name = av_default_item_name,
4309 .option = mov_options,
4310 .version = LIBAVUTIL_VERSION_INT,
4313 AVInputFormat ff_mov_demuxer = {
4314 .name = "mov,mp4,m4a,3gp,3g2,mj2",
4315 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
4316 .priv_class = &mov_class,
4317 .priv_data_size = sizeof(MOVContext),
4318 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
4319 .read_probe = mov_probe,
4320 .read_header = mov_read_header,
4321 .read_packet = mov_read_packet,
4322 .read_close = mov_read_close,
4323 .read_seek = mov_read_seek,
4324 .flags = AVFMT_NO_BYTE_SEEK,