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 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
199 st->attached_pic = pkt;
200 st->attached_pic.stream_index = st->index;
201 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
203 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
204 st->codec->codec_id = id;
209 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
211 char language[4] = { 0 };
212 char buf[200], place[100];
213 uint16_t langcode = 0;
214 double longitude, latitude, altitude;
215 const char *key = "location";
217 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
218 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
219 return AVERROR_INVALIDDATA;
222 avio_skip(pb, 4); // version+flags
223 langcode = avio_rb16(pb);
224 ff_mov_lang_to_iso639(langcode, language);
227 len -= avio_get_str(pb, len, place, sizeof(place));
229 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
230 return AVERROR_INVALIDDATA;
232 avio_skip(pb, 1); // role
236 av_log(c->fc, AV_LOG_ERROR, "no space for coordinates left (%d)\n", len);
237 return AVERROR_INVALIDDATA;
239 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
240 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
241 altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
243 // Try to output in the same format as the ?xyz field
244 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
246 av_strlcatf(buf, sizeof(buf), "%+f", altitude);
247 av_strlcatf(buf, sizeof(buf), "/%s", place);
249 if (*language && strcmp(language, "und")) {
251 snprintf(key2, sizeof(key2), "%s-%s", key, language);
252 av_dict_set(&c->fc->metadata, key2, buf, 0);
254 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
255 return av_dict_set(&c->fc->metadata, key, buf, 0);
258 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
261 char key2[32], language[4] = {0};
263 const char *key = NULL;
264 uint16_t langcode = 0;
265 uint32_t data_type = 0, str_size, str_size_alloc;
266 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
271 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
272 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
273 case MKTAG( 'X','M','P','_'):
274 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
275 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
276 case MKTAG( 'a','k','I','D'): key = "account_type";
277 parse = mov_metadata_int8_no_padding; break;
278 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
279 case MKTAG( 'c','a','t','g'): key = "category"; break;
280 case MKTAG( 'c','p','i','l'): key = "compilation";
281 parse = mov_metadata_int8_no_padding; break;
282 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
283 case MKTAG( 'd','e','s','c'): key = "description"; break;
284 case MKTAG( 'd','i','s','k'): key = "disc";
285 parse = mov_metadata_track_or_disc_number; break;
286 case MKTAG( 'e','g','i','d'): key = "episode_uid";
287 parse = mov_metadata_int8_no_padding; break;
288 case MKTAG( 'g','n','r','e'): key = "genre";
289 parse = mov_metadata_gnre; break;
290 case MKTAG( 'h','d','v','d'): key = "hd_video";
291 parse = mov_metadata_int8_no_padding; break;
292 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
293 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
294 case MKTAG( 'l','o','c','i'):
295 return mov_metadata_loci(c, pb, atom.size);
296 case MKTAG( 'p','c','s','t'): key = "podcast";
297 parse = mov_metadata_int8_no_padding; break;
298 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
299 parse = mov_metadata_int8_no_padding; break;
300 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
301 case MKTAG( 'r','t','n','g'): key = "rating";
302 parse = mov_metadata_int8_no_padding; break;
303 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
304 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
305 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
306 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
307 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
308 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
309 case MKTAG( 's','t','i','k'): key = "media_type";
310 parse = mov_metadata_int8_no_padding; break;
311 case MKTAG( 't','r','k','n'): key = "track";
312 parse = mov_metadata_track_or_disc_number; break;
313 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
314 case MKTAG( 't','v','e','s'): key = "episode_sort";
315 parse = mov_metadata_int8_bypass_padding; break;
316 case MKTAG( 't','v','n','n'): key = "network"; break;
317 case MKTAG( 't','v','s','h'): key = "show"; break;
318 case MKTAG( 't','v','s','n'): key = "season_number";
319 parse = mov_metadata_int8_bypass_padding; break;
320 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
321 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
322 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
323 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
324 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
325 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
326 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
327 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
328 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
329 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
330 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
331 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
332 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
333 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
334 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
335 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
336 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
337 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
338 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
339 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
340 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
341 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
342 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
343 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
344 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
345 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
346 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
347 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
348 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
349 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
350 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
351 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
352 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
353 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
354 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
357 if (c->itunes_metadata && atom.size > 8) {
358 int data_size = avio_rb32(pb);
359 int tag = avio_rl32(pb);
360 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
361 data_type = avio_rb32(pb); // type
362 avio_rb32(pb); // unknown
363 str_size = data_size - 16;
366 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
367 int ret = mov_read_covr(c, pb, data_type, str_size);
369 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
372 } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
373 uint32_t index = AV_RB32(&atom.type);
374 if (index < c->meta_keys_count) {
375 key = c->meta_keys[index];
377 av_log(c->fc, AV_LOG_WARNING,
378 "The index of 'data' is out of range: %d >= %d.\n",
379 index, c->meta_keys_count);
383 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
384 str_size = avio_rb16(pb); // string length
385 if (str_size > atom.size) {
387 avio_seek(pb, -2, SEEK_CUR);
388 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
391 langcode = avio_rb16(pb);
392 ff_mov_lang_to_iso639(langcode, language);
395 str_size = atom.size;
397 if (c->export_all && !key) {
398 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
404 if (atom.size < 0 || str_size >= INT_MAX/2)
405 return AVERROR_INVALIDDATA;
407 // Allocates enough space if data_type is a float32 number, otherwise
408 // worst-case requirement for output string in case of utf8 coded input
409 num = (data_type == 23);
410 str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
411 str = av_mallocz(str_size_alloc);
413 return AVERROR(ENOMEM);
416 parse(c, pb, str_size, key);
418 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
419 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
420 } else if (data_type == 23 && str_size >= 4) { // BE float32
421 float val = av_int2float(avio_rb32(pb));
422 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
423 av_log(c->fc, AV_LOG_ERROR,
424 "Failed to store the float32 number (%f) in string.\n", val);
425 return AVERROR_INVALIDDATA;
428 int ret = ffio_read_size(pb, str, str_size);
435 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
436 av_dict_set(&c->fc->metadata, key, str, 0);
437 if (*language && strcmp(language, "und")) {
438 snprintf(key2, sizeof(key2), "%s-%s", key, language);
439 av_dict_set(&c->fc->metadata, key2, str, 0);
442 av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
443 av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
444 key, str, (char*)&atom.type, str_size_alloc, atom.size);
450 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
453 int i, nb_chapters, str_len, version;
457 if ((atom.size -= 5) < 0)
460 version = avio_r8(pb);
463 avio_rb32(pb); // ???
464 nb_chapters = avio_r8(pb);
466 for (i = 0; i < nb_chapters; i++) {
470 start = avio_rb64(pb);
471 str_len = avio_r8(pb);
473 if ((atom.size -= 9+str_len) < 0)
476 ret = ffio_read_size(pb, str, str_len);
480 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
485 #define MIN_DATA_ENTRY_BOX_SIZE 12
486 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
489 MOVStreamContext *sc;
492 if (c->fc->nb_streams < 1)
494 st = c->fc->streams[c->fc->nb_streams-1];
497 avio_rb32(pb); // version + flags
498 entries = avio_rb32(pb);
499 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
500 entries >= UINT_MAX / sizeof(*sc->drefs))
501 return AVERROR_INVALIDDATA;
504 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
506 return AVERROR(ENOMEM);
507 sc->drefs_count = entries;
509 for (i = 0; i < sc->drefs_count; i++) {
510 MOVDref *dref = &sc->drefs[i];
511 uint32_t size = avio_rb32(pb);
512 int64_t next = avio_tell(pb) + size - 4;
515 return AVERROR_INVALIDDATA;
517 dref->type = avio_rl32(pb);
518 avio_rb32(pb); // version + flags
519 av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
521 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
522 /* macintosh alias record */
523 uint16_t volume_len, len;
529 volume_len = avio_r8(pb);
530 volume_len = FFMIN(volume_len, 27);
531 ret = ffio_read_size(pb, dref->volume, 27);
534 dref->volume[volume_len] = 0;
535 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
540 len = FFMIN(len, 63);
541 ret = ffio_read_size(pb, dref->filename, 63);
544 dref->filename[len] = 0;
545 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
549 /* read next level up_from_alias/down_to_target */
550 dref->nlvl_from = avio_rb16(pb);
551 dref->nlvl_to = avio_rb16(pb);
552 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
553 dref->nlvl_from, dref->nlvl_to);
557 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
560 type = avio_rb16(pb);
562 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
565 if (type == 2 || type == 18) { // absolute path
567 dref->path = av_mallocz(len+1);
569 return AVERROR(ENOMEM);
571 ret = ffio_read_size(pb, dref->path, len);
573 av_freep(&dref->path);
576 if (type == 18) // no additional processing needed
578 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
580 memmove(dref->path, dref->path+volume_len, len);
583 for (j = 0; j < len; j++)
584 if (dref->path[j] == ':')
586 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
587 } else if (type == 0) { // directory name
589 dref->dir = av_malloc(len+1);
591 return AVERROR(ENOMEM);
593 ret = ffio_read_size(pb, dref->dir, len);
595 av_freep(&dref->dir);
599 for (j = 0; j < len; j++)
600 if (dref->dir[j] == ':')
602 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
607 avio_seek(pb, next, SEEK_SET);
612 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
616 uint32_t av_unused ctype;
621 avio_r8(pb); /* version */
622 avio_rb24(pb); /* flags */
625 ctype = avio_rl32(pb);
626 type = avio_rl32(pb); /* component subtype */
628 av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
629 av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
631 if (c->fc->nb_streams < 1) { // meta before first trak
632 if (type == MKTAG('m','d','t','a')) {
633 c->found_hdlr_mdta = 1;
638 st = c->fc->streams[c->fc->nb_streams-1];
640 if (type == MKTAG('v','i','d','e'))
641 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
642 else if (type == MKTAG('s','o','u','n'))
643 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
644 else if (type == MKTAG('m','1','a',' '))
645 st->codec->codec_id = AV_CODEC_ID_MP2;
646 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
647 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
649 avio_rb32(pb); /* component manufacture */
650 avio_rb32(pb); /* component flags */
651 avio_rb32(pb); /* component flags mask */
653 title_size = atom.size - 24;
654 if (title_size > 0) {
655 title_str = av_malloc(title_size + 1); /* Add null terminator */
657 return AVERROR(ENOMEM);
659 ret = ffio_read_size(pb, title_str, title_size);
661 av_freep(&title_str);
664 title_str[title_size] = 0;
666 int off = (!c->isom && title_str[0] == title_size - 1);
667 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
669 av_freep(&title_str);
675 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
680 if (fc->nb_streams < 1)
682 st = fc->streams[fc->nb_streams-1];
684 avio_rb32(pb); /* version + flags */
685 ff_mp4_read_descr(fc, pb, &tag);
686 if (tag == MP4ESDescrTag) {
687 ff_mp4_parse_es_descr(pb, NULL);
689 avio_rb16(pb); /* ID */
691 ff_mp4_read_descr(fc, pb, &tag);
692 if (tag == MP4DecConfigDescrTag)
693 ff_mp4_read_dec_config_descr(fc, st, pb);
697 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
699 return ff_mov_read_esds(c->fc, pb);
702 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
705 enum AVAudioServiceType *ast;
706 int ac3info, acmod, lfeon, bsmod;
708 if (c->fc->nb_streams < 1)
710 st = c->fc->streams[c->fc->nb_streams-1];
712 ast = (enum AVAudioServiceType*)ff_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
715 return AVERROR(ENOMEM);
717 ac3info = avio_rb24(pb);
718 bsmod = (ac3info >> 14) & 0x7;
719 acmod = (ac3info >> 11) & 0x7;
720 lfeon = (ac3info >> 10) & 0x1;
721 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
722 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
724 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
726 if (st->codec->channels > 1 && bsmod == 0x7)
727 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
729 st->codec->audio_service_type = *ast;
734 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
737 enum AVAudioServiceType *ast;
738 int eac3info, acmod, lfeon, bsmod;
740 if (c->fc->nb_streams < 1)
742 st = c->fc->streams[c->fc->nb_streams-1];
744 ast = (enum AVAudioServiceType*)ff_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
747 return AVERROR(ENOMEM);
749 /* No need to parse fields for additional independent substreams and its
750 * associated dependent substreams since libavcodec's E-AC-3 decoder
751 * does not support them yet. */
752 avio_rb16(pb); /* data_rate and num_ind_sub */
753 eac3info = avio_rb24(pb);
754 bsmod = (eac3info >> 12) & 0x1f;
755 acmod = (eac3info >> 9) & 0x7;
756 lfeon = (eac3info >> 8) & 0x1;
757 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
759 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
760 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
762 if (st->codec->channels > 1 && bsmod == 0x7)
763 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
765 st->codec->audio_service_type = *ast;
770 static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
772 const uint32_t ddts_size = 20;
775 uint32_t frame_duration_code = 0;
776 uint32_t channel_layout_code = 0;
779 buf = av_malloc(ddts_size + FF_INPUT_BUFFER_PADDING_SIZE);
781 return AVERROR(ENOMEM);
783 if (avio_read(pb, buf, ddts_size) < ddts_size) {
785 return AVERROR_INVALIDDATA;
788 init_get_bits(&gb, buf, 8*ddts_size);
790 if (c->fc->nb_streams < 1) {
793 st = c->fc->streams[c->fc->nb_streams-1];
795 st->codec->sample_rate = get_bits_long(&gb, 32);
796 skip_bits_long(&gb, 32); /* max bitrate */
797 st->codec->bit_rate = get_bits_long(&gb, 32);
798 st->codec->bits_per_coded_sample = get_bits(&gb, 8);
799 frame_duration_code = get_bits(&gb, 2);
800 skip_bits(&gb, 30); /* various fields */
801 channel_layout_code = get_bits(&gb, 16);
803 st->codec->frame_size =
804 (frame_duration_code == 0) ? 512 :
805 (frame_duration_code == 1) ? 1024 :
806 (frame_duration_code == 2) ? 2048 :
807 (frame_duration_code == 3) ? 4096 : 0;
809 if (channel_layout_code > 0xff) {
810 av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
812 st->codec->channel_layout =
813 ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
814 ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
815 ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
816 ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
817 ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
818 ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
820 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
825 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
829 if (c->fc->nb_streams < 1)
831 st = c->fc->streams[c->fc->nb_streams-1];
836 /* skip version and flags */
839 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
844 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
849 if (c->fc->nb_streams < 1)
851 st = c->fc->streams[c->fc->nb_streams-1];
853 if ((ret = ff_get_wav_header(c->fc, pb, st->codec, atom.size, 0)) < 0)
854 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
859 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
861 const int num = avio_rb32(pb);
862 const int den = avio_rb32(pb);
865 if (c->fc->nb_streams < 1)
867 st = c->fc->streams[c->fc->nb_streams-1];
869 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
870 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
871 av_log(c->fc, AV_LOG_WARNING,
872 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
873 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
875 } else if (den != 0) {
876 av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
882 /* this atom contains actual media data */
883 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
885 if (atom.size == 0) /* wrong one (MP4) */
888 return 0; /* now go for moov */
891 #define DRM_BLOB_SIZE 56
893 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
895 uint8_t intermediate_key[20];
896 uint8_t intermediate_iv[20];
899 uint8_t file_checksum[20];
900 uint8_t calculated_checksum[20];
904 uint8_t *activation_bytes = c->activation_bytes;
905 uint8_t *fixed_key = c->audible_fixed_key;
909 sha = av_sha_alloc();
911 return AVERROR(ENOMEM);
912 c->aes_decrypt = av_aes_alloc();
913 if (!c->aes_decrypt) {
914 ret = AVERROR(ENOMEM);
918 /* drm blob processing */
919 avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
920 avio_read(pb, input, DRM_BLOB_SIZE);
921 avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
922 avio_read(pb, file_checksum, 20);
924 av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
925 for (i = 0; i < 20; i++)
926 av_log(sha, AV_LOG_INFO, "%02x", file_checksum[i]);
927 av_log(c->fc, AV_LOG_INFO, "\n");
929 /* verify activation data */
930 if (!activation_bytes) {
931 av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
932 ret = 0; /* allow ffprobe to continue working on .aax files */
935 if (c->activation_bytes_size != 4) {
936 av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
937 ret = AVERROR(EINVAL);
941 /* verify fixed key */
942 if (c->audible_fixed_key_size != 16) {
943 av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
944 ret = AVERROR(EINVAL);
948 /* AAX (and AAX+) key derivation */
949 av_sha_init(sha, 160);
950 av_sha_update(sha, fixed_key, 16);
951 av_sha_update(sha, activation_bytes, 4);
952 av_sha_final(sha, intermediate_key);
953 av_sha_init(sha, 160);
954 av_sha_update(sha, fixed_key, 16);
955 av_sha_update(sha, intermediate_key, 20);
956 av_sha_update(sha, activation_bytes, 4);
957 av_sha_final(sha, intermediate_iv);
958 av_sha_init(sha, 160);
959 av_sha_update(sha, intermediate_key, 16);
960 av_sha_update(sha, intermediate_iv, 16);
961 av_sha_final(sha, calculated_checksum);
962 if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
963 av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
964 ret = AVERROR_INVALIDDATA;
967 av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
968 av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
969 for (i = 0; i < 4; i++) {
970 // file data (in output) is stored in big-endian mode
971 if (activation_bytes[i] != output[3 - i]) { // critical error
972 av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
973 ret = AVERROR_INVALIDDATA;
977 memcpy(c->file_key, output + 8, 16);
978 memcpy(input, output + 26, 16);
979 av_sha_init(sha, 160);
980 av_sha_update(sha, input, 16);
981 av_sha_update(sha, c->file_key, 16);
982 av_sha_update(sha, fixed_key, 16);
983 av_sha_final(sha, c->file_iv);
991 // Audible AAX (and AAX+) bytestream decryption
992 static int aax_filter(uint8_t *input, int size, MOVContext *c)
995 unsigned char iv[16];
997 memcpy(iv, c->file_iv, 16); // iv is overwritten
998 blocks = size >> 4; // trailing bytes are not encrypted!
999 av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1000 av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1005 /* read major brand, minor version and compatible brands and store them as metadata */
1006 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1009 int comp_brand_size;
1010 char* comp_brands_str;
1011 uint8_t type[5] = {0};
1012 int ret = ffio_read_size(pb, type, 4);
1016 if (strcmp(type, "qt "))
1018 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1019 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1020 minor_ver = avio_rb32(pb); /* minor version */
1021 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1023 comp_brand_size = atom.size - 8;
1024 if (comp_brand_size < 0)
1025 return AVERROR_INVALIDDATA;
1026 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1027 if (!comp_brands_str)
1028 return AVERROR(ENOMEM);
1030 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1032 av_freep(&comp_brands_str);
1035 comp_brands_str[comp_brand_size] = 0;
1036 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1037 av_freep(&comp_brands_str);
1042 /* this atom should contain all header atoms */
1043 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1047 if (c->found_moov) {
1048 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1049 avio_skip(pb, atom.size);
1053 if ((ret = mov_read_default(c, pb, atom)) < 0)
1055 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1056 /* so we don't parse the whole file if over a network */
1058 return 0; /* now go for mdat */
1061 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1063 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1064 c->has_looked_for_mfra = 1;
1067 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1069 if ((ret = mov_read_mfra(c, pb)) < 0) {
1070 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1071 "read the mfra (may be a live ismv)\n");
1074 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1075 "seekable, can not look for mfra\n");
1078 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
1079 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1080 return mov_read_default(c, pb, atom);
1083 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1087 struct tm *ptm, tmbuf;
1089 if(time >= 2082844800)
1090 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1092 ptm = gmtime_r(&timet, &tmbuf);
1094 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
1095 av_dict_set(metadata, "creation_time", buffer, 0);
1099 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1102 MOVStreamContext *sc;
1104 char language[4] = {0};
1106 int64_t creation_time;
1108 if (c->fc->nb_streams < 1)
1110 st = c->fc->streams[c->fc->nb_streams-1];
1113 if (sc->time_scale) {
1114 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1115 return AVERROR_INVALIDDATA;
1118 version = avio_r8(pb);
1120 avpriv_request_sample(c->fc, "Version %d", version);
1121 return AVERROR_PATCHWELCOME;
1123 avio_rb24(pb); /* flags */
1125 creation_time = avio_rb64(pb);
1128 creation_time = avio_rb32(pb);
1129 avio_rb32(pb); /* modification time */
1131 mov_metadata_creation_time(&st->metadata, creation_time);
1133 sc->time_scale = avio_rb32(pb);
1134 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1136 lang = avio_rb16(pb); /* language */
1137 if (ff_mov_lang_to_iso639(lang, language))
1138 av_dict_set(&st->metadata, "language", language, 0);
1139 avio_rb16(pb); /* quality */
1144 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1146 int64_t creation_time;
1147 int version = avio_r8(pb); /* version */
1148 avio_rb24(pb); /* flags */
1151 creation_time = avio_rb64(pb);
1154 creation_time = avio_rb32(pb);
1155 avio_rb32(pb); /* modification time */
1157 mov_metadata_creation_time(&c->fc->metadata, creation_time);
1158 c->time_scale = avio_rb32(pb); /* time scale */
1160 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1162 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1163 // set the AVCodecContext duration because the duration of individual tracks
1164 // may be inaccurate
1165 if (c->time_scale > 0 && !c->trex_data)
1166 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1167 avio_rb32(pb); /* preferred scale */
1169 avio_rb16(pb); /* preferred volume */
1171 avio_skip(pb, 10); /* reserved */
1173 avio_skip(pb, 36); /* display matrix */
1175 avio_rb32(pb); /* preview time */
1176 avio_rb32(pb); /* preview duration */
1177 avio_rb32(pb); /* poster time */
1178 avio_rb32(pb); /* selection time */
1179 avio_rb32(pb); /* selection duration */
1180 avio_rb32(pb); /* current time */
1181 avio_rb32(pb); /* next track ID */
1186 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1191 if (c->fc->nb_streams < 1)
1193 st = c->fc->streams[c->fc->nb_streams-1];
1195 little_endian = avio_rb16(pb) & 0xFF;
1196 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1197 if (little_endian == 1) {
1198 switch (st->codec->codec_id) {
1199 case AV_CODEC_ID_PCM_S24BE:
1200 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
1202 case AV_CODEC_ID_PCM_S32BE:
1203 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
1205 case AV_CODEC_ID_PCM_F32BE:
1206 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
1208 case AV_CODEC_ID_PCM_F64BE:
1209 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
1218 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1221 char color_parameter_type[5] = { 0 };
1222 uint16_t color_primaries, color_trc, color_matrix;
1225 if (c->fc->nb_streams < 1)
1227 st = c->fc->streams[c->fc->nb_streams - 1];
1229 ret = ffio_read_size(pb, color_parameter_type, 4);
1232 if (strncmp(color_parameter_type, "nclx", 4) &&
1233 strncmp(color_parameter_type, "nclc", 4)) {
1234 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1235 color_parameter_type);
1239 color_primaries = avio_rb16(pb);
1240 color_trc = avio_rb16(pb);
1241 color_matrix = avio_rb16(pb);
1243 av_log(c->fc, AV_LOG_TRACE,
1244 "%s: pri %d trc %d matrix %d",
1245 color_parameter_type, color_primaries, color_trc, color_matrix);
1247 if (!strncmp(color_parameter_type, "nclx", 4)) {
1248 uint8_t color_range = avio_r8(pb) >> 7;
1249 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1251 st->codec->color_range = AVCOL_RANGE_JPEG;
1253 st->codec->color_range = AVCOL_RANGE_MPEG;
1254 /* 14496-12 references JPEG XR specs (rather than the more complete
1255 * 23001-8) so some adjusting is required */
1256 if (color_primaries >= AVCOL_PRI_FILM)
1257 color_primaries = AVCOL_PRI_UNSPECIFIED;
1258 if ((color_trc >= AVCOL_TRC_LINEAR &&
1259 color_trc <= AVCOL_TRC_LOG_SQRT) ||
1260 color_trc >= AVCOL_TRC_BT2020_10)
1261 color_trc = AVCOL_TRC_UNSPECIFIED;
1262 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
1263 color_matrix = AVCOL_SPC_UNSPECIFIED;
1264 st->codec->color_primaries = color_primaries;
1265 st->codec->color_trc = color_trc;
1266 st->codec->colorspace = color_matrix;
1267 } else if (!strncmp(color_parameter_type, "nclc", 4)) {
1268 /* color primaries, Table 4-4 */
1269 switch (color_primaries) {
1270 case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
1271 case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
1272 case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
1274 /* color transfer, Table 4-5 */
1275 switch (color_trc) {
1276 case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
1277 case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
1279 /* color matrix, Table 4-6 */
1280 switch (color_matrix) {
1281 case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
1282 case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
1283 case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
1286 av_log(c->fc, AV_LOG_TRACE, "\n");
1291 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1294 unsigned mov_field_order;
1295 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1297 if (c->fc->nb_streams < 1) // will happen with jp2 files
1299 st = c->fc->streams[c->fc->nb_streams-1];
1301 return AVERROR_INVALIDDATA;
1302 mov_field_order = avio_rb16(pb);
1303 if ((mov_field_order & 0xFF00) == 0x0100)
1304 decoded_field_order = AV_FIELD_PROGRESSIVE;
1305 else if ((mov_field_order & 0xFF00) == 0x0200) {
1306 switch (mov_field_order & 0xFF) {
1307 case 0x01: decoded_field_order = AV_FIELD_TT;
1309 case 0x06: decoded_field_order = AV_FIELD_BB;
1311 case 0x09: decoded_field_order = AV_FIELD_TB;
1313 case 0x0E: decoded_field_order = AV_FIELD_BT;
1317 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1318 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1320 st->codec->field_order = decoded_field_order;
1325 static int mov_realloc_extradata(AVCodecContext *codec, MOVAtom atom)
1328 uint64_t size = (uint64_t)codec->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1329 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1330 return AVERROR_INVALIDDATA;
1331 if ((err = av_reallocp(&codec->extradata, size)) < 0) {
1332 codec->extradata_size = 0;
1335 codec->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1339 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1340 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1341 AVCodecContext *codec, uint8_t *buf)
1343 int64_t result = atom.size;
1346 AV_WB32(buf , atom.size + 8);
1347 AV_WL32(buf + 4, atom.type);
1348 err = ffio_read_size(pb, buf + 8, atom.size);
1350 codec->extradata_size -= atom.size;
1352 } else if (err < atom.size) {
1353 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1354 codec->extradata_size -= atom.size - err;
1357 memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1361 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
1362 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1363 enum AVCodecID codec_id)
1366 uint64_t original_size;
1369 if (c->fc->nb_streams < 1) // will happen with jp2 files
1371 st = c->fc->streams[c->fc->nb_streams-1];
1373 if (st->codec->codec_id != codec_id)
1374 return 0; /* unexpected codec_id - don't mess with extradata */
1376 original_size = st->codec->extradata_size;
1377 err = mov_realloc_extradata(st->codec, atom);
1381 err = mov_read_atom_into_extradata(c, pb, atom, st->codec, st->codec->extradata + original_size);
1384 return 0; // Note: this is the original behavior to ignore truncation.
1387 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1388 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1390 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1393 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1395 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1398 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1400 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1403 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1405 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1408 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1410 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1412 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1416 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1418 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1420 if (!ret && c->fc->nb_streams >= 1) {
1421 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
1422 if (avctx->extradata_size >= 40) {
1423 avctx->height = AV_RB16(&avctx->extradata[36]);
1424 avctx->width = AV_RB16(&avctx->extradata[38]);
1430 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1432 if (c->fc->nb_streams >= 1) {
1433 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1434 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1435 codec->codec_id == AV_CODEC_ID_H264 &&
1438 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1439 if (avio_rb16(pb) == 0xd4d)
1440 codec->width = 1440;
1445 return mov_read_avid(c, pb, atom);
1448 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1452 uint64_t original_size;
1453 if (c->fc->nb_streams >= 1) {
1454 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1455 if (codec->codec_id == AV_CODEC_ID_H264)
1457 if (atom.size == 16) {
1458 original_size = codec->extradata_size;
1459 ret = mov_realloc_extradata(codec, atom);
1461 length = mov_read_atom_into_extradata(c, pb, atom, codec, codec->extradata + original_size);
1462 if (length == atom.size) {
1463 const uint8_t range_value = codec->extradata[original_size + 19];
1464 switch (range_value) {
1466 codec->color_range = AVCOL_RANGE_MPEG;
1469 codec->color_range = AVCOL_RANGE_JPEG;
1472 av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1475 ff_dlog(c, "color_range: %d\n", codec->color_range);
1477 /* For some reason the whole atom was not added to the extradata */
1478 av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1481 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1484 av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1491 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1493 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1496 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1501 if (c->fc->nb_streams < 1)
1503 st = c->fc->streams[c->fc->nb_streams-1];
1505 if ((uint64_t)atom.size > (1<<30))
1506 return AVERROR_INVALIDDATA;
1508 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1509 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1510 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1511 // pass all frma atom to codec, needed at least for QDMC and QDM2
1512 av_freep(&st->codec->extradata);
1513 ret = ff_get_extradata(st->codec, pb, atom.size);
1516 } else if (atom.size > 8) { /* to read frma, esds atoms */
1517 if (st->codec->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1519 ret = ffio_ensure_seekback(pb, 8);
1522 buffer = avio_rb64(pb);
1524 if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1525 && buffer >> 32 <= atom.size
1526 && buffer >> 32 >= 8) {
1529 } else if (!st->codec->extradata_size) {
1530 #define ALAC_EXTRADATA_SIZE 36
1531 st->codec->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1532 if (!st->codec->extradata)
1533 return AVERROR(ENOMEM);
1534 st->codec->extradata_size = ALAC_EXTRADATA_SIZE;
1535 AV_WB32(st->codec->extradata , ALAC_EXTRADATA_SIZE);
1536 AV_WB32(st->codec->extradata + 4, MKTAG('a','l','a','c'));
1537 AV_WB64(st->codec->extradata + 12, buffer);
1538 avio_read(pb, st->codec->extradata + 20, 16);
1539 avio_skip(pb, atom.size - 24);
1543 if ((ret = mov_read_default(c, pb, atom)) < 0)
1546 avio_skip(pb, atom.size);
1551 * This function reads atom content and puts data in extradata without tag
1552 * nor size unlike mov_read_extradata.
1554 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1559 if (c->fc->nb_streams < 1)
1561 st = c->fc->streams[c->fc->nb_streams-1];
1563 if ((uint64_t)atom.size > (1<<30))
1564 return AVERROR_INVALIDDATA;
1566 if (atom.size >= 10) {
1567 // Broken files created by legacy versions of libavformat will
1568 // wrap a whole fiel atom inside of a glbl atom.
1569 unsigned size = avio_rb32(pb);
1570 unsigned type = avio_rl32(pb);
1571 avio_seek(pb, -8, SEEK_CUR);
1572 if (type == MKTAG('f','i','e','l') && size == atom.size)
1573 return mov_read_default(c, pb, atom);
1575 if (st->codec->extradata_size > 1 && st->codec->extradata) {
1576 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1579 av_freep(&st->codec->extradata);
1580 ret = ff_get_extradata(st->codec, pb, atom.size);
1587 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1590 uint8_t profile_level;
1593 if (c->fc->nb_streams < 1)
1595 st = c->fc->streams[c->fc->nb_streams-1];
1597 if (atom.size >= (1<<28) || atom.size < 7)
1598 return AVERROR_INVALIDDATA;
1600 profile_level = avio_r8(pb);
1601 if ((profile_level & 0xf0) != 0xc0)
1604 avio_seek(pb, 6, SEEK_CUR);
1605 av_freep(&st->codec->extradata);
1606 ret = ff_get_extradata(st->codec, pb, atom.size - 7);
1614 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1615 * but can have extradata appended at the end after the 40 bytes belonging
1618 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1623 if (c->fc->nb_streams < 1)
1625 if (atom.size <= 40)
1627 st = c->fc->streams[c->fc->nb_streams-1];
1629 if ((uint64_t)atom.size > (1<<30))
1630 return AVERROR_INVALIDDATA;
1633 av_freep(&st->codec->extradata);
1634 ret = ff_get_extradata(st->codec, pb, atom.size - 40);
1641 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1644 MOVStreamContext *sc;
1645 unsigned int i, entries;
1647 if (c->fc->nb_streams < 1)
1649 st = c->fc->streams[c->fc->nb_streams-1];
1652 avio_r8(pb); /* version */
1653 avio_rb24(pb); /* flags */
1655 entries = avio_rb32(pb);
1660 if (sc->chunk_offsets)
1661 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1662 av_free(sc->chunk_offsets);
1663 sc->chunk_count = 0;
1664 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1665 if (!sc->chunk_offsets)
1666 return AVERROR(ENOMEM);
1667 sc->chunk_count = entries;
1669 if (atom.type == MKTAG('s','t','c','o'))
1670 for (i = 0; i < entries && !pb->eof_reached; i++)
1671 sc->chunk_offsets[i] = avio_rb32(pb);
1672 else if (atom.type == MKTAG('c','o','6','4'))
1673 for (i = 0; i < entries && !pb->eof_reached; i++)
1674 sc->chunk_offsets[i] = avio_rb64(pb);
1676 return AVERROR_INVALIDDATA;
1678 sc->chunk_count = i;
1680 if (pb->eof_reached)
1687 * Compute codec id for 'lpcm' tag.
1688 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1690 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1697 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1700 static int mov_codec_id(AVStream *st, uint32_t format)
1702 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1705 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1706 (format & 0xFFFF) == 'T' + ('S' << 8)))
1707 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1709 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1710 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1711 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1712 /* skip old asf mpeg4 tag */
1713 format && format != MKTAG('m','p','4','s')) {
1714 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1716 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1718 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1719 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1720 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1721 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1722 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1724 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1728 st->codec->codec_tag = format;
1733 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1734 AVStream *st, MOVStreamContext *sc)
1736 uint8_t codec_name[32];
1737 unsigned int color_depth, len, j;
1738 int color_greyscale;
1741 avio_rb16(pb); /* version */
1742 avio_rb16(pb); /* revision level */
1743 avio_rb32(pb); /* vendor */
1744 avio_rb32(pb); /* temporal quality */
1745 avio_rb32(pb); /* spatial quality */
1747 st->codec->width = avio_rb16(pb); /* width */
1748 st->codec->height = avio_rb16(pb); /* height */
1750 avio_rb32(pb); /* horiz resolution */
1751 avio_rb32(pb); /* vert resolution */
1752 avio_rb32(pb); /* data size, always 0 */
1753 avio_rb16(pb); /* frames per samples */
1755 len = avio_r8(pb); /* codec name, pascal string */
1758 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1760 avio_skip(pb, 31 - len);
1763 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1765 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1766 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1767 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1768 st->codec->width &= ~1;
1769 st->codec->height &= ~1;
1771 /* Flash Media Server uses tag H263 with Sorenson Spark */
1772 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1773 !memcmp(codec_name, "Sorenson H263", 13))
1774 st->codec->codec_id = AV_CODEC_ID_FLV1;
1776 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1777 color_table_id = avio_rb16(pb); /* colortable id */
1778 av_log(c->fc, AV_LOG_TRACE, "depth %d, ctab id %d\n",
1779 st->codec->bits_per_coded_sample, color_table_id);
1780 /* figure out the palette situation */
1781 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1782 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1783 /* Do not create a greyscale palette for cinepak */
1784 if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1787 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1788 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1789 /* for palette traversal */
1790 unsigned int color_start, color_count, color_end;
1791 unsigned int a, r, g, b;
1793 if (color_greyscale) {
1794 int color_index, color_dec;
1795 /* compute the greyscale palette */
1796 st->codec->bits_per_coded_sample = color_depth;
1797 color_count = 1 << color_depth;
1799 color_dec = 256 / (color_count - 1);
1800 for (j = 0; j < color_count; j++) {
1801 r = g = b = color_index;
1802 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1803 color_index -= color_dec;
1804 if (color_index < 0)
1807 } else if (color_table_id) {
1808 const uint8_t *color_table;
1809 /* if flag bit 3 is set, use the default palette */
1810 color_count = 1 << color_depth;
1811 if (color_depth == 2)
1812 color_table = ff_qt_default_palette_4;
1813 else if (color_depth == 4)
1814 color_table = ff_qt_default_palette_16;
1816 color_table = ff_qt_default_palette_256;
1818 for (j = 0; j < color_count; j++) {
1819 r = color_table[j * 3 + 0];
1820 g = color_table[j * 3 + 1];
1821 b = color_table[j * 3 + 2];
1822 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1825 /* load the palette from the file */
1826 color_start = avio_rb32(pb);
1827 color_count = avio_rb16(pb);
1828 color_end = avio_rb16(pb);
1829 if ((color_start <= 255) && (color_end <= 255)) {
1830 for (j = color_start; j <= color_end; j++) {
1831 /* each A, R, G, or B component is 16 bits;
1832 * only use the top 8 bits */
1841 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1845 sc->has_palette = 1;
1849 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1850 AVStream *st, MOVStreamContext *sc)
1852 int bits_per_sample, flags;
1853 uint16_t version = avio_rb16(pb);
1854 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1856 avio_rb16(pb); /* revision level */
1857 avio_rb32(pb); /* vendor */
1859 st->codec->channels = avio_rb16(pb); /* channel count */
1860 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1861 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codec->channels);
1863 sc->audio_cid = avio_rb16(pb);
1864 avio_rb16(pb); /* packet size = 0 */
1866 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1868 // Read QT version 1 fields. In version 0 these do not exist.
1869 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1871 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1874 sc->samples_per_frame = avio_rb32(pb);
1875 avio_rb32(pb); /* bytes per packet */
1876 sc->bytes_per_frame = avio_rb32(pb);
1877 avio_rb32(pb); /* bytes per sample */
1878 } else if (version == 2) {
1879 avio_rb32(pb); /* sizeof struct only */
1880 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1881 st->codec->channels = avio_rb32(pb);
1882 avio_rb32(pb); /* always 0x7F000000 */
1883 st->codec->bits_per_coded_sample = avio_rb32(pb);
1885 flags = avio_rb32(pb); /* lpcm format specific flag */
1886 sc->bytes_per_frame = avio_rb32(pb);
1887 sc->samples_per_frame = avio_rb32(pb);
1888 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1889 st->codec->codec_id =
1890 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1893 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1894 /* can't correctly handle variable sized packet as audio unit */
1895 switch (st->codec->codec_id) {
1896 case AV_CODEC_ID_MP2:
1897 case AV_CODEC_ID_MP3:
1898 st->need_parsing = AVSTREAM_PARSE_FULL;
1904 switch (st->codec->codec_id) {
1905 case AV_CODEC_ID_PCM_S8:
1906 case AV_CODEC_ID_PCM_U8:
1907 if (st->codec->bits_per_coded_sample == 16)
1908 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1910 case AV_CODEC_ID_PCM_S16LE:
1911 case AV_CODEC_ID_PCM_S16BE:
1912 if (st->codec->bits_per_coded_sample == 8)
1913 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1914 else if (st->codec->bits_per_coded_sample == 24)
1915 st->codec->codec_id =
1916 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1917 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1918 else if (st->codec->bits_per_coded_sample == 32)
1919 st->codec->codec_id =
1920 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1921 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1923 /* set values for old format before stsd version 1 appeared */
1924 case AV_CODEC_ID_MACE3:
1925 sc->samples_per_frame = 6;
1926 sc->bytes_per_frame = 2 * st->codec->channels;
1928 case AV_CODEC_ID_MACE6:
1929 sc->samples_per_frame = 6;
1930 sc->bytes_per_frame = 1 * st->codec->channels;
1932 case AV_CODEC_ID_ADPCM_IMA_QT:
1933 sc->samples_per_frame = 64;
1934 sc->bytes_per_frame = 34 * st->codec->channels;
1936 case AV_CODEC_ID_GSM:
1937 sc->samples_per_frame = 160;
1938 sc->bytes_per_frame = 33;
1944 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1945 if (bits_per_sample) {
1946 st->codec->bits_per_coded_sample = bits_per_sample;
1947 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1951 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1952 AVStream *st, MOVStreamContext *sc,
1955 // ttxt stsd contains display flags, justification, background
1956 // color, fonts, and default styles, so fake an atom to read it
1957 MOVAtom fake_atom = { .size = size };
1958 // mp4s contains a regular esds atom
1959 if (st->codec->codec_tag != AV_RL32("mp4s"))
1960 mov_read_glbl(c, pb, fake_atom);
1961 st->codec->width = sc->width;
1962 st->codec->height = sc->height;
1965 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1970 y = (ycbcr >> 16) & 0xFF;
1971 cr = (ycbcr >> 8) & 0xFF;
1974 b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
1975 g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
1976 r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
1978 return (r << 16) | (g << 8) | b;
1981 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1983 char buf[256] = {0};
1984 uint8_t *src = st->codec->extradata;
1987 if (st->codec->extradata_size != 64)
1990 if (st->codec->width > 0 && st->codec->height > 0)
1991 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1992 st->codec->width, st->codec->height);
1993 av_strlcat(buf, "palette: ", sizeof(buf));
1995 for (i = 0; i < 16; i++) {
1996 uint32_t yuv = AV_RB32(src + i * 4);
1997 uint32_t rgba = yuv_to_rgba(yuv);
1999 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2002 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2005 av_freep(&st->codec->extradata);
2006 st->codec->extradata_size = 0;
2007 st->codec->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
2008 if (!st->codec->extradata)
2009 return AVERROR(ENOMEM);
2010 st->codec->extradata_size = strlen(buf);
2011 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
2016 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2017 AVStream *st, MOVStreamContext *sc,
2022 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
2023 if ((int)size != size)
2024 return AVERROR(ENOMEM);
2026 ret = ff_get_extradata(st->codec, pb, size);
2030 MOVStreamContext *tmcd_ctx = st->priv_data;
2032 val = AV_RB32(st->codec->extradata + 4);
2033 tmcd_ctx->tmcd_flags = val;
2035 st->codec->flags2 |= AV_CODEC_FLAG2_DROP_FRAME_TIMECODE;
2036 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
2037 st->codec->time_base.num = 1;
2038 /* adjust for per frame dur in counter mode */
2039 if (tmcd_ctx->tmcd_flags & 0x0008) {
2040 int timescale = AV_RB32(st->codec->extradata + 8);
2041 int framedur = AV_RB32(st->codec->extradata + 12);
2042 st->codec->time_base.den *= timescale;
2043 st->codec->time_base.num *= framedur;
2046 uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
2047 uint32_t format = AV_RB32(st->codec->extradata + 22);
2048 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2049 uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
2050 if (str_size > 0 && size >= (int)str_size + 26) {
2051 char *reel_name = av_malloc(str_size + 1);
2053 return AVERROR(ENOMEM);
2054 memcpy(reel_name, st->codec->extradata + 30, str_size);
2055 reel_name[str_size] = 0; /* Add null terminator */
2056 /* don't add reel_name if emtpy string */
2057 if (*reel_name == 0) {
2060 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2067 /* other codec type, just skip (rtp, mp4s ...) */
2068 avio_skip(pb, size);
2073 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2074 AVStream *st, MOVStreamContext *sc)
2076 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2077 !st->codec->sample_rate && sc->time_scale > 1)
2078 st->codec->sample_rate = sc->time_scale;
2080 /* special codec parameters handling */
2081 switch (st->codec->codec_id) {
2082 #if CONFIG_DV_DEMUXER
2083 case AV_CODEC_ID_DVAUDIO:
2084 c->dv_fctx = avformat_alloc_context();
2086 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2087 return AVERROR(ENOMEM);
2089 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2091 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2092 return AVERROR(ENOMEM);
2094 sc->dv_audio_container = 1;
2095 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
2098 /* no ifdef since parameters are always those */
2099 case AV_CODEC_ID_QCELP:
2100 st->codec->channels = 1;
2101 // force sample rate for qcelp when not stored in mov
2102 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
2103 st->codec->sample_rate = 8000;
2104 // FIXME: Why is the following needed for some files?
2105 sc->samples_per_frame = 160;
2106 if (!sc->bytes_per_frame)
2107 sc->bytes_per_frame = 35;
2109 case AV_CODEC_ID_AMR_NB:
2110 st->codec->channels = 1;
2111 /* force sample rate for amr, stsd in 3gp does not store sample rate */
2112 st->codec->sample_rate = 8000;
2114 case AV_CODEC_ID_AMR_WB:
2115 st->codec->channels = 1;
2116 st->codec->sample_rate = 16000;
2118 case AV_CODEC_ID_MP2:
2119 case AV_CODEC_ID_MP3:
2120 /* force type after stsd for m1a hdlr */
2121 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
2123 case AV_CODEC_ID_GSM:
2124 case AV_CODEC_ID_ADPCM_MS:
2125 case AV_CODEC_ID_ADPCM_IMA_WAV:
2126 case AV_CODEC_ID_ILBC:
2127 case AV_CODEC_ID_MACE3:
2128 case AV_CODEC_ID_MACE6:
2129 case AV_CODEC_ID_QDM2:
2130 st->codec->block_align = sc->bytes_per_frame;
2132 case AV_CODEC_ID_ALAC:
2133 if (st->codec->extradata_size == 36) {
2134 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
2135 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
2138 case AV_CODEC_ID_AC3:
2139 case AV_CODEC_ID_EAC3:
2140 case AV_CODEC_ID_MPEG1VIDEO:
2141 case AV_CODEC_ID_VC1:
2142 st->need_parsing = AVSTREAM_PARSE_FULL;
2150 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2151 int codec_tag, int format,
2154 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2157 (codec_tag != format &&
2158 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2159 : codec_tag != MKTAG('j','p','e','g')))) {
2160 /* Multiple fourcc, we skip JPEG. This is not correct, we should
2161 * export it as a separate AVStream but this needs a few changes
2162 * in the MOV demuxer, patch welcome. */
2164 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2165 avio_skip(pb, size);
2168 if ( codec_tag == AV_RL32("avc1") ||
2169 codec_tag == AV_RL32("hvc1") ||
2170 codec_tag == AV_RL32("hev1")
2172 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
2177 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2180 MOVStreamContext *sc;
2181 int pseudo_stream_id;
2183 if (c->fc->nb_streams < 1)
2185 st = c->fc->streams[c->fc->nb_streams-1];
2188 for (pseudo_stream_id = 0;
2189 pseudo_stream_id < entries && !pb->eof_reached;
2190 pseudo_stream_id++) {
2191 //Parsing Sample description table
2193 int ret, dref_id = 1;
2194 MOVAtom a = { AV_RL32("stsd") };
2195 int64_t start_pos = avio_tell(pb);
2196 int64_t size = avio_rb32(pb); /* size */
2197 uint32_t format = avio_rl32(pb); /* data format */
2200 avio_rb32(pb); /* reserved */
2201 avio_rb16(pb); /* reserved */
2202 dref_id = avio_rb16(pb);
2203 }else if (size <= 7){
2204 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
2205 return AVERROR_INVALIDDATA;
2208 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
2209 size - (avio_tell(pb) - start_pos)))
2212 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
2213 sc->dref_id= dref_id;
2215 id = mov_codec_id(st, format);
2217 av_log(c->fc, AV_LOG_TRACE,
2218 "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
2219 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
2220 (format >> 24) & 0xff, format, st->codec->codec_type);
2222 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
2223 st->codec->codec_id = id;
2224 mov_parse_stsd_video(c, pb, st, sc);
2225 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
2226 st->codec->codec_id = id;
2227 mov_parse_stsd_audio(c, pb, st, sc);
2228 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
2229 st->codec->codec_id = id;
2230 mov_parse_stsd_subtitle(c, pb, st, sc,
2231 size - (avio_tell(pb) - start_pos));
2233 ret = mov_parse_stsd_data(c, pb, st, sc,
2234 size - (avio_tell(pb) - start_pos));
2238 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2239 a.size = size - (avio_tell(pb) - start_pos);
2241 if ((ret = mov_read_default(c, pb, a)) < 0)
2243 } else if (a.size > 0)
2244 avio_skip(pb, a.size);
2247 if (pb->eof_reached)
2250 return mov_finalize_stsd_codec(c, pb, st, sc);
2253 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2257 avio_r8(pb); /* version */
2258 avio_rb24(pb); /* flags */
2259 entries = avio_rb32(pb);
2261 return ff_mov_read_stsd_entries(c, pb, entries);
2264 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2267 MOVStreamContext *sc;
2268 unsigned int i, entries;
2270 if (c->fc->nb_streams < 1)
2272 st = c->fc->streams[c->fc->nb_streams-1];
2275 avio_r8(pb); /* version */
2276 avio_rb24(pb); /* flags */
2278 entries = avio_rb32(pb);
2280 av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
2285 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2286 av_free(sc->stsc_data);
2288 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2290 return AVERROR(ENOMEM);
2292 for (i = 0; i < entries && !pb->eof_reached; i++) {
2293 sc->stsc_data[i].first = avio_rb32(pb);
2294 sc->stsc_data[i].count = avio_rb32(pb);
2295 sc->stsc_data[i].id = avio_rb32(pb);
2300 if (pb->eof_reached)
2306 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2309 MOVStreamContext *sc;
2310 unsigned i, entries;
2312 if (c->fc->nb_streams < 1)
2314 st = c->fc->streams[c->fc->nb_streams-1];
2317 avio_rb32(pb); // version + flags
2319 entries = avio_rb32(pb);
2321 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2322 av_free(sc->stps_data);
2324 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2326 return AVERROR(ENOMEM);
2328 for (i = 0; i < entries && !pb->eof_reached; i++) {
2329 sc->stps_data[i] = avio_rb32(pb);
2330 //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
2335 if (pb->eof_reached)
2341 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2344 MOVStreamContext *sc;
2345 unsigned int i, entries;
2347 if (c->fc->nb_streams < 1)
2349 st = c->fc->streams[c->fc->nb_streams-1];
2352 avio_r8(pb); /* version */
2353 avio_rb24(pb); /* flags */
2355 entries = avio_rb32(pb);
2357 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
2361 sc->keyframe_absent = 1;
2362 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2363 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2367 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2368 if (entries >= UINT_MAX / sizeof(int))
2369 return AVERROR_INVALIDDATA;
2370 av_freep(&sc->keyframes);
2371 sc->keyframe_count = 0;
2372 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2374 return AVERROR(ENOMEM);
2376 for (i = 0; i < entries && !pb->eof_reached; i++) {
2377 sc->keyframes[i] = avio_rb32(pb);
2378 //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
2381 sc->keyframe_count = i;
2383 if (pb->eof_reached)
2389 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2392 MOVStreamContext *sc;
2393 unsigned int i, entries, sample_size, field_size, num_bytes;
2398 if (c->fc->nb_streams < 1)
2400 st = c->fc->streams[c->fc->nb_streams-1];
2403 avio_r8(pb); /* version */
2404 avio_rb24(pb); /* flags */
2406 if (atom.type == MKTAG('s','t','s','z')) {
2407 sample_size = avio_rb32(pb);
2408 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2409 sc->sample_size = sample_size;
2410 sc->stsz_sample_size = sample_size;
2414 avio_rb24(pb); /* reserved */
2415 field_size = avio_r8(pb);
2417 entries = avio_rb32(pb);
2419 av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2421 sc->sample_count = entries;
2425 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2426 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2427 return AVERROR_INVALIDDATA;
2432 if (entries >= (UINT_MAX - 4) / field_size)
2433 return AVERROR_INVALIDDATA;
2434 if (sc->sample_sizes)
2435 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2436 av_free(sc->sample_sizes);
2437 sc->sample_count = 0;
2438 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2439 if (!sc->sample_sizes)
2440 return AVERROR(ENOMEM);
2442 num_bytes = (entries*field_size+4)>>3;
2444 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2446 av_freep(&sc->sample_sizes);
2447 return AVERROR(ENOMEM);
2450 ret = ffio_read_size(pb, buf, num_bytes);
2452 av_freep(&sc->sample_sizes);
2457 init_get_bits(&gb, buf, 8*num_bytes);
2459 for (i = 0; i < entries && !pb->eof_reached; i++) {
2460 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2461 sc->data_size += sc->sample_sizes[i];
2464 sc->sample_count = i;
2468 if (pb->eof_reached)
2474 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2477 MOVStreamContext *sc;
2478 unsigned int i, entries;
2480 int64_t total_sample_count=0;
2482 if (c->fc->nb_streams < 1)
2484 st = c->fc->streams[c->fc->nb_streams-1];
2487 avio_r8(pb); /* version */
2488 avio_rb24(pb); /* flags */
2489 entries = avio_rb32(pb);
2491 av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2492 c->fc->nb_streams-1, entries);
2495 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2496 av_free(sc->stts_data);
2498 sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2500 return AVERROR(ENOMEM);
2502 for (i = 0; i < entries && !pb->eof_reached; i++) {
2503 int sample_duration;
2506 sample_count=avio_rb32(pb);
2507 sample_duration = avio_rb32(pb);
2509 if (sample_count < 0) {
2510 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2511 return AVERROR_INVALIDDATA;
2513 sc->stts_data[i].count= sample_count;
2514 sc->stts_data[i].duration= sample_duration;
2516 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2517 sample_count, sample_duration);
2521 && sample_count == 1
2522 && total_sample_count > 100
2523 && sample_duration/10 > duration / total_sample_count)
2524 sample_duration = duration / total_sample_count;
2525 duration+=(int64_t)sample_duration*sample_count;
2526 total_sample_count+=sample_count;
2531 sc->duration_for_fps += duration;
2532 sc->nb_frames_for_fps += total_sample_count;
2534 if (pb->eof_reached)
2537 st->nb_frames= total_sample_count;
2539 st->duration= duration;
2540 sc->track_end = duration;
2544 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2547 if (duration == INT_MIN) {
2548 av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2551 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2555 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2558 MOVStreamContext *sc;
2559 unsigned int i, entries;
2561 if (c->fc->nb_streams < 1)
2563 st = c->fc->streams[c->fc->nb_streams-1];
2566 avio_r8(pb); /* version */
2567 avio_rb24(pb); /* flags */
2568 entries = avio_rb32(pb);
2570 av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2574 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2575 return AVERROR_INVALIDDATA;
2576 av_freep(&sc->ctts_data);
2577 sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2579 return AVERROR(ENOMEM);
2581 for (i = 0; i < entries && !pb->eof_reached; i++) {
2582 int count =avio_rb32(pb);
2583 int duration =avio_rb32(pb);
2585 sc->ctts_data[i].count = count;
2586 sc->ctts_data[i].duration= duration;
2588 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2591 if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2592 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2593 av_freep(&sc->ctts_data);
2599 mov_update_dts_shift(sc, duration);
2604 if (pb->eof_reached)
2607 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2612 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2615 MOVStreamContext *sc;
2616 unsigned int i, entries;
2618 uint32_t grouping_type;
2620 if (c->fc->nb_streams < 1)
2622 st = c->fc->streams[c->fc->nb_streams-1];
2625 version = avio_r8(pb); /* version */
2626 avio_rb24(pb); /* flags */
2627 grouping_type = avio_rl32(pb);
2628 if (grouping_type != MKTAG( 'r','a','p',' '))
2629 return 0; /* only support 'rap ' grouping */
2631 avio_rb32(pb); /* grouping_type_parameter */
2633 entries = avio_rb32(pb);
2637 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2638 av_free(sc->rap_group);
2639 sc->rap_group_count = 0;
2640 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2642 return AVERROR(ENOMEM);
2644 for (i = 0; i < entries && !pb->eof_reached; i++) {
2645 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2646 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2649 sc->rap_group_count = i;
2651 return pb->eof_reached ? AVERROR_EOF : 0;
2654 static void mov_build_index(MOVContext *mov, AVStream *st)
2656 MOVStreamContext *sc = st->priv_data;
2657 int64_t current_offset;
2658 int64_t current_dts = 0;
2659 unsigned int stts_index = 0;
2660 unsigned int stsc_index = 0;
2661 unsigned int stss_index = 0;
2662 unsigned int stps_index = 0;
2664 uint64_t stream_size = 0;
2666 if (sc->elst_count) {
2667 int i, edit_start_index = 0, unsupported = 0;
2668 int64_t empty_duration = 0; // empty duration of the first edit list entry
2669 int64_t start_time = 0; // start time of the media
2671 for (i = 0; i < sc->elst_count; i++) {
2672 const MOVElst *e = &sc->elst_data[i];
2673 if (i == 0 && e->time == -1) {
2674 /* if empty, the first entry is the start time of the stream
2675 * relative to the presentation itself */
2676 empty_duration = e->duration;
2677 edit_start_index = 1;
2678 } else if (i == edit_start_index && e->time >= 0) {
2679 start_time = e->time;
2684 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
2685 "a/v desync might occur, patch welcome\n");
2687 /* adjust first dts according to edit list */
2688 if ((empty_duration || start_time) && mov->time_scale > 0) {
2690 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
2691 sc->time_offset = start_time - empty_duration;
2692 current_dts = -sc->time_offset;
2693 if (sc->ctts_count>0 && sc->stts_count>0 &&
2694 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2695 /* more than 16 frames delay, dts are likely wrong
2696 this happens with files created by iMovie */
2698 st->codec->has_b_frames = 1;
2703 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2704 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2705 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2706 unsigned int current_sample = 0;
2707 unsigned int stts_sample = 0;
2708 unsigned int sample_size;
2709 unsigned int distance = 0;
2710 unsigned int rap_group_index = 0;
2711 unsigned int rap_group_sample = 0;
2712 int64_t last_dts = 0;
2713 int64_t dts_correction = 0;
2714 int rap_group_present = sc->rap_group_count && sc->rap_group;
2715 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2717 current_dts -= sc->dts_shift;
2718 last_dts = current_dts;
2720 if (!sc->sample_count || st->nb_index_entries)
2722 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2724 if (av_reallocp_array(&st->index_entries,
2725 st->nb_index_entries + sc->sample_count,
2726 sizeof(*st->index_entries)) < 0) {
2727 st->nb_index_entries = 0;
2730 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2732 for (i = 0; i < sc->chunk_count; i++) {
2733 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2734 current_offset = sc->chunk_offsets[i];
2735 while (stsc_index + 1 < sc->stsc_count &&
2736 i + 1 == sc->stsc_data[stsc_index + 1].first)
2739 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2740 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2741 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2742 sc->stsz_sample_size = sc->sample_size;
2744 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2745 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2746 sc->stsz_sample_size = sc->sample_size;
2749 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2751 if (current_sample >= sc->sample_count) {
2752 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2756 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2758 if (stss_index + 1 < sc->keyframe_count)
2760 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2762 if (stps_index + 1 < sc->stps_count)
2765 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2766 if (sc->rap_group[rap_group_index].index > 0)
2768 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2769 rap_group_sample = 0;
2773 if (sc->keyframe_absent
2775 && !rap_group_present
2776 && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2780 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2781 if (sc->pseudo_stream_id == -1 ||
2782 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2783 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2784 e->pos = current_offset;
2785 e->timestamp = current_dts;
2786 e->size = sample_size;
2787 e->min_distance = distance;
2788 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2789 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2790 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2791 current_offset, current_dts, sample_size, distance, keyframe);
2792 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2793 ff_rfps_add_frame(mov->fc, st, current_dts);
2796 current_offset += sample_size;
2797 stream_size += sample_size;
2799 /* A negative sample duration is invalid based on the spec,
2800 * but some samples need it to correct the DTS. */
2801 if (sc->stts_data[stts_index].duration < 0) {
2802 av_log(mov->fc, AV_LOG_WARNING,
2803 "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2804 sc->stts_data[stts_index].duration, stts_index,
2806 dts_correction += sc->stts_data[stts_index].duration - 1;
2807 sc->stts_data[stts_index].duration = 1;
2809 current_dts += sc->stts_data[stts_index].duration;
2810 if (!dts_correction || current_dts + dts_correction > last_dts) {
2811 current_dts += dts_correction;
2814 /* Avoid creating non-monotonous DTS */
2815 dts_correction += current_dts - last_dts - 1;
2816 current_dts = last_dts + 1;
2818 last_dts = current_dts;
2822 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2828 if (st->duration > 0)
2829 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2831 unsigned chunk_samples, total = 0;
2833 // compute total chunk count
2834 for (i = 0; i < sc->stsc_count; i++) {
2835 unsigned count, chunk_count;
2837 chunk_samples = sc->stsc_data[i].count;
2838 if (i != sc->stsc_count - 1 &&
2839 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2840 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2844 if (sc->samples_per_frame >= 160) { // gsm
2845 count = chunk_samples / sc->samples_per_frame;
2846 } else if (sc->samples_per_frame > 1) {
2847 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2848 count = (chunk_samples+samples-1) / samples;
2850 count = (chunk_samples+1023) / 1024;
2853 if (i < sc->stsc_count - 1)
2854 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2856 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2857 total += chunk_count * count;
2860 av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2861 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2863 if (av_reallocp_array(&st->index_entries,
2864 st->nb_index_entries + total,
2865 sizeof(*st->index_entries)) < 0) {
2866 st->nb_index_entries = 0;
2869 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2872 for (i = 0; i < sc->chunk_count; i++) {
2873 current_offset = sc->chunk_offsets[i];
2874 if (stsc_index + 1 < sc->stsc_count &&
2875 i + 1 == sc->stsc_data[stsc_index + 1].first)
2877 chunk_samples = sc->stsc_data[stsc_index].count;
2879 while (chunk_samples > 0) {
2881 unsigned size, samples;
2883 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2884 avpriv_request_sample(mov->fc,
2885 "Zero bytes per frame, but %d samples per frame",
2886 sc->samples_per_frame);
2890 if (sc->samples_per_frame >= 160) { // gsm
2891 samples = sc->samples_per_frame;
2892 size = sc->bytes_per_frame;
2894 if (sc->samples_per_frame > 1) {
2895 samples = FFMIN((1024 / sc->samples_per_frame)*
2896 sc->samples_per_frame, chunk_samples);
2897 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2899 samples = FFMIN(1024, chunk_samples);
2900 size = samples * sc->sample_size;
2904 if (st->nb_index_entries >= total) {
2905 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2908 e = &st->index_entries[st->nb_index_entries++];
2909 e->pos = current_offset;
2910 e->timestamp = current_dts;
2912 e->min_distance = 0;
2913 e->flags = AVINDEX_KEYFRAME;
2914 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2915 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2918 current_offset += size;
2919 current_dts += samples;
2920 chunk_samples -= samples;
2926 static int test_same_origin(const char *src, const char *ref) {
2936 av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
2937 av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
2939 if (strlen(src) == 0) {
2941 } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
2942 strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
2943 strlen(src_host) + 1 >= sizeof(src_host) ||
2944 strlen(ref_host) + 1 >= sizeof(ref_host)) {
2946 } else if (strcmp(src_proto, ref_proto) ||
2947 strcmp(src_auth, ref_auth) ||
2948 strcmp(src_host, ref_host) ||
2949 src_port != ref_port) {
2955 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref,
2956 AVIOInterruptCB *int_cb)
2958 AVOpenCallback open_func = c->fc->open_cb;
2961 open_func = ffio_open2_wrapper;
2963 /* try relative path, we do not try the absolute because it can leak information about our
2964 system to an attacker */
2965 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2966 char filename[1025];
2967 const char *src_path;
2970 /* find a source dir */
2971 src_path = strrchr(src, '/');
2977 /* find a next level down to target */
2978 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2979 if (ref->path[l] == '/') {
2980 if (i == ref->nlvl_to - 1)
2986 /* compose filename if next level down to target was found */
2987 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2988 memcpy(filename, src, src_path - src);
2989 filename[src_path - src] = 0;
2991 for (i = 1; i < ref->nlvl_from; i++)
2992 av_strlcat(filename, "../", sizeof(filename));
2994 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
2995 if (!c->use_absolute_path && !c->fc->open_cb) {
2996 int same_origin = test_same_origin(src, filename);
2999 av_log(c->fc, AV_LOG_ERROR,
3000 "Reference with mismatching origin, %s not tried for security reasons, "
3001 "set demuxer option use_absolute_path to allow it anyway\n",
3003 return AVERROR(ENOENT);
3006 if(strstr(ref->path + l + 1, "..") ||
3007 strstr(ref->path + l + 1, ":") ||
3008 (ref->nlvl_from > 1 && same_origin < 0) ||
3009 (filename[0] == '/' && src_path == src))
3010 return AVERROR(ENOENT);
3013 if (strlen(filename) + 1 == sizeof(filename))
3014 return AVERROR(ENOENT);
3015 if (!open_func(c->fc, pb, filename, AVIO_FLAG_READ, int_cb, NULL))
3018 } else if (c->use_absolute_path) {
3019 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
3020 "this is a possible security issue\n");
3021 if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
3023 } else if (c->fc->open_cb) {
3024 if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
3027 av_log(c->fc, AV_LOG_ERROR,
3028 "Absolute path %s not tried for security reasons, "
3029 "set demuxer option use_absolute_path to allow absolute paths\n",
3033 return AVERROR(ENOENT);
3036 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
3038 if (sc->time_scale <= 0) {
3039 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
3040 sc->time_scale = c->time_scale;
3041 if (sc->time_scale <= 0)
3046 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3049 MOVStreamContext *sc;
3052 st = avformat_new_stream(c->fc, NULL);
3053 if (!st) return AVERROR(ENOMEM);
3054 st->id = c->fc->nb_streams;
3055 sc = av_mallocz(sizeof(MOVStreamContext));
3056 if (!sc) return AVERROR(ENOMEM);
3059 st->codec->codec_type = AVMEDIA_TYPE_DATA;
3060 sc->ffindex = st->index;
3062 if ((ret = mov_read_default(c, pb, atom)) < 0)
3066 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
3067 (!sc->sample_size && !sc->sample_count))) {
3068 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
3073 fix_timescale(c, sc);
3075 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
3077 mov_build_index(c, st);
3079 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
3080 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
3081 if (mov_open_dref(c, &sc->pb, c->fc->filename, dref,
3082 &c->fc->interrupt_callback) < 0)
3083 av_log(c->fc, AV_LOG_ERROR,
3084 "stream %d, error opening alias: path='%s', dir='%s', "
3085 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
3086 st->index, dref->path, dref->dir, dref->filename,
3087 dref->volume, dref->nlvl_from, dref->nlvl_to);
3090 sc->pb_is_copied = 1;
3093 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3094 if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&
3095 sc->height && sc->width &&
3096 (st->codec->width != sc->width || st->codec->height != sc->height)) {
3097 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
3098 ((double)st->codec->width * sc->height), INT_MAX);
3101 #if FF_API_R_FRAME_RATE
3102 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
3103 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
3104 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
3108 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3109 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
3110 TAG_IS_AVCI(st->codec->codec_tag)) {
3111 ret = ff_generate_avci_extradata(st);
3116 switch (st->codec->codec_id) {
3117 #if CONFIG_H261_DECODER
3118 case AV_CODEC_ID_H261:
3120 #if CONFIG_H263_DECODER
3121 case AV_CODEC_ID_H263:
3123 #if CONFIG_MPEG4_DECODER
3124 case AV_CODEC_ID_MPEG4:
3126 st->codec->width = 0; /* let decoder init width/height */
3127 st->codec->height= 0;
3131 // If the duration of the mp3 packets is not constant, then they could need a parser
3132 if (st->codec->codec_id == AV_CODEC_ID_MP3
3133 && sc->stts_count > 3
3134 && sc->stts_count*10 > st->nb_frames
3135 && sc->time_scale == st->codec->sample_rate) {
3136 st->need_parsing = AVSTREAM_PARSE_FULL;
3138 /* Do not need those anymore. */
3139 av_freep(&sc->chunk_offsets);
3140 av_freep(&sc->stsc_data);
3141 av_freep(&sc->sample_sizes);
3142 av_freep(&sc->keyframes);
3143 av_freep(&sc->stts_data);
3144 av_freep(&sc->stps_data);
3145 av_freep(&sc->elst_data);
3146 av_freep(&sc->rap_group);
3151 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3154 c->itunes_metadata = 1;
3155 ret = mov_read_default(c, pb, atom);
3156 c->itunes_metadata = 0;
3160 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3169 count = avio_rb32(pb);
3170 if (count > UINT_MAX / sizeof(*c->meta_keys)) {
3171 av_log(c->fc, AV_LOG_ERROR,
3172 "The 'keys' atom with the invalid key count: %d\n", count);
3173 return AVERROR_INVALIDDATA;
3176 c->meta_keys_count = count + 1;
3177 c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
3179 return AVERROR(ENOMEM);
3181 for (i = 1; i <= count; ++i) {
3182 uint32_t key_size = avio_rb32(pb);
3183 uint32_t type = avio_rl32(pb);
3185 av_log(c->fc, AV_LOG_ERROR,
3186 "The key# %d in meta has invalid size: %d\n", i, key_size);
3187 return AVERROR_INVALIDDATA;
3190 if (type != MKTAG('m','d','t','a')) {
3191 avio_skip(pb, key_size);
3193 c->meta_keys[i] = av_mallocz(key_size + 1);
3194 if (!c->meta_keys[i])
3195 return AVERROR(ENOMEM);
3196 avio_read(pb, c->meta_keys[i], key_size);
3202 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
3204 int64_t end = avio_tell(pb) + size;
3205 uint8_t *key = NULL, *val = NULL;
3208 MOVStreamContext *sc;
3210 if (c->fc->nb_streams < 1)
3212 st = c->fc->streams[c->fc->nb_streams-1];
3215 for (i = 0; i < 2; i++) {
3220 if (end - avio_tell(pb) <= 12)
3223 len = avio_rb32(pb);
3224 tag = avio_rl32(pb);
3225 avio_skip(pb, 4); // flags
3227 if (len < 12 || len - 12 > end - avio_tell(pb))
3231 if (tag == MKTAG('n', 'a', 'm', 'e'))
3233 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
3240 *p = av_malloc(len + 1);
3243 ret = ffio_read_size(pb, *p, len);
3252 if (strcmp(key, "iTunSMPB") == 0) {
3253 int priming, remainder, samples;
3254 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
3255 if(priming>0 && priming<16384)
3256 sc->start_pad = priming;
3259 if (strcmp(key, "cdec") != 0) {
3260 av_dict_set(&c->fc->metadata, key, val,
3261 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
3266 avio_seek(pb, end, SEEK_SET);
3272 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3274 int64_t end = avio_tell(pb) + atom.size;
3280 len = avio_rb32(pb);
3281 tag = avio_rl32(pb);
3283 if (len > atom.size)
3286 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
3287 uint8_t domain[128];
3290 avio_skip(pb, 4); // flags
3293 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
3294 avio_skip(pb, len - domain_len);
3295 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
3299 av_log(c->fc, AV_LOG_VERBOSE,
3300 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
3304 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3306 while (atom.size > 8) {
3307 uint32_t tag = avio_rl32(pb);
3309 if (tag == MKTAG('h','d','l','r')) {
3310 avio_seek(pb, -8, SEEK_CUR);
3312 return mov_read_default(c, pb, atom);
3318 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3323 int display_matrix[3][3];
3325 MOVStreamContext *sc;
3329 if (c->fc->nb_streams < 1)
3331 st = c->fc->streams[c->fc->nb_streams-1];
3334 version = avio_r8(pb);
3335 flags = avio_rb24(pb);
3336 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
3342 avio_rb32(pb); /* creation time */
3343 avio_rb32(pb); /* modification time */
3345 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
3346 avio_rb32(pb); /* reserved */
3348 /* highlevel (considering edits) duration in movie timebase */
3349 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
3350 avio_rb32(pb); /* reserved */
3351 avio_rb32(pb); /* reserved */
3353 avio_rb16(pb); /* layer */
3354 avio_rb16(pb); /* alternate group */
3355 avio_rb16(pb); /* volume */
3356 avio_rb16(pb); /* reserved */
3358 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
3359 // they're kept in fixed point format through all calculations
3360 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
3361 // side data, but the scale factor is not needed to calculate aspect ratio
3362 for (i = 0; i < 3; i++) {
3363 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
3364 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
3365 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
3368 width = avio_rb32(pb); // 16.16 fixed point track width
3369 height = avio_rb32(pb); // 16.16 fixed point track height
3370 sc->width = width >> 16;
3371 sc->height = height >> 16;
3373 // save the matrix and add rotate metadata when it is not the default
3375 if (display_matrix[0][0] != (1 << 16) ||
3376 display_matrix[1][1] != (1 << 16) ||
3377 display_matrix[2][2] != (1 << 30) ||
3378 display_matrix[0][1] || display_matrix[0][2] ||
3379 display_matrix[1][0] || display_matrix[1][2] ||
3380 display_matrix[2][0] || display_matrix[2][1]) {
3384 av_freep(&sc->display_matrix);
3385 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
3386 if (!sc->display_matrix)
3387 return AVERROR(ENOMEM);
3389 for (i = 0; i < 3; i++)
3390 for (j = 0; j < 3; j++)
3391 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
3393 rotate = av_display_rotation_get(sc->display_matrix);
3394 if (!isnan(rotate)) {
3395 char rotate_buf[64];
3397 if (rotate < 0) // for backward compatibility
3399 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
3400 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
3404 // transform the display width/height according to the matrix
3405 // to keep the same scale, use [width height 1<<16]
3406 if (width && height && sc->display_matrix) {
3407 double disp_transform[2];
3409 #define SQR(a) ((a)*(double)(a))
3410 for (i = 0; i < 2; i++)
3411 disp_transform[i] = sqrt(SQR(display_matrix[i][0]) + SQR(display_matrix[i][1]));
3413 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
3414 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
3415 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
3416 st->sample_aspect_ratio = av_d2q(
3417 disp_transform[0] / disp_transform[1],
3423 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3425 MOVFragment *frag = &c->fragment;
3426 MOVTrackExt *trex = NULL;
3427 MOVFragmentIndex* index = NULL;
3428 int flags, track_id, i, found = 0;
3430 avio_r8(pb); /* version */
3431 flags = avio_rb24(pb);
3433 track_id = avio_rb32(pb);
3435 return AVERROR_INVALIDDATA;
3436 frag->track_id = track_id;
3437 for (i = 0; i < c->trex_count; i++)
3438 if (c->trex_data[i].track_id == frag->track_id) {
3439 trex = &c->trex_data[i];
3443 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
3444 return AVERROR_INVALIDDATA;
3447 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
3448 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
3449 frag->moof_offset : frag->implicit_offset;
3450 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
3452 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
3453 avio_rb32(pb) : trex->duration;
3454 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
3455 avio_rb32(pb) : trex->size;
3456 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
3457 avio_rb32(pb) : trex->flags;
3458 frag->time = AV_NOPTS_VALUE;
3459 for (i = 0; i < c->fragment_index_count; i++) {
3461 MOVFragmentIndex* candidate = c->fragment_index_data[i];
3462 if (candidate->track_id == frag->track_id) {
3463 av_log(c->fc, AV_LOG_DEBUG,
3464 "found fragment index for track %u\n", frag->track_id);
3466 for (j = index->current_item; j < index->item_count; j++) {
3467 if (frag->implicit_offset == index->items[j].moof_offset) {
3468 av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
3469 "for track %u and moof_offset %"PRId64"\n",
3470 frag->track_id, index->items[j].moof_offset);
3471 frag->time = index->items[j].time;
3472 index->current_item = j + 1;
3481 if (index && !found) {
3482 av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
3483 "it doesn't have an (in-order) entry for moof_offset "
3484 "%"PRId64"\n", frag->track_id, frag->implicit_offset);
3486 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
3490 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3492 c->chapter_track = avio_rb32(pb);
3496 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3501 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
3502 return AVERROR_INVALIDDATA;
3503 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
3504 sizeof(*c->trex_data))) < 0) {
3509 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
3511 trex = &c->trex_data[c->trex_count++];
3512 avio_r8(pb); /* version */
3513 avio_rb24(pb); /* flags */
3514 trex->track_id = avio_rb32(pb);
3515 trex->stsd_id = avio_rb32(pb);
3516 trex->duration = avio_rb32(pb);
3517 trex->size = avio_rb32(pb);
3518 trex->flags = avio_rb32(pb);
3522 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3524 MOVFragment *frag = &c->fragment;
3525 AVStream *st = NULL;
3526 MOVStreamContext *sc;
3529 for (i = 0; i < c->fc->nb_streams; i++) {
3530 if (c->fc->streams[i]->id == frag->track_id) {
3531 st = c->fc->streams[i];
3536 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3537 return AVERROR_INVALIDDATA;
3540 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
3542 version = avio_r8(pb);
3543 avio_rb24(pb); /* flags */
3545 sc->track_end = avio_rb64(pb);
3547 sc->track_end = avio_rb32(pb);
3552 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3554 MOVFragment *frag = &c->fragment;
3555 AVStream *st = NULL;
3556 MOVStreamContext *sc;
3560 int data_offset = 0;
3561 unsigned entries, first_sample_flags = frag->flags;
3562 int flags, distance, i, err;
3564 for (i = 0; i < c->fc->nb_streams; i++) {
3565 if (c->fc->streams[i]->id == frag->track_id) {
3566 st = c->fc->streams[i];
3571 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3572 return AVERROR_INVALIDDATA;
3575 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3577 avio_r8(pb); /* version */
3578 flags = avio_rb24(pb);
3579 entries = avio_rb32(pb);
3580 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
3582 /* Always assume the presence of composition time offsets.
3583 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3584 * 1) in the initial movie, there are no samples.
3585 * 2) in the first movie fragment, there is only one sample without composition time offset.
3586 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
3587 if (!sc->ctts_count && sc->sample_count)
3589 /* Complement ctts table if moov atom doesn't have ctts atom. */
3590 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3592 return AVERROR(ENOMEM);
3593 sc->ctts_data = ctts_data;
3594 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3595 sc->ctts_data[sc->ctts_count].duration = 0;
3598 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3599 return AVERROR_INVALIDDATA;
3600 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3601 sizeof(*sc->ctts_data))) < 0) {
3605 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
3606 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3607 dts = sc->track_end - sc->time_offset;
3608 offset = frag->base_data_offset + data_offset;
3610 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3611 for (i = 0; i < entries && !pb->eof_reached; i++) {
3612 unsigned sample_size = frag->size;
3613 int sample_flags = i ? frag->flags : first_sample_flags;
3614 unsigned sample_duration = frag->duration;
3617 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3618 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
3619 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
3620 sc->ctts_data[sc->ctts_count].count = 1;
3621 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3623 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
3624 if (frag->time != AV_NOPTS_VALUE) {
3625 if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3626 int64_t pts = frag->time;
3627 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3628 " sc->dts_shift %d ctts.duration %d"
3629 " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3630 sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3631 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3632 dts = pts - sc->dts_shift;
3633 if (flags & MOV_TRUN_SAMPLE_CTS) {
3634 dts -= sc->ctts_data[sc->ctts_count].duration;
3636 dts -= sc->time_offset;
3638 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3641 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3642 ", using it for dts\n", dts);
3644 frag->time = AV_NOPTS_VALUE;
3647 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3651 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3652 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3655 err = av_add_index_entry(st, offset, dts, sample_size, distance,
3656 keyframe ? AVINDEX_KEYFRAME : 0);
3658 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
3660 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3661 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3662 offset, dts, sample_size, distance, keyframe);
3664 dts += sample_duration;
3665 offset += sample_size;
3666 sc->data_size += sample_size;
3667 sc->duration_for_fps += sample_duration;
3668 sc->nb_frames_for_fps ++;
3671 if (pb->eof_reached)
3674 frag->implicit_offset = offset;
3676 sc->track_end = dts + sc->time_offset;
3677 if (st->duration < sc->track_end)
3678 st->duration = sc->track_end;
3683 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3685 int64_t offset = avio_tell(pb) + atom.size, pts;
3687 unsigned i, track_id;
3688 AVStream *st = NULL;
3689 MOVStreamContext *sc;
3690 MOVFragmentIndex *index = NULL;
3691 MOVFragmentIndex **tmp;
3692 AVRational timescale;
3694 version = avio_r8(pb);
3696 avpriv_request_sample(c->fc, "sidx version %u", version);
3697 return AVERROR_PATCHWELCOME;
3700 avio_rb24(pb); // flags
3702 track_id = avio_rb32(pb); // Reference ID
3703 for (i = 0; i < c->fc->nb_streams; i++) {
3704 if (c->fc->streams[i]->id == track_id) {
3705 st = c->fc->streams[i];
3710 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", track_id);
3711 return AVERROR_INVALIDDATA;
3716 timescale = av_make_q(1, avio_rb32(pb));
3719 pts = avio_rb32(pb);
3720 offset += avio_rb32(pb);
3722 pts = avio_rb64(pb);
3723 offset += avio_rb64(pb);
3726 avio_rb16(pb); // reserved
3728 index = av_mallocz(sizeof(MOVFragmentIndex));
3730 return AVERROR(ENOMEM);
3732 index->track_id = track_id;
3734 index->item_count = avio_rb16(pb);
3735 index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
3737 if (!index->items) {
3739 return AVERROR(ENOMEM);
3742 for (i = 0; i < index->item_count; i++) {
3743 uint32_t size = avio_rb32(pb);
3744 uint32_t duration = avio_rb32(pb);
3745 if (size & 0x80000000) {
3746 avpriv_request_sample(c->fc, "sidx reference_type 1");
3747 av_freep(&index->items);
3749 return AVERROR_PATCHWELCOME;
3751 avio_rb32(pb); // sap_flags
3752 index->items[i].moof_offset = offset;
3753 index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
3758 st->duration = sc->track_end = pts;
3760 tmp = av_realloc_array(c->fragment_index_data,
3761 c->fragment_index_count + 1,
3762 sizeof(MOVFragmentIndex*));
3764 av_freep(&index->items);
3766 return AVERROR(ENOMEM);
3769 c->fragment_index_data = tmp;
3770 c->fragment_index_data[c->fragment_index_count++] = index;
3772 if (offset == avio_size(pb))
3773 c->fragment_index_complete = 1;
3778 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3779 /* like the files created with Adobe Premiere 5.0, for samples see */
3780 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3781 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3786 return 0; /* continue */
3787 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3788 avio_skip(pb, atom.size - 4);
3791 atom.type = avio_rl32(pb);
3793 if (atom.type != MKTAG('m','d','a','t')) {
3794 avio_skip(pb, atom.size);
3797 err = mov_read_mdat(c, pb, atom);
3801 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3806 uint8_t *moov_data; /* uncompressed data */
3807 long cmov_len, moov_len;
3810 avio_rb32(pb); /* dcom atom */
3811 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3812 return AVERROR_INVALIDDATA;
3813 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3814 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3815 return AVERROR_INVALIDDATA;
3817 avio_rb32(pb); /* cmvd atom */
3818 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3819 return AVERROR_INVALIDDATA;
3820 moov_len = avio_rb32(pb); /* uncompressed size */
3821 cmov_len = atom.size - 6 * 4;
3823 cmov_data = av_malloc(cmov_len);
3825 return AVERROR(ENOMEM);
3826 moov_data = av_malloc(moov_len);
3829 return AVERROR(ENOMEM);
3831 ret = ffio_read_size(pb, cmov_data, cmov_len);
3833 goto free_and_return;
3835 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3836 goto free_and_return;
3837 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3838 goto free_and_return;
3839 ctx.seekable = AVIO_SEEKABLE_NORMAL;
3840 atom.type = MKTAG('m','o','o','v');
3841 atom.size = moov_len;
3842 ret = mov_read_default(c, &ctx, atom);
3848 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3849 return AVERROR(ENOSYS);
3853 /* edit list atom */
3854 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3856 MOVStreamContext *sc;
3857 int i, edit_count, version;
3859 if (c->fc->nb_streams < 1 || c->ignore_editlist)
3861 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3863 version = avio_r8(pb); /* version */
3864 avio_rb24(pb); /* flags */
3865 edit_count = avio_rb32(pb); /* entries */
3870 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
3871 av_free(sc->elst_data);
3873 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
3875 return AVERROR(ENOMEM);
3877 av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3878 for (i = 0; i < edit_count && !pb->eof_reached; i++) {
3879 MOVElst *e = &sc->elst_data[i];
3882 e->duration = avio_rb64(pb);
3883 e->time = avio_rb64(pb);
3885 e->duration = avio_rb32(pb); /* segment duration */
3886 e->time = (int32_t)avio_rb32(pb); /* media time */
3888 e->rate = avio_rb32(pb) / 65536.0;
3889 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3890 e->duration, e->time, e->rate);
3897 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3899 MOVStreamContext *sc;
3901 if (c->fc->nb_streams < 1)
3902 return AVERROR_INVALIDDATA;
3903 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3904 sc->timecode_track = avio_rb32(pb);
3908 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3912 static const uint8_t uuid_isml_manifest[] = {
3913 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3914 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3917 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3918 return AVERROR_INVALIDDATA;
3920 ret = avio_read(pb, uuid, sizeof(uuid));
3923 } else if (ret != sizeof(uuid)) {
3924 return AVERROR_INVALIDDATA;
3926 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3927 uint8_t *buffer, *ptr;
3929 size_t len = atom.size - sizeof(uuid);
3932 return AVERROR_INVALIDDATA;
3934 ret = avio_skip(pb, 4); // zeroes
3937 buffer = av_mallocz(len + 1);
3939 return AVERROR(ENOMEM);
3941 ret = avio_read(pb, buffer, len);
3945 } else if (ret != len) {
3947 return AVERROR_INVALIDDATA;
3951 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
3952 ptr += sizeof("systemBitrate=\"") - 1;
3953 c->bitrates_count++;
3954 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3956 c->bitrates_count = 0;
3958 return AVERROR(ENOMEM);
3961 ret = strtol(ptr, &endptr, 10);
3962 if (ret < 0 || errno || *endptr != '"') {
3963 c->bitrates[c->bitrates_count - 1] = 0;
3965 c->bitrates[c->bitrates_count - 1] = ret;
3974 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3977 uint8_t content[16];
3982 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
3988 && !memcmp(content, "Anevia\x1A\x1A", 8)
3989 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
3990 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
3996 static const MOVParseTableEntry mov_default_parse_table[] = {
3997 { MKTAG('A','C','L','R'), mov_read_aclr },
3998 { MKTAG('A','P','R','G'), mov_read_avid },
3999 { MKTAG('A','A','L','P'), mov_read_avid },
4000 { MKTAG('A','R','E','S'), mov_read_ares },
4001 { MKTAG('a','v','s','s'), mov_read_avss },
4002 { MKTAG('c','h','p','l'), mov_read_chpl },
4003 { MKTAG('c','o','6','4'), mov_read_stco },
4004 { MKTAG('c','o','l','r'), mov_read_colr },
4005 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
4006 { MKTAG('d','i','n','f'), mov_read_default },
4007 { MKTAG('D','p','x','E'), mov_read_dpxe },
4008 { MKTAG('d','r','e','f'), mov_read_dref },
4009 { MKTAG('e','d','t','s'), mov_read_default },
4010 { MKTAG('e','l','s','t'), mov_read_elst },
4011 { MKTAG('e','n','d','a'), mov_read_enda },
4012 { MKTAG('f','i','e','l'), mov_read_fiel },
4013 { MKTAG('a','d','r','m'), mov_read_adrm },
4014 { MKTAG('f','t','y','p'), mov_read_ftyp },
4015 { MKTAG('g','l','b','l'), mov_read_glbl },
4016 { MKTAG('h','d','l','r'), mov_read_hdlr },
4017 { MKTAG('i','l','s','t'), mov_read_ilst },
4018 { MKTAG('j','p','2','h'), mov_read_jp2h },
4019 { MKTAG('m','d','a','t'), mov_read_mdat },
4020 { MKTAG('m','d','h','d'), mov_read_mdhd },
4021 { MKTAG('m','d','i','a'), mov_read_default },
4022 { MKTAG('m','e','t','a'), mov_read_meta },
4023 { MKTAG('m','i','n','f'), mov_read_default },
4024 { MKTAG('m','o','o','f'), mov_read_moof },
4025 { MKTAG('m','o','o','v'), mov_read_moov },
4026 { MKTAG('m','v','e','x'), mov_read_default },
4027 { MKTAG('m','v','h','d'), mov_read_mvhd },
4028 { MKTAG('S','M','I',' '), mov_read_svq3 },
4029 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
4030 { MKTAG('a','v','c','C'), mov_read_glbl },
4031 { MKTAG('p','a','s','p'), mov_read_pasp },
4032 { MKTAG('s','i','d','x'), mov_read_sidx },
4033 { MKTAG('s','t','b','l'), mov_read_default },
4034 { MKTAG('s','t','c','o'), mov_read_stco },
4035 { MKTAG('s','t','p','s'), mov_read_stps },
4036 { MKTAG('s','t','r','f'), mov_read_strf },
4037 { MKTAG('s','t','s','c'), mov_read_stsc },
4038 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
4039 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
4040 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
4041 { MKTAG('s','t','t','s'), mov_read_stts },
4042 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
4043 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
4044 { MKTAG('t','f','d','t'), mov_read_tfdt },
4045 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
4046 { MKTAG('t','r','a','k'), mov_read_trak },
4047 { MKTAG('t','r','a','f'), mov_read_default },
4048 { MKTAG('t','r','e','f'), mov_read_default },
4049 { MKTAG('t','m','c','d'), mov_read_tmcd },
4050 { MKTAG('c','h','a','p'), mov_read_chap },
4051 { MKTAG('t','r','e','x'), mov_read_trex },
4052 { MKTAG('t','r','u','n'), mov_read_trun },
4053 { MKTAG('u','d','t','a'), mov_read_default },
4054 { MKTAG('w','a','v','e'), mov_read_wave },
4055 { MKTAG('e','s','d','s'), mov_read_esds },
4056 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
4057 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
4058 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
4059 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
4060 { MKTAG('w','f','e','x'), mov_read_wfex },
4061 { MKTAG('c','m','o','v'), mov_read_cmov },
4062 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
4063 { MKTAG('d','v','c','1'), mov_read_dvc1 },
4064 { MKTAG('s','b','g','p'), mov_read_sbgp },
4065 { MKTAG('h','v','c','C'), mov_read_glbl },
4066 { MKTAG('u','u','i','d'), mov_read_uuid },
4067 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
4068 { MKTAG('f','r','e','e'), mov_read_free },
4069 { MKTAG('-','-','-','-'), mov_read_custom },
4073 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4075 int64_t total_size = 0;
4079 if (c->atom_depth > 10) {
4080 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
4081 return AVERROR_INVALIDDATA;
4086 atom.size = INT64_MAX;
4087 while (total_size + 8 <= atom.size && !avio_feof(pb)) {
4088 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
4091 if (atom.size >= 8) {
4092 a.size = avio_rb32(pb);
4093 a.type = avio_rl32(pb);
4094 if (a.type == MKTAG('f','r','e','e') &&
4098 uint32_t *type = (uint32_t *)buf + 1;
4099 if (avio_read(pb, buf, 8) != 8)
4100 return AVERROR_INVALIDDATA;
4101 avio_seek(pb, -8, SEEK_CUR);
4102 if (*type == MKTAG('m','v','h','d') ||
4103 *type == MKTAG('c','m','o','v')) {
4104 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
4105 a.type = MKTAG('m','o','o','v');
4108 if (atom.type != MKTAG('r','o','o','t') &&
4109 atom.type != MKTAG('m','o','o','v'))
4111 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
4113 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
4120 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
4121 a.size = avio_rb64(pb) - 8;
4125 av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
4126 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
4128 a.size = atom.size - total_size + 8;
4133 a.size = FFMIN(a.size, atom.size - total_size);
4135 for (i = 0; mov_default_parse_table[i].type; i++)
4136 if (mov_default_parse_table[i].type == a.type) {
4137 parse = mov_default_parse_table[i].parse;
4141 // container is user data
4142 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
4143 atom.type == MKTAG('i','l','s','t')))
4144 parse = mov_read_udta_string;
4146 // Supports parsing the QuickTime Metadata Keys.
4147 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
4148 if (!parse && c->found_hdlr_mdta &&
4149 atom.type == MKTAG('m','e','t','a') &&
4150 a.type == MKTAG('k','e','y','s')) {
4151 parse = mov_read_keys;
4154 if (!parse) { /* skip leaf atoms data */
4155 avio_skip(pb, a.size);
4157 int64_t start_pos = avio_tell(pb);
4159 int err = parse(c, pb, a);
4164 if (c->found_moov && c->found_mdat &&
4165 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
4166 start_pos + a.size == avio_size(pb))) {
4167 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
4168 c->next_root_atom = start_pos + a.size;
4172 left = a.size - avio_tell(pb) + start_pos;
4173 if (left > 0) /* skip garbage at atom end */
4174 avio_skip(pb, left);
4175 else if (left < 0) {
4176 av_log(c->fc, AV_LOG_WARNING,
4177 "overread end of atom '%.4s' by %"PRId64" bytes\n",
4178 (char*)&a.type, -left);
4179 avio_seek(pb, left, SEEK_CUR);
4183 total_size += a.size;
4186 if (total_size < atom.size && atom.size < 0x7ffff)
4187 avio_skip(pb, atom.size - total_size);
4193 static int mov_probe(AVProbeData *p)
4198 int moov_offset = -1;
4200 /* check file header */
4203 /* ignore invalid offset */
4204 if ((offset + 8) > (unsigned int)p->buf_size)
4206 tag = AV_RL32(p->buf + offset + 4);
4208 /* check for obvious tags */
4209 case MKTAG('m','o','o','v'):
4210 moov_offset = offset + 4;
4211 case MKTAG('m','d','a','t'):
4212 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
4213 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
4214 case MKTAG('f','t','y','p'):
4215 if (AV_RB32(p->buf+offset) < 8 &&
4216 (AV_RB32(p->buf+offset) != 1 ||
4217 offset + 12 > (unsigned int)p->buf_size ||
4218 AV_RB64(p->buf+offset + 8) == 0)) {
4219 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4220 } else if (tag == MKTAG('f','t','y','p') &&
4221 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
4222 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
4224 score = FFMAX(score, 5);
4226 score = AVPROBE_SCORE_MAX;
4228 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4230 /* those are more common words, so rate then a bit less */
4231 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
4232 case MKTAG('w','i','d','e'):
4233 case MKTAG('f','r','e','e'):
4234 case MKTAG('j','u','n','k'):
4235 case MKTAG('p','i','c','t'):
4236 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
4237 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4239 case MKTAG(0x82,0x82,0x7f,0x7d):
4240 case MKTAG('s','k','i','p'):
4241 case MKTAG('u','u','i','d'):
4242 case MKTAG('p','r','f','l'):
4243 /* if we only find those cause probedata is too small at least rate them */
4244 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4245 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4248 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4251 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
4252 /* moov atom in the header - we should make sure that this is not a
4253 * MOV-packed MPEG-PS */
4254 offset = moov_offset;
4256 while(offset < (p->buf_size - 16)){ /* Sufficient space */
4257 /* We found an actual hdlr atom */
4258 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
4259 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
4260 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
4261 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
4262 /* We found a media handler reference atom describing an
4263 * MPEG-PS-in-MOV, return a
4264 * low score to force expanding the probe window until
4265 * mpegps_probe finds what it needs */
4276 // must be done after parsing all trak because there's no order requirement
4277 static void mov_read_chapters(AVFormatContext *s)
4279 MOVContext *mov = s->priv_data;
4280 AVStream *st = NULL;
4281 MOVStreamContext *sc;
4285 for (i = 0; i < s->nb_streams; i++)
4286 if (s->streams[i]->id == mov->chapter_track) {
4291 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
4295 st->discard = AVDISCARD_ALL;
4297 cur_pos = avio_tell(sc->pb);
4299 for (i = 0; i < st->nb_index_entries; i++) {
4300 AVIndexEntry *sample = &st->index_entries[i];
4301 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
4306 if (end < sample->timestamp) {
4307 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
4308 end = AV_NOPTS_VALUE;
4311 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4312 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
4316 // the first two bytes are the length of the title
4317 len = avio_rb16(sc->pb);
4318 if (len > sample->size-2)
4320 title_len = 2*len + 1;
4321 if (!(title = av_mallocz(title_len)))
4324 // The samples could theoretically be in any encoding if there's an encd
4325 // atom following, but in practice are only utf-8 or utf-16, distinguished
4326 // instead by the presence of a BOM
4330 ch = avio_rb16(sc->pb);
4332 avio_get_str16be(sc->pb, len, title, title_len);
4333 else if (ch == 0xfffe)
4334 avio_get_str16le(sc->pb, len, title, title_len);
4337 if (len == 1 || len == 2)
4340 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
4344 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
4348 avio_seek(sc->pb, cur_pos, SEEK_SET);
4351 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
4352 uint32_t value, int flags)
4355 char buf[AV_TIMECODE_STR_SIZE];
4356 AVRational rate = {st->codec->time_base.den,
4357 st->codec->time_base.num};
4358 int ret = av_timecode_init(&tc, rate, flags, 0, s);
4361 av_dict_set(&st->metadata, "timecode",
4362 av_timecode_make_string(&tc, buf, value), 0);
4366 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
4368 MOVStreamContext *sc = st->priv_data;
4370 int64_t cur_pos = avio_tell(sc->pb);
4373 if (!st->nb_index_entries)
4376 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
4377 value = avio_rb32(s->pb);
4379 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
4380 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
4381 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
4383 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
4384 * not the case) and thus assume "frame number format" instead of QT one.
4385 * No sample with tmcd track can be found with a QT timecode at the moment,
4386 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
4388 parse_timecode_in_framenum_format(s, st, value, flags);
4390 avio_seek(sc->pb, cur_pos, SEEK_SET);
4394 static int mov_read_close(AVFormatContext *s)
4396 MOVContext *mov = s->priv_data;
4399 for (i = 0; i < s->nb_streams; i++) {
4400 AVStream *st = s->streams[i];
4401 MOVStreamContext *sc = st->priv_data;
4406 av_freep(&sc->ctts_data);
4407 for (j = 0; j < sc->drefs_count; j++) {
4408 av_freep(&sc->drefs[j].path);
4409 av_freep(&sc->drefs[j].dir);
4411 av_freep(&sc->drefs);
4413 sc->drefs_count = 0;
4415 if (!sc->pb_is_copied)
4416 avio_closep(&sc->pb);
4419 av_freep(&sc->chunk_offsets);
4420 av_freep(&sc->stsc_data);
4421 av_freep(&sc->sample_sizes);
4422 av_freep(&sc->keyframes);
4423 av_freep(&sc->stts_data);
4424 av_freep(&sc->stps_data);
4425 av_freep(&sc->elst_data);
4426 av_freep(&sc->rap_group);
4427 av_freep(&sc->display_matrix);
4430 if (mov->dv_demux) {
4431 avformat_free_context(mov->dv_fctx);
4432 mov->dv_fctx = NULL;
4435 if (mov->meta_keys) {
4436 for (i = 1; i < mov->meta_keys_count; i++) {
4437 av_freep(&mov->meta_keys[i]);
4439 av_freep(&mov->meta_keys);
4442 av_freep(&mov->trex_data);
4443 av_freep(&mov->bitrates);
4445 for (i = 0; i < mov->fragment_index_count; i++) {
4446 MOVFragmentIndex* index = mov->fragment_index_data[i];
4447 av_freep(&index->items);
4448 av_freep(&mov->fragment_index_data[i]);
4450 av_freep(&mov->fragment_index_data);
4452 av_freep(&mov->aes_decrypt);
4457 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
4461 for (i = 0; i < s->nb_streams; i++) {
4462 AVStream *st = s->streams[i];
4463 MOVStreamContext *sc = st->priv_data;
4465 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4466 sc->timecode_track == tmcd_id)
4472 /* look for a tmcd track not referenced by any video track, and export it globally */
4473 static void export_orphan_timecode(AVFormatContext *s)
4477 for (i = 0; i < s->nb_streams; i++) {
4478 AVStream *st = s->streams[i];
4480 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
4481 !tmcd_is_referenced(s, i + 1)) {
4482 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
4484 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
4491 static int read_tfra(MOVContext *mov, AVIOContext *f)
4493 MOVFragmentIndex* index = NULL;
4494 int version, fieldlength, i, j;
4495 int64_t pos = avio_tell(f);
4496 uint32_t size = avio_rb32(f);
4499 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
4502 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
4503 index = av_mallocz(sizeof(MOVFragmentIndex));
4505 return AVERROR(ENOMEM);
4508 tmp = av_realloc_array(mov->fragment_index_data,
4509 mov->fragment_index_count + 1,
4510 sizeof(MOVFragmentIndex*));
4513 return AVERROR(ENOMEM);
4515 mov->fragment_index_data = tmp;
4516 mov->fragment_index_data[mov->fragment_index_count++] = index;
4518 version = avio_r8(f);
4520 index->track_id = avio_rb32(f);
4521 fieldlength = avio_rb32(f);
4522 index->item_count = avio_rb32(f);
4523 index->items = av_mallocz_array(
4524 index->item_count, sizeof(MOVFragmentIndexItem));
4525 if (!index->items) {
4526 index->item_count = 0;
4527 return AVERROR(ENOMEM);
4529 for (i = 0; i < index->item_count; i++) {
4530 int64_t time, offset;
4532 time = avio_rb64(f);
4533 offset = avio_rb64(f);
4535 time = avio_rb32(f);
4536 offset = avio_rb32(f);
4538 index->items[i].time = time;
4539 index->items[i].moof_offset = offset;
4540 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
4542 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
4544 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
4548 avio_seek(f, pos + size, SEEK_SET);
4552 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
4554 int64_t stream_size = avio_size(f);
4555 int64_t original_pos = avio_tell(f);
4559 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
4563 mfra_size = avio_rb32(f);
4564 if (mfra_size < 0 || mfra_size > stream_size) {
4565 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
4568 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
4572 if (avio_rb32(f) != mfra_size) {
4573 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
4576 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
4577 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
4580 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
4582 ret = read_tfra(c, f);
4588 seek_ret = avio_seek(f, original_pos, SEEK_SET);
4590 av_log(c->fc, AV_LOG_ERROR,
4591 "failed to seek back after looking for mfra\n");
4597 static int mov_read_header(AVFormatContext *s)
4599 MOVContext *mov = s->priv_data;
4600 AVIOContext *pb = s->pb;
4602 MOVAtom atom = { AV_RL32("root") };
4606 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
4608 atom.size = avio_size(pb);
4610 atom.size = INT64_MAX;
4612 /* check MOV header */
4614 if (mov->moov_retry)
4615 avio_seek(pb, 0, SEEK_SET);
4616 if ((err = mov_read_default(mov, pb, atom)) < 0) {
4617 av_log(s, AV_LOG_ERROR, "error reading header\n");
4621 } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
4622 if (!mov->found_moov) {
4623 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
4625 return AVERROR_INVALIDDATA;
4627 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
4630 if (mov->chapter_track > 0)
4631 mov_read_chapters(s);
4632 for (i = 0; i < s->nb_streams; i++)
4633 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
4634 mov_read_timecode_track(s, s->streams[i]);
4637 /* copy timecode metadata from tmcd tracks to the related video streams */
4638 for (i = 0; i < s->nb_streams; i++) {
4639 AVStream *st = s->streams[i];
4640 MOVStreamContext *sc = st->priv_data;
4641 if (sc->timecode_track > 0) {
4642 AVDictionaryEntry *tcr;
4643 int tmcd_st_id = -1;
4645 for (j = 0; j < s->nb_streams; j++)
4646 if (s->streams[j]->id == sc->timecode_track)
4649 if (tmcd_st_id < 0 || tmcd_st_id == i)
4651 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
4653 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
4656 export_orphan_timecode(s);
4658 for (i = 0; i < s->nb_streams; i++) {
4659 AVStream *st = s->streams[i];
4660 MOVStreamContext *sc = st->priv_data;
4661 fix_timescale(mov, sc);
4662 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
4663 st->skip_samples = sc->start_pad;
4665 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
4666 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4667 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
4668 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4669 if (st->codec->width <= 0 || st->codec->height <= 0) {
4670 st->codec->width = sc->width;
4671 st->codec->height = sc->height;
4673 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
4674 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
4680 if (mov->trex_data) {
4681 for (i = 0; i < s->nb_streams; i++) {
4682 AVStream *st = s->streams[i];
4683 MOVStreamContext *sc = st->priv_data;
4684 if (st->duration > 0)
4685 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
4689 if (mov->use_mfra_for > 0) {
4690 for (i = 0; i < s->nb_streams; i++) {
4691 AVStream *st = s->streams[i];
4692 MOVStreamContext *sc = st->priv_data;
4693 if (sc->duration_for_fps > 0) {
4694 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
4695 sc->duration_for_fps;
4700 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
4701 if (mov->bitrates[i]) {
4702 s->streams[i]->codec->bit_rate = mov->bitrates[i];
4706 ff_rfps_calculate(s);
4708 for (i = 0; i < s->nb_streams; i++) {
4709 AVStream *st = s->streams[i];
4710 MOVStreamContext *sc = st->priv_data;
4712 switch (st->codec->codec_type) {
4713 case AVMEDIA_TYPE_AUDIO:
4714 err = ff_replaygain_export(st, s->metadata);
4720 case AVMEDIA_TYPE_VIDEO:
4721 if (sc->display_matrix) {
4722 AVPacketSideData *sd, *tmp;
4724 tmp = av_realloc_array(st->side_data,
4725 st->nb_side_data + 1, sizeof(*tmp));
4727 return AVERROR(ENOMEM);
4729 st->side_data = tmp;
4732 sd = &st->side_data[st->nb_side_data - 1];
4733 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
4734 sd->size = sizeof(int32_t) * 9;
4735 sd->data = (uint8_t*)sc->display_matrix;
4736 sc->display_matrix = NULL;
4741 ff_configure_buffers_for_index(s, AV_TIME_BASE);
4746 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
4748 AVIndexEntry *sample = NULL;
4749 int64_t best_dts = INT64_MAX;
4751 for (i = 0; i < s->nb_streams; i++) {
4752 AVStream *avst = s->streams[i];
4753 MOVStreamContext *msc = avst->priv_data;
4754 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
4755 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
4756 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
4757 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
4758 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
4760 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
4761 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
4762 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
4763 sample = current_sample;
4772 static int should_retry(AVIOContext *pb, int error_code) {
4773 if (error_code == AVERROR_EOF || avio_feof(pb))
4779 static int mov_switch_root(AVFormatContext *s, int64_t target)
4781 MOVContext *mov = s->priv_data;
4783 int already_read = 0;
4785 if (avio_seek(s->pb, target, SEEK_SET) != target) {
4786 av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
4787 return AVERROR_INVALIDDATA;
4790 mov->next_root_atom = 0;
4792 for (i = 0; i < mov->fragment_index_count; i++) {
4793 MOVFragmentIndex *index = mov->fragment_index_data[i];
4795 for (j = 0; j < index->item_count; j++) {
4796 MOVFragmentIndexItem *item = &index->items[j];
4798 mov->next_root_atom = item->moof_offset;
4799 break; // Advance to next index in outer loop
4800 } else if (item->moof_offset == target) {
4801 index->current_item = FFMIN(j, index->current_item);
4802 if (item->headers_read)
4804 item->headers_read = 1;
4809 index->current_item = 0;
4815 mov->found_mdat = 0;
4817 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
4820 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
4825 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
4827 MOVContext *mov = s->priv_data;
4828 MOVStreamContext *sc;
4829 AVIndexEntry *sample;
4830 AVStream *st = NULL;
4834 sample = mov_find_next_sample(s, &st);
4835 if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
4836 if (!mov->next_root_atom)
4838 if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
4843 /* must be done just before reading, to avoid infinite loop on sample */
4844 sc->current_sample++;
4846 if (mov->next_root_atom) {
4847 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
4848 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
4851 if (st->discard != AVDISCARD_ALL) {
4852 int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
4853 if (ret64 != sample->pos) {
4854 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
4855 sc->ffindex, sample->pos);
4856 sc->current_sample -= should_retry(sc->pb, ret64);
4857 return AVERROR_INVALIDDATA;
4859 ret = av_get_packet(sc->pb, pkt, sample->size);
4861 sc->current_sample -= should_retry(sc->pb, ret);
4864 if (sc->has_palette) {
4867 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
4869 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
4871 memcpy(pal, sc->palette, AVPALETTE_SIZE);
4872 sc->has_palette = 0;
4875 #if CONFIG_DV_DEMUXER
4876 if (mov->dv_demux && sc->dv_audio_container) {
4877 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
4878 av_freep(&pkt->data);
4880 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
4887 pkt->stream_index = sc->ffindex;
4888 pkt->dts = sample->timestamp;
4889 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
4890 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
4891 /* update ctts context */
4893 if (sc->ctts_index < sc->ctts_count &&
4894 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
4896 sc->ctts_sample = 0;
4899 pkt->dts = AV_NOPTS_VALUE;
4901 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
4902 st->index_entries[sc->current_sample].timestamp : st->duration;
4903 pkt->duration = next_dts - pkt->dts;
4904 pkt->pts = pkt->dts;
4906 if (st->discard == AVDISCARD_ALL)
4908 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
4909 pkt->pos = sample->pos;
4912 aax_filter(pkt->data, pkt->size, mov);
4917 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
4919 MOVContext *mov = s->priv_data;
4922 if (!mov->fragment_index_complete)
4925 for (i = 0; i < mov->fragment_index_count; i++) {
4926 if (mov->fragment_index_data[i]->track_id == st->id) {
4927 MOVFragmentIndex *index = index = mov->fragment_index_data[i];
4928 for (j = index->item_count - 1; j >= 0; j--) {
4929 if (index->items[j].time <= timestamp) {
4930 if (index->items[j].headers_read)
4933 return mov_switch_root(s, index->items[j].moof_offset);
4942 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
4944 MOVStreamContext *sc = st->priv_data;
4945 int sample, time_sample;
4948 int ret = mov_seek_fragment(s, st, timestamp);
4952 sample = av_index_search_timestamp(st, timestamp, flags);
4953 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
4954 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
4956 if (sample < 0) /* not sure what to do */
4957 return AVERROR_INVALIDDATA;
4958 sc->current_sample = sample;
4959 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
4960 /* adjust ctts index */
4961 if (sc->ctts_data) {
4963 for (i = 0; i < sc->ctts_count; i++) {
4964 int next = time_sample + sc->ctts_data[i].count;
4965 if (next > sc->current_sample) {
4967 sc->ctts_sample = sc->current_sample - time_sample;
4976 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
4978 MOVContext *mc = s->priv_data;
4983 if (stream_index >= s->nb_streams)
4984 return AVERROR_INVALIDDATA;
4986 st = s->streams[stream_index];
4987 sample = mov_seek_stream(s, st, sample_time, flags);
4991 if (mc->seek_individually) {
4992 /* adjust seek timestamp to found sample timestamp */
4993 int64_t seek_timestamp = st->index_entries[sample].timestamp;
4995 for (i = 0; i < s->nb_streams; i++) {
4997 MOVStreamContext *sc = s->streams[i]->priv_data;
4999 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
5001 if (stream_index == i)
5004 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
5005 mov_seek_stream(s, st, timestamp, flags);
5008 for (i = 0; i < s->nb_streams; i++) {
5009 MOVStreamContext *sc;
5012 sc->current_sample = 0;
5015 MOVStreamContext *sc;
5016 AVIndexEntry *entry = mov_find_next_sample(s, &st);
5018 return AVERROR_INVALIDDATA;
5020 if (sc->ffindex == stream_index && sc->current_sample == sample)
5022 sc->current_sample++;
5028 #define OFFSET(x) offsetof(MOVContext, x)
5029 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
5030 static const AVOption mov_options[] = {
5031 {"use_absolute_path",
5032 "allow using absolute path when opening alias, this is a possible security issue",
5033 OFFSET(use_absolute_path), AV_OPT_TYPE_INT, {.i64 = 0},
5035 {"seek_streams_individually",
5036 "Seek each stream individually to the to the closest point",
5037 OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
5039 {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_INT, {.i64 = 0},
5042 "use mfra for fragment timestamps",
5043 OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
5044 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
5046 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
5047 FLAGS, "use_mfra_for" },
5048 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
5049 FLAGS, "use_mfra_for" },
5050 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
5051 FLAGS, "use_mfra_for" },
5052 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
5053 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5054 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
5055 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5056 { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
5057 AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5058 { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
5059 "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
5060 AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
5061 .flags = AV_OPT_FLAG_DECODING_PARAM },
5065 static const AVClass mov_class = {
5066 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
5067 .item_name = av_default_item_name,
5068 .option = mov_options,
5069 .version = LIBAVUTIL_VERSION_INT,
5072 AVInputFormat ff_mov_demuxer = {
5073 .name = "mov,mp4,m4a,3gp,3g2,mj2",
5074 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5075 .priv_class = &mov_class,
5076 .priv_data_size = sizeof(MOVContext),
5077 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
5078 .read_probe = mov_probe,
5079 .read_header = mov_read_header,
5080 .read_packet = mov_read_packet,
5081 .read_close = mov_read_close,
5082 .read_seek = mov_read_seek,
5083 .flags = AVFMT_NO_BYTE_SEEK,