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/aes_ctr.h"
43 #include "libavutil/sha.h"
44 #include "libavutil/timecode.h"
45 #include "libavcodec/ac3tab.h"
48 #include "avio_internal.h"
51 #include "libavcodec/get_bits.h"
54 #include "replaygain.h"
60 #include "qtpalette.h"
62 /* those functions parse an atom */
63 /* links atom IDs to parse functions */
64 typedef struct MOVParseTableEntry {
66 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
69 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
70 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
72 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
73 unsigned len, const char *key)
77 short current, total = 0;
78 avio_rb16(pb); // unknown
79 current = avio_rb16(pb);
81 total = avio_rb16(pb);
83 snprintf(buf, sizeof(buf), "%d", current);
85 snprintf(buf, sizeof(buf), "%d/%d", current, total);
86 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
87 av_dict_set(&c->fc->metadata, key, buf, 0);
92 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
93 unsigned len, const char *key)
95 /* bypass padding bytes */
100 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
101 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
106 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
107 unsigned len, const char *key)
109 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
110 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
115 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
116 unsigned len, const char *key)
120 avio_r8(pb); // unknown
123 if (genre < 1 || genre > ID3v1_GENRE_MAX)
125 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
126 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
131 static const uint32_t mac_to_unicode[128] = {
132 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
133 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
134 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
135 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
136 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
137 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
138 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
139 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
140 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
141 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
142 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
143 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
144 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
145 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
146 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
147 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
150 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
151 char *dst, int dstlen)
154 char *end = dst+dstlen-1;
157 for (i = 0; i < len; i++) {
158 uint8_t t, c = avio_r8(pb);
159 if (c < 0x80 && p < end)
162 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
168 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
172 MOVStreamContext *sc;
177 case 0xd: id = AV_CODEC_ID_MJPEG; break;
178 case 0xe: id = AV_CODEC_ID_PNG; break;
179 case 0x1b: id = AV_CODEC_ID_BMP; break;
181 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
186 st = avformat_new_stream(c->fc, NULL);
188 return AVERROR(ENOMEM);
189 sc = av_mallocz(sizeof(*sc));
191 return AVERROR(ENOMEM);
194 ret = av_get_packet(pb, &pkt, len);
198 if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
199 if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
200 id = AV_CODEC_ID_PNG;
202 id = AV_CODEC_ID_MJPEG;
206 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
208 st->attached_pic = pkt;
209 st->attached_pic.stream_index = st->index;
210 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
212 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
213 st->codec->codec_id = id;
218 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
220 char language[4] = { 0 };
221 char buf[200], place[100];
222 uint16_t langcode = 0;
223 double longitude, latitude, altitude;
224 const char *key = "location";
226 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
227 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
228 return AVERROR_INVALIDDATA;
231 avio_skip(pb, 4); // version+flags
232 langcode = avio_rb16(pb);
233 ff_mov_lang_to_iso639(langcode, language);
236 len -= avio_get_str(pb, len, place, sizeof(place));
238 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
239 return AVERROR_INVALIDDATA;
241 avio_skip(pb, 1); // role
245 av_log(c->fc, AV_LOG_ERROR, "no space for coordinates left (%d)\n", len);
246 return AVERROR_INVALIDDATA;
248 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
249 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
250 altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
252 // Try to output in the same format as the ?xyz field
253 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
255 av_strlcatf(buf, sizeof(buf), "%+f", altitude);
256 av_strlcatf(buf, sizeof(buf), "/%s", place);
258 if (*language && strcmp(language, "und")) {
260 snprintf(key2, sizeof(key2), "%s-%s", key, language);
261 av_dict_set(&c->fc->metadata, key2, buf, 0);
263 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
264 return av_dict_set(&c->fc->metadata, key, buf, 0);
267 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
270 char key2[32], language[4] = {0};
272 const char *key = NULL;
273 uint16_t langcode = 0;
274 uint32_t data_type = 0, str_size, str_size_alloc;
275 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
280 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
281 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
282 case MKTAG( 'X','M','P','_'):
283 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
284 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
285 case MKTAG( 'a','k','I','D'): key = "account_type";
286 parse = mov_metadata_int8_no_padding; break;
287 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
288 case MKTAG( 'c','a','t','g'): key = "category"; break;
289 case MKTAG( 'c','p','i','l'): key = "compilation";
290 parse = mov_metadata_int8_no_padding; break;
291 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
292 case MKTAG( 'd','e','s','c'): key = "description"; break;
293 case MKTAG( 'd','i','s','k'): key = "disc";
294 parse = mov_metadata_track_or_disc_number; break;
295 case MKTAG( 'e','g','i','d'): key = "episode_uid";
296 parse = mov_metadata_int8_no_padding; break;
297 case MKTAG( 'g','n','r','e'): key = "genre";
298 parse = mov_metadata_gnre; break;
299 case MKTAG( 'h','d','v','d'): key = "hd_video";
300 parse = mov_metadata_int8_no_padding; break;
301 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
302 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
303 case MKTAG( 'l','o','c','i'):
304 return mov_metadata_loci(c, pb, atom.size);
305 case MKTAG( 'p','c','s','t'): key = "podcast";
306 parse = mov_metadata_int8_no_padding; break;
307 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
308 parse = mov_metadata_int8_no_padding; break;
309 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
310 case MKTAG( 'r','t','n','g'): key = "rating";
311 parse = mov_metadata_int8_no_padding; break;
312 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
313 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
314 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
315 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
316 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
317 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
318 case MKTAG( 's','t','i','k'): key = "media_type";
319 parse = mov_metadata_int8_no_padding; break;
320 case MKTAG( 't','r','k','n'): key = "track";
321 parse = mov_metadata_track_or_disc_number; break;
322 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
323 case MKTAG( 't','v','e','s'): key = "episode_sort";
324 parse = mov_metadata_int8_bypass_padding; break;
325 case MKTAG( 't','v','n','n'): key = "network"; break;
326 case MKTAG( 't','v','s','h'): key = "show"; break;
327 case MKTAG( 't','v','s','n'): key = "season_number";
328 parse = mov_metadata_int8_bypass_padding; break;
329 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
330 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
331 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
332 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
333 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
334 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
335 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
336 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
337 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
338 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
339 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
340 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
341 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
342 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
343 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
344 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
345 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
346 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
347 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
348 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
349 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
350 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
351 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
352 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
353 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
354 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
355 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
356 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
357 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
358 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
359 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
360 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
361 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
362 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
363 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
366 if (c->itunes_metadata && atom.size > 8) {
367 int data_size = avio_rb32(pb);
368 int tag = avio_rl32(pb);
369 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
370 data_type = avio_rb32(pb); // type
371 avio_rb32(pb); // unknown
372 str_size = data_size - 16;
375 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
376 int ret = mov_read_covr(c, pb, data_type, str_size);
378 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
381 } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
382 uint32_t index = AV_RB32(&atom.type);
383 if (index < c->meta_keys_count) {
384 key = c->meta_keys[index];
386 av_log(c->fc, AV_LOG_WARNING,
387 "The index of 'data' is out of range: %d >= %d.\n",
388 index, c->meta_keys_count);
392 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
393 str_size = avio_rb16(pb); // string length
394 if (str_size > atom.size) {
396 avio_seek(pb, -2, SEEK_CUR);
397 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
400 langcode = avio_rb16(pb);
401 ff_mov_lang_to_iso639(langcode, language);
404 str_size = atom.size;
406 if (c->export_all && !key) {
407 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
413 if (atom.size < 0 || str_size >= INT_MAX/2)
414 return AVERROR_INVALIDDATA;
416 // Allocates enough space if data_type is a float32 number, otherwise
417 // worst-case requirement for output string in case of utf8 coded input
418 num = (data_type == 23);
419 str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
420 str = av_mallocz(str_size_alloc);
422 return AVERROR(ENOMEM);
425 parse(c, pb, str_size, key);
427 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
428 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
429 } else if (data_type == 23 && str_size >= 4) { // BE float32
430 float val = av_int2float(avio_rb32(pb));
431 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
432 av_log(c->fc, AV_LOG_ERROR,
433 "Failed to store the float32 number (%f) in string.\n", val);
435 return AVERROR_INVALIDDATA;
438 int ret = ffio_read_size(pb, str, str_size);
445 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
446 av_dict_set(&c->fc->metadata, key, str, 0);
447 if (*language && strcmp(language, "und")) {
448 snprintf(key2, sizeof(key2), "%s-%s", key, language);
449 av_dict_set(&c->fc->metadata, key2, str, 0);
451 if (!strcmp(key, "encoder")) {
452 int major, minor, micro;
453 if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, µ) == 3) {
454 c->handbrake_version = 1000000*major + 1000*minor + micro;
458 av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
459 av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
460 key, str, (char*)&atom.type, str_size_alloc, atom.size);
466 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
469 int i, nb_chapters, str_len, version;
473 if (c->ignore_chapters)
476 if ((atom.size -= 5) < 0)
479 version = avio_r8(pb);
482 avio_rb32(pb); // ???
483 nb_chapters = avio_r8(pb);
485 for (i = 0; i < nb_chapters; i++) {
489 start = avio_rb64(pb);
490 str_len = avio_r8(pb);
492 if ((atom.size -= 9+str_len) < 0)
495 ret = ffio_read_size(pb, str, str_len);
499 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
504 #define MIN_DATA_ENTRY_BOX_SIZE 12
505 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
508 MOVStreamContext *sc;
511 if (c->fc->nb_streams < 1)
513 st = c->fc->streams[c->fc->nb_streams-1];
516 avio_rb32(pb); // version + flags
517 entries = avio_rb32(pb);
518 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
519 entries >= UINT_MAX / sizeof(*sc->drefs))
520 return AVERROR_INVALIDDATA;
523 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
525 return AVERROR(ENOMEM);
526 sc->drefs_count = entries;
528 for (i = 0; i < entries; i++) {
529 MOVDref *dref = &sc->drefs[i];
530 uint32_t size = avio_rb32(pb);
531 int64_t next = avio_tell(pb) + size - 4;
534 return AVERROR_INVALIDDATA;
536 dref->type = avio_rl32(pb);
537 avio_rb32(pb); // version + flags
538 av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
540 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
541 /* macintosh alias record */
542 uint16_t volume_len, len;
548 volume_len = avio_r8(pb);
549 volume_len = FFMIN(volume_len, 27);
550 ret = ffio_read_size(pb, dref->volume, 27);
553 dref->volume[volume_len] = 0;
554 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
559 len = FFMIN(len, 63);
560 ret = ffio_read_size(pb, dref->filename, 63);
563 dref->filename[len] = 0;
564 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
568 /* read next level up_from_alias/down_to_target */
569 dref->nlvl_from = avio_rb16(pb);
570 dref->nlvl_to = avio_rb16(pb);
571 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
572 dref->nlvl_from, dref->nlvl_to);
576 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
579 type = avio_rb16(pb);
581 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
584 if (type == 2) { // absolute path
586 dref->path = av_mallocz(len+1);
588 return AVERROR(ENOMEM);
590 ret = ffio_read_size(pb, dref->path, len);
592 av_freep(&dref->path);
595 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
597 memmove(dref->path, dref->path+volume_len, len);
600 for (j = 0; j < len; j++)
601 if (dref->path[j] == ':' || dref->path[j] == 0)
603 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
604 } else if (type == 0) { // directory name
606 dref->dir = av_malloc(len+1);
608 return AVERROR(ENOMEM);
610 ret = ffio_read_size(pb, dref->dir, len);
612 av_freep(&dref->dir);
616 for (j = 0; j < len; j++)
617 if (dref->dir[j] == ':')
619 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
624 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x08%x size %d\n",
629 avio_seek(pb, next, SEEK_SET);
634 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
638 uint32_t av_unused ctype;
643 avio_r8(pb); /* version */
644 avio_rb24(pb); /* flags */
647 ctype = avio_rl32(pb);
648 type = avio_rl32(pb); /* component subtype */
650 av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
651 av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
653 if (c->trak_index < 0) { // meta not inside a trak
654 if (type == MKTAG('m','d','t','a')) {
655 c->found_hdlr_mdta = 1;
660 st = c->fc->streams[c->fc->nb_streams-1];
662 if (type == MKTAG('v','i','d','e'))
663 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
664 else if (type == MKTAG('s','o','u','n'))
665 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
666 else if (type == MKTAG('m','1','a',' '))
667 st->codec->codec_id = AV_CODEC_ID_MP2;
668 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
669 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
671 avio_rb32(pb); /* component manufacture */
672 avio_rb32(pb); /* component flags */
673 avio_rb32(pb); /* component flags mask */
675 title_size = atom.size - 24;
676 if (title_size > 0) {
677 title_str = av_malloc(title_size + 1); /* Add null terminator */
679 return AVERROR(ENOMEM);
681 ret = ffio_read_size(pb, title_str, title_size);
683 av_freep(&title_str);
686 title_str[title_size] = 0;
688 int off = (!c->isom && title_str[0] == title_size - 1);
689 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
691 av_freep(&title_str);
697 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
702 if (fc->nb_streams < 1)
704 st = fc->streams[fc->nb_streams-1];
706 avio_rb32(pb); /* version + flags */
707 ff_mp4_read_descr(fc, pb, &tag);
708 if (tag == MP4ESDescrTag) {
709 ff_mp4_parse_es_descr(pb, NULL);
711 avio_rb16(pb); /* ID */
713 ff_mp4_read_descr(fc, pb, &tag);
714 if (tag == MP4DecConfigDescrTag)
715 ff_mp4_read_dec_config_descr(fc, st, pb);
719 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
721 return ff_mov_read_esds(c->fc, pb);
724 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
727 enum AVAudioServiceType *ast;
728 int ac3info, acmod, lfeon, bsmod;
730 if (c->fc->nb_streams < 1)
732 st = c->fc->streams[c->fc->nb_streams-1];
734 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
737 return AVERROR(ENOMEM);
739 ac3info = avio_rb24(pb);
740 bsmod = (ac3info >> 14) & 0x7;
741 acmod = (ac3info >> 11) & 0x7;
742 lfeon = (ac3info >> 10) & 0x1;
743 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
744 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
746 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
748 if (st->codec->channels > 1 && bsmod == 0x7)
749 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
751 st->codec->audio_service_type = *ast;
756 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
759 enum AVAudioServiceType *ast;
760 int eac3info, acmod, lfeon, bsmod;
762 if (c->fc->nb_streams < 1)
764 st = c->fc->streams[c->fc->nb_streams-1];
766 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
769 return AVERROR(ENOMEM);
771 /* No need to parse fields for additional independent substreams and its
772 * associated dependent substreams since libavcodec's E-AC-3 decoder
773 * does not support them yet. */
774 avio_rb16(pb); /* data_rate and num_ind_sub */
775 eac3info = avio_rb24(pb);
776 bsmod = (eac3info >> 12) & 0x1f;
777 acmod = (eac3info >> 9) & 0x7;
778 lfeon = (eac3info >> 8) & 0x1;
779 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
781 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
782 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
784 if (st->codec->channels > 1 && bsmod == 0x7)
785 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
787 st->codec->audio_service_type = *ast;
792 static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
794 const uint32_t ddts_size = 20;
797 uint32_t frame_duration_code = 0;
798 uint32_t channel_layout_code = 0;
801 buf = av_malloc(ddts_size + FF_INPUT_BUFFER_PADDING_SIZE);
803 return AVERROR(ENOMEM);
805 if (avio_read(pb, buf, ddts_size) < ddts_size) {
807 return AVERROR_INVALIDDATA;
810 init_get_bits(&gb, buf, 8*ddts_size);
812 if (c->fc->nb_streams < 1) {
815 st = c->fc->streams[c->fc->nb_streams-1];
817 st->codec->sample_rate = get_bits_long(&gb, 32);
818 skip_bits_long(&gb, 32); /* max bitrate */
819 st->codec->bit_rate = get_bits_long(&gb, 32);
820 st->codec->bits_per_coded_sample = get_bits(&gb, 8);
821 frame_duration_code = get_bits(&gb, 2);
822 skip_bits(&gb, 30); /* various fields */
823 channel_layout_code = get_bits(&gb, 16);
825 st->codec->frame_size =
826 (frame_duration_code == 0) ? 512 :
827 (frame_duration_code == 1) ? 1024 :
828 (frame_duration_code == 2) ? 2048 :
829 (frame_duration_code == 3) ? 4096 : 0;
831 if (channel_layout_code > 0xff) {
832 av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
834 st->codec->channel_layout =
835 ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
836 ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
837 ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
838 ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
839 ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
840 ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
842 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
847 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
851 if (c->fc->nb_streams < 1)
853 st = c->fc->streams[c->fc->nb_streams-1];
858 /* skip version and flags */
861 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
866 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
871 if (c->fc->nb_streams < 1)
873 st = c->fc->streams[c->fc->nb_streams-1];
875 if ((ret = ff_get_wav_header(c->fc, pb, st->codec, atom.size, 0)) < 0)
876 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
881 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
883 const int num = avio_rb32(pb);
884 const int den = avio_rb32(pb);
887 if (c->fc->nb_streams < 1)
889 st = c->fc->streams[c->fc->nb_streams-1];
891 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
892 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
893 av_log(c->fc, AV_LOG_WARNING,
894 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
895 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
897 } else if (den != 0) {
898 av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
904 /* this atom contains actual media data */
905 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
907 if (atom.size == 0) /* wrong one (MP4) */
910 return 0; /* now go for moov */
913 #define DRM_BLOB_SIZE 56
915 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
917 uint8_t intermediate_key[20];
918 uint8_t intermediate_iv[20];
921 uint8_t file_checksum[20];
922 uint8_t calculated_checksum[20];
926 uint8_t *activation_bytes = c->activation_bytes;
927 uint8_t *fixed_key = c->audible_fixed_key;
931 sha = av_sha_alloc();
933 return AVERROR(ENOMEM);
934 c->aes_decrypt = av_aes_alloc();
935 if (!c->aes_decrypt) {
936 ret = AVERROR(ENOMEM);
940 /* drm blob processing */
941 avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
942 avio_read(pb, input, DRM_BLOB_SIZE);
943 avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
944 avio_read(pb, file_checksum, 20);
946 av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
947 for (i = 0; i < 20; i++)
948 av_log(sha, AV_LOG_INFO, "%02x", file_checksum[i]);
949 av_log(c->fc, AV_LOG_INFO, "\n");
951 /* verify activation data */
952 if (!activation_bytes) {
953 av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
954 ret = 0; /* allow ffprobe to continue working on .aax files */
957 if (c->activation_bytes_size != 4) {
958 av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
959 ret = AVERROR(EINVAL);
963 /* verify fixed key */
964 if (c->audible_fixed_key_size != 16) {
965 av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
966 ret = AVERROR(EINVAL);
970 /* AAX (and AAX+) key derivation */
971 av_sha_init(sha, 160);
972 av_sha_update(sha, fixed_key, 16);
973 av_sha_update(sha, activation_bytes, 4);
974 av_sha_final(sha, intermediate_key);
975 av_sha_init(sha, 160);
976 av_sha_update(sha, fixed_key, 16);
977 av_sha_update(sha, intermediate_key, 20);
978 av_sha_update(sha, activation_bytes, 4);
979 av_sha_final(sha, intermediate_iv);
980 av_sha_init(sha, 160);
981 av_sha_update(sha, intermediate_key, 16);
982 av_sha_update(sha, intermediate_iv, 16);
983 av_sha_final(sha, calculated_checksum);
984 if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
985 av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
986 ret = AVERROR_INVALIDDATA;
989 av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
990 av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
991 for (i = 0; i < 4; i++) {
992 // file data (in output) is stored in big-endian mode
993 if (activation_bytes[i] != output[3 - i]) { // critical error
994 av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
995 ret = AVERROR_INVALIDDATA;
999 memcpy(c->file_key, output + 8, 16);
1000 memcpy(input, output + 26, 16);
1001 av_sha_init(sha, 160);
1002 av_sha_update(sha, input, 16);
1003 av_sha_update(sha, c->file_key, 16);
1004 av_sha_update(sha, fixed_key, 16);
1005 av_sha_final(sha, c->file_iv);
1013 // Audible AAX (and AAX+) bytestream decryption
1014 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1017 unsigned char iv[16];
1019 memcpy(iv, c->file_iv, 16); // iv is overwritten
1020 blocks = size >> 4; // trailing bytes are not encrypted!
1021 av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1022 av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1027 /* read major brand, minor version and compatible brands and store them as metadata */
1028 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1031 int comp_brand_size;
1032 char* comp_brands_str;
1033 uint8_t type[5] = {0};
1034 int ret = ffio_read_size(pb, type, 4);
1038 if (strcmp(type, "qt "))
1040 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1041 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1042 minor_ver = avio_rb32(pb); /* minor version */
1043 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1045 comp_brand_size = atom.size - 8;
1046 if (comp_brand_size < 0)
1047 return AVERROR_INVALIDDATA;
1048 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1049 if (!comp_brands_str)
1050 return AVERROR(ENOMEM);
1052 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1054 av_freep(&comp_brands_str);
1057 comp_brands_str[comp_brand_size] = 0;
1058 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1059 av_freep(&comp_brands_str);
1064 /* this atom should contain all header atoms */
1065 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1069 if (c->found_moov) {
1070 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1071 avio_skip(pb, atom.size);
1075 if ((ret = mov_read_default(c, pb, atom)) < 0)
1077 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1078 /* so we don't parse the whole file if over a network */
1080 return 0; /* now go for mdat */
1083 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1085 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1086 c->has_looked_for_mfra = 1;
1089 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1091 if ((ret = mov_read_mfra(c, pb)) < 0) {
1092 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1093 "read the mfra (may be a live ismv)\n");
1096 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1097 "seekable, can not look for mfra\n");
1100 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
1101 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1102 return mov_read_default(c, pb, atom);
1105 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1109 struct tm *ptm, tmbuf;
1111 if(time >= 2082844800)
1112 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1114 ptm = gmtime_r(&timet, &tmbuf);
1116 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
1117 av_dict_set(metadata, "creation_time", buffer, 0);
1121 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1124 MOVStreamContext *sc;
1126 char language[4] = {0};
1128 int64_t creation_time;
1130 if (c->fc->nb_streams < 1)
1132 st = c->fc->streams[c->fc->nb_streams-1];
1135 if (sc->time_scale) {
1136 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1137 return AVERROR_INVALIDDATA;
1140 version = avio_r8(pb);
1142 avpriv_request_sample(c->fc, "Version %d", version);
1143 return AVERROR_PATCHWELCOME;
1145 avio_rb24(pb); /* flags */
1147 creation_time = avio_rb64(pb);
1150 creation_time = avio_rb32(pb);
1151 avio_rb32(pb); /* modification time */
1153 mov_metadata_creation_time(&st->metadata, creation_time);
1155 sc->time_scale = avio_rb32(pb);
1156 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1158 lang = avio_rb16(pb); /* language */
1159 if (ff_mov_lang_to_iso639(lang, language))
1160 av_dict_set(&st->metadata, "language", language, 0);
1161 avio_rb16(pb); /* quality */
1166 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1168 int64_t creation_time;
1169 int version = avio_r8(pb); /* version */
1170 avio_rb24(pb); /* flags */
1173 creation_time = avio_rb64(pb);
1176 creation_time = avio_rb32(pb);
1177 avio_rb32(pb); /* modification time */
1179 mov_metadata_creation_time(&c->fc->metadata, creation_time);
1180 c->time_scale = avio_rb32(pb); /* time scale */
1182 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1184 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1185 // set the AVCodecContext duration because the duration of individual tracks
1186 // may be inaccurate
1187 if (c->time_scale > 0 && !c->trex_data)
1188 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1189 avio_rb32(pb); /* preferred scale */
1191 avio_rb16(pb); /* preferred volume */
1193 avio_skip(pb, 10); /* reserved */
1195 avio_skip(pb, 36); /* display matrix */
1197 avio_rb32(pb); /* preview time */
1198 avio_rb32(pb); /* preview duration */
1199 avio_rb32(pb); /* poster time */
1200 avio_rb32(pb); /* selection time */
1201 avio_rb32(pb); /* selection duration */
1202 avio_rb32(pb); /* current time */
1203 avio_rb32(pb); /* next track ID */
1208 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1213 if (c->fc->nb_streams < 1)
1215 st = c->fc->streams[c->fc->nb_streams-1];
1217 little_endian = avio_rb16(pb) & 0xFF;
1218 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1219 if (little_endian == 1) {
1220 switch (st->codec->codec_id) {
1221 case AV_CODEC_ID_PCM_S24BE:
1222 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
1224 case AV_CODEC_ID_PCM_S32BE:
1225 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
1227 case AV_CODEC_ID_PCM_F32BE:
1228 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
1230 case AV_CODEC_ID_PCM_F64BE:
1231 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
1240 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1243 char color_parameter_type[5] = { 0 };
1244 uint16_t color_primaries, color_trc, color_matrix;
1247 if (c->fc->nb_streams < 1)
1249 st = c->fc->streams[c->fc->nb_streams - 1];
1251 ret = ffio_read_size(pb, color_parameter_type, 4);
1254 if (strncmp(color_parameter_type, "nclx", 4) &&
1255 strncmp(color_parameter_type, "nclc", 4)) {
1256 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1257 color_parameter_type);
1261 color_primaries = avio_rb16(pb);
1262 color_trc = avio_rb16(pb);
1263 color_matrix = avio_rb16(pb);
1265 av_log(c->fc, AV_LOG_TRACE,
1266 "%s: pri %d trc %d matrix %d",
1267 color_parameter_type, color_primaries, color_trc, color_matrix);
1269 if (!strncmp(color_parameter_type, "nclx", 4)) {
1270 uint8_t color_range = avio_r8(pb) >> 7;
1271 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1273 st->codec->color_range = AVCOL_RANGE_JPEG;
1275 st->codec->color_range = AVCOL_RANGE_MPEG;
1276 /* 14496-12 references JPEG XR specs (rather than the more complete
1277 * 23001-8) so some adjusting is required */
1278 if (color_primaries >= AVCOL_PRI_FILM)
1279 color_primaries = AVCOL_PRI_UNSPECIFIED;
1280 if ((color_trc >= AVCOL_TRC_LINEAR &&
1281 color_trc <= AVCOL_TRC_LOG_SQRT) ||
1282 color_trc >= AVCOL_TRC_BT2020_10)
1283 color_trc = AVCOL_TRC_UNSPECIFIED;
1284 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
1285 color_matrix = AVCOL_SPC_UNSPECIFIED;
1286 st->codec->color_primaries = color_primaries;
1287 st->codec->color_trc = color_trc;
1288 st->codec->colorspace = color_matrix;
1289 } else if (!strncmp(color_parameter_type, "nclc", 4)) {
1290 /* color primaries, Table 4-4 */
1291 switch (color_primaries) {
1292 case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
1293 case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
1294 case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
1296 /* color transfer, Table 4-5 */
1297 switch (color_trc) {
1298 case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
1299 case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
1301 /* color matrix, Table 4-6 */
1302 switch (color_matrix) {
1303 case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
1304 case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
1305 case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
1308 av_log(c->fc, AV_LOG_TRACE, "\n");
1313 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1316 unsigned mov_field_order;
1317 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1319 if (c->fc->nb_streams < 1) // will happen with jp2 files
1321 st = c->fc->streams[c->fc->nb_streams-1];
1323 return AVERROR_INVALIDDATA;
1324 mov_field_order = avio_rb16(pb);
1325 if ((mov_field_order & 0xFF00) == 0x0100)
1326 decoded_field_order = AV_FIELD_PROGRESSIVE;
1327 else if ((mov_field_order & 0xFF00) == 0x0200) {
1328 switch (mov_field_order & 0xFF) {
1329 case 0x01: decoded_field_order = AV_FIELD_TT;
1331 case 0x06: decoded_field_order = AV_FIELD_BB;
1333 case 0x09: decoded_field_order = AV_FIELD_TB;
1335 case 0x0E: decoded_field_order = AV_FIELD_BT;
1339 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1340 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1342 st->codec->field_order = decoded_field_order;
1347 static int mov_realloc_extradata(AVCodecContext *codec, MOVAtom atom)
1350 uint64_t size = (uint64_t)codec->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1351 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1352 return AVERROR_INVALIDDATA;
1353 if ((err = av_reallocp(&codec->extradata, size)) < 0) {
1354 codec->extradata_size = 0;
1357 codec->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1361 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1362 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1363 AVCodecContext *codec, uint8_t *buf)
1365 int64_t result = atom.size;
1368 AV_WB32(buf , atom.size + 8);
1369 AV_WL32(buf + 4, atom.type);
1370 err = ffio_read_size(pb, buf + 8, atom.size);
1372 codec->extradata_size -= atom.size;
1374 } else if (err < atom.size) {
1375 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1376 codec->extradata_size -= atom.size - err;
1379 memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1383 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
1384 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1385 enum AVCodecID codec_id)
1388 uint64_t original_size;
1391 if (c->fc->nb_streams < 1) // will happen with jp2 files
1393 st = c->fc->streams[c->fc->nb_streams-1];
1395 if (st->codec->codec_id != codec_id)
1396 return 0; /* unexpected codec_id - don't mess with extradata */
1398 original_size = st->codec->extradata_size;
1399 err = mov_realloc_extradata(st->codec, atom);
1403 err = mov_read_atom_into_extradata(c, pb, atom, st->codec, st->codec->extradata + original_size);
1406 return 0; // Note: this is the original behavior to ignore truncation.
1409 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1410 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1412 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1415 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1417 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1420 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1422 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1425 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1427 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1430 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1432 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1434 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1438 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1440 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1442 if (!ret && c->fc->nb_streams >= 1) {
1443 AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
1444 if (avctx->extradata_size >= 40) {
1445 avctx->height = AV_RB16(&avctx->extradata[36]);
1446 avctx->width = AV_RB16(&avctx->extradata[38]);
1452 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1454 if (c->fc->nb_streams >= 1) {
1455 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1456 if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1457 codec->codec_id == AV_CODEC_ID_H264 &&
1460 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1461 if (avio_rb16(pb) == 0xd4d)
1462 codec->width = 1440;
1467 return mov_read_avid(c, pb, atom);
1470 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1474 uint64_t original_size;
1475 if (c->fc->nb_streams >= 1) {
1476 AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1477 if (codec->codec_id == AV_CODEC_ID_H264)
1479 if (atom.size == 16) {
1480 original_size = codec->extradata_size;
1481 ret = mov_realloc_extradata(codec, atom);
1483 length = mov_read_atom_into_extradata(c, pb, atom, codec, codec->extradata + original_size);
1484 if (length == atom.size) {
1485 const uint8_t range_value = codec->extradata[original_size + 19];
1486 switch (range_value) {
1488 codec->color_range = AVCOL_RANGE_MPEG;
1491 codec->color_range = AVCOL_RANGE_JPEG;
1494 av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1497 ff_dlog(c, "color_range: %d\n", codec->color_range);
1499 /* For some reason the whole atom was not added to the extradata */
1500 av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1503 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1506 av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1513 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1515 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1518 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1523 if (c->fc->nb_streams < 1)
1525 st = c->fc->streams[c->fc->nb_streams-1];
1527 if ((uint64_t)atom.size > (1<<30))
1528 return AVERROR_INVALIDDATA;
1530 if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1531 st->codec->codec_id == AV_CODEC_ID_QDMC ||
1532 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1533 // pass all frma atom to codec, needed at least for QDMC and QDM2
1534 av_freep(&st->codec->extradata);
1535 ret = ff_get_extradata(st->codec, pb, atom.size);
1538 } else if (atom.size > 8) { /* to read frma, esds atoms */
1539 if (st->codec->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1541 ret = ffio_ensure_seekback(pb, 8);
1544 buffer = avio_rb64(pb);
1546 if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1547 && buffer >> 32 <= atom.size
1548 && buffer >> 32 >= 8) {
1551 } else if (!st->codec->extradata_size) {
1552 #define ALAC_EXTRADATA_SIZE 36
1553 st->codec->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1554 if (!st->codec->extradata)
1555 return AVERROR(ENOMEM);
1556 st->codec->extradata_size = ALAC_EXTRADATA_SIZE;
1557 AV_WB32(st->codec->extradata , ALAC_EXTRADATA_SIZE);
1558 AV_WB32(st->codec->extradata + 4, MKTAG('a','l','a','c'));
1559 AV_WB64(st->codec->extradata + 12, buffer);
1560 avio_read(pb, st->codec->extradata + 20, 16);
1561 avio_skip(pb, atom.size - 24);
1565 if ((ret = mov_read_default(c, pb, atom)) < 0)
1568 avio_skip(pb, atom.size);
1573 * This function reads atom content and puts data in extradata without tag
1574 * nor size unlike mov_read_extradata.
1576 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1581 if (c->fc->nb_streams < 1)
1583 st = c->fc->streams[c->fc->nb_streams-1];
1585 if ((uint64_t)atom.size > (1<<30))
1586 return AVERROR_INVALIDDATA;
1588 if (atom.size >= 10) {
1589 // Broken files created by legacy versions of libavformat will
1590 // wrap a whole fiel atom inside of a glbl atom.
1591 unsigned size = avio_rb32(pb);
1592 unsigned type = avio_rl32(pb);
1593 avio_seek(pb, -8, SEEK_CUR);
1594 if (type == MKTAG('f','i','e','l') && size == atom.size)
1595 return mov_read_default(c, pb, atom);
1597 if (st->codec->extradata_size > 1 && st->codec->extradata) {
1598 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1601 av_freep(&st->codec->extradata);
1602 ret = ff_get_extradata(st->codec, pb, atom.size);
1609 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1612 uint8_t profile_level;
1615 if (c->fc->nb_streams < 1)
1617 st = c->fc->streams[c->fc->nb_streams-1];
1619 if (atom.size >= (1<<28) || atom.size < 7)
1620 return AVERROR_INVALIDDATA;
1622 profile_level = avio_r8(pb);
1623 if ((profile_level & 0xf0) != 0xc0)
1626 avio_seek(pb, 6, SEEK_CUR);
1627 av_freep(&st->codec->extradata);
1628 ret = ff_get_extradata(st->codec, pb, atom.size - 7);
1636 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1637 * but can have extradata appended at the end after the 40 bytes belonging
1640 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1645 if (c->fc->nb_streams < 1)
1647 if (atom.size <= 40)
1649 st = c->fc->streams[c->fc->nb_streams-1];
1651 if ((uint64_t)atom.size > (1<<30))
1652 return AVERROR_INVALIDDATA;
1655 av_freep(&st->codec->extradata);
1656 ret = ff_get_extradata(st->codec, pb, atom.size - 40);
1663 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1666 MOVStreamContext *sc;
1667 unsigned int i, entries;
1669 if (c->fc->nb_streams < 1)
1671 st = c->fc->streams[c->fc->nb_streams-1];
1674 avio_r8(pb); /* version */
1675 avio_rb24(pb); /* flags */
1677 entries = avio_rb32(pb);
1682 if (sc->chunk_offsets)
1683 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1684 av_free(sc->chunk_offsets);
1685 sc->chunk_count = 0;
1686 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1687 if (!sc->chunk_offsets)
1688 return AVERROR(ENOMEM);
1689 sc->chunk_count = entries;
1691 if (atom.type == MKTAG('s','t','c','o'))
1692 for (i = 0; i < entries && !pb->eof_reached; i++)
1693 sc->chunk_offsets[i] = avio_rb32(pb);
1694 else if (atom.type == MKTAG('c','o','6','4'))
1695 for (i = 0; i < entries && !pb->eof_reached; i++)
1696 sc->chunk_offsets[i] = avio_rb64(pb);
1698 return AVERROR_INVALIDDATA;
1700 sc->chunk_count = i;
1702 if (pb->eof_reached)
1709 * Compute codec id for 'lpcm' tag.
1710 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1712 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1719 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1722 static int mov_codec_id(AVStream *st, uint32_t format)
1724 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1727 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1728 (format & 0xFFFF) == 'T' + ('S' << 8)))
1729 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1731 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1732 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1733 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1734 /* skip old asf mpeg4 tag */
1735 format && format != MKTAG('m','p','4','s')) {
1736 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1738 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1740 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1741 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1742 (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1743 st->codec->codec_id == AV_CODEC_ID_NONE)) {
1744 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1746 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1750 st->codec->codec_tag = format;
1755 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1756 AVStream *st, MOVStreamContext *sc)
1758 uint8_t codec_name[32];
1762 /* The first 16 bytes of the video sample description are already
1763 * read in ff_mov_read_stsd_entries() */
1764 stsd_start = avio_tell(pb) - 16;
1766 avio_rb16(pb); /* version */
1767 avio_rb16(pb); /* revision level */
1768 avio_rb32(pb); /* vendor */
1769 avio_rb32(pb); /* temporal quality */
1770 avio_rb32(pb); /* spatial quality */
1772 st->codec->width = avio_rb16(pb); /* width */
1773 st->codec->height = avio_rb16(pb); /* height */
1775 avio_rb32(pb); /* horiz resolution */
1776 avio_rb32(pb); /* vert resolution */
1777 avio_rb32(pb); /* data size, always 0 */
1778 avio_rb16(pb); /* frames per samples */
1780 len = avio_r8(pb); /* codec name, pascal string */
1783 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1785 avio_skip(pb, 31 - len);
1788 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1790 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1791 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1792 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1793 st->codec->width &= ~1;
1794 st->codec->height &= ~1;
1796 /* Flash Media Server uses tag H263 with Sorenson Spark */
1797 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1798 !memcmp(codec_name, "Sorenson H263", 13))
1799 st->codec->codec_id = AV_CODEC_ID_FLV1;
1801 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1803 avio_seek(pb, stsd_start, SEEK_SET);
1805 if (ff_get_qtpalette(st->codec->codec_id, pb, sc->palette)) {
1806 st->codec->bits_per_coded_sample &= 0x1F;
1807 sc->has_palette = 1;
1811 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1812 AVStream *st, MOVStreamContext *sc)
1814 int bits_per_sample, flags;
1815 uint16_t version = avio_rb16(pb);
1816 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1818 avio_rb16(pb); /* revision level */
1819 avio_rb32(pb); /* vendor */
1821 st->codec->channels = avio_rb16(pb); /* channel count */
1822 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1823 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codec->channels);
1825 sc->audio_cid = avio_rb16(pb);
1826 avio_rb16(pb); /* packet size = 0 */
1828 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1830 // Read QT version 1 fields. In version 0 these do not exist.
1831 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1833 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1836 sc->samples_per_frame = avio_rb32(pb);
1837 avio_rb32(pb); /* bytes per packet */
1838 sc->bytes_per_frame = avio_rb32(pb);
1839 avio_rb32(pb); /* bytes per sample */
1840 } else if (version == 2) {
1841 avio_rb32(pb); /* sizeof struct only */
1842 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1843 st->codec->channels = avio_rb32(pb);
1844 avio_rb32(pb); /* always 0x7F000000 */
1845 st->codec->bits_per_coded_sample = avio_rb32(pb);
1847 flags = avio_rb32(pb); /* lpcm format specific flag */
1848 sc->bytes_per_frame = avio_rb32(pb);
1849 sc->samples_per_frame = avio_rb32(pb);
1850 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1851 st->codec->codec_id =
1852 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1855 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1856 /* can't correctly handle variable sized packet as audio unit */
1857 switch (st->codec->codec_id) {
1858 case AV_CODEC_ID_MP2:
1859 case AV_CODEC_ID_MP3:
1860 st->need_parsing = AVSTREAM_PARSE_FULL;
1866 switch (st->codec->codec_id) {
1867 case AV_CODEC_ID_PCM_S8:
1868 case AV_CODEC_ID_PCM_U8:
1869 if (st->codec->bits_per_coded_sample == 16)
1870 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1872 case AV_CODEC_ID_PCM_S16LE:
1873 case AV_CODEC_ID_PCM_S16BE:
1874 if (st->codec->bits_per_coded_sample == 8)
1875 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1876 else if (st->codec->bits_per_coded_sample == 24)
1877 st->codec->codec_id =
1878 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1879 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1880 else if (st->codec->bits_per_coded_sample == 32)
1881 st->codec->codec_id =
1882 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1883 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1885 /* set values for old format before stsd version 1 appeared */
1886 case AV_CODEC_ID_MACE3:
1887 sc->samples_per_frame = 6;
1888 sc->bytes_per_frame = 2 * st->codec->channels;
1890 case AV_CODEC_ID_MACE6:
1891 sc->samples_per_frame = 6;
1892 sc->bytes_per_frame = 1 * st->codec->channels;
1894 case AV_CODEC_ID_ADPCM_IMA_QT:
1895 sc->samples_per_frame = 64;
1896 sc->bytes_per_frame = 34 * st->codec->channels;
1898 case AV_CODEC_ID_GSM:
1899 sc->samples_per_frame = 160;
1900 sc->bytes_per_frame = 33;
1906 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1907 if (bits_per_sample) {
1908 st->codec->bits_per_coded_sample = bits_per_sample;
1909 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1913 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1914 AVStream *st, MOVStreamContext *sc,
1917 // ttxt stsd contains display flags, justification, background
1918 // color, fonts, and default styles, so fake an atom to read it
1919 MOVAtom fake_atom = { .size = size };
1920 // mp4s contains a regular esds atom
1921 if (st->codec->codec_tag != AV_RL32("mp4s"))
1922 mov_read_glbl(c, pb, fake_atom);
1923 st->codec->width = sc->width;
1924 st->codec->height = sc->height;
1927 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1932 y = (ycbcr >> 16) & 0xFF;
1933 cr = (ycbcr >> 8) & 0xFF;
1936 b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
1937 g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
1938 r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
1940 return (r << 16) | (g << 8) | b;
1943 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1945 char buf[256] = {0};
1946 uint8_t *src = st->codec->extradata;
1949 if (st->codec->extradata_size != 64)
1952 if (st->codec->width > 0 && st->codec->height > 0)
1953 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1954 st->codec->width, st->codec->height);
1955 av_strlcat(buf, "palette: ", sizeof(buf));
1957 for (i = 0; i < 16; i++) {
1958 uint32_t yuv = AV_RB32(src + i * 4);
1959 uint32_t rgba = yuv_to_rgba(yuv);
1961 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1964 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1967 av_freep(&st->codec->extradata);
1968 st->codec->extradata_size = 0;
1969 st->codec->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
1970 if (!st->codec->extradata)
1971 return AVERROR(ENOMEM);
1972 st->codec->extradata_size = strlen(buf);
1973 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1978 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1979 AVStream *st, MOVStreamContext *sc,
1984 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1985 if ((int)size != size)
1986 return AVERROR(ENOMEM);
1988 ret = ff_get_extradata(st->codec, pb, size);
1992 MOVStreamContext *tmcd_ctx = st->priv_data;
1994 val = AV_RB32(st->codec->extradata + 4);
1995 tmcd_ctx->tmcd_flags = val;
1997 st->codec->flags2 |= AV_CODEC_FLAG2_DROP_FRAME_TIMECODE;
1998 st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
1999 st->codec->time_base.num = 1;
2000 /* adjust for per frame dur in counter mode */
2001 if (tmcd_ctx->tmcd_flags & 0x0008) {
2002 int timescale = AV_RB32(st->codec->extradata + 8);
2003 int framedur = AV_RB32(st->codec->extradata + 12);
2004 st->codec->time_base.den *= timescale;
2005 st->codec->time_base.num *= framedur;
2008 uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
2009 uint32_t format = AV_RB32(st->codec->extradata + 22);
2010 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2011 uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
2012 if (str_size > 0 && size >= (int)str_size + 26) {
2013 char *reel_name = av_malloc(str_size + 1);
2015 return AVERROR(ENOMEM);
2016 memcpy(reel_name, st->codec->extradata + 30, str_size);
2017 reel_name[str_size] = 0; /* Add null terminator */
2018 /* don't add reel_name if emtpy string */
2019 if (*reel_name == 0) {
2022 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2029 /* other codec type, just skip (rtp, mp4s ...) */
2030 avio_skip(pb, size);
2035 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2036 AVStream *st, MOVStreamContext *sc)
2038 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2039 !st->codec->sample_rate && sc->time_scale > 1)
2040 st->codec->sample_rate = sc->time_scale;
2042 /* special codec parameters handling */
2043 switch (st->codec->codec_id) {
2044 #if CONFIG_DV_DEMUXER
2045 case AV_CODEC_ID_DVAUDIO:
2046 c->dv_fctx = avformat_alloc_context();
2048 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2049 return AVERROR(ENOMEM);
2051 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2053 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2054 return AVERROR(ENOMEM);
2056 sc->dv_audio_container = 1;
2057 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
2060 /* no ifdef since parameters are always those */
2061 case AV_CODEC_ID_QCELP:
2062 st->codec->channels = 1;
2063 // force sample rate for qcelp when not stored in mov
2064 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
2065 st->codec->sample_rate = 8000;
2066 // FIXME: Why is the following needed for some files?
2067 sc->samples_per_frame = 160;
2068 if (!sc->bytes_per_frame)
2069 sc->bytes_per_frame = 35;
2071 case AV_CODEC_ID_AMR_NB:
2072 st->codec->channels = 1;
2073 /* force sample rate for amr, stsd in 3gp does not store sample rate */
2074 st->codec->sample_rate = 8000;
2076 case AV_CODEC_ID_AMR_WB:
2077 st->codec->channels = 1;
2078 st->codec->sample_rate = 16000;
2080 case AV_CODEC_ID_MP2:
2081 case AV_CODEC_ID_MP3:
2082 /* force type after stsd for m1a hdlr */
2083 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
2085 case AV_CODEC_ID_GSM:
2086 case AV_CODEC_ID_ADPCM_MS:
2087 case AV_CODEC_ID_ADPCM_IMA_WAV:
2088 case AV_CODEC_ID_ILBC:
2089 case AV_CODEC_ID_MACE3:
2090 case AV_CODEC_ID_MACE6:
2091 case AV_CODEC_ID_QDM2:
2092 st->codec->block_align = sc->bytes_per_frame;
2094 case AV_CODEC_ID_ALAC:
2095 if (st->codec->extradata_size == 36) {
2096 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
2097 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
2100 case AV_CODEC_ID_AC3:
2101 case AV_CODEC_ID_EAC3:
2102 case AV_CODEC_ID_MPEG1VIDEO:
2103 case AV_CODEC_ID_VC1:
2104 st->need_parsing = AVSTREAM_PARSE_FULL;
2112 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2113 int codec_tag, int format,
2116 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2119 (codec_tag != format &&
2120 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2121 : codec_tag != MKTAG('j','p','e','g')))) {
2122 /* Multiple fourcc, we skip JPEG. This is not correct, we should
2123 * export it as a separate AVStream but this needs a few changes
2124 * in the MOV demuxer, patch welcome. */
2126 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2127 avio_skip(pb, size);
2130 if ( codec_tag == AV_RL32("avc1") ||
2131 codec_tag == AV_RL32("hvc1") ||
2132 codec_tag == AV_RL32("hev1")
2134 av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
2139 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2142 MOVStreamContext *sc;
2143 int pseudo_stream_id;
2145 if (c->fc->nb_streams < 1)
2147 st = c->fc->streams[c->fc->nb_streams-1];
2150 for (pseudo_stream_id = 0;
2151 pseudo_stream_id < entries && !pb->eof_reached;
2152 pseudo_stream_id++) {
2153 //Parsing Sample description table
2155 int ret, dref_id = 1;
2156 MOVAtom a = { AV_RL32("stsd") };
2157 int64_t start_pos = avio_tell(pb);
2158 int64_t size = avio_rb32(pb); /* size */
2159 uint32_t format = avio_rl32(pb); /* data format */
2162 avio_rb32(pb); /* reserved */
2163 avio_rb16(pb); /* reserved */
2164 dref_id = avio_rb16(pb);
2165 }else if (size <= 7){
2166 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
2167 return AVERROR_INVALIDDATA;
2170 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
2171 size - (avio_tell(pb) - start_pos)))
2174 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
2175 sc->dref_id= dref_id;
2176 sc->format = format;
2178 id = mov_codec_id(st, format);
2180 av_log(c->fc, AV_LOG_TRACE,
2181 "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
2182 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
2183 (format >> 24) & 0xff, format, st->codec->codec_type);
2185 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
2186 st->codec->codec_id = id;
2187 mov_parse_stsd_video(c, pb, st, sc);
2188 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
2189 st->codec->codec_id = id;
2190 mov_parse_stsd_audio(c, pb, st, sc);
2191 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
2192 st->codec->codec_id = id;
2193 mov_parse_stsd_subtitle(c, pb, st, sc,
2194 size - (avio_tell(pb) - start_pos));
2196 ret = mov_parse_stsd_data(c, pb, st, sc,
2197 size - (avio_tell(pb) - start_pos));
2201 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2202 a.size = size - (avio_tell(pb) - start_pos);
2204 if ((ret = mov_read_default(c, pb, a)) < 0)
2206 } else if (a.size > 0)
2207 avio_skip(pb, a.size);
2210 if (pb->eof_reached)
2213 return mov_finalize_stsd_codec(c, pb, st, sc);
2216 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2220 avio_r8(pb); /* version */
2221 avio_rb24(pb); /* flags */
2222 entries = avio_rb32(pb);
2224 return ff_mov_read_stsd_entries(c, pb, entries);
2227 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2230 MOVStreamContext *sc;
2231 unsigned int i, entries;
2233 if (c->fc->nb_streams < 1)
2235 st = c->fc->streams[c->fc->nb_streams-1];
2238 avio_r8(pb); /* version */
2239 avio_rb24(pb); /* flags */
2241 entries = avio_rb32(pb);
2243 av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
2248 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2249 av_free(sc->stsc_data);
2251 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2253 return AVERROR(ENOMEM);
2255 for (i = 0; i < entries && !pb->eof_reached; i++) {
2256 sc->stsc_data[i].first = avio_rb32(pb);
2257 sc->stsc_data[i].count = avio_rb32(pb);
2258 sc->stsc_data[i].id = avio_rb32(pb);
2263 if (pb->eof_reached)
2269 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2272 MOVStreamContext *sc;
2273 unsigned i, entries;
2275 if (c->fc->nb_streams < 1)
2277 st = c->fc->streams[c->fc->nb_streams-1];
2280 avio_rb32(pb); // version + flags
2282 entries = avio_rb32(pb);
2284 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2285 av_free(sc->stps_data);
2287 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2289 return AVERROR(ENOMEM);
2291 for (i = 0; i < entries && !pb->eof_reached; i++) {
2292 sc->stps_data[i] = avio_rb32(pb);
2293 //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
2298 if (pb->eof_reached)
2304 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2307 MOVStreamContext *sc;
2308 unsigned int i, entries;
2310 if (c->fc->nb_streams < 1)
2312 st = c->fc->streams[c->fc->nb_streams-1];
2315 avio_r8(pb); /* version */
2316 avio_rb24(pb); /* flags */
2318 entries = avio_rb32(pb);
2320 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
2324 sc->keyframe_absent = 1;
2325 if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2326 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2330 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2331 if (entries >= UINT_MAX / sizeof(int))
2332 return AVERROR_INVALIDDATA;
2333 av_freep(&sc->keyframes);
2334 sc->keyframe_count = 0;
2335 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2337 return AVERROR(ENOMEM);
2339 for (i = 0; i < entries && !pb->eof_reached; i++) {
2340 sc->keyframes[i] = avio_rb32(pb);
2341 //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
2344 sc->keyframe_count = i;
2346 if (pb->eof_reached)
2352 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2355 MOVStreamContext *sc;
2356 unsigned int i, entries, sample_size, field_size, num_bytes;
2361 if (c->fc->nb_streams < 1)
2363 st = c->fc->streams[c->fc->nb_streams-1];
2366 avio_r8(pb); /* version */
2367 avio_rb24(pb); /* flags */
2369 if (atom.type == MKTAG('s','t','s','z')) {
2370 sample_size = avio_rb32(pb);
2371 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2372 sc->sample_size = sample_size;
2373 sc->stsz_sample_size = sample_size;
2377 avio_rb24(pb); /* reserved */
2378 field_size = avio_r8(pb);
2380 entries = avio_rb32(pb);
2382 av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2384 sc->sample_count = entries;
2388 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2389 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2390 return AVERROR_INVALIDDATA;
2395 if (entries >= (UINT_MAX - 4) / field_size)
2396 return AVERROR_INVALIDDATA;
2397 if (sc->sample_sizes)
2398 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2399 av_free(sc->sample_sizes);
2400 sc->sample_count = 0;
2401 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2402 if (!sc->sample_sizes)
2403 return AVERROR(ENOMEM);
2405 num_bytes = (entries*field_size+4)>>3;
2407 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2409 av_freep(&sc->sample_sizes);
2410 return AVERROR(ENOMEM);
2413 ret = ffio_read_size(pb, buf, num_bytes);
2415 av_freep(&sc->sample_sizes);
2420 init_get_bits(&gb, buf, 8*num_bytes);
2422 for (i = 0; i < entries && !pb->eof_reached; i++) {
2423 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2424 sc->data_size += sc->sample_sizes[i];
2427 sc->sample_count = i;
2431 if (pb->eof_reached)
2437 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2440 MOVStreamContext *sc;
2441 unsigned int i, entries;
2443 int64_t total_sample_count=0;
2445 if (c->fc->nb_streams < 1)
2447 st = c->fc->streams[c->fc->nb_streams-1];
2450 avio_r8(pb); /* version */
2451 avio_rb24(pb); /* flags */
2452 entries = avio_rb32(pb);
2454 av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2455 c->fc->nb_streams-1, entries);
2458 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2459 av_free(sc->stts_data);
2461 sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2463 return AVERROR(ENOMEM);
2465 for (i = 0; i < entries && !pb->eof_reached; i++) {
2466 int sample_duration;
2469 sample_count=avio_rb32(pb);
2470 sample_duration = avio_rb32(pb);
2472 if (sample_count < 0) {
2473 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2474 return AVERROR_INVALIDDATA;
2476 sc->stts_data[i].count= sample_count;
2477 sc->stts_data[i].duration= sample_duration;
2479 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2480 sample_count, sample_duration);
2484 && sample_count == 1
2485 && total_sample_count > 100
2486 && sample_duration/10 > duration / total_sample_count)
2487 sample_duration = duration / total_sample_count;
2488 duration+=(int64_t)sample_duration*sample_count;
2489 total_sample_count+=sample_count;
2494 sc->duration_for_fps += duration;
2495 sc->nb_frames_for_fps += total_sample_count;
2497 if (pb->eof_reached)
2500 st->nb_frames= total_sample_count;
2502 st->duration= duration;
2503 sc->track_end = duration;
2507 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2510 if (duration == INT_MIN) {
2511 av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2514 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2518 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2521 MOVStreamContext *sc;
2522 unsigned int i, entries;
2524 if (c->fc->nb_streams < 1)
2526 st = c->fc->streams[c->fc->nb_streams-1];
2529 avio_r8(pb); /* version */
2530 avio_rb24(pb); /* flags */
2531 entries = avio_rb32(pb);
2533 av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2537 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2538 return AVERROR_INVALIDDATA;
2539 av_freep(&sc->ctts_data);
2540 sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2542 return AVERROR(ENOMEM);
2544 for (i = 0; i < entries && !pb->eof_reached; i++) {
2545 int count =avio_rb32(pb);
2546 int duration =avio_rb32(pb);
2548 sc->ctts_data[i].count = count;
2549 sc->ctts_data[i].duration= duration;
2551 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2554 if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2555 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2556 av_freep(&sc->ctts_data);
2562 mov_update_dts_shift(sc, duration);
2567 if (pb->eof_reached)
2570 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2575 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2578 MOVStreamContext *sc;
2579 unsigned int i, entries;
2581 uint32_t grouping_type;
2583 if (c->fc->nb_streams < 1)
2585 st = c->fc->streams[c->fc->nb_streams-1];
2588 version = avio_r8(pb); /* version */
2589 avio_rb24(pb); /* flags */
2590 grouping_type = avio_rl32(pb);
2591 if (grouping_type != MKTAG( 'r','a','p',' '))
2592 return 0; /* only support 'rap ' grouping */
2594 avio_rb32(pb); /* grouping_type_parameter */
2596 entries = avio_rb32(pb);
2600 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2601 av_free(sc->rap_group);
2602 sc->rap_group_count = 0;
2603 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2605 return AVERROR(ENOMEM);
2607 for (i = 0; i < entries && !pb->eof_reached; i++) {
2608 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2609 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2612 sc->rap_group_count = i;
2614 return pb->eof_reached ? AVERROR_EOF : 0;
2617 static void mov_build_index(MOVContext *mov, AVStream *st)
2619 MOVStreamContext *sc = st->priv_data;
2620 int64_t current_offset;
2621 int64_t current_dts = 0;
2622 unsigned int stts_index = 0;
2623 unsigned int stsc_index = 0;
2624 unsigned int stss_index = 0;
2625 unsigned int stps_index = 0;
2627 uint64_t stream_size = 0;
2629 if (sc->elst_count) {
2630 int i, edit_start_index = 0, unsupported = 0;
2631 int64_t empty_duration = 0; // empty duration of the first edit list entry
2632 int64_t start_time = 0; // start time of the media
2634 for (i = 0; i < sc->elst_count; i++) {
2635 const MOVElst *e = &sc->elst_data[i];
2636 if (i == 0 && e->time == -1) {
2637 /* if empty, the first entry is the start time of the stream
2638 * relative to the presentation itself */
2639 empty_duration = e->duration;
2640 edit_start_index = 1;
2641 } else if (i == edit_start_index && e->time >= 0) {
2642 start_time = e->time;
2647 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
2648 "a/v desync might occur, patch welcome\n");
2650 /* adjust first dts according to edit list */
2651 if ((empty_duration || start_time) && mov->time_scale > 0) {
2653 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
2654 sc->time_offset = start_time - empty_duration;
2655 current_dts = -sc->time_offset;
2656 if (sc->ctts_count>0 && sc->stts_count>0 &&
2657 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2658 /* more than 16 frames delay, dts are likely wrong
2659 this happens with files created by iMovie */
2661 st->codec->has_b_frames = 1;
2666 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2667 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2668 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2669 unsigned int current_sample = 0;
2670 unsigned int stts_sample = 0;
2671 unsigned int sample_size;
2672 unsigned int distance = 0;
2673 unsigned int rap_group_index = 0;
2674 unsigned int rap_group_sample = 0;
2675 int64_t last_dts = 0;
2676 int64_t dts_correction = 0;
2677 int rap_group_present = sc->rap_group_count && sc->rap_group;
2678 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2680 current_dts -= sc->dts_shift;
2681 last_dts = current_dts;
2683 if (!sc->sample_count || st->nb_index_entries)
2685 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2687 if (av_reallocp_array(&st->index_entries,
2688 st->nb_index_entries + sc->sample_count,
2689 sizeof(*st->index_entries)) < 0) {
2690 st->nb_index_entries = 0;
2693 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2695 for (i = 0; i < sc->chunk_count; i++) {
2696 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2697 current_offset = sc->chunk_offsets[i];
2698 while (stsc_index + 1 < sc->stsc_count &&
2699 i + 1 == sc->stsc_data[stsc_index + 1].first)
2702 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2703 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2704 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2705 sc->stsz_sample_size = sc->sample_size;
2707 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2708 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2709 sc->stsz_sample_size = sc->sample_size;
2712 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2714 if (current_sample >= sc->sample_count) {
2715 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2719 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2721 if (stss_index + 1 < sc->keyframe_count)
2723 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2725 if (stps_index + 1 < sc->stps_count)
2728 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2729 if (sc->rap_group[rap_group_index].index > 0)
2731 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2732 rap_group_sample = 0;
2736 if (sc->keyframe_absent
2738 && !rap_group_present
2739 && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2743 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2744 if (sc->pseudo_stream_id == -1 ||
2745 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2746 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2747 e->pos = current_offset;
2748 e->timestamp = current_dts;
2749 e->size = sample_size;
2750 e->min_distance = distance;
2751 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2752 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2753 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2754 current_offset, current_dts, sample_size, distance, keyframe);
2755 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2756 ff_rfps_add_frame(mov->fc, st, current_dts);
2759 current_offset += sample_size;
2760 stream_size += sample_size;
2762 /* A negative sample duration is invalid based on the spec,
2763 * but some samples need it to correct the DTS. */
2764 if (sc->stts_data[stts_index].duration < 0) {
2765 av_log(mov->fc, AV_LOG_WARNING,
2766 "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2767 sc->stts_data[stts_index].duration, stts_index,
2769 dts_correction += sc->stts_data[stts_index].duration - 1;
2770 sc->stts_data[stts_index].duration = 1;
2772 current_dts += sc->stts_data[stts_index].duration;
2773 if (!dts_correction || current_dts + dts_correction > last_dts) {
2774 current_dts += dts_correction;
2777 /* Avoid creating non-monotonous DTS */
2778 dts_correction += current_dts - last_dts - 1;
2779 current_dts = last_dts + 1;
2781 last_dts = current_dts;
2785 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2791 if (st->duration > 0)
2792 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2794 unsigned chunk_samples, total = 0;
2796 // compute total chunk count
2797 for (i = 0; i < sc->stsc_count; i++) {
2798 unsigned count, chunk_count;
2800 chunk_samples = sc->stsc_data[i].count;
2801 if (i != sc->stsc_count - 1 &&
2802 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2803 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2807 if (sc->samples_per_frame >= 160) { // gsm
2808 count = chunk_samples / sc->samples_per_frame;
2809 } else if (sc->samples_per_frame > 1) {
2810 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2811 count = (chunk_samples+samples-1) / samples;
2813 count = (chunk_samples+1023) / 1024;
2816 if (i < sc->stsc_count - 1)
2817 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2819 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2820 total += chunk_count * count;
2823 av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2824 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2826 if (av_reallocp_array(&st->index_entries,
2827 st->nb_index_entries + total,
2828 sizeof(*st->index_entries)) < 0) {
2829 st->nb_index_entries = 0;
2832 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2835 for (i = 0; i < sc->chunk_count; i++) {
2836 current_offset = sc->chunk_offsets[i];
2837 if (stsc_index + 1 < sc->stsc_count &&
2838 i + 1 == sc->stsc_data[stsc_index + 1].first)
2840 chunk_samples = sc->stsc_data[stsc_index].count;
2842 while (chunk_samples > 0) {
2844 unsigned size, samples;
2846 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2847 avpriv_request_sample(mov->fc,
2848 "Zero bytes per frame, but %d samples per frame",
2849 sc->samples_per_frame);
2853 if (sc->samples_per_frame >= 160) { // gsm
2854 samples = sc->samples_per_frame;
2855 size = sc->bytes_per_frame;
2857 if (sc->samples_per_frame > 1) {
2858 samples = FFMIN((1024 / sc->samples_per_frame)*
2859 sc->samples_per_frame, chunk_samples);
2860 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2862 samples = FFMIN(1024, chunk_samples);
2863 size = samples * sc->sample_size;
2867 if (st->nb_index_entries >= total) {
2868 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2871 e = &st->index_entries[st->nb_index_entries++];
2872 e->pos = current_offset;
2873 e->timestamp = current_dts;
2875 e->min_distance = 0;
2876 e->flags = AVINDEX_KEYFRAME;
2877 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2878 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2881 current_offset += size;
2882 current_dts += samples;
2883 chunk_samples -= samples;
2889 static int test_same_origin(const char *src, const char *ref) {
2899 av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
2900 av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
2902 if (strlen(src) == 0) {
2904 } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
2905 strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
2906 strlen(src_host) + 1 >= sizeof(src_host) ||
2907 strlen(ref_host) + 1 >= sizeof(ref_host)) {
2909 } else if (strcmp(src_proto, ref_proto) ||
2910 strcmp(src_auth, ref_auth) ||
2911 strcmp(src_host, ref_host) ||
2912 src_port != ref_port) {
2918 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref,
2919 AVIOInterruptCB *int_cb)
2921 AVOpenCallback open_func = c->fc->open_cb;
2924 open_func = ffio_open2_wrapper;
2926 /* try relative path, we do not try the absolute because it can leak information about our
2927 system to an attacker */
2928 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2929 char filename[1025];
2930 const char *src_path;
2933 /* find a source dir */
2934 src_path = strrchr(src, '/');
2940 /* find a next level down to target */
2941 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2942 if (ref->path[l] == '/') {
2943 if (i == ref->nlvl_to - 1)
2949 /* compose filename if next level down to target was found */
2950 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2951 memcpy(filename, src, src_path - src);
2952 filename[src_path - src] = 0;
2954 for (i = 1; i < ref->nlvl_from; i++)
2955 av_strlcat(filename, "../", sizeof(filename));
2957 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
2958 if (!c->use_absolute_path && !c->fc->open_cb) {
2959 int same_origin = test_same_origin(src, filename);
2962 av_log(c->fc, AV_LOG_ERROR,
2963 "Reference with mismatching origin, %s not tried for security reasons, "
2964 "set demuxer option use_absolute_path to allow it anyway\n",
2966 return AVERROR(ENOENT);
2969 if(strstr(ref->path + l + 1, "..") ||
2970 strstr(ref->path + l + 1, ":") ||
2971 (ref->nlvl_from > 1 && same_origin < 0) ||
2972 (filename[0] == '/' && src_path == src))
2973 return AVERROR(ENOENT);
2976 if (strlen(filename) + 1 == sizeof(filename))
2977 return AVERROR(ENOENT);
2978 if (!open_func(c->fc, pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2981 } else if (c->use_absolute_path) {
2982 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
2983 "this is a possible security issue\n");
2984 if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2986 } else if (c->fc->open_cb) {
2987 if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2990 av_log(c->fc, AV_LOG_ERROR,
2991 "Absolute path %s not tried for security reasons, "
2992 "set demuxer option use_absolute_path to allow absolute paths\n",
2996 return AVERROR(ENOENT);
2999 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
3001 if (sc->time_scale <= 0) {
3002 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
3003 sc->time_scale = c->time_scale;
3004 if (sc->time_scale <= 0)
3009 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3012 MOVStreamContext *sc;
3015 st = avformat_new_stream(c->fc, NULL);
3016 if (!st) return AVERROR(ENOMEM);
3017 st->id = c->fc->nb_streams;
3018 sc = av_mallocz(sizeof(MOVStreamContext));
3019 if (!sc) return AVERROR(ENOMEM);
3022 st->codec->codec_type = AVMEDIA_TYPE_DATA;
3023 sc->ffindex = st->index;
3024 c->trak_index = st->index;
3026 if ((ret = mov_read_default(c, pb, atom)) < 0)
3032 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
3033 (!sc->sample_size && !sc->sample_count))) {
3034 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
3039 fix_timescale(c, sc);
3041 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
3043 mov_build_index(c, st);
3045 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
3046 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
3047 if (mov_open_dref(c, &sc->pb, c->fc->filename, dref,
3048 &c->fc->interrupt_callback) < 0)
3049 av_log(c->fc, AV_LOG_ERROR,
3050 "stream %d, error opening alias: path='%s', dir='%s', "
3051 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
3052 st->index, dref->path, dref->dir, dref->filename,
3053 dref->volume, dref->nlvl_from, dref->nlvl_to);
3056 sc->pb_is_copied = 1;
3059 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3060 if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&
3061 sc->height && sc->width &&
3062 (st->codec->width != sc->width || st->codec->height != sc->height)) {
3063 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
3064 ((double)st->codec->width * sc->height), INT_MAX);
3067 #if FF_API_R_FRAME_RATE
3068 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
3069 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
3070 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
3074 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3075 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
3076 TAG_IS_AVCI(st->codec->codec_tag)) {
3077 ret = ff_generate_avci_extradata(st);
3082 switch (st->codec->codec_id) {
3083 #if CONFIG_H261_DECODER
3084 case AV_CODEC_ID_H261:
3086 #if CONFIG_H263_DECODER
3087 case AV_CODEC_ID_H263:
3089 #if CONFIG_MPEG4_DECODER
3090 case AV_CODEC_ID_MPEG4:
3092 st->codec->width = 0; /* let decoder init width/height */
3093 st->codec->height= 0;
3097 // If the duration of the mp3 packets is not constant, then they could need a parser
3098 if (st->codec->codec_id == AV_CODEC_ID_MP3
3099 && sc->stts_count > 3
3100 && sc->stts_count*10 > st->nb_frames
3101 && sc->time_scale == st->codec->sample_rate) {
3102 st->need_parsing = AVSTREAM_PARSE_FULL;
3104 /* Do not need those anymore. */
3105 av_freep(&sc->chunk_offsets);
3106 av_freep(&sc->stsc_data);
3107 av_freep(&sc->sample_sizes);
3108 av_freep(&sc->keyframes);
3109 av_freep(&sc->stts_data);
3110 av_freep(&sc->stps_data);
3111 av_freep(&sc->elst_data);
3112 av_freep(&sc->rap_group);
3117 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3120 c->itunes_metadata = 1;
3121 ret = mov_read_default(c, pb, atom);
3122 c->itunes_metadata = 0;
3126 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3135 count = avio_rb32(pb);
3136 if (count > UINT_MAX / sizeof(*c->meta_keys)) {
3137 av_log(c->fc, AV_LOG_ERROR,
3138 "The 'keys' atom with the invalid key count: %d\n", count);
3139 return AVERROR_INVALIDDATA;
3142 c->meta_keys_count = count + 1;
3143 c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
3145 return AVERROR(ENOMEM);
3147 for (i = 1; i <= count; ++i) {
3148 uint32_t key_size = avio_rb32(pb);
3149 uint32_t type = avio_rl32(pb);
3151 av_log(c->fc, AV_LOG_ERROR,
3152 "The key# %d in meta has invalid size: %d\n", i, key_size);
3153 return AVERROR_INVALIDDATA;
3156 if (type != MKTAG('m','d','t','a')) {
3157 avio_skip(pb, key_size);
3159 c->meta_keys[i] = av_mallocz(key_size + 1);
3160 if (!c->meta_keys[i])
3161 return AVERROR(ENOMEM);
3162 avio_read(pb, c->meta_keys[i], key_size);
3168 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
3170 int64_t end = avio_tell(pb) + size;
3171 uint8_t *key = NULL, *val = NULL;
3174 MOVStreamContext *sc;
3176 if (c->fc->nb_streams < 1)
3178 st = c->fc->streams[c->fc->nb_streams-1];
3181 for (i = 0; i < 2; i++) {
3186 if (end - avio_tell(pb) <= 12)
3189 len = avio_rb32(pb);
3190 tag = avio_rl32(pb);
3191 avio_skip(pb, 4); // flags
3193 if (len < 12 || len - 12 > end - avio_tell(pb))
3197 if (tag == MKTAG('n', 'a', 'm', 'e'))
3199 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
3206 *p = av_malloc(len + 1);
3209 ret = ffio_read_size(pb, *p, len);
3218 if (strcmp(key, "iTunSMPB") == 0) {
3219 int priming, remainder, samples;
3220 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
3221 if(priming>0 && priming<16384)
3222 sc->start_pad = priming;
3225 if (strcmp(key, "cdec") != 0) {
3226 av_dict_set(&c->fc->metadata, key, val,
3227 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
3232 avio_seek(pb, end, SEEK_SET);
3238 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3240 int64_t end = avio_tell(pb) + atom.size;
3246 len = avio_rb32(pb);
3247 tag = avio_rl32(pb);
3249 if (len > atom.size)
3252 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
3253 uint8_t domain[128];
3256 avio_skip(pb, 4); // flags
3259 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
3260 avio_skip(pb, len - domain_len);
3261 return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
3265 av_log(c->fc, AV_LOG_VERBOSE,
3266 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
3270 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3272 while (atom.size > 8) {
3273 uint32_t tag = avio_rl32(pb);
3275 if (tag == MKTAG('h','d','l','r')) {
3276 avio_seek(pb, -8, SEEK_CUR);
3278 return mov_read_default(c, pb, atom);
3284 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3289 int display_matrix[3][3];
3291 MOVStreamContext *sc;
3295 if (c->fc->nb_streams < 1)
3297 st = c->fc->streams[c->fc->nb_streams-1];
3300 version = avio_r8(pb);
3301 flags = avio_rb24(pb);
3302 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
3308 avio_rb32(pb); /* creation time */
3309 avio_rb32(pb); /* modification time */
3311 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
3312 avio_rb32(pb); /* reserved */
3314 /* highlevel (considering edits) duration in movie timebase */
3315 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
3316 avio_rb32(pb); /* reserved */
3317 avio_rb32(pb); /* reserved */
3319 avio_rb16(pb); /* layer */
3320 avio_rb16(pb); /* alternate group */
3321 avio_rb16(pb); /* volume */
3322 avio_rb16(pb); /* reserved */
3324 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
3325 // they're kept in fixed point format through all calculations
3326 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
3327 // side data, but the scale factor is not needed to calculate aspect ratio
3328 for (i = 0; i < 3; i++) {
3329 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
3330 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
3331 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
3334 width = avio_rb32(pb); // 16.16 fixed point track width
3335 height = avio_rb32(pb); // 16.16 fixed point track height
3336 sc->width = width >> 16;
3337 sc->height = height >> 16;
3339 // save the matrix and add rotate metadata when it is not the default
3341 if (display_matrix[0][0] != (1 << 16) ||
3342 display_matrix[1][1] != (1 << 16) ||
3343 display_matrix[2][2] != (1 << 30) ||
3344 display_matrix[0][1] || display_matrix[0][2] ||
3345 display_matrix[1][0] || display_matrix[1][2] ||
3346 display_matrix[2][0] || display_matrix[2][1]) {
3350 av_freep(&sc->display_matrix);
3351 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
3352 if (!sc->display_matrix)
3353 return AVERROR(ENOMEM);
3355 for (i = 0; i < 3; i++)
3356 for (j = 0; j < 3; j++)
3357 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
3359 rotate = av_display_rotation_get(sc->display_matrix);
3360 if (!isnan(rotate)) {
3361 char rotate_buf[64];
3363 if (rotate < 0) // for backward compatibility
3365 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
3366 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
3370 // transform the display width/height according to the matrix
3371 // to keep the same scale, use [width height 1<<16]
3372 if (width && height && sc->display_matrix) {
3373 double disp_transform[2];
3375 for (i = 0; i < 2; i++)
3376 disp_transform[i] = hypot(display_matrix[i][0], display_matrix[i][1]);
3378 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
3379 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
3380 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
3381 st->sample_aspect_ratio = av_d2q(
3382 disp_transform[0] / disp_transform[1],
3388 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3390 MOVFragment *frag = &c->fragment;
3391 MOVTrackExt *trex = NULL;
3392 MOVFragmentIndex* index = NULL;
3393 int flags, track_id, i, found = 0;
3395 avio_r8(pb); /* version */
3396 flags = avio_rb24(pb);
3398 track_id = avio_rb32(pb);
3400 return AVERROR_INVALIDDATA;
3401 frag->track_id = track_id;
3402 for (i = 0; i < c->trex_count; i++)
3403 if (c->trex_data[i].track_id == frag->track_id) {
3404 trex = &c->trex_data[i];
3408 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
3409 return AVERROR_INVALIDDATA;
3412 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
3413 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
3414 frag->moof_offset : frag->implicit_offset;
3415 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
3417 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
3418 avio_rb32(pb) : trex->duration;
3419 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
3420 avio_rb32(pb) : trex->size;
3421 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
3422 avio_rb32(pb) : trex->flags;
3423 frag->time = AV_NOPTS_VALUE;
3424 for (i = 0; i < c->fragment_index_count; i++) {
3426 MOVFragmentIndex* candidate = c->fragment_index_data[i];
3427 if (candidate->track_id == frag->track_id) {
3428 av_log(c->fc, AV_LOG_DEBUG,
3429 "found fragment index for track %u\n", frag->track_id);
3431 for (j = index->current_item; j < index->item_count; j++) {
3432 if (frag->implicit_offset == index->items[j].moof_offset) {
3433 av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
3434 "for track %u and moof_offset %"PRId64"\n",
3435 frag->track_id, index->items[j].moof_offset);
3436 frag->time = index->items[j].time;
3437 index->current_item = j + 1;
3446 if (index && !found) {
3447 av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
3448 "it doesn't have an (in-order) entry for moof_offset "
3449 "%"PRId64"\n", frag->track_id, frag->implicit_offset);
3451 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
3455 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3457 c->chapter_track = avio_rb32(pb);
3461 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3466 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
3467 return AVERROR_INVALIDDATA;
3468 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
3469 sizeof(*c->trex_data))) < 0) {
3474 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
3476 trex = &c->trex_data[c->trex_count++];
3477 avio_r8(pb); /* version */
3478 avio_rb24(pb); /* flags */
3479 trex->track_id = avio_rb32(pb);
3480 trex->stsd_id = avio_rb32(pb);
3481 trex->duration = avio_rb32(pb);
3482 trex->size = avio_rb32(pb);
3483 trex->flags = avio_rb32(pb);
3487 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3489 MOVFragment *frag = &c->fragment;
3490 AVStream *st = NULL;
3491 MOVStreamContext *sc;
3494 for (i = 0; i < c->fc->nb_streams; i++) {
3495 if (c->fc->streams[i]->id == frag->track_id) {
3496 st = c->fc->streams[i];
3501 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3502 return AVERROR_INVALIDDATA;
3505 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
3507 version = avio_r8(pb);
3508 avio_rb24(pb); /* flags */
3510 sc->track_end = avio_rb64(pb);
3512 sc->track_end = avio_rb32(pb);
3517 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3519 MOVFragment *frag = &c->fragment;
3520 AVStream *st = NULL;
3521 MOVStreamContext *sc;
3525 int data_offset = 0;
3526 unsigned entries, first_sample_flags = frag->flags;
3527 int flags, distance, i, err;
3529 for (i = 0; i < c->fc->nb_streams; i++) {
3530 if (c->fc->streams[i]->id == frag->track_id) {
3531 st = c->fc->streams[i];
3536 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3537 return AVERROR_INVALIDDATA;
3540 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3542 avio_r8(pb); /* version */
3543 flags = avio_rb24(pb);
3544 entries = avio_rb32(pb);
3545 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
3547 /* Always assume the presence of composition time offsets.
3548 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3549 * 1) in the initial movie, there are no samples.
3550 * 2) in the first movie fragment, there is only one sample without composition time offset.
3551 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
3552 if (!sc->ctts_count && sc->sample_count)
3554 /* Complement ctts table if moov atom doesn't have ctts atom. */
3555 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3557 return AVERROR(ENOMEM);
3558 sc->ctts_data = ctts_data;
3559 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3560 sc->ctts_data[sc->ctts_count].duration = 0;
3563 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3564 return AVERROR_INVALIDDATA;
3565 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3566 sizeof(*sc->ctts_data))) < 0) {
3570 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
3571 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3572 dts = sc->track_end - sc->time_offset;
3573 offset = frag->base_data_offset + data_offset;
3575 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3576 for (i = 0; i < entries && !pb->eof_reached; i++) {
3577 unsigned sample_size = frag->size;
3578 int sample_flags = i ? frag->flags : first_sample_flags;
3579 unsigned sample_duration = frag->duration;
3582 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3583 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
3584 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
3585 sc->ctts_data[sc->ctts_count].count = 1;
3586 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3588 mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
3589 if (frag->time != AV_NOPTS_VALUE) {
3590 if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3591 int64_t pts = frag->time;
3592 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3593 " sc->dts_shift %d ctts.duration %d"
3594 " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3595 sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3596 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3597 dts = pts - sc->dts_shift;
3598 if (flags & MOV_TRUN_SAMPLE_CTS) {
3599 dts -= sc->ctts_data[sc->ctts_count].duration;
3601 dts -= sc->time_offset;
3603 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3606 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3607 ", using it for dts\n", dts);
3609 frag->time = AV_NOPTS_VALUE;
3612 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3616 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3617 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3620 err = av_add_index_entry(st, offset, dts, sample_size, distance,
3621 keyframe ? AVINDEX_KEYFRAME : 0);
3623 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
3625 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3626 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3627 offset, dts, sample_size, distance, keyframe);
3629 dts += sample_duration;
3630 offset += sample_size;
3631 sc->data_size += sample_size;
3632 sc->duration_for_fps += sample_duration;
3633 sc->nb_frames_for_fps ++;
3636 if (pb->eof_reached)
3639 frag->implicit_offset = offset;
3641 sc->track_end = dts + sc->time_offset;
3642 if (st->duration < sc->track_end)
3643 st->duration = sc->track_end;
3648 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3650 int64_t offset = avio_tell(pb) + atom.size, pts;
3652 unsigned i, track_id;
3653 AVStream *st = NULL;
3654 MOVStreamContext *sc;
3655 MOVFragmentIndex *index = NULL;
3656 MOVFragmentIndex **tmp;
3657 AVRational timescale;
3659 version = avio_r8(pb);
3661 avpriv_request_sample(c->fc, "sidx version %u", version);
3662 return AVERROR_PATCHWELCOME;
3665 avio_rb24(pb); // flags
3667 track_id = avio_rb32(pb); // Reference ID
3668 for (i = 0; i < c->fc->nb_streams; i++) {
3669 if (c->fc->streams[i]->id == track_id) {
3670 st = c->fc->streams[i];
3675 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", track_id);
3676 return AVERROR_INVALIDDATA;
3681 timescale = av_make_q(1, avio_rb32(pb));
3684 pts = avio_rb32(pb);
3685 offset += avio_rb32(pb);
3687 pts = avio_rb64(pb);
3688 offset += avio_rb64(pb);
3691 avio_rb16(pb); // reserved
3693 index = av_mallocz(sizeof(MOVFragmentIndex));
3695 return AVERROR(ENOMEM);
3697 index->track_id = track_id;
3699 index->item_count = avio_rb16(pb);
3700 index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
3702 if (!index->items) {
3704 return AVERROR(ENOMEM);
3707 for (i = 0; i < index->item_count; i++) {
3708 uint32_t size = avio_rb32(pb);
3709 uint32_t duration = avio_rb32(pb);
3710 if (size & 0x80000000) {
3711 avpriv_request_sample(c->fc, "sidx reference_type 1");
3712 av_freep(&index->items);
3714 return AVERROR_PATCHWELCOME;
3716 avio_rb32(pb); // sap_flags
3717 index->items[i].moof_offset = offset;
3718 index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
3723 st->duration = sc->track_end = pts;
3725 tmp = av_realloc_array(c->fragment_index_data,
3726 c->fragment_index_count + 1,
3727 sizeof(MOVFragmentIndex*));
3729 av_freep(&index->items);
3731 return AVERROR(ENOMEM);
3734 c->fragment_index_data = tmp;
3735 c->fragment_index_data[c->fragment_index_count++] = index;
3737 if (offset == avio_size(pb))
3738 c->fragment_index_complete = 1;
3743 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3744 /* like the files created with Adobe Premiere 5.0, for samples see */
3745 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3746 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3751 return 0; /* continue */
3752 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3753 avio_skip(pb, atom.size - 4);
3756 atom.type = avio_rl32(pb);
3758 if (atom.type != MKTAG('m','d','a','t')) {
3759 avio_skip(pb, atom.size);
3762 err = mov_read_mdat(c, pb, atom);
3766 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3771 uint8_t *moov_data; /* uncompressed data */
3772 long cmov_len, moov_len;
3775 avio_rb32(pb); /* dcom atom */
3776 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3777 return AVERROR_INVALIDDATA;
3778 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3779 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3780 return AVERROR_INVALIDDATA;
3782 avio_rb32(pb); /* cmvd atom */
3783 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3784 return AVERROR_INVALIDDATA;
3785 moov_len = avio_rb32(pb); /* uncompressed size */
3786 cmov_len = atom.size - 6 * 4;
3788 cmov_data = av_malloc(cmov_len);
3790 return AVERROR(ENOMEM);
3791 moov_data = av_malloc(moov_len);
3794 return AVERROR(ENOMEM);
3796 ret = ffio_read_size(pb, cmov_data, cmov_len);
3798 goto free_and_return;
3800 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3801 goto free_and_return;
3802 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3803 goto free_and_return;
3804 ctx.seekable = AVIO_SEEKABLE_NORMAL;
3805 atom.type = MKTAG('m','o','o','v');
3806 atom.size = moov_len;
3807 ret = mov_read_default(c, &ctx, atom);
3813 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3814 return AVERROR(ENOSYS);
3818 /* edit list atom */
3819 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3821 MOVStreamContext *sc;
3822 int i, edit_count, version;
3824 if (c->fc->nb_streams < 1 || c->ignore_editlist)
3826 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3828 version = avio_r8(pb); /* version */
3829 avio_rb24(pb); /* flags */
3830 edit_count = avio_rb32(pb); /* entries */
3835 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
3836 av_free(sc->elst_data);
3838 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
3840 return AVERROR(ENOMEM);
3842 av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3843 for (i = 0; i < edit_count && !pb->eof_reached; i++) {
3844 MOVElst *e = &sc->elst_data[i];
3847 e->duration = avio_rb64(pb);
3848 e->time = avio_rb64(pb);
3850 e->duration = avio_rb32(pb); /* segment duration */
3851 e->time = (int32_t)avio_rb32(pb); /* media time */
3853 e->rate = avio_rb32(pb) / 65536.0;
3854 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3855 e->duration, e->time, e->rate);
3862 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3864 MOVStreamContext *sc;
3866 if (c->fc->nb_streams < 1)
3867 return AVERROR_INVALIDDATA;
3868 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3869 sc->timecode_track = avio_rb32(pb);
3873 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3877 static const uint8_t uuid_isml_manifest[] = {
3878 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3879 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3882 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3883 return AVERROR_INVALIDDATA;
3885 ret = avio_read(pb, uuid, sizeof(uuid));
3888 } else if (ret != sizeof(uuid)) {
3889 return AVERROR_INVALIDDATA;
3891 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3892 uint8_t *buffer, *ptr;
3894 size_t len = atom.size - sizeof(uuid);
3897 return AVERROR_INVALIDDATA;
3899 ret = avio_skip(pb, 4); // zeroes
3902 buffer = av_mallocz(len + 1);
3904 return AVERROR(ENOMEM);
3906 ret = avio_read(pb, buffer, len);
3910 } else if (ret != len) {
3912 return AVERROR_INVALIDDATA;
3916 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
3917 ptr += sizeof("systemBitrate=\"") - 1;
3918 c->bitrates_count++;
3919 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3921 c->bitrates_count = 0;
3923 return AVERROR(ENOMEM);
3926 ret = strtol(ptr, &endptr, 10);
3927 if (ret < 0 || errno || *endptr != '"') {
3928 c->bitrates[c->bitrates_count - 1] = 0;
3930 c->bitrates[c->bitrates_count - 1] = ret;
3939 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3942 uint8_t content[16];
3947 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
3953 && !memcmp(content, "Anevia\x1A\x1A", 8)
3954 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
3955 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
3961 static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3963 uint32_t format = avio_rl32(pb);
3964 MOVStreamContext *sc;
3968 if (c->fc->nb_streams < 1)
3970 st = c->fc->streams[c->fc->nb_streams - 1];
3975 case MKTAG('e','n','c','v'): // encrypted video
3976 case MKTAG('e','n','c','a'): // encrypted audio
3977 id = mov_codec_id(st, format);
3978 if (st->codec->codec_id != AV_CODEC_ID_NONE &&
3979 st->codec->codec_id != id) {
3980 av_log(c->fc, AV_LOG_WARNING,
3981 "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
3982 (char*)&format, st->codec->codec_id);
3986 st->codec->codec_id = id;
3987 sc->format = format;
3991 av_log(c->fc, AV_LOG_WARNING,
3992 "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
3993 (char*)&format, (char*)&sc->format);
4000 static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4003 MOVStreamContext *sc;
4004 size_t auxiliary_info_size;
4006 if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
4009 st = c->fc->streams[c->fc->nb_streams - 1];
4012 if (sc->cenc.aes_ctr) {
4013 av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
4014 return AVERROR_INVALIDDATA;
4017 avio_r8(pb); /* version */
4018 sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
4020 avio_rb32(pb); /* entries */
4022 if (atom.size < 8) {
4023 av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" too small\n", atom.size);
4024 return AVERROR_INVALIDDATA;
4027 /* save the auxiliary info as is */
4028 auxiliary_info_size = atom.size - 8;
4030 sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
4031 if (!sc->cenc.auxiliary_info) {
4032 return AVERROR(ENOMEM);
4035 sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
4037 sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
4039 if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
4040 av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
4041 return AVERROR_INVALIDDATA;
4044 /* initialize the cipher */
4045 sc->cenc.aes_ctr = av_aes_ctr_alloc();
4046 if (!sc->cenc.aes_ctr) {
4047 return AVERROR(ENOMEM);
4050 return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
4053 static int cenc_filter(MOVContext *c, MOVStreamContext *sc, uint8_t *input, int size)
4055 uint32_t encrypted_bytes;
4056 uint16_t subsample_count;
4057 uint16_t clear_bytes;
4058 uint8_t* input_end = input + size;
4061 if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4062 av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
4063 return AVERROR_INVALIDDATA;
4066 av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
4067 sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
4069 if (!sc->cenc.use_subsamples)
4071 /* decrypt the whole packet */
4072 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
4076 /* read the subsample count */
4077 if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4078 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
4079 return AVERROR_INVALIDDATA;
4082 subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
4083 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
4085 for (; subsample_count > 0; subsample_count--)
4087 if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4088 av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
4089 return AVERROR_INVALIDDATA;
4092 /* read the number of clear / encrypted bytes */
4093 clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
4094 sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
4095 encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
4096 sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
4098 if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
4099 av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
4100 return AVERROR_INVALIDDATA;
4103 /* skip the clear bytes */
4104 input += clear_bytes;
4106 /* decrypt the encrypted bytes */
4107 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
4108 input += encrypted_bytes;
4111 if (input < input_end) {
4112 av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
4113 return AVERROR_INVALIDDATA;
4119 static const MOVParseTableEntry mov_default_parse_table[] = {
4120 { MKTAG('A','C','L','R'), mov_read_aclr },
4121 { MKTAG('A','P','R','G'), mov_read_avid },
4122 { MKTAG('A','A','L','P'), mov_read_avid },
4123 { MKTAG('A','R','E','S'), mov_read_ares },
4124 { MKTAG('a','v','s','s'), mov_read_avss },
4125 { MKTAG('c','h','p','l'), mov_read_chpl },
4126 { MKTAG('c','o','6','4'), mov_read_stco },
4127 { MKTAG('c','o','l','r'), mov_read_colr },
4128 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
4129 { MKTAG('d','i','n','f'), mov_read_default },
4130 { MKTAG('D','p','x','E'), mov_read_dpxe },
4131 { MKTAG('d','r','e','f'), mov_read_dref },
4132 { MKTAG('e','d','t','s'), mov_read_default },
4133 { MKTAG('e','l','s','t'), mov_read_elst },
4134 { MKTAG('e','n','d','a'), mov_read_enda },
4135 { MKTAG('f','i','e','l'), mov_read_fiel },
4136 { MKTAG('a','d','r','m'), mov_read_adrm },
4137 { MKTAG('f','t','y','p'), mov_read_ftyp },
4138 { MKTAG('g','l','b','l'), mov_read_glbl },
4139 { MKTAG('h','d','l','r'), mov_read_hdlr },
4140 { MKTAG('i','l','s','t'), mov_read_ilst },
4141 { MKTAG('j','p','2','h'), mov_read_jp2h },
4142 { MKTAG('m','d','a','t'), mov_read_mdat },
4143 { MKTAG('m','d','h','d'), mov_read_mdhd },
4144 { MKTAG('m','d','i','a'), mov_read_default },
4145 { MKTAG('m','e','t','a'), mov_read_meta },
4146 { MKTAG('m','i','n','f'), mov_read_default },
4147 { MKTAG('m','o','o','f'), mov_read_moof },
4148 { MKTAG('m','o','o','v'), mov_read_moov },
4149 { MKTAG('m','v','e','x'), mov_read_default },
4150 { MKTAG('m','v','h','d'), mov_read_mvhd },
4151 { MKTAG('S','M','I',' '), mov_read_svq3 },
4152 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
4153 { MKTAG('a','v','c','C'), mov_read_glbl },
4154 { MKTAG('p','a','s','p'), mov_read_pasp },
4155 { MKTAG('s','i','d','x'), mov_read_sidx },
4156 { MKTAG('s','t','b','l'), mov_read_default },
4157 { MKTAG('s','t','c','o'), mov_read_stco },
4158 { MKTAG('s','t','p','s'), mov_read_stps },
4159 { MKTAG('s','t','r','f'), mov_read_strf },
4160 { MKTAG('s','t','s','c'), mov_read_stsc },
4161 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
4162 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
4163 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
4164 { MKTAG('s','t','t','s'), mov_read_stts },
4165 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
4166 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
4167 { MKTAG('t','f','d','t'), mov_read_tfdt },
4168 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
4169 { MKTAG('t','r','a','k'), mov_read_trak },
4170 { MKTAG('t','r','a','f'), mov_read_default },
4171 { MKTAG('t','r','e','f'), mov_read_default },
4172 { MKTAG('t','m','c','d'), mov_read_tmcd },
4173 { MKTAG('c','h','a','p'), mov_read_chap },
4174 { MKTAG('t','r','e','x'), mov_read_trex },
4175 { MKTAG('t','r','u','n'), mov_read_trun },
4176 { MKTAG('u','d','t','a'), mov_read_default },
4177 { MKTAG('w','a','v','e'), mov_read_wave },
4178 { MKTAG('e','s','d','s'), mov_read_esds },
4179 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
4180 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
4181 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
4182 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
4183 { MKTAG('w','f','e','x'), mov_read_wfex },
4184 { MKTAG('c','m','o','v'), mov_read_cmov },
4185 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
4186 { MKTAG('d','v','c','1'), mov_read_dvc1 },
4187 { MKTAG('s','b','g','p'), mov_read_sbgp },
4188 { MKTAG('h','v','c','C'), mov_read_glbl },
4189 { MKTAG('u','u','i','d'), mov_read_uuid },
4190 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
4191 { MKTAG('f','r','e','e'), mov_read_free },
4192 { MKTAG('-','-','-','-'), mov_read_custom },
4193 { MKTAG('s','i','n','f'), mov_read_default },
4194 { MKTAG('f','r','m','a'), mov_read_frma },
4195 { MKTAG('s','e','n','c'), mov_read_senc },
4199 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4201 int64_t total_size = 0;
4205 if (c->atom_depth > 10) {
4206 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
4207 return AVERROR_INVALIDDATA;
4212 atom.size = INT64_MAX;
4213 while (total_size + 8 <= atom.size && !avio_feof(pb)) {
4214 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
4217 if (atom.size >= 8) {
4218 a.size = avio_rb32(pb);
4219 a.type = avio_rl32(pb);
4220 if (a.type == MKTAG('f','r','e','e') &&
4224 uint32_t *type = (uint32_t *)buf + 1;
4225 if (avio_read(pb, buf, 8) != 8)
4226 return AVERROR_INVALIDDATA;
4227 avio_seek(pb, -8, SEEK_CUR);
4228 if (*type == MKTAG('m','v','h','d') ||
4229 *type == MKTAG('c','m','o','v')) {
4230 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
4231 a.type = MKTAG('m','o','o','v');
4234 if (atom.type != MKTAG('r','o','o','t') &&
4235 atom.type != MKTAG('m','o','o','v'))
4237 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
4239 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
4246 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
4247 a.size = avio_rb64(pb) - 8;
4251 av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
4252 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
4254 a.size = atom.size - total_size + 8;
4259 a.size = FFMIN(a.size, atom.size - total_size);
4261 for (i = 0; mov_default_parse_table[i].type; i++)
4262 if (mov_default_parse_table[i].type == a.type) {
4263 parse = mov_default_parse_table[i].parse;
4267 // container is user data
4268 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
4269 atom.type == MKTAG('i','l','s','t')))
4270 parse = mov_read_udta_string;
4272 // Supports parsing the QuickTime Metadata Keys.
4273 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
4274 if (!parse && c->found_hdlr_mdta &&
4275 atom.type == MKTAG('m','e','t','a') &&
4276 a.type == MKTAG('k','e','y','s')) {
4277 parse = mov_read_keys;
4280 if (!parse) { /* skip leaf atoms data */
4281 avio_skip(pb, a.size);
4283 int64_t start_pos = avio_tell(pb);
4285 int err = parse(c, pb, a);
4290 if (c->found_moov && c->found_mdat &&
4291 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
4292 start_pos + a.size == avio_size(pb))) {
4293 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
4294 c->next_root_atom = start_pos + a.size;
4298 left = a.size - avio_tell(pb) + start_pos;
4299 if (left > 0) /* skip garbage at atom end */
4300 avio_skip(pb, left);
4301 else if (left < 0) {
4302 av_log(c->fc, AV_LOG_WARNING,
4303 "overread end of atom '%.4s' by %"PRId64" bytes\n",
4304 (char*)&a.type, -left);
4305 avio_seek(pb, left, SEEK_CUR);
4309 total_size += a.size;
4312 if (total_size < atom.size && atom.size < 0x7ffff)
4313 avio_skip(pb, atom.size - total_size);
4319 static int mov_probe(AVProbeData *p)
4324 int moov_offset = -1;
4326 /* check file header */
4329 /* ignore invalid offset */
4330 if ((offset + 8) > (unsigned int)p->buf_size)
4332 tag = AV_RL32(p->buf + offset + 4);
4334 /* check for obvious tags */
4335 case MKTAG('m','o','o','v'):
4336 moov_offset = offset + 4;
4337 case MKTAG('m','d','a','t'):
4338 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
4339 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
4340 case MKTAG('f','t','y','p'):
4341 if (AV_RB32(p->buf+offset) < 8 &&
4342 (AV_RB32(p->buf+offset) != 1 ||
4343 offset + 12 > (unsigned int)p->buf_size ||
4344 AV_RB64(p->buf+offset + 8) == 0)) {
4345 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4346 } else if (tag == MKTAG('f','t','y','p') &&
4347 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
4348 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
4350 score = FFMAX(score, 5);
4352 score = AVPROBE_SCORE_MAX;
4354 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4356 /* those are more common words, so rate then a bit less */
4357 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
4358 case MKTAG('w','i','d','e'):
4359 case MKTAG('f','r','e','e'):
4360 case MKTAG('j','u','n','k'):
4361 case MKTAG('p','i','c','t'):
4362 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
4363 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4365 case MKTAG(0x82,0x82,0x7f,0x7d):
4366 case MKTAG('s','k','i','p'):
4367 case MKTAG('u','u','i','d'):
4368 case MKTAG('p','r','f','l'):
4369 /* if we only find those cause probedata is too small at least rate them */
4370 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4371 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4374 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4377 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
4378 /* moov atom in the header - we should make sure that this is not a
4379 * MOV-packed MPEG-PS */
4380 offset = moov_offset;
4382 while(offset < (p->buf_size - 16)){ /* Sufficient space */
4383 /* We found an actual hdlr atom */
4384 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
4385 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
4386 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
4387 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
4388 /* We found a media handler reference atom describing an
4389 * MPEG-PS-in-MOV, return a
4390 * low score to force expanding the probe window until
4391 * mpegps_probe finds what it needs */
4402 // must be done after parsing all trak because there's no order requirement
4403 static void mov_read_chapters(AVFormatContext *s)
4405 MOVContext *mov = s->priv_data;
4406 AVStream *st = NULL;
4407 MOVStreamContext *sc;
4411 for (i = 0; i < s->nb_streams; i++)
4412 if (s->streams[i]->id == mov->chapter_track) {
4417 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
4421 st->discard = AVDISCARD_ALL;
4423 cur_pos = avio_tell(sc->pb);
4425 for (i = 0; i < st->nb_index_entries; i++) {
4426 AVIndexEntry *sample = &st->index_entries[i];
4427 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
4432 if (end < sample->timestamp) {
4433 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
4434 end = AV_NOPTS_VALUE;
4437 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4438 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
4442 // the first two bytes are the length of the title
4443 len = avio_rb16(sc->pb);
4444 if (len > sample->size-2)
4446 title_len = 2*len + 1;
4447 if (!(title = av_mallocz(title_len)))
4450 // The samples could theoretically be in any encoding if there's an encd
4451 // atom following, but in practice are only utf-8 or utf-16, distinguished
4452 // instead by the presence of a BOM
4456 ch = avio_rb16(sc->pb);
4458 avio_get_str16be(sc->pb, len, title, title_len);
4459 else if (ch == 0xfffe)
4460 avio_get_str16le(sc->pb, len, title, title_len);
4463 if (len == 1 || len == 2)
4466 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
4470 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
4474 avio_seek(sc->pb, cur_pos, SEEK_SET);
4477 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
4478 uint32_t value, int flags)
4481 char buf[AV_TIMECODE_STR_SIZE];
4482 AVRational rate = {st->codec->time_base.den,
4483 st->codec->time_base.num};
4484 int ret = av_timecode_init(&tc, rate, flags, 0, s);
4487 av_dict_set(&st->metadata, "timecode",
4488 av_timecode_make_string(&tc, buf, value), 0);
4492 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
4494 MOVStreamContext *sc = st->priv_data;
4496 int64_t cur_pos = avio_tell(sc->pb);
4499 if (!st->nb_index_entries)
4502 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
4503 value = avio_rb32(s->pb);
4505 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
4506 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
4507 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
4509 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
4510 * not the case) and thus assume "frame number format" instead of QT one.
4511 * No sample with tmcd track can be found with a QT timecode at the moment,
4512 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
4514 parse_timecode_in_framenum_format(s, st, value, flags);
4516 avio_seek(sc->pb, cur_pos, SEEK_SET);
4520 static int mov_read_close(AVFormatContext *s)
4522 MOVContext *mov = s->priv_data;
4525 for (i = 0; i < s->nb_streams; i++) {
4526 AVStream *st = s->streams[i];
4527 MOVStreamContext *sc = st->priv_data;
4532 av_freep(&sc->ctts_data);
4533 for (j = 0; j < sc->drefs_count; j++) {
4534 av_freep(&sc->drefs[j].path);
4535 av_freep(&sc->drefs[j].dir);
4537 av_freep(&sc->drefs);
4539 sc->drefs_count = 0;
4541 if (!sc->pb_is_copied)
4542 avio_closep(&sc->pb);
4545 av_freep(&sc->chunk_offsets);
4546 av_freep(&sc->stsc_data);
4547 av_freep(&sc->sample_sizes);
4548 av_freep(&sc->keyframes);
4549 av_freep(&sc->stts_data);
4550 av_freep(&sc->stps_data);
4551 av_freep(&sc->elst_data);
4552 av_freep(&sc->rap_group);
4553 av_freep(&sc->display_matrix);
4555 av_freep(&sc->cenc.auxiliary_info);
4556 av_aes_ctr_free(sc->cenc.aes_ctr);
4559 if (mov->dv_demux) {
4560 avformat_free_context(mov->dv_fctx);
4561 mov->dv_fctx = NULL;
4564 if (mov->meta_keys) {
4565 for (i = 1; i < mov->meta_keys_count; i++) {
4566 av_freep(&mov->meta_keys[i]);
4568 av_freep(&mov->meta_keys);
4571 av_freep(&mov->trex_data);
4572 av_freep(&mov->bitrates);
4574 for (i = 0; i < mov->fragment_index_count; i++) {
4575 MOVFragmentIndex* index = mov->fragment_index_data[i];
4576 av_freep(&index->items);
4577 av_freep(&mov->fragment_index_data[i]);
4579 av_freep(&mov->fragment_index_data);
4581 av_freep(&mov->aes_decrypt);
4586 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
4590 for (i = 0; i < s->nb_streams; i++) {
4591 AVStream *st = s->streams[i];
4592 MOVStreamContext *sc = st->priv_data;
4594 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4595 sc->timecode_track == tmcd_id)
4601 /* look for a tmcd track not referenced by any video track, and export it globally */
4602 static void export_orphan_timecode(AVFormatContext *s)
4606 for (i = 0; i < s->nb_streams; i++) {
4607 AVStream *st = s->streams[i];
4609 if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
4610 !tmcd_is_referenced(s, i + 1)) {
4611 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
4613 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
4620 static int read_tfra(MOVContext *mov, AVIOContext *f)
4622 MOVFragmentIndex* index = NULL;
4623 int version, fieldlength, i, j;
4624 int64_t pos = avio_tell(f);
4625 uint32_t size = avio_rb32(f);
4628 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
4631 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
4632 index = av_mallocz(sizeof(MOVFragmentIndex));
4634 return AVERROR(ENOMEM);
4637 tmp = av_realloc_array(mov->fragment_index_data,
4638 mov->fragment_index_count + 1,
4639 sizeof(MOVFragmentIndex*));
4642 return AVERROR(ENOMEM);
4644 mov->fragment_index_data = tmp;
4645 mov->fragment_index_data[mov->fragment_index_count++] = index;
4647 version = avio_r8(f);
4649 index->track_id = avio_rb32(f);
4650 fieldlength = avio_rb32(f);
4651 index->item_count = avio_rb32(f);
4652 index->items = av_mallocz_array(
4653 index->item_count, sizeof(MOVFragmentIndexItem));
4654 if (!index->items) {
4655 index->item_count = 0;
4656 return AVERROR(ENOMEM);
4658 for (i = 0; i < index->item_count; i++) {
4659 int64_t time, offset;
4661 time = avio_rb64(f);
4662 offset = avio_rb64(f);
4664 time = avio_rb32(f);
4665 offset = avio_rb32(f);
4667 index->items[i].time = time;
4668 index->items[i].moof_offset = offset;
4669 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
4671 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
4673 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
4677 avio_seek(f, pos + size, SEEK_SET);
4681 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
4683 int64_t stream_size = avio_size(f);
4684 int64_t original_pos = avio_tell(f);
4688 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
4692 mfra_size = avio_rb32(f);
4693 if (mfra_size < 0 || mfra_size > stream_size) {
4694 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
4697 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
4701 if (avio_rb32(f) != mfra_size) {
4702 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
4705 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
4706 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
4709 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
4711 ret = read_tfra(c, f);
4717 seek_ret = avio_seek(f, original_pos, SEEK_SET);
4719 av_log(c->fc, AV_LOG_ERROR,
4720 "failed to seek back after looking for mfra\n");
4726 static int mov_read_header(AVFormatContext *s)
4728 MOVContext *mov = s->priv_data;
4729 AVIOContext *pb = s->pb;
4731 MOVAtom atom = { AV_RL32("root") };
4734 if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
4735 av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
4736 mov->decryption_key_len, AES_CTR_KEY_SIZE);
4737 return AVERROR(EINVAL);
4741 mov->trak_index = -1;
4742 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
4744 atom.size = avio_size(pb);
4746 atom.size = INT64_MAX;
4748 /* check MOV header */
4750 if (mov->moov_retry)
4751 avio_seek(pb, 0, SEEK_SET);
4752 if ((err = mov_read_default(mov, pb, atom)) < 0) {
4753 av_log(s, AV_LOG_ERROR, "error reading header\n");
4757 } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
4758 if (!mov->found_moov) {
4759 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
4761 return AVERROR_INVALIDDATA;
4763 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
4766 if (mov->chapter_track > 0 && !mov->ignore_chapters)
4767 mov_read_chapters(s);
4768 for (i = 0; i < s->nb_streams; i++)
4769 if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
4770 mov_read_timecode_track(s, s->streams[i]);
4773 /* copy timecode metadata from tmcd tracks to the related video streams */
4774 for (i = 0; i < s->nb_streams; i++) {
4775 AVStream *st = s->streams[i];
4776 MOVStreamContext *sc = st->priv_data;
4777 if (sc->timecode_track > 0) {
4778 AVDictionaryEntry *tcr;
4779 int tmcd_st_id = -1;
4781 for (j = 0; j < s->nb_streams; j++)
4782 if (s->streams[j]->id == sc->timecode_track)
4785 if (tmcd_st_id < 0 || tmcd_st_id == i)
4787 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
4789 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
4792 export_orphan_timecode(s);
4794 for (i = 0; i < s->nb_streams; i++) {
4795 AVStream *st = s->streams[i];
4796 MOVStreamContext *sc = st->priv_data;
4797 fix_timescale(mov, sc);
4798 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
4799 st->skip_samples = sc->start_pad;
4801 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
4802 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4803 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
4804 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4805 if (st->codec->width <= 0 || st->codec->height <= 0) {
4806 st->codec->width = sc->width;
4807 st->codec->height = sc->height;
4809 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
4810 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
4814 if (mov->handbrake_version &&
4815 mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
4816 st->codec->codec_id == AV_CODEC_ID_MP3
4818 av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
4819 st->need_parsing = AVSTREAM_PARSE_FULL;
4823 if (mov->trex_data) {
4824 for (i = 0; i < s->nb_streams; i++) {
4825 AVStream *st = s->streams[i];
4826 MOVStreamContext *sc = st->priv_data;
4827 if (st->duration > 0)
4828 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
4832 if (mov->use_mfra_for > 0) {
4833 for (i = 0; i < s->nb_streams; i++) {
4834 AVStream *st = s->streams[i];
4835 MOVStreamContext *sc = st->priv_data;
4836 if (sc->duration_for_fps > 0) {
4837 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
4838 sc->duration_for_fps;
4843 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
4844 if (mov->bitrates[i]) {
4845 s->streams[i]->codec->bit_rate = mov->bitrates[i];
4849 ff_rfps_calculate(s);
4851 for (i = 0; i < s->nb_streams; i++) {
4852 AVStream *st = s->streams[i];
4853 MOVStreamContext *sc = st->priv_data;
4855 switch (st->codec->codec_type) {
4856 case AVMEDIA_TYPE_AUDIO:
4857 err = ff_replaygain_export(st, s->metadata);
4863 case AVMEDIA_TYPE_VIDEO:
4864 if (sc->display_matrix) {
4865 AVPacketSideData *sd, *tmp;
4867 tmp = av_realloc_array(st->side_data,
4868 st->nb_side_data + 1, sizeof(*tmp));
4870 return AVERROR(ENOMEM);
4872 st->side_data = tmp;
4875 sd = &st->side_data[st->nb_side_data - 1];
4876 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
4877 sd->size = sizeof(int32_t) * 9;
4878 sd->data = (uint8_t*)sc->display_matrix;
4879 sc->display_matrix = NULL;
4884 ff_configure_buffers_for_index(s, AV_TIME_BASE);
4889 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
4891 AVIndexEntry *sample = NULL;
4892 int64_t best_dts = INT64_MAX;
4894 for (i = 0; i < s->nb_streams; i++) {
4895 AVStream *avst = s->streams[i];
4896 MOVStreamContext *msc = avst->priv_data;
4897 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
4898 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
4899 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
4900 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
4901 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
4903 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
4904 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
4905 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
4906 sample = current_sample;
4915 static int should_retry(AVIOContext *pb, int error_code) {
4916 if (error_code == AVERROR_EOF || avio_feof(pb))
4922 static int mov_switch_root(AVFormatContext *s, int64_t target)
4924 MOVContext *mov = s->priv_data;
4926 int already_read = 0;
4928 if (avio_seek(s->pb, target, SEEK_SET) != target) {
4929 av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
4930 return AVERROR_INVALIDDATA;
4933 mov->next_root_atom = 0;
4935 for (i = 0; i < mov->fragment_index_count; i++) {
4936 MOVFragmentIndex *index = mov->fragment_index_data[i];
4938 for (j = 0; j < index->item_count; j++) {
4939 MOVFragmentIndexItem *item = &index->items[j];
4941 mov->next_root_atom = item->moof_offset;
4942 break; // Advance to next index in outer loop
4943 } else if (item->moof_offset == target) {
4944 index->current_item = FFMIN(j, index->current_item);
4945 if (item->headers_read)
4947 item->headers_read = 1;
4952 index->current_item = 0;
4958 mov->found_mdat = 0;
4960 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
4963 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
4968 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
4970 MOVContext *mov = s->priv_data;
4971 MOVStreamContext *sc;
4972 AVIndexEntry *sample;
4973 AVStream *st = NULL;
4977 sample = mov_find_next_sample(s, &st);
4978 if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
4979 if (!mov->next_root_atom)
4981 if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
4986 /* must be done just before reading, to avoid infinite loop on sample */
4987 sc->current_sample++;
4989 if (mov->next_root_atom) {
4990 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
4991 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
4994 if (st->discard != AVDISCARD_ALL) {
4995 int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
4996 if (ret64 != sample->pos) {
4997 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
4998 sc->ffindex, sample->pos);
4999 sc->current_sample -= should_retry(sc->pb, ret64);
5000 return AVERROR_INVALIDDATA;
5002 ret = av_get_packet(sc->pb, pkt, sample->size);
5004 sc->current_sample -= should_retry(sc->pb, ret);
5007 if (sc->has_palette) {
5010 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
5012 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
5014 memcpy(pal, sc->palette, AVPALETTE_SIZE);
5015 sc->has_palette = 0;
5018 #if CONFIG_DV_DEMUXER
5019 if (mov->dv_demux && sc->dv_audio_container) {
5020 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
5021 av_freep(&pkt->data);
5023 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
5030 pkt->stream_index = sc->ffindex;
5031 pkt->dts = sample->timestamp;
5032 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
5033 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
5034 /* update ctts context */
5036 if (sc->ctts_index < sc->ctts_count &&
5037 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
5039 sc->ctts_sample = 0;
5042 pkt->dts = AV_NOPTS_VALUE;
5044 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
5045 st->index_entries[sc->current_sample].timestamp : st->duration;
5046 pkt->duration = next_dts - pkt->dts;
5047 pkt->pts = pkt->dts;
5049 if (st->discard == AVDISCARD_ALL)
5051 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
5052 pkt->pos = sample->pos;
5055 aax_filter(pkt->data, pkt->size, mov);
5057 if (sc->cenc.aes_ctr) {
5058 ret = cenc_filter(mov, sc, pkt->data, pkt->size);
5067 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
5069 MOVContext *mov = s->priv_data;
5072 if (!mov->fragment_index_complete)
5075 for (i = 0; i < mov->fragment_index_count; i++) {
5076 if (mov->fragment_index_data[i]->track_id == st->id) {
5077 MOVFragmentIndex *index = mov->fragment_index_data[i];
5078 for (j = index->item_count - 1; j >= 0; j--) {
5079 if (index->items[j].time <= timestamp) {
5080 if (index->items[j].headers_read)
5083 return mov_switch_root(s, index->items[j].moof_offset);
5092 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
5094 MOVStreamContext *sc = st->priv_data;
5095 int sample, time_sample;
5098 int ret = mov_seek_fragment(s, st, timestamp);
5102 sample = av_index_search_timestamp(st, timestamp, flags);
5103 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
5104 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
5106 if (sample < 0) /* not sure what to do */
5107 return AVERROR_INVALIDDATA;
5108 sc->current_sample = sample;
5109 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
5110 /* adjust ctts index */
5111 if (sc->ctts_data) {
5113 for (i = 0; i < sc->ctts_count; i++) {
5114 int next = time_sample + sc->ctts_data[i].count;
5115 if (next > sc->current_sample) {
5117 sc->ctts_sample = sc->current_sample - time_sample;
5126 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
5128 MOVContext *mc = s->priv_data;
5133 if (stream_index >= s->nb_streams)
5134 return AVERROR_INVALIDDATA;
5136 st = s->streams[stream_index];
5137 sample = mov_seek_stream(s, st, sample_time, flags);
5141 if (mc->seek_individually) {
5142 /* adjust seek timestamp to found sample timestamp */
5143 int64_t seek_timestamp = st->index_entries[sample].timestamp;
5145 for (i = 0; i < s->nb_streams; i++) {
5147 MOVStreamContext *sc = s->streams[i]->priv_data;
5149 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
5151 if (stream_index == i)
5154 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
5155 mov_seek_stream(s, st, timestamp, flags);
5158 for (i = 0; i < s->nb_streams; i++) {
5159 MOVStreamContext *sc;
5162 sc->current_sample = 0;
5165 MOVStreamContext *sc;
5166 AVIndexEntry *entry = mov_find_next_sample(s, &st);
5168 return AVERROR_INVALIDDATA;
5170 if (sc->ffindex == stream_index && sc->current_sample == sample)
5172 sc->current_sample++;
5178 #define OFFSET(x) offsetof(MOVContext, x)
5179 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
5180 static const AVOption mov_options[] = {
5181 {"use_absolute_path",
5182 "allow using absolute path when opening alias, this is a possible security issue",
5183 OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
5185 {"seek_streams_individually",
5186 "Seek each stream individually to the to the closest point",
5187 OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
5189 {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
5191 {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
5194 "use mfra for fragment timestamps",
5195 OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
5196 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
5198 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
5199 FLAGS, "use_mfra_for" },
5200 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
5201 FLAGS, "use_mfra_for" },
5202 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
5203 FLAGS, "use_mfra_for" },
5204 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
5205 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5206 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
5207 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5208 { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
5209 AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5210 { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
5211 "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
5212 AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
5213 .flags = AV_OPT_FLAG_DECODING_PARAM },
5214 { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5219 static const AVClass mov_class = {
5220 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
5221 .item_name = av_default_item_name,
5222 .option = mov_options,
5223 .version = LIBAVUTIL_VERSION_INT,
5226 AVInputFormat ff_mov_demuxer = {
5227 .name = "mov,mp4,m4a,3gp,3g2,mj2",
5228 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5229 .priv_class = &mov_class,
5230 .priv_data_size = sizeof(MOVContext),
5231 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
5232 .read_probe = mov_probe,
5233 .read_header = mov_read_header,
5234 .read_packet = mov_read_packet,
5235 .read_close = mov_read_close,
5236 .read_seek = mov_read_seek,
5237 .flags = AVFMT_NO_BYTE_SEEK,