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/internal.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/intfloat.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/time_internal.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/display.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/aes.h"
42 #include "libavutil/sha.h"
43 #include "libavutil/timecode.h"
44 #include "libavcodec/ac3tab.h"
47 #include "avio_internal.h"
50 #include "libavcodec/get_bits.h"
53 #include "replaygain.h"
59 #include "qtpalette.h"
61 /* those functions parse an atom */
62 /* links atom IDs to parse functions */
63 typedef struct MOVParseTableEntry {
65 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
68 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
69 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
71 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
72 unsigned len, const char *key)
76 short current, total = 0;
77 avio_rb16(pb); // unknown
78 current = avio_rb16(pb);
80 total = avio_rb16(pb);
82 snprintf(buf, sizeof(buf), "%d", current);
84 snprintf(buf, sizeof(buf), "%d/%d", current, total);
85 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
86 av_dict_set(&c->fc->metadata, key, buf, 0);
91 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
92 unsigned len, const char *key)
94 /* bypass padding bytes */
99 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
100 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
105 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
106 unsigned len, const char *key)
108 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
109 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
114 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
115 unsigned len, const char *key)
119 avio_r8(pb); // unknown
122 if (genre < 1 || genre > ID3v1_GENRE_MAX)
124 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
125 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
130 static const uint32_t mac_to_unicode[128] = {
131 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
132 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
133 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
134 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
135 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
136 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
137 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
138 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
139 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
140 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
141 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
142 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
143 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
144 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
145 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
146 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
149 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
150 char *dst, int dstlen)
153 char *end = dst+dstlen-1;
156 for (i = 0; i < len; i++) {
157 uint8_t t, c = avio_r8(pb);
158 if (c < 0x80 && p < end)
161 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
167 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
171 MOVStreamContext *sc;
176 case 0xd: id = AV_CODEC_ID_MJPEG; break;
177 case 0xe: id = AV_CODEC_ID_PNG; break;
178 case 0x1b: id = AV_CODEC_ID_BMP; break;
180 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
185 st = avformat_new_stream(c->fc, NULL);
187 return AVERROR(ENOMEM);
188 sc = av_mallocz(sizeof(*sc));
190 return AVERROR(ENOMEM);
193 ret = av_get_packet(pb, &pkt, len);
197 if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
198 if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
199 id = AV_CODEC_ID_PNG;
201 id = AV_CODEC_ID_MJPEG;
205 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
207 st->attached_pic = pkt;
208 st->attached_pic.stream_index = st->index;
209 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
211 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
212 st->codec->codec_id = id;
217 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
219 char language[4] = { 0 };
220 char buf[200], place[100];
221 uint16_t langcode = 0;
222 double longitude, latitude, altitude;
223 const char *key = "location";
225 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
226 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
227 return AVERROR_INVALIDDATA;
230 avio_skip(pb, 4); // version+flags
231 langcode = avio_rb16(pb);
232 ff_mov_lang_to_iso639(langcode, language);
235 len -= avio_get_str(pb, len, place, sizeof(place));
237 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
238 return AVERROR_INVALIDDATA;
240 avio_skip(pb, 1); // role
244 av_log(c->fc, AV_LOG_ERROR, "no space for coordinates left (%d)\n", len);
245 return AVERROR_INVALIDDATA;
247 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
248 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
249 altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
251 // Try to output in the same format as the ?xyz field
252 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
254 av_strlcatf(buf, sizeof(buf), "%+f", altitude);
255 av_strlcatf(buf, sizeof(buf), "/%s", place);
257 if (*language && strcmp(language, "und")) {
259 snprintf(key2, sizeof(key2), "%s-%s", key, language);
260 av_dict_set(&c->fc->metadata, key2, buf, 0);
262 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
263 return av_dict_set(&c->fc->metadata, key, buf, 0);
266 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
269 char key2[32], language[4] = {0};
271 const char *key = NULL;
272 uint16_t langcode = 0;
273 uint32_t data_type = 0, str_size, str_size_alloc;
274 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
279 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
280 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
281 case MKTAG( 'X','M','P','_'):
282 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
283 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
284 case MKTAG( 'a','k','I','D'): key = "account_type";
285 parse = mov_metadata_int8_no_padding; break;
286 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
287 case MKTAG( 'c','a','t','g'): key = "category"; break;
288 case MKTAG( 'c','p','i','l'): key = "compilation";
289 parse = mov_metadata_int8_no_padding; break;
290 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
291 case MKTAG( 'd','e','s','c'): key = "description"; break;
292 case MKTAG( 'd','i','s','k'): key = "disc";
293 parse = mov_metadata_track_or_disc_number; break;
294 case MKTAG( 'e','g','i','d'): key = "episode_uid";
295 parse = mov_metadata_int8_no_padding; break;
296 case MKTAG( 'g','n','r','e'): key = "genre";
297 parse = mov_metadata_gnre; break;
298 case MKTAG( 'h','d','v','d'): key = "hd_video";
299 parse = mov_metadata_int8_no_padding; break;
300 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
301 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
302 case MKTAG( 'l','o','c','i'):
303 return mov_metadata_loci(c, pb, atom.size);
304 case MKTAG( 'p','c','s','t'): key = "podcast";
305 parse = mov_metadata_int8_no_padding; break;
306 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
307 parse = mov_metadata_int8_no_padding; break;
308 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
309 case MKTAG( 'r','t','n','g'): key = "rating";
310 parse = mov_metadata_int8_no_padding; break;
311 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
312 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
313 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
314 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
315 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
316 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
317 case MKTAG( 's','t','i','k'): key = "media_type";
318 parse = mov_metadata_int8_no_padding; break;
319 case MKTAG( 't','r','k','n'): key = "track";
320 parse = mov_metadata_track_or_disc_number; break;
321 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
322 case MKTAG( 't','v','e','s'): key = "episode_sort";
323 parse = mov_metadata_int8_bypass_padding; break;
324 case MKTAG( 't','v','n','n'): key = "network"; break;
325 case MKTAG( 't','v','s','h'): key = "show"; break;
326 case MKTAG( 't','v','s','n'): key = "season_number";
327 parse = mov_metadata_int8_bypass_padding; break;
328 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
329 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
330 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
331 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
332 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
333 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
334 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
335 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
336 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
337 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
338 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
339 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
340 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
341 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
342 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
343 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
344 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
345 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
346 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
347 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
348 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
349 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
350 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
351 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
352 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
353 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
354 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
355 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
356 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
357 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
358 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
359 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
360 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
361 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
362 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
365 if (c->itunes_metadata && atom.size > 8) {
366 int data_size = avio_rb32(pb);
367 int tag = avio_rl32(pb);
368 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
369 data_type = avio_rb32(pb); // type
370 avio_rb32(pb); // unknown
371 str_size = data_size - 16;
374 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
375 int ret = mov_read_covr(c, pb, data_type, str_size);
377 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
380 } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
381 uint32_t index = AV_RB32(&atom.type);
382 if (index < c->meta_keys_count) {
383 key = c->meta_keys[index];
385 av_log(c->fc, AV_LOG_WARNING,
386 "The index of 'data' is out of range: %d >= %d.\n",
387 index, c->meta_keys_count);
391 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
392 str_size = avio_rb16(pb); // string length
393 if (str_size > atom.size) {
395 avio_seek(pb, -2, SEEK_CUR);
396 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
399 langcode = avio_rb16(pb);
400 ff_mov_lang_to_iso639(langcode, language);
403 str_size = atom.size;
405 if (c->export_all && !key) {
406 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
412 if (atom.size < 0 || str_size >= INT_MAX/2)
413 return AVERROR_INVALIDDATA;
415 // Allocates enough space if data_type is a float32 number, otherwise
416 // worst-case requirement for output string in case of utf8 coded input
417 num = (data_type == 23);
418 str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
419 str = av_mallocz(str_size_alloc);
421 return AVERROR(ENOMEM);
424 parse(c, pb, str_size, key);
426 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
427 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
428 } else if (data_type == 23 && str_size >= 4) { // BE float32
429 float val = av_int2float(avio_rb32(pb));
430 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
431 av_log(c->fc, AV_LOG_ERROR,
432 "Failed to store the float32 number (%f) in string.\n", val);
434 return AVERROR_INVALIDDATA;
437 int ret = ffio_read_size(pb, str, str_size);
444 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
445 av_dict_set(&c->fc->metadata, key, str, 0);
446 if (*language && strcmp(language, "und")) {
447 snprintf(key2, sizeof(key2), "%s-%s", key, language);
448 av_dict_set(&c->fc->metadata, key2, str, 0);
451 av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
452 av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
453 key, str, (char*)&atom.type, str_size_alloc, atom.size);
459 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
462 int i, nb_chapters, str_len, version;
466 if (c->ignore_chapters)
469 if ((atom.size -= 5) < 0)
472 version = avio_r8(pb);
475 avio_rb32(pb); // ???
476 nb_chapters = avio_r8(pb);
478 for (i = 0; i < nb_chapters; i++) {
482 start = avio_rb64(pb);
483 str_len = avio_r8(pb);
485 if ((atom.size -= 9+str_len) < 0)
488 ret = ffio_read_size(pb, str, str_len);
492 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
497 #define MIN_DATA_ENTRY_BOX_SIZE 12
498 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
501 MOVStreamContext *sc;
504 if (c->fc->nb_streams < 1)
506 st = c->fc->streams[c->fc->nb_streams-1];
509 avio_rb32(pb); // version + flags
510 entries = avio_rb32(pb);
511 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
512 entries >= UINT_MAX / sizeof(*sc->drefs))
513 return AVERROR_INVALIDDATA;
516 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
518 return AVERROR(ENOMEM);
519 sc->drefs_count = entries;
521 for (i = 0; i < entries; i++) {
522 MOVDref *dref = &sc->drefs[i];
523 uint32_t size = avio_rb32(pb);
524 int64_t next = avio_tell(pb) + size - 4;
527 return AVERROR_INVALIDDATA;
529 dref->type = avio_rl32(pb);
530 avio_rb32(pb); // version + flags
531 av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
533 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
534 /* macintosh alias record */
535 uint16_t volume_len, len;
541 volume_len = avio_r8(pb);
542 volume_len = FFMIN(volume_len, 27);
543 ret = ffio_read_size(pb, dref->volume, 27);
546 dref->volume[volume_len] = 0;
547 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
552 len = FFMIN(len, 63);
553 ret = ffio_read_size(pb, dref->filename, 63);
556 dref->filename[len] = 0;
557 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
561 /* read next level up_from_alias/down_to_target */
562 dref->nlvl_from = avio_rb16(pb);
563 dref->nlvl_to = avio_rb16(pb);
564 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
565 dref->nlvl_from, dref->nlvl_to);
569 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
572 type = avio_rb16(pb);
574 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
577 if (type == 2) { // absolute path
579 dref->path = av_mallocz(len+1);
581 return AVERROR(ENOMEM);
583 ret = ffio_read_size(pb, dref->path, len);
585 av_freep(&dref->path);
588 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
590 memmove(dref->path, dref->path+volume_len, len);
593 for (j = 0; j < len; j++)
594 if (dref->path[j] == ':' || dref->path[j] == 0)
596 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
597 } else if (type == 0) { // directory name
599 dref->dir = av_malloc(len+1);
601 return AVERROR(ENOMEM);
603 ret = ffio_read_size(pb, dref->dir, len);
605 av_freep(&dref->dir);
609 for (j = 0; j < len; j++)
610 if (dref->dir[j] == ':')
612 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
617 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x08%x size %d\n",
622 avio_seek(pb, next, SEEK_SET);
627 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
631 uint32_t av_unused ctype;
636 avio_r8(pb); /* version */
637 avio_rb24(pb); /* flags */
640 ctype = avio_rl32(pb);
641 type = avio_rl32(pb); /* component subtype */
643 av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
644 av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
646 if (c->fc->nb_streams < 1) { // meta before first trak
647 if (type == MKTAG('m','d','t','a')) {
648 c->found_hdlr_mdta = 1;
653 st = c->fc->streams[c->fc->nb_streams-1];
655 if (type == MKTAG('v','i','d','e'))
656 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
657 else if (type == MKTAG('s','o','u','n'))
658 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
659 else if (type == MKTAG('m','1','a',' '))
660 st->codec->codec_id = AV_CODEC_ID_MP2;
661 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
662 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
664 avio_rb32(pb); /* component manufacture */
665 avio_rb32(pb); /* component flags */
666 avio_rb32(pb); /* component flags mask */
668 title_size = atom.size - 24;
669 if (title_size > 0) {
670 title_str = av_malloc(title_size + 1); /* Add null terminator */
672 return AVERROR(ENOMEM);
674 ret = ffio_read_size(pb, title_str, title_size);
676 av_freep(&title_str);
679 title_str[title_size] = 0;
681 int off = (!c->isom && title_str[0] == title_size - 1);
682 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
684 av_freep(&title_str);
690 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
695 if (fc->nb_streams < 1)
697 st = fc->streams[fc->nb_streams-1];
699 avio_rb32(pb); /* version + flags */
700 ff_mp4_read_descr(fc, pb, &tag);
701 if (tag == MP4ESDescrTag) {
702 ff_mp4_parse_es_descr(pb, NULL);
704 avio_rb16(pb); /* ID */
706 ff_mp4_read_descr(fc, pb, &tag);
707 if (tag == MP4DecConfigDescrTag)
708 ff_mp4_read_dec_config_descr(fc, st, pb);
712 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
714 return ff_mov_read_esds(c->fc, pb);
717 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
720 enum AVAudioServiceType *ast;
721 int ac3info, acmod, lfeon, bsmod;
723 if (c->fc->nb_streams < 1)
725 st = c->fc->streams[c->fc->nb_streams-1];
727 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
730 return AVERROR(ENOMEM);
732 ac3info = avio_rb24(pb);
733 bsmod = (ac3info >> 14) & 0x7;
734 acmod = (ac3info >> 11) & 0x7;
735 lfeon = (ac3info >> 10) & 0x1;
736 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
737 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
739 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
741 if (st->codec->channels > 1 && bsmod == 0x7)
742 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
744 st->codec->audio_service_type = *ast;
749 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
752 enum AVAudioServiceType *ast;
753 int eac3info, acmod, lfeon, bsmod;
755 if (c->fc->nb_streams < 1)
757 st = c->fc->streams[c->fc->nb_streams-1];
759 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
762 return AVERROR(ENOMEM);
764 /* No need to parse fields for additional independent substreams and its
765 * associated dependent substreams since libavcodec's E-AC-3 decoder
766 * does not support them yet. */
767 avio_rb16(pb); /* data_rate and num_ind_sub */
768 eac3info = avio_rb24(pb);
769 bsmod = (eac3info >> 12) & 0x1f;
770 acmod = (eac3info >> 9) & 0x7;
771 lfeon = (eac3info >> 8) & 0x1;
772 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
774 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
775 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
777 if (st->codec->channels > 1 && bsmod == 0x7)
778 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
780 st->codec->audio_service_type = *ast;
785 static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
787 const uint32_t ddts_size = 20;
790 uint32_t frame_duration_code = 0;
791 uint32_t channel_layout_code = 0;
794 buf = av_malloc(ddts_size + FF_INPUT_BUFFER_PADDING_SIZE);
796 return AVERROR(ENOMEM);
798 if (avio_read(pb, buf, ddts_size) < ddts_size) {
800 return AVERROR_INVALIDDATA;
803 init_get_bits(&gb, buf, 8*ddts_size);
805 if (c->fc->nb_streams < 1) {
808 st = c->fc->streams[c->fc->nb_streams-1];
810 st->codec->sample_rate = get_bits_long(&gb, 32);
811 skip_bits_long(&gb, 32); /* max bitrate */
812 st->codec->bit_rate = get_bits_long(&gb, 32);
813 st->codec->bits_per_coded_sample = get_bits(&gb, 8);
814 frame_duration_code = get_bits(&gb, 2);
815 skip_bits(&gb, 30); /* various fields */
816 channel_layout_code = get_bits(&gb, 16);
818 st->codec->frame_size =
819 (frame_duration_code == 0) ? 512 :
820 (frame_duration_code == 1) ? 1024 :
821 (frame_duration_code == 2) ? 2048 :
822 (frame_duration_code == 3) ? 4096 : 0;
824 if (channel_layout_code > 0xff) {
825 av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
827 st->codec->channel_layout =
828 ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
829 ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
830 ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
831 ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
832 ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
833 ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
835 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
840 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
844 if (c->fc->nb_streams < 1)
846 st = c->fc->streams[c->fc->nb_streams-1];
851 /* skip version and flags */
854 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
859 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
864 if (c->fc->nb_streams < 1)
866 st = c->fc->streams[c->fc->nb_streams-1];
868 if ((ret = ff_get_wav_header(c->fc, pb, st->codec, atom.size, 0)) < 0)
869 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
874 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
876 const int num = avio_rb32(pb);
877 const int den = avio_rb32(pb);
880 if (c->fc->nb_streams < 1)
882 st = c->fc->streams[c->fc->nb_streams-1];
884 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
885 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
886 av_log(c->fc, AV_LOG_WARNING,
887 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
888 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
890 } else if (den != 0) {
891 av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
897 /* this atom contains actual media data */
898 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
900 if (atom.size == 0) /* wrong one (MP4) */
903 return 0; /* now go for moov */
906 #define DRM_BLOB_SIZE 56
908 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
910 uint8_t intermediate_key[20];
911 uint8_t intermediate_iv[20];
914 uint8_t file_checksum[20];
915 uint8_t calculated_checksum[20];
919 uint8_t *activation_bytes = c->activation_bytes;
920 uint8_t *fixed_key = c->audible_fixed_key;
924 sha = av_sha_alloc();
926 return AVERROR(ENOMEM);
927 c->aes_decrypt = av_aes_alloc();
928 if (!c->aes_decrypt) {
929 ret = AVERROR(ENOMEM);
933 /* drm blob processing */
934 avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
935 avio_read(pb, input, DRM_BLOB_SIZE);
936 avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
937 avio_read(pb, file_checksum, 20);
939 av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
940 for (i = 0; i < 20; i++)
941 av_log(sha, AV_LOG_INFO, "%02x", file_checksum[i]);
942 av_log(c->fc, AV_LOG_INFO, "\n");
944 /* verify activation data */
945 if (!activation_bytes) {
946 av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
947 ret = 0; /* allow ffprobe to continue working on .aax files */
950 if (c->activation_bytes_size != 4) {
951 av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
952 ret = AVERROR(EINVAL);
956 /* verify fixed key */
957 if (c->audible_fixed_key_size != 16) {
958 av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
959 ret = AVERROR(EINVAL);
963 /* AAX (and AAX+) key derivation */
964 av_sha_init(sha, 160);
965 av_sha_update(sha, fixed_key, 16);
966 av_sha_update(sha, activation_bytes, 4);
967 av_sha_final(sha, intermediate_key);
968 av_sha_init(sha, 160);
969 av_sha_update(sha, fixed_key, 16);
970 av_sha_update(sha, intermediate_key, 20);
971 av_sha_update(sha, activation_bytes, 4);
972 av_sha_final(sha, intermediate_iv);
973 av_sha_init(sha, 160);
974 av_sha_update(sha, intermediate_key, 16);
975 av_sha_update(sha, intermediate_iv, 16);
976 av_sha_final(sha, calculated_checksum);
977 if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
978 av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
979 ret = AVERROR_INVALIDDATA;
982 av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
983 av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
984 for (i = 0; i < 4; i++) {
985 // file data (in output) is stored in big-endian mode
986 if (activation_bytes[i] != output[3 - i]) { // critical error
987 av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
988 ret = AVERROR_INVALIDDATA;
992 memcpy(c->file_key, output + 8, 16);
993 memcpy(input, output + 26, 16);
994 av_sha_init(sha, 160);
995 av_sha_update(sha, input, 16);
996 av_sha_update(sha, c->file_key, 16);
997 av_sha_update(sha, fixed_key, 16);
998 av_sha_final(sha, c->file_iv);
1006 // Audible AAX (and AAX+) bytestream decryption
1007 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1010 unsigned char iv[16];
1012 memcpy(iv, c->file_iv, 16); // iv is overwritten
1013 blocks = size >> 4; // trailing bytes are not encrypted!
1014 av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1015 av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1020 /* read major brand, minor version and compatible brands and store them as metadata */
1021 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1024 int comp_brand_size;
1025 char* comp_brands_str;
1026 uint8_t type[5] = {0};
1027 int ret = ffio_read_size(pb, type, 4);
1031 if (strcmp(type, "qt "))
1033 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1034 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1035 minor_ver = avio_rb32(pb); /* minor version */
1036 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1038 comp_brand_size = atom.size - 8;
1039 if (comp_brand_size < 0)
1040 return AVERROR_INVALIDDATA;
1041 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1042 if (!comp_brands_str)
1043 return AVERROR(ENOMEM);
1045 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1047 av_freep(&comp_brands_str);
1050 comp_brands_str[comp_brand_size] = 0;
1051 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1052 av_freep(&comp_brands_str);
1057 /* this atom should contain all header atoms */
1058 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1062 if (c->found_moov) {
1063 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1064 avio_skip(pb, atom.size);
1068 if ((ret = mov_read_default(c, pb, atom)) < 0)
1070 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1071 /* so we don't parse the whole file if over a network */
1073 return 0; /* now go for mdat */
1076 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1078 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1079 c->has_looked_for_mfra = 1;
1082 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1084 if ((ret = mov_read_mfra(c, pb)) < 0) {
1085 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1086 "read the mfra (may be a live ismv)\n");
1089 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1090 "seekable, can not look for mfra\n");
1093 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
1094 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1095 return mov_read_default(c, pb, atom);
1098 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1102 struct tm *ptm, tmbuf;
1104 if(time >= 2082844800)
1105 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1107 ptm = gmtime_r(&timet, &tmbuf);
1109 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
1110 av_dict_set(metadata, "creation_time", buffer, 0);
1114 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1117 MOVStreamContext *sc;
1119 char language[4] = {0};
1121 int64_t creation_time;
1123 if (c->fc->nb_streams < 1)
1125 st = c->fc->streams[c->fc->nb_streams-1];
1128 if (sc->time_scale) {
1129 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1130 return AVERROR_INVALIDDATA;
1133 version = avio_r8(pb);
1135 avpriv_request_sample(c->fc, "Version %d", version);
1136 return AVERROR_PATCHWELCOME;
1138 avio_rb24(pb); /* flags */
1140 creation_time = avio_rb64(pb);
1143 creation_time = avio_rb32(pb);
1144 avio_rb32(pb); /* modification time */
1146 mov_metadata_creation_time(&st->metadata, creation_time);
1148 sc->time_scale = avio_rb32(pb);
1149 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1151 lang = avio_rb16(pb); /* language */
1152 if (ff_mov_lang_to_iso639(lang, language))
1153 av_dict_set(&st->metadata, "language", language, 0);
1154 avio_rb16(pb); /* quality */
1159 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1161 int64_t creation_time;
1162 int version = avio_r8(pb); /* version */
1163 avio_rb24(pb); /* flags */
1166 creation_time = avio_rb64(pb);
1169 creation_time = avio_rb32(pb);
1170 avio_rb32(pb); /* modification time */
1172 mov_metadata_creation_time(&c->fc->metadata, creation_time);
1173 c->time_scale = avio_rb32(pb); /* time scale */
1175 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1177 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1178 // set the AVCodecContext duration because the duration of individual tracks
1179 // may be inaccurate
1180 if (c->time_scale > 0 && !c->trex_data)
1181 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1182 avio_rb32(pb); /* preferred scale */
1184 avio_rb16(pb); /* preferred volume */
1186 avio_skip(pb, 10); /* reserved */
1188 avio_skip(pb, 36); /* display matrix */
1190 avio_rb32(pb); /* preview time */
1191 avio_rb32(pb); /* preview duration */
1192 avio_rb32(pb); /* poster time */
1193 avio_rb32(pb); /* selection time */
1194 avio_rb32(pb); /* selection duration */
1195 avio_rb32(pb); /* current time */
1196 avio_rb32(pb); /* next track ID */
1201 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1206 if (c->fc->nb_streams < 1)
1208 st = c->fc->streams[c->fc->nb_streams-1];
1210 little_endian = avio_rb16(pb) & 0xFF;
1211 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1212 if (little_endian == 1) {
1213 switch (st->codec->codec_id) {
1214 case AV_CODEC_ID_PCM_S24BE:
1215 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
1217 case AV_CODEC_ID_PCM_S32BE:
1218 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
1220 case AV_CODEC_ID_PCM_F32BE:
1221 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
1223 case AV_CODEC_ID_PCM_F64BE:
1224 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
1233 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1236 char color_parameter_type[5] = { 0 };
1237 uint16_t color_primaries, color_trc, color_matrix;
1240 if (c->fc->nb_streams < 1)
1242 st = c->fc->streams[c->fc->nb_streams - 1];
1244 ret = ffio_read_size(pb, color_parameter_type, 4);
1247 if (strncmp(color_parameter_type, "nclx", 4) &&
1248 strncmp(color_parameter_type, "nclc", 4)) {
1249 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1250 color_parameter_type);
1254 color_primaries = avio_rb16(pb);
1255 color_trc = avio_rb16(pb);
1256 color_matrix = avio_rb16(pb);
1258 av_log(c->fc, AV_LOG_TRACE,
1259 "%s: pri %d trc %d matrix %d",
1260 color_parameter_type, color_primaries, color_trc, color_matrix);
1262 if (!strncmp(color_parameter_type, "nclx", 4)) {
1263 uint8_t color_range = avio_r8(pb) >> 7;
1264 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1266 st->codec->color_range = AVCOL_RANGE_JPEG;
1268 st->codec->color_range = AVCOL_RANGE_MPEG;
1269 /* 14496-12 references JPEG XR specs (rather than the more complete
1270 * 23001-8) so some adjusting is required */
1271 if (color_primaries >= AVCOL_PRI_FILM)
1272 color_primaries = AVCOL_PRI_UNSPECIFIED;
1273 if ((color_trc >= AVCOL_TRC_LINEAR &&
1274 color_trc <= AVCOL_TRC_LOG_SQRT) ||
1275 color_trc >= AVCOL_TRC_BT2020_10)
1276 color_trc = AVCOL_TRC_UNSPECIFIED;
1277 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
1278 color_matrix = AVCOL_SPC_UNSPECIFIED;
1279 st->codec->color_primaries = color_primaries;
1280 st->codec->color_trc = color_trc;
1281 st->codec->colorspace = color_matrix;
1282 } else if (!strncmp(color_parameter_type, "nclc", 4)) {
1283 /* color primaries, Table 4-4 */
1284 switch (color_primaries) {
1285 case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
1286 case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
1287 case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
1289 /* color transfer, Table 4-5 */
1290 switch (color_trc) {
1291 case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
1292 case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
1294 /* color matrix, Table 4-6 */
1295 switch (color_matrix) {
1296 case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
1297 case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
1298 case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
1301 av_log(c->fc, AV_LOG_TRACE, "\n");
1306 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1309 unsigned mov_field_order;
1310 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1312 if (c->fc->nb_streams < 1) // will happen with jp2 files
1314 st = c->fc->streams[c->fc->nb_streams-1];
1316 return AVERROR_INVALIDDATA;
1317 mov_field_order = avio_rb16(pb);
1318 if ((mov_field_order & 0xFF00) == 0x0100)
1319 decoded_field_order = AV_FIELD_PROGRESSIVE;
1320 else if ((mov_field_order & 0xFF00) == 0x0200) {
1321 switch (mov_field_order & 0xFF) {
1322 case 0x01: decoded_field_order = AV_FIELD_TT;
1324 case 0x06: decoded_field_order = AV_FIELD_BB;
1326 case 0x09: decoded_field_order = AV_FIELD_TB;
1328 case 0x0E: decoded_field_order = AV_FIELD_BT;
1332 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1333 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1335 st->codec->field_order = decoded_field_order;
1340 static int mov_realloc_extradata(AVCodecContext *codec, MOVAtom atom)
1343 uint64_t size = (uint64_t)codec->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1344 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1345 return AVERROR_INVALIDDATA;
1346 if ((err = av_reallocp(&codec->extradata, size)) < 0) {
1347 codec->extradata_size = 0;
1350 codec->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1354 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1355 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1356 AVCodecContext *codec, uint8_t *buf)
1358 int64_t result = atom.size;
1361 AV_WB32(buf , atom.size + 8);
1362 AV_WL32(buf + 4, atom.type);
1363 err = ffio_read_size(pb, buf + 8, atom.size);
1365 codec->extradata_size -= atom.size;
1367 } else if (err < atom.size) {
1368 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1369 codec->extradata_size -= atom.size - err;
1372 memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1376 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
1377 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1378 enum AVCodecID codec_id)
1381 uint64_t original_size;
1384 if (c->fc->nb_streams < 1) // will happen with jp2 files
1386 st = c->fc->streams[c->fc->nb_streams-1];
1388 if (st->codec->codec_id != codec_id)
1389 return 0; /* unexpected codec_id - don't mess with extradata */
1391 original_size = st->codec->extradata_size;
1392 err = mov_realloc_extradata(st->codec, atom);
1396 err = mov_read_atom_into_extradata(c, pb, atom, st->codec, st->codec->extradata + original_size);
1399 return 0; // Note: this is the original behavior to ignore truncation.
1402 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1403 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1405 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1408 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1410 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1413 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1415 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1418 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1420 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1423 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1425 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1427 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1431 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1433 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1435 if (!ret && c->fc->nb_streams >= 1) {
1436 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
1437 if (avctx->extradata_size >= 40) {
1438 avctx->height = AV_RB16(&avctx->extradata[36]);
1439 avctx->width = AV_RB16(&avctx->extradata[38]);
1445 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1447 if (c->fc->nb_streams >= 1) {
1448 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1449 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1450 codec->codec_id == AV_CODEC_ID_H264 &&
1453 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1454 if (avio_rb16(pb) == 0xd4d)
1455 codec->width = 1440;
1460 return mov_read_avid(c, pb, atom);
1463 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1467 uint64_t original_size;
1468 if (c->fc->nb_streams >= 1) {
1469 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1470 if (codec->codec_id == AV_CODEC_ID_H264)
1472 if (atom.size == 16) {
1473 original_size = codec->extradata_size;
1474 ret = mov_realloc_extradata(codec, atom);
1476 length = mov_read_atom_into_extradata(c, pb, atom, codec, codec->extradata + original_size);
1477 if (length == atom.size) {
1478 const uint8_t range_value = codec->extradata[original_size + 19];
1479 switch (range_value) {
1481 codec->color_range = AVCOL_RANGE_MPEG;
1484 codec->color_range = AVCOL_RANGE_JPEG;
1487 av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1490 ff_dlog(c, "color_range: %d\n", codec->color_range);
1492 /* For some reason the whole atom was not added to the extradata */
1493 av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1496 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1499 av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1506 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1508 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1511 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1516 if (c->fc->nb_streams < 1)
1518 st = c->fc->streams[c->fc->nb_streams-1];
1520 if ((uint64_t)atom.size > (1<<30))
1521 return AVERROR_INVALIDDATA;
1523 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1524 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1525 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1526 // pass all frma atom to codec, needed at least for QDMC and QDM2
1527 av_freep(&st->codec->extradata);
1528 ret = ff_get_extradata(st->codec, pb, atom.size);
1531 } else if (atom.size > 8) { /* to read frma, esds atoms */
1532 if (st->codec->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1534 ret = ffio_ensure_seekback(pb, 8);
1537 buffer = avio_rb64(pb);
1539 if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1540 && buffer >> 32 <= atom.size
1541 && buffer >> 32 >= 8) {
1544 } else if (!st->codec->extradata_size) {
1545 #define ALAC_EXTRADATA_SIZE 36
1546 st->codec->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1547 if (!st->codec->extradata)
1548 return AVERROR(ENOMEM);
1549 st->codec->extradata_size = ALAC_EXTRADATA_SIZE;
1550 AV_WB32(st->codec->extradata , ALAC_EXTRADATA_SIZE);
1551 AV_WB32(st->codec->extradata + 4, MKTAG('a','l','a','c'));
1552 AV_WB64(st->codec->extradata + 12, buffer);
1553 avio_read(pb, st->codec->extradata + 20, 16);
1554 avio_skip(pb, atom.size - 24);
1558 if ((ret = mov_read_default(c, pb, atom)) < 0)
1561 avio_skip(pb, atom.size);
1566 * This function reads atom content and puts data in extradata without tag
1567 * nor size unlike mov_read_extradata.
1569 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1574 if (c->fc->nb_streams < 1)
1576 st = c->fc->streams[c->fc->nb_streams-1];
1578 if ((uint64_t)atom.size > (1<<30))
1579 return AVERROR_INVALIDDATA;
1581 if (atom.size >= 10) {
1582 // Broken files created by legacy versions of libavformat will
1583 // wrap a whole fiel atom inside of a glbl atom.
1584 unsigned size = avio_rb32(pb);
1585 unsigned type = avio_rl32(pb);
1586 avio_seek(pb, -8, SEEK_CUR);
1587 if (type == MKTAG('f','i','e','l') && size == atom.size)
1588 return mov_read_default(c, pb, atom);
1590 if (st->codec->extradata_size > 1 && st->codec->extradata) {
1591 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1594 av_freep(&st->codec->extradata);
1595 ret = ff_get_extradata(st->codec, pb, atom.size);
1602 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1605 uint8_t profile_level;
1608 if (c->fc->nb_streams < 1)
1610 st = c->fc->streams[c->fc->nb_streams-1];
1612 if (atom.size >= (1<<28) || atom.size < 7)
1613 return AVERROR_INVALIDDATA;
1615 profile_level = avio_r8(pb);
1616 if ((profile_level & 0xf0) != 0xc0)
1619 avio_seek(pb, 6, SEEK_CUR);
1620 av_freep(&st->codec->extradata);
1621 ret = ff_get_extradata(st->codec, pb, atom.size - 7);
1629 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1630 * but can have extradata appended at the end after the 40 bytes belonging
1633 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1638 if (c->fc->nb_streams < 1)
1640 if (atom.size <= 40)
1642 st = c->fc->streams[c->fc->nb_streams-1];
1644 if ((uint64_t)atom.size > (1<<30))
1645 return AVERROR_INVALIDDATA;
1648 av_freep(&st->codec->extradata);
1649 ret = ff_get_extradata(st->codec, pb, atom.size - 40);
1656 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1659 MOVStreamContext *sc;
1660 unsigned int i, entries;
1662 if (c->fc->nb_streams < 1)
1664 st = c->fc->streams[c->fc->nb_streams-1];
1667 avio_r8(pb); /* version */
1668 avio_rb24(pb); /* flags */
1670 entries = avio_rb32(pb);
1675 if (sc->chunk_offsets)
1676 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1677 av_free(sc->chunk_offsets);
1678 sc->chunk_count = 0;
1679 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1680 if (!sc->chunk_offsets)
1681 return AVERROR(ENOMEM);
1682 sc->chunk_count = entries;
1684 if (atom.type == MKTAG('s','t','c','o'))
1685 for (i = 0; i < entries && !pb->eof_reached; i++)
1686 sc->chunk_offsets[i] = avio_rb32(pb);
1687 else if (atom.type == MKTAG('c','o','6','4'))
1688 for (i = 0; i < entries && !pb->eof_reached; i++)
1689 sc->chunk_offsets[i] = avio_rb64(pb);
1691 return AVERROR_INVALIDDATA;
1693 sc->chunk_count = i;
1695 if (pb->eof_reached)
1702 * Compute codec id for 'lpcm' tag.
1703 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1705 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1712 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1715 static int mov_codec_id(AVStream *st, uint32_t format)
1717 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1720 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1721 (format & 0xFFFF) == 'T' + ('S' << 8)))
1722 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1724 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1725 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1726 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1727 /* skip old asf mpeg4 tag */
1728 format && format != MKTAG('m','p','4','s')) {
1729 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1731 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1733 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1734 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1735 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1736 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1737 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1739 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1743 st->codec->codec_tag = format;
1748 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1749 AVStream *st, MOVStreamContext *sc)
1751 uint8_t codec_name[32];
1752 unsigned int color_depth, len, j;
1753 int color_greyscale;
1756 avio_rb16(pb); /* version */
1757 avio_rb16(pb); /* revision level */
1758 avio_rb32(pb); /* vendor */
1759 avio_rb32(pb); /* temporal quality */
1760 avio_rb32(pb); /* spatial quality */
1762 st->codec->width = avio_rb16(pb); /* width */
1763 st->codec->height = avio_rb16(pb); /* height */
1765 avio_rb32(pb); /* horiz resolution */
1766 avio_rb32(pb); /* vert resolution */
1767 avio_rb32(pb); /* data size, always 0 */
1768 avio_rb16(pb); /* frames per samples */
1770 len = avio_r8(pb); /* codec name, pascal string */
1773 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1775 avio_skip(pb, 31 - len);
1778 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1780 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1781 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1782 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1783 st->codec->width &= ~1;
1784 st->codec->height &= ~1;
1786 /* Flash Media Server uses tag H263 with Sorenson Spark */
1787 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1788 !memcmp(codec_name, "Sorenson H263", 13))
1789 st->codec->codec_id = AV_CODEC_ID_FLV1;
1791 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1792 color_table_id = avio_rb16(pb); /* colortable id */
1793 av_log(c->fc, AV_LOG_TRACE, "depth %d, ctab id %d\n",
1794 st->codec->bits_per_coded_sample, color_table_id);
1795 /* figure out the palette situation */
1796 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1797 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1798 /* Do not create a greyscale palette for cinepak */
1799 if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1802 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1803 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1804 /* for palette traversal */
1805 unsigned int color_start, color_count, color_end;
1806 unsigned int a, r, g, b;
1808 if (color_greyscale) {
1809 int color_index, color_dec;
1810 /* compute the greyscale palette */
1811 st->codec->bits_per_coded_sample = color_depth;
1812 color_count = 1 << color_depth;
1814 color_dec = 256 / (color_count - 1);
1815 for (j = 0; j < color_count; j++) {
1816 r = g = b = color_index;
1817 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1818 color_index -= color_dec;
1819 if (color_index < 0)
1822 } else if (color_table_id) {
1823 const uint8_t *color_table;
1824 /* if flag bit 3 is set, use the default palette */
1825 color_count = 1 << color_depth;
1826 if (color_depth == 2)
1827 color_table = ff_qt_default_palette_4;
1828 else if (color_depth == 4)
1829 color_table = ff_qt_default_palette_16;
1831 color_table = ff_qt_default_palette_256;
1833 for (j = 0; j < color_count; j++) {
1834 r = color_table[j * 3 + 0];
1835 g = color_table[j * 3 + 1];
1836 b = color_table[j * 3 + 2];
1837 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1840 /* load the palette from the file */
1841 color_start = avio_rb32(pb);
1842 color_count = avio_rb16(pb);
1843 color_end = avio_rb16(pb);
1844 if ((color_start <= 255) && (color_end <= 255)) {
1845 for (j = color_start; j <= color_end; j++) {
1846 /* each A, R, G, or B component is 16 bits;
1847 * only use the top 8 bits */
1856 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1860 sc->has_palette = 1;
1864 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1865 AVStream *st, MOVStreamContext *sc)
1867 int bits_per_sample, flags;
1868 uint16_t version = avio_rb16(pb);
1869 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1871 avio_rb16(pb); /* revision level */
1872 avio_rb32(pb); /* vendor */
1874 st->codec->channels = avio_rb16(pb); /* channel count */
1875 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1876 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codec->channels);
1878 sc->audio_cid = avio_rb16(pb);
1879 avio_rb16(pb); /* packet size = 0 */
1881 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1883 // Read QT version 1 fields. In version 0 these do not exist.
1884 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1886 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1889 sc->samples_per_frame = avio_rb32(pb);
1890 avio_rb32(pb); /* bytes per packet */
1891 sc->bytes_per_frame = avio_rb32(pb);
1892 avio_rb32(pb); /* bytes per sample */
1893 } else if (version == 2) {
1894 avio_rb32(pb); /* sizeof struct only */
1895 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1896 st->codec->channels = avio_rb32(pb);
1897 avio_rb32(pb); /* always 0x7F000000 */
1898 st->codec->bits_per_coded_sample = avio_rb32(pb);
1900 flags = avio_rb32(pb); /* lpcm format specific flag */
1901 sc->bytes_per_frame = avio_rb32(pb);
1902 sc->samples_per_frame = avio_rb32(pb);
1903 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1904 st->codec->codec_id =
1905 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1908 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1909 /* can't correctly handle variable sized packet as audio unit */
1910 switch (st->codec->codec_id) {
1911 case AV_CODEC_ID_MP2:
1912 case AV_CODEC_ID_MP3:
1913 st->need_parsing = AVSTREAM_PARSE_FULL;
1919 switch (st->codec->codec_id) {
1920 case AV_CODEC_ID_PCM_S8:
1921 case AV_CODEC_ID_PCM_U8:
1922 if (st->codec->bits_per_coded_sample == 16)
1923 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1925 case AV_CODEC_ID_PCM_S16LE:
1926 case AV_CODEC_ID_PCM_S16BE:
1927 if (st->codec->bits_per_coded_sample == 8)
1928 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1929 else if (st->codec->bits_per_coded_sample == 24)
1930 st->codec->codec_id =
1931 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1932 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1933 else if (st->codec->bits_per_coded_sample == 32)
1934 st->codec->codec_id =
1935 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1936 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1938 /* set values for old format before stsd version 1 appeared */
1939 case AV_CODEC_ID_MACE3:
1940 sc->samples_per_frame = 6;
1941 sc->bytes_per_frame = 2 * st->codec->channels;
1943 case AV_CODEC_ID_MACE6:
1944 sc->samples_per_frame = 6;
1945 sc->bytes_per_frame = 1 * st->codec->channels;
1947 case AV_CODEC_ID_ADPCM_IMA_QT:
1948 sc->samples_per_frame = 64;
1949 sc->bytes_per_frame = 34 * st->codec->channels;
1951 case AV_CODEC_ID_GSM:
1952 sc->samples_per_frame = 160;
1953 sc->bytes_per_frame = 33;
1959 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1960 if (bits_per_sample) {
1961 st->codec->bits_per_coded_sample = bits_per_sample;
1962 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1966 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1967 AVStream *st, MOVStreamContext *sc,
1970 // ttxt stsd contains display flags, justification, background
1971 // color, fonts, and default styles, so fake an atom to read it
1972 MOVAtom fake_atom = { .size = size };
1973 // mp4s contains a regular esds atom
1974 if (st->codec->codec_tag != AV_RL32("mp4s"))
1975 mov_read_glbl(c, pb, fake_atom);
1976 st->codec->width = sc->width;
1977 st->codec->height = sc->height;
1980 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1985 y = (ycbcr >> 16) & 0xFF;
1986 cr = (ycbcr >> 8) & 0xFF;
1989 b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
1990 g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
1991 r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
1993 return (r << 16) | (g << 8) | b;
1996 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1998 char buf[256] = {0};
1999 uint8_t *src = st->codec->extradata;
2002 if (st->codec->extradata_size != 64)
2005 if (st->codec->width > 0 && st->codec->height > 0)
2006 snprintf(buf, sizeof(buf), "size: %dx%d\n",
2007 st->codec->width, st->codec->height);
2008 av_strlcat(buf, "palette: ", sizeof(buf));
2010 for (i = 0; i < 16; i++) {
2011 uint32_t yuv = AV_RB32(src + i * 4);
2012 uint32_t rgba = yuv_to_rgba(yuv);
2014 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2017 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2020 av_freep(&st->codec->extradata);
2021 st->codec->extradata_size = 0;
2022 st->codec->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
2023 if (!st->codec->extradata)
2024 return AVERROR(ENOMEM);
2025 st->codec->extradata_size = strlen(buf);
2026 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
2031 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2032 AVStream *st, MOVStreamContext *sc,
2037 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
2038 if ((int)size != size)
2039 return AVERROR(ENOMEM);
2041 ret = ff_get_extradata(st->codec, pb, size);
2045 MOVStreamContext *tmcd_ctx = st->priv_data;
2047 val = AV_RB32(st->codec->extradata + 4);
2048 tmcd_ctx->tmcd_flags = val;
2050 st->codec->flags2 |= AV_CODEC_FLAG2_DROP_FRAME_TIMECODE;
2051 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
2052 st->codec->time_base.num = 1;
2053 /* adjust for per frame dur in counter mode */
2054 if (tmcd_ctx->tmcd_flags & 0x0008) {
2055 int timescale = AV_RB32(st->codec->extradata + 8);
2056 int framedur = AV_RB32(st->codec->extradata + 12);
2057 st->codec->time_base.den *= timescale;
2058 st->codec->time_base.num *= framedur;
2061 uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
2062 uint32_t format = AV_RB32(st->codec->extradata + 22);
2063 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2064 uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
2065 if (str_size > 0 && size >= (int)str_size + 26) {
2066 char *reel_name = av_malloc(str_size + 1);
2068 return AVERROR(ENOMEM);
2069 memcpy(reel_name, st->codec->extradata + 30, str_size);
2070 reel_name[str_size] = 0; /* Add null terminator */
2071 /* don't add reel_name if emtpy string */
2072 if (*reel_name == 0) {
2075 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2082 /* other codec type, just skip (rtp, mp4s ...) */
2083 avio_skip(pb, size);
2088 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2089 AVStream *st, MOVStreamContext *sc)
2091 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2092 !st->codec->sample_rate && sc->time_scale > 1)
2093 st->codec->sample_rate = sc->time_scale;
2095 /* special codec parameters handling */
2096 switch (st->codec->codec_id) {
2097 #if CONFIG_DV_DEMUXER
2098 case AV_CODEC_ID_DVAUDIO:
2099 c->dv_fctx = avformat_alloc_context();
2101 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2102 return AVERROR(ENOMEM);
2104 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2106 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2107 return AVERROR(ENOMEM);
2109 sc->dv_audio_container = 1;
2110 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
2113 /* no ifdef since parameters are always those */
2114 case AV_CODEC_ID_QCELP:
2115 st->codec->channels = 1;
2116 // force sample rate for qcelp when not stored in mov
2117 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
2118 st->codec->sample_rate = 8000;
2119 // FIXME: Why is the following needed for some files?
2120 sc->samples_per_frame = 160;
2121 if (!sc->bytes_per_frame)
2122 sc->bytes_per_frame = 35;
2124 case AV_CODEC_ID_AMR_NB:
2125 st->codec->channels = 1;
2126 /* force sample rate for amr, stsd in 3gp does not store sample rate */
2127 st->codec->sample_rate = 8000;
2129 case AV_CODEC_ID_AMR_WB:
2130 st->codec->channels = 1;
2131 st->codec->sample_rate = 16000;
2133 case AV_CODEC_ID_MP2:
2134 case AV_CODEC_ID_MP3:
2135 /* force type after stsd for m1a hdlr */
2136 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
2138 case AV_CODEC_ID_GSM:
2139 case AV_CODEC_ID_ADPCM_MS:
2140 case AV_CODEC_ID_ADPCM_IMA_WAV:
2141 case AV_CODEC_ID_ILBC:
2142 case AV_CODEC_ID_MACE3:
2143 case AV_CODEC_ID_MACE6:
2144 case AV_CODEC_ID_QDM2:
2145 st->codec->block_align = sc->bytes_per_frame;
2147 case AV_CODEC_ID_ALAC:
2148 if (st->codec->extradata_size == 36) {
2149 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
2150 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
2153 case AV_CODEC_ID_AC3:
2154 case AV_CODEC_ID_EAC3:
2155 case AV_CODEC_ID_MPEG1VIDEO:
2156 case AV_CODEC_ID_VC1:
2157 st->need_parsing = AVSTREAM_PARSE_FULL;
2165 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2166 int codec_tag, int format,
2169 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2172 (codec_tag != format &&
2173 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2174 : codec_tag != MKTAG('j','p','e','g')))) {
2175 /* Multiple fourcc, we skip JPEG. This is not correct, we should
2176 * export it as a separate AVStream but this needs a few changes
2177 * in the MOV demuxer, patch welcome. */
2179 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2180 avio_skip(pb, size);
2183 if ( codec_tag == AV_RL32("avc1") ||
2184 codec_tag == AV_RL32("hvc1") ||
2185 codec_tag == AV_RL32("hev1")
2187 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
2192 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2195 MOVStreamContext *sc;
2196 int pseudo_stream_id;
2198 if (c->fc->nb_streams < 1)
2200 st = c->fc->streams[c->fc->nb_streams-1];
2203 for (pseudo_stream_id = 0;
2204 pseudo_stream_id < entries && !pb->eof_reached;
2205 pseudo_stream_id++) {
2206 //Parsing Sample description table
2208 int ret, dref_id = 1;
2209 MOVAtom a = { AV_RL32("stsd") };
2210 int64_t start_pos = avio_tell(pb);
2211 int64_t size = avio_rb32(pb); /* size */
2212 uint32_t format = avio_rl32(pb); /* data format */
2215 avio_rb32(pb); /* reserved */
2216 avio_rb16(pb); /* reserved */
2217 dref_id = avio_rb16(pb);
2218 }else if (size <= 7){
2219 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
2220 return AVERROR_INVALIDDATA;
2223 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
2224 size - (avio_tell(pb) - start_pos)))
2227 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
2228 sc->dref_id= dref_id;
2230 id = mov_codec_id(st, format);
2232 av_log(c->fc, AV_LOG_TRACE,
2233 "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
2234 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
2235 (format >> 24) & 0xff, format, st->codec->codec_type);
2237 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
2238 st->codec->codec_id = id;
2239 mov_parse_stsd_video(c, pb, st, sc);
2240 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
2241 st->codec->codec_id = id;
2242 mov_parse_stsd_audio(c, pb, st, sc);
2243 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
2244 st->codec->codec_id = id;
2245 mov_parse_stsd_subtitle(c, pb, st, sc,
2246 size - (avio_tell(pb) - start_pos));
2248 ret = mov_parse_stsd_data(c, pb, st, sc,
2249 size - (avio_tell(pb) - start_pos));
2253 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2254 a.size = size - (avio_tell(pb) - start_pos);
2256 if ((ret = mov_read_default(c, pb, a)) < 0)
2258 } else if (a.size > 0)
2259 avio_skip(pb, a.size);
2262 if (pb->eof_reached)
2265 return mov_finalize_stsd_codec(c, pb, st, sc);
2268 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2272 avio_r8(pb); /* version */
2273 avio_rb24(pb); /* flags */
2274 entries = avio_rb32(pb);
2276 return ff_mov_read_stsd_entries(c, pb, entries);
2279 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2282 MOVStreamContext *sc;
2283 unsigned int i, entries;
2285 if (c->fc->nb_streams < 1)
2287 st = c->fc->streams[c->fc->nb_streams-1];
2290 avio_r8(pb); /* version */
2291 avio_rb24(pb); /* flags */
2293 entries = avio_rb32(pb);
2295 av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
2300 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2301 av_free(sc->stsc_data);
2303 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2305 return AVERROR(ENOMEM);
2307 for (i = 0; i < entries && !pb->eof_reached; i++) {
2308 sc->stsc_data[i].first = avio_rb32(pb);
2309 sc->stsc_data[i].count = avio_rb32(pb);
2310 sc->stsc_data[i].id = avio_rb32(pb);
2315 if (pb->eof_reached)
2321 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2324 MOVStreamContext *sc;
2325 unsigned i, entries;
2327 if (c->fc->nb_streams < 1)
2329 st = c->fc->streams[c->fc->nb_streams-1];
2332 avio_rb32(pb); // version + flags
2334 entries = avio_rb32(pb);
2336 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2337 av_free(sc->stps_data);
2339 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2341 return AVERROR(ENOMEM);
2343 for (i = 0; i < entries && !pb->eof_reached; i++) {
2344 sc->stps_data[i] = avio_rb32(pb);
2345 //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
2350 if (pb->eof_reached)
2356 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2359 MOVStreamContext *sc;
2360 unsigned int i, entries;
2362 if (c->fc->nb_streams < 1)
2364 st = c->fc->streams[c->fc->nb_streams-1];
2367 avio_r8(pb); /* version */
2368 avio_rb24(pb); /* flags */
2370 entries = avio_rb32(pb);
2372 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
2376 sc->keyframe_absent = 1;
2377 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2378 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2382 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2383 if (entries >= UINT_MAX / sizeof(int))
2384 return AVERROR_INVALIDDATA;
2385 av_freep(&sc->keyframes);
2386 sc->keyframe_count = 0;
2387 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2389 return AVERROR(ENOMEM);
2391 for (i = 0; i < entries && !pb->eof_reached; i++) {
2392 sc->keyframes[i] = avio_rb32(pb);
2393 //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
2396 sc->keyframe_count = i;
2398 if (pb->eof_reached)
2404 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2407 MOVStreamContext *sc;
2408 unsigned int i, entries, sample_size, field_size, num_bytes;
2413 if (c->fc->nb_streams < 1)
2415 st = c->fc->streams[c->fc->nb_streams-1];
2418 avio_r8(pb); /* version */
2419 avio_rb24(pb); /* flags */
2421 if (atom.type == MKTAG('s','t','s','z')) {
2422 sample_size = avio_rb32(pb);
2423 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2424 sc->sample_size = sample_size;
2425 sc->stsz_sample_size = sample_size;
2429 avio_rb24(pb); /* reserved */
2430 field_size = avio_r8(pb);
2432 entries = avio_rb32(pb);
2434 av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2436 sc->sample_count = entries;
2440 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2441 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2442 return AVERROR_INVALIDDATA;
2447 if (entries >= (UINT_MAX - 4) / field_size)
2448 return AVERROR_INVALIDDATA;
2449 if (sc->sample_sizes)
2450 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2451 av_free(sc->sample_sizes);
2452 sc->sample_count = 0;
2453 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2454 if (!sc->sample_sizes)
2455 return AVERROR(ENOMEM);
2457 num_bytes = (entries*field_size+4)>>3;
2459 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2461 av_freep(&sc->sample_sizes);
2462 return AVERROR(ENOMEM);
2465 ret = ffio_read_size(pb, buf, num_bytes);
2467 av_freep(&sc->sample_sizes);
2472 init_get_bits(&gb, buf, 8*num_bytes);
2474 for (i = 0; i < entries && !pb->eof_reached; i++) {
2475 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2476 sc->data_size += sc->sample_sizes[i];
2479 sc->sample_count = i;
2483 if (pb->eof_reached)
2489 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2492 MOVStreamContext *sc;
2493 unsigned int i, entries;
2495 int64_t total_sample_count=0;
2497 if (c->fc->nb_streams < 1)
2499 st = c->fc->streams[c->fc->nb_streams-1];
2502 avio_r8(pb); /* version */
2503 avio_rb24(pb); /* flags */
2504 entries = avio_rb32(pb);
2506 av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2507 c->fc->nb_streams-1, entries);
2510 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2511 av_free(sc->stts_data);
2513 sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2515 return AVERROR(ENOMEM);
2517 for (i = 0; i < entries && !pb->eof_reached; i++) {
2518 int sample_duration;
2521 sample_count=avio_rb32(pb);
2522 sample_duration = avio_rb32(pb);
2524 if (sample_count < 0) {
2525 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2526 return AVERROR_INVALIDDATA;
2528 sc->stts_data[i].count= sample_count;
2529 sc->stts_data[i].duration= sample_duration;
2531 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2532 sample_count, sample_duration);
2536 && sample_count == 1
2537 && total_sample_count > 100
2538 && sample_duration/10 > duration / total_sample_count)
2539 sample_duration = duration / total_sample_count;
2540 duration+=(int64_t)sample_duration*sample_count;
2541 total_sample_count+=sample_count;
2546 sc->duration_for_fps += duration;
2547 sc->nb_frames_for_fps += total_sample_count;
2549 if (pb->eof_reached)
2552 st->nb_frames= total_sample_count;
2554 st->duration= duration;
2555 sc->track_end = duration;
2559 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2562 if (duration == INT_MIN) {
2563 av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2566 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2570 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2573 MOVStreamContext *sc;
2574 unsigned int i, entries;
2576 if (c->fc->nb_streams < 1)
2578 st = c->fc->streams[c->fc->nb_streams-1];
2581 avio_r8(pb); /* version */
2582 avio_rb24(pb); /* flags */
2583 entries = avio_rb32(pb);
2585 av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2589 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2590 return AVERROR_INVALIDDATA;
2591 av_freep(&sc->ctts_data);
2592 sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2594 return AVERROR(ENOMEM);
2596 for (i = 0; i < entries && !pb->eof_reached; i++) {
2597 int count =avio_rb32(pb);
2598 int duration =avio_rb32(pb);
2600 sc->ctts_data[i].count = count;
2601 sc->ctts_data[i].duration= duration;
2603 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2606 if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2607 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2608 av_freep(&sc->ctts_data);
2614 mov_update_dts_shift(sc, duration);
2619 if (pb->eof_reached)
2622 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2627 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2630 MOVStreamContext *sc;
2631 unsigned int i, entries;
2633 uint32_t grouping_type;
2635 if (c->fc->nb_streams < 1)
2637 st = c->fc->streams[c->fc->nb_streams-1];
2640 version = avio_r8(pb); /* version */
2641 avio_rb24(pb); /* flags */
2642 grouping_type = avio_rl32(pb);
2643 if (grouping_type != MKTAG( 'r','a','p',' '))
2644 return 0; /* only support 'rap ' grouping */
2646 avio_rb32(pb); /* grouping_type_parameter */
2648 entries = avio_rb32(pb);
2652 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2653 av_free(sc->rap_group);
2654 sc->rap_group_count = 0;
2655 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2657 return AVERROR(ENOMEM);
2659 for (i = 0; i < entries && !pb->eof_reached; i++) {
2660 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2661 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2664 sc->rap_group_count = i;
2666 return pb->eof_reached ? AVERROR_EOF : 0;
2669 static void mov_build_index(MOVContext *mov, AVStream *st)
2671 MOVStreamContext *sc = st->priv_data;
2672 int64_t current_offset;
2673 int64_t current_dts = 0;
2674 unsigned int stts_index = 0;
2675 unsigned int stsc_index = 0;
2676 unsigned int stss_index = 0;
2677 unsigned int stps_index = 0;
2679 uint64_t stream_size = 0;
2681 if (sc->elst_count) {
2682 int i, edit_start_index = 0, unsupported = 0;
2683 int64_t empty_duration = 0; // empty duration of the first edit list entry
2684 int64_t start_time = 0; // start time of the media
2686 for (i = 0; i < sc->elst_count; i++) {
2687 const MOVElst *e = &sc->elst_data[i];
2688 if (i == 0 && e->time == -1) {
2689 /* if empty, the first entry is the start time of the stream
2690 * relative to the presentation itself */
2691 empty_duration = e->duration;
2692 edit_start_index = 1;
2693 } else if (i == edit_start_index && e->time >= 0) {
2694 start_time = e->time;
2699 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
2700 "a/v desync might occur, patch welcome\n");
2702 /* adjust first dts according to edit list */
2703 if ((empty_duration || start_time) && mov->time_scale > 0) {
2705 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
2706 sc->time_offset = start_time - empty_duration;
2707 current_dts = -sc->time_offset;
2708 if (sc->ctts_count>0 && sc->stts_count>0 &&
2709 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2710 /* more than 16 frames delay, dts are likely wrong
2711 this happens with files created by iMovie */
2713 st->codec->has_b_frames = 1;
2718 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2719 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2720 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2721 unsigned int current_sample = 0;
2722 unsigned int stts_sample = 0;
2723 unsigned int sample_size;
2724 unsigned int distance = 0;
2725 unsigned int rap_group_index = 0;
2726 unsigned int rap_group_sample = 0;
2727 int64_t last_dts = 0;
2728 int64_t dts_correction = 0;
2729 int rap_group_present = sc->rap_group_count && sc->rap_group;
2730 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2732 current_dts -= sc->dts_shift;
2733 last_dts = current_dts;
2735 if (!sc->sample_count || st->nb_index_entries)
2737 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2739 if (av_reallocp_array(&st->index_entries,
2740 st->nb_index_entries + sc->sample_count,
2741 sizeof(*st->index_entries)) < 0) {
2742 st->nb_index_entries = 0;
2745 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2747 for (i = 0; i < sc->chunk_count; i++) {
2748 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2749 current_offset = sc->chunk_offsets[i];
2750 while (stsc_index + 1 < sc->stsc_count &&
2751 i + 1 == sc->stsc_data[stsc_index + 1].first)
2754 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2755 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2756 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2757 sc->stsz_sample_size = sc->sample_size;
2759 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2760 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2761 sc->stsz_sample_size = sc->sample_size;
2764 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2766 if (current_sample >= sc->sample_count) {
2767 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2771 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2773 if (stss_index + 1 < sc->keyframe_count)
2775 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2777 if (stps_index + 1 < sc->stps_count)
2780 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2781 if (sc->rap_group[rap_group_index].index > 0)
2783 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2784 rap_group_sample = 0;
2788 if (sc->keyframe_absent
2790 && !rap_group_present
2791 && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2795 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2796 if (sc->pseudo_stream_id == -1 ||
2797 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2798 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2799 e->pos = current_offset;
2800 e->timestamp = current_dts;
2801 e->size = sample_size;
2802 e->min_distance = distance;
2803 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2804 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2805 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2806 current_offset, current_dts, sample_size, distance, keyframe);
2807 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2808 ff_rfps_add_frame(mov->fc, st, current_dts);
2811 current_offset += sample_size;
2812 stream_size += sample_size;
2814 /* A negative sample duration is invalid based on the spec,
2815 * but some samples need it to correct the DTS. */
2816 if (sc->stts_data[stts_index].duration < 0) {
2817 av_log(mov->fc, AV_LOG_WARNING,
2818 "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2819 sc->stts_data[stts_index].duration, stts_index,
2821 dts_correction += sc->stts_data[stts_index].duration - 1;
2822 sc->stts_data[stts_index].duration = 1;
2824 current_dts += sc->stts_data[stts_index].duration;
2825 if (!dts_correction || current_dts + dts_correction > last_dts) {
2826 current_dts += dts_correction;
2829 /* Avoid creating non-monotonous DTS */
2830 dts_correction += current_dts - last_dts - 1;
2831 current_dts = last_dts + 1;
2833 last_dts = current_dts;
2837 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2843 if (st->duration > 0)
2844 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2846 unsigned chunk_samples, total = 0;
2848 // compute total chunk count
2849 for (i = 0; i < sc->stsc_count; i++) {
2850 unsigned count, chunk_count;
2852 chunk_samples = sc->stsc_data[i].count;
2853 if (i != sc->stsc_count - 1 &&
2854 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2855 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2859 if (sc->samples_per_frame >= 160) { // gsm
2860 count = chunk_samples / sc->samples_per_frame;
2861 } else if (sc->samples_per_frame > 1) {
2862 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2863 count = (chunk_samples+samples-1) / samples;
2865 count = (chunk_samples+1023) / 1024;
2868 if (i < sc->stsc_count - 1)
2869 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2871 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2872 total += chunk_count * count;
2875 av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2876 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2878 if (av_reallocp_array(&st->index_entries,
2879 st->nb_index_entries + total,
2880 sizeof(*st->index_entries)) < 0) {
2881 st->nb_index_entries = 0;
2884 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2887 for (i = 0; i < sc->chunk_count; i++) {
2888 current_offset = sc->chunk_offsets[i];
2889 if (stsc_index + 1 < sc->stsc_count &&
2890 i + 1 == sc->stsc_data[stsc_index + 1].first)
2892 chunk_samples = sc->stsc_data[stsc_index].count;
2894 while (chunk_samples > 0) {
2896 unsigned size, samples;
2898 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2899 avpriv_request_sample(mov->fc,
2900 "Zero bytes per frame, but %d samples per frame",
2901 sc->samples_per_frame);
2905 if (sc->samples_per_frame >= 160) { // gsm
2906 samples = sc->samples_per_frame;
2907 size = sc->bytes_per_frame;
2909 if (sc->samples_per_frame > 1) {
2910 samples = FFMIN((1024 / sc->samples_per_frame)*
2911 sc->samples_per_frame, chunk_samples);
2912 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2914 samples = FFMIN(1024, chunk_samples);
2915 size = samples * sc->sample_size;
2919 if (st->nb_index_entries >= total) {
2920 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2923 e = &st->index_entries[st->nb_index_entries++];
2924 e->pos = current_offset;
2925 e->timestamp = current_dts;
2927 e->min_distance = 0;
2928 e->flags = AVINDEX_KEYFRAME;
2929 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2930 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2933 current_offset += size;
2934 current_dts += samples;
2935 chunk_samples -= samples;
2941 static int test_same_origin(const char *src, const char *ref) {
2951 av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
2952 av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
2954 if (strlen(src) == 0) {
2956 } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
2957 strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
2958 strlen(src_host) + 1 >= sizeof(src_host) ||
2959 strlen(ref_host) + 1 >= sizeof(ref_host)) {
2961 } else if (strcmp(src_proto, ref_proto) ||
2962 strcmp(src_auth, ref_auth) ||
2963 strcmp(src_host, ref_host) ||
2964 src_port != ref_port) {
2970 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref,
2971 AVIOInterruptCB *int_cb)
2973 AVOpenCallback open_func = c->fc->open_cb;
2976 open_func = ffio_open2_wrapper;
2978 /* try relative path, we do not try the absolute because it can leak information about our
2979 system to an attacker */
2980 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2981 char filename[1025];
2982 const char *src_path;
2985 /* find a source dir */
2986 src_path = strrchr(src, '/');
2992 /* find a next level down to target */
2993 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2994 if (ref->path[l] == '/') {
2995 if (i == ref->nlvl_to - 1)
3001 /* compose filename if next level down to target was found */
3002 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
3003 memcpy(filename, src, src_path - src);
3004 filename[src_path - src] = 0;
3006 for (i = 1; i < ref->nlvl_from; i++)
3007 av_strlcat(filename, "../", sizeof(filename));
3009 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
3010 if (!c->use_absolute_path && !c->fc->open_cb) {
3011 int same_origin = test_same_origin(src, filename);
3014 av_log(c->fc, AV_LOG_ERROR,
3015 "Reference with mismatching origin, %s not tried for security reasons, "
3016 "set demuxer option use_absolute_path to allow it anyway\n",
3018 return AVERROR(ENOENT);
3021 if(strstr(ref->path + l + 1, "..") ||
3022 strstr(ref->path + l + 1, ":") ||
3023 (ref->nlvl_from > 1 && same_origin < 0) ||
3024 (filename[0] == '/' && src_path == src))
3025 return AVERROR(ENOENT);
3028 if (strlen(filename) + 1 == sizeof(filename))
3029 return AVERROR(ENOENT);
3030 if (!open_func(c->fc, pb, filename, AVIO_FLAG_READ, int_cb, NULL))
3033 } else if (c->use_absolute_path) {
3034 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
3035 "this is a possible security issue\n");
3036 if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
3038 } else if (c->fc->open_cb) {
3039 if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
3042 av_log(c->fc, AV_LOG_ERROR,
3043 "Absolute path %s not tried for security reasons, "
3044 "set demuxer option use_absolute_path to allow absolute paths\n",
3048 return AVERROR(ENOENT);
3051 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
3053 if (sc->time_scale <= 0) {
3054 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
3055 sc->time_scale = c->time_scale;
3056 if (sc->time_scale <= 0)
3061 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3064 MOVStreamContext *sc;
3067 st = avformat_new_stream(c->fc, NULL);
3068 if (!st) return AVERROR(ENOMEM);
3069 st->id = c->fc->nb_streams;
3070 sc = av_mallocz(sizeof(MOVStreamContext));
3071 if (!sc) return AVERROR(ENOMEM);
3074 st->codec->codec_type = AVMEDIA_TYPE_DATA;
3075 sc->ffindex = st->index;
3077 if ((ret = mov_read_default(c, pb, atom)) < 0)
3081 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
3082 (!sc->sample_size && !sc->sample_count))) {
3083 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
3088 fix_timescale(c, sc);
3090 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
3092 mov_build_index(c, st);
3094 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
3095 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
3096 if (mov_open_dref(c, &sc->pb, c->fc->filename, dref,
3097 &c->fc->interrupt_callback) < 0)
3098 av_log(c->fc, AV_LOG_ERROR,
3099 "stream %d, error opening alias: path='%s', dir='%s', "
3100 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
3101 st->index, dref->path, dref->dir, dref->filename,
3102 dref->volume, dref->nlvl_from, dref->nlvl_to);
3105 sc->pb_is_copied = 1;
3108 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3109 if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&
3110 sc->height && sc->width &&
3111 (st->codec->width != sc->width || st->codec->height != sc->height)) {
3112 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
3113 ((double)st->codec->width * sc->height), INT_MAX);
3116 #if FF_API_R_FRAME_RATE
3117 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
3118 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
3119 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
3123 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3124 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
3125 TAG_IS_AVCI(st->codec->codec_tag)) {
3126 ret = ff_generate_avci_extradata(st);
3131 switch (st->codec->codec_id) {
3132 #if CONFIG_H261_DECODER
3133 case AV_CODEC_ID_H261:
3135 #if CONFIG_H263_DECODER
3136 case AV_CODEC_ID_H263:
3138 #if CONFIG_MPEG4_DECODER
3139 case AV_CODEC_ID_MPEG4:
3141 st->codec->width = 0; /* let decoder init width/height */
3142 st->codec->height= 0;
3146 // If the duration of the mp3 packets is not constant, then they could need a parser
3147 if (st->codec->codec_id == AV_CODEC_ID_MP3
3148 && sc->stts_count > 3
3149 && sc->stts_count*10 > st->nb_frames
3150 && sc->time_scale == st->codec->sample_rate) {
3151 st->need_parsing = AVSTREAM_PARSE_FULL;
3153 /* Do not need those anymore. */
3154 av_freep(&sc->chunk_offsets);
3155 av_freep(&sc->stsc_data);
3156 av_freep(&sc->sample_sizes);
3157 av_freep(&sc->keyframes);
3158 av_freep(&sc->stts_data);
3159 av_freep(&sc->stps_data);
3160 av_freep(&sc->elst_data);
3161 av_freep(&sc->rap_group);
3166 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3169 c->itunes_metadata = 1;
3170 ret = mov_read_default(c, pb, atom);
3171 c->itunes_metadata = 0;
3175 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3184 count = avio_rb32(pb);
3185 if (count > UINT_MAX / sizeof(*c->meta_keys)) {
3186 av_log(c->fc, AV_LOG_ERROR,
3187 "The 'keys' atom with the invalid key count: %d\n", count);
3188 return AVERROR_INVALIDDATA;
3191 c->meta_keys_count = count + 1;
3192 c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
3194 return AVERROR(ENOMEM);
3196 for (i = 1; i <= count; ++i) {
3197 uint32_t key_size = avio_rb32(pb);
3198 uint32_t type = avio_rl32(pb);
3200 av_log(c->fc, AV_LOG_ERROR,
3201 "The key# %d in meta has invalid size: %d\n", i, key_size);
3202 return AVERROR_INVALIDDATA;
3205 if (type != MKTAG('m','d','t','a')) {
3206 avio_skip(pb, key_size);
3208 c->meta_keys[i] = av_mallocz(key_size + 1);
3209 if (!c->meta_keys[i])
3210 return AVERROR(ENOMEM);
3211 avio_read(pb, c->meta_keys[i], key_size);
3217 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
3219 int64_t end = avio_tell(pb) + size;
3220 uint8_t *key = NULL, *val = NULL;
3223 MOVStreamContext *sc;
3225 if (c->fc->nb_streams < 1)
3227 st = c->fc->streams[c->fc->nb_streams-1];
3230 for (i = 0; i < 2; i++) {
3235 if (end - avio_tell(pb) <= 12)
3238 len = avio_rb32(pb);
3239 tag = avio_rl32(pb);
3240 avio_skip(pb, 4); // flags
3242 if (len < 12 || len - 12 > end - avio_tell(pb))
3246 if (tag == MKTAG('n', 'a', 'm', 'e'))
3248 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
3255 *p = av_malloc(len + 1);
3258 ret = ffio_read_size(pb, *p, len);
3267 if (strcmp(key, "iTunSMPB") == 0) {
3268 int priming, remainder, samples;
3269 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
3270 if(priming>0 && priming<16384)
3271 sc->start_pad = priming;
3274 if (strcmp(key, "cdec") != 0) {
3275 av_dict_set(&c->fc->metadata, key, val,
3276 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
3281 avio_seek(pb, end, SEEK_SET);
3287 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3289 int64_t end = avio_tell(pb) + atom.size;
3295 len = avio_rb32(pb);
3296 tag = avio_rl32(pb);
3298 if (len > atom.size)
3301 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
3302 uint8_t domain[128];
3305 avio_skip(pb, 4); // flags
3308 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
3309 avio_skip(pb, len - domain_len);
3310 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
3314 av_log(c->fc, AV_LOG_VERBOSE,
3315 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
3319 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3321 while (atom.size > 8) {
3322 uint32_t tag = avio_rl32(pb);
3324 if (tag == MKTAG('h','d','l','r')) {
3325 avio_seek(pb, -8, SEEK_CUR);
3327 return mov_read_default(c, pb, atom);
3333 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3338 int display_matrix[3][3];
3340 MOVStreamContext *sc;
3344 if (c->fc->nb_streams < 1)
3346 st = c->fc->streams[c->fc->nb_streams-1];
3349 version = avio_r8(pb);
3350 flags = avio_rb24(pb);
3351 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
3357 avio_rb32(pb); /* creation time */
3358 avio_rb32(pb); /* modification time */
3360 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
3361 avio_rb32(pb); /* reserved */
3363 /* highlevel (considering edits) duration in movie timebase */
3364 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
3365 avio_rb32(pb); /* reserved */
3366 avio_rb32(pb); /* reserved */
3368 avio_rb16(pb); /* layer */
3369 avio_rb16(pb); /* alternate group */
3370 avio_rb16(pb); /* volume */
3371 avio_rb16(pb); /* reserved */
3373 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
3374 // they're kept in fixed point format through all calculations
3375 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
3376 // side data, but the scale factor is not needed to calculate aspect ratio
3377 for (i = 0; i < 3; i++) {
3378 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
3379 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
3380 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
3383 width = avio_rb32(pb); // 16.16 fixed point track width
3384 height = avio_rb32(pb); // 16.16 fixed point track height
3385 sc->width = width >> 16;
3386 sc->height = height >> 16;
3388 // save the matrix and add rotate metadata when it is not the default
3390 if (display_matrix[0][0] != (1 << 16) ||
3391 display_matrix[1][1] != (1 << 16) ||
3392 display_matrix[2][2] != (1 << 30) ||
3393 display_matrix[0][1] || display_matrix[0][2] ||
3394 display_matrix[1][0] || display_matrix[1][2] ||
3395 display_matrix[2][0] || display_matrix[2][1]) {
3399 av_freep(&sc->display_matrix);
3400 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
3401 if (!sc->display_matrix)
3402 return AVERROR(ENOMEM);
3404 for (i = 0; i < 3; i++)
3405 for (j = 0; j < 3; j++)
3406 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
3408 rotate = av_display_rotation_get(sc->display_matrix);
3409 if (!isnan(rotate)) {
3410 char rotate_buf[64];
3412 if (rotate < 0) // for backward compatibility
3414 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
3415 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
3419 // transform the display width/height according to the matrix
3420 // to keep the same scale, use [width height 1<<16]
3421 if (width && height && sc->display_matrix) {
3422 double disp_transform[2];
3424 for (i = 0; i < 2; i++)
3425 disp_transform[i] = hypot(display_matrix[i][0], display_matrix[i][1]);
3427 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
3428 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
3429 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
3430 st->sample_aspect_ratio = av_d2q(
3431 disp_transform[0] / disp_transform[1],
3437 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3439 MOVFragment *frag = &c->fragment;
3440 MOVTrackExt *trex = NULL;
3441 MOVFragmentIndex* index = NULL;
3442 int flags, track_id, i, found = 0;
3444 avio_r8(pb); /* version */
3445 flags = avio_rb24(pb);
3447 track_id = avio_rb32(pb);
3449 return AVERROR_INVALIDDATA;
3450 frag->track_id = track_id;
3451 for (i = 0; i < c->trex_count; i++)
3452 if (c->trex_data[i].track_id == frag->track_id) {
3453 trex = &c->trex_data[i];
3457 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
3458 return AVERROR_INVALIDDATA;
3461 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
3462 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
3463 frag->moof_offset : frag->implicit_offset;
3464 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
3466 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
3467 avio_rb32(pb) : trex->duration;
3468 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
3469 avio_rb32(pb) : trex->size;
3470 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
3471 avio_rb32(pb) : trex->flags;
3472 frag->time = AV_NOPTS_VALUE;
3473 for (i = 0; i < c->fragment_index_count; i++) {
3475 MOVFragmentIndex* candidate = c->fragment_index_data[i];
3476 if (candidate->track_id == frag->track_id) {
3477 av_log(c->fc, AV_LOG_DEBUG,
3478 "found fragment index for track %u\n", frag->track_id);
3480 for (j = index->current_item; j < index->item_count; j++) {
3481 if (frag->implicit_offset == index->items[j].moof_offset) {
3482 av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
3483 "for track %u and moof_offset %"PRId64"\n",
3484 frag->track_id, index->items[j].moof_offset);
3485 frag->time = index->items[j].time;
3486 index->current_item = j + 1;
3495 if (index && !found) {
3496 av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
3497 "it doesn't have an (in-order) entry for moof_offset "
3498 "%"PRId64"\n", frag->track_id, frag->implicit_offset);
3500 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
3504 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3506 c->chapter_track = avio_rb32(pb);
3510 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3515 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
3516 return AVERROR_INVALIDDATA;
3517 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
3518 sizeof(*c->trex_data))) < 0) {
3523 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
3525 trex = &c->trex_data[c->trex_count++];
3526 avio_r8(pb); /* version */
3527 avio_rb24(pb); /* flags */
3528 trex->track_id = avio_rb32(pb);
3529 trex->stsd_id = avio_rb32(pb);
3530 trex->duration = avio_rb32(pb);
3531 trex->size = avio_rb32(pb);
3532 trex->flags = avio_rb32(pb);
3536 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3538 MOVFragment *frag = &c->fragment;
3539 AVStream *st = NULL;
3540 MOVStreamContext *sc;
3543 for (i = 0; i < c->fc->nb_streams; i++) {
3544 if (c->fc->streams[i]->id == frag->track_id) {
3545 st = c->fc->streams[i];
3550 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3551 return AVERROR_INVALIDDATA;
3554 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
3556 version = avio_r8(pb);
3557 avio_rb24(pb); /* flags */
3559 sc->track_end = avio_rb64(pb);
3561 sc->track_end = avio_rb32(pb);
3566 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3568 MOVFragment *frag = &c->fragment;
3569 AVStream *st = NULL;
3570 MOVStreamContext *sc;
3574 int data_offset = 0;
3575 unsigned entries, first_sample_flags = frag->flags;
3576 int flags, distance, i, err;
3578 for (i = 0; i < c->fc->nb_streams; i++) {
3579 if (c->fc->streams[i]->id == frag->track_id) {
3580 st = c->fc->streams[i];
3585 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3586 return AVERROR_INVALIDDATA;
3589 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3591 avio_r8(pb); /* version */
3592 flags = avio_rb24(pb);
3593 entries = avio_rb32(pb);
3594 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
3596 /* Always assume the presence of composition time offsets.
3597 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3598 * 1) in the initial movie, there are no samples.
3599 * 2) in the first movie fragment, there is only one sample without composition time offset.
3600 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
3601 if (!sc->ctts_count && sc->sample_count)
3603 /* Complement ctts table if moov atom doesn't have ctts atom. */
3604 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3606 return AVERROR(ENOMEM);
3607 sc->ctts_data = ctts_data;
3608 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3609 sc->ctts_data[sc->ctts_count].duration = 0;
3612 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3613 return AVERROR_INVALIDDATA;
3614 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3615 sizeof(*sc->ctts_data))) < 0) {
3619 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
3620 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3621 dts = sc->track_end - sc->time_offset;
3622 offset = frag->base_data_offset + data_offset;
3624 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3625 for (i = 0; i < entries && !pb->eof_reached; i++) {
3626 unsigned sample_size = frag->size;
3627 int sample_flags = i ? frag->flags : first_sample_flags;
3628 unsigned sample_duration = frag->duration;
3631 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3632 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
3633 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
3634 sc->ctts_data[sc->ctts_count].count = 1;
3635 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3637 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
3638 if (frag->time != AV_NOPTS_VALUE) {
3639 if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3640 int64_t pts = frag->time;
3641 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3642 " sc->dts_shift %d ctts.duration %d"
3643 " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3644 sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3645 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3646 dts = pts - sc->dts_shift;
3647 if (flags & MOV_TRUN_SAMPLE_CTS) {
3648 dts -= sc->ctts_data[sc->ctts_count].duration;
3650 dts -= sc->time_offset;
3652 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3655 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3656 ", using it for dts\n", dts);
3658 frag->time = AV_NOPTS_VALUE;
3661 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3665 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3666 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3669 err = av_add_index_entry(st, offset, dts, sample_size, distance,
3670 keyframe ? AVINDEX_KEYFRAME : 0);
3672 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
3674 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3675 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3676 offset, dts, sample_size, distance, keyframe);
3678 dts += sample_duration;
3679 offset += sample_size;
3680 sc->data_size += sample_size;
3681 sc->duration_for_fps += sample_duration;
3682 sc->nb_frames_for_fps ++;
3685 if (pb->eof_reached)
3688 frag->implicit_offset = offset;
3690 sc->track_end = dts + sc->time_offset;
3691 if (st->duration < sc->track_end)
3692 st->duration = sc->track_end;
3697 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3699 int64_t offset = avio_tell(pb) + atom.size, pts;
3701 unsigned i, track_id;
3702 AVStream *st = NULL;
3703 MOVStreamContext *sc;
3704 MOVFragmentIndex *index = NULL;
3705 MOVFragmentIndex **tmp;
3706 AVRational timescale;
3708 version = avio_r8(pb);
3710 avpriv_request_sample(c->fc, "sidx version %u", version);
3711 return AVERROR_PATCHWELCOME;
3714 avio_rb24(pb); // flags
3716 track_id = avio_rb32(pb); // Reference ID
3717 for (i = 0; i < c->fc->nb_streams; i++) {
3718 if (c->fc->streams[i]->id == track_id) {
3719 st = c->fc->streams[i];
3724 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", track_id);
3725 return AVERROR_INVALIDDATA;
3730 timescale = av_make_q(1, avio_rb32(pb));
3733 pts = avio_rb32(pb);
3734 offset += avio_rb32(pb);
3736 pts = avio_rb64(pb);
3737 offset += avio_rb64(pb);
3740 avio_rb16(pb); // reserved
3742 index = av_mallocz(sizeof(MOVFragmentIndex));
3744 return AVERROR(ENOMEM);
3746 index->track_id = track_id;
3748 index->item_count = avio_rb16(pb);
3749 index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
3751 if (!index->items) {
3753 return AVERROR(ENOMEM);
3756 for (i = 0; i < index->item_count; i++) {
3757 uint32_t size = avio_rb32(pb);
3758 uint32_t duration = avio_rb32(pb);
3759 if (size & 0x80000000) {
3760 avpriv_request_sample(c->fc, "sidx reference_type 1");
3761 av_freep(&index->items);
3763 return AVERROR_PATCHWELCOME;
3765 avio_rb32(pb); // sap_flags
3766 index->items[i].moof_offset = offset;
3767 index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
3772 st->duration = sc->track_end = pts;
3774 tmp = av_realloc_array(c->fragment_index_data,
3775 c->fragment_index_count + 1,
3776 sizeof(MOVFragmentIndex*));
3778 av_freep(&index->items);
3780 return AVERROR(ENOMEM);
3783 c->fragment_index_data = tmp;
3784 c->fragment_index_data[c->fragment_index_count++] = index;
3786 if (offset == avio_size(pb))
3787 c->fragment_index_complete = 1;
3792 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3793 /* like the files created with Adobe Premiere 5.0, for samples see */
3794 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3795 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3800 return 0; /* continue */
3801 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3802 avio_skip(pb, atom.size - 4);
3805 atom.type = avio_rl32(pb);
3807 if (atom.type != MKTAG('m','d','a','t')) {
3808 avio_skip(pb, atom.size);
3811 err = mov_read_mdat(c, pb, atom);
3815 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3820 uint8_t *moov_data; /* uncompressed data */
3821 long cmov_len, moov_len;
3824 avio_rb32(pb); /* dcom atom */
3825 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3826 return AVERROR_INVALIDDATA;
3827 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3828 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3829 return AVERROR_INVALIDDATA;
3831 avio_rb32(pb); /* cmvd atom */
3832 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3833 return AVERROR_INVALIDDATA;
3834 moov_len = avio_rb32(pb); /* uncompressed size */
3835 cmov_len = atom.size - 6 * 4;
3837 cmov_data = av_malloc(cmov_len);
3839 return AVERROR(ENOMEM);
3840 moov_data = av_malloc(moov_len);
3843 return AVERROR(ENOMEM);
3845 ret = ffio_read_size(pb, cmov_data, cmov_len);
3847 goto free_and_return;
3849 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3850 goto free_and_return;
3851 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3852 goto free_and_return;
3853 ctx.seekable = AVIO_SEEKABLE_NORMAL;
3854 atom.type = MKTAG('m','o','o','v');
3855 atom.size = moov_len;
3856 ret = mov_read_default(c, &ctx, atom);
3862 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3863 return AVERROR(ENOSYS);
3867 /* edit list atom */
3868 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3870 MOVStreamContext *sc;
3871 int i, edit_count, version;
3873 if (c->fc->nb_streams < 1 || c->ignore_editlist)
3875 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3877 version = avio_r8(pb); /* version */
3878 avio_rb24(pb); /* flags */
3879 edit_count = avio_rb32(pb); /* entries */
3884 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
3885 av_free(sc->elst_data);
3887 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
3889 return AVERROR(ENOMEM);
3891 av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3892 for (i = 0; i < edit_count && !pb->eof_reached; i++) {
3893 MOVElst *e = &sc->elst_data[i];
3896 e->duration = avio_rb64(pb);
3897 e->time = avio_rb64(pb);
3899 e->duration = avio_rb32(pb); /* segment duration */
3900 e->time = (int32_t)avio_rb32(pb); /* media time */
3902 e->rate = avio_rb32(pb) / 65536.0;
3903 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3904 e->duration, e->time, e->rate);
3911 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3913 MOVStreamContext *sc;
3915 if (c->fc->nb_streams < 1)
3916 return AVERROR_INVALIDDATA;
3917 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3918 sc->timecode_track = avio_rb32(pb);
3922 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3926 static const uint8_t uuid_isml_manifest[] = {
3927 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3928 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3931 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3932 return AVERROR_INVALIDDATA;
3934 ret = avio_read(pb, uuid, sizeof(uuid));
3937 } else if (ret != sizeof(uuid)) {
3938 return AVERROR_INVALIDDATA;
3940 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3941 uint8_t *buffer, *ptr;
3943 size_t len = atom.size - sizeof(uuid);
3946 return AVERROR_INVALIDDATA;
3948 ret = avio_skip(pb, 4); // zeroes
3951 buffer = av_mallocz(len + 1);
3953 return AVERROR(ENOMEM);
3955 ret = avio_read(pb, buffer, len);
3959 } else if (ret != len) {
3961 return AVERROR_INVALIDDATA;
3965 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
3966 ptr += sizeof("systemBitrate=\"") - 1;
3967 c->bitrates_count++;
3968 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3970 c->bitrates_count = 0;
3972 return AVERROR(ENOMEM);
3975 ret = strtol(ptr, &endptr, 10);
3976 if (ret < 0 || errno || *endptr != '"') {
3977 c->bitrates[c->bitrates_count - 1] = 0;
3979 c->bitrates[c->bitrates_count - 1] = ret;
3988 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3991 uint8_t content[16];
3996 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
4002 && !memcmp(content, "Anevia\x1A\x1A", 8)
4003 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
4004 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
4010 static const MOVParseTableEntry mov_default_parse_table[] = {
4011 { MKTAG('A','C','L','R'), mov_read_aclr },
4012 { MKTAG('A','P','R','G'), mov_read_avid },
4013 { MKTAG('A','A','L','P'), mov_read_avid },
4014 { MKTAG('A','R','E','S'), mov_read_ares },
4015 { MKTAG('a','v','s','s'), mov_read_avss },
4016 { MKTAG('c','h','p','l'), mov_read_chpl },
4017 { MKTAG('c','o','6','4'), mov_read_stco },
4018 { MKTAG('c','o','l','r'), mov_read_colr },
4019 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
4020 { MKTAG('d','i','n','f'), mov_read_default },
4021 { MKTAG('D','p','x','E'), mov_read_dpxe },
4022 { MKTAG('d','r','e','f'), mov_read_dref },
4023 { MKTAG('e','d','t','s'), mov_read_default },
4024 { MKTAG('e','l','s','t'), mov_read_elst },
4025 { MKTAG('e','n','d','a'), mov_read_enda },
4026 { MKTAG('f','i','e','l'), mov_read_fiel },
4027 { MKTAG('a','d','r','m'), mov_read_adrm },
4028 { MKTAG('f','t','y','p'), mov_read_ftyp },
4029 { MKTAG('g','l','b','l'), mov_read_glbl },
4030 { MKTAG('h','d','l','r'), mov_read_hdlr },
4031 { MKTAG('i','l','s','t'), mov_read_ilst },
4032 { MKTAG('j','p','2','h'), mov_read_jp2h },
4033 { MKTAG('m','d','a','t'), mov_read_mdat },
4034 { MKTAG('m','d','h','d'), mov_read_mdhd },
4035 { MKTAG('m','d','i','a'), mov_read_default },
4036 { MKTAG('m','e','t','a'), mov_read_meta },
4037 { MKTAG('m','i','n','f'), mov_read_default },
4038 { MKTAG('m','o','o','f'), mov_read_moof },
4039 { MKTAG('m','o','o','v'), mov_read_moov },
4040 { MKTAG('m','v','e','x'), mov_read_default },
4041 { MKTAG('m','v','h','d'), mov_read_mvhd },
4042 { MKTAG('S','M','I',' '), mov_read_svq3 },
4043 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
4044 { MKTAG('a','v','c','C'), mov_read_glbl },
4045 { MKTAG('p','a','s','p'), mov_read_pasp },
4046 { MKTAG('s','i','d','x'), mov_read_sidx },
4047 { MKTAG('s','t','b','l'), mov_read_default },
4048 { MKTAG('s','t','c','o'), mov_read_stco },
4049 { MKTAG('s','t','p','s'), mov_read_stps },
4050 { MKTAG('s','t','r','f'), mov_read_strf },
4051 { MKTAG('s','t','s','c'), mov_read_stsc },
4052 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
4053 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
4054 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
4055 { MKTAG('s','t','t','s'), mov_read_stts },
4056 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
4057 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
4058 { MKTAG('t','f','d','t'), mov_read_tfdt },
4059 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
4060 { MKTAG('t','r','a','k'), mov_read_trak },
4061 { MKTAG('t','r','a','f'), mov_read_default },
4062 { MKTAG('t','r','e','f'), mov_read_default },
4063 { MKTAG('t','m','c','d'), mov_read_tmcd },
4064 { MKTAG('c','h','a','p'), mov_read_chap },
4065 { MKTAG('t','r','e','x'), mov_read_trex },
4066 { MKTAG('t','r','u','n'), mov_read_trun },
4067 { MKTAG('u','d','t','a'), mov_read_default },
4068 { MKTAG('w','a','v','e'), mov_read_wave },
4069 { MKTAG('e','s','d','s'), mov_read_esds },
4070 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
4071 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
4072 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
4073 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
4074 { MKTAG('w','f','e','x'), mov_read_wfex },
4075 { MKTAG('c','m','o','v'), mov_read_cmov },
4076 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
4077 { MKTAG('d','v','c','1'), mov_read_dvc1 },
4078 { MKTAG('s','b','g','p'), mov_read_sbgp },
4079 { MKTAG('h','v','c','C'), mov_read_glbl },
4080 { MKTAG('u','u','i','d'), mov_read_uuid },
4081 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
4082 { MKTAG('f','r','e','e'), mov_read_free },
4083 { MKTAG('-','-','-','-'), mov_read_custom },
4087 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4089 int64_t total_size = 0;
4093 if (c->atom_depth > 10) {
4094 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
4095 return AVERROR_INVALIDDATA;
4100 atom.size = INT64_MAX;
4101 while (total_size + 8 <= atom.size && !avio_feof(pb)) {
4102 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
4105 if (atom.size >= 8) {
4106 a.size = avio_rb32(pb);
4107 a.type = avio_rl32(pb);
4108 if (a.type == MKTAG('f','r','e','e') &&
4112 uint32_t *type = (uint32_t *)buf + 1;
4113 if (avio_read(pb, buf, 8) != 8)
4114 return AVERROR_INVALIDDATA;
4115 avio_seek(pb, -8, SEEK_CUR);
4116 if (*type == MKTAG('m','v','h','d') ||
4117 *type == MKTAG('c','m','o','v')) {
4118 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
4119 a.type = MKTAG('m','o','o','v');
4122 if (atom.type != MKTAG('r','o','o','t') &&
4123 atom.type != MKTAG('m','o','o','v'))
4125 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
4127 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
4134 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
4135 a.size = avio_rb64(pb) - 8;
4139 av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
4140 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
4142 a.size = atom.size - total_size + 8;
4147 a.size = FFMIN(a.size, atom.size - total_size);
4149 for (i = 0; mov_default_parse_table[i].type; i++)
4150 if (mov_default_parse_table[i].type == a.type) {
4151 parse = mov_default_parse_table[i].parse;
4155 // container is user data
4156 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
4157 atom.type == MKTAG('i','l','s','t')))
4158 parse = mov_read_udta_string;
4160 // Supports parsing the QuickTime Metadata Keys.
4161 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
4162 if (!parse && c->found_hdlr_mdta &&
4163 atom.type == MKTAG('m','e','t','a') &&
4164 a.type == MKTAG('k','e','y','s')) {
4165 parse = mov_read_keys;
4168 if (!parse) { /* skip leaf atoms data */
4169 avio_skip(pb, a.size);
4171 int64_t start_pos = avio_tell(pb);
4173 int err = parse(c, pb, a);
4178 if (c->found_moov && c->found_mdat &&
4179 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
4180 start_pos + a.size == avio_size(pb))) {
4181 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
4182 c->next_root_atom = start_pos + a.size;
4186 left = a.size - avio_tell(pb) + start_pos;
4187 if (left > 0) /* skip garbage at atom end */
4188 avio_skip(pb, left);
4189 else if (left < 0) {
4190 av_log(c->fc, AV_LOG_WARNING,
4191 "overread end of atom '%.4s' by %"PRId64" bytes\n",
4192 (char*)&a.type, -left);
4193 avio_seek(pb, left, SEEK_CUR);
4197 total_size += a.size;
4200 if (total_size < atom.size && atom.size < 0x7ffff)
4201 avio_skip(pb, atom.size - total_size);
4207 static int mov_probe(AVProbeData *p)
4212 int moov_offset = -1;
4214 /* check file header */
4217 /* ignore invalid offset */
4218 if ((offset + 8) > (unsigned int)p->buf_size)
4220 tag = AV_RL32(p->buf + offset + 4);
4222 /* check for obvious tags */
4223 case MKTAG('m','o','o','v'):
4224 moov_offset = offset + 4;
4225 case MKTAG('m','d','a','t'):
4226 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
4227 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
4228 case MKTAG('f','t','y','p'):
4229 if (AV_RB32(p->buf+offset) < 8 &&
4230 (AV_RB32(p->buf+offset) != 1 ||
4231 offset + 12 > (unsigned int)p->buf_size ||
4232 AV_RB64(p->buf+offset + 8) == 0)) {
4233 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4234 } else if (tag == MKTAG('f','t','y','p') &&
4235 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
4236 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
4238 score = FFMAX(score, 5);
4240 score = AVPROBE_SCORE_MAX;
4242 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4244 /* those are more common words, so rate then a bit less */
4245 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
4246 case MKTAG('w','i','d','e'):
4247 case MKTAG('f','r','e','e'):
4248 case MKTAG('j','u','n','k'):
4249 case MKTAG('p','i','c','t'):
4250 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
4251 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4253 case MKTAG(0x82,0x82,0x7f,0x7d):
4254 case MKTAG('s','k','i','p'):
4255 case MKTAG('u','u','i','d'):
4256 case MKTAG('p','r','f','l'):
4257 /* if we only find those cause probedata is too small at least rate them */
4258 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4259 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4262 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4265 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
4266 /* moov atom in the header - we should make sure that this is not a
4267 * MOV-packed MPEG-PS */
4268 offset = moov_offset;
4270 while(offset < (p->buf_size - 16)){ /* Sufficient space */
4271 /* We found an actual hdlr atom */
4272 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
4273 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
4274 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
4275 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
4276 /* We found a media handler reference atom describing an
4277 * MPEG-PS-in-MOV, return a
4278 * low score to force expanding the probe window until
4279 * mpegps_probe finds what it needs */
4290 // must be done after parsing all trak because there's no order requirement
4291 static void mov_read_chapters(AVFormatContext *s)
4293 MOVContext *mov = s->priv_data;
4294 AVStream *st = NULL;
4295 MOVStreamContext *sc;
4299 for (i = 0; i < s->nb_streams; i++)
4300 if (s->streams[i]->id == mov->chapter_track) {
4305 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
4309 st->discard = AVDISCARD_ALL;
4311 cur_pos = avio_tell(sc->pb);
4313 for (i = 0; i < st->nb_index_entries; i++) {
4314 AVIndexEntry *sample = &st->index_entries[i];
4315 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
4320 if (end < sample->timestamp) {
4321 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
4322 end = AV_NOPTS_VALUE;
4325 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4326 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
4330 // the first two bytes are the length of the title
4331 len = avio_rb16(sc->pb);
4332 if (len > sample->size-2)
4334 title_len = 2*len + 1;
4335 if (!(title = av_mallocz(title_len)))
4338 // The samples could theoretically be in any encoding if there's an encd
4339 // atom following, but in practice are only utf-8 or utf-16, distinguished
4340 // instead by the presence of a BOM
4344 ch = avio_rb16(sc->pb);
4346 avio_get_str16be(sc->pb, len, title, title_len);
4347 else if (ch == 0xfffe)
4348 avio_get_str16le(sc->pb, len, title, title_len);
4351 if (len == 1 || len == 2)
4354 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
4358 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
4362 avio_seek(sc->pb, cur_pos, SEEK_SET);
4365 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
4366 uint32_t value, int flags)
4369 char buf[AV_TIMECODE_STR_SIZE];
4370 AVRational rate = {st->codec->time_base.den,
4371 st->codec->time_base.num};
4372 int ret = av_timecode_init(&tc, rate, flags, 0, s);
4375 av_dict_set(&st->metadata, "timecode",
4376 av_timecode_make_string(&tc, buf, value), 0);
4380 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
4382 MOVStreamContext *sc = st->priv_data;
4384 int64_t cur_pos = avio_tell(sc->pb);
4387 if (!st->nb_index_entries)
4390 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
4391 value = avio_rb32(s->pb);
4393 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
4394 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
4395 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
4397 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
4398 * not the case) and thus assume "frame number format" instead of QT one.
4399 * No sample with tmcd track can be found with a QT timecode at the moment,
4400 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
4402 parse_timecode_in_framenum_format(s, st, value, flags);
4404 avio_seek(sc->pb, cur_pos, SEEK_SET);
4408 static int mov_read_close(AVFormatContext *s)
4410 MOVContext *mov = s->priv_data;
4413 for (i = 0; i < s->nb_streams; i++) {
4414 AVStream *st = s->streams[i];
4415 MOVStreamContext *sc = st->priv_data;
4420 av_freep(&sc->ctts_data);
4421 for (j = 0; j < sc->drefs_count; j++) {
4422 av_freep(&sc->drefs[j].path);
4423 av_freep(&sc->drefs[j].dir);
4425 av_freep(&sc->drefs);
4427 sc->drefs_count = 0;
4429 if (!sc->pb_is_copied)
4430 avio_closep(&sc->pb);
4433 av_freep(&sc->chunk_offsets);
4434 av_freep(&sc->stsc_data);
4435 av_freep(&sc->sample_sizes);
4436 av_freep(&sc->keyframes);
4437 av_freep(&sc->stts_data);
4438 av_freep(&sc->stps_data);
4439 av_freep(&sc->elst_data);
4440 av_freep(&sc->rap_group);
4441 av_freep(&sc->display_matrix);
4444 if (mov->dv_demux) {
4445 avformat_free_context(mov->dv_fctx);
4446 mov->dv_fctx = NULL;
4449 if (mov->meta_keys) {
4450 for (i = 1; i < mov->meta_keys_count; i++) {
4451 av_freep(&mov->meta_keys[i]);
4453 av_freep(&mov->meta_keys);
4456 av_freep(&mov->trex_data);
4457 av_freep(&mov->bitrates);
4459 for (i = 0; i < mov->fragment_index_count; i++) {
4460 MOVFragmentIndex* index = mov->fragment_index_data[i];
4461 av_freep(&index->items);
4462 av_freep(&mov->fragment_index_data[i]);
4464 av_freep(&mov->fragment_index_data);
4466 av_freep(&mov->aes_decrypt);
4471 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
4475 for (i = 0; i < s->nb_streams; i++) {
4476 AVStream *st = s->streams[i];
4477 MOVStreamContext *sc = st->priv_data;
4479 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4480 sc->timecode_track == tmcd_id)
4486 /* look for a tmcd track not referenced by any video track, and export it globally */
4487 static void export_orphan_timecode(AVFormatContext *s)
4491 for (i = 0; i < s->nb_streams; i++) {
4492 AVStream *st = s->streams[i];
4494 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
4495 !tmcd_is_referenced(s, i + 1)) {
4496 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
4498 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
4505 static int read_tfra(MOVContext *mov, AVIOContext *f)
4507 MOVFragmentIndex* index = NULL;
4508 int version, fieldlength, i, j;
4509 int64_t pos = avio_tell(f);
4510 uint32_t size = avio_rb32(f);
4513 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
4516 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
4517 index = av_mallocz(sizeof(MOVFragmentIndex));
4519 return AVERROR(ENOMEM);
4522 tmp = av_realloc_array(mov->fragment_index_data,
4523 mov->fragment_index_count + 1,
4524 sizeof(MOVFragmentIndex*));
4527 return AVERROR(ENOMEM);
4529 mov->fragment_index_data = tmp;
4530 mov->fragment_index_data[mov->fragment_index_count++] = index;
4532 version = avio_r8(f);
4534 index->track_id = avio_rb32(f);
4535 fieldlength = avio_rb32(f);
4536 index->item_count = avio_rb32(f);
4537 index->items = av_mallocz_array(
4538 index->item_count, sizeof(MOVFragmentIndexItem));
4539 if (!index->items) {
4540 index->item_count = 0;
4541 return AVERROR(ENOMEM);
4543 for (i = 0; i < index->item_count; i++) {
4544 int64_t time, offset;
4546 time = avio_rb64(f);
4547 offset = avio_rb64(f);
4549 time = avio_rb32(f);
4550 offset = avio_rb32(f);
4552 index->items[i].time = time;
4553 index->items[i].moof_offset = offset;
4554 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
4556 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
4558 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
4562 avio_seek(f, pos + size, SEEK_SET);
4566 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
4568 int64_t stream_size = avio_size(f);
4569 int64_t original_pos = avio_tell(f);
4573 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
4577 mfra_size = avio_rb32(f);
4578 if (mfra_size < 0 || mfra_size > stream_size) {
4579 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
4582 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
4586 if (avio_rb32(f) != mfra_size) {
4587 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
4590 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
4591 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
4594 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
4596 ret = read_tfra(c, f);
4602 seek_ret = avio_seek(f, original_pos, SEEK_SET);
4604 av_log(c->fc, AV_LOG_ERROR,
4605 "failed to seek back after looking for mfra\n");
4611 static int mov_read_header(AVFormatContext *s)
4613 MOVContext *mov = s->priv_data;
4614 AVIOContext *pb = s->pb;
4616 MOVAtom atom = { AV_RL32("root") };
4620 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
4622 atom.size = avio_size(pb);
4624 atom.size = INT64_MAX;
4626 /* check MOV header */
4628 if (mov->moov_retry)
4629 avio_seek(pb, 0, SEEK_SET);
4630 if ((err = mov_read_default(mov, pb, atom)) < 0) {
4631 av_log(s, AV_LOG_ERROR, "error reading header\n");
4635 } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
4636 if (!mov->found_moov) {
4637 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
4639 return AVERROR_INVALIDDATA;
4641 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
4644 if (mov->chapter_track > 0 && !mov->ignore_chapters)
4645 mov_read_chapters(s);
4646 for (i = 0; i < s->nb_streams; i++)
4647 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
4648 mov_read_timecode_track(s, s->streams[i]);
4651 /* copy timecode metadata from tmcd tracks to the related video streams */
4652 for (i = 0; i < s->nb_streams; i++) {
4653 AVStream *st = s->streams[i];
4654 MOVStreamContext *sc = st->priv_data;
4655 if (sc->timecode_track > 0) {
4656 AVDictionaryEntry *tcr;
4657 int tmcd_st_id = -1;
4659 for (j = 0; j < s->nb_streams; j++)
4660 if (s->streams[j]->id == sc->timecode_track)
4663 if (tmcd_st_id < 0 || tmcd_st_id == i)
4665 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
4667 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
4670 export_orphan_timecode(s);
4672 for (i = 0; i < s->nb_streams; i++) {
4673 AVStream *st = s->streams[i];
4674 MOVStreamContext *sc = st->priv_data;
4675 fix_timescale(mov, sc);
4676 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
4677 st->skip_samples = sc->start_pad;
4679 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
4680 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4681 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
4682 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4683 if (st->codec->width <= 0 || st->codec->height <= 0) {
4684 st->codec->width = sc->width;
4685 st->codec->height = sc->height;
4687 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
4688 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
4694 if (mov->trex_data) {
4695 for (i = 0; i < s->nb_streams; i++) {
4696 AVStream *st = s->streams[i];
4697 MOVStreamContext *sc = st->priv_data;
4698 if (st->duration > 0)
4699 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
4703 if (mov->use_mfra_for > 0) {
4704 for (i = 0; i < s->nb_streams; i++) {
4705 AVStream *st = s->streams[i];
4706 MOVStreamContext *sc = st->priv_data;
4707 if (sc->duration_for_fps > 0) {
4708 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
4709 sc->duration_for_fps;
4714 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
4715 if (mov->bitrates[i]) {
4716 s->streams[i]->codec->bit_rate = mov->bitrates[i];
4720 ff_rfps_calculate(s);
4722 for (i = 0; i < s->nb_streams; i++) {
4723 AVStream *st = s->streams[i];
4724 MOVStreamContext *sc = st->priv_data;
4726 switch (st->codec->codec_type) {
4727 case AVMEDIA_TYPE_AUDIO:
4728 err = ff_replaygain_export(st, s->metadata);
4734 case AVMEDIA_TYPE_VIDEO:
4735 if (sc->display_matrix) {
4736 AVPacketSideData *sd, *tmp;
4738 tmp = av_realloc_array(st->side_data,
4739 st->nb_side_data + 1, sizeof(*tmp));
4741 return AVERROR(ENOMEM);
4743 st->side_data = tmp;
4746 sd = &st->side_data[st->nb_side_data - 1];
4747 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
4748 sd->size = sizeof(int32_t) * 9;
4749 sd->data = (uint8_t*)sc->display_matrix;
4750 sc->display_matrix = NULL;
4755 ff_configure_buffers_for_index(s, AV_TIME_BASE);
4760 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
4762 AVIndexEntry *sample = NULL;
4763 int64_t best_dts = INT64_MAX;
4765 for (i = 0; i < s->nb_streams; i++) {
4766 AVStream *avst = s->streams[i];
4767 MOVStreamContext *msc = avst->priv_data;
4768 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
4769 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
4770 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
4771 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
4772 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
4774 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
4775 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
4776 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
4777 sample = current_sample;
4786 static int should_retry(AVIOContext *pb, int error_code) {
4787 if (error_code == AVERROR_EOF || avio_feof(pb))
4793 static int mov_switch_root(AVFormatContext *s, int64_t target)
4795 MOVContext *mov = s->priv_data;
4797 int already_read = 0;
4799 if (avio_seek(s->pb, target, SEEK_SET) != target) {
4800 av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
4801 return AVERROR_INVALIDDATA;
4804 mov->next_root_atom = 0;
4806 for (i = 0; i < mov->fragment_index_count; i++) {
4807 MOVFragmentIndex *index = mov->fragment_index_data[i];
4809 for (j = 0; j < index->item_count; j++) {
4810 MOVFragmentIndexItem *item = &index->items[j];
4812 mov->next_root_atom = item->moof_offset;
4813 break; // Advance to next index in outer loop
4814 } else if (item->moof_offset == target) {
4815 index->current_item = FFMIN(j, index->current_item);
4816 if (item->headers_read)
4818 item->headers_read = 1;
4823 index->current_item = 0;
4829 mov->found_mdat = 0;
4831 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
4834 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
4839 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
4841 MOVContext *mov = s->priv_data;
4842 MOVStreamContext *sc;
4843 AVIndexEntry *sample;
4844 AVStream *st = NULL;
4848 sample = mov_find_next_sample(s, &st);
4849 if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
4850 if (!mov->next_root_atom)
4852 if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
4857 /* must be done just before reading, to avoid infinite loop on sample */
4858 sc->current_sample++;
4860 if (mov->next_root_atom) {
4861 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
4862 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
4865 if (st->discard != AVDISCARD_ALL) {
4866 int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
4867 if (ret64 != sample->pos) {
4868 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
4869 sc->ffindex, sample->pos);
4870 sc->current_sample -= should_retry(sc->pb, ret64);
4871 return AVERROR_INVALIDDATA;
4873 ret = av_get_packet(sc->pb, pkt, sample->size);
4875 sc->current_sample -= should_retry(sc->pb, ret);
4878 if (sc->has_palette) {
4881 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
4883 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
4885 memcpy(pal, sc->palette, AVPALETTE_SIZE);
4886 sc->has_palette = 0;
4889 #if CONFIG_DV_DEMUXER
4890 if (mov->dv_demux && sc->dv_audio_container) {
4891 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
4892 av_freep(&pkt->data);
4894 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
4901 pkt->stream_index = sc->ffindex;
4902 pkt->dts = sample->timestamp;
4903 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
4904 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
4905 /* update ctts context */
4907 if (sc->ctts_index < sc->ctts_count &&
4908 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
4910 sc->ctts_sample = 0;
4913 pkt->dts = AV_NOPTS_VALUE;
4915 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
4916 st->index_entries[sc->current_sample].timestamp : st->duration;
4917 pkt->duration = next_dts - pkt->dts;
4918 pkt->pts = pkt->dts;
4920 if (st->discard == AVDISCARD_ALL)
4922 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
4923 pkt->pos = sample->pos;
4926 aax_filter(pkt->data, pkt->size, mov);
4931 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
4933 MOVContext *mov = s->priv_data;
4936 if (!mov->fragment_index_complete)
4939 for (i = 0; i < mov->fragment_index_count; i++) {
4940 if (mov->fragment_index_data[i]->track_id == st->id) {
4941 MOVFragmentIndex *index = mov->fragment_index_data[i];
4942 for (j = index->item_count - 1; j >= 0; j--) {
4943 if (index->items[j].time <= timestamp) {
4944 if (index->items[j].headers_read)
4947 return mov_switch_root(s, index->items[j].moof_offset);
4956 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
4958 MOVStreamContext *sc = st->priv_data;
4959 int sample, time_sample;
4962 int ret = mov_seek_fragment(s, st, timestamp);
4966 sample = av_index_search_timestamp(st, timestamp, flags);
4967 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
4968 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
4970 if (sample < 0) /* not sure what to do */
4971 return AVERROR_INVALIDDATA;
4972 sc->current_sample = sample;
4973 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
4974 /* adjust ctts index */
4975 if (sc->ctts_data) {
4977 for (i = 0; i < sc->ctts_count; i++) {
4978 int next = time_sample + sc->ctts_data[i].count;
4979 if (next > sc->current_sample) {
4981 sc->ctts_sample = sc->current_sample - time_sample;
4990 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
4992 MOVContext *mc = s->priv_data;
4997 if (stream_index >= s->nb_streams)
4998 return AVERROR_INVALIDDATA;
5000 st = s->streams[stream_index];
5001 sample = mov_seek_stream(s, st, sample_time, flags);
5005 if (mc->seek_individually) {
5006 /* adjust seek timestamp to found sample timestamp */
5007 int64_t seek_timestamp = st->index_entries[sample].timestamp;
5009 for (i = 0; i < s->nb_streams; i++) {
5011 MOVStreamContext *sc = s->streams[i]->priv_data;
5013 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
5015 if (stream_index == i)
5018 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
5019 mov_seek_stream(s, st, timestamp, flags);
5022 for (i = 0; i < s->nb_streams; i++) {
5023 MOVStreamContext *sc;
5026 sc->current_sample = 0;
5029 MOVStreamContext *sc;
5030 AVIndexEntry *entry = mov_find_next_sample(s, &st);
5032 return AVERROR_INVALIDDATA;
5034 if (sc->ffindex == stream_index && sc->current_sample == sample)
5036 sc->current_sample++;
5042 #define OFFSET(x) offsetof(MOVContext, x)
5043 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
5044 static const AVOption mov_options[] = {
5045 {"use_absolute_path",
5046 "allow using absolute path when opening alias, this is a possible security issue",
5047 OFFSET(use_absolute_path), AV_OPT_TYPE_INT, {.i64 = 0},
5049 {"seek_streams_individually",
5050 "Seek each stream individually to the to the closest point",
5051 OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
5053 {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_INT, {.i64 = 0},
5055 {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
5058 "use mfra for fragment timestamps",
5059 OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
5060 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
5062 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
5063 FLAGS, "use_mfra_for" },
5064 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
5065 FLAGS, "use_mfra_for" },
5066 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
5067 FLAGS, "use_mfra_for" },
5068 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
5069 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5070 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
5071 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5072 { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
5073 AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5074 { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
5075 "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
5076 AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
5077 .flags = AV_OPT_FLAG_DECODING_PARAM },
5081 static const AVClass mov_class = {
5082 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
5083 .item_name = av_default_item_name,
5084 .option = mov_options,
5085 .version = LIBAVUTIL_VERSION_INT,
5088 AVInputFormat ff_mov_demuxer = {
5089 .name = "mov,mp4,m4a,3gp,3g2,mj2",
5090 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5091 .priv_class = &mov_class,
5092 .priv_data_size = sizeof(MOVContext),
5093 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
5094 .read_probe = mov_probe,
5095 .read_header = mov_read_header,
5096 .read_packet = mov_read_packet,
5097 .read_close = mov_read_close,
5098 .read_seek = mov_read_seek,
5099 .flags = AVFMT_NO_BYTE_SEEK,