3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * first version by Francois Revol <revol@free.fr>
7 * seek function by Gael Chardon <gael.dev@4now.net>
9 * This file is part of FFmpeg.
11 * FFmpeg is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * FFmpeg is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with FFmpeg; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include "libavutil/attributes.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/intfloat.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/time_internal.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/display.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/aes.h"
42 #include "libavutil/sha.h"
43 #include "libavutil/timecode.h"
44 #include "libavcodec/ac3tab.h"
47 #include "avio_internal.h"
50 #include "libavcodec/get_bits.h"
53 #include "replaygain.h"
59 #include "qtpalette.h"
61 /* those functions parse an atom */
62 /* links atom IDs to parse functions */
63 typedef struct MOVParseTableEntry {
65 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
68 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
69 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
71 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
72 unsigned len, const char *key)
76 short current, total = 0;
77 avio_rb16(pb); // unknown
78 current = avio_rb16(pb);
80 total = avio_rb16(pb);
82 snprintf(buf, sizeof(buf), "%d", current);
84 snprintf(buf, sizeof(buf), "%d/%d", current, total);
85 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
86 av_dict_set(&c->fc->metadata, key, buf, 0);
91 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
92 unsigned len, const char *key)
94 /* bypass padding bytes */
99 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
100 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
105 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
106 unsigned len, const char *key)
108 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
109 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
114 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
115 unsigned len, const char *key)
119 avio_r8(pb); // unknown
122 if (genre < 1 || genre > ID3v1_GENRE_MAX)
124 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
125 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
130 static const uint32_t mac_to_unicode[128] = {
131 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
132 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
133 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
134 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
135 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
136 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
137 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
138 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
139 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
140 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
141 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
142 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
143 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
144 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
145 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
146 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
149 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
150 char *dst, int dstlen)
153 char *end = dst+dstlen-1;
156 for (i = 0; i < len; i++) {
157 uint8_t t, c = avio_r8(pb);
158 if (c < 0x80 && p < end)
161 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
167 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
171 MOVStreamContext *sc;
176 case 0xd: id = AV_CODEC_ID_MJPEG; break;
177 case 0xe: id = AV_CODEC_ID_PNG; break;
178 case 0x1b: id = AV_CODEC_ID_BMP; break;
180 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
185 st = avformat_new_stream(c->fc, NULL);
187 return AVERROR(ENOMEM);
188 sc = av_mallocz(sizeof(*sc));
190 return AVERROR(ENOMEM);
193 ret = av_get_packet(pb, &pkt, len);
197 if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
198 if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
199 id = AV_CODEC_ID_PNG;
201 id = AV_CODEC_ID_MJPEG;
205 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
207 st->attached_pic = pkt;
208 st->attached_pic.stream_index = st->index;
209 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
211 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
212 st->codec->codec_id = id;
217 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
219 char language[4] = { 0 };
220 char buf[200], place[100];
221 uint16_t langcode = 0;
222 double longitude, latitude, altitude;
223 const char *key = "location";
225 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
226 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
227 return AVERROR_INVALIDDATA;
230 avio_skip(pb, 4); // version+flags
231 langcode = avio_rb16(pb);
232 ff_mov_lang_to_iso639(langcode, language);
235 len -= avio_get_str(pb, len, place, sizeof(place));
237 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
238 return AVERROR_INVALIDDATA;
240 avio_skip(pb, 1); // role
244 av_log(c->fc, AV_LOG_ERROR, "no space for coordinates left (%d)\n", len);
245 return AVERROR_INVALIDDATA;
247 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
248 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
249 altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
251 // Try to output in the same format as the ?xyz field
252 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
254 av_strlcatf(buf, sizeof(buf), "%+f", altitude);
255 av_strlcatf(buf, sizeof(buf), "/%s", place);
257 if (*language && strcmp(language, "und")) {
259 snprintf(key2, sizeof(key2), "%s-%s", key, language);
260 av_dict_set(&c->fc->metadata, key2, buf, 0);
262 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
263 return av_dict_set(&c->fc->metadata, key, buf, 0);
266 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
269 char key2[32], language[4] = {0};
271 const char *key = NULL;
272 uint16_t langcode = 0;
273 uint32_t data_type = 0, str_size, str_size_alloc;
274 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
279 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
280 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
281 case MKTAG( 'X','M','P','_'):
282 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
283 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
284 case MKTAG( 'a','k','I','D'): key = "account_type";
285 parse = mov_metadata_int8_no_padding; break;
286 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
287 case MKTAG( 'c','a','t','g'): key = "category"; break;
288 case MKTAG( 'c','p','i','l'): key = "compilation";
289 parse = mov_metadata_int8_no_padding; break;
290 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
291 case MKTAG( 'd','e','s','c'): key = "description"; break;
292 case MKTAG( 'd','i','s','k'): key = "disc";
293 parse = mov_metadata_track_or_disc_number; break;
294 case MKTAG( 'e','g','i','d'): key = "episode_uid";
295 parse = mov_metadata_int8_no_padding; break;
296 case MKTAG( 'g','n','r','e'): key = "genre";
297 parse = mov_metadata_gnre; break;
298 case MKTAG( 'h','d','v','d'): key = "hd_video";
299 parse = mov_metadata_int8_no_padding; break;
300 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
301 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
302 case MKTAG( 'l','o','c','i'):
303 return mov_metadata_loci(c, pb, atom.size);
304 case MKTAG( 'p','c','s','t'): key = "podcast";
305 parse = mov_metadata_int8_no_padding; break;
306 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
307 parse = mov_metadata_int8_no_padding; break;
308 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
309 case MKTAG( 'r','t','n','g'): key = "rating";
310 parse = mov_metadata_int8_no_padding; break;
311 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
312 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
313 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
314 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
315 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
316 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
317 case MKTAG( 's','t','i','k'): key = "media_type";
318 parse = mov_metadata_int8_no_padding; break;
319 case MKTAG( 't','r','k','n'): key = "track";
320 parse = mov_metadata_track_or_disc_number; break;
321 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
322 case MKTAG( 't','v','e','s'): key = "episode_sort";
323 parse = mov_metadata_int8_bypass_padding; break;
324 case MKTAG( 't','v','n','n'): key = "network"; break;
325 case MKTAG( 't','v','s','h'): key = "show"; break;
326 case MKTAG( 't','v','s','n'): key = "season_number";
327 parse = mov_metadata_int8_bypass_padding; break;
328 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
329 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
330 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
331 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
332 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
333 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
334 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
335 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
336 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
337 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
338 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
339 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
340 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
341 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
342 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
343 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
344 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
345 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
346 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
347 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
348 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
349 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
350 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
351 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
352 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
353 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
354 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
355 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
356 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
357 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
358 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
359 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
360 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
361 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
362 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
365 if (c->itunes_metadata && atom.size > 8) {
366 int data_size = avio_rb32(pb);
367 int tag = avio_rl32(pb);
368 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
369 data_type = avio_rb32(pb); // type
370 avio_rb32(pb); // unknown
371 str_size = data_size - 16;
374 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
375 int ret = mov_read_covr(c, pb, data_type, str_size);
377 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
380 } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
381 uint32_t index = AV_RB32(&atom.type);
382 if (index < c->meta_keys_count) {
383 key = c->meta_keys[index];
385 av_log(c->fc, AV_LOG_WARNING,
386 "The index of 'data' is out of range: %d >= %d.\n",
387 index, c->meta_keys_count);
391 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
392 str_size = avio_rb16(pb); // string length
393 if (str_size > atom.size) {
395 avio_seek(pb, -2, SEEK_CUR);
396 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
399 langcode = avio_rb16(pb);
400 ff_mov_lang_to_iso639(langcode, language);
403 str_size = atom.size;
405 if (c->export_all && !key) {
406 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
412 if (atom.size < 0 || str_size >= INT_MAX/2)
413 return AVERROR_INVALIDDATA;
415 // Allocates enough space if data_type is a float32 number, otherwise
416 // worst-case requirement for output string in case of utf8 coded input
417 num = (data_type == 23);
418 str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
419 str = av_mallocz(str_size_alloc);
421 return AVERROR(ENOMEM);
424 parse(c, pb, str_size, key);
426 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
427 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
428 } else if (data_type == 23 && str_size >= 4) { // BE float32
429 float val = av_int2float(avio_rb32(pb));
430 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
431 av_log(c->fc, AV_LOG_ERROR,
432 "Failed to store the float32 number (%f) in string.\n", val);
433 return AVERROR_INVALIDDATA;
436 int ret = ffio_read_size(pb, str, str_size);
443 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
444 av_dict_set(&c->fc->metadata, key, str, 0);
445 if (*language && strcmp(language, "und")) {
446 snprintf(key2, sizeof(key2), "%s-%s", key, language);
447 av_dict_set(&c->fc->metadata, key2, str, 0);
450 av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
451 av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
452 key, str, (char*)&atom.type, str_size_alloc, atom.size);
458 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
461 int i, nb_chapters, str_len, version;
465 if ((atom.size -= 5) < 0)
468 version = avio_r8(pb);
471 avio_rb32(pb); // ???
472 nb_chapters = avio_r8(pb);
474 for (i = 0; i < nb_chapters; i++) {
478 start = avio_rb64(pb);
479 str_len = avio_r8(pb);
481 if ((atom.size -= 9+str_len) < 0)
484 ret = ffio_read_size(pb, str, str_len);
488 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
493 #define MIN_DATA_ENTRY_BOX_SIZE 12
494 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
497 MOVStreamContext *sc;
500 if (c->fc->nb_streams < 1)
502 st = c->fc->streams[c->fc->nb_streams-1];
505 avio_rb32(pb); // version + flags
506 entries = avio_rb32(pb);
507 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
508 entries >= UINT_MAX / sizeof(*sc->drefs))
509 return AVERROR_INVALIDDATA;
512 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
514 return AVERROR(ENOMEM);
515 sc->drefs_count = entries;
517 for (i = 0; i < sc->drefs_count; i++) {
518 MOVDref *dref = &sc->drefs[i];
519 uint32_t size = avio_rb32(pb);
520 int64_t next = avio_tell(pb) + size - 4;
523 return AVERROR_INVALIDDATA;
525 dref->type = avio_rl32(pb);
526 avio_rb32(pb); // version + flags
527 av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
529 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
530 /* macintosh alias record */
531 uint16_t volume_len, len;
537 volume_len = avio_r8(pb);
538 volume_len = FFMIN(volume_len, 27);
539 ret = ffio_read_size(pb, dref->volume, 27);
542 dref->volume[volume_len] = 0;
543 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
548 len = FFMIN(len, 63);
549 ret = ffio_read_size(pb, dref->filename, 63);
552 dref->filename[len] = 0;
553 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
557 /* read next level up_from_alias/down_to_target */
558 dref->nlvl_from = avio_rb16(pb);
559 dref->nlvl_to = avio_rb16(pb);
560 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
561 dref->nlvl_from, dref->nlvl_to);
565 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
568 type = avio_rb16(pb);
570 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
573 if (type == 2 || type == 18) { // absolute path
575 dref->path = av_mallocz(len+1);
577 return AVERROR(ENOMEM);
579 ret = ffio_read_size(pb, dref->path, len);
581 av_freep(&dref->path);
584 if (type == 18) // no additional processing needed
586 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
588 memmove(dref->path, dref->path+volume_len, len);
591 for (j = 0; j < len; j++)
592 if (dref->path[j] == ':')
594 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
595 } else if (type == 0) { // directory name
597 dref->dir = av_malloc(len+1);
599 return AVERROR(ENOMEM);
601 ret = ffio_read_size(pb, dref->dir, len);
603 av_freep(&dref->dir);
607 for (j = 0; j < len; j++)
608 if (dref->dir[j] == ':')
610 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
615 avio_seek(pb, next, SEEK_SET);
620 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
624 uint32_t av_unused ctype;
629 avio_r8(pb); /* version */
630 avio_rb24(pb); /* flags */
633 ctype = avio_rl32(pb);
634 type = avio_rl32(pb); /* component subtype */
636 av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
637 av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
639 if (c->fc->nb_streams < 1) { // meta before first trak
640 if (type == MKTAG('m','d','t','a')) {
641 c->found_hdlr_mdta = 1;
646 st = c->fc->streams[c->fc->nb_streams-1];
648 if (type == MKTAG('v','i','d','e'))
649 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
650 else if (type == MKTAG('s','o','u','n'))
651 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
652 else if (type == MKTAG('m','1','a',' '))
653 st->codec->codec_id = AV_CODEC_ID_MP2;
654 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
655 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
657 avio_rb32(pb); /* component manufacture */
658 avio_rb32(pb); /* component flags */
659 avio_rb32(pb); /* component flags mask */
661 title_size = atom.size - 24;
662 if (title_size > 0) {
663 title_str = av_malloc(title_size + 1); /* Add null terminator */
665 return AVERROR(ENOMEM);
667 ret = ffio_read_size(pb, title_str, title_size);
669 av_freep(&title_str);
672 title_str[title_size] = 0;
674 int off = (!c->isom && title_str[0] == title_size - 1);
675 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
677 av_freep(&title_str);
683 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
688 if (fc->nb_streams < 1)
690 st = fc->streams[fc->nb_streams-1];
692 avio_rb32(pb); /* version + flags */
693 ff_mp4_read_descr(fc, pb, &tag);
694 if (tag == MP4ESDescrTag) {
695 ff_mp4_parse_es_descr(pb, NULL);
697 avio_rb16(pb); /* ID */
699 ff_mp4_read_descr(fc, pb, &tag);
700 if (tag == MP4DecConfigDescrTag)
701 ff_mp4_read_dec_config_descr(fc, st, pb);
705 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
707 return ff_mov_read_esds(c->fc, pb);
710 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
713 enum AVAudioServiceType *ast;
714 int ac3info, acmod, lfeon, bsmod;
716 if (c->fc->nb_streams < 1)
718 st = c->fc->streams[c->fc->nb_streams-1];
720 ast = (enum AVAudioServiceType*)ff_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
723 return AVERROR(ENOMEM);
725 ac3info = avio_rb24(pb);
726 bsmod = (ac3info >> 14) & 0x7;
727 acmod = (ac3info >> 11) & 0x7;
728 lfeon = (ac3info >> 10) & 0x1;
729 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
730 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
732 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
734 if (st->codec->channels > 1 && bsmod == 0x7)
735 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
737 st->codec->audio_service_type = *ast;
742 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
745 enum AVAudioServiceType *ast;
746 int eac3info, acmod, lfeon, bsmod;
748 if (c->fc->nb_streams < 1)
750 st = c->fc->streams[c->fc->nb_streams-1];
752 ast = (enum AVAudioServiceType*)ff_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
755 return AVERROR(ENOMEM);
757 /* No need to parse fields for additional independent substreams and its
758 * associated dependent substreams since libavcodec's E-AC-3 decoder
759 * does not support them yet. */
760 avio_rb16(pb); /* data_rate and num_ind_sub */
761 eac3info = avio_rb24(pb);
762 bsmod = (eac3info >> 12) & 0x1f;
763 acmod = (eac3info >> 9) & 0x7;
764 lfeon = (eac3info >> 8) & 0x1;
765 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
767 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
768 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
770 if (st->codec->channels > 1 && bsmod == 0x7)
771 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
773 st->codec->audio_service_type = *ast;
778 static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
780 const uint32_t ddts_size = 20;
783 uint32_t frame_duration_code = 0;
784 uint32_t channel_layout_code = 0;
787 buf = av_malloc(ddts_size + FF_INPUT_BUFFER_PADDING_SIZE);
789 return AVERROR(ENOMEM);
791 if (avio_read(pb, buf, ddts_size) < ddts_size) {
793 return AVERROR_INVALIDDATA;
796 init_get_bits(&gb, buf, 8*ddts_size);
798 if (c->fc->nb_streams < 1) {
801 st = c->fc->streams[c->fc->nb_streams-1];
803 st->codec->sample_rate = get_bits_long(&gb, 32);
804 skip_bits_long(&gb, 32); /* max bitrate */
805 st->codec->bit_rate = get_bits_long(&gb, 32);
806 st->codec->bits_per_coded_sample = get_bits(&gb, 8);
807 frame_duration_code = get_bits(&gb, 2);
808 skip_bits(&gb, 30); /* various fields */
809 channel_layout_code = get_bits(&gb, 16);
811 st->codec->frame_size =
812 (frame_duration_code == 0) ? 512 :
813 (frame_duration_code == 1) ? 1024 :
814 (frame_duration_code == 2) ? 2048 :
815 (frame_duration_code == 3) ? 4096 : 0;
817 if (channel_layout_code > 0xff) {
818 av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
820 st->codec->channel_layout =
821 ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
822 ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
823 ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
824 ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
825 ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
826 ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
828 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
833 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
837 if (c->fc->nb_streams < 1)
839 st = c->fc->streams[c->fc->nb_streams-1];
844 /* skip version and flags */
847 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
852 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
857 if (c->fc->nb_streams < 1)
859 st = c->fc->streams[c->fc->nb_streams-1];
861 if ((ret = ff_get_wav_header(c->fc, pb, st->codec, atom.size, 0)) < 0)
862 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
867 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
869 const int num = avio_rb32(pb);
870 const int den = avio_rb32(pb);
873 if (c->fc->nb_streams < 1)
875 st = c->fc->streams[c->fc->nb_streams-1];
877 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
878 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
879 av_log(c->fc, AV_LOG_WARNING,
880 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
881 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
883 } else if (den != 0) {
884 av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
890 /* this atom contains actual media data */
891 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
893 if (atom.size == 0) /* wrong one (MP4) */
896 return 0; /* now go for moov */
899 #define DRM_BLOB_SIZE 56
901 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
903 uint8_t intermediate_key[20];
904 uint8_t intermediate_iv[20];
907 uint8_t file_checksum[20];
908 uint8_t calculated_checksum[20];
912 uint8_t *activation_bytes = c->activation_bytes;
913 uint8_t *fixed_key = c->audible_fixed_key;
917 sha = av_sha_alloc();
919 return AVERROR(ENOMEM);
920 c->aes_decrypt = av_aes_alloc();
921 if (!c->aes_decrypt) {
922 ret = AVERROR(ENOMEM);
926 /* drm blob processing */
927 avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
928 avio_read(pb, input, DRM_BLOB_SIZE);
929 avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
930 avio_read(pb, file_checksum, 20);
932 av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
933 for (i = 0; i < 20; i++)
934 av_log(sha, AV_LOG_INFO, "%02x", file_checksum[i]);
935 av_log(c->fc, AV_LOG_INFO, "\n");
937 /* verify activation data */
938 if (!activation_bytes) {
939 av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
940 ret = 0; /* allow ffprobe to continue working on .aax files */
943 if (c->activation_bytes_size != 4) {
944 av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
945 ret = AVERROR(EINVAL);
949 /* verify fixed key */
950 if (c->audible_fixed_key_size != 16) {
951 av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
952 ret = AVERROR(EINVAL);
956 /* AAX (and AAX+) key derivation */
957 av_sha_init(sha, 160);
958 av_sha_update(sha, fixed_key, 16);
959 av_sha_update(sha, activation_bytes, 4);
960 av_sha_final(sha, intermediate_key);
961 av_sha_init(sha, 160);
962 av_sha_update(sha, fixed_key, 16);
963 av_sha_update(sha, intermediate_key, 20);
964 av_sha_update(sha, activation_bytes, 4);
965 av_sha_final(sha, intermediate_iv);
966 av_sha_init(sha, 160);
967 av_sha_update(sha, intermediate_key, 16);
968 av_sha_update(sha, intermediate_iv, 16);
969 av_sha_final(sha, calculated_checksum);
970 if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
971 av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
972 ret = AVERROR_INVALIDDATA;
975 av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
976 av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
977 for (i = 0; i < 4; i++) {
978 // file data (in output) is stored in big-endian mode
979 if (activation_bytes[i] != output[3 - i]) { // critical error
980 av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
981 ret = AVERROR_INVALIDDATA;
985 memcpy(c->file_key, output + 8, 16);
986 memcpy(input, output + 26, 16);
987 av_sha_init(sha, 160);
988 av_sha_update(sha, input, 16);
989 av_sha_update(sha, c->file_key, 16);
990 av_sha_update(sha, fixed_key, 16);
991 av_sha_final(sha, c->file_iv);
999 // Audible AAX (and AAX+) bytestream decryption
1000 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1003 unsigned char iv[16];
1005 memcpy(iv, c->file_iv, 16); // iv is overwritten
1006 blocks = size >> 4; // trailing bytes are not encrypted!
1007 av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1008 av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1013 /* read major brand, minor version and compatible brands and store them as metadata */
1014 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1017 int comp_brand_size;
1018 char* comp_brands_str;
1019 uint8_t type[5] = {0};
1020 int ret = ffio_read_size(pb, type, 4);
1024 if (strcmp(type, "qt "))
1026 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1027 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1028 minor_ver = avio_rb32(pb); /* minor version */
1029 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1031 comp_brand_size = atom.size - 8;
1032 if (comp_brand_size < 0)
1033 return AVERROR_INVALIDDATA;
1034 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1035 if (!comp_brands_str)
1036 return AVERROR(ENOMEM);
1038 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1040 av_freep(&comp_brands_str);
1043 comp_brands_str[comp_brand_size] = 0;
1044 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1045 av_freep(&comp_brands_str);
1050 /* this atom should contain all header atoms */
1051 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1055 if (c->found_moov) {
1056 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1057 avio_skip(pb, atom.size);
1061 if ((ret = mov_read_default(c, pb, atom)) < 0)
1063 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1064 /* so we don't parse the whole file if over a network */
1066 return 0; /* now go for mdat */
1069 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1071 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1072 c->has_looked_for_mfra = 1;
1075 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1077 if ((ret = mov_read_mfra(c, pb)) < 0) {
1078 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1079 "read the mfra (may be a live ismv)\n");
1082 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1083 "seekable, can not look for mfra\n");
1086 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
1087 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1088 return mov_read_default(c, pb, atom);
1091 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1095 struct tm *ptm, tmbuf;
1097 if(time >= 2082844800)
1098 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1100 ptm = gmtime_r(&timet, &tmbuf);
1102 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
1103 av_dict_set(metadata, "creation_time", buffer, 0);
1107 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1110 MOVStreamContext *sc;
1112 char language[4] = {0};
1114 int64_t creation_time;
1116 if (c->fc->nb_streams < 1)
1118 st = c->fc->streams[c->fc->nb_streams-1];
1121 if (sc->time_scale) {
1122 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1123 return AVERROR_INVALIDDATA;
1126 version = avio_r8(pb);
1128 avpriv_request_sample(c->fc, "Version %d", version);
1129 return AVERROR_PATCHWELCOME;
1131 avio_rb24(pb); /* flags */
1133 creation_time = avio_rb64(pb);
1136 creation_time = avio_rb32(pb);
1137 avio_rb32(pb); /* modification time */
1139 mov_metadata_creation_time(&st->metadata, creation_time);
1141 sc->time_scale = avio_rb32(pb);
1142 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1144 lang = avio_rb16(pb); /* language */
1145 if (ff_mov_lang_to_iso639(lang, language))
1146 av_dict_set(&st->metadata, "language", language, 0);
1147 avio_rb16(pb); /* quality */
1152 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1154 int64_t creation_time;
1155 int version = avio_r8(pb); /* version */
1156 avio_rb24(pb); /* flags */
1159 creation_time = avio_rb64(pb);
1162 creation_time = avio_rb32(pb);
1163 avio_rb32(pb); /* modification time */
1165 mov_metadata_creation_time(&c->fc->metadata, creation_time);
1166 c->time_scale = avio_rb32(pb); /* time scale */
1168 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1170 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1171 // set the AVCodecContext duration because the duration of individual tracks
1172 // may be inaccurate
1173 if (c->time_scale > 0 && !c->trex_data)
1174 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1175 avio_rb32(pb); /* preferred scale */
1177 avio_rb16(pb); /* preferred volume */
1179 avio_skip(pb, 10); /* reserved */
1181 avio_skip(pb, 36); /* display matrix */
1183 avio_rb32(pb); /* preview time */
1184 avio_rb32(pb); /* preview duration */
1185 avio_rb32(pb); /* poster time */
1186 avio_rb32(pb); /* selection time */
1187 avio_rb32(pb); /* selection duration */
1188 avio_rb32(pb); /* current time */
1189 avio_rb32(pb); /* next track ID */
1194 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1199 if (c->fc->nb_streams < 1)
1201 st = c->fc->streams[c->fc->nb_streams-1];
1203 little_endian = avio_rb16(pb) & 0xFF;
1204 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1205 if (little_endian == 1) {
1206 switch (st->codec->codec_id) {
1207 case AV_CODEC_ID_PCM_S24BE:
1208 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
1210 case AV_CODEC_ID_PCM_S32BE:
1211 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
1213 case AV_CODEC_ID_PCM_F32BE:
1214 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
1216 case AV_CODEC_ID_PCM_F64BE:
1217 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
1226 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1229 char color_parameter_type[5] = { 0 };
1230 uint16_t color_primaries, color_trc, color_matrix;
1233 if (c->fc->nb_streams < 1)
1235 st = c->fc->streams[c->fc->nb_streams - 1];
1237 ret = ffio_read_size(pb, color_parameter_type, 4);
1240 if (strncmp(color_parameter_type, "nclx", 4) &&
1241 strncmp(color_parameter_type, "nclc", 4)) {
1242 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1243 color_parameter_type);
1247 color_primaries = avio_rb16(pb);
1248 color_trc = avio_rb16(pb);
1249 color_matrix = avio_rb16(pb);
1251 av_log(c->fc, AV_LOG_TRACE,
1252 "%s: pri %d trc %d matrix %d",
1253 color_parameter_type, color_primaries, color_trc, color_matrix);
1255 if (!strncmp(color_parameter_type, "nclx", 4)) {
1256 uint8_t color_range = avio_r8(pb) >> 7;
1257 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1259 st->codec->color_range = AVCOL_RANGE_JPEG;
1261 st->codec->color_range = AVCOL_RANGE_MPEG;
1262 /* 14496-12 references JPEG XR specs (rather than the more complete
1263 * 23001-8) so some adjusting is required */
1264 if (color_primaries >= AVCOL_PRI_FILM)
1265 color_primaries = AVCOL_PRI_UNSPECIFIED;
1266 if ((color_trc >= AVCOL_TRC_LINEAR &&
1267 color_trc <= AVCOL_TRC_LOG_SQRT) ||
1268 color_trc >= AVCOL_TRC_BT2020_10)
1269 color_trc = AVCOL_TRC_UNSPECIFIED;
1270 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
1271 color_matrix = AVCOL_SPC_UNSPECIFIED;
1272 st->codec->color_primaries = color_primaries;
1273 st->codec->color_trc = color_trc;
1274 st->codec->colorspace = color_matrix;
1275 } else if (!strncmp(color_parameter_type, "nclc", 4)) {
1276 /* color primaries, Table 4-4 */
1277 switch (color_primaries) {
1278 case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
1279 case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
1280 case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
1282 /* color transfer, Table 4-5 */
1283 switch (color_trc) {
1284 case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
1285 case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
1287 /* color matrix, Table 4-6 */
1288 switch (color_matrix) {
1289 case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
1290 case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
1291 case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
1294 av_log(c->fc, AV_LOG_TRACE, "\n");
1299 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1302 unsigned mov_field_order;
1303 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1305 if (c->fc->nb_streams < 1) // will happen with jp2 files
1307 st = c->fc->streams[c->fc->nb_streams-1];
1309 return AVERROR_INVALIDDATA;
1310 mov_field_order = avio_rb16(pb);
1311 if ((mov_field_order & 0xFF00) == 0x0100)
1312 decoded_field_order = AV_FIELD_PROGRESSIVE;
1313 else if ((mov_field_order & 0xFF00) == 0x0200) {
1314 switch (mov_field_order & 0xFF) {
1315 case 0x01: decoded_field_order = AV_FIELD_TT;
1317 case 0x06: decoded_field_order = AV_FIELD_BB;
1319 case 0x09: decoded_field_order = AV_FIELD_TB;
1321 case 0x0E: decoded_field_order = AV_FIELD_BT;
1325 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1326 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1328 st->codec->field_order = decoded_field_order;
1333 static int mov_realloc_extradata(AVCodecContext *codec, MOVAtom atom)
1336 uint64_t size = (uint64_t)codec->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1337 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1338 return AVERROR_INVALIDDATA;
1339 if ((err = av_reallocp(&codec->extradata, size)) < 0) {
1340 codec->extradata_size = 0;
1343 codec->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1347 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1348 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1349 AVCodecContext *codec, uint8_t *buf)
1351 int64_t result = atom.size;
1354 AV_WB32(buf , atom.size + 8);
1355 AV_WL32(buf + 4, atom.type);
1356 err = ffio_read_size(pb, buf + 8, atom.size);
1358 codec->extradata_size -= atom.size;
1360 } else if (err < atom.size) {
1361 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1362 codec->extradata_size -= atom.size - err;
1365 memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1369 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
1370 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1371 enum AVCodecID codec_id)
1374 uint64_t original_size;
1377 if (c->fc->nb_streams < 1) // will happen with jp2 files
1379 st = c->fc->streams[c->fc->nb_streams-1];
1381 if (st->codec->codec_id != codec_id)
1382 return 0; /* unexpected codec_id - don't mess with extradata */
1384 original_size = st->codec->extradata_size;
1385 err = mov_realloc_extradata(st->codec, atom);
1389 err = mov_read_atom_into_extradata(c, pb, atom, st->codec, st->codec->extradata + original_size);
1392 return 0; // Note: this is the original behavior to ignore truncation.
1395 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1396 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1398 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1401 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1403 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1406 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1408 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1411 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1413 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1416 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1418 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1420 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1424 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1426 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1428 if (!ret && c->fc->nb_streams >= 1) {
1429 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
1430 if (avctx->extradata_size >= 40) {
1431 avctx->height = AV_RB16(&avctx->extradata[36]);
1432 avctx->width = AV_RB16(&avctx->extradata[38]);
1438 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1440 if (c->fc->nb_streams >= 1) {
1441 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1442 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1443 codec->codec_id == AV_CODEC_ID_H264 &&
1446 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1447 if (avio_rb16(pb) == 0xd4d)
1448 codec->width = 1440;
1453 return mov_read_avid(c, pb, atom);
1456 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1460 uint64_t original_size;
1461 if (c->fc->nb_streams >= 1) {
1462 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1463 if (codec->codec_id == AV_CODEC_ID_H264)
1465 if (atom.size == 16) {
1466 original_size = codec->extradata_size;
1467 ret = mov_realloc_extradata(codec, atom);
1469 length = mov_read_atom_into_extradata(c, pb, atom, codec, codec->extradata + original_size);
1470 if (length == atom.size) {
1471 const uint8_t range_value = codec->extradata[original_size + 19];
1472 switch (range_value) {
1474 codec->color_range = AVCOL_RANGE_MPEG;
1477 codec->color_range = AVCOL_RANGE_JPEG;
1480 av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1483 ff_dlog(c, "color_range: %d\n", codec->color_range);
1485 /* For some reason the whole atom was not added to the extradata */
1486 av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1489 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1492 av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1499 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1501 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1504 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1509 if (c->fc->nb_streams < 1)
1511 st = c->fc->streams[c->fc->nb_streams-1];
1513 if ((uint64_t)atom.size > (1<<30))
1514 return AVERROR_INVALIDDATA;
1516 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1517 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1518 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1519 // pass all frma atom to codec, needed at least for QDMC and QDM2
1520 av_freep(&st->codec->extradata);
1521 ret = ff_get_extradata(st->codec, pb, atom.size);
1524 } else if (atom.size > 8) { /* to read frma, esds atoms */
1525 if (st->codec->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1527 ret = ffio_ensure_seekback(pb, 8);
1530 buffer = avio_rb64(pb);
1532 if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1533 && buffer >> 32 <= atom.size
1534 && buffer >> 32 >= 8) {
1537 } else if (!st->codec->extradata_size) {
1538 #define ALAC_EXTRADATA_SIZE 36
1539 st->codec->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1540 if (!st->codec->extradata)
1541 return AVERROR(ENOMEM);
1542 st->codec->extradata_size = ALAC_EXTRADATA_SIZE;
1543 AV_WB32(st->codec->extradata , ALAC_EXTRADATA_SIZE);
1544 AV_WB32(st->codec->extradata + 4, MKTAG('a','l','a','c'));
1545 AV_WB64(st->codec->extradata + 12, buffer);
1546 avio_read(pb, st->codec->extradata + 20, 16);
1547 avio_skip(pb, atom.size - 24);
1551 if ((ret = mov_read_default(c, pb, atom)) < 0)
1554 avio_skip(pb, atom.size);
1559 * This function reads atom content and puts data in extradata without tag
1560 * nor size unlike mov_read_extradata.
1562 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1567 if (c->fc->nb_streams < 1)
1569 st = c->fc->streams[c->fc->nb_streams-1];
1571 if ((uint64_t)atom.size > (1<<30))
1572 return AVERROR_INVALIDDATA;
1574 if (atom.size >= 10) {
1575 // Broken files created by legacy versions of libavformat will
1576 // wrap a whole fiel atom inside of a glbl atom.
1577 unsigned size = avio_rb32(pb);
1578 unsigned type = avio_rl32(pb);
1579 avio_seek(pb, -8, SEEK_CUR);
1580 if (type == MKTAG('f','i','e','l') && size == atom.size)
1581 return mov_read_default(c, pb, atom);
1583 if (st->codec->extradata_size > 1 && st->codec->extradata) {
1584 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1587 av_freep(&st->codec->extradata);
1588 ret = ff_get_extradata(st->codec, pb, atom.size);
1595 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1598 uint8_t profile_level;
1601 if (c->fc->nb_streams < 1)
1603 st = c->fc->streams[c->fc->nb_streams-1];
1605 if (atom.size >= (1<<28) || atom.size < 7)
1606 return AVERROR_INVALIDDATA;
1608 profile_level = avio_r8(pb);
1609 if ((profile_level & 0xf0) != 0xc0)
1612 avio_seek(pb, 6, SEEK_CUR);
1613 av_freep(&st->codec->extradata);
1614 ret = ff_get_extradata(st->codec, pb, atom.size - 7);
1622 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1623 * but can have extradata appended at the end after the 40 bytes belonging
1626 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1631 if (c->fc->nb_streams < 1)
1633 if (atom.size <= 40)
1635 st = c->fc->streams[c->fc->nb_streams-1];
1637 if ((uint64_t)atom.size > (1<<30))
1638 return AVERROR_INVALIDDATA;
1641 av_freep(&st->codec->extradata);
1642 ret = ff_get_extradata(st->codec, pb, atom.size - 40);
1649 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1652 MOVStreamContext *sc;
1653 unsigned int i, entries;
1655 if (c->fc->nb_streams < 1)
1657 st = c->fc->streams[c->fc->nb_streams-1];
1660 avio_r8(pb); /* version */
1661 avio_rb24(pb); /* flags */
1663 entries = avio_rb32(pb);
1668 if (sc->chunk_offsets)
1669 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1670 av_free(sc->chunk_offsets);
1671 sc->chunk_count = 0;
1672 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1673 if (!sc->chunk_offsets)
1674 return AVERROR(ENOMEM);
1675 sc->chunk_count = entries;
1677 if (atom.type == MKTAG('s','t','c','o'))
1678 for (i = 0; i < entries && !pb->eof_reached; i++)
1679 sc->chunk_offsets[i] = avio_rb32(pb);
1680 else if (atom.type == MKTAG('c','o','6','4'))
1681 for (i = 0; i < entries && !pb->eof_reached; i++)
1682 sc->chunk_offsets[i] = avio_rb64(pb);
1684 return AVERROR_INVALIDDATA;
1686 sc->chunk_count = i;
1688 if (pb->eof_reached)
1695 * Compute codec id for 'lpcm' tag.
1696 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1698 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1705 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1708 static int mov_codec_id(AVStream *st, uint32_t format)
1710 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1713 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1714 (format & 0xFFFF) == 'T' + ('S' << 8)))
1715 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1717 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1718 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1719 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1720 /* skip old asf mpeg4 tag */
1721 format && format != MKTAG('m','p','4','s')) {
1722 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1724 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1726 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1727 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1728 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1729 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1730 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1732 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1736 st->codec->codec_tag = format;
1741 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1742 AVStream *st, MOVStreamContext *sc)
1744 uint8_t codec_name[32];
1745 unsigned int color_depth, len, j;
1746 int color_greyscale;
1749 avio_rb16(pb); /* version */
1750 avio_rb16(pb); /* revision level */
1751 avio_rb32(pb); /* vendor */
1752 avio_rb32(pb); /* temporal quality */
1753 avio_rb32(pb); /* spatial quality */
1755 st->codec->width = avio_rb16(pb); /* width */
1756 st->codec->height = avio_rb16(pb); /* height */
1758 avio_rb32(pb); /* horiz resolution */
1759 avio_rb32(pb); /* vert resolution */
1760 avio_rb32(pb); /* data size, always 0 */
1761 avio_rb16(pb); /* frames per samples */
1763 len = avio_r8(pb); /* codec name, pascal string */
1766 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1768 avio_skip(pb, 31 - len);
1771 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1773 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1774 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1775 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1776 st->codec->width &= ~1;
1777 st->codec->height &= ~1;
1779 /* Flash Media Server uses tag H263 with Sorenson Spark */
1780 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1781 !memcmp(codec_name, "Sorenson H263", 13))
1782 st->codec->codec_id = AV_CODEC_ID_FLV1;
1784 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1785 color_table_id = avio_rb16(pb); /* colortable id */
1786 av_log(c->fc, AV_LOG_TRACE, "depth %d, ctab id %d\n",
1787 st->codec->bits_per_coded_sample, color_table_id);
1788 /* figure out the palette situation */
1789 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1790 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1791 /* Do not create a greyscale palette for cinepak */
1792 if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1795 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1796 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1797 /* for palette traversal */
1798 unsigned int color_start, color_count, color_end;
1799 unsigned int a, r, g, b;
1801 if (color_greyscale) {
1802 int color_index, color_dec;
1803 /* compute the greyscale palette */
1804 st->codec->bits_per_coded_sample = color_depth;
1805 color_count = 1 << color_depth;
1807 color_dec = 256 / (color_count - 1);
1808 for (j = 0; j < color_count; j++) {
1809 r = g = b = color_index;
1810 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1811 color_index -= color_dec;
1812 if (color_index < 0)
1815 } else if (color_table_id) {
1816 const uint8_t *color_table;
1817 /* if flag bit 3 is set, use the default palette */
1818 color_count = 1 << color_depth;
1819 if (color_depth == 2)
1820 color_table = ff_qt_default_palette_4;
1821 else if (color_depth == 4)
1822 color_table = ff_qt_default_palette_16;
1824 color_table = ff_qt_default_palette_256;
1826 for (j = 0; j < color_count; j++) {
1827 r = color_table[j * 3 + 0];
1828 g = color_table[j * 3 + 1];
1829 b = color_table[j * 3 + 2];
1830 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1833 /* load the palette from the file */
1834 color_start = avio_rb32(pb);
1835 color_count = avio_rb16(pb);
1836 color_end = avio_rb16(pb);
1837 if ((color_start <= 255) && (color_end <= 255)) {
1838 for (j = color_start; j <= color_end; j++) {
1839 /* each A, R, G, or B component is 16 bits;
1840 * only use the top 8 bits */
1849 sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1853 sc->has_palette = 1;
1857 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1858 AVStream *st, MOVStreamContext *sc)
1860 int bits_per_sample, flags;
1861 uint16_t version = avio_rb16(pb);
1862 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1864 avio_rb16(pb); /* revision level */
1865 avio_rb32(pb); /* vendor */
1867 st->codec->channels = avio_rb16(pb); /* channel count */
1868 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1869 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codec->channels);
1871 sc->audio_cid = avio_rb16(pb);
1872 avio_rb16(pb); /* packet size = 0 */
1874 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1876 // Read QT version 1 fields. In version 0 these do not exist.
1877 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1879 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1882 sc->samples_per_frame = avio_rb32(pb);
1883 avio_rb32(pb); /* bytes per packet */
1884 sc->bytes_per_frame = avio_rb32(pb);
1885 avio_rb32(pb); /* bytes per sample */
1886 } else if (version == 2) {
1887 avio_rb32(pb); /* sizeof struct only */
1888 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1889 st->codec->channels = avio_rb32(pb);
1890 avio_rb32(pb); /* always 0x7F000000 */
1891 st->codec->bits_per_coded_sample = avio_rb32(pb);
1893 flags = avio_rb32(pb); /* lpcm format specific flag */
1894 sc->bytes_per_frame = avio_rb32(pb);
1895 sc->samples_per_frame = avio_rb32(pb);
1896 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1897 st->codec->codec_id =
1898 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1901 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1902 /* can't correctly handle variable sized packet as audio unit */
1903 switch (st->codec->codec_id) {
1904 case AV_CODEC_ID_MP2:
1905 case AV_CODEC_ID_MP3:
1906 st->need_parsing = AVSTREAM_PARSE_FULL;
1912 switch (st->codec->codec_id) {
1913 case AV_CODEC_ID_PCM_S8:
1914 case AV_CODEC_ID_PCM_U8:
1915 if (st->codec->bits_per_coded_sample == 16)
1916 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1918 case AV_CODEC_ID_PCM_S16LE:
1919 case AV_CODEC_ID_PCM_S16BE:
1920 if (st->codec->bits_per_coded_sample == 8)
1921 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1922 else if (st->codec->bits_per_coded_sample == 24)
1923 st->codec->codec_id =
1924 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1925 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1926 else if (st->codec->bits_per_coded_sample == 32)
1927 st->codec->codec_id =
1928 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1929 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1931 /* set values for old format before stsd version 1 appeared */
1932 case AV_CODEC_ID_MACE3:
1933 sc->samples_per_frame = 6;
1934 sc->bytes_per_frame = 2 * st->codec->channels;
1936 case AV_CODEC_ID_MACE6:
1937 sc->samples_per_frame = 6;
1938 sc->bytes_per_frame = 1 * st->codec->channels;
1940 case AV_CODEC_ID_ADPCM_IMA_QT:
1941 sc->samples_per_frame = 64;
1942 sc->bytes_per_frame = 34 * st->codec->channels;
1944 case AV_CODEC_ID_GSM:
1945 sc->samples_per_frame = 160;
1946 sc->bytes_per_frame = 33;
1952 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1953 if (bits_per_sample) {
1954 st->codec->bits_per_coded_sample = bits_per_sample;
1955 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1959 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1960 AVStream *st, MOVStreamContext *sc,
1963 // ttxt stsd contains display flags, justification, background
1964 // color, fonts, and default styles, so fake an atom to read it
1965 MOVAtom fake_atom = { .size = size };
1966 // mp4s contains a regular esds atom
1967 if (st->codec->codec_tag != AV_RL32("mp4s"))
1968 mov_read_glbl(c, pb, fake_atom);
1969 st->codec->width = sc->width;
1970 st->codec->height = sc->height;
1973 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1978 y = (ycbcr >> 16) & 0xFF;
1979 cr = (ycbcr >> 8) & 0xFF;
1982 b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
1983 g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
1984 r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
1986 return (r << 16) | (g << 8) | b;
1989 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1991 char buf[256] = {0};
1992 uint8_t *src = st->codec->extradata;
1995 if (st->codec->extradata_size != 64)
1998 if (st->codec->width > 0 && st->codec->height > 0)
1999 snprintf(buf, sizeof(buf), "size: %dx%d\n",
2000 st->codec->width, st->codec->height);
2001 av_strlcat(buf, "palette: ", sizeof(buf));
2003 for (i = 0; i < 16; i++) {
2004 uint32_t yuv = AV_RB32(src + i * 4);
2005 uint32_t rgba = yuv_to_rgba(yuv);
2007 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2010 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2013 av_freep(&st->codec->extradata);
2014 st->codec->extradata_size = 0;
2015 st->codec->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
2016 if (!st->codec->extradata)
2017 return AVERROR(ENOMEM);
2018 st->codec->extradata_size = strlen(buf);
2019 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
2024 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2025 AVStream *st, MOVStreamContext *sc,
2030 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
2031 if ((int)size != size)
2032 return AVERROR(ENOMEM);
2034 ret = ff_get_extradata(st->codec, pb, size);
2038 MOVStreamContext *tmcd_ctx = st->priv_data;
2040 val = AV_RB32(st->codec->extradata + 4);
2041 tmcd_ctx->tmcd_flags = val;
2043 st->codec->flags2 |= AV_CODEC_FLAG2_DROP_FRAME_TIMECODE;
2044 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
2045 st->codec->time_base.num = 1;
2046 /* adjust for per frame dur in counter mode */
2047 if (tmcd_ctx->tmcd_flags & 0x0008) {
2048 int timescale = AV_RB32(st->codec->extradata + 8);
2049 int framedur = AV_RB32(st->codec->extradata + 12);
2050 st->codec->time_base.den *= timescale;
2051 st->codec->time_base.num *= framedur;
2054 uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
2055 uint32_t format = AV_RB32(st->codec->extradata + 22);
2056 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2057 uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
2058 if (str_size > 0 && size >= (int)str_size + 26) {
2059 char *reel_name = av_malloc(str_size + 1);
2061 return AVERROR(ENOMEM);
2062 memcpy(reel_name, st->codec->extradata + 30, str_size);
2063 reel_name[str_size] = 0; /* Add null terminator */
2064 /* don't add reel_name if emtpy string */
2065 if (*reel_name == 0) {
2068 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2075 /* other codec type, just skip (rtp, mp4s ...) */
2076 avio_skip(pb, size);
2081 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2082 AVStream *st, MOVStreamContext *sc)
2084 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2085 !st->codec->sample_rate && sc->time_scale > 1)
2086 st->codec->sample_rate = sc->time_scale;
2088 /* special codec parameters handling */
2089 switch (st->codec->codec_id) {
2090 #if CONFIG_DV_DEMUXER
2091 case AV_CODEC_ID_DVAUDIO:
2092 c->dv_fctx = avformat_alloc_context();
2094 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2095 return AVERROR(ENOMEM);
2097 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2099 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2100 return AVERROR(ENOMEM);
2102 sc->dv_audio_container = 1;
2103 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
2106 /* no ifdef since parameters are always those */
2107 case AV_CODEC_ID_QCELP:
2108 st->codec->channels = 1;
2109 // force sample rate for qcelp when not stored in mov
2110 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
2111 st->codec->sample_rate = 8000;
2112 // FIXME: Why is the following needed for some files?
2113 sc->samples_per_frame = 160;
2114 if (!sc->bytes_per_frame)
2115 sc->bytes_per_frame = 35;
2117 case AV_CODEC_ID_AMR_NB:
2118 st->codec->channels = 1;
2119 /* force sample rate for amr, stsd in 3gp does not store sample rate */
2120 st->codec->sample_rate = 8000;
2122 case AV_CODEC_ID_AMR_WB:
2123 st->codec->channels = 1;
2124 st->codec->sample_rate = 16000;
2126 case AV_CODEC_ID_MP2:
2127 case AV_CODEC_ID_MP3:
2128 /* force type after stsd for m1a hdlr */
2129 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
2131 case AV_CODEC_ID_GSM:
2132 case AV_CODEC_ID_ADPCM_MS:
2133 case AV_CODEC_ID_ADPCM_IMA_WAV:
2134 case AV_CODEC_ID_ILBC:
2135 case AV_CODEC_ID_MACE3:
2136 case AV_CODEC_ID_MACE6:
2137 case AV_CODEC_ID_QDM2:
2138 st->codec->block_align = sc->bytes_per_frame;
2140 case AV_CODEC_ID_ALAC:
2141 if (st->codec->extradata_size == 36) {
2142 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
2143 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
2146 case AV_CODEC_ID_AC3:
2147 case AV_CODEC_ID_EAC3:
2148 case AV_CODEC_ID_MPEG1VIDEO:
2149 case AV_CODEC_ID_VC1:
2150 st->need_parsing = AVSTREAM_PARSE_FULL;
2158 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2159 int codec_tag, int format,
2162 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2165 (codec_tag != format &&
2166 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2167 : codec_tag != MKTAG('j','p','e','g')))) {
2168 /* Multiple fourcc, we skip JPEG. This is not correct, we should
2169 * export it as a separate AVStream but this needs a few changes
2170 * in the MOV demuxer, patch welcome. */
2172 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2173 avio_skip(pb, size);
2176 if ( codec_tag == AV_RL32("avc1") ||
2177 codec_tag == AV_RL32("hvc1") ||
2178 codec_tag == AV_RL32("hev1")
2180 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
2185 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2188 MOVStreamContext *sc;
2189 int pseudo_stream_id;
2191 if (c->fc->nb_streams < 1)
2193 st = c->fc->streams[c->fc->nb_streams-1];
2196 for (pseudo_stream_id = 0;
2197 pseudo_stream_id < entries && !pb->eof_reached;
2198 pseudo_stream_id++) {
2199 //Parsing Sample description table
2201 int ret, dref_id = 1;
2202 MOVAtom a = { AV_RL32("stsd") };
2203 int64_t start_pos = avio_tell(pb);
2204 int64_t size = avio_rb32(pb); /* size */
2205 uint32_t format = avio_rl32(pb); /* data format */
2208 avio_rb32(pb); /* reserved */
2209 avio_rb16(pb); /* reserved */
2210 dref_id = avio_rb16(pb);
2211 }else if (size <= 7){
2212 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
2213 return AVERROR_INVALIDDATA;
2216 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
2217 size - (avio_tell(pb) - start_pos)))
2220 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
2221 sc->dref_id= dref_id;
2223 id = mov_codec_id(st, format);
2225 av_log(c->fc, AV_LOG_TRACE,
2226 "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
2227 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
2228 (format >> 24) & 0xff, format, st->codec->codec_type);
2230 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
2231 st->codec->codec_id = id;
2232 mov_parse_stsd_video(c, pb, st, sc);
2233 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
2234 st->codec->codec_id = id;
2235 mov_parse_stsd_audio(c, pb, st, sc);
2236 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
2237 st->codec->codec_id = id;
2238 mov_parse_stsd_subtitle(c, pb, st, sc,
2239 size - (avio_tell(pb) - start_pos));
2241 ret = mov_parse_stsd_data(c, pb, st, sc,
2242 size - (avio_tell(pb) - start_pos));
2246 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2247 a.size = size - (avio_tell(pb) - start_pos);
2249 if ((ret = mov_read_default(c, pb, a)) < 0)
2251 } else if (a.size > 0)
2252 avio_skip(pb, a.size);
2255 if (pb->eof_reached)
2258 return mov_finalize_stsd_codec(c, pb, st, sc);
2261 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2265 avio_r8(pb); /* version */
2266 avio_rb24(pb); /* flags */
2267 entries = avio_rb32(pb);
2269 return ff_mov_read_stsd_entries(c, pb, entries);
2272 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2275 MOVStreamContext *sc;
2276 unsigned int i, entries;
2278 if (c->fc->nb_streams < 1)
2280 st = c->fc->streams[c->fc->nb_streams-1];
2283 avio_r8(pb); /* version */
2284 avio_rb24(pb); /* flags */
2286 entries = avio_rb32(pb);
2288 av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
2293 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2294 av_free(sc->stsc_data);
2296 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2298 return AVERROR(ENOMEM);
2300 for (i = 0; i < entries && !pb->eof_reached; i++) {
2301 sc->stsc_data[i].first = avio_rb32(pb);
2302 sc->stsc_data[i].count = avio_rb32(pb);
2303 sc->stsc_data[i].id = avio_rb32(pb);
2308 if (pb->eof_reached)
2314 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2317 MOVStreamContext *sc;
2318 unsigned i, entries;
2320 if (c->fc->nb_streams < 1)
2322 st = c->fc->streams[c->fc->nb_streams-1];
2325 avio_rb32(pb); // version + flags
2327 entries = avio_rb32(pb);
2329 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2330 av_free(sc->stps_data);
2332 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2334 return AVERROR(ENOMEM);
2336 for (i = 0; i < entries && !pb->eof_reached; i++) {
2337 sc->stps_data[i] = avio_rb32(pb);
2338 //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
2343 if (pb->eof_reached)
2349 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2352 MOVStreamContext *sc;
2353 unsigned int i, entries;
2355 if (c->fc->nb_streams < 1)
2357 st = c->fc->streams[c->fc->nb_streams-1];
2360 avio_r8(pb); /* version */
2361 avio_rb24(pb); /* flags */
2363 entries = avio_rb32(pb);
2365 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
2369 sc->keyframe_absent = 1;
2370 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2371 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2375 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2376 if (entries >= UINT_MAX / sizeof(int))
2377 return AVERROR_INVALIDDATA;
2378 av_freep(&sc->keyframes);
2379 sc->keyframe_count = 0;
2380 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2382 return AVERROR(ENOMEM);
2384 for (i = 0; i < entries && !pb->eof_reached; i++) {
2385 sc->keyframes[i] = avio_rb32(pb);
2386 //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
2389 sc->keyframe_count = i;
2391 if (pb->eof_reached)
2397 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2400 MOVStreamContext *sc;
2401 unsigned int i, entries, sample_size, field_size, num_bytes;
2406 if (c->fc->nb_streams < 1)
2408 st = c->fc->streams[c->fc->nb_streams-1];
2411 avio_r8(pb); /* version */
2412 avio_rb24(pb); /* flags */
2414 if (atom.type == MKTAG('s','t','s','z')) {
2415 sample_size = avio_rb32(pb);
2416 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2417 sc->sample_size = sample_size;
2418 sc->stsz_sample_size = sample_size;
2422 avio_rb24(pb); /* reserved */
2423 field_size = avio_r8(pb);
2425 entries = avio_rb32(pb);
2427 av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2429 sc->sample_count = entries;
2433 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2434 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2435 return AVERROR_INVALIDDATA;
2440 if (entries >= (UINT_MAX - 4) / field_size)
2441 return AVERROR_INVALIDDATA;
2442 if (sc->sample_sizes)
2443 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2444 av_free(sc->sample_sizes);
2445 sc->sample_count = 0;
2446 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2447 if (!sc->sample_sizes)
2448 return AVERROR(ENOMEM);
2450 num_bytes = (entries*field_size+4)>>3;
2452 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2454 av_freep(&sc->sample_sizes);
2455 return AVERROR(ENOMEM);
2458 ret = ffio_read_size(pb, buf, num_bytes);
2460 av_freep(&sc->sample_sizes);
2465 init_get_bits(&gb, buf, 8*num_bytes);
2467 for (i = 0; i < entries && !pb->eof_reached; i++) {
2468 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2469 sc->data_size += sc->sample_sizes[i];
2472 sc->sample_count = i;
2476 if (pb->eof_reached)
2482 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2485 MOVStreamContext *sc;
2486 unsigned int i, entries;
2488 int64_t total_sample_count=0;
2490 if (c->fc->nb_streams < 1)
2492 st = c->fc->streams[c->fc->nb_streams-1];
2495 avio_r8(pb); /* version */
2496 avio_rb24(pb); /* flags */
2497 entries = avio_rb32(pb);
2499 av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2500 c->fc->nb_streams-1, entries);
2503 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2504 av_free(sc->stts_data);
2506 sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2508 return AVERROR(ENOMEM);
2510 for (i = 0; i < entries && !pb->eof_reached; i++) {
2511 int sample_duration;
2514 sample_count=avio_rb32(pb);
2515 sample_duration = avio_rb32(pb);
2517 if (sample_count < 0) {
2518 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2519 return AVERROR_INVALIDDATA;
2521 sc->stts_data[i].count= sample_count;
2522 sc->stts_data[i].duration= sample_duration;
2524 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2525 sample_count, sample_duration);
2529 && sample_count == 1
2530 && total_sample_count > 100
2531 && sample_duration/10 > duration / total_sample_count)
2532 sample_duration = duration / total_sample_count;
2533 duration+=(int64_t)sample_duration*sample_count;
2534 total_sample_count+=sample_count;
2539 sc->duration_for_fps += duration;
2540 sc->nb_frames_for_fps += total_sample_count;
2542 if (pb->eof_reached)
2545 st->nb_frames= total_sample_count;
2547 st->duration= duration;
2548 sc->track_end = duration;
2552 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2555 if (duration == INT_MIN) {
2556 av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2559 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2563 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2566 MOVStreamContext *sc;
2567 unsigned int i, entries;
2569 if (c->fc->nb_streams < 1)
2571 st = c->fc->streams[c->fc->nb_streams-1];
2574 avio_r8(pb); /* version */
2575 avio_rb24(pb); /* flags */
2576 entries = avio_rb32(pb);
2578 av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2582 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2583 return AVERROR_INVALIDDATA;
2584 av_freep(&sc->ctts_data);
2585 sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2587 return AVERROR(ENOMEM);
2589 for (i = 0; i < entries && !pb->eof_reached; i++) {
2590 int count =avio_rb32(pb);
2591 int duration =avio_rb32(pb);
2593 sc->ctts_data[i].count = count;
2594 sc->ctts_data[i].duration= duration;
2596 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2599 if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2600 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2601 av_freep(&sc->ctts_data);
2607 mov_update_dts_shift(sc, duration);
2612 if (pb->eof_reached)
2615 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2620 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2623 MOVStreamContext *sc;
2624 unsigned int i, entries;
2626 uint32_t grouping_type;
2628 if (c->fc->nb_streams < 1)
2630 st = c->fc->streams[c->fc->nb_streams-1];
2633 version = avio_r8(pb); /* version */
2634 avio_rb24(pb); /* flags */
2635 grouping_type = avio_rl32(pb);
2636 if (grouping_type != MKTAG( 'r','a','p',' '))
2637 return 0; /* only support 'rap ' grouping */
2639 avio_rb32(pb); /* grouping_type_parameter */
2641 entries = avio_rb32(pb);
2645 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2646 av_free(sc->rap_group);
2647 sc->rap_group_count = 0;
2648 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2650 return AVERROR(ENOMEM);
2652 for (i = 0; i < entries && !pb->eof_reached; i++) {
2653 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2654 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2657 sc->rap_group_count = i;
2659 return pb->eof_reached ? AVERROR_EOF : 0;
2662 static void mov_build_index(MOVContext *mov, AVStream *st)
2664 MOVStreamContext *sc = st->priv_data;
2665 int64_t current_offset;
2666 int64_t current_dts = 0;
2667 unsigned int stts_index = 0;
2668 unsigned int stsc_index = 0;
2669 unsigned int stss_index = 0;
2670 unsigned int stps_index = 0;
2672 uint64_t stream_size = 0;
2674 if (sc->elst_count) {
2675 int i, edit_start_index = 0, unsupported = 0;
2676 int64_t empty_duration = 0; // empty duration of the first edit list entry
2677 int64_t start_time = 0; // start time of the media
2679 for (i = 0; i < sc->elst_count; i++) {
2680 const MOVElst *e = &sc->elst_data[i];
2681 if (i == 0 && e->time == -1) {
2682 /* if empty, the first entry is the start time of the stream
2683 * relative to the presentation itself */
2684 empty_duration = e->duration;
2685 edit_start_index = 1;
2686 } else if (i == edit_start_index && e->time >= 0) {
2687 start_time = e->time;
2692 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
2693 "a/v desync might occur, patch welcome\n");
2695 /* adjust first dts according to edit list */
2696 if ((empty_duration || start_time) && mov->time_scale > 0) {
2698 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
2699 sc->time_offset = start_time - empty_duration;
2700 current_dts = -sc->time_offset;
2701 if (sc->ctts_count>0 && sc->stts_count>0 &&
2702 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2703 /* more than 16 frames delay, dts are likely wrong
2704 this happens with files created by iMovie */
2706 st->codec->has_b_frames = 1;
2711 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2712 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2713 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2714 unsigned int current_sample = 0;
2715 unsigned int stts_sample = 0;
2716 unsigned int sample_size;
2717 unsigned int distance = 0;
2718 unsigned int rap_group_index = 0;
2719 unsigned int rap_group_sample = 0;
2720 int64_t last_dts = 0;
2721 int64_t dts_correction = 0;
2722 int rap_group_present = sc->rap_group_count && sc->rap_group;
2723 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2725 current_dts -= sc->dts_shift;
2726 last_dts = current_dts;
2728 if (!sc->sample_count || st->nb_index_entries)
2730 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2732 if (av_reallocp_array(&st->index_entries,
2733 st->nb_index_entries + sc->sample_count,
2734 sizeof(*st->index_entries)) < 0) {
2735 st->nb_index_entries = 0;
2738 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2740 for (i = 0; i < sc->chunk_count; i++) {
2741 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2742 current_offset = sc->chunk_offsets[i];
2743 while (stsc_index + 1 < sc->stsc_count &&
2744 i + 1 == sc->stsc_data[stsc_index + 1].first)
2747 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2748 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2749 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2750 sc->stsz_sample_size = sc->sample_size;
2752 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2753 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2754 sc->stsz_sample_size = sc->sample_size;
2757 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2759 if (current_sample >= sc->sample_count) {
2760 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2764 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2766 if (stss_index + 1 < sc->keyframe_count)
2768 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2770 if (stps_index + 1 < sc->stps_count)
2773 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2774 if (sc->rap_group[rap_group_index].index > 0)
2776 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2777 rap_group_sample = 0;
2781 if (sc->keyframe_absent
2783 && !rap_group_present
2784 && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2788 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2789 if (sc->pseudo_stream_id == -1 ||
2790 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2791 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2792 e->pos = current_offset;
2793 e->timestamp = current_dts;
2794 e->size = sample_size;
2795 e->min_distance = distance;
2796 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2797 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2798 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2799 current_offset, current_dts, sample_size, distance, keyframe);
2800 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2801 ff_rfps_add_frame(mov->fc, st, current_dts);
2804 current_offset += sample_size;
2805 stream_size += sample_size;
2807 /* A negative sample duration is invalid based on the spec,
2808 * but some samples need it to correct the DTS. */
2809 if (sc->stts_data[stts_index].duration < 0) {
2810 av_log(mov->fc, AV_LOG_WARNING,
2811 "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2812 sc->stts_data[stts_index].duration, stts_index,
2814 dts_correction += sc->stts_data[stts_index].duration - 1;
2815 sc->stts_data[stts_index].duration = 1;
2817 current_dts += sc->stts_data[stts_index].duration;
2818 if (!dts_correction || current_dts + dts_correction > last_dts) {
2819 current_dts += dts_correction;
2822 /* Avoid creating non-monotonous DTS */
2823 dts_correction += current_dts - last_dts - 1;
2824 current_dts = last_dts + 1;
2826 last_dts = current_dts;
2830 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2836 if (st->duration > 0)
2837 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2839 unsigned chunk_samples, total = 0;
2841 // compute total chunk count
2842 for (i = 0; i < sc->stsc_count; i++) {
2843 unsigned count, chunk_count;
2845 chunk_samples = sc->stsc_data[i].count;
2846 if (i != sc->stsc_count - 1 &&
2847 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2848 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2852 if (sc->samples_per_frame >= 160) { // gsm
2853 count = chunk_samples / sc->samples_per_frame;
2854 } else if (sc->samples_per_frame > 1) {
2855 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2856 count = (chunk_samples+samples-1) / samples;
2858 count = (chunk_samples+1023) / 1024;
2861 if (i < sc->stsc_count - 1)
2862 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2864 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2865 total += chunk_count * count;
2868 av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2869 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2871 if (av_reallocp_array(&st->index_entries,
2872 st->nb_index_entries + total,
2873 sizeof(*st->index_entries)) < 0) {
2874 st->nb_index_entries = 0;
2877 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2880 for (i = 0; i < sc->chunk_count; i++) {
2881 current_offset = sc->chunk_offsets[i];
2882 if (stsc_index + 1 < sc->stsc_count &&
2883 i + 1 == sc->stsc_data[stsc_index + 1].first)
2885 chunk_samples = sc->stsc_data[stsc_index].count;
2887 while (chunk_samples > 0) {
2889 unsigned size, samples;
2891 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2892 avpriv_request_sample(mov->fc,
2893 "Zero bytes per frame, but %d samples per frame",
2894 sc->samples_per_frame);
2898 if (sc->samples_per_frame >= 160) { // gsm
2899 samples = sc->samples_per_frame;
2900 size = sc->bytes_per_frame;
2902 if (sc->samples_per_frame > 1) {
2903 samples = FFMIN((1024 / sc->samples_per_frame)*
2904 sc->samples_per_frame, chunk_samples);
2905 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2907 samples = FFMIN(1024, chunk_samples);
2908 size = samples * sc->sample_size;
2912 if (st->nb_index_entries >= total) {
2913 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2916 e = &st->index_entries[st->nb_index_entries++];
2917 e->pos = current_offset;
2918 e->timestamp = current_dts;
2920 e->min_distance = 0;
2921 e->flags = AVINDEX_KEYFRAME;
2922 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2923 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2926 current_offset += size;
2927 current_dts += samples;
2928 chunk_samples -= samples;
2934 static int test_same_origin(const char *src, const char *ref) {
2944 av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
2945 av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
2947 if (strlen(src) == 0) {
2949 } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
2950 strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
2951 strlen(src_host) + 1 >= sizeof(src_host) ||
2952 strlen(ref_host) + 1 >= sizeof(ref_host)) {
2954 } else if (strcmp(src_proto, ref_proto) ||
2955 strcmp(src_auth, ref_auth) ||
2956 strcmp(src_host, ref_host) ||
2957 src_port != ref_port) {
2963 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref,
2964 AVIOInterruptCB *int_cb)
2966 AVOpenCallback open_func = c->fc->open_cb;
2969 open_func = ffio_open2_wrapper;
2971 /* try relative path, we do not try the absolute because it can leak information about our
2972 system to an attacker */
2973 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2974 char filename[1025];
2975 const char *src_path;
2978 /* find a source dir */
2979 src_path = strrchr(src, '/');
2985 /* find a next level down to target */
2986 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2987 if (ref->path[l] == '/') {
2988 if (i == ref->nlvl_to - 1)
2994 /* compose filename if next level down to target was found */
2995 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2996 memcpy(filename, src, src_path - src);
2997 filename[src_path - src] = 0;
2999 for (i = 1; i < ref->nlvl_from; i++)
3000 av_strlcat(filename, "../", sizeof(filename));
3002 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
3003 if (!c->use_absolute_path && !c->fc->open_cb) {
3004 int same_origin = test_same_origin(src, filename);
3007 av_log(c->fc, AV_LOG_ERROR,
3008 "Reference with mismatching origin, %s not tried for security reasons, "
3009 "set demuxer option use_absolute_path to allow it anyway\n",
3011 return AVERROR(ENOENT);
3014 if(strstr(ref->path + l + 1, "..") ||
3015 strstr(ref->path + l + 1, ":") ||
3016 (ref->nlvl_from > 1 && same_origin < 0) ||
3017 (filename[0] == '/' && src_path == src))
3018 return AVERROR(ENOENT);
3021 if (strlen(filename) + 1 == sizeof(filename))
3022 return AVERROR(ENOENT);
3023 if (!open_func(c->fc, pb, filename, AVIO_FLAG_READ, int_cb, NULL))
3026 } else if (c->use_absolute_path) {
3027 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
3028 "this is a possible security issue\n");
3029 if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
3031 } else if (c->fc->open_cb) {
3032 if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
3035 av_log(c->fc, AV_LOG_ERROR,
3036 "Absolute path %s not tried for security reasons, "
3037 "set demuxer option use_absolute_path to allow absolute paths\n",
3041 return AVERROR(ENOENT);
3044 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
3046 if (sc->time_scale <= 0) {
3047 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
3048 sc->time_scale = c->time_scale;
3049 if (sc->time_scale <= 0)
3054 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3057 MOVStreamContext *sc;
3060 st = avformat_new_stream(c->fc, NULL);
3061 if (!st) return AVERROR(ENOMEM);
3062 st->id = c->fc->nb_streams;
3063 sc = av_mallocz(sizeof(MOVStreamContext));
3064 if (!sc) return AVERROR(ENOMEM);
3067 st->codec->codec_type = AVMEDIA_TYPE_DATA;
3068 sc->ffindex = st->index;
3070 if ((ret = mov_read_default(c, pb, atom)) < 0)
3074 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
3075 (!sc->sample_size && !sc->sample_count))) {
3076 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
3081 fix_timescale(c, sc);
3083 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
3085 mov_build_index(c, st);
3087 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
3088 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
3089 if (mov_open_dref(c, &sc->pb, c->fc->filename, dref,
3090 &c->fc->interrupt_callback) < 0)
3091 av_log(c->fc, AV_LOG_ERROR,
3092 "stream %d, error opening alias: path='%s', dir='%s', "
3093 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
3094 st->index, dref->path, dref->dir, dref->filename,
3095 dref->volume, dref->nlvl_from, dref->nlvl_to);
3098 sc->pb_is_copied = 1;
3101 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3102 if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&
3103 sc->height && sc->width &&
3104 (st->codec->width != sc->width || st->codec->height != sc->height)) {
3105 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
3106 ((double)st->codec->width * sc->height), INT_MAX);
3109 #if FF_API_R_FRAME_RATE
3110 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
3111 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
3112 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
3116 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3117 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
3118 TAG_IS_AVCI(st->codec->codec_tag)) {
3119 ret = ff_generate_avci_extradata(st);
3124 switch (st->codec->codec_id) {
3125 #if CONFIG_H261_DECODER
3126 case AV_CODEC_ID_H261:
3128 #if CONFIG_H263_DECODER
3129 case AV_CODEC_ID_H263:
3131 #if CONFIG_MPEG4_DECODER
3132 case AV_CODEC_ID_MPEG4:
3134 st->codec->width = 0; /* let decoder init width/height */
3135 st->codec->height= 0;
3139 // If the duration of the mp3 packets is not constant, then they could need a parser
3140 if (st->codec->codec_id == AV_CODEC_ID_MP3
3141 && sc->stts_count > 3
3142 && sc->stts_count*10 > st->nb_frames
3143 && sc->time_scale == st->codec->sample_rate) {
3144 st->need_parsing = AVSTREAM_PARSE_FULL;
3146 /* Do not need those anymore. */
3147 av_freep(&sc->chunk_offsets);
3148 av_freep(&sc->stsc_data);
3149 av_freep(&sc->sample_sizes);
3150 av_freep(&sc->keyframes);
3151 av_freep(&sc->stts_data);
3152 av_freep(&sc->stps_data);
3153 av_freep(&sc->elst_data);
3154 av_freep(&sc->rap_group);
3159 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3162 c->itunes_metadata = 1;
3163 ret = mov_read_default(c, pb, atom);
3164 c->itunes_metadata = 0;
3168 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3177 count = avio_rb32(pb);
3178 if (count > UINT_MAX / sizeof(*c->meta_keys)) {
3179 av_log(c->fc, AV_LOG_ERROR,
3180 "The 'keys' atom with the invalid key count: %d\n", count);
3181 return AVERROR_INVALIDDATA;
3184 c->meta_keys_count = count + 1;
3185 c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
3187 return AVERROR(ENOMEM);
3189 for (i = 1; i <= count; ++i) {
3190 uint32_t key_size = avio_rb32(pb);
3191 uint32_t type = avio_rl32(pb);
3193 av_log(c->fc, AV_LOG_ERROR,
3194 "The key# %d in meta has invalid size: %d\n", i, key_size);
3195 return AVERROR_INVALIDDATA;
3198 if (type != MKTAG('m','d','t','a')) {
3199 avio_skip(pb, key_size);
3201 c->meta_keys[i] = av_mallocz(key_size + 1);
3202 if (!c->meta_keys[i])
3203 return AVERROR(ENOMEM);
3204 avio_read(pb, c->meta_keys[i], key_size);
3210 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
3212 int64_t end = avio_tell(pb) + size;
3213 uint8_t *key = NULL, *val = NULL;
3216 MOVStreamContext *sc;
3218 if (c->fc->nb_streams < 1)
3220 st = c->fc->streams[c->fc->nb_streams-1];
3223 for (i = 0; i < 2; i++) {
3228 if (end - avio_tell(pb) <= 12)
3231 len = avio_rb32(pb);
3232 tag = avio_rl32(pb);
3233 avio_skip(pb, 4); // flags
3235 if (len < 12 || len - 12 > end - avio_tell(pb))
3239 if (tag == MKTAG('n', 'a', 'm', 'e'))
3241 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
3248 *p = av_malloc(len + 1);
3251 ret = ffio_read_size(pb, *p, len);
3260 if (strcmp(key, "iTunSMPB") == 0) {
3261 int priming, remainder, samples;
3262 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
3263 if(priming>0 && priming<16384)
3264 sc->start_pad = priming;
3267 if (strcmp(key, "cdec") != 0) {
3268 av_dict_set(&c->fc->metadata, key, val,
3269 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
3274 avio_seek(pb, end, SEEK_SET);
3280 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3282 int64_t end = avio_tell(pb) + atom.size;
3288 len = avio_rb32(pb);
3289 tag = avio_rl32(pb);
3291 if (len > atom.size)
3294 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
3295 uint8_t domain[128];
3298 avio_skip(pb, 4); // flags
3301 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
3302 avio_skip(pb, len - domain_len);
3303 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
3307 av_log(c->fc, AV_LOG_VERBOSE,
3308 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
3312 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3314 while (atom.size > 8) {
3315 uint32_t tag = avio_rl32(pb);
3317 if (tag == MKTAG('h','d','l','r')) {
3318 avio_seek(pb, -8, SEEK_CUR);
3320 return mov_read_default(c, pb, atom);
3326 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3331 int display_matrix[3][3];
3333 MOVStreamContext *sc;
3337 if (c->fc->nb_streams < 1)
3339 st = c->fc->streams[c->fc->nb_streams-1];
3342 version = avio_r8(pb);
3343 flags = avio_rb24(pb);
3344 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
3350 avio_rb32(pb); /* creation time */
3351 avio_rb32(pb); /* modification time */
3353 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
3354 avio_rb32(pb); /* reserved */
3356 /* highlevel (considering edits) duration in movie timebase */
3357 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
3358 avio_rb32(pb); /* reserved */
3359 avio_rb32(pb); /* reserved */
3361 avio_rb16(pb); /* layer */
3362 avio_rb16(pb); /* alternate group */
3363 avio_rb16(pb); /* volume */
3364 avio_rb16(pb); /* reserved */
3366 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
3367 // they're kept in fixed point format through all calculations
3368 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
3369 // side data, but the scale factor is not needed to calculate aspect ratio
3370 for (i = 0; i < 3; i++) {
3371 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
3372 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
3373 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
3376 width = avio_rb32(pb); // 16.16 fixed point track width
3377 height = avio_rb32(pb); // 16.16 fixed point track height
3378 sc->width = width >> 16;
3379 sc->height = height >> 16;
3381 // save the matrix and add rotate metadata when it is not the default
3383 if (display_matrix[0][0] != (1 << 16) ||
3384 display_matrix[1][1] != (1 << 16) ||
3385 display_matrix[2][2] != (1 << 30) ||
3386 display_matrix[0][1] || display_matrix[0][2] ||
3387 display_matrix[1][0] || display_matrix[1][2] ||
3388 display_matrix[2][0] || display_matrix[2][1]) {
3392 av_freep(&sc->display_matrix);
3393 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
3394 if (!sc->display_matrix)
3395 return AVERROR(ENOMEM);
3397 for (i = 0; i < 3; i++)
3398 for (j = 0; j < 3; j++)
3399 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
3401 rotate = av_display_rotation_get(sc->display_matrix);
3402 if (!isnan(rotate)) {
3403 char rotate_buf[64];
3405 if (rotate < 0) // for backward compatibility
3407 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
3408 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
3412 // transform the display width/height according to the matrix
3413 // to keep the same scale, use [width height 1<<16]
3414 if (width && height && sc->display_matrix) {
3415 double disp_transform[2];
3417 #define SQR(a) ((a)*(double)(a))
3418 for (i = 0; i < 2; i++)
3419 disp_transform[i] = sqrt(SQR(display_matrix[i][0]) + SQR(display_matrix[i][1]));
3421 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
3422 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
3423 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
3424 st->sample_aspect_ratio = av_d2q(
3425 disp_transform[0] / disp_transform[1],
3431 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3433 MOVFragment *frag = &c->fragment;
3434 MOVTrackExt *trex = NULL;
3435 MOVFragmentIndex* index = NULL;
3436 int flags, track_id, i, found = 0;
3438 avio_r8(pb); /* version */
3439 flags = avio_rb24(pb);
3441 track_id = avio_rb32(pb);
3443 return AVERROR_INVALIDDATA;
3444 frag->track_id = track_id;
3445 for (i = 0; i < c->trex_count; i++)
3446 if (c->trex_data[i].track_id == frag->track_id) {
3447 trex = &c->trex_data[i];
3451 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
3452 return AVERROR_INVALIDDATA;
3455 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
3456 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
3457 frag->moof_offset : frag->implicit_offset;
3458 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
3460 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
3461 avio_rb32(pb) : trex->duration;
3462 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
3463 avio_rb32(pb) : trex->size;
3464 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
3465 avio_rb32(pb) : trex->flags;
3466 frag->time = AV_NOPTS_VALUE;
3467 for (i = 0; i < c->fragment_index_count; i++) {
3469 MOVFragmentIndex* candidate = c->fragment_index_data[i];
3470 if (candidate->track_id == frag->track_id) {
3471 av_log(c->fc, AV_LOG_DEBUG,
3472 "found fragment index for track %u\n", frag->track_id);
3474 for (j = index->current_item; j < index->item_count; j++) {
3475 if (frag->implicit_offset == index->items[j].moof_offset) {
3476 av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
3477 "for track %u and moof_offset %"PRId64"\n",
3478 frag->track_id, index->items[j].moof_offset);
3479 frag->time = index->items[j].time;
3480 index->current_item = j + 1;
3489 if (index && !found) {
3490 av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
3491 "it doesn't have an (in-order) entry for moof_offset "
3492 "%"PRId64"\n", frag->track_id, frag->implicit_offset);
3494 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
3498 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3500 c->chapter_track = avio_rb32(pb);
3504 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3509 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
3510 return AVERROR_INVALIDDATA;
3511 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
3512 sizeof(*c->trex_data))) < 0) {
3517 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
3519 trex = &c->trex_data[c->trex_count++];
3520 avio_r8(pb); /* version */
3521 avio_rb24(pb); /* flags */
3522 trex->track_id = avio_rb32(pb);
3523 trex->stsd_id = avio_rb32(pb);
3524 trex->duration = avio_rb32(pb);
3525 trex->size = avio_rb32(pb);
3526 trex->flags = avio_rb32(pb);
3530 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3532 MOVFragment *frag = &c->fragment;
3533 AVStream *st = NULL;
3534 MOVStreamContext *sc;
3537 for (i = 0; i < c->fc->nb_streams; i++) {
3538 if (c->fc->streams[i]->id == frag->track_id) {
3539 st = c->fc->streams[i];
3544 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3545 return AVERROR_INVALIDDATA;
3548 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
3550 version = avio_r8(pb);
3551 avio_rb24(pb); /* flags */
3553 sc->track_end = avio_rb64(pb);
3555 sc->track_end = avio_rb32(pb);
3560 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3562 MOVFragment *frag = &c->fragment;
3563 AVStream *st = NULL;
3564 MOVStreamContext *sc;
3568 int data_offset = 0;
3569 unsigned entries, first_sample_flags = frag->flags;
3570 int flags, distance, i, err;
3572 for (i = 0; i < c->fc->nb_streams; i++) {
3573 if (c->fc->streams[i]->id == frag->track_id) {
3574 st = c->fc->streams[i];
3579 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3580 return AVERROR_INVALIDDATA;
3583 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3585 avio_r8(pb); /* version */
3586 flags = avio_rb24(pb);
3587 entries = avio_rb32(pb);
3588 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
3590 /* Always assume the presence of composition time offsets.
3591 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3592 * 1) in the initial movie, there are no samples.
3593 * 2) in the first movie fragment, there is only one sample without composition time offset.
3594 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
3595 if (!sc->ctts_count && sc->sample_count)
3597 /* Complement ctts table if moov atom doesn't have ctts atom. */
3598 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3600 return AVERROR(ENOMEM);
3601 sc->ctts_data = ctts_data;
3602 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3603 sc->ctts_data[sc->ctts_count].duration = 0;
3606 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3607 return AVERROR_INVALIDDATA;
3608 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3609 sizeof(*sc->ctts_data))) < 0) {
3613 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
3614 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3615 dts = sc->track_end - sc->time_offset;
3616 offset = frag->base_data_offset + data_offset;
3618 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3619 for (i = 0; i < entries && !pb->eof_reached; i++) {
3620 unsigned sample_size = frag->size;
3621 int sample_flags = i ? frag->flags : first_sample_flags;
3622 unsigned sample_duration = frag->duration;
3625 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3626 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
3627 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
3628 sc->ctts_data[sc->ctts_count].count = 1;
3629 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3631 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
3632 if (frag->time != AV_NOPTS_VALUE) {
3633 if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3634 int64_t pts = frag->time;
3635 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3636 " sc->dts_shift %d ctts.duration %d"
3637 " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3638 sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3639 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3640 dts = pts - sc->dts_shift;
3641 if (flags & MOV_TRUN_SAMPLE_CTS) {
3642 dts -= sc->ctts_data[sc->ctts_count].duration;
3644 dts -= sc->time_offset;
3646 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3649 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3650 ", using it for dts\n", dts);
3652 frag->time = AV_NOPTS_VALUE;
3655 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3659 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3660 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3663 err = av_add_index_entry(st, offset, dts, sample_size, distance,
3664 keyframe ? AVINDEX_KEYFRAME : 0);
3666 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
3668 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3669 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3670 offset, dts, sample_size, distance, keyframe);
3672 dts += sample_duration;
3673 offset += sample_size;
3674 sc->data_size += sample_size;
3675 sc->duration_for_fps += sample_duration;
3676 sc->nb_frames_for_fps ++;
3679 if (pb->eof_reached)
3682 frag->implicit_offset = offset;
3684 sc->track_end = dts + sc->time_offset;
3685 if (st->duration < sc->track_end)
3686 st->duration = sc->track_end;
3691 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3693 int64_t offset = avio_tell(pb) + atom.size, pts;
3695 unsigned i, track_id;
3696 AVStream *st = NULL;
3697 MOVStreamContext *sc;
3698 MOVFragmentIndex *index = NULL;
3699 MOVFragmentIndex **tmp;
3700 AVRational timescale;
3702 version = avio_r8(pb);
3704 avpriv_request_sample(c->fc, "sidx version %u", version);
3705 return AVERROR_PATCHWELCOME;
3708 avio_rb24(pb); // flags
3710 track_id = avio_rb32(pb); // Reference ID
3711 for (i = 0; i < c->fc->nb_streams; i++) {
3712 if (c->fc->streams[i]->id == track_id) {
3713 st = c->fc->streams[i];
3718 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", track_id);
3719 return AVERROR_INVALIDDATA;
3724 timescale = av_make_q(1, avio_rb32(pb));
3727 pts = avio_rb32(pb);
3728 offset += avio_rb32(pb);
3730 pts = avio_rb64(pb);
3731 offset += avio_rb64(pb);
3734 avio_rb16(pb); // reserved
3736 index = av_mallocz(sizeof(MOVFragmentIndex));
3738 return AVERROR(ENOMEM);
3740 index->track_id = track_id;
3742 index->item_count = avio_rb16(pb);
3743 index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
3745 if (!index->items) {
3747 return AVERROR(ENOMEM);
3750 for (i = 0; i < index->item_count; i++) {
3751 uint32_t size = avio_rb32(pb);
3752 uint32_t duration = avio_rb32(pb);
3753 if (size & 0x80000000) {
3754 avpriv_request_sample(c->fc, "sidx reference_type 1");
3755 av_freep(&index->items);
3757 return AVERROR_PATCHWELCOME;
3759 avio_rb32(pb); // sap_flags
3760 index->items[i].moof_offset = offset;
3761 index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
3766 st->duration = sc->track_end = pts;
3768 tmp = av_realloc_array(c->fragment_index_data,
3769 c->fragment_index_count + 1,
3770 sizeof(MOVFragmentIndex*));
3772 av_freep(&index->items);
3774 return AVERROR(ENOMEM);
3777 c->fragment_index_data = tmp;
3778 c->fragment_index_data[c->fragment_index_count++] = index;
3780 if (offset == avio_size(pb))
3781 c->fragment_index_complete = 1;
3786 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3787 /* like the files created with Adobe Premiere 5.0, for samples see */
3788 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3789 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3794 return 0; /* continue */
3795 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3796 avio_skip(pb, atom.size - 4);
3799 atom.type = avio_rl32(pb);
3801 if (atom.type != MKTAG('m','d','a','t')) {
3802 avio_skip(pb, atom.size);
3805 err = mov_read_mdat(c, pb, atom);
3809 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3814 uint8_t *moov_data; /* uncompressed data */
3815 long cmov_len, moov_len;
3818 avio_rb32(pb); /* dcom atom */
3819 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3820 return AVERROR_INVALIDDATA;
3821 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3822 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3823 return AVERROR_INVALIDDATA;
3825 avio_rb32(pb); /* cmvd atom */
3826 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3827 return AVERROR_INVALIDDATA;
3828 moov_len = avio_rb32(pb); /* uncompressed size */
3829 cmov_len = atom.size - 6 * 4;
3831 cmov_data = av_malloc(cmov_len);
3833 return AVERROR(ENOMEM);
3834 moov_data = av_malloc(moov_len);
3837 return AVERROR(ENOMEM);
3839 ret = ffio_read_size(pb, cmov_data, cmov_len);
3841 goto free_and_return;
3843 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3844 goto free_and_return;
3845 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3846 goto free_and_return;
3847 ctx.seekable = AVIO_SEEKABLE_NORMAL;
3848 atom.type = MKTAG('m','o','o','v');
3849 atom.size = moov_len;
3850 ret = mov_read_default(c, &ctx, atom);
3856 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3857 return AVERROR(ENOSYS);
3861 /* edit list atom */
3862 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3864 MOVStreamContext *sc;
3865 int i, edit_count, version;
3867 if (c->fc->nb_streams < 1 || c->ignore_editlist)
3869 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3871 version = avio_r8(pb); /* version */
3872 avio_rb24(pb); /* flags */
3873 edit_count = avio_rb32(pb); /* entries */
3878 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
3879 av_free(sc->elst_data);
3881 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
3883 return AVERROR(ENOMEM);
3885 av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3886 for (i = 0; i < edit_count && !pb->eof_reached; i++) {
3887 MOVElst *e = &sc->elst_data[i];
3890 e->duration = avio_rb64(pb);
3891 e->time = avio_rb64(pb);
3893 e->duration = avio_rb32(pb); /* segment duration */
3894 e->time = (int32_t)avio_rb32(pb); /* media time */
3896 e->rate = avio_rb32(pb) / 65536.0;
3897 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3898 e->duration, e->time, e->rate);
3905 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3907 MOVStreamContext *sc;
3909 if (c->fc->nb_streams < 1)
3910 return AVERROR_INVALIDDATA;
3911 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3912 sc->timecode_track = avio_rb32(pb);
3916 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3920 static const uint8_t uuid_isml_manifest[] = {
3921 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3922 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3925 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3926 return AVERROR_INVALIDDATA;
3928 ret = avio_read(pb, uuid, sizeof(uuid));
3931 } else if (ret != sizeof(uuid)) {
3932 return AVERROR_INVALIDDATA;
3934 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3935 uint8_t *buffer, *ptr;
3937 size_t len = atom.size - sizeof(uuid);
3940 return AVERROR_INVALIDDATA;
3942 ret = avio_skip(pb, 4); // zeroes
3945 buffer = av_mallocz(len + 1);
3947 return AVERROR(ENOMEM);
3949 ret = avio_read(pb, buffer, len);
3953 } else if (ret != len) {
3955 return AVERROR_INVALIDDATA;
3959 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
3960 ptr += sizeof("systemBitrate=\"") - 1;
3961 c->bitrates_count++;
3962 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3964 c->bitrates_count = 0;
3966 return AVERROR(ENOMEM);
3969 ret = strtol(ptr, &endptr, 10);
3970 if (ret < 0 || errno || *endptr != '"') {
3971 c->bitrates[c->bitrates_count - 1] = 0;
3973 c->bitrates[c->bitrates_count - 1] = ret;
3982 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3985 uint8_t content[16];
3990 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
3996 && !memcmp(content, "Anevia\x1A\x1A", 8)
3997 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
3998 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
4004 static const MOVParseTableEntry mov_default_parse_table[] = {
4005 { MKTAG('A','C','L','R'), mov_read_aclr },
4006 { MKTAG('A','P','R','G'), mov_read_avid },
4007 { MKTAG('A','A','L','P'), mov_read_avid },
4008 { MKTAG('A','R','E','S'), mov_read_ares },
4009 { MKTAG('a','v','s','s'), mov_read_avss },
4010 { MKTAG('c','h','p','l'), mov_read_chpl },
4011 { MKTAG('c','o','6','4'), mov_read_stco },
4012 { MKTAG('c','o','l','r'), mov_read_colr },
4013 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
4014 { MKTAG('d','i','n','f'), mov_read_default },
4015 { MKTAG('D','p','x','E'), mov_read_dpxe },
4016 { MKTAG('d','r','e','f'), mov_read_dref },
4017 { MKTAG('e','d','t','s'), mov_read_default },
4018 { MKTAG('e','l','s','t'), mov_read_elst },
4019 { MKTAG('e','n','d','a'), mov_read_enda },
4020 { MKTAG('f','i','e','l'), mov_read_fiel },
4021 { MKTAG('a','d','r','m'), mov_read_adrm },
4022 { MKTAG('f','t','y','p'), mov_read_ftyp },
4023 { MKTAG('g','l','b','l'), mov_read_glbl },
4024 { MKTAG('h','d','l','r'), mov_read_hdlr },
4025 { MKTAG('i','l','s','t'), mov_read_ilst },
4026 { MKTAG('j','p','2','h'), mov_read_jp2h },
4027 { MKTAG('m','d','a','t'), mov_read_mdat },
4028 { MKTAG('m','d','h','d'), mov_read_mdhd },
4029 { MKTAG('m','d','i','a'), mov_read_default },
4030 { MKTAG('m','e','t','a'), mov_read_meta },
4031 { MKTAG('m','i','n','f'), mov_read_default },
4032 { MKTAG('m','o','o','f'), mov_read_moof },
4033 { MKTAG('m','o','o','v'), mov_read_moov },
4034 { MKTAG('m','v','e','x'), mov_read_default },
4035 { MKTAG('m','v','h','d'), mov_read_mvhd },
4036 { MKTAG('S','M','I',' '), mov_read_svq3 },
4037 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
4038 { MKTAG('a','v','c','C'), mov_read_glbl },
4039 { MKTAG('p','a','s','p'), mov_read_pasp },
4040 { MKTAG('s','i','d','x'), mov_read_sidx },
4041 { MKTAG('s','t','b','l'), mov_read_default },
4042 { MKTAG('s','t','c','o'), mov_read_stco },
4043 { MKTAG('s','t','p','s'), mov_read_stps },
4044 { MKTAG('s','t','r','f'), mov_read_strf },
4045 { MKTAG('s','t','s','c'), mov_read_stsc },
4046 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
4047 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
4048 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
4049 { MKTAG('s','t','t','s'), mov_read_stts },
4050 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
4051 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
4052 { MKTAG('t','f','d','t'), mov_read_tfdt },
4053 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
4054 { MKTAG('t','r','a','k'), mov_read_trak },
4055 { MKTAG('t','r','a','f'), mov_read_default },
4056 { MKTAG('t','r','e','f'), mov_read_default },
4057 { MKTAG('t','m','c','d'), mov_read_tmcd },
4058 { MKTAG('c','h','a','p'), mov_read_chap },
4059 { MKTAG('t','r','e','x'), mov_read_trex },
4060 { MKTAG('t','r','u','n'), mov_read_trun },
4061 { MKTAG('u','d','t','a'), mov_read_default },
4062 { MKTAG('w','a','v','e'), mov_read_wave },
4063 { MKTAG('e','s','d','s'), mov_read_esds },
4064 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
4065 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
4066 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
4067 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
4068 { MKTAG('w','f','e','x'), mov_read_wfex },
4069 { MKTAG('c','m','o','v'), mov_read_cmov },
4070 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
4071 { MKTAG('d','v','c','1'), mov_read_dvc1 },
4072 { MKTAG('s','b','g','p'), mov_read_sbgp },
4073 { MKTAG('h','v','c','C'), mov_read_glbl },
4074 { MKTAG('u','u','i','d'), mov_read_uuid },
4075 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
4076 { MKTAG('f','r','e','e'), mov_read_free },
4077 { MKTAG('-','-','-','-'), mov_read_custom },
4081 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4083 int64_t total_size = 0;
4087 if (c->atom_depth > 10) {
4088 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
4089 return AVERROR_INVALIDDATA;
4094 atom.size = INT64_MAX;
4095 while (total_size + 8 <= atom.size && !avio_feof(pb)) {
4096 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
4099 if (atom.size >= 8) {
4100 a.size = avio_rb32(pb);
4101 a.type = avio_rl32(pb);
4102 if (a.type == MKTAG('f','r','e','e') &&
4106 uint32_t *type = (uint32_t *)buf + 1;
4107 if (avio_read(pb, buf, 8) != 8)
4108 return AVERROR_INVALIDDATA;
4109 avio_seek(pb, -8, SEEK_CUR);
4110 if (*type == MKTAG('m','v','h','d') ||
4111 *type == MKTAG('c','m','o','v')) {
4112 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
4113 a.type = MKTAG('m','o','o','v');
4116 if (atom.type != MKTAG('r','o','o','t') &&
4117 atom.type != MKTAG('m','o','o','v'))
4119 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
4121 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
4128 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
4129 a.size = avio_rb64(pb) - 8;
4133 av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
4134 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
4136 a.size = atom.size - total_size + 8;
4141 a.size = FFMIN(a.size, atom.size - total_size);
4143 for (i = 0; mov_default_parse_table[i].type; i++)
4144 if (mov_default_parse_table[i].type == a.type) {
4145 parse = mov_default_parse_table[i].parse;
4149 // container is user data
4150 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
4151 atom.type == MKTAG('i','l','s','t')))
4152 parse = mov_read_udta_string;
4154 // Supports parsing the QuickTime Metadata Keys.
4155 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
4156 if (!parse && c->found_hdlr_mdta &&
4157 atom.type == MKTAG('m','e','t','a') &&
4158 a.type == MKTAG('k','e','y','s')) {
4159 parse = mov_read_keys;
4162 if (!parse) { /* skip leaf atoms data */
4163 avio_skip(pb, a.size);
4165 int64_t start_pos = avio_tell(pb);
4167 int err = parse(c, pb, a);
4172 if (c->found_moov && c->found_mdat &&
4173 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
4174 start_pos + a.size == avio_size(pb))) {
4175 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
4176 c->next_root_atom = start_pos + a.size;
4180 left = a.size - avio_tell(pb) + start_pos;
4181 if (left > 0) /* skip garbage at atom end */
4182 avio_skip(pb, left);
4183 else if (left < 0) {
4184 av_log(c->fc, AV_LOG_WARNING,
4185 "overread end of atom '%.4s' by %"PRId64" bytes\n",
4186 (char*)&a.type, -left);
4187 avio_seek(pb, left, SEEK_CUR);
4191 total_size += a.size;
4194 if (total_size < atom.size && atom.size < 0x7ffff)
4195 avio_skip(pb, atom.size - total_size);
4201 static int mov_probe(AVProbeData *p)
4206 int moov_offset = -1;
4208 /* check file header */
4211 /* ignore invalid offset */
4212 if ((offset + 8) > (unsigned int)p->buf_size)
4214 tag = AV_RL32(p->buf + offset + 4);
4216 /* check for obvious tags */
4217 case MKTAG('m','o','o','v'):
4218 moov_offset = offset + 4;
4219 case MKTAG('m','d','a','t'):
4220 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
4221 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
4222 case MKTAG('f','t','y','p'):
4223 if (AV_RB32(p->buf+offset) < 8 &&
4224 (AV_RB32(p->buf+offset) != 1 ||
4225 offset + 12 > (unsigned int)p->buf_size ||
4226 AV_RB64(p->buf+offset + 8) == 0)) {
4227 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4228 } else if (tag == MKTAG('f','t','y','p') &&
4229 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
4230 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
4232 score = FFMAX(score, 5);
4234 score = AVPROBE_SCORE_MAX;
4236 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4238 /* those are more common words, so rate then a bit less */
4239 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
4240 case MKTAG('w','i','d','e'):
4241 case MKTAG('f','r','e','e'):
4242 case MKTAG('j','u','n','k'):
4243 case MKTAG('p','i','c','t'):
4244 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
4245 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4247 case MKTAG(0x82,0x82,0x7f,0x7d):
4248 case MKTAG('s','k','i','p'):
4249 case MKTAG('u','u','i','d'):
4250 case MKTAG('p','r','f','l'):
4251 /* if we only find those cause probedata is too small at least rate them */
4252 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4253 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4256 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4259 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
4260 /* moov atom in the header - we should make sure that this is not a
4261 * MOV-packed MPEG-PS */
4262 offset = moov_offset;
4264 while(offset < (p->buf_size - 16)){ /* Sufficient space */
4265 /* We found an actual hdlr atom */
4266 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
4267 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
4268 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
4269 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
4270 /* We found a media handler reference atom describing an
4271 * MPEG-PS-in-MOV, return a
4272 * low score to force expanding the probe window until
4273 * mpegps_probe finds what it needs */
4284 // must be done after parsing all trak because there's no order requirement
4285 static void mov_read_chapters(AVFormatContext *s)
4287 MOVContext *mov = s->priv_data;
4288 AVStream *st = NULL;
4289 MOVStreamContext *sc;
4293 for (i = 0; i < s->nb_streams; i++)
4294 if (s->streams[i]->id == mov->chapter_track) {
4299 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
4303 st->discard = AVDISCARD_ALL;
4305 cur_pos = avio_tell(sc->pb);
4307 for (i = 0; i < st->nb_index_entries; i++) {
4308 AVIndexEntry *sample = &st->index_entries[i];
4309 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
4314 if (end < sample->timestamp) {
4315 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
4316 end = AV_NOPTS_VALUE;
4319 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4320 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
4324 // the first two bytes are the length of the title
4325 len = avio_rb16(sc->pb);
4326 if (len > sample->size-2)
4328 title_len = 2*len + 1;
4329 if (!(title = av_mallocz(title_len)))
4332 // The samples could theoretically be in any encoding if there's an encd
4333 // atom following, but in practice are only utf-8 or utf-16, distinguished
4334 // instead by the presence of a BOM
4338 ch = avio_rb16(sc->pb);
4340 avio_get_str16be(sc->pb, len, title, title_len);
4341 else if (ch == 0xfffe)
4342 avio_get_str16le(sc->pb, len, title, title_len);
4345 if (len == 1 || len == 2)
4348 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
4352 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
4356 avio_seek(sc->pb, cur_pos, SEEK_SET);
4359 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
4360 uint32_t value, int flags)
4363 char buf[AV_TIMECODE_STR_SIZE];
4364 AVRational rate = {st->codec->time_base.den,
4365 st->codec->time_base.num};
4366 int ret = av_timecode_init(&tc, rate, flags, 0, s);
4369 av_dict_set(&st->metadata, "timecode",
4370 av_timecode_make_string(&tc, buf, value), 0);
4374 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
4376 MOVStreamContext *sc = st->priv_data;
4378 int64_t cur_pos = avio_tell(sc->pb);
4381 if (!st->nb_index_entries)
4384 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
4385 value = avio_rb32(s->pb);
4387 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
4388 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
4389 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
4391 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
4392 * not the case) and thus assume "frame number format" instead of QT one.
4393 * No sample with tmcd track can be found with a QT timecode at the moment,
4394 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
4396 parse_timecode_in_framenum_format(s, st, value, flags);
4398 avio_seek(sc->pb, cur_pos, SEEK_SET);
4402 static int mov_read_close(AVFormatContext *s)
4404 MOVContext *mov = s->priv_data;
4407 for (i = 0; i < s->nb_streams; i++) {
4408 AVStream *st = s->streams[i];
4409 MOVStreamContext *sc = st->priv_data;
4414 av_freep(&sc->ctts_data);
4415 for (j = 0; j < sc->drefs_count; j++) {
4416 av_freep(&sc->drefs[j].path);
4417 av_freep(&sc->drefs[j].dir);
4419 av_freep(&sc->drefs);
4421 sc->drefs_count = 0;
4423 if (!sc->pb_is_copied)
4424 avio_closep(&sc->pb);
4427 av_freep(&sc->chunk_offsets);
4428 av_freep(&sc->stsc_data);
4429 av_freep(&sc->sample_sizes);
4430 av_freep(&sc->keyframes);
4431 av_freep(&sc->stts_data);
4432 av_freep(&sc->stps_data);
4433 av_freep(&sc->elst_data);
4434 av_freep(&sc->rap_group);
4435 av_freep(&sc->display_matrix);
4438 if (mov->dv_demux) {
4439 avformat_free_context(mov->dv_fctx);
4440 mov->dv_fctx = NULL;
4443 if (mov->meta_keys) {
4444 for (i = 1; i < mov->meta_keys_count; i++) {
4445 av_freep(&mov->meta_keys[i]);
4447 av_freep(&mov->meta_keys);
4450 av_freep(&mov->trex_data);
4451 av_freep(&mov->bitrates);
4453 for (i = 0; i < mov->fragment_index_count; i++) {
4454 MOVFragmentIndex* index = mov->fragment_index_data[i];
4455 av_freep(&index->items);
4456 av_freep(&mov->fragment_index_data[i]);
4458 av_freep(&mov->fragment_index_data);
4460 av_freep(&mov->aes_decrypt);
4465 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
4469 for (i = 0; i < s->nb_streams; i++) {
4470 AVStream *st = s->streams[i];
4471 MOVStreamContext *sc = st->priv_data;
4473 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4474 sc->timecode_track == tmcd_id)
4480 /* look for a tmcd track not referenced by any video track, and export it globally */
4481 static void export_orphan_timecode(AVFormatContext *s)
4485 for (i = 0; i < s->nb_streams; i++) {
4486 AVStream *st = s->streams[i];
4488 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
4489 !tmcd_is_referenced(s, i + 1)) {
4490 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
4492 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
4499 static int read_tfra(MOVContext *mov, AVIOContext *f)
4501 MOVFragmentIndex* index = NULL;
4502 int version, fieldlength, i, j;
4503 int64_t pos = avio_tell(f);
4504 uint32_t size = avio_rb32(f);
4507 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
4510 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
4511 index = av_mallocz(sizeof(MOVFragmentIndex));
4513 return AVERROR(ENOMEM);
4516 tmp = av_realloc_array(mov->fragment_index_data,
4517 mov->fragment_index_count + 1,
4518 sizeof(MOVFragmentIndex*));
4521 return AVERROR(ENOMEM);
4523 mov->fragment_index_data = tmp;
4524 mov->fragment_index_data[mov->fragment_index_count++] = index;
4526 version = avio_r8(f);
4528 index->track_id = avio_rb32(f);
4529 fieldlength = avio_rb32(f);
4530 index->item_count = avio_rb32(f);
4531 index->items = av_mallocz_array(
4532 index->item_count, sizeof(MOVFragmentIndexItem));
4533 if (!index->items) {
4534 index->item_count = 0;
4535 return AVERROR(ENOMEM);
4537 for (i = 0; i < index->item_count; i++) {
4538 int64_t time, offset;
4540 time = avio_rb64(f);
4541 offset = avio_rb64(f);
4543 time = avio_rb32(f);
4544 offset = avio_rb32(f);
4546 index->items[i].time = time;
4547 index->items[i].moof_offset = offset;
4548 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
4550 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
4552 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
4556 avio_seek(f, pos + size, SEEK_SET);
4560 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
4562 int64_t stream_size = avio_size(f);
4563 int64_t original_pos = avio_tell(f);
4567 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
4571 mfra_size = avio_rb32(f);
4572 if (mfra_size < 0 || mfra_size > stream_size) {
4573 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
4576 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
4580 if (avio_rb32(f) != mfra_size) {
4581 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
4584 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
4585 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
4588 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
4590 ret = read_tfra(c, f);
4596 seek_ret = avio_seek(f, original_pos, SEEK_SET);
4598 av_log(c->fc, AV_LOG_ERROR,
4599 "failed to seek back after looking for mfra\n");
4605 static int mov_read_header(AVFormatContext *s)
4607 MOVContext *mov = s->priv_data;
4608 AVIOContext *pb = s->pb;
4610 MOVAtom atom = { AV_RL32("root") };
4614 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
4616 atom.size = avio_size(pb);
4618 atom.size = INT64_MAX;
4620 /* check MOV header */
4622 if (mov->moov_retry)
4623 avio_seek(pb, 0, SEEK_SET);
4624 if ((err = mov_read_default(mov, pb, atom)) < 0) {
4625 av_log(s, AV_LOG_ERROR, "error reading header\n");
4629 } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
4630 if (!mov->found_moov) {
4631 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
4633 return AVERROR_INVALIDDATA;
4635 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
4638 if (mov->chapter_track > 0)
4639 mov_read_chapters(s);
4640 for (i = 0; i < s->nb_streams; i++)
4641 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
4642 mov_read_timecode_track(s, s->streams[i]);
4645 /* copy timecode metadata from tmcd tracks to the related video streams */
4646 for (i = 0; i < s->nb_streams; i++) {
4647 AVStream *st = s->streams[i];
4648 MOVStreamContext *sc = st->priv_data;
4649 if (sc->timecode_track > 0) {
4650 AVDictionaryEntry *tcr;
4651 int tmcd_st_id = -1;
4653 for (j = 0; j < s->nb_streams; j++)
4654 if (s->streams[j]->id == sc->timecode_track)
4657 if (tmcd_st_id < 0 || tmcd_st_id == i)
4659 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
4661 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
4664 export_orphan_timecode(s);
4666 for (i = 0; i < s->nb_streams; i++) {
4667 AVStream *st = s->streams[i];
4668 MOVStreamContext *sc = st->priv_data;
4669 fix_timescale(mov, sc);
4670 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
4671 st->skip_samples = sc->start_pad;
4673 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
4674 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4675 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
4676 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4677 if (st->codec->width <= 0 || st->codec->height <= 0) {
4678 st->codec->width = sc->width;
4679 st->codec->height = sc->height;
4681 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
4682 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
4688 if (mov->trex_data) {
4689 for (i = 0; i < s->nb_streams; i++) {
4690 AVStream *st = s->streams[i];
4691 MOVStreamContext *sc = st->priv_data;
4692 if (st->duration > 0)
4693 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
4697 if (mov->use_mfra_for > 0) {
4698 for (i = 0; i < s->nb_streams; i++) {
4699 AVStream *st = s->streams[i];
4700 MOVStreamContext *sc = st->priv_data;
4701 if (sc->duration_for_fps > 0) {
4702 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
4703 sc->duration_for_fps;
4708 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
4709 if (mov->bitrates[i]) {
4710 s->streams[i]->codec->bit_rate = mov->bitrates[i];
4714 ff_rfps_calculate(s);
4716 for (i = 0; i < s->nb_streams; i++) {
4717 AVStream *st = s->streams[i];
4718 MOVStreamContext *sc = st->priv_data;
4720 switch (st->codec->codec_type) {
4721 case AVMEDIA_TYPE_AUDIO:
4722 err = ff_replaygain_export(st, s->metadata);
4728 case AVMEDIA_TYPE_VIDEO:
4729 if (sc->display_matrix) {
4730 AVPacketSideData *sd, *tmp;
4732 tmp = av_realloc_array(st->side_data,
4733 st->nb_side_data + 1, sizeof(*tmp));
4735 return AVERROR(ENOMEM);
4737 st->side_data = tmp;
4740 sd = &st->side_data[st->nb_side_data - 1];
4741 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
4742 sd->size = sizeof(int32_t) * 9;
4743 sd->data = (uint8_t*)sc->display_matrix;
4744 sc->display_matrix = NULL;
4749 ff_configure_buffers_for_index(s, AV_TIME_BASE);
4754 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
4756 AVIndexEntry *sample = NULL;
4757 int64_t best_dts = INT64_MAX;
4759 for (i = 0; i < s->nb_streams; i++) {
4760 AVStream *avst = s->streams[i];
4761 MOVStreamContext *msc = avst->priv_data;
4762 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
4763 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
4764 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
4765 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
4766 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
4768 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
4769 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
4770 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
4771 sample = current_sample;
4780 static int should_retry(AVIOContext *pb, int error_code) {
4781 if (error_code == AVERROR_EOF || avio_feof(pb))
4787 static int mov_switch_root(AVFormatContext *s, int64_t target)
4789 MOVContext *mov = s->priv_data;
4791 int already_read = 0;
4793 if (avio_seek(s->pb, target, SEEK_SET) != target) {
4794 av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
4795 return AVERROR_INVALIDDATA;
4798 mov->next_root_atom = 0;
4800 for (i = 0; i < mov->fragment_index_count; i++) {
4801 MOVFragmentIndex *index = mov->fragment_index_data[i];
4803 for (j = 0; j < index->item_count; j++) {
4804 MOVFragmentIndexItem *item = &index->items[j];
4806 mov->next_root_atom = item->moof_offset;
4807 break; // Advance to next index in outer loop
4808 } else if (item->moof_offset == target) {
4809 index->current_item = FFMIN(j, index->current_item);
4810 if (item->headers_read)
4812 item->headers_read = 1;
4817 index->current_item = 0;
4823 mov->found_mdat = 0;
4825 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
4828 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
4833 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
4835 MOVContext *mov = s->priv_data;
4836 MOVStreamContext *sc;
4837 AVIndexEntry *sample;
4838 AVStream *st = NULL;
4842 sample = mov_find_next_sample(s, &st);
4843 if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
4844 if (!mov->next_root_atom)
4846 if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
4851 /* must be done just before reading, to avoid infinite loop on sample */
4852 sc->current_sample++;
4854 if (mov->next_root_atom) {
4855 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
4856 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
4859 if (st->discard != AVDISCARD_ALL) {
4860 int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
4861 if (ret64 != sample->pos) {
4862 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
4863 sc->ffindex, sample->pos);
4864 sc->current_sample -= should_retry(sc->pb, ret64);
4865 return AVERROR_INVALIDDATA;
4867 ret = av_get_packet(sc->pb, pkt, sample->size);
4869 sc->current_sample -= should_retry(sc->pb, ret);
4872 if (sc->has_palette) {
4875 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
4877 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
4879 memcpy(pal, sc->palette, AVPALETTE_SIZE);
4880 sc->has_palette = 0;
4883 #if CONFIG_DV_DEMUXER
4884 if (mov->dv_demux && sc->dv_audio_container) {
4885 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
4886 av_freep(&pkt->data);
4888 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
4895 pkt->stream_index = sc->ffindex;
4896 pkt->dts = sample->timestamp;
4897 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
4898 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
4899 /* update ctts context */
4901 if (sc->ctts_index < sc->ctts_count &&
4902 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
4904 sc->ctts_sample = 0;
4907 pkt->dts = AV_NOPTS_VALUE;
4909 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
4910 st->index_entries[sc->current_sample].timestamp : st->duration;
4911 pkt->duration = next_dts - pkt->dts;
4912 pkt->pts = pkt->dts;
4914 if (st->discard == AVDISCARD_ALL)
4916 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
4917 pkt->pos = sample->pos;
4920 aax_filter(pkt->data, pkt->size, mov);
4925 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
4927 MOVContext *mov = s->priv_data;
4930 if (!mov->fragment_index_complete)
4933 for (i = 0; i < mov->fragment_index_count; i++) {
4934 if (mov->fragment_index_data[i]->track_id == st->id) {
4935 MOVFragmentIndex *index = index = mov->fragment_index_data[i];
4936 for (j = index->item_count - 1; j >= 0; j--) {
4937 if (index->items[j].time <= timestamp) {
4938 if (index->items[j].headers_read)
4941 return mov_switch_root(s, index->items[j].moof_offset);
4950 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
4952 MOVStreamContext *sc = st->priv_data;
4953 int sample, time_sample;
4956 int ret = mov_seek_fragment(s, st, timestamp);
4960 sample = av_index_search_timestamp(st, timestamp, flags);
4961 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
4962 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
4964 if (sample < 0) /* not sure what to do */
4965 return AVERROR_INVALIDDATA;
4966 sc->current_sample = sample;
4967 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
4968 /* adjust ctts index */
4969 if (sc->ctts_data) {
4971 for (i = 0; i < sc->ctts_count; i++) {
4972 int next = time_sample + sc->ctts_data[i].count;
4973 if (next > sc->current_sample) {
4975 sc->ctts_sample = sc->current_sample - time_sample;
4984 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
4986 MOVContext *mc = s->priv_data;
4991 if (stream_index >= s->nb_streams)
4992 return AVERROR_INVALIDDATA;
4994 st = s->streams[stream_index];
4995 sample = mov_seek_stream(s, st, sample_time, flags);
4999 if (mc->seek_individually) {
5000 /* adjust seek timestamp to found sample timestamp */
5001 int64_t seek_timestamp = st->index_entries[sample].timestamp;
5003 for (i = 0; i < s->nb_streams; i++) {
5005 MOVStreamContext *sc = s->streams[i]->priv_data;
5007 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
5009 if (stream_index == i)
5012 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
5013 mov_seek_stream(s, st, timestamp, flags);
5016 for (i = 0; i < s->nb_streams; i++) {
5017 MOVStreamContext *sc;
5020 sc->current_sample = 0;
5023 MOVStreamContext *sc;
5024 AVIndexEntry *entry = mov_find_next_sample(s, &st);
5026 return AVERROR_INVALIDDATA;
5028 if (sc->ffindex == stream_index && sc->current_sample == sample)
5030 sc->current_sample++;
5036 #define OFFSET(x) offsetof(MOVContext, x)
5037 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
5038 static const AVOption mov_options[] = {
5039 {"use_absolute_path",
5040 "allow using absolute path when opening alias, this is a possible security issue",
5041 OFFSET(use_absolute_path), AV_OPT_TYPE_INT, {.i64 = 0},
5043 {"seek_streams_individually",
5044 "Seek each stream individually to the to the closest point",
5045 OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
5047 {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_INT, {.i64 = 0},
5050 "use mfra for fragment timestamps",
5051 OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
5052 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
5054 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
5055 FLAGS, "use_mfra_for" },
5056 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
5057 FLAGS, "use_mfra_for" },
5058 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
5059 FLAGS, "use_mfra_for" },
5060 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
5061 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5062 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
5063 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5064 { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
5065 AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5066 { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
5067 "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
5068 AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
5069 .flags = AV_OPT_FLAG_DECODING_PARAM },
5073 static const AVClass mov_class = {
5074 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
5075 .item_name = av_default_item_name,
5076 .option = mov_options,
5077 .version = LIBAVUTIL_VERSION_INT,
5080 AVInputFormat ff_mov_demuxer = {
5081 .name = "mov,mp4,m4a,3gp,3g2,mj2",
5082 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5083 .priv_class = &mov_class,
5084 .priv_data_size = sizeof(MOVContext),
5085 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
5086 .read_probe = mov_probe,
5087 .read_header = mov_read_header,
5088 .read_packet = mov_read_packet,
5089 .read_close = mov_read_close,
5090 .read_seek = mov_read_seek,
5091 .flags = AVFMT_NO_BYTE_SEEK,