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/avassert.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/display.h"
41 #include "libavutil/opt.h"
42 #include "libavutil/aes.h"
43 #include "libavutil/aes_ctr.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/sha.h"
46 #include "libavutil/spherical.h"
47 #include "libavutil/stereo3d.h"
48 #include "libavutil/timecode.h"
49 #include "libavcodec/ac3tab.h"
50 #include "libavcodec/flac.h"
51 #include "libavcodec/mpegaudiodecheader.h"
54 #include "avio_internal.h"
57 #include "libavcodec/get_bits.h"
60 #include "replaygain.h"
66 #include "qtpalette.h"
68 /* those functions parse an atom */
69 /* links atom IDs to parse functions */
70 typedef struct MOVParseTableEntry {
72 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
75 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
76 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
77 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
78 int count, int duration);
80 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
81 unsigned len, const char *key)
85 short current, total = 0;
86 avio_rb16(pb); // unknown
87 current = avio_rb16(pb);
89 total = avio_rb16(pb);
91 snprintf(buf, sizeof(buf), "%d", current);
93 snprintf(buf, sizeof(buf), "%d/%d", current, total);
94 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
95 av_dict_set(&c->fc->metadata, key, buf, 0);
100 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
101 unsigned len, const char *key)
103 /* bypass padding bytes */
108 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
109 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
114 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
115 unsigned len, const char *key)
117 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
118 av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
123 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
124 unsigned len, const char *key)
128 avio_r8(pb); // unknown
131 if (genre < 1 || genre > ID3v1_GENRE_MAX)
133 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
134 av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
139 static const uint32_t mac_to_unicode[128] = {
140 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
141 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
142 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
143 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
144 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
145 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
146 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
147 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
148 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
149 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
150 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
151 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
152 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
153 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
154 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
155 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
158 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
159 char *dst, int dstlen)
162 char *end = dst+dstlen-1;
165 for (i = 0; i < len; i++) {
166 uint8_t t, c = avio_r8(pb);
174 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
180 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
184 MOVStreamContext *sc;
189 case 0xd: id = AV_CODEC_ID_MJPEG; break;
190 case 0xe: id = AV_CODEC_ID_PNG; break;
191 case 0x1b: id = AV_CODEC_ID_BMP; break;
193 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
198 st = avformat_new_stream(c->fc, NULL);
200 return AVERROR(ENOMEM);
201 sc = av_mallocz(sizeof(*sc));
203 return AVERROR(ENOMEM);
206 ret = av_get_packet(pb, &pkt, len);
210 if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
211 if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
212 id = AV_CODEC_ID_PNG;
214 id = AV_CODEC_ID_MJPEG;
218 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
220 st->attached_pic = pkt;
221 st->attached_pic.stream_index = st->index;
222 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
224 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
225 st->codecpar->codec_id = id;
231 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
233 char language[4] = { 0 };
234 char buf[200], place[100];
235 uint16_t langcode = 0;
236 double longitude, latitude, altitude;
237 const char *key = "location";
239 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
240 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
241 return AVERROR_INVALIDDATA;
244 avio_skip(pb, 4); // version+flags
245 langcode = avio_rb16(pb);
246 ff_mov_lang_to_iso639(langcode, language);
249 len -= avio_get_str(pb, len, place, sizeof(place));
251 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
252 return AVERROR_INVALIDDATA;
254 avio_skip(pb, 1); // role
258 av_log(c->fc, AV_LOG_ERROR,
259 "loci too short (%u bytes left, need at least %d)\n", len, 12);
260 return AVERROR_INVALIDDATA;
262 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
263 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
264 altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
266 // Try to output in the same format as the ?xyz field
267 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
269 av_strlcatf(buf, sizeof(buf), "%+f", altitude);
270 av_strlcatf(buf, sizeof(buf), "/%s", place);
272 if (*language && strcmp(language, "und")) {
274 snprintf(key2, sizeof(key2), "%s-%s", key, language);
275 av_dict_set(&c->fc->metadata, key2, buf, 0);
277 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
278 return av_dict_set(&c->fc->metadata, key, buf, 0);
281 static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
287 if (c->ignore_chapters)
290 n_hmmt = avio_rb32(pb);
291 for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
292 int moment_time = avio_rb32(pb);
293 avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
298 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
301 char key2[32], language[4] = {0};
303 const char *key = NULL;
304 uint16_t langcode = 0;
305 uint32_t data_type = 0, str_size, str_size_alloc;
306 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
311 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
312 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
313 case MKTAG( 'X','M','P','_'):
314 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
315 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
316 case MKTAG( 'a','k','I','D'): key = "account_type";
317 parse = mov_metadata_int8_no_padding; break;
318 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
319 case MKTAG( 'c','a','t','g'): key = "category"; break;
320 case MKTAG( 'c','p','i','l'): key = "compilation";
321 parse = mov_metadata_int8_no_padding; break;
322 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
323 case MKTAG( 'd','e','s','c'): key = "description"; break;
324 case MKTAG( 'd','i','s','k'): key = "disc";
325 parse = mov_metadata_track_or_disc_number; break;
326 case MKTAG( 'e','g','i','d'): key = "episode_uid";
327 parse = mov_metadata_int8_no_padding; break;
328 case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
329 case MKTAG( 'g','n','r','e'): key = "genre";
330 parse = mov_metadata_gnre; break;
331 case MKTAG( 'h','d','v','d'): key = "hd_video";
332 parse = mov_metadata_int8_no_padding; break;
333 case MKTAG( 'H','M','M','T'):
334 return mov_metadata_hmmt(c, pb, atom.size);
335 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
336 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
337 case MKTAG( 'l','o','c','i'):
338 return mov_metadata_loci(c, pb, atom.size);
339 case MKTAG( 'm','a','n','u'): key = "make"; break;
340 case MKTAG( 'm','o','d','l'): key = "model"; break;
341 case MKTAG( 'p','c','s','t'): key = "podcast";
342 parse = mov_metadata_int8_no_padding; break;
343 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
344 parse = mov_metadata_int8_no_padding; break;
345 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
346 case MKTAG( 'r','t','n','g'): key = "rating";
347 parse = mov_metadata_int8_no_padding; break;
348 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
349 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
350 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
351 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
352 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
353 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
354 case MKTAG( 's','t','i','k'): key = "media_type";
355 parse = mov_metadata_int8_no_padding; break;
356 case MKTAG( 't','r','k','n'): key = "track";
357 parse = mov_metadata_track_or_disc_number; break;
358 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
359 case MKTAG( 't','v','e','s'): key = "episode_sort";
360 parse = mov_metadata_int8_bypass_padding; break;
361 case MKTAG( 't','v','n','n'): key = "network"; break;
362 case MKTAG( 't','v','s','h'): key = "show"; break;
363 case MKTAG( 't','v','s','n'): key = "season_number";
364 parse = mov_metadata_int8_bypass_padding; break;
365 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
366 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
367 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
368 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
369 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
370 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
371 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
372 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
373 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
374 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
375 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
376 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
377 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
378 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
379 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
380 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
381 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
382 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
383 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
384 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
385 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
386 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
387 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
388 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
389 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
390 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
391 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
392 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
393 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
394 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
395 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
396 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
397 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
398 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
399 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
402 if (c->itunes_metadata && atom.size > 8) {
403 int data_size = avio_rb32(pb);
404 int tag = avio_rl32(pb);
405 if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
406 data_type = avio_rb32(pb); // type
407 avio_rb32(pb); // unknown
408 str_size = data_size - 16;
411 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
412 int ret = mov_read_covr(c, pb, data_type, str_size);
414 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
417 atom.size -= str_size;
421 } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
422 uint32_t index = AV_RB32(&atom.type);
423 if (index < c->meta_keys_count && index > 0) {
424 key = c->meta_keys[index];
426 av_log(c->fc, AV_LOG_WARNING,
427 "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n",
428 index, c->meta_keys_count);
432 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
433 str_size = avio_rb16(pb); // string length
434 if (str_size > atom.size) {
436 avio_seek(pb, -2, SEEK_CUR);
437 av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
440 langcode = avio_rb16(pb);
441 ff_mov_lang_to_iso639(langcode, language);
444 str_size = atom.size;
446 if (c->export_all && !key) {
447 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
453 if (atom.size < 0 || str_size >= INT_MAX/2)
454 return AVERROR_INVALIDDATA;
456 // Allocates enough space if data_type is a int32 or float32 number, otherwise
457 // worst-case requirement for output string in case of utf8 coded input
458 num = (data_type >= 21 && data_type <= 23);
459 str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
460 str = av_mallocz(str_size_alloc);
462 return AVERROR(ENOMEM);
465 parse(c, pb, str_size, key);
467 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
468 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
469 } else if (data_type == 21) { // BE signed integer, variable size
472 val = (int8_t)avio_r8(pb);
473 else if (str_size == 2)
474 val = (int16_t)avio_rb16(pb);
475 else if (str_size == 3)
476 val = ((int32_t)(avio_rb24(pb)<<8))>>8;
477 else if (str_size == 4)
478 val = (int32_t)avio_rb32(pb);
479 if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
480 av_log(c->fc, AV_LOG_ERROR,
481 "Failed to store the number (%d) in string.\n", val);
483 return AVERROR_INVALIDDATA;
485 } else if (data_type == 22) { // BE unsigned integer, variable size
486 unsigned int val = 0;
489 else if (str_size == 2)
491 else if (str_size == 3)
493 else if (str_size == 4)
495 if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
496 av_log(c->fc, AV_LOG_ERROR,
497 "Failed to store the number (%u) in string.\n", val);
499 return AVERROR_INVALIDDATA;
501 } else if (data_type == 23 && str_size >= 4) { // BE float32
502 float val = av_int2float(avio_rb32(pb));
503 if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
504 av_log(c->fc, AV_LOG_ERROR,
505 "Failed to store the float32 number (%f) in string.\n", val);
507 return AVERROR_INVALIDDATA;
510 int ret = ffio_read_size(pb, str, str_size);
517 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
518 av_dict_set(&c->fc->metadata, key, str, 0);
519 if (*language && strcmp(language, "und")) {
520 snprintf(key2, sizeof(key2), "%s-%s", key, language);
521 av_dict_set(&c->fc->metadata, key2, str, 0);
523 if (!strcmp(key, "encoder")) {
524 int major, minor, micro;
525 if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, µ) == 3) {
526 c->handbrake_version = 1000000*major + 1000*minor + micro;
535 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
538 int i, nb_chapters, str_len, version;
542 if (c->ignore_chapters)
545 if ((atom.size -= 5) < 0)
548 version = avio_r8(pb);
551 avio_rb32(pb); // ???
552 nb_chapters = avio_r8(pb);
554 for (i = 0; i < nb_chapters; i++) {
558 start = avio_rb64(pb);
559 str_len = avio_r8(pb);
561 if ((atom.size -= 9+str_len) < 0)
564 ret = ffio_read_size(pb, str, str_len);
568 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
573 #define MIN_DATA_ENTRY_BOX_SIZE 12
574 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
577 MOVStreamContext *sc;
580 if (c->fc->nb_streams < 1)
582 st = c->fc->streams[c->fc->nb_streams-1];
585 avio_rb32(pb); // version + flags
586 entries = avio_rb32(pb);
588 entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
589 entries >= UINT_MAX / sizeof(*sc->drefs))
590 return AVERROR_INVALIDDATA;
594 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
596 return AVERROR(ENOMEM);
597 sc->drefs_count = entries;
599 for (i = 0; i < entries; i++) {
600 MOVDref *dref = &sc->drefs[i];
601 uint32_t size = avio_rb32(pb);
602 int64_t next = avio_tell(pb) + size - 4;
605 return AVERROR_INVALIDDATA;
607 dref->type = avio_rl32(pb);
608 avio_rb32(pb); // version + flags
610 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
611 /* macintosh alias record */
612 uint16_t volume_len, len;
618 volume_len = avio_r8(pb);
619 volume_len = FFMIN(volume_len, 27);
620 ret = ffio_read_size(pb, dref->volume, 27);
623 dref->volume[volume_len] = 0;
624 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
629 len = FFMIN(len, 63);
630 ret = ffio_read_size(pb, dref->filename, 63);
633 dref->filename[len] = 0;
634 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
638 /* read next level up_from_alias/down_to_target */
639 dref->nlvl_from = avio_rb16(pb);
640 dref->nlvl_to = avio_rb16(pb);
641 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
642 dref->nlvl_from, dref->nlvl_to);
646 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
649 type = avio_rb16(pb);
651 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
654 if (type == 2) { // absolute path
656 dref->path = av_mallocz(len+1);
658 return AVERROR(ENOMEM);
660 ret = ffio_read_size(pb, dref->path, len);
662 av_freep(&dref->path);
665 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
667 memmove(dref->path, dref->path+volume_len, len);
670 // trim string of any ending zeros
671 for (j = len - 1; j >= 0; j--) {
672 if (dref->path[j] == 0)
677 for (j = 0; j < len; j++)
678 if (dref->path[j] == ':' || dref->path[j] == 0)
680 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
681 } else if (type == 0) { // directory name
683 dref->dir = av_malloc(len+1);
685 return AVERROR(ENOMEM);
687 ret = ffio_read_size(pb, dref->dir, len);
689 av_freep(&dref->dir);
693 for (j = 0; j < len; j++)
694 if (dref->dir[j] == ':')
696 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
701 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n",
706 avio_seek(pb, next, SEEK_SET);
711 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
720 avio_r8(pb); /* version */
721 avio_rb24(pb); /* flags */
724 ctype = avio_rl32(pb);
725 type = avio_rl32(pb); /* component subtype */
727 av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype));
728 av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type));
730 if (c->trak_index < 0) { // meta not inside a trak
731 if (type == MKTAG('m','d','t','a')) {
732 c->found_hdlr_mdta = 1;
737 st = c->fc->streams[c->fc->nb_streams-1];
739 if (type == MKTAG('v','i','d','e'))
740 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
741 else if (type == MKTAG('s','o','u','n'))
742 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
743 else if (type == MKTAG('m','1','a',' '))
744 st->codecpar->codec_id = AV_CODEC_ID_MP2;
745 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
746 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
748 avio_rb32(pb); /* component manufacture */
749 avio_rb32(pb); /* component flags */
750 avio_rb32(pb); /* component flags mask */
752 title_size = atom.size - 24;
753 if (title_size > 0) {
754 if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
755 return AVERROR_INVALIDDATA;
756 title_str = av_malloc(title_size + 1); /* Add null terminator */
758 return AVERROR(ENOMEM);
760 ret = ffio_read_size(pb, title_str, title_size);
762 av_freep(&title_str);
765 title_str[title_size] = 0;
767 int off = (!c->isom && title_str[0] == title_size - 1);
768 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
770 av_freep(&title_str);
776 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
778 return ff_mov_read_esds(c->fc, pb);
781 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
784 enum AVAudioServiceType *ast;
785 int ac3info, acmod, lfeon, bsmod;
787 if (c->fc->nb_streams < 1)
789 st = c->fc->streams[c->fc->nb_streams-1];
791 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
794 return AVERROR(ENOMEM);
796 ac3info = avio_rb24(pb);
797 bsmod = (ac3info >> 14) & 0x7;
798 acmod = (ac3info >> 11) & 0x7;
799 lfeon = (ac3info >> 10) & 0x1;
800 st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
801 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
803 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
805 if (st->codecpar->channels > 1 && bsmod == 0x7)
806 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
808 #if FF_API_LAVF_AVCTX
809 FF_DISABLE_DEPRECATION_WARNINGS
810 st->codec->audio_service_type = *ast;
811 FF_ENABLE_DEPRECATION_WARNINGS
817 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
820 enum AVAudioServiceType *ast;
821 int eac3info, acmod, lfeon, bsmod;
823 if (c->fc->nb_streams < 1)
825 st = c->fc->streams[c->fc->nb_streams-1];
827 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
830 return AVERROR(ENOMEM);
832 /* No need to parse fields for additional independent substreams and its
833 * associated dependent substreams since libavcodec's E-AC-3 decoder
834 * does not support them yet. */
835 avio_rb16(pb); /* data_rate and num_ind_sub */
836 eac3info = avio_rb24(pb);
837 bsmod = (eac3info >> 12) & 0x1f;
838 acmod = (eac3info >> 9) & 0x7;
839 lfeon = (eac3info >> 8) & 0x1;
840 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
842 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
843 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
845 if (st->codecpar->channels > 1 && bsmod == 0x7)
846 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
848 #if FF_API_LAVF_AVCTX
849 FF_DISABLE_DEPRECATION_WARNINGS
850 st->codec->audio_service_type = *ast;
851 FF_ENABLE_DEPRECATION_WARNINGS
857 static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
859 const uint32_t ddts_size = 20;
862 uint32_t frame_duration_code = 0;
863 uint32_t channel_layout_code = 0;
866 buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE);
868 return AVERROR(ENOMEM);
870 if (avio_read(pb, buf, ddts_size) < ddts_size) {
872 return AVERROR_INVALIDDATA;
875 init_get_bits(&gb, buf, 8*ddts_size);
877 if (c->fc->nb_streams < 1) {
881 st = c->fc->streams[c->fc->nb_streams-1];
883 st->codecpar->sample_rate = get_bits_long(&gb, 32);
884 if (st->codecpar->sample_rate <= 0) {
885 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
887 return AVERROR_INVALIDDATA;
889 skip_bits_long(&gb, 32); /* max bitrate */
890 st->codecpar->bit_rate = get_bits_long(&gb, 32);
891 st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
892 frame_duration_code = get_bits(&gb, 2);
893 skip_bits(&gb, 30); /* various fields */
894 channel_layout_code = get_bits(&gb, 16);
896 st->codecpar->frame_size =
897 (frame_duration_code == 0) ? 512 :
898 (frame_duration_code == 1) ? 1024 :
899 (frame_duration_code == 2) ? 2048 :
900 (frame_duration_code == 3) ? 4096 : 0;
902 if (channel_layout_code > 0xff) {
903 av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
905 st->codecpar->channel_layout =
906 ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
907 ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
908 ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
909 ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
910 ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
911 ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
913 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
919 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
923 if (c->fc->nb_streams < 1)
925 st = c->fc->streams[c->fc->nb_streams-1];
930 /* skip version and flags */
933 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
938 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
943 if (c->fc->nb_streams < 1)
945 st = c->fc->streams[c->fc->nb_streams-1];
947 if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
948 av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
953 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
955 const int num = avio_rb32(pb);
956 const int den = avio_rb32(pb);
959 if (c->fc->nb_streams < 1)
961 st = c->fc->streams[c->fc->nb_streams-1];
963 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
964 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
965 av_log(c->fc, AV_LOG_WARNING,
966 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
967 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
969 } else if (den != 0) {
970 av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
976 /* this atom contains actual media data */
977 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
979 if (atom.size == 0) /* wrong one (MP4) */
982 return 0; /* now go for moov */
985 #define DRM_BLOB_SIZE 56
987 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
989 uint8_t intermediate_key[20];
990 uint8_t intermediate_iv[20];
993 uint8_t file_checksum[20];
994 uint8_t calculated_checksum[20];
998 uint8_t *activation_bytes = c->activation_bytes;
999 uint8_t *fixed_key = c->audible_fixed_key;
1003 sha = av_sha_alloc();
1005 return AVERROR(ENOMEM);
1006 c->aes_decrypt = av_aes_alloc();
1007 if (!c->aes_decrypt) {
1008 ret = AVERROR(ENOMEM);
1012 /* drm blob processing */
1013 avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
1014 avio_read(pb, input, DRM_BLOB_SIZE);
1015 avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
1016 avio_read(pb, file_checksum, 20);
1018 av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
1019 for (i = 0; i < 20; i++)
1020 av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
1021 av_log(c->fc, AV_LOG_INFO, "\n");
1023 /* verify activation data */
1024 if (!activation_bytes) {
1025 av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
1026 ret = 0; /* allow ffprobe to continue working on .aax files */
1029 if (c->activation_bytes_size != 4) {
1030 av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
1031 ret = AVERROR(EINVAL);
1035 /* verify fixed key */
1036 if (c->audible_fixed_key_size != 16) {
1037 av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
1038 ret = AVERROR(EINVAL);
1042 /* AAX (and AAX+) key derivation */
1043 av_sha_init(sha, 160);
1044 av_sha_update(sha, fixed_key, 16);
1045 av_sha_update(sha, activation_bytes, 4);
1046 av_sha_final(sha, intermediate_key);
1047 av_sha_init(sha, 160);
1048 av_sha_update(sha, fixed_key, 16);
1049 av_sha_update(sha, intermediate_key, 20);
1050 av_sha_update(sha, activation_bytes, 4);
1051 av_sha_final(sha, intermediate_iv);
1052 av_sha_init(sha, 160);
1053 av_sha_update(sha, intermediate_key, 16);
1054 av_sha_update(sha, intermediate_iv, 16);
1055 av_sha_final(sha, calculated_checksum);
1056 if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
1057 av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
1058 ret = AVERROR_INVALIDDATA;
1061 av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
1062 av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
1063 for (i = 0; i < 4; i++) {
1064 // file data (in output) is stored in big-endian mode
1065 if (activation_bytes[i] != output[3 - i]) { // critical error
1066 av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
1067 ret = AVERROR_INVALIDDATA;
1071 memcpy(c->file_key, output + 8, 16);
1072 memcpy(input, output + 26, 16);
1073 av_sha_init(sha, 160);
1074 av_sha_update(sha, input, 16);
1075 av_sha_update(sha, c->file_key, 16);
1076 av_sha_update(sha, fixed_key, 16);
1077 av_sha_final(sha, c->file_iv);
1085 // Audible AAX (and AAX+) bytestream decryption
1086 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1089 unsigned char iv[16];
1091 memcpy(iv, c->file_iv, 16); // iv is overwritten
1092 blocks = size >> 4; // trailing bytes are not encrypted!
1093 av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1094 av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1099 /* read major brand, minor version and compatible brands and store them as metadata */
1100 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1103 int comp_brand_size;
1104 char* comp_brands_str;
1105 uint8_t type[5] = {0};
1106 int ret = ffio_read_size(pb, type, 4);
1110 if (strcmp(type, "qt "))
1112 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1113 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1114 minor_ver = avio_rb32(pb); /* minor version */
1115 av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1117 comp_brand_size = atom.size - 8;
1118 if (comp_brand_size < 0)
1119 return AVERROR_INVALIDDATA;
1120 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1121 if (!comp_brands_str)
1122 return AVERROR(ENOMEM);
1124 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1126 av_freep(&comp_brands_str);
1129 comp_brands_str[comp_brand_size] = 0;
1130 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1131 av_freep(&comp_brands_str);
1136 /* this atom should contain all header atoms */
1137 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1141 if (c->found_moov) {
1142 av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1143 avio_skip(pb, atom.size);
1147 if ((ret = mov_read_default(c, pb, atom)) < 0)
1149 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1150 /* so we don't parse the whole file if over a network */
1152 return 0; /* now go for mdat */
1155 static MOVFragmentStreamInfo * get_frag_stream_info(
1156 MOVFragmentIndex *frag_index,
1161 MOVFragmentIndexItem * item;
1163 if (index < 0 || index >= frag_index->nb_items)
1165 item = &frag_index->item[index];
1166 for (i = 0; i < item->nb_stream_info; i++)
1167 if (item->stream_info[i].id == id)
1168 return &item->stream_info[i];
1170 // This shouldn't happen
1174 static void set_frag_stream(MOVFragmentIndex *frag_index, int id)
1177 MOVFragmentIndexItem * item;
1179 if (frag_index->current < 0 ||
1180 frag_index->current >= frag_index->nb_items)
1183 item = &frag_index->item[frag_index->current];
1184 for (i = 0; i < item->nb_stream_info; i++)
1185 if (item->stream_info[i].id == id) {
1190 // id not found. This shouldn't happen.
1194 static MOVFragmentStreamInfo * get_current_frag_stream_info(
1195 MOVFragmentIndex *frag_index)
1197 MOVFragmentIndexItem *item;
1198 if (frag_index->current < 0 ||
1199 frag_index->current >= frag_index->nb_items)
1202 item = &frag_index->item[frag_index->current];
1203 if (item->current >= 0 && item->current < item->nb_stream_info)
1204 return &item->stream_info[item->current];
1206 // This shouldn't happen
1210 static int search_frag_moof_offset(MOVFragmentIndex *frag_index, int64_t offset)
1213 int64_t moof_offset;
1215 // Optimize for appending new entries
1216 if (!frag_index->nb_items ||
1217 frag_index->item[frag_index->nb_items - 1].moof_offset < offset)
1218 return frag_index->nb_items;
1221 b = frag_index->nb_items;
1225 moof_offset = frag_index->item[m].moof_offset;
1226 if (moof_offset >= offset)
1228 if (moof_offset <= offset)
1234 static int64_t get_stream_info_time(MOVFragmentStreamInfo * frag_stream_info)
1237 if (frag_stream_info) {
1238 if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE)
1239 return frag_stream_info->sidx_pts;
1240 if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE)
1241 return frag_stream_info->first_tfra_pts;
1242 if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE)
1243 return frag_stream_info->tfdt_dts;
1245 return AV_NOPTS_VALUE;
1248 static int64_t get_frag_time(MOVFragmentIndex *frag_index,
1249 int index, int track_id)
1251 MOVFragmentStreamInfo * frag_stream_info;
1255 if (track_id >= 0) {
1256 frag_stream_info = get_frag_stream_info(frag_index, index, track_id);
1257 return frag_stream_info->sidx_pts;
1260 for (i = 0; i < frag_index->item[index].nb_stream_info; i++) {
1261 frag_stream_info = &frag_index->item[index].stream_info[i];
1262 timestamp = get_stream_info_time(frag_stream_info);
1263 if (timestamp != AV_NOPTS_VALUE)
1266 return AV_NOPTS_VALUE;
1269 static int search_frag_timestamp(MOVFragmentIndex *frag_index,
1270 AVStream *st, int64_t timestamp)
1277 // If the stream is referenced by any sidx, limit the search
1278 // to fragments that referenced this stream in the sidx
1279 MOVStreamContext *sc = st->priv_data;
1285 b = frag_index->nb_items;
1289 frag_time = get_frag_time(frag_index, m, id);
1290 if (frag_time != AV_NOPTS_VALUE) {
1291 if (frag_time >= timestamp)
1293 if (frag_time <= timestamp)
1300 static int update_frag_index(MOVContext *c, int64_t offset)
1303 MOVFragmentIndexItem * item;
1304 MOVFragmentStreamInfo * frag_stream_info;
1306 // If moof_offset already exists in frag_index, return index to it
1307 index = search_frag_moof_offset(&c->frag_index, offset);
1308 if (index < c->frag_index.nb_items &&
1309 c->frag_index.item[index].moof_offset == offset)
1312 // offset is not yet in frag index.
1313 // Insert new item at index (sorted by moof offset)
1314 item = av_fast_realloc(c->frag_index.item,
1315 &c->frag_index.allocated_size,
1316 (c->frag_index.nb_items + 1) *
1317 sizeof(*c->frag_index.item));
1320 c->frag_index.item = item;
1322 frag_stream_info = av_realloc_array(NULL, c->fc->nb_streams,
1323 sizeof(*item->stream_info));
1324 if (!frag_stream_info)
1327 for (i = 0; i < c->fc->nb_streams; i++) {
1328 frag_stream_info[i].id = c->fc->streams[i]->id;
1329 frag_stream_info[i].sidx_pts = AV_NOPTS_VALUE;
1330 frag_stream_info[i].tfdt_dts = AV_NOPTS_VALUE;
1331 frag_stream_info[i].first_tfra_pts = AV_NOPTS_VALUE;
1332 frag_stream_info[i].index_entry = -1;
1333 frag_stream_info[i].encryption_index = NULL;
1336 if (index < c->frag_index.nb_items)
1337 memmove(c->frag_index.item + index + 1, c->frag_index.item + index,
1338 (c->frag_index.nb_items - index) * sizeof(*c->frag_index.item));
1340 item = &c->frag_index.item[index];
1341 item->headers_read = 0;
1343 item->nb_stream_info = c->fc->nb_streams;
1344 item->moof_offset = offset;
1345 item->stream_info = frag_stream_info;
1346 c->frag_index.nb_items++;
1351 static void fix_frag_index_entries(MOVFragmentIndex *frag_index, int index,
1352 int id, int entries)
1355 MOVFragmentStreamInfo * frag_stream_info;
1359 for (i = index; i < frag_index->nb_items; i++) {
1360 frag_stream_info = get_frag_stream_info(frag_index, i, id);
1361 if (frag_stream_info && frag_stream_info->index_entry >= 0)
1362 frag_stream_info->index_entry += entries;
1366 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1368 if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1369 c->has_looked_for_mfra = 1;
1370 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
1372 av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1374 if ((ret = mov_read_mfra(c, pb)) < 0) {
1375 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1376 "read the mfra (may be a live ismv)\n");
1379 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1380 "seekable, can not look for mfra\n");
1383 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
1384 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1385 c->frag_index.current = update_frag_index(c, c->fragment.moof_offset);
1386 return mov_read_default(c, pb, atom);
1389 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1392 if(time >= 2082844800)
1393 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1395 if ((int64_t)(time * 1000000ULL) / 1000000 != time) {
1396 av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n");
1400 avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
1404 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1407 MOVStreamContext *sc;
1409 char language[4] = {0};
1411 int64_t creation_time;
1413 if (c->fc->nb_streams < 1)
1415 st = c->fc->streams[c->fc->nb_streams-1];
1418 if (sc->time_scale) {
1419 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1420 return AVERROR_INVALIDDATA;
1423 version = avio_r8(pb);
1425 avpriv_request_sample(c->fc, "Version %d", version);
1426 return AVERROR_PATCHWELCOME;
1428 avio_rb24(pb); /* flags */
1430 creation_time = avio_rb64(pb);
1433 creation_time = avio_rb32(pb);
1434 avio_rb32(pb); /* modification time */
1436 mov_metadata_creation_time(&st->metadata, creation_time);
1438 sc->time_scale = avio_rb32(pb);
1439 if (sc->time_scale <= 0) {
1440 av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale);
1443 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1445 lang = avio_rb16(pb); /* language */
1446 if (ff_mov_lang_to_iso639(lang, language))
1447 av_dict_set(&st->metadata, "language", language, 0);
1448 avio_rb16(pb); /* quality */
1453 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1456 int64_t creation_time;
1457 int version = avio_r8(pb); /* version */
1458 avio_rb24(pb); /* flags */
1461 creation_time = avio_rb64(pb);
1464 creation_time = avio_rb32(pb);
1465 avio_rb32(pb); /* modification time */
1467 mov_metadata_creation_time(&c->fc->metadata, creation_time);
1468 c->time_scale = avio_rb32(pb); /* time scale */
1469 if (c->time_scale <= 0) {
1470 av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale);
1473 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1475 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1476 // set the AVCodecContext duration because the duration of individual tracks
1477 // may be inaccurate
1478 if (c->time_scale > 0 && !c->trex_data)
1479 c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1480 avio_rb32(pb); /* preferred scale */
1482 avio_rb16(pb); /* preferred volume */
1484 avio_skip(pb, 10); /* reserved */
1486 /* movie display matrix, store it in main context and use it later on */
1487 for (i = 0; i < 3; i++) {
1488 c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
1489 c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
1490 c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
1493 avio_rb32(pb); /* preview time */
1494 avio_rb32(pb); /* preview duration */
1495 avio_rb32(pb); /* poster time */
1496 avio_rb32(pb); /* selection time */
1497 avio_rb32(pb); /* selection duration */
1498 avio_rb32(pb); /* current time */
1499 avio_rb32(pb); /* next track ID */
1504 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1509 if (c->fc->nb_streams < 1)
1511 st = c->fc->streams[c->fc->nb_streams-1];
1513 little_endian = avio_rb16(pb) & 0xFF;
1514 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1515 if (little_endian == 1) {
1516 switch (st->codecpar->codec_id) {
1517 case AV_CODEC_ID_PCM_S24BE:
1518 st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
1520 case AV_CODEC_ID_PCM_S32BE:
1521 st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
1523 case AV_CODEC_ID_PCM_F32BE:
1524 st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
1526 case AV_CODEC_ID_PCM_F64BE:
1527 st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
1536 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1539 char color_parameter_type[5] = { 0 };
1540 uint16_t color_primaries, color_trc, color_matrix;
1543 if (c->fc->nb_streams < 1)
1545 st = c->fc->streams[c->fc->nb_streams - 1];
1547 ret = ffio_read_size(pb, color_parameter_type, 4);
1550 if (strncmp(color_parameter_type, "nclx", 4) &&
1551 strncmp(color_parameter_type, "nclc", 4)) {
1552 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1553 color_parameter_type);
1557 color_primaries = avio_rb16(pb);
1558 color_trc = avio_rb16(pb);
1559 color_matrix = avio_rb16(pb);
1561 av_log(c->fc, AV_LOG_TRACE,
1562 "%s: pri %d trc %d matrix %d",
1563 color_parameter_type, color_primaries, color_trc, color_matrix);
1565 if (!strncmp(color_parameter_type, "nclx", 4)) {
1566 uint8_t color_range = avio_r8(pb) >> 7;
1567 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1569 st->codecpar->color_range = AVCOL_RANGE_JPEG;
1571 st->codecpar->color_range = AVCOL_RANGE_MPEG;
1574 if (!av_color_primaries_name(color_primaries))
1575 color_primaries = AVCOL_PRI_UNSPECIFIED;
1576 if (!av_color_transfer_name(color_trc))
1577 color_trc = AVCOL_TRC_UNSPECIFIED;
1578 if (!av_color_space_name(color_matrix))
1579 color_matrix = AVCOL_SPC_UNSPECIFIED;
1581 st->codecpar->color_primaries = color_primaries;
1582 st->codecpar->color_trc = color_trc;
1583 st->codecpar->color_space = color_matrix;
1584 av_log(c->fc, AV_LOG_TRACE, "\n");
1589 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1592 unsigned mov_field_order;
1593 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1595 if (c->fc->nb_streams < 1) // will happen with jp2 files
1597 st = c->fc->streams[c->fc->nb_streams-1];
1599 return AVERROR_INVALIDDATA;
1600 mov_field_order = avio_rb16(pb);
1601 if ((mov_field_order & 0xFF00) == 0x0100)
1602 decoded_field_order = AV_FIELD_PROGRESSIVE;
1603 else if ((mov_field_order & 0xFF00) == 0x0200) {
1604 switch (mov_field_order & 0xFF) {
1605 case 0x01: decoded_field_order = AV_FIELD_TT;
1607 case 0x06: decoded_field_order = AV_FIELD_BB;
1609 case 0x09: decoded_field_order = AV_FIELD_TB;
1611 case 0x0E: decoded_field_order = AV_FIELD_BT;
1615 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1616 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1618 st->codecpar->field_order = decoded_field_order;
1623 static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
1626 uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1627 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1628 return AVERROR_INVALIDDATA;
1629 if ((err = av_reallocp(&par->extradata, size)) < 0) {
1630 par->extradata_size = 0;
1633 par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1637 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1638 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1639 AVCodecParameters *par, uint8_t *buf)
1641 int64_t result = atom.size;
1644 AV_WB32(buf , atom.size + 8);
1645 AV_WL32(buf + 4, atom.type);
1646 err = ffio_read_size(pb, buf + 8, atom.size);
1648 par->extradata_size -= atom.size;
1650 } else if (err < atom.size) {
1651 av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1652 par->extradata_size -= atom.size - err;
1655 memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1659 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1660 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1661 enum AVCodecID codec_id)
1664 uint64_t original_size;
1667 if (c->fc->nb_streams < 1) // will happen with jp2 files
1669 st = c->fc->streams[c->fc->nb_streams-1];
1671 if (st->codecpar->codec_id != codec_id)
1672 return 0; /* unexpected codec_id - don't mess with extradata */
1674 original_size = st->codecpar->extradata_size;
1675 err = mov_realloc_extradata(st->codecpar, atom);
1679 err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
1682 return 0; // Note: this is the original behavior to ignore truncation.
1685 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1686 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1688 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1691 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1693 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1696 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1698 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1701 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1703 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1706 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1708 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1710 ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1714 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1716 int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1718 if (!ret && c->fc->nb_streams >= 1) {
1719 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1720 if (par->extradata_size >= 40) {
1721 par->height = AV_RB16(&par->extradata[36]);
1722 par->width = AV_RB16(&par->extradata[38]);
1728 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1730 if (c->fc->nb_streams >= 1) {
1731 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1732 if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1733 par->codec_id == AV_CODEC_ID_H264 &&
1737 cid = avio_rb16(pb);
1738 /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1739 if (cid == 0xd4d || cid == 0xd4e)
1742 } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
1743 par->codec_tag == MKTAG('A', 'V', 'j', '2') ||
1744 par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
1748 num = avio_rb32(pb);
1749 den = avio_rb32(pb);
1750 if (num <= 0 || den <= 0)
1752 switch (avio_rb32(pb)) {
1754 if (den >= INT_MAX / 2)
1758 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1759 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1766 return mov_read_avid(c, pb, atom);
1769 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1773 uint64_t original_size;
1774 if (c->fc->nb_streams >= 1) {
1775 AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1776 if (par->codec_id == AV_CODEC_ID_H264)
1778 if (atom.size == 16) {
1779 original_size = par->extradata_size;
1780 ret = mov_realloc_extradata(par, atom);
1782 length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
1783 if (length == atom.size) {
1784 const uint8_t range_value = par->extradata[original_size + 19];
1785 switch (range_value) {
1787 par->color_range = AVCOL_RANGE_MPEG;
1790 par->color_range = AVCOL_RANGE_JPEG;
1793 av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1796 ff_dlog(c, "color_range: %d\n", par->color_range);
1798 /* For some reason the whole atom was not added to the extradata */
1799 av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1802 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1805 av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1812 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1814 return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1817 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1822 if (c->fc->nb_streams < 1)
1824 st = c->fc->streams[c->fc->nb_streams-1];
1826 if ((uint64_t)atom.size > (1<<30))
1827 return AVERROR_INVALIDDATA;
1829 if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
1830 st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
1831 st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
1832 // pass all frma atom to codec, needed at least for QDMC and QDM2
1833 av_freep(&st->codecpar->extradata);
1834 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1837 } else if (atom.size > 8) { /* to read frma, esds atoms */
1838 if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1840 ret = ffio_ensure_seekback(pb, 8);
1843 buffer = avio_rb64(pb);
1845 if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1846 && buffer >> 32 <= atom.size
1847 && buffer >> 32 >= 8) {
1850 } else if (!st->codecpar->extradata_size) {
1851 #define ALAC_EXTRADATA_SIZE 36
1852 st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1853 if (!st->codecpar->extradata)
1854 return AVERROR(ENOMEM);
1855 st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
1856 AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE);
1857 AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
1858 AV_WB64(st->codecpar->extradata + 12, buffer);
1859 avio_read(pb, st->codecpar->extradata + 20, 16);
1860 avio_skip(pb, atom.size - 24);
1864 if ((ret = mov_read_default(c, pb, atom)) < 0)
1867 avio_skip(pb, atom.size);
1872 * This function reads atom content and puts data in extradata without tag
1873 * nor size unlike mov_read_extradata.
1875 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1880 if (c->fc->nb_streams < 1)
1882 st = c->fc->streams[c->fc->nb_streams-1];
1884 if ((uint64_t)atom.size > (1<<30))
1885 return AVERROR_INVALIDDATA;
1887 if (atom.size >= 10) {
1888 // Broken files created by legacy versions of libavformat will
1889 // wrap a whole fiel atom inside of a glbl atom.
1890 unsigned size = avio_rb32(pb);
1891 unsigned type = avio_rl32(pb);
1892 avio_seek(pb, -8, SEEK_CUR);
1893 if (type == MKTAG('f','i','e','l') && size == atom.size)
1894 return mov_read_default(c, pb, atom);
1896 if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
1897 av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1900 av_freep(&st->codecpar->extradata);
1901 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1908 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1911 uint8_t profile_level;
1914 if (c->fc->nb_streams < 1)
1916 st = c->fc->streams[c->fc->nb_streams-1];
1918 if (atom.size >= (1<<28) || atom.size < 7)
1919 return AVERROR_INVALIDDATA;
1921 profile_level = avio_r8(pb);
1922 if ((profile_level & 0xf0) != 0xc0)
1925 avio_seek(pb, 6, SEEK_CUR);
1926 av_freep(&st->codecpar->extradata);
1927 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
1935 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1936 * but can have extradata appended at the end after the 40 bytes belonging
1939 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1944 if (c->fc->nb_streams < 1)
1946 if (atom.size <= 40)
1948 st = c->fc->streams[c->fc->nb_streams-1];
1950 if ((uint64_t)atom.size > (1<<30))
1951 return AVERROR_INVALIDDATA;
1954 av_freep(&st->codecpar->extradata);
1955 ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
1962 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1965 MOVStreamContext *sc;
1966 unsigned int i, entries;
1968 if (c->fc->nb_streams < 1)
1970 st = c->fc->streams[c->fc->nb_streams-1];
1973 avio_r8(pb); /* version */
1974 avio_rb24(pb); /* flags */
1976 entries = avio_rb32(pb);
1981 if (sc->chunk_offsets)
1982 av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1983 av_free(sc->chunk_offsets);
1984 sc->chunk_count = 0;
1985 sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1986 if (!sc->chunk_offsets)
1987 return AVERROR(ENOMEM);
1988 sc->chunk_count = entries;
1990 if (atom.type == MKTAG('s','t','c','o'))
1991 for (i = 0; i < entries && !pb->eof_reached; i++)
1992 sc->chunk_offsets[i] = avio_rb32(pb);
1993 else if (atom.type == MKTAG('c','o','6','4'))
1994 for (i = 0; i < entries && !pb->eof_reached; i++)
1995 sc->chunk_offsets[i] = avio_rb64(pb);
1997 return AVERROR_INVALIDDATA;
1999 sc->chunk_count = i;
2001 if (pb->eof_reached) {
2002 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STCO atom\n");
2009 static int mov_codec_id(AVStream *st, uint32_t format)
2011 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
2014 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
2015 (format & 0xFFFF) == 'T' + ('S' << 8)))
2016 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
2018 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
2019 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2020 } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
2021 /* skip old ASF MPEG-4 tag */
2022 format && format != MKTAG('m','p','4','s')) {
2023 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2025 id = ff_codec_get_id(ff_codec_bmp_tags, format);
2027 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2028 else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
2029 (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
2030 st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
2031 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
2033 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2037 st->codecpar->codec_tag = format;
2042 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
2043 AVStream *st, MOVStreamContext *sc)
2045 uint8_t codec_name[32] = { 0 };
2049 /* The first 16 bytes of the video sample description are already
2050 * read in ff_mov_read_stsd_entries() */
2051 stsd_start = avio_tell(pb) - 16;
2053 avio_rb16(pb); /* version */
2054 avio_rb16(pb); /* revision level */
2055 avio_rb32(pb); /* vendor */
2056 avio_rb32(pb); /* temporal quality */
2057 avio_rb32(pb); /* spatial quality */
2059 st->codecpar->width = avio_rb16(pb); /* width */
2060 st->codecpar->height = avio_rb16(pb); /* height */
2062 avio_rb32(pb); /* horiz resolution */
2063 avio_rb32(pb); /* vert resolution */
2064 avio_rb32(pb); /* data size, always 0 */
2065 avio_rb16(pb); /* frames per samples */
2067 len = avio_r8(pb); /* codec name, pascal string */
2070 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
2072 avio_skip(pb, 31 - len);
2075 av_dict_set(&st->metadata, "encoder", codec_name, 0);
2077 /* codec_tag YV12 triggers an UV swap in rawdec.c */
2078 if (!strncmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
2079 st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
2080 st->codecpar->width &= ~1;
2081 st->codecpar->height &= ~1;
2083 /* Flash Media Server uses tag H.263 with Sorenson Spark */
2084 if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
2085 !strncmp(codec_name, "Sorenson H263", 13))
2086 st->codecpar->codec_id = AV_CODEC_ID_FLV1;
2088 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
2090 avio_seek(pb, stsd_start, SEEK_SET);
2092 if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
2093 st->codecpar->bits_per_coded_sample &= 0x1F;
2094 sc->has_palette = 1;
2098 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
2099 AVStream *st, MOVStreamContext *sc)
2101 int bits_per_sample, flags;
2102 uint16_t version = avio_rb16(pb);
2103 AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
2105 avio_rb16(pb); /* revision level */
2106 avio_rb32(pb); /* vendor */
2108 st->codecpar->channels = avio_rb16(pb); /* channel count */
2109 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
2110 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
2112 sc->audio_cid = avio_rb16(pb);
2113 avio_rb16(pb); /* packet size = 0 */
2115 st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
2117 // Read QT version 1 fields. In version 0 these do not exist.
2118 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
2120 (compatible_brands && strstr(compatible_brands->value, "qt "))) {
2123 sc->samples_per_frame = avio_rb32(pb);
2124 avio_rb32(pb); /* bytes per packet */
2125 sc->bytes_per_frame = avio_rb32(pb);
2126 avio_rb32(pb); /* bytes per sample */
2127 } else if (version == 2) {
2128 avio_rb32(pb); /* sizeof struct only */
2129 st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
2130 st->codecpar->channels = avio_rb32(pb);
2131 avio_rb32(pb); /* always 0x7F000000 */
2132 st->codecpar->bits_per_coded_sample = avio_rb32(pb);
2134 flags = avio_rb32(pb); /* lpcm format specific flag */
2135 sc->bytes_per_frame = avio_rb32(pb);
2136 sc->samples_per_frame = avio_rb32(pb);
2137 if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
2138 st->codecpar->codec_id =
2139 ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
2142 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
2143 /* can't correctly handle variable sized packet as audio unit */
2144 switch (st->codecpar->codec_id) {
2145 case AV_CODEC_ID_MP2:
2146 case AV_CODEC_ID_MP3:
2147 st->need_parsing = AVSTREAM_PARSE_FULL;
2153 if (sc->format == 0) {
2154 if (st->codecpar->bits_per_coded_sample == 8)
2155 st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
2156 else if (st->codecpar->bits_per_coded_sample == 16)
2157 st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
2160 switch (st->codecpar->codec_id) {
2161 case AV_CODEC_ID_PCM_S8:
2162 case AV_CODEC_ID_PCM_U8:
2163 if (st->codecpar->bits_per_coded_sample == 16)
2164 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
2166 case AV_CODEC_ID_PCM_S16LE:
2167 case AV_CODEC_ID_PCM_S16BE:
2168 if (st->codecpar->bits_per_coded_sample == 8)
2169 st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
2170 else if (st->codecpar->bits_per_coded_sample == 24)
2171 st->codecpar->codec_id =
2172 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
2173 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2174 else if (st->codecpar->bits_per_coded_sample == 32)
2175 st->codecpar->codec_id =
2176 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
2177 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2179 /* set values for old format before stsd version 1 appeared */
2180 case AV_CODEC_ID_MACE3:
2181 sc->samples_per_frame = 6;
2182 sc->bytes_per_frame = 2 * st->codecpar->channels;
2184 case AV_CODEC_ID_MACE6:
2185 sc->samples_per_frame = 6;
2186 sc->bytes_per_frame = 1 * st->codecpar->channels;
2188 case AV_CODEC_ID_ADPCM_IMA_QT:
2189 sc->samples_per_frame = 64;
2190 sc->bytes_per_frame = 34 * st->codecpar->channels;
2192 case AV_CODEC_ID_GSM:
2193 sc->samples_per_frame = 160;
2194 sc->bytes_per_frame = 33;
2200 bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
2201 if (bits_per_sample) {
2202 st->codecpar->bits_per_coded_sample = bits_per_sample;
2203 sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
2207 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
2208 AVStream *st, MOVStreamContext *sc,
2211 // ttxt stsd contains display flags, justification, background
2212 // color, fonts, and default styles, so fake an atom to read it
2213 MOVAtom fake_atom = { .size = size };
2214 // mp4s contains a regular esds atom
2215 if (st->codecpar->codec_tag != AV_RL32("mp4s"))
2216 mov_read_glbl(c, pb, fake_atom);
2217 st->codecpar->width = sc->width;
2218 st->codecpar->height = sc->height;
2221 static uint32_t yuv_to_rgba(uint32_t ycbcr)
2226 y = (ycbcr >> 16) & 0xFF;
2227 cr = (ycbcr >> 8) & 0xFF;
2230 b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
2231 g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
2232 r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
2234 return (r << 16) | (g << 8) | b;
2237 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
2239 char buf[256] = {0};
2240 uint8_t *src = st->codecpar->extradata;
2243 if (st->codecpar->extradata_size != 64)
2246 if (st->codecpar->width > 0 && st->codecpar->height > 0)
2247 snprintf(buf, sizeof(buf), "size: %dx%d\n",
2248 st->codecpar->width, st->codecpar->height);
2249 av_strlcat(buf, "palette: ", sizeof(buf));
2251 for (i = 0; i < 16; i++) {
2252 uint32_t yuv = AV_RB32(src + i * 4);
2253 uint32_t rgba = yuv_to_rgba(yuv);
2255 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2258 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2261 av_freep(&st->codecpar->extradata);
2262 st->codecpar->extradata_size = 0;
2263 st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
2264 if (!st->codecpar->extradata)
2265 return AVERROR(ENOMEM);
2266 st->codecpar->extradata_size = strlen(buf);
2267 memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
2272 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2273 AVStream *st, MOVStreamContext *sc,
2278 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
2279 if ((int)size != size)
2280 return AVERROR(ENOMEM);
2282 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
2286 MOVStreamContext *tmcd_ctx = st->priv_data;
2288 val = AV_RB32(st->codecpar->extradata + 4);
2289 tmcd_ctx->tmcd_flags = val;
2290 st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
2291 st->avg_frame_rate.den = 1;
2292 #if FF_API_LAVF_AVCTX
2293 FF_DISABLE_DEPRECATION_WARNINGS
2294 st->codec->time_base = av_inv_q(st->avg_frame_rate);
2295 FF_ENABLE_DEPRECATION_WARNINGS
2297 /* adjust for per frame dur in counter mode */
2298 if (tmcd_ctx->tmcd_flags & 0x0008) {
2299 int timescale = AV_RB32(st->codecpar->extradata + 8);
2300 int framedur = AV_RB32(st->codecpar->extradata + 12);
2301 st->avg_frame_rate.num *= timescale;
2302 st->avg_frame_rate.den *= framedur;
2303 #if FF_API_LAVF_AVCTX
2304 FF_DISABLE_DEPRECATION_WARNINGS
2305 st->codec->time_base.den *= timescale;
2306 st->codec->time_base.num *= framedur;
2307 FF_ENABLE_DEPRECATION_WARNINGS
2311 uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
2312 uint32_t format = AV_RB32(st->codecpar->extradata + 22);
2313 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2314 uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
2315 if (str_size > 0 && size >= (int)str_size + 26) {
2316 char *reel_name = av_malloc(str_size + 1);
2318 return AVERROR(ENOMEM);
2319 memcpy(reel_name, st->codecpar->extradata + 30, str_size);
2320 reel_name[str_size] = 0; /* Add null terminator */
2321 /* don't add reel_name if emtpy string */
2322 if (*reel_name == 0) {
2325 av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2332 /* other codec type, just skip (rtp, mp4s ...) */
2333 avio_skip(pb, size);
2338 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2339 AVStream *st, MOVStreamContext *sc)
2341 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2342 !st->codecpar->sample_rate && sc->time_scale > 1)
2343 st->codecpar->sample_rate = sc->time_scale;
2345 /* special codec parameters handling */
2346 switch (st->codecpar->codec_id) {
2347 #if CONFIG_DV_DEMUXER
2348 case AV_CODEC_ID_DVAUDIO:
2349 c->dv_fctx = avformat_alloc_context();
2351 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2352 return AVERROR(ENOMEM);
2354 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2356 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2357 return AVERROR(ENOMEM);
2359 sc->dv_audio_container = 1;
2360 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
2363 /* no ifdef since parameters are always those */
2364 case AV_CODEC_ID_QCELP:
2365 st->codecpar->channels = 1;
2366 // force sample rate for qcelp when not stored in mov
2367 if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
2368 st->codecpar->sample_rate = 8000;
2369 // FIXME: Why is the following needed for some files?
2370 sc->samples_per_frame = 160;
2371 if (!sc->bytes_per_frame)
2372 sc->bytes_per_frame = 35;
2374 case AV_CODEC_ID_AMR_NB:
2375 st->codecpar->channels = 1;
2376 /* force sample rate for amr, stsd in 3gp does not store sample rate */
2377 st->codecpar->sample_rate = 8000;
2379 case AV_CODEC_ID_AMR_WB:
2380 st->codecpar->channels = 1;
2381 st->codecpar->sample_rate = 16000;
2383 case AV_CODEC_ID_MP2:
2384 case AV_CODEC_ID_MP3:
2385 /* force type after stsd for m1a hdlr */
2386 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2388 case AV_CODEC_ID_GSM:
2389 case AV_CODEC_ID_ADPCM_MS:
2390 case AV_CODEC_ID_ADPCM_IMA_WAV:
2391 case AV_CODEC_ID_ILBC:
2392 case AV_CODEC_ID_MACE3:
2393 case AV_CODEC_ID_MACE6:
2394 case AV_CODEC_ID_QDM2:
2395 st->codecpar->block_align = sc->bytes_per_frame;
2397 case AV_CODEC_ID_ALAC:
2398 if (st->codecpar->extradata_size == 36) {
2399 st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
2400 st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
2403 case AV_CODEC_ID_AC3:
2404 case AV_CODEC_ID_EAC3:
2405 case AV_CODEC_ID_MPEG1VIDEO:
2406 case AV_CODEC_ID_VC1:
2407 case AV_CODEC_ID_VP8:
2408 case AV_CODEC_ID_VP9:
2409 st->need_parsing = AVSTREAM_PARSE_FULL;
2417 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2418 int codec_tag, int format,
2421 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2424 (codec_tag != format &&
2425 // AVID 1:1 samples with differing data format and codec tag exist
2426 (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
2427 // prores is allowed to have differing data format and codec tag
2428 codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
2430 codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
2431 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2432 : codec_tag != MKTAG('j','p','e','g')))) {
2433 /* Multiple fourcc, we skip JPEG. This is not correct, we should
2434 * export it as a separate AVStream but this needs a few changes
2435 * in the MOV demuxer, patch welcome. */
2437 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2438 avio_skip(pb, size);
2445 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2448 MOVStreamContext *sc;
2449 int pseudo_stream_id;
2451 av_assert0 (c->fc->nb_streams >= 1);
2452 st = c->fc->streams[c->fc->nb_streams-1];
2455 for (pseudo_stream_id = 0;
2456 pseudo_stream_id < entries && !pb->eof_reached;
2457 pseudo_stream_id++) {
2458 //Parsing Sample description table
2460 int ret, dref_id = 1;
2461 MOVAtom a = { AV_RL32("stsd") };
2462 int64_t start_pos = avio_tell(pb);
2463 int64_t size = avio_rb32(pb); /* size */
2464 uint32_t format = avio_rl32(pb); /* data format */
2467 avio_rb32(pb); /* reserved */
2468 avio_rb16(pb); /* reserved */
2469 dref_id = avio_rb16(pb);
2470 } else if (size <= 7) {
2471 av_log(c->fc, AV_LOG_ERROR,
2472 "invalid size %"PRId64" in stsd\n", size);
2473 return AVERROR_INVALIDDATA;
2476 if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
2477 size - (avio_tell(pb) - start_pos))) {
2482 sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
2483 sc->dref_id= dref_id;
2484 sc->format = format;
2486 id = mov_codec_id(st, format);
2488 av_log(c->fc, AV_LOG_TRACE,
2489 "size=%"PRId64" 4CC=%s codec_type=%d\n", size,
2490 av_fourcc2str(format), st->codecpar->codec_type);
2492 if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
2493 st->codecpar->codec_id = id;
2494 mov_parse_stsd_video(c, pb, st, sc);
2495 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
2496 st->codecpar->codec_id = id;
2497 mov_parse_stsd_audio(c, pb, st, sc);
2498 if (st->codecpar->sample_rate < 0) {
2499 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
2500 return AVERROR_INVALIDDATA;
2502 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
2503 st->codecpar->codec_id = id;
2504 mov_parse_stsd_subtitle(c, pb, st, sc,
2505 size - (avio_tell(pb) - start_pos));
2507 ret = mov_parse_stsd_data(c, pb, st, sc,
2508 size - (avio_tell(pb) - start_pos));
2512 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2513 a.size = size - (avio_tell(pb) - start_pos);
2515 if ((ret = mov_read_default(c, pb, a)) < 0)
2517 } else if (a.size > 0)
2518 avio_skip(pb, a.size);
2520 if (sc->extradata && st->codecpar->extradata) {
2521 int extra_size = st->codecpar->extradata_size;
2523 /* Move the current stream extradata to the stream context one. */
2524 sc->extradata_size[pseudo_stream_id] = extra_size;
2525 sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
2526 if (!sc->extradata[pseudo_stream_id])
2527 return AVERROR(ENOMEM);
2528 memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
2529 av_freep(&st->codecpar->extradata);
2530 st->codecpar->extradata_size = 0;
2535 if (pb->eof_reached) {
2536 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSD atom\n");
2543 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2546 MOVStreamContext *sc;
2549 if (c->fc->nb_streams < 1)
2551 st = c->fc->streams[c->fc->nb_streams - 1];
2554 avio_r8(pb); /* version */
2555 avio_rb24(pb); /* flags */
2556 entries = avio_rb32(pb);
2559 av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
2560 return AVERROR_INVALIDDATA;
2563 if (sc->extradata) {
2564 av_log(c->fc, AV_LOG_ERROR,
2565 "Duplicate stsd found in this track.\n");
2566 return AVERROR_INVALIDDATA;
2569 /* Prepare space for hosting multiple extradata. */
2570 sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
2572 return AVERROR(ENOMEM);
2574 sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
2575 if (!sc->extradata_size) {
2576 ret = AVERROR(ENOMEM);
2580 ret = ff_mov_read_stsd_entries(c, pb, entries);
2584 /* Restore back the primary extradata. */
2585 av_freep(&st->codecpar->extradata);
2586 st->codecpar->extradata_size = sc->extradata_size[0];
2587 if (sc->extradata_size[0]) {
2588 st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
2589 if (!st->codecpar->extradata)
2590 return AVERROR(ENOMEM);
2591 memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
2594 return mov_finalize_stsd_codec(c, pb, st, sc);
2596 if (sc->extradata) {
2598 for (j = 0; j < sc->stsd_count; j++)
2599 av_freep(&sc->extradata[j]);
2602 av_freep(&sc->extradata);
2603 av_freep(&sc->extradata_size);
2607 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2610 MOVStreamContext *sc;
2611 unsigned int i, entries;
2613 if (c->fc->nb_streams < 1)
2615 st = c->fc->streams[c->fc->nb_streams-1];
2618 avio_r8(pb); /* version */
2619 avio_rb24(pb); /* flags */
2621 entries = avio_rb32(pb);
2622 if ((uint64_t)entries * 12 + 4 > atom.size)
2623 return AVERROR_INVALIDDATA;
2625 av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
2630 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2631 av_free(sc->stsc_data);
2633 sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2635 return AVERROR(ENOMEM);
2637 for (i = 0; i < entries && !pb->eof_reached; i++) {
2638 sc->stsc_data[i].first = avio_rb32(pb);
2639 sc->stsc_data[i].count = avio_rb32(pb);
2640 sc->stsc_data[i].id = avio_rb32(pb);
2644 for (i = sc->stsc_count - 1; i < UINT_MAX; i--) {
2645 int64_t first_min = i + 1;
2646 if ((i+1 < sc->stsc_count && sc->stsc_data[i].first >= sc->stsc_data[i+1].first) ||
2647 (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first) ||
2648 sc->stsc_data[i].first < first_min ||
2649 sc->stsc_data[i].count < 1 ||
2650 sc->stsc_data[i].id < 1) {
2651 av_log(c->fc, AV_LOG_WARNING, "STSC entry %d is invalid (first=%d count=%d id=%d)\n", i, sc->stsc_data[i].first, sc->stsc_data[i].count, sc->stsc_data[i].id);
2652 if (i+1 >= sc->stsc_count) {
2653 sc->stsc_data[i].first = FFMAX(sc->stsc_data[i].first, first_min);
2654 if (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first)
2655 sc->stsc_data[i].first = FFMIN(sc->stsc_data[i-1].first + 1LL, INT_MAX);
2656 sc->stsc_data[i].count = FFMAX(sc->stsc_data[i].count, 1);
2657 sc->stsc_data[i].id = FFMAX(sc->stsc_data[i].id, 1);
2660 av_assert0(sc->stsc_data[i+1].first >= 2);
2661 // We replace this entry by the next valid
2662 sc->stsc_data[i].first = sc->stsc_data[i+1].first - 1;
2663 sc->stsc_data[i].count = sc->stsc_data[i+1].count;
2664 sc->stsc_data[i].id = sc->stsc_data[i+1].id;
2668 if (pb->eof_reached) {
2669 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSC atom\n");
2676 static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
2678 return index < count - 1;
2681 /* Compute the samples value for the stsc entry at the given index. */
2682 static inline int64_t mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
2686 if (mov_stsc_index_valid(index, sc->stsc_count))
2687 chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
2689 chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
2691 return sc->stsc_data[index].count * (int64_t)chunk_count;
2694 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2697 MOVStreamContext *sc;
2698 unsigned i, entries;
2700 if (c->fc->nb_streams < 1)
2702 st = c->fc->streams[c->fc->nb_streams-1];
2705 avio_rb32(pb); // version + flags
2707 entries = avio_rb32(pb);
2709 av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2710 av_free(sc->stps_data);
2712 sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2714 return AVERROR(ENOMEM);
2716 for (i = 0; i < entries && !pb->eof_reached; i++) {
2717 sc->stps_data[i] = avio_rb32(pb);
2722 if (pb->eof_reached) {
2723 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STPS atom\n");
2730 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2733 MOVStreamContext *sc;
2734 unsigned int i, entries;
2736 if (c->fc->nb_streams < 1)
2738 st = c->fc->streams[c->fc->nb_streams-1];
2741 avio_r8(pb); /* version */
2742 avio_rb24(pb); /* flags */
2744 entries = avio_rb32(pb);
2746 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
2750 sc->keyframe_absent = 1;
2751 if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2752 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2756 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2757 if (entries >= UINT_MAX / sizeof(int))
2758 return AVERROR_INVALIDDATA;
2759 av_freep(&sc->keyframes);
2760 sc->keyframe_count = 0;
2761 sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2763 return AVERROR(ENOMEM);
2765 for (i = 0; i < entries && !pb->eof_reached; i++) {
2766 sc->keyframes[i] = avio_rb32(pb);
2769 sc->keyframe_count = i;
2771 if (pb->eof_reached) {
2772 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSS atom\n");
2779 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2782 MOVStreamContext *sc;
2783 unsigned int i, entries, sample_size, field_size, num_bytes;
2788 if (c->fc->nb_streams < 1)
2790 st = c->fc->streams[c->fc->nb_streams-1];
2793 avio_r8(pb); /* version */
2794 avio_rb24(pb); /* flags */
2796 if (atom.type == MKTAG('s','t','s','z')) {
2797 sample_size = avio_rb32(pb);
2798 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2799 sc->sample_size = sample_size;
2800 sc->stsz_sample_size = sample_size;
2804 avio_rb24(pb); /* reserved */
2805 field_size = avio_r8(pb);
2807 entries = avio_rb32(pb);
2809 av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
2811 sc->sample_count = entries;
2815 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2816 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
2817 return AVERROR_INVALIDDATA;
2822 if (entries >= (UINT_MAX - 4) / field_size)
2823 return AVERROR_INVALIDDATA;
2824 if (sc->sample_sizes)
2825 av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2826 av_free(sc->sample_sizes);
2827 sc->sample_count = 0;
2828 sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2829 if (!sc->sample_sizes)
2830 return AVERROR(ENOMEM);
2832 num_bytes = (entries*field_size+4)>>3;
2834 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2836 av_freep(&sc->sample_sizes);
2837 return AVERROR(ENOMEM);
2840 ret = ffio_read_size(pb, buf, num_bytes);
2842 av_freep(&sc->sample_sizes);
2847 init_get_bits(&gb, buf, 8*num_bytes);
2849 for (i = 0; i < entries && !pb->eof_reached; i++) {
2850 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2851 sc->data_size += sc->sample_sizes[i];
2854 sc->sample_count = i;
2858 if (pb->eof_reached) {
2859 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSZ atom\n");
2866 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2869 MOVStreamContext *sc;
2870 unsigned int i, entries, alloc_size = 0;
2872 int64_t total_sample_count=0;
2874 if (c->fc->nb_streams < 1)
2876 st = c->fc->streams[c->fc->nb_streams-1];
2879 avio_r8(pb); /* version */
2880 avio_rb24(pb); /* flags */
2881 entries = avio_rb32(pb);
2883 av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
2884 c->fc->nb_streams-1, entries);
2887 av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2888 av_freep(&sc->stts_data);
2890 if (entries >= INT_MAX / sizeof(*sc->stts_data))
2891 return AVERROR(ENOMEM);
2893 for (i = 0; i < entries && !pb->eof_reached; i++) {
2894 int sample_duration;
2895 unsigned int sample_count;
2896 unsigned int min_entries = FFMIN(FFMAX(i + 1, 1024 * 1024), entries);
2897 MOVStts *stts_data = av_fast_realloc(sc->stts_data, &alloc_size,
2898 min_entries * sizeof(*sc->stts_data));
2900 av_freep(&sc->stts_data);
2902 return AVERROR(ENOMEM);
2904 sc->stts_count = min_entries;
2905 sc->stts_data = stts_data;
2907 sample_count=avio_rb32(pb);
2908 sample_duration = avio_rb32(pb);
2910 sc->stts_data[i].count= sample_count;
2911 sc->stts_data[i].duration= sample_duration;
2913 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2914 sample_count, sample_duration);
2918 && sample_count == 1
2919 && total_sample_count > 100
2920 && sample_duration/10 > duration / total_sample_count)
2921 sample_duration = duration / total_sample_count;
2922 duration+=(int64_t)sample_duration*(uint64_t)sample_count;
2923 total_sample_count+=sample_count;
2929 duration <= INT64_MAX - sc->duration_for_fps &&
2930 total_sample_count <= INT64_MAX - sc->nb_frames_for_fps
2932 sc->duration_for_fps += duration;
2933 sc->nb_frames_for_fps += total_sample_count;
2936 if (pb->eof_reached) {
2937 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STTS atom\n");
2941 st->nb_frames= total_sample_count;
2943 st->duration= FFMIN(st->duration, duration);
2944 sc->track_end = duration;
2948 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2951 if (duration == INT_MIN) {
2952 av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2955 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2959 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2962 MOVStreamContext *sc;
2963 unsigned int i, entries, ctts_count = 0;
2965 if (c->fc->nb_streams < 1)
2967 st = c->fc->streams[c->fc->nb_streams-1];
2970 avio_r8(pb); /* version */
2971 avio_rb24(pb); /* flags */
2972 entries = avio_rb32(pb);
2974 av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
2978 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2979 return AVERROR_INVALIDDATA;
2980 av_freep(&sc->ctts_data);
2981 sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
2983 return AVERROR(ENOMEM);
2985 for (i = 0; i < entries && !pb->eof_reached; i++) {
2986 int count =avio_rb32(pb);
2987 int duration =avio_rb32(pb);
2990 av_log(c->fc, AV_LOG_TRACE,
2991 "ignoring CTTS entry with count=%d duration=%d\n",
2996 add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size,
2999 av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
3002 if (FFNABS(duration) < -(1<<28) && i+2<entries) {
3003 av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
3004 av_freep(&sc->ctts_data);
3010 mov_update_dts_shift(sc, duration);
3013 sc->ctts_count = ctts_count;
3015 if (pb->eof_reached) {
3016 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted CTTS atom\n");
3020 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
3025 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3028 MOVStreamContext *sc;
3029 unsigned int i, entries;
3031 uint32_t grouping_type;
3033 if (c->fc->nb_streams < 1)
3035 st = c->fc->streams[c->fc->nb_streams-1];
3038 version = avio_r8(pb); /* version */
3039 avio_rb24(pb); /* flags */
3040 grouping_type = avio_rl32(pb);
3041 if (grouping_type != MKTAG( 'r','a','p',' '))
3042 return 0; /* only support 'rap ' grouping */
3044 avio_rb32(pb); /* grouping_type_parameter */
3046 entries = avio_rb32(pb);
3050 av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
3051 av_free(sc->rap_group);
3052 sc->rap_group_count = 0;
3053 sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
3055 return AVERROR(ENOMEM);
3057 for (i = 0; i < entries && !pb->eof_reached; i++) {
3058 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
3059 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
3062 sc->rap_group_count = i;
3064 if (pb->eof_reached) {
3065 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted SBGP atom\n");
3073 * Get ith edit list entry (media time, duration).
3075 static int get_edit_list_entry(MOVContext *mov,
3076 const MOVStreamContext *msc,
3077 unsigned int edit_list_index,
3078 int64_t *edit_list_media_time,
3079 int64_t *edit_list_duration,
3080 int64_t global_timescale)
3082 if (edit_list_index == msc->elst_count) {
3085 *edit_list_media_time = msc->elst_data[edit_list_index].time;
3086 *edit_list_duration = msc->elst_data[edit_list_index].duration;
3088 /* duration is in global timescale units;convert to msc timescale */
3089 if (global_timescale == 0) {
3090 avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
3093 *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
3099 * Find the closest previous frame to the timestamp_pts, in e_old index
3100 * entries. Searching for just any frame / just key frames can be controlled by
3101 * last argument 'flag'.
3102 * Note that if ctts_data is not NULL, we will always search for a key frame
3103 * irrespective of the value of 'flag'. If we don't find any keyframe, we will
3104 * return the first frame of the video.
3106 * Here the timestamp_pts is considered to be a presentation timestamp and
3107 * the timestamp of index entries are considered to be decoding timestamps.
3109 * Returns 0 if successful in finding a frame, else returns -1.
3110 * Places the found index corresponding output arg.
3112 * If ctts_old is not NULL, then refines the searched entry by searching
3113 * backwards from the found timestamp, to find the frame with correct PTS.
3115 * Places the found ctts_index and ctts_sample in corresponding output args.
3117 static int find_prev_closest_index(AVStream *st,
3118 AVIndexEntry *e_old,
3122 int64_t timestamp_pts,
3125 int64_t* ctts_index,
3126 int64_t* ctts_sample)
3128 MOVStreamContext *msc = st->priv_data;
3129 AVIndexEntry *e_keep = st->index_entries;
3130 int nb_keep = st->nb_index_entries;
3132 int64_t index_ctts_count;
3136 // If dts_shift > 0, then all the index timestamps will have to be offset by
3137 // at least dts_shift amount to obtain PTS.
3138 // Hence we decrement the searched timestamp_pts by dts_shift to find the closest index element.
3139 if (msc->dts_shift > 0) {
3140 timestamp_pts -= msc->dts_shift;
3143 st->index_entries = e_old;
3144 st->nb_index_entries = nb_old;
3145 *index = av_index_search_timestamp(st, timestamp_pts, flag | AVSEEK_FLAG_BACKWARD);
3147 // Keep going backwards in the index entries until the timestamp is the same.
3149 for (i = *index; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
3151 if ((flag & AVSEEK_FLAG_ANY) ||
3152 (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
3158 // If we have CTTS then refine the search, by searching backwards over PTS
3159 // computed by adding corresponding CTTS durations to index timestamps.
3160 if (ctts_data && *index >= 0) {
3161 av_assert0(ctts_index);
3162 av_assert0(ctts_sample);
3163 // Find out the ctts_index for the found frame.
3166 for (index_ctts_count = 0; index_ctts_count < *index; index_ctts_count++) {
3167 if (*ctts_index < ctts_count) {
3169 if (ctts_data[*ctts_index].count == *ctts_sample) {
3176 while (*index >= 0 && (*ctts_index) >= 0 && (*ctts_index) < ctts_count) {
3177 // Find a "key frame" with PTS <= timestamp_pts (So that we can decode B-frames correctly).
3178 // No need to add dts_shift to the timestamp here becase timestamp_pts has already been
3179 // compensated by dts_shift above.
3180 if ((e_old[*index].timestamp + ctts_data[*ctts_index].duration) <= timestamp_pts &&
3181 (e_old[*index].flags & AVINDEX_KEYFRAME)) {
3186 if (*ctts_sample == 0) {
3188 if (*ctts_index >= 0)
3189 *ctts_sample = ctts_data[*ctts_index].count - 1;
3196 /* restore AVStream state*/
3197 st->index_entries = e_keep;
3198 st->nb_index_entries = nb_keep;
3199 return *index >= 0 ? 0 : -1;
3203 * Add index entry with the given values, to the end of st->index_entries.
3204 * Returns the new size st->index_entries if successful, else returns -1.
3206 * This function is similar to ff_add_index_entry in libavformat/utils.c
3207 * except that here we are always unconditionally adding an index entry to
3208 * the end, instead of searching the entries list and skipping the add if
3209 * there is an existing entry with the same timestamp.
3210 * This is needed because the mov_fix_index calls this func with the same
3211 * unincremented timestamp for successive discarded frames.
3213 static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
3214 int size, int distance, int flags)
3216 AVIndexEntry *entries, *ie;
3218 const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
3220 // Double the allocation each time, to lower memory fragmentation.
3221 // Another difference from ff_add_index_entry function.
3222 const size_t requested_size =
3223 min_size_needed > st->index_entries_allocated_size ?
3224 FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
3227 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
3230 entries = av_fast_realloc(st->index_entries,
3231 &st->index_entries_allocated_size,
3236 st->index_entries= entries;
3238 index= st->nb_index_entries++;
3239 ie= &entries[index];
3242 ie->timestamp = timestamp;
3243 ie->min_distance= distance;
3250 * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
3251 * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
3253 static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
3254 int64_t* frame_duration_buffer,
3255 int frame_duration_buffer_size) {
3257 av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
3258 for (i = 0; i < frame_duration_buffer_size; i++) {
3259 end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
3260 st->index_entries[end_index - 1 - i].timestamp = end_ts;
3265 * Append a new ctts entry to ctts_data.
3266 * Returns the new ctts_count if successful, else returns -1.
3268 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
3269 int count, int duration)
3271 MOVStts *ctts_buf_new;
3272 const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
3273 const size_t requested_size =
3274 min_size_needed > *allocated_size ?
3275 FFMAX(min_size_needed, 2 * (*allocated_size)) :
3278 if((unsigned)(*ctts_count) >= UINT_MAX / sizeof(MOVStts) - 1)
3281 ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
3286 *ctts_data = ctts_buf_new;
3288 ctts_buf_new[*ctts_count].count = count;
3289 ctts_buf_new[*ctts_count].duration = duration;
3291 *ctts_count = (*ctts_count) + 1;
3295 #define MAX_REORDER_DELAY 16
3296 static void mov_estimate_video_delay(MOVContext *c, AVStream* st) {
3297 MOVStreamContext *msc = st->priv_data;
3300 int ctts_sample = 0;
3301 int64_t pts_buf[MAX_REORDER_DELAY + 1]; // Circular buffer to sort pts.
3304 int j, r, num_swaps;
3306 if (st->codecpar->video_delay <= 0 && msc->ctts_data &&
3307 st->codecpar->codec_id == AV_CODEC_ID_H264) {
3308 st->codecpar->video_delay = 0;
3309 for(ind = 0; ind < st->nb_index_entries && ctts_ind < msc->ctts_count; ++ind) {
3310 if (buf_size == (MAX_REORDER_DELAY + 1)) {
3311 // If circular buffer is full, then move the first element forward.
3312 buf_start = (buf_start + 1) % buf_size;
3317 // Point j to the last elem of the buffer and insert the current pts there.
3318 j = (buf_start + buf_size - 1) % buf_size;
3319 pts_buf[j] = st->index_entries[ind].timestamp + msc->ctts_data[ctts_ind].duration;
3321 // The timestamps that are already in the sorted buffer, and are greater than the
3322 // current pts, are exactly the timestamps that need to be buffered to output PTS
3323 // in correct sorted order.
3324 // Hence the video delay (which is the buffer size used to sort DTS and output PTS),
3325 // can be computed as the maximum no. of swaps any particular timestamp needs to
3326 // go through, to keep this buffer in sorted order.
3328 while (j != buf_start) {
3329 r = (j - 1 + buf_size) % buf_size;
3330 if (pts_buf[j] < pts_buf[r]) {
3331 FFSWAP(int64_t, pts_buf[j], pts_buf[r]);
3336 st->codecpar->video_delay = FFMAX(st->codecpar->video_delay, num_swaps);
3339 if (ctts_sample == msc->ctts_data[ctts_ind].count) {
3344 av_log(c->fc, AV_LOG_DEBUG, "Setting codecpar->delay to %d for stream st: %d\n",
3345 st->codecpar->video_delay, st->index);
3349 static void mov_current_sample_inc(MOVStreamContext *sc)
3351 sc->current_sample++;
3352 sc->current_index++;
3353 if (sc->index_ranges &&
3354 sc->current_index >= sc->current_index_range->end &&
3355 sc->current_index_range->end) {
3356 sc->current_index_range++;
3357 sc->current_index = sc->current_index_range->start;
3361 static void mov_current_sample_dec(MOVStreamContext *sc)
3363 sc->current_sample--;
3364 sc->current_index--;
3365 if (sc->index_ranges &&
3366 sc->current_index < sc->current_index_range->start &&
3367 sc->current_index_range > sc->index_ranges) {
3368 sc->current_index_range--;
3369 sc->current_index = sc->current_index_range->end - 1;
3373 static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
3377 sc->current_sample = current_sample;
3378 sc->current_index = current_sample;
3379 if (!sc->index_ranges) {
3383 for (sc->current_index_range = sc->index_ranges;
3384 sc->current_index_range->end;
3385 sc->current_index_range++) {
3386 range_size = sc->current_index_range->end - sc->current_index_range->start;
3387 if (range_size > current_sample) {
3388 sc->current_index = sc->current_index_range->start + current_sample;
3391 current_sample -= range_size;
3396 * Fix st->index_entries, so that it contains only the entries (and the entries
3397 * which are needed to decode them) that fall in the edit list time ranges.
3398 * Also fixes the timestamps of the index entries to match the timeline
3399 * specified the edit lists.
3401 static void mov_fix_index(MOVContext *mov, AVStream *st)
3403 MOVStreamContext *msc = st->priv_data;
3404 AVIndexEntry *e_old = st->index_entries;
3405 int nb_old = st->nb_index_entries;
3406 const AVIndexEntry *e_old_end = e_old + nb_old;
3407 const AVIndexEntry *current = NULL;
3408 MOVStts *ctts_data_old = msc->ctts_data;
3409 int64_t ctts_index_old = 0;
3410 int64_t ctts_sample_old = 0;
3411 int64_t ctts_count_old = msc->ctts_count;
3412 int64_t edit_list_media_time = 0;
3413 int64_t edit_list_duration = 0;
3414 int64_t frame_duration = 0;
3415 int64_t edit_list_dts_counter = 0;
3416 int64_t edit_list_dts_entry_end = 0;
3417 int64_t edit_list_start_ctts_sample = 0;
3419 int64_t curr_ctts = 0;
3420 int64_t empty_edits_sum_duration = 0;
3421 int64_t edit_list_index = 0;
3424 int64_t start_dts = 0;
3425 int64_t edit_list_start_encountered = 0;
3426 int64_t search_timestamp = 0;
3427 int64_t* frame_duration_buffer = NULL;
3428 int num_discarded_begin = 0;
3429 int first_non_zero_audio_edit = -1;
3430 int packet_skip_samples = 0;
3431 MOVIndexRange *current_index_range;
3433 int found_keyframe_after_edit = 0;
3435 if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
3439 // allocate the index ranges array
3440 msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
3441 if (!msc->index_ranges) {
3442 av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
3445 msc->current_index_range = msc->index_ranges;
3446 current_index_range = msc->index_ranges - 1;
3448 // Clean AVStream from traces of old index
3449 st->index_entries = NULL;
3450 st->index_entries_allocated_size = 0;
3451 st->nb_index_entries = 0;
3453 // Clean ctts fields of MOVStreamContext
3454 msc->ctts_data = NULL;
3455 msc->ctts_count = 0;
3456 msc->ctts_index = 0;
3457 msc->ctts_sample = 0;
3458 msc->ctts_allocated_size = 0;
3460 // Reinitialize min_corrected_pts so that it can be computed again.
3461 msc->min_corrected_pts = -1;
3463 // If the dts_shift is positive (in case of negative ctts values in mov),
3464 // then negate the DTS by dts_shift
3465 if (msc->dts_shift > 0) {
3466 edit_list_dts_entry_end -= msc->dts_shift;
3467 av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
3470 start_dts = edit_list_dts_entry_end;
3472 while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
3473 &edit_list_duration, mov->time_scale)) {
3474 av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
3475 st->index, edit_list_index, edit_list_media_time, edit_list_duration);
3477 edit_list_dts_counter = edit_list_dts_entry_end;
3478 edit_list_dts_entry_end += edit_list_duration;
3479 num_discarded_begin = 0;
3480 if (edit_list_media_time == -1) {
3481 empty_edits_sum_duration += edit_list_duration;
3485 // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
3486 // according to the edit list below.
3487 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3488 if (first_non_zero_audio_edit < 0) {
3489 first_non_zero_audio_edit = 1;
3491 first_non_zero_audio_edit = 0;
3494 if (first_non_zero_audio_edit > 0)
3495 st->skip_samples = msc->start_pad = 0;
3498 // While reordering frame index according to edit list we must handle properly
3499 // the scenario when edit list entry starts from none key frame.
3500 // We find closest previous key frame and preserve it and consequent frames in index.
3501 // All frames which are outside edit list entry time boundaries will be dropped after decoding.
3502 search_timestamp = edit_list_media_time;
3503 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3504 // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
3505 // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
3506 // edit_list_media_time to cover the decoder delay.
3507 search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
3510 if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, 0,
3511 &index, &ctts_index_old, &ctts_sample_old) < 0) {
3512 av_log(mov->fc, AV_LOG_WARNING,
3513 "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
3514 st->index, edit_list_index, search_timestamp);
3515 if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, AVSEEK_FLAG_ANY,
3516 &index, &ctts_index_old, &ctts_sample_old) < 0) {
3517 av_log(mov->fc, AV_LOG_WARNING,
3518 "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n",
3519 st->index, edit_list_index, search_timestamp);
3522 ctts_sample_old = 0;
3525 current = e_old + index;
3526 edit_list_start_ctts_sample = ctts_sample_old;
3528 // Iterate over index and arrange it according to edit list
3529 edit_list_start_encountered = 0;
3530 found_keyframe_after_edit = 0;
3531 for (; current < e_old_end; current++, index++) {
3532 // check if frame outside edit list mark it for discard
3533 frame_duration = (current + 1 < e_old_end) ?
3534 ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
3536 flags = current->flags;
3538 // frames (pts) before or after edit list
3539 curr_cts = current->timestamp + msc->dts_shift;
3542 if (ctts_data_old && ctts_index_old < ctts_count_old) {
3543 curr_ctts = ctts_data_old[ctts_index_old].duration;
3544 av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",
3545 curr_cts, curr_ctts, ctts_index_old, ctts_count_old);
3546 curr_cts += curr_ctts;
3548 if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
3549 if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3550 &msc->ctts_allocated_size,
3551 ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3552 ctts_data_old[ctts_index_old].duration) == -1) {
3553 av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3555 ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3556 ctts_data_old[ctts_index_old].duration);
3560 ctts_sample_old = 0;
3561 edit_list_start_ctts_sample = 0;
3565 if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
3566 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
3567 curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
3568 first_non_zero_audio_edit > 0) {
3569 packet_skip_samples = edit_list_media_time - curr_cts;
3570 st->skip_samples += packet_skip_samples;
3572 // Shift the index entry timestamp by packet_skip_samples to be correct.
3573 edit_list_dts_counter -= packet_skip_samples;
3574 if (edit_list_start_encountered == 0) {
3575 edit_list_start_encountered = 1;
3576 // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3577 // discarded packets.
3578 if (frame_duration_buffer) {
3579 fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3580 frame_duration_buffer, num_discarded_begin);
3581 av_freep(&frame_duration_buffer);
3585 av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
3587 flags |= AVINDEX_DISCARD_FRAME;
3588 av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
3590 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
3591 num_discarded_begin++;
3592 frame_duration_buffer = av_realloc(frame_duration_buffer,
3593 num_discarded_begin * sizeof(int64_t));
3594 if (!frame_duration_buffer) {
3595 av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
3598 frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
3600 // Increment skip_samples for the first non-zero audio edit list
3601 if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
3602 st->skip_samples += frame_duration;
3607 if (msc->min_corrected_pts < 0) {
3608 msc->min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
3610 msc->min_corrected_pts = FFMIN(msc->min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
3612 if (edit_list_start_encountered == 0) {
3613 edit_list_start_encountered = 1;
3614 // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3615 // discarded packets.
3616 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
3617 fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3618 frame_duration_buffer, num_discarded_begin);
3619 av_freep(&frame_duration_buffer);
3624 if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
3625 current->min_distance, flags) == -1) {
3626 av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
3630 // Update the index ranges array
3631 if (current_index_range < msc->index_ranges || index != current_index_range->end) {
3632 current_index_range++;
3633 current_index_range->start = index;
3635 current_index_range->end = index + 1;
3637 // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
3638 if (edit_list_start_encountered > 0) {
3639 edit_list_dts_counter = edit_list_dts_counter + frame_duration;
3642 // Break when found first key frame after edit entry completion
3643 if ((curr_cts + frame_duration >= (edit_list_duration + edit_list_media_time)) &&
3644 ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
3645 if (ctts_data_old) {
3646 // If we have CTTS and this is the first keyframe after edit elist,
3647 // wait for one more, because there might be trailing B-frames after this I-frame
3648 // that do belong to the edit.
3649 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && found_keyframe_after_edit == 0) {
3650 found_keyframe_after_edit = 1;
3653 if (ctts_sample_old != 0) {
3654 if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3655 &msc->ctts_allocated_size,
3656 ctts_sample_old - edit_list_start_ctts_sample,
3657 ctts_data_old[ctts_index_old].duration) == -1) {
3658 av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3659 ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
3660 ctts_data_old[ctts_index_old].duration);
3669 // If there are empty edits, then msc->min_corrected_pts might be positive
3670 // intentionally. So we subtract the sum duration of emtpy edits here.
3671 msc->min_corrected_pts -= empty_edits_sum_duration;
3673 // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
3674 // dts by that amount to make the first pts zero.
3675 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && msc->min_corrected_pts > 0) {
3676 av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", msc->min_corrected_pts);
3677 for (i = 0; i < st->nb_index_entries; ++i) {
3678 st->index_entries[i].timestamp -= msc->min_corrected_pts;
3682 // Update av stream length, if it ends up shorter than the track's media duration
3683 st->duration = FFMIN(st->duration, edit_list_dts_entry_end - start_dts);
3684 msc->start_pad = st->skip_samples;
3686 // Free the old index and the old CTTS structures
3688 av_free(ctts_data_old);
3689 av_freep(&frame_duration_buffer);
3691 // Null terminate the index ranges array
3692 current_index_range++;
3693 current_index_range->start = 0;
3694 current_index_range->end = 0;
3695 msc->current_index = msc->index_ranges[0].start;
3698 static void mov_build_index(MOVContext *mov, AVStream *st)
3700 MOVStreamContext *sc = st->priv_data;
3701 int64_t current_offset;
3702 int64_t current_dts = 0;
3703 unsigned int stts_index = 0;
3704 unsigned int stsc_index = 0;
3705 unsigned int stss_index = 0;
3706 unsigned int stps_index = 0;
3708 uint64_t stream_size = 0;
3709 MOVStts *ctts_data_old = sc->ctts_data;
3710 unsigned int ctts_count_old = sc->ctts_count;
3712 if (sc->elst_count) {
3713 int i, edit_start_index = 0, multiple_edits = 0;
3714 int64_t empty_duration = 0; // empty duration of the first edit list entry
3715 int64_t start_time = 0; // start time of the media
3717 for (i = 0; i < sc->elst_count; i++) {
3718 const MOVElst *e = &sc->elst_data[i];
3719 if (i == 0 && e->time == -1) {
3720 /* if empty, the first entry is the start time of the stream
3721 * relative to the presentation itself */
3722 empty_duration = e->duration;
3723 edit_start_index = 1;
3724 } else if (i == edit_start_index && e->time >= 0) {
3725 start_time = e->time;
3731 if (multiple_edits && !mov->advanced_editlist)
3732 av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
3733 "Use -advanced_editlist to correctly decode otherwise "
3734 "a/v desync might occur\n");
3736 /* adjust first dts according to edit list */
3737 if ((empty_duration || start_time) && mov->time_scale > 0) {
3739 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
3740 sc->time_offset = start_time - empty_duration;
3741 sc->min_corrected_pts = start_time;
3742 if (!mov->advanced_editlist)
3743 current_dts = -sc->time_offset;
3746 if (!multiple_edits && !mov->advanced_editlist &&
3747 st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
3748 sc->start_pad = start_time;
3751 /* only use old uncompressed audio chunk demuxing when stts specifies it */
3752 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
3753 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
3754 unsigned int current_sample = 0;
3755 unsigned int stts_sample = 0;
3756 unsigned int sample_size;
3757 unsigned int distance = 0;
3758 unsigned int rap_group_index = 0;
3759 unsigned int rap_group_sample = 0;
3760 int64_t last_dts = 0;
3761 int64_t dts_correction = 0;
3762 int rap_group_present = sc->rap_group_count && sc->rap_group;
3763 int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
3765 current_dts -= sc->dts_shift;
3766 last_dts = current_dts;
3768 if (!sc->sample_count || st->nb_index_entries)
3770 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3772 if (av_reallocp_array(&st->index_entries,
3773 st->nb_index_entries + sc->sample_count,
3774 sizeof(*st->index_entries)) < 0) {
3775 st->nb_index_entries = 0;
3778 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
3780 if (ctts_data_old) {
3781 // Expand ctts entries such that we have a 1-1 mapping with samples
3782 if (sc->sample_count >= UINT_MAX / sizeof(*sc->ctts_data))
3785 sc->ctts_allocated_size = 0;
3786 sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size,
3787 sc->sample_count * sizeof(*sc->ctts_data));
3788 if (!sc->ctts_data) {
3789 av_free(ctts_data_old);
3793 memset((uint8_t*)(sc->ctts_data), 0, sc->ctts_allocated_size);
3795 for (i = 0; i < ctts_count_old &&
3796 sc->ctts_count < sc->sample_count; i++)
3797 for (j = 0; j < ctts_data_old[i].count &&
3798 sc->ctts_count < sc->sample_count; j++)
3799 add_ctts_entry(&sc->ctts_data, &sc->ctts_count,
3800 &sc->ctts_allocated_size, 1,
3801 ctts_data_old[i].duration);
3802 av_free(ctts_data_old);
3805 for (i = 0; i < sc->chunk_count; i++) {
3806 int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
3807 current_offset = sc->chunk_offsets[i];
3808 while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3809 i + 1 == sc->stsc_data[stsc_index + 1].first)
3812 if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
3813 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
3814 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
3815 sc->stsz_sample_size = sc->sample_size;
3817 if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
3818 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
3819 sc->stsz_sample_size = sc->sample_size;
3822 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
3824 if (current_sample >= sc->sample_count) {
3825 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
3829 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
3831 if (stss_index + 1 < sc->keyframe_count)
3833 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
3835 if (stps_index + 1 < sc->stps_count)
3838 if (rap_group_present && rap_group_index < sc->rap_group_count) {
3839 if (sc->rap_group[rap_group_index].index > 0)
3841 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
3842 rap_group_sample = 0;
3846 if (sc->keyframe_absent
3848 && !rap_group_present
3849 && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
3853 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
3854 if (sc->pseudo_stream_id == -1 ||
3855 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
3857 if (sample_size > 0x3FFFFFFF) {
3858 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
3861 e = &st->index_entries[st->nb_index_entries++];
3862 e->pos = current_offset;
3863 e->timestamp = current_dts;
3864 e->size = sample_size;
3865 e->min_distance = distance;
3866 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
3867 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
3868 "size %u, distance %u, keyframe %d\n", st->index, current_sample,
3869 current_offset, current_dts, sample_size, distance, keyframe);
3870 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
3871 ff_rfps_add_frame(mov->fc, st, current_dts);
3874 current_offset += sample_size;
3875 stream_size += sample_size;
3877 /* A negative sample duration is invalid based on the spec,
3878 * but some samples need it to correct the DTS. */
3879 if (sc->stts_data[stts_index].duration < 0) {
3880 av_log(mov->fc, AV_LOG_WARNING,
3881 "Invalid SampleDelta %d in STTS, at %d st:%d\n",
3882 sc->stts_data[stts_index].duration, stts_index,
3884 dts_correction += sc->stts_data[stts_index].duration - 1;
3885 sc->stts_data[stts_index].duration = 1;
3887 current_dts += sc->stts_data[stts_index].duration;
3888 if (!dts_correction || current_dts + dts_correction > last_dts) {
3889 current_dts += dts_correction;
3892 /* Avoid creating non-monotonous DTS */
3893 dts_correction += current_dts - last_dts - 1;
3894 current_dts = last_dts + 1;
3896 last_dts = current_dts;
3900 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
3906 if (st->duration > 0)
3907 st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
3909 unsigned chunk_samples, total = 0;
3911 if (!sc->chunk_count)
3914 // compute total chunk count
3915 for (i = 0; i < sc->stsc_count; i++) {
3916 unsigned count, chunk_count;
3918 chunk_samples = sc->stsc_data[i].count;
3919 if (i != sc->stsc_count - 1 &&
3920 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
3921 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
3925 if (sc->samples_per_frame >= 160) { // gsm
3926 count = chunk_samples / sc->samples_per_frame;
3927 } else if (sc->samples_per_frame > 1) {
3928 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
3929 count = (chunk_samples+samples-1) / samples;
3931 count = (chunk_samples+1023) / 1024;
3934 if (mov_stsc_index_valid(i, sc->stsc_count))
3935 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
3937 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
3938 total += chunk_count * count;
3941 av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
3942 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3944 if (av_reallocp_array(&st->index_entries,
3945 st->nb_index_entries + total,
3946 sizeof(*st->index_entries)) < 0) {
3947 st->nb_index_entries = 0;
3950 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
3953 for (i = 0; i < sc->chunk_count; i++) {
3954 current_offset = sc->chunk_offsets[i];
3955 if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3956 i + 1 == sc->stsc_data[stsc_index + 1].first)
3958 chunk_samples = sc->stsc_data[stsc_index].count;
3960 while (chunk_samples > 0) {
3962 unsigned size, samples;
3964 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
3965 avpriv_request_sample(mov->fc,
3966 "Zero bytes per frame, but %d samples per frame",
3967 sc->samples_per_frame);
3971 if (sc->samples_per_frame >= 160) { // gsm
3972 samples = sc->samples_per_frame;
3973 size = sc->bytes_per_frame;
3975 if (sc->samples_per_frame > 1) {
3976 samples = FFMIN((1024 / sc->samples_per_frame)*
3977 sc->samples_per_frame, chunk_samples);
3978 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
3980 samples = FFMIN(1024, chunk_samples);
3981 size = samples * sc->sample_size;
3985 if (st->nb_index_entries >= total) {
3986 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
3989 if (size > 0x3FFFFFFF) {
3990 av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
3993 e = &st->index_entries[st->nb_index_entries++];
3994 e->pos = current_offset;
3995 e->timestamp = current_dts;
3997 e->min_distance = 0;
3998 e->flags = AVINDEX_KEYFRAME;
3999 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
4000 "size %u, duration %u\n", st->index, i, current_offset, current_dts,
4003 current_offset += size;
4004 current_dts += samples;
4005 chunk_samples -= samples;
4010 if (!mov->ignore_editlist && mov->advanced_editlist) {
4011 // Fix index according to edit lists.
4012 mov_fix_index(mov, st);
4015 mov_estimate_video_delay(mov, st);
4018 static int test_same_origin(const char *src, const char *ref) {
4028 av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
4029 av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
4031 if (strlen(src) == 0) {
4033 } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
4034 strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
4035 strlen(src_host) + 1 >= sizeof(src_host) ||
4036 strlen(ref_host) + 1 >= sizeof(ref_host)) {
4038 } else if (strcmp(src_proto, ref_proto) ||
4039 strcmp(src_auth, ref_auth) ||
4040 strcmp(src_host, ref_host) ||
4041 src_port != ref_port) {
4047 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
4049 /* try relative path, we do not try the absolute because it can leak information about our
4050 system to an attacker */
4051 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
4052 char filename[1025];
4053 const char *src_path;
4056 /* find a source dir */
4057 src_path = strrchr(src, '/');
4063 /* find a next level down to target */
4064 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
4065 if (ref->path[l] == '/') {
4066 if (i == ref->nlvl_to - 1)
4072 /* compose filename if next level down to target was found */
4073 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
4074 memcpy(filename, src, src_path - src);
4075 filename[src_path - src] = 0;
4077 for (i = 1; i < ref->nlvl_from; i++)
4078 av_strlcat(filename, "../", sizeof(filename));
4080 av_strlcat(filename, ref->path + l + 1, sizeof(filename));
4081 if (!c->use_absolute_path) {
4082 int same_origin = test_same_origin(src, filename);
4085 av_log(c->fc, AV_LOG_ERROR,
4086 "Reference with mismatching origin, %s not tried for security reasons, "
4087 "set demuxer option use_absolute_path to allow it anyway\n",
4089 return AVERROR(ENOENT);
4092 if(strstr(ref->path + l + 1, "..") ||
4093 strstr(ref->path + l + 1, ":") ||
4094 (ref->nlvl_from > 1 && same_origin < 0) ||
4095 (filename[0] == '/' && src_path == src))
4096 return AVERROR(ENOENT);
4099 if (strlen(filename) + 1 == sizeof(filename))
4100 return AVERROR(ENOENT);
4101 if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
4104 } else if (c->use_absolute_path) {
4105 av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
4106 "this is a possible security issue\n");
4107 if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
4110 av_log(c->fc, AV_LOG_ERROR,
4111 "Absolute path %s not tried for security reasons, "
4112 "set demuxer option use_absolute_path to allow absolute paths\n",
4116 return AVERROR(ENOENT);
4119 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
4121 if (sc->time_scale <= 0) {
4122 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
4123 sc->time_scale = c->time_scale;
4124 if (sc->time_scale <= 0)
4129 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4132 MOVStreamContext *sc;
4135 st = avformat_new_stream(c->fc, NULL);
4136 if (!st) return AVERROR(ENOMEM);
4137 st->id = c->fc->nb_streams;
4138 sc = av_mallocz(sizeof(MOVStreamContext));
4139 if (!sc) return AVERROR(ENOMEM);
4142 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
4143 sc->ffindex = st->index;
4144 c->trak_index = st->index;
4146 if ((ret = mov_read_default(c, pb, atom)) < 0)
4152 if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
4153 (!sc->sample_size && !sc->sample_count))) ||
4154 (!sc->chunk_count && sc->sample_count)) {
4155 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
4159 if (sc->chunk_count && sc->stsc_count && sc->stsc_data[ sc->stsc_count - 1 ].first > sc->chunk_count) {
4160 av_log(c->fc, AV_LOG_ERROR, "stream %d, contradictionary STSC and STCO\n",
4162 return AVERROR_INVALIDDATA;
4165 fix_timescale(c, sc);
4167 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
4169 mov_build_index(c, st);
4171 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
4172 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
4173 if (c->enable_drefs) {
4174 if (mov_open_dref(c, &sc->pb, c->fc->url, dref) < 0)
4175 av_log(c->fc, AV_LOG_ERROR,
4176 "stream %d, error opening alias: path='%s', dir='%s', "
4177 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
4178 st->index, dref->path, dref->dir, dref->filename,
4179 dref->volume, dref->nlvl_from, dref->nlvl_to);
4181 av_log(c->fc, AV_LOG_WARNING,
4182 "Skipped opening external track: "
4183 "stream %d, alias: path='%s', dir='%s', "
4184 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
4185 "Set enable_drefs to allow this.\n",
4186 st->index, dref->path, dref->dir, dref->filename,
4187 dref->volume, dref->nlvl_from, dref->nlvl_to);
4191 sc->pb_is_copied = 1;
4194 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
4195 if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
4196 sc->height && sc->width &&
4197 (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
4198 st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
4199 ((double)st->codecpar->width * sc->height), INT_MAX);
4202 #if FF_API_R_FRAME_RATE
4203 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
4204 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
4205 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
4209 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
4210 if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
4211 TAG_IS_AVCI(st->codecpar->codec_tag)) {
4212 ret = ff_generate_avci_extradata(st);
4217 switch (st->codecpar->codec_id) {
4218 #if CONFIG_H261_DECODER
4219 case AV_CODEC_ID_H261:
4221 #if CONFIG_H263_DECODER
4222 case AV_CODEC_ID_H263:
4224 #if CONFIG_MPEG4_DECODER
4225 case AV_CODEC_ID_MPEG4:
4227 st->codecpar->width = 0; /* let decoder init width/height */
4228 st->codecpar->height= 0;
4232 // If the duration of the mp3 packets is not constant, then they could need a parser
4233 if (st->codecpar->codec_id == AV_CODEC_ID_MP3
4234 && sc->stts_count > 3
4235 && sc->stts_count*10 > st->nb_frames
4236 && sc->time_scale == st->codecpar->sample_rate) {
4237 st->need_parsing = AVSTREAM_PARSE_FULL;
4239 /* Do not need those anymore. */
4240 av_freep(&sc->chunk_offsets);
4241 av_freep(&sc->sample_sizes);
4242 av_freep(&sc->keyframes);
4243 av_freep(&sc->stts_data);
4244 av_freep(&sc->stps_data);
4245 av_freep(&sc->elst_data);
4246 av_freep(&sc->rap_group);
4251 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4254 c->itunes_metadata = 1;
4255 ret = mov_read_default(c, pb, atom);
4256 c->itunes_metadata = 0;
4260 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4269 count = avio_rb32(pb);
4270 if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
4271 av_log(c->fc, AV_LOG_ERROR,
4272 "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
4273 return AVERROR_INVALIDDATA;
4276 c->meta_keys_count = count + 1;
4277 c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
4279 return AVERROR(ENOMEM);
4281 for (i = 1; i <= count; ++i) {
4282 uint32_t key_size = avio_rb32(pb);
4283 uint32_t type = avio_rl32(pb);
4285 av_log(c->fc, AV_LOG_ERROR,
4286 "The key# %"PRIu32" in meta has invalid size:"
4287 "%"PRIu32"\n", i, key_size);
4288 return AVERROR_INVALIDDATA;
4291 if (type != MKTAG('m','d','t','a')) {
4292 avio_skip(pb, key_size);
4294 c->meta_keys[i] = av_mallocz(key_size + 1);
4295 if (!c->meta_keys[i])
4296 return AVERROR(ENOMEM);
4297 avio_read(pb, c->meta_keys[i], key_size);
4303 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4305 int64_t end = avio_tell(pb) + atom.size;
4306 uint8_t *key = NULL, *val = NULL, *mean = NULL;
4310 MOVStreamContext *sc;
4312 if (c->fc->nb_streams < 1)
4314 st = c->fc->streams[c->fc->nb_streams-1];
4317 for (i = 0; i < 3; i++) {
4321 if (end - avio_tell(pb) <= 12)
4324 len = avio_rb32(pb);
4325 tag = avio_rl32(pb);
4326 avio_skip(pb, 4); // flags
4328 if (len < 12 || len - 12 > end - avio_tell(pb))
4332 if (tag == MKTAG('m', 'e', 'a', 'n'))
4334 else if (tag == MKTAG('n', 'a', 'm', 'e'))
4336 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
4343 *p = av_malloc(len + 1);
4345 ret = AVERROR(ENOMEM);
4348 ret = ffio_read_size(pb, *p, len);
4356 if (mean && key && val) {
4357 if (strcmp(key, "iTunSMPB") == 0) {
4358 int priming, remainder, samples;
4359 if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
4360 if(priming>0 && priming<16384)
4361 sc->start_pad = priming;
4364 if (strcmp(key, "cdec") != 0) {
4365 av_dict_set(&c->fc->metadata, key, val,
4366 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
4370 av_log(c->fc, AV_LOG_VERBOSE,
4371 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
4374 avio_seek(pb, end, SEEK_SET);
4381 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4383 while (atom.size > 8) {
4384 uint32_t tag = avio_rl32(pb);
4386 if (tag == MKTAG('h','d','l','r')) {
4387 avio_seek(pb, -8, SEEK_CUR);
4389 return mov_read_default(c, pb, atom);
4395 // return 1 when matrix is identity, 0 otherwise
4396 #define IS_MATRIX_IDENT(matrix) \
4397 ( (matrix)[0][0] == (1 << 16) && \
4398 (matrix)[1][1] == (1 << 16) && \
4399 (matrix)[2][2] == (1 << 30) && \
4400 !(matrix)[0][1] && !(matrix)[0][2] && \
4401 !(matrix)[1][0] && !(matrix)[1][2] && \
4402 !(matrix)[2][0] && !(matrix)[2][1])
4404 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4409 int display_matrix[3][3];
4410 int res_display_matrix[3][3] = { { 0 } };
4412 MOVStreamContext *sc;
4416 if (c->fc->nb_streams < 1)
4418 st = c->fc->streams[c->fc->nb_streams-1];
4421 version = avio_r8(pb);
4422 flags = avio_rb24(pb);
4423 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
4429 avio_rb32(pb); /* creation time */
4430 avio_rb32(pb); /* modification time */
4432 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
4433 avio_rb32(pb); /* reserved */
4435 /* highlevel (considering edits) duration in movie timebase */
4436 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
4437 avio_rb32(pb); /* reserved */
4438 avio_rb32(pb); /* reserved */
4440 avio_rb16(pb); /* layer */
4441 avio_rb16(pb); /* alternate group */
4442 avio_rb16(pb); /* volume */
4443 avio_rb16(pb); /* reserved */
4445 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
4446 // they're kept in fixed point format through all calculations
4447 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
4448 // side data, but the scale factor is not needed to calculate aspect ratio
4449 for (i = 0; i < 3; i++) {
4450 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
4451 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
4452 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
4455 width = avio_rb32(pb); // 16.16 fixed point track width
4456 height = avio_rb32(pb); // 16.16 fixed point track height
4457 sc->width = width >> 16;
4458 sc->height = height >> 16;
4460 // apply the moov display matrix (after the tkhd one)
4461 for (i = 0; i < 3; i++) {
4462 const int sh[3] = { 16, 16, 30 };
4463 for (j = 0; j < 3; j++) {
4464 for (e = 0; e < 3; e++) {
4465 res_display_matrix[i][j] +=
4466 ((int64_t) display_matrix[i][e] *
4467 c->movie_display_matrix[e][j]) >> sh[e];
4472 // save the matrix when it is not the default identity
4473 if (!IS_MATRIX_IDENT(res_display_matrix)) {
4476 av_freep(&sc->display_matrix);
4477 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
4478 if (!sc->display_matrix)
4479 return AVERROR(ENOMEM);
4481 for (i = 0; i < 3; i++)
4482 for (j = 0; j < 3; j++)
4483 sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
4485 #if FF_API_OLD_ROTATE_API
4486 rotate = av_display_rotation_get(sc->display_matrix);
4487 if (!isnan(rotate)) {
4488 char rotate_buf[64];
4490 if (rotate < 0) // for backward compatibility
4492 snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
4493 av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
4498 // transform the display width/height according to the matrix
4499 // to keep the same scale, use [width height 1<<16]
4500 if (width && height && sc->display_matrix) {
4501 double disp_transform[2];
4503 for (i = 0; i < 2; i++)
4504 disp_transform[i] = hypot(sc->display_matrix[0 + i],
4505 sc->display_matrix[3 + i]);
4507 if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
4508 disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
4509 fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
4510 st->sample_aspect_ratio = av_d2q(
4511 disp_transform[0] / disp_transform[1],
4517 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4519 MOVFragment *frag = &c->fragment;
4520 MOVTrackExt *trex = NULL;
4521 int flags, track_id, i;
4523 avio_r8(pb); /* version */
4524 flags = avio_rb24(pb);
4526 track_id = avio_rb32(pb);
4528 return AVERROR_INVALIDDATA;
4529 frag->track_id = track_id;
4530 set_frag_stream(&c->frag_index, track_id);
4531 for (i = 0; i < c->trex_count; i++)
4532 if (c->trex_data[i].track_id == frag->track_id) {
4533 trex = &c->trex_data[i];
4537 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
4538 return AVERROR_INVALIDDATA;
4541 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
4542 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
4543 frag->moof_offset : frag->implicit_offset;
4544 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
4546 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
4547 avio_rb32(pb) : trex->duration;
4548 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
4549 avio_rb32(pb) : trex->size;
4550 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
4551 avio_rb32(pb) : trex->flags;
4552 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
4557 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4562 num = atom.size / 4;
4563 if (!(new_tracks = av_malloc_array(num, sizeof(int))))
4564 return AVERROR(ENOMEM);
4566 av_free(c->chapter_tracks);
4567 c->chapter_tracks = new_tracks;
4568 c->nb_chapter_tracks = num;
4570 for (i = 0; i < num && !pb->eof_reached; i++)
4571 c->chapter_tracks[i] = avio_rb32(pb);
4576 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4581 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
4582 return AVERROR_INVALIDDATA;
4583 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
4584 sizeof(*c->trex_data))) < 0) {
4589 c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
4591 trex = &c->trex_data[c->trex_count++];
4592 avio_r8(pb); /* version */
4593 avio_rb24(pb); /* flags */
4594 trex->track_id = avio_rb32(pb);
4595 trex->stsd_id = avio_rb32(pb);
4596 trex->duration = avio_rb32(pb);
4597 trex->size = avio_rb32(pb);
4598 trex->flags = avio_rb32(pb);
4602 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4604 MOVFragment *frag = &c->fragment;
4605 AVStream *st = NULL;
4606 MOVStreamContext *sc;
4608 MOVFragmentStreamInfo * frag_stream_info;
4609 int64_t base_media_decode_time;
4611 for (i = 0; i < c->fc->nb_streams; i++) {
4612 if (c->fc->streams[i]->id == frag->track_id) {
4613 st = c->fc->streams[i];
4618 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4619 return AVERROR_INVALIDDATA;
4622 if (sc->pseudo_stream_id + 1 != frag->stsd_id && sc->pseudo_stream_id != -1)
4624 version = avio_r8(pb);
4625 avio_rb24(pb); /* flags */
4627 base_media_decode_time = avio_rb64(pb);
4629 base_media_decode_time = avio_rb32(pb);
4632 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4633 if (frag_stream_info)
4634 frag_stream_info->tfdt_dts = base_media_decode_time;
4635 sc->track_end = base_media_decode_time;
4640 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4642 MOVFragment *frag = &c->fragment;
4643 AVStream *st = NULL;
4644 MOVStreamContext *sc;
4647 int64_t dts, pts = AV_NOPTS_VALUE;
4648 int data_offset = 0;
4649 unsigned entries, first_sample_flags = frag->flags;
4650 int flags, distance, i;
4651 int64_t prev_dts = AV_NOPTS_VALUE;
4652 int next_frag_index = -1, index_entry_pos;
4653 size_t requested_size;
4654 size_t old_ctts_allocated_size;
4655 AVIndexEntry *new_entries;
4656 MOVFragmentStreamInfo * frag_stream_info;
4658 for (i = 0; i < c->fc->nb_streams; i++) {
4659 if (c->fc->streams[i]->id == frag->track_id) {
4660 st = c->fc->streams[i];
4665 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4666 return AVERROR_INVALIDDATA;
4669 if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
4672 // Find the next frag_index index that has a valid index_entry for
4673 // the current track_id.
4675 // A valid index_entry means the trun for the fragment was read
4676 // and it's samples are in index_entries at the given position.
4677 // New index entries will be inserted before the index_entry found.
4678 index_entry_pos = st->nb_index_entries;
4679 for (i = c->frag_index.current + 1; i < c->frag_index.nb_items; i++) {
4680 frag_stream_info = get_frag_stream_info(&c->frag_index, i, frag->track_id);
4681 if (frag_stream_info && frag_stream_info->index_entry >= 0) {
4682 next_frag_index = i;
4683 index_entry_pos = frag_stream_info->index_entry;
4688 avio_r8(pb); /* version */
4689 flags = avio_rb24(pb);
4690 entries = avio_rb32(pb);
4691 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
4693 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
4694 return AVERROR_INVALIDDATA;
4695 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
4696 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
4698 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4699 if (frag_stream_info)
4701 if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE &&
4702 c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
4703 pts = frag_stream_info->first_tfra_pts;
4704 av_log(c->fc, AV_LOG_DEBUG, "found mfra time %"PRId64
4705 ", using it for pts\n", pts);
4706 } else if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE) {
4707 // FIXME: sidx earliest_presentation_time is *PTS*, s.b.
4708 // pts = frag_stream_info->sidx_pts;
4709 dts = frag_stream_info->sidx_pts - sc->time_offset;
4710 av_log(c->fc, AV_LOG_DEBUG, "found sidx time %"PRId64
4711 ", using it for pts\n", pts);
4712 } else if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE) {
4713 dts = frag_stream_info->tfdt_dts - sc->time_offset;
4714 av_log(c->fc, AV_LOG_DEBUG, "found tfdt time %"PRId64
4715 ", using it for dts\n", dts);
4717 dts = sc->track_end - sc->time_offset;
4718 av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4719 ", using it for dts\n", dts);
4722 dts = sc->track_end - sc->time_offset;
4723 av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4724 ", using it for dts\n", dts);
4726 offset = frag->base_data_offset + data_offset;
4728 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
4730 // realloc space for new index entries
4731 if((unsigned)st->nb_index_entries + entries >= UINT_MAX / sizeof(AVIndexEntry)) {
4732 entries = UINT_MAX / sizeof(AVIndexEntry) - st->nb_index_entries;
4733 av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
4738 requested_size = (st->nb_index_entries + entries) * sizeof(AVIndexEntry);
4739 new_entries = av_fast_realloc(st->index_entries,
4740 &st->index_entries_allocated_size,
4743 return AVERROR(ENOMEM);
4744 st->index_entries= new_entries;
4746 requested_size = (st->nb_index_entries + entries) * sizeof(*sc->ctts_data);
4747 old_ctts_allocated_size = sc->ctts_allocated_size;
4748 ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size,
4751 return AVERROR(ENOMEM);
4752 sc->ctts_data = ctts_data;
4754 // In case there were samples without ctts entries, ensure they get
4755 // zero valued entries. This ensures clips which mix boxes with and
4756 // without ctts entries don't pickup uninitialized data.
4757 memset((uint8_t*)(sc->ctts_data) + old_ctts_allocated_size, 0,
4758 sc->ctts_allocated_size - old_ctts_allocated_size);
4760 if (index_entry_pos < st->nb_index_entries) {
4761 // Make hole in index_entries and ctts_data for new samples
4762 memmove(st->index_entries + index_entry_pos + entries,
4763 st->index_entries + index_entry_pos,
4764 sizeof(*st->index_entries) *
4765 (st->nb_index_entries - index_entry_pos));
4766 memmove(sc->ctts_data + index_entry_pos + entries,
4767 sc->ctts_data + index_entry_pos,
4768 sizeof(*sc->ctts_data) * (sc->ctts_count - index_entry_pos));
4769 if (index_entry_pos < sc->current_sample) {
4770 sc->current_sample += entries;
4774 st->nb_index_entries += entries;
4775 sc->ctts_count = st->nb_index_entries;
4777 // Record the index_entry position in frag_index of this fragment
4778 if (frag_stream_info)
4779 frag_stream_info->index_entry = index_entry_pos;
4781 if (index_entry_pos > 0)
4782 prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4784 for (i = 0; i < entries && !pb->eof_reached; i++) {
4785 unsigned sample_size = frag->size;
4786 int sample_flags = i ? frag->flags : first_sample_flags;
4787 unsigned sample_duration = frag->duration;
4788 unsigned ctts_duration = 0;
4790 int index_entry_flags = 0;
4792 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
4793 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
4794 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
4795 if (flags & MOV_TRUN_SAMPLE_CTS) ctts_duration = avio_rb32(pb);
4797 mov_update_dts_shift(sc, ctts_duration);
4798 if (pts != AV_NOPTS_VALUE) {
4799 dts = pts - sc->dts_shift;
4800 if (flags & MOV_TRUN_SAMPLE_CTS) {
4801 dts -= ctts_duration;
4803 dts -= sc->time_offset;
4805 av_log(c->fc, AV_LOG_DEBUG,
4806 "pts %"PRId64" calculated dts %"PRId64
4807 " sc->dts_shift %d ctts.duration %d"
4808 " sc->time_offset %"PRId64
4809 " flags & MOV_TRUN_SAMPLE_CTS %d\n",
4811 sc->dts_shift, ctts_duration,
4812 sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
4813 pts = AV_NOPTS_VALUE;
4816 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4820 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
4821 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
4824 index_entry_flags |= AVINDEX_KEYFRAME;
4826 // Fragments can overlap in time. Discard overlapping frames after
4828 if (prev_dts >= dts)
4829 index_entry_flags |= AVINDEX_DISCARD_FRAME;
4831 st->index_entries[index_entry_pos].pos = offset;
4832 st->index_entries[index_entry_pos].timestamp = dts;
4833 st->index_entries[index_entry_pos].size= sample_size;
4834 st->index_entries[index_entry_pos].min_distance= distance;
4835 st->index_entries[index_entry_pos].flags = index_entry_flags;
4837 sc->ctts_data[index_entry_pos].count = 1;
4838 sc->ctts_data[index_entry_pos].duration = ctts_duration;
4841 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
4842 "size %u, distance %d, keyframe %d\n", st->index,
4843 index_entry_pos, offset, dts, sample_size, distance, keyframe);
4845 dts += sample_duration;
4846 offset += sample_size;
4847 sc->data_size += sample_size;
4849 if (sample_duration <= INT64_MAX - sc->duration_for_fps &&
4850 1 <= INT64_MAX - sc->nb_frames_for_fps
4852 sc->duration_for_fps += sample_duration;
4853 sc->nb_frames_for_fps ++;
4857 // EOF found before reading all entries. Fix the hole this would
4858 // leave in index_entries and ctts_data
4859 int gap = entries - i;
4860 memmove(st->index_entries + index_entry_pos,
4861 st->index_entries + index_entry_pos + gap,
4862 sizeof(*st->index_entries) *
4863 (st->nb_index_entries - (index_entry_pos + gap)));
4864 memmove(sc->ctts_data + index_entry_pos,
4865 sc->ctts_data + index_entry_pos + gap,
4866 sizeof(*sc->ctts_data) *
4867 (sc->ctts_count - (index_entry_pos + gap)));
4869 st->nb_index_entries -= gap;
4870 sc->ctts_count -= gap;
4871 if (index_entry_pos < sc->current_sample) {
4872 sc->current_sample -= gap;
4877 // The end of this new fragment may overlap in time with the start
4878 // of the next fragment in index_entries. Mark the samples in the next
4879 // fragment that overlap with AVINDEX_DISCARD_FRAME
4880 prev_dts = AV_NOPTS_VALUE;
4881 if (index_entry_pos > 0)
4882 prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4883 for (i = index_entry_pos; i < st->nb_index_entries; i++) {
4884 if (prev_dts < st->index_entries[i].timestamp)
4886 st->index_entries[i].flags |= AVINDEX_DISCARD_FRAME;
4889 // If a hole was created to insert the new index_entries into,
4890 // the index_entry recorded for all subsequent moof must
4891 // be incremented by the number of entries inserted.
4892 fix_frag_index_entries(&c->frag_index, next_frag_index,
4893 frag->track_id, entries);
4895 if (pb->eof_reached) {
4896 av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted TRUN atom\n");
4900 frag->implicit_offset = offset;
4902 sc->track_end = dts + sc->time_offset;
4903 if (st->duration < sc->track_end)
4904 st->duration = sc->track_end;
4909 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4911 int64_t offset = avio_tell(pb) + atom.size, pts, timestamp;
4913 unsigned i, j, track_id, item_count;
4914 AVStream *st = NULL;
4915 AVStream *ref_st = NULL;
4916 MOVStreamContext *sc, *ref_sc = NULL;
4917 AVRational timescale;
4919 version = avio_r8(pb);
4921 avpriv_request_sample(c->fc, "sidx version %u", version);
4925 avio_rb24(pb); // flags
4927 track_id = avio_rb32(pb); // Reference ID
4928 for (i = 0; i < c->fc->nb_streams; i++) {
4929 if (c->fc->streams[i]->id == track_id) {
4930 st = c->fc->streams[i];
4935 av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
4941 timescale = av_make_q(1, avio_rb32(pb));
4943 if (timescale.den <= 0) {
4944 av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
4945 return AVERROR_INVALIDDATA;
4949 pts = avio_rb32(pb);
4950 offset += avio_rb32(pb);
4952 pts = avio_rb64(pb);
4953 offset += avio_rb64(pb);
4956 avio_rb16(pb); // reserved
4958 item_count = avio_rb16(pb);
4960 for (i = 0; i < item_count; i++) {
4962 MOVFragmentStreamInfo * frag_stream_info;
4963 uint32_t size = avio_rb32(pb);
4964 uint32_t duration = avio_rb32(pb);
4965 if (size & 0x80000000) {
4966 avpriv_request_sample(c->fc, "sidx reference_type 1");
4967 return AVERROR_PATCHWELCOME;
4969 avio_rb32(pb); // sap_flags
4970 timestamp = av_rescale_q(pts, st->time_base, timescale);
4972 index = update_frag_index(c, offset);
4973 frag_stream_info = get_frag_stream_info(&c->frag_index, index, track_id);
4974 if (frag_stream_info)
4975 frag_stream_info->sidx_pts = timestamp;
4981 st->duration = sc->track_end = pts;
4985 if (offset == avio_size(pb)) {
4986 // Find first entry in fragment index that came from an sidx.
4987 // This will pretty much always be the first entry.
4988 for (i = 0; i < c->frag_index.nb_items; i++) {
4989 MOVFragmentIndexItem * item = &c->frag_index.item[i];
4990 for (j = 0; ref_st == NULL && j < item->nb_stream_info; j++) {
4991 MOVFragmentStreamInfo * si;
4992 si = &item->stream_info[j];
4993 if (si->sidx_pts != AV_NOPTS_VALUE) {
4994 ref_st = c->fc->streams[j];
4995 ref_sc = ref_st->priv_data;
5000 for (i = 0; i < c->fc->nb_streams; i++) {
5001 st = c->fc->streams[i];
5003 if (!sc->has_sidx) {
5004 st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
5008 c->frag_index.complete = 1;
5014 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
5015 /* like the files created with Adobe Premiere 5.0, for samples see */
5016 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
5017 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5022 return 0; /* continue */
5023 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
5024 avio_skip(pb, atom.size - 4);
5027 atom.type = avio_rl32(pb);
5029 if (atom.type != MKTAG('m','d','a','t')) {
5030 avio_skip(pb, atom.size);
5033 err = mov_read_mdat(c, pb, atom);
5037 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5042 uint8_t *moov_data; /* uncompressed data */
5043 long cmov_len, moov_len;
5046 avio_rb32(pb); /* dcom atom */
5047 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
5048 return AVERROR_INVALIDDATA;
5049 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
5050 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
5051 return AVERROR_INVALIDDATA;
5053 avio_rb32(pb); /* cmvd atom */
5054 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
5055 return AVERROR_INVALIDDATA;
5056 moov_len = avio_rb32(pb); /* uncompressed size */
5057 cmov_len = atom.size - 6 * 4;
5059 cmov_data = av_malloc(cmov_len);
5061 return AVERROR(ENOMEM);
5062 moov_data = av_malloc(moov_len);
5065 return AVERROR(ENOMEM);
5067 ret = ffio_read_size(pb, cmov_data, cmov_len);
5069 goto free_and_return;
5071 ret = AVERROR_INVALIDDATA;
5072 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
5073 goto free_and_return;
5074 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
5075 goto free_and_return;
5076 ctx.seekable = AVIO_SEEKABLE_NORMAL;
5077 atom.type = MKTAG('m','o','o','v');
5078 atom.size = moov_len;
5079 ret = mov_read_default(c, &ctx, atom);
5085 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
5086 return AVERROR(ENOSYS);
5090 /* edit list atom */
5091 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5093 MOVStreamContext *sc;
5094 int i, edit_count, version;
5095 int64_t elst_entry_size;
5097 if (c->fc->nb_streams < 1 || c->ignore_editlist)
5099 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
5101 version = avio_r8(pb); /* version */
5102 avio_rb24(pb); /* flags */
5103 edit_count = avio_rb32(pb); /* entries */
5106 elst_entry_size = version == 1 ? 20 : 12;
5107 if (atom.size != edit_count * elst_entry_size) {
5108 if (c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
5109 av_log(c->fc, AV_LOG_ERROR, "Invalid edit list entry_count: %d for elst atom of size: %"PRId64" bytes.\n",
5110 edit_count, atom.size + 8);
5111 return AVERROR_INVALIDDATA;
5113 edit_count = atom.size / elst_entry_size;
5114 if (edit_count * elst_entry_size != atom.size) {
5115 av_log(c->fc, AV_LOG_WARNING, "ELST atom of %"PRId64" bytes, bigger than %d entries.", atom.size, edit_count);
5123 av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
5124 av_free(sc->elst_data);
5126 sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
5128 return AVERROR(ENOMEM);
5130 av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
5131 for (i = 0; i < edit_count && atom.size > 0 && !pb->eof_reached; i++) {
5132 MOVElst *e = &sc->elst_data[i];
5135 e->duration = avio_rb64(pb);
5136 e->time = avio_rb64(pb);
5139 e->duration = avio_rb32(pb); /* segment duration */
5140 e->time = (int32_t)avio_rb32(pb); /* media time */
5143 e->rate = avio_rb32(pb) / 65536.0;
5145 av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
5146 e->duration, e->time, e->rate);
5148 if (e->time < 0 && e->time != -1 &&
5149 c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
5150 av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
5151 c->fc->nb_streams-1, i, e->time);
5152 return AVERROR_INVALIDDATA;
5160 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5162 MOVStreamContext *sc;
5164 if (c->fc->nb_streams < 1)
5165 return AVERROR_INVALIDDATA;
5166 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5167 sc->timecode_track = avio_rb32(pb);
5171 static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5174 int version, color_range, color_primaries, color_trc, color_space;
5176 if (c->fc->nb_streams < 1)
5178 st = c->fc->streams[c->fc->nb_streams - 1];
5180 if (atom.size < 5) {
5181 av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
5182 return AVERROR_INVALIDDATA;
5185 version = avio_r8(pb);
5187 av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
5190 avio_skip(pb, 3); /* flags */
5192 avio_skip(pb, 2); /* profile + level */
5193 color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
5194 color_primaries = avio_r8(pb);
5195 color_trc = avio_r8(pb);
5196 color_space = avio_r8(pb);
5197 if (avio_rb16(pb)) /* codecIntializationDataSize */
5198 return AVERROR_INVALIDDATA;
5200 if (!av_color_primaries_name(color_primaries))
5201 color_primaries = AVCOL_PRI_UNSPECIFIED;
5202 if (!av_color_transfer_name(color_trc))
5203 color_trc = AVCOL_TRC_UNSPECIFIED;
5204 if (!av_color_space_name(color_space))
5205 color_space = AVCOL_SPC_UNSPECIFIED;
5207 st->codecpar->color_range = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
5208 st->codecpar->color_primaries = color_primaries;
5209 st->codecpar->color_trc = color_trc;
5210 st->codecpar->color_space = color_space;
5215 static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5217 MOVStreamContext *sc;
5218 const int chroma_den = 50000;
5219 const int luma_den = 10000;
5222 if (c->fc->nb_streams < 1)
5223 return AVERROR_INVALIDDATA;
5225 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5227 if (atom.size < 5) {
5228 av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
5229 return AVERROR_INVALIDDATA;
5232 version = avio_r8(pb);
5234 av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
5237 avio_skip(pb, 3); /* flags */
5239 sc->mastering = av_mastering_display_metadata_alloc();
5241 return AVERROR(ENOMEM);
5243 for (i = 0; i < 3; i++)
5244 for (j = 0; j < 2; j++)
5245 sc->mastering->display_primaries[i][j] =
5246 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5247 for (i = 0; i < 2; i++)
5248 sc->mastering->white_point[i] =
5249 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5250 sc->mastering->max_luminance =
5251 av_make_q(lrint(((double)avio_rb32(pb) / (1 << 8)) * luma_den), luma_den);
5252 sc->mastering->min_luminance =
5253 av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den);
5255 sc->mastering->has_primaries = 1;
5256 sc->mastering->has_luminance = 1;
5261 static int mov_read_mdcv(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5263 MOVStreamContext *sc;
5264 const int mapping[3] = {1, 2, 0};
5265 const int chroma_den = 50000;
5266 const int luma_den = 10000;
5269 if (c->fc->nb_streams < 1)
5270 return AVERROR_INVALIDDATA;
5272 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5274 if (atom.size < 24) {
5275 av_log(c->fc, AV_LOG_ERROR, "Invalid Mastering Display Color Volume box\n");
5276 return AVERROR_INVALIDDATA;
5279 sc->mastering = av_mastering_display_metadata_alloc();
5281 return AVERROR(ENOMEM);
5283 for (i = 0; i < 3; i++) {
5284 const int j = mapping[i];
5285 sc->mastering->display_primaries[j][0] = av_make_q(avio_rb16(pb), chroma_den);
5286 sc->mastering->display_primaries[j][1] = av_make_q(avio_rb16(pb), chroma_den);
5288 sc->mastering->white_point[0] = av_make_q(avio_rb16(pb), chroma_den);
5289 sc->mastering->white_point[1] = av_make_q(avio_rb16(pb), chroma_den);
5291 sc->mastering->max_luminance = av_make_q(avio_rb32(pb), luma_den);
5292 sc->mastering->min_luminance = av_make_q(avio_rb32(pb), luma_den);
5294 sc->mastering->has_luminance = 1;
5295 sc->mastering->has_primaries = 1;
5300 static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5302 MOVStreamContext *sc;
5305 if (c->fc->nb_streams < 1)
5306 return AVERROR_INVALIDDATA;
5308 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5310 if (atom.size < 5) {
5311 av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
5312 return AVERROR_INVALIDDATA;
5315 version = avio_r8(pb);
5317 av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
5320 avio_skip(pb, 3); /* flags */
5322 sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
5324 return AVERROR(ENOMEM);
5326 sc->coll->MaxCLL = avio_rb16(pb);
5327 sc->coll->MaxFALL = avio_rb16(pb);
5332 static int mov_read_clli(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5334 MOVStreamContext *sc;
5336 if (c->fc->nb_streams < 1)
5337 return AVERROR_INVALIDDATA;
5339 sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5341 if (atom.size < 4) {
5342 av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level Info box\n");
5343 return AVERROR_INVALIDDATA;
5346 sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
5348 return AVERROR(ENOMEM);
5350 sc->coll->MaxCLL = avio_rb16(pb);
5351 sc->coll->MaxFALL = avio_rb16(pb);
5356 static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5359 MOVStreamContext *sc;
5360 enum AVStereo3DType type;
5363 if (c->fc->nb_streams < 1)
5366 st = c->fc->streams[c->fc->nb_streams - 1];
5369 if (atom.size < 5) {
5370 av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
5371 return AVERROR_INVALIDDATA;
5373 avio_skip(pb, 4); /* version + flags */
5378 type = AV_STEREO3D_2D;
5381 type = AV_STEREO3D_TOPBOTTOM;
5384 type = AV_STEREO3D_SIDEBYSIDE;
5387 av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
5391 sc->stereo3d = av_stereo3d_alloc();
5393 return AVERROR(ENOMEM);
5395 sc->stereo3d->type = type;
5399 static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5402 MOVStreamContext *sc;
5403 int size, version, layout;
5404 int32_t yaw, pitch, roll;
5405 uint32_t l = 0, t = 0, r = 0, b = 0;
5406 uint32_t tag, padding = 0;
5407 enum AVSphericalProjection projection;
5409 if (c->fc->nb_streams < 1)
5412 st = c->fc->streams[c->fc->nb_streams - 1];
5415 if (atom.size < 8) {
5416 av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
5417 return AVERROR_INVALIDDATA;
5420 size = avio_rb32(pb);
5421 if (size <= 12 || size > atom.size)
5422 return AVERROR_INVALIDDATA;
5424 tag = avio_rl32(pb);
5425 if (tag != MKTAG('s','v','h','d')) {
5426 av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
5429 version = avio_r8(pb);
5431 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5435 avio_skip(pb, 3); /* flags */
5436 avio_skip(pb, size - 12); /* metadata_source */
5438 size = avio_rb32(pb);
5439 if (size > atom.size)
5440 return AVERROR_INVALIDDATA;
5442 tag = avio_rl32(pb);
5443 if (tag != MKTAG('p','r','o','j')) {
5444 av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
5448 size = avio_rb32(pb);
5449 if (size > atom.size)
5450 return AVERROR_INVALIDDATA;
5452 tag = avio_rl32(pb);
5453 if (tag != MKTAG('p','r','h','d')) {
5454 av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
5457 version = avio_r8(pb);
5459 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5463 avio_skip(pb, 3); /* flags */
5465 /* 16.16 fixed point */
5466 yaw = avio_rb32(pb);
5467 pitch = avio_rb32(pb);
5468 roll = avio_rb32(pb);
5470 size = avio_rb32(pb);
5471 if (size > atom.size)
5472 return AVERROR_INVALIDDATA;
5474 tag = avio_rl32(pb);
5475 version = avio_r8(pb);
5477 av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5481 avio_skip(pb, 3); /* flags */
5483 case MKTAG('c','b','m','p'):
5484 layout = avio_rb32(pb);
5486 av_log(c->fc, AV_LOG_WARNING,
5487 "Unsupported cubemap layout %d\n", layout);
5490 projection = AV_SPHERICAL_CUBEMAP;
5491 padding = avio_rb32(pb);
5493 case MKTAG('e','q','u','i'):
5499 if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
5500 av_log(c->fc, AV_LOG_ERROR,
5501 "Invalid bounding rectangle coordinates "
5502 "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
5503 return AVERROR_INVALIDDATA;
5506 if (l || t || r || b)
5507 projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
5509 projection = AV_SPHERICAL_EQUIRECTANGULAR;
5512 av_log(c->fc, AV_LOG_ERROR, "Unknown projection type: %s\n", av_fourcc2str(tag));
5516 sc->spherical = av_spherical_alloc(&sc->spherical_size);
5518 return AVERROR(ENOMEM);
5520 sc->spherical->projection = projection;
5522 sc->spherical->yaw = yaw;
5523 sc->spherical->pitch = pitch;
5524 sc->spherical->roll = roll;
5526 sc->spherical->padding = padding;
5528 sc->spherical->bound_left = l;
5529 sc->spherical->bound_top = t;
5530 sc->spherical->bound_right = r;
5531 sc->spherical->bound_bottom = b;
5536 static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
5539 uint8_t *buffer = av_malloc(len + 1);
5543 return AVERROR(ENOMEM);
5546 ret = ffio_read_size(pb, buffer, len);
5550 /* Check for mandatory keys and values, try to support XML as best-effort */
5551 if (!sc->spherical &&
5552 av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
5553 (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
5554 av_stristr(val, "true") &&
5555 (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
5556 av_stristr(val, "true") &&
5557 (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
5558 av_stristr(val, "equirectangular")) {
5559 sc->spherical = av_spherical_alloc(&sc->spherical_size);
5563 sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
5565 if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
5566 enum AVStereo3DType mode;
5568 if (av_stristr(buffer, "left-right"))
5569 mode = AV_STEREO3D_SIDEBYSIDE;
5570 else if (av_stristr(buffer, "top-bottom"))
5571 mode = AV_STEREO3D_TOPBOTTOM;
5573 mode = AV_STEREO3D_2D;
5575 sc->stereo3d = av_stereo3d_alloc();
5579 sc->stereo3d->type = mode;
5583 val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
5585 sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
5586 val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
5588 sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
5589 val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
5591 sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
5599 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5602 MOVStreamContext *sc;
5605 static const uint8_t uuid_isml_manifest[] = {
5606 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
5607 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
5609 static const uint8_t uuid_xmp[] = {
5610 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
5611 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
5613 static const uint8_t uuid_spherical[] = {
5614 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
5615 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
5618 if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
5619 return AVERROR_INVALIDDATA;
5621 if (c->fc->nb_streams < 1)
5623 st = c->fc->streams[c->fc->nb_streams - 1];
5626 ret = avio_read(pb, uuid, sizeof(uuid));
5629 } else if (ret != sizeof(uuid)) {
5630 return AVERROR_INVALIDDATA;
5632 if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
5633 uint8_t *buffer, *ptr;
5635 size_t len = atom.size - sizeof(uuid);
5638 return AVERROR_INVALIDDATA;
5640 ret = avio_skip(pb, 4); // zeroes
5643 buffer = av_mallocz(len + 1);
5645 return AVERROR(ENOMEM);
5647 ret = avio_read(pb, buffer, len);
5651 } else if (ret != len) {
5653 return AVERROR_INVALIDDATA;
5657 while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
5658 ptr += sizeof("systemBitrate=\"") - 1;
5659 c->bitrates_count++;
5660 c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
5662 c->bitrates_count = 0;
5664 return AVERROR(ENOMEM);
5667 ret = strtol(ptr, &endptr, 10);
5668 if (ret < 0 || errno || *endptr != '"') {
5669 c->bitrates[c->bitrates_count - 1] = 0;
5671 c->bitrates[c->bitrates_count - 1] = ret;
5676 } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
5678 size_t len = atom.size - sizeof(uuid);
5679 if (c->export_xmp) {
5680 buffer = av_mallocz(len + 1);
5682 return AVERROR(ENOMEM);
5684 ret = avio_read(pb, buffer, len);
5688 } else if (ret != len) {
5690 return AVERROR_INVALIDDATA;
5693 av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
5696 // skip all uuid atom, which makes it fast for long uuid-xmp file
5697 ret = avio_skip(pb, len);
5701 } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
5702 size_t len = atom.size - sizeof(uuid);
5703 ret = mov_parse_uuid_spherical(sc, pb, len);
5707 av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
5713 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5716 uint8_t content[16];
5721 ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
5727 && !memcmp(content, "Anevia\x1A\x1A", 8)
5728 && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
5729 c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
5735 static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5737 uint32_t format = avio_rl32(pb);
5738 MOVStreamContext *sc;
5742 if (c->fc->nb_streams < 1)
5744 st = c->fc->streams[c->fc->nb_streams - 1];
5749 case MKTAG('e','n','c','v'): // encrypted video
5750 case MKTAG('e','n','c','a'): // encrypted audio
5751 id = mov_codec_id(st, format);
5752 if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
5753 st->codecpar->codec_id != id) {
5754 av_log(c->fc, AV_LOG_WARNING,
5755 "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
5756 (char*)&format, st->codecpar->codec_id);
5760 st->codecpar->codec_id = id;
5761 sc->format = format;
5765 if (format != sc->format) {
5766 av_log(c->fc, AV_LOG_WARNING,
5767 "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
5768 (char*)&format, (char*)&sc->format);
5777 * Gets the current encryption info and associated current stream context. If
5778 * we are parsing a track fragment, this will return the specific encryption
5779 * info for this fragment; otherwise this will return the global encryption
5780 * info for the current stream.
5782 static int get_current_encryption_info(MOVContext *c, MOVEncryptionIndex **encryption_index, MOVStreamContext **sc)
5784 MOVFragmentStreamInfo *frag_stream_info;
5788 frag_stream_info = get_current_frag_stream_info(&c->frag_index);
5789 if (frag_stream_info) {
5790 for (i = 0; i < c->fc->nb_streams; i++) {
5791 if (c->fc->streams[i]->id == frag_stream_info->id) {
5792 st = c->fc->streams[i];
5796 if (i == c->fc->nb_streams)
5798 *sc = st->priv_data;
5800 if (!frag_stream_info->encryption_index) {
5801 frag_stream_info->encryption_index = av_mallocz(sizeof(*frag_stream_info->encryption_index));
5802 if (!frag_stream_info->encryption_index)
5803 return AVERROR(ENOMEM);
5805 *encryption_index = frag_stream_info->encryption_index;
5808 // No current track fragment, using stream level encryption info.
5810 if (c->fc->nb_streams < 1)
5812 st = c->fc->streams[c->fc->nb_streams - 1];
5813 *sc = st->priv_data;
5815 if (!(*sc)->cenc.encryption_index) {
5816 (*sc)->cenc.encryption_index = av_mallocz(sizeof(*frag_stream_info->encryption_index));
5817 if (!(*sc)->cenc.encryption_index)
5818 return AVERROR(ENOMEM);
5821 *encryption_index = (*sc)->cenc.encryption_index;
5826 static int mov_read_sample_encryption_info(MOVContext *c, AVIOContext *pb, MOVStreamContext *sc, AVEncryptionInfo **sample, int use_subsamples)
5829 unsigned int subsample_count;
5830 AVSubsampleEncryptionInfo *subsamples;
5832 *sample = av_encryption_info_clone(sc->cenc.default_encrypted_sample);
5834 return AVERROR(ENOMEM);
5836 if (sc->cenc.per_sample_iv_size != 0) {
5837 if (avio_read(pb, (*sample)->iv, sc->cenc.per_sample_iv_size) != sc->cenc.per_sample_iv_size) {
5838 av_log(c->fc, AV_LOG_ERROR, "failed to read the initialization vector\n");
5839 av_encryption_info_free(*sample);
5841 return AVERROR_INVALIDDATA;
5845 if (use_subsamples) {
5846 subsample_count = avio_rb16(pb);
5847 av_free((*sample)->subsamples);
5848 (*sample)->subsamples = av_mallocz_array(subsample_count, sizeof(*subsamples));
5849 if (!(*sample)->subsamples) {
5850 av_encryption_info_free(*sample);
5852 return AVERROR(ENOMEM);
5855 for (i = 0; i < subsample_count && !pb->eof_reached; i++) {
5856 (*sample)->subsamples[i].bytes_of_clear_data = avio_rb16(pb);
5857 (*sample)->subsamples[i].bytes_of_protected_data = avio_rb32(pb);
5860 if (pb->eof_reached) {
5861 av_log(c->fc, AV_LOG_ERROR, "hit EOF while reading sub-sample encryption info\n");
5862 av_encryption_info_free(*sample);
5864 return AVERROR_INVALIDDATA;
5866 (*sample)->subsample_count = subsample_count;
5872 static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5874 AVEncryptionInfo **encrypted_samples;
5875 MOVEncryptionIndex *encryption_index;
5876 MOVStreamContext *sc;
5877 int use_subsamples, ret;
5878 unsigned int sample_count, i, alloc_size = 0;
5880 ret = get_current_encryption_info(c, &encryption_index, &sc);
5884 if (encryption_index->nb_encrypted_samples) {
5885 // This can happen if we have both saio/saiz and senc atoms.
5886 av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in senc\n");
5890 avio_r8(pb); /* version */
5891 use_subsamples = avio_rb24(pb) & 0x02; /* flags */
5893 sample_count = avio_rb32(pb);
5894 if (sample_count >= INT_MAX / sizeof(*encrypted_samples))
5895 return AVERROR(ENOMEM);
5897 for (i = 0; i < sample_count; i++) {
5898 unsigned int min_samples = FFMIN(FFMAX(i + 1, 1024 * 1024), sample_count);
5899 encrypted_samples = av_fast_realloc(encryption_index->encrypted_samples, &alloc_size,
5900 min_samples * sizeof(*encrypted_samples));
5901 if (encrypted_samples) {
5902 encryption_index->encrypted_samples = encrypted_samples;
5904 ret = mov_read_sample_encryption_info(
5905 c, pb, sc, &encryption_index->encrypted_samples[i], use_subsamples);
5907 ret = AVERROR(ENOMEM);
5909 if (pb->eof_reached) {
5910 av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading senc\n");
5911 ret = AVERROR_INVALIDDATA;
5916 av_encryption_info_free(encryption_index->encrypted_samples[i - 1]);
5917 av_freep(&encryption_index->encrypted_samples);
5921 encryption_index->nb_encrypted_samples = sample_count;
5926 static int mov_parse_auxiliary_info(MOVContext *c, MOVStreamContext *sc, AVIOContext *pb, MOVEncryptionIndex *encryption_index)
5928 AVEncryptionInfo **sample, **encrypted_samples;
5930 size_t sample_count, sample_info_size, i;
5932 unsigned int alloc_size = 0;
5934 if (encryption_index->nb_encrypted_samples)
5936 sample_count = encryption_index->auxiliary_info_sample_count;
5937 if (encryption_index->auxiliary_offsets_count != 1) {
5938 av_log(c->fc, AV_LOG_ERROR, "Multiple auxiliary info chunks are not supported\n");
5939 return AVERROR_PATCHWELCOME;
5941 if (sample_count >= INT_MAX / sizeof(*encrypted_samples))
5942 return AVERROR(ENOMEM);
5944 prev_pos = avio_tell(pb);
5945 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) ||
5946 avio_seek(pb, encryption_index->auxiliary_offsets[0], SEEK_SET) != encryption_index->auxiliary_offsets[0]) {
5947 av_log(c->fc, AV_LOG_INFO, "Failed to seek for auxiliary info, will only parse senc atoms for encryption info\n");
5951 for (i = 0; i < sample_count && !pb->eof_reached; i++) {
5952 unsigned int min_samples = FFMIN(FFMAX(i + 1, 1024 * 1024), sample_count);
5953 encrypted_samples = av_fast_realloc(encryption_index->encrypted_samples, &alloc_size,
5954 min_samples * sizeof(*encrypted_samples));
5955 if (!encrypted_samples) {
5956 ret = AVERROR(ENOMEM);
5959 encryption_index->encrypted_samples = encrypted_samples;
5961 sample = &encryption_index->encrypted_samples[i];
5962 sample_info_size = encryption_index->auxiliary_info_default_size
5963 ? encryption_index->auxiliary_info_default_size
5964 : encryption_index->auxiliary_info_sizes[i];
5966 ret = mov_read_sample_encryption_info(c, pb, sc, sample, sample_info_size > sc->cenc.per_sample_iv_size);
5970 if (pb->eof_reached) {
5971 av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading auxiliary info\n");
5972 ret = AVERROR_INVALIDDATA;
5974 encryption_index->nb_encrypted_samples = sample_count;
5978 avio_seek(pb, prev_pos, SEEK_SET);
5980 for (; i > 0; i--) {
5981 av_encryption_info_free(encryption_index->encrypted_samples[i - 1]);
5983 av_freep(&encryption_index->encrypted_samples);
5989 * Tries to read the given number of bytes from the stream and puts it in a
5990 * newly allocated buffer. This reads in small chunks to avoid allocating large
5991 * memory if the file contains an invalid/malicious size value.
5993 static int mov_try_read_block(AVIOContext *pb, size_t size, uint8_t **data)
5995 const unsigned int block_size = 1024 * 1024;
5996 uint8_t *buffer = NULL;
5997 unsigned int alloc_size = 0, offset = 0;
5998 while (offset < size) {
5999 unsigned int new_size =
6000 alloc_size >= INT_MAX - block_size ? INT_MAX : alloc_size + block_size;
6001 uint8_t *new_buffer = av_fast_realloc(buffer, &alloc_size, new_size);
6002 unsigned int to_read = FFMIN(size, alloc_size) - offset;
6005 return AVERROR(ENOMEM);
6007 buffer = new_buffer;
6009 if (avio_read(pb, buffer + offset, to_read) != to_read) {
6011 return AVERROR_INVALIDDATA;
6020 static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6022 MOVEncryptionIndex *encryption_index;
6023 MOVStreamContext *sc;
6025 unsigned int sample_count;
6027 ret = get_current_encryption_info(c, &encryption_index, &sc);
6031 if (encryption_index->nb_encrypted_samples) {
6032 // This can happen if we have both saio/saiz and senc atoms.
6033 av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in saiz\n");
6037 if (encryption_index->auxiliary_info_sample_count) {
6038 av_log(c->fc, AV_LOG_ERROR, "Duplicate saiz atom\n");
6039 return AVERROR_INVALIDDATA;
6042 avio_r8(pb); /* version */
6043 if (avio_rb24(pb) & 0x01) { /* flags */
6044 if (avio_rb32(pb) != sc->cenc.default_encrypted_sample->scheme) {
6045 av_log(c->fc, AV_LOG_DEBUG, "Ignoring saiz box with non-zero aux_info_type\n");
6048 if (avio_rb32(pb) != 0) {
6049 av_log(c->fc, AV_LOG_DEBUG, "Ignoring saiz box with non-zero aux_info_type_parameter\n");
6054 encryption_index->auxiliary_info_default_size = avio_r8(pb);
6055 sample_count = avio_rb32(pb);
6056 encryption_index->auxiliary_info_sample_count = sample_count;
6058 if (encryption_index->auxiliary_info_default_size == 0) {
6059 ret = mov_try_read_block(pb, sample_count, &encryption_index->auxiliary_info_sizes);
6061 av_log(c->fc, AV_LOG_ERROR, "Failed to read the auxiliary info\n");
6066 if (encryption_index->auxiliary_offsets_count) {
6067 return mov_parse_auxiliary_info(c, sc, pb, encryption_index);
6073 static int mov_read_saio(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6075 uint64_t *auxiliary_offsets;
6076 MOVEncryptionIndex *encryption_index;
6077 MOVStreamContext *sc;
6079 unsigned int version, entry_count, alloc_size = 0;
6081 ret = get_current_encryption_info(c, &encryption_index, &sc);
6085 if (encryption_index->nb_encrypted_samples) {
6086 // This can happen if we have both saio/saiz and senc atoms.
6087 av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in saio\n");
6091 if (encryption_index->auxiliary_offsets_count) {
6092 av_log(c->fc, AV_LOG_ERROR, "Duplicate saio atom\n");
6093 return AVERROR_INVALIDDATA;
6096 version = avio_r8(pb); /* version */
6097 if (avio_rb24(pb) & 0x01) { /* flags */
6098 if (avio_rb32(pb) != sc->cenc.default_encrypted_sample->scheme) {
6099 av_log(c->fc, AV_LOG_DEBUG, "Ignoring saio box with non-zero aux_info_type\n");
6102 if (avio_rb32(pb) != 0) {
6103 av_log(c->fc, AV_LOG_DEBUG, "Ignoring saio box with non-zero aux_info_type_parameter\n");
6108 entry_count = avio_rb32(pb);
6109 if (entry_count >= INT_MAX / sizeof(*auxiliary_offsets))
6110 return AVERROR(ENOMEM);
6112 for (i = 0; i < entry_count && !pb->eof_reached; i++) {
6113 unsigned int min_offsets = FFMIN(FFMAX(i + 1, 1024), entry_count);
6114 auxiliary_offsets = av_fast_realloc(
6115 encryption_index->auxiliary_offsets, &alloc_size,
6116 min_offsets * sizeof(*auxiliary_offsets));
6117 if (!auxiliary_offsets) {
6118 av_freep(&encryption_index->auxiliary_offsets);
6119 return AVERROR(ENOMEM);
6121 encryption_index->auxiliary_offsets = auxiliary_offsets;
6124 encryption_index->auxiliary_offsets[i] = avio_rb32(pb);
6126 encryption_index->auxiliary_offsets[i] = avio_rb64(pb);
6128 if (c->frag_index.current >= 0) {
6129 encryption_index->auxiliary_offsets[i] += c->fragment.base_data_offset;
6133 if (pb->eof_reached) {
6134 av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading saio\n");
6135 av_freep(&encryption_index->auxiliary_offsets);
6136 return AVERROR_INVALIDDATA;
6139 encryption_index->auxiliary_offsets_count = entry_count;
6141 if (encryption_index->auxiliary_info_sample_count) {
6142 return mov_parse_auxiliary_info(c, sc, pb, encryption_index);
6148 static int mov_read_schm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6151 MOVStreamContext *sc;
6153 if (c->fc->nb_streams < 1)
6155 st = c->fc->streams[c->fc->nb_streams-1];
6158 if (sc->pseudo_stream_id != 0) {
6159 av_log(c->fc, AV_LOG_ERROR, "schm boxes are only supported in first sample descriptor\n");
6160 return AVERROR_PATCHWELCOME;
6164 return AVERROR_INVALIDDATA;
6166 avio_rb32(pb); /* version and flags */
6168 if (!sc->cenc.default_encrypted_sample) {
6169 sc->cenc.default_encrypted_sample = av_encryption_info_alloc(0, 16, 16);
6170 if (!sc->cenc.default_encrypted_sample) {
6171 return AVERROR(ENOMEM);
6175 sc->cenc.default_encrypted_sample->scheme = avio_rb32(pb);
6179 static int mov_read_tenc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6182 MOVStreamContext *sc;
6183 unsigned int version, pattern, is_protected, iv_size;
6185 if (c->fc->nb_streams < 1)
6187 st = c->fc->streams[c->fc->nb_streams-1];
6190 if (sc->pseudo_stream_id != 0) {
6191 av_log(c->fc, AV_LOG_ERROR, "tenc atom are only supported in first sample descriptor\n");
6192 return AVERROR_PATCHWELCOME;
6195 if (!sc->cenc.default_encrypted_sample) {
6196 sc->cenc.default_encrypted_sample = av_encryption_info_alloc(0, 16, 16);
6197 if (!sc->cenc.default_encrypted_sample) {
6198 return AVERROR(ENOMEM);
6203 return AVERROR_INVALIDDATA;
6205 version = avio_r8(pb); /* version */
6206 avio_rb24(pb); /* flags */
6208 avio_r8(pb); /* reserved */
6209 pattern = avio_r8(pb);
6212 sc->cenc.default_encrypted_sample->crypt_byte_block = pattern >> 4;
6213 sc->cenc.default_encrypted_sample->skip_byte_block = pattern & 0xf;
6216 is_protected = avio_r8(pb);
6217 if (is_protected && !sc->cenc.encryption_index) {
6218 // The whole stream should be by-default encrypted.
6219 sc->cenc.encryption_index = av_mallocz(sizeof(MOVEncryptionIndex));
6220 if (!sc->cenc.encryption_index)
6221 return AVERROR(ENOMEM);
6223 sc->cenc.per_sample_iv_size = avio_r8(pb);
6224 if (avio_read(pb, sc->cenc.default_encrypted_sample->key_id, 16) != 16) {
6225 av_log(c->fc, AV_LOG_ERROR, "failed to read the default key ID");
6226 return AVERROR_INVALIDDATA;
6229 if (is_protected && !sc->cenc.per_sample_iv_size) {
6230 iv_size = avio_r8(pb);
6231 if (iv_size != 8 && iv_size != 16) {
6232 av_log(c->fc, AV_LOG_ERROR, "invalid default_constant_IV_size in tenc atom\n");
6233 return AVERROR_INVALIDDATA;
6236 if (avio_read(pb, sc->cenc.default_encrypted_sample->iv, iv_size) != iv_size) {
6237 av_log(c->fc, AV_LOG_ERROR, "failed to read the default IV");
6238 return AVERROR_INVALIDDATA;
6245 static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6248 int last, type, size, ret;
6251 if (c->fc->nb_streams < 1)
6253 st = c->fc->streams[c->fc->nb_streams-1];
6255 if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
6256 return AVERROR_INVALIDDATA;
6258 /* Check FlacSpecificBox version. */
6259 if (avio_r8(pb) != 0)
6260 return AVERROR_INVALIDDATA;
6262 avio_rb24(pb); /* Flags */
6264 avio_read(pb, buf, sizeof(buf));
6265 flac_parse_block_header(buf, &last, &type, &size);
6267 if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
6268 av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
6269 return AVERROR_INVALIDDATA;
6272 ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
6277 av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
6282 static int cenc_decrypt(MOVContext *c, MOVStreamContext *sc, AVEncryptionInfo *sample, uint8_t *input, int size)
6286 if (sample->scheme != MKBETAG('c','e','n','c') || sample->crypt_byte_block != 0 || sample->skip_byte_block != 0) {
6287 av_log(c->fc, AV_LOG_ERROR, "Only the 'cenc' encryption scheme is supported\n");
6288 return AVERROR_PATCHWELCOME;
6291 if (!sc->cenc.aes_ctr) {
6292 /* initialize the cipher */
6293 sc->cenc.aes_ctr = av_aes_ctr_alloc();
6294 if (!sc->cenc.aes_ctr) {
6295 return AVERROR(ENOMEM);
6298 ret = av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
6304 av_aes_ctr_set_full_iv(sc->cenc.aes_ctr, sample->iv);
6306 if (!sample->subsample_count)
6308 /* decrypt the whole packet */
6309 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
6313 for (i = 0; i < sample->subsample_count; i++)
6315 if (sample->subsamples[i].bytes_of_clear_data + sample->subsamples[i].bytes_of_protected_data > size) {
6316 av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
6317 return AVERROR_INVALIDDATA;
6320 /* skip the clear bytes */
6321 input += sample->subsamples[i].bytes_of_clear_data;
6322 size -= sample->subsamples[i].bytes_of_clear_data;
6324 /* decrypt the encrypted bytes */
6325 av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, sample->subsamples[i].bytes_of_protected_data);
6326 input += sample->subsamples[i].bytes_of_protected_data;
6327 size -= sample->subsamples[i].bytes_of_protected_data;
6331 av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
6332 return AVERROR_INVALIDDATA;
6338 static int cenc_filter(MOVContext *mov, MOVStreamContext *sc, AVPacket *pkt, int current_index)
6340 MOVFragmentStreamInfo *frag_stream_info;
6341 MOVEncryptionIndex *encryption_index;
6342 AVEncryptionInfo *encrypted_sample;
6343 int encrypted_index;
6345 frag_stream_info = get_current_frag_stream_info(&mov->frag_index);
6346 encrypted_index = current_index;
6347 encryption_index = NULL;
6348 if (frag_stream_info) {
6349 // Note this only supports encryption info in the first sample descriptor.
6350 if (mov->fragment.stsd_id == 1) {
6351 if (frag_stream_info->encryption_index) {
6352 encrypted_index = current_index - frag_stream_info->index_entry;
6353 encryption_index = frag_stream_info->encryption_index;
6355 encryption_index = sc->cenc.encryption_index;
6359 encryption_index = sc->cenc.encryption_index;
6362 if (encryption_index) {
6363 if (encryption_index->auxiliary_info_sample_count &&
6364 !encryption_index->nb_encrypted_samples) {
6365 av_log(mov->fc, AV_LOG_ERROR, "saiz atom found without saio\n");
6366 return AVERROR_INVALIDDATA;
6368 if (encryption_index->auxiliary_offsets_count &&
6369 !encryption_index->nb_encrypted_samples) {
6370 av_log(mov->fc, AV_LOG_ERROR, "saio atom found without saiz\n");
6371 return AVERROR_INVALIDDATA;
6374 if (!encryption_index->nb_encrypted_samples) {
6375 // Full-sample encryption with default settings.
6376 encrypted_sample = sc->cenc.default_encrypted_sample;
6377 } else if (encrypted_index >= 0 && encrypted_index < encryption_index->nb_encrypted_samples) {
6378 // Per-sample setting override.
6379 encrypted_sample = encryption_index->encrypted_samples[encrypted_index];
6381 av_log(mov->fc, AV_LOG_ERROR, "Incorrect number of samples in encryption info\n");
6382 return AVERROR_INVALIDDATA;
6385 if (mov->decryption_key) {
6386 return cenc_decrypt(mov, sc, encrypted_sample, pkt->data, pkt->size);
6393 static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6395 const int OPUS_SEEK_PREROLL_MS = 80;
6400 if (c->fc->nb_streams < 1)
6402 st = c->fc->streams[c->fc->nb_streams-1];
6404 if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
6405 return AVERROR_INVALIDDATA;
6407 /* Check OpusSpecificBox version. */
6408 if (avio_r8(pb) != 0) {
6409 av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
6410 return AVERROR_INVALIDDATA;
6413 /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
6414 size = atom.size + 8;
6416 if (ff_alloc_extradata(st->codecpar, size))
6417 return AVERROR(ENOMEM);
6419 AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
6420 AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
6421 AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
6422 avio_read(pb, st->codecpar->extradata + 9, size - 9);
6424 /* OpusSpecificBox is stored in big-endian, but OpusHead is
6425 little-endian; aside from the preceeding magic and version they're
6426 otherwise currently identical. Data after output gain at offset 16
6427 doesn't need to be bytewapped. */
6428 pre_skip = AV_RB16(st->codecpar->extradata + 10);
6429 AV_WL16(st->codecpar->extradata + 10, pre_skip);
6430 AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
6431 AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
6433 st->codecpar->initial_padding = pre_skip;
6434 st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
6435 (AVRational){1, 1000},
6436 (AVRational){1, 48000});
6441 static const MOVParseTableEntry mov_default_parse_table[] = {
6442 { MKTAG('A','C','L','R'), mov_read_aclr },
6443 { MKTAG('A','P','R','G'), mov_read_avid },
6444 { MKTAG('A','A','L','P'), mov_read_avid },
6445 { MKTAG('A','R','E','S'), mov_read_ares },
6446 { MKTAG('a','v','s','s'), mov_read_avss },
6447 { MKTAG('c','h','p','l'), mov_read_chpl },
6448 { MKTAG('c','o','6','4'), mov_read_stco },
6449 { MKTAG('c','o','l','r'), mov_read_colr },
6450 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
6451 { MKTAG('d','i','n','f'), mov_read_default },
6452 { MKTAG('D','p','x','E'), mov_read_dpxe },
6453 { MKTAG('d','r','e','f'), mov_read_dref },
6454 { MKTAG('e','d','t','s'), mov_read_default },
6455 { MKTAG('e','l','s','t'), mov_read_elst },
6456 { MKTAG('e','n','d','a'), mov_read_enda },
6457 { MKTAG('f','i','e','l'), mov_read_fiel },
6458 { MKTAG('a','d','r','m'), mov_read_adrm },
6459 { MKTAG('f','t','y','p'), mov_read_ftyp },
6460 { MKTAG('g','l','b','l'), mov_read_glbl },
6461 { MKTAG('h','d','l','r'), mov_read_hdlr },
6462 { MKTAG('i','l','s','t'), mov_read_ilst },
6463 { MKTAG('j','p','2','h'), mov_read_jp2h },
6464 { MKTAG('m','d','a','t'), mov_read_mdat },
6465 { MKTAG('m','d','h','d'), mov_read_mdhd },
6466 { MKTAG('m','d','i','a'), mov_read_default },
6467 { MKTAG('m','e','t','a'), mov_read_meta },
6468 { MKTAG('m','i','n','f'), mov_read_default },
6469 { MKTAG('m','o','o','f'), mov_read_moof },
6470 { MKTAG('m','o','o','v'), mov_read_moov },
6471 { MKTAG('m','v','e','x'), mov_read_default },
6472 { MKTAG('m','v','h','d'), mov_read_mvhd },
6473 { MKTAG('S','M','I',' '), mov_read_svq3 },
6474 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
6475 { MKTAG('a','v','c','C'), mov_read_glbl },
6476 { MKTAG('p','a','s','p'), mov_read_pasp },
6477 { MKTAG('s','i','d','x'), mov_read_sidx },
6478 { MKTAG('s','t','b','l'), mov_read_default },
6479 { MKTAG('s','t','c','o'), mov_read_stco },
6480 { MKTAG('s','t','p','s'), mov_read_stps },
6481 { MKTAG('s','t','r','f'), mov_read_strf },
6482 { MKTAG('s','t','s','c'), mov_read_stsc },
6483 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
6484 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
6485 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
6486 { MKTAG('s','t','t','s'), mov_read_stts },
6487 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
6488 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
6489 { MKTAG('t','f','d','t'), mov_read_tfdt },
6490 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
6491 { MKTAG('t','r','a','k'), mov_read_trak },
6492 { MKTAG('t','r','a','f'), mov_read_default },
6493 { MKTAG('t','r','e','f'), mov_read_default },
6494 { MKTAG('t','m','c','d'), mov_read_tmcd },
6495 { MKTAG('c','h','a','p'), mov_read_chap },
6496 { MKTAG('t','r','e','x'), mov_read_trex },
6497 { MKTAG('t','r','u','n'), mov_read_trun },
6498 { MKTAG('u','d','t','a'), mov_read_default },
6499 { MKTAG('w','a','v','e'), mov_read_wave },
6500 { MKTAG('e','s','d','s'), mov_read_esds },
6501 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
6502 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
6503 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
6504 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
6505 { MKTAG('w','f','e','x'), mov_read_wfex },
6506 { MKTAG('c','m','o','v'), mov_read_cmov },
6507 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
6508 { MKTAG('d','v','c','1'), mov_read_dvc1 },
6509 { MKTAG('s','b','g','p'), mov_read_sbgp },
6510 { MKTAG('h','v','c','C'), mov_read_glbl },
6511 { MKTAG('u','u','i','d'), mov_read_uuid },
6512 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
6513 { MKTAG('f','r','e','e'), mov_read_free },
6514 { MKTAG('-','-','-','-'), mov_read_custom },
6515 { MKTAG('s','i','n','f'), mov_read_default },
6516 { MKTAG('f','r','m','a'), mov_read_frma },
6517 { MKTAG('s','e','n','c'), mov_read_senc },
6518 { MKTAG('s','a','i','z'), mov_read_saiz },
6519 { MKTAG('s','a','i','o'), mov_read_saio },
6520 { MKTAG('s','c','h','m'), mov_read_schm },
6521 { MKTAG('s','c','h','i'), mov_read_default },
6522 { MKTAG('t','e','n','c'), mov_read_tenc },
6523 { MKTAG('d','f','L','a'), mov_read_dfla },
6524 { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
6525 { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
6526 { MKTAG('d','O','p','s'), mov_read_dops },
6527 { MKTAG('S','m','D','m'), mov_read_smdm },
6528 { MKTAG('C','o','L','L'), mov_read_coll },
6529 { MKTAG('v','p','c','C'), mov_read_vpcc },
6530 { MKTAG('m','d','c','v'), mov_read_mdcv },
6531 { MKTAG('c','l','l','i'), mov_read_clli },
6535 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6537 int64_t total_size = 0;
6541 if (c->atom_depth > 10) {
6542 av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
6543 return AVERROR_INVALIDDATA;
6548 atom.size = INT64_MAX;
6549 while (total_size <= atom.size - 8 && !avio_feof(pb)) {
6550 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
6553 if (atom.size >= 8) {
6554 a.size = avio_rb32(pb);
6555 a.type = avio_rl32(pb);
6556 if (a.type == MKTAG('f','r','e','e') &&
6558 c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
6561 uint32_t *type = (uint32_t *)buf + 1;
6562 if (avio_read(pb, buf, 8) != 8)
6563 return AVERROR_INVALIDDATA;
6564 avio_seek(pb, -8, SEEK_CUR);
6565 if (*type == MKTAG('m','v','h','d') ||
6566 *type == MKTAG('c','m','o','v')) {
6567 av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
6568 a.type = MKTAG('m','o','o','v');
6571 if (atom.type != MKTAG('r','o','o','t') &&
6572 atom.type != MKTAG('m','o','o','v'))
6574 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
6576 av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
6583 if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
6584 a.size = avio_rb64(pb) - 8;
6588 av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
6589 av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
6591 a.size = atom.size - total_size + 8;
6596 a.size = FFMIN(a.size, atom.size - total_size);
6598 for (i = 0; mov_default_parse_table[i].type; i++)
6599 if (mov_default_parse_table[i].type == a.type) {
6600 parse = mov_default_parse_table[i].parse;
6604 // container is user data
6605 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
6606 atom.type == MKTAG('i','l','s','t')))
6607 parse = mov_read_udta_string;
6609 // Supports parsing the QuickTime Metadata Keys.
6610 // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
6611 if (!parse && c->found_hdlr_mdta &&
6612 atom.type == MKTAG('m','e','t','a') &&
6613 a.type == MKTAG('k','e','y','s')) {
6614 parse = mov_read_keys;
6617 if (!parse) { /* skip leaf atoms data */
6618 avio_skip(pb, a.size);
6620 int64_t start_pos = avio_tell(pb);
6622 int err = parse(c, pb, a);
6627 if (c->found_moov && c->found_mdat &&
6628 ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete) ||
6629 start_pos + a.size == avio_size(pb))) {
6630 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete)
6631 c->next_root_atom = start_pos + a.size;
6635 left = a.size - avio_tell(pb) + start_pos;
6636 if (left > 0) /* skip garbage at atom end */
6637 avio_skip(pb, left);
6638 else if (left < 0) {
6639 av_log(c->fc, AV_LOG_WARNING,
6640 "overread end of atom '%.4s' by %"PRId64" bytes\n",
6641 (char*)&a.type, -left);
6642 avio_seek(pb, left, SEEK_CUR);
6646 total_size += a.size;
6649 if (total_size < atom.size && atom.size < 0x7ffff)
6650 avio_skip(pb, atom.size - total_size);
6656 static int mov_probe(AVProbeData *p)
6661 int moov_offset = -1;
6663 /* check file header */
6666 /* ignore invalid offset */
6667 if ((offset + 8) > (unsigned int)p->buf_size)
6669 tag = AV_RL32(p->buf + offset + 4);
6671 /* check for obvious tags */
6672 case MKTAG('m','o','o','v'):
6673 moov_offset = offset + 4;
6674 case MKTAG('m','d','a','t'):
6675 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
6676 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
6677 case MKTAG('f','t','y','p'):
6678 if (AV_RB32(p->buf+offset) < 8 &&
6679 (AV_RB32(p->buf+offset) != 1 ||
6680 offset + 12 > (unsigned int)p->buf_size ||
6681 AV_RB64(p->buf+offset + 8) == 0)) {
6682 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6683 } else if (tag == MKTAG('f','t','y','p') &&
6684 ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
6685 || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
6687 score = FFMAX(score, 5);
6689 score = AVPROBE_SCORE_MAX;
6691 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6693 /* those are more common words, so rate then a bit less */
6694 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
6695 case MKTAG('w','i','d','e'):
6696 case MKTAG('f','r','e','e'):
6697 case MKTAG('j','u','n','k'):
6698 case MKTAG('p','i','c','t'):
6699 score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
6700 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6702 case MKTAG(0x82,0x82,0x7f,0x7d):
6703 case MKTAG('s','k','i','p'):
6704 case MKTAG('u','u','i','d'):
6705 case MKTAG('p','r','f','l'):
6706 /* if we only find those cause probedata is too small at least rate them */
6707 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6708 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6711 offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6714 if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
6715 /* moov atom in the header - we should make sure that this is not a
6716 * MOV-packed MPEG-PS */
6717 offset = moov_offset;
6719 while(offset < (p->buf_size - 16)){ /* Sufficient space */
6720 /* We found an actual hdlr atom */
6721 if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
6722 AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
6723 AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
6724 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
6725 /* We found a media handler reference atom describing an
6726 * MPEG-PS-in-MOV, return a
6727 * low score to force expanding the probe window until
6728 * mpegps_probe finds what it needs */
6739 // must be done after parsing all trak because there's no order requirement
6740 static void mov_read_chapters(AVFormatContext *s)
6742 MOVContext *mov = s->priv_data;
6744 MOVStreamContext *sc;
6749 for (j = 0; j < mov->nb_chapter_tracks; j++) {
6750 chapter_track = mov->chapter_tracks[j];
6752 for (i = 0; i < s->nb_streams; i++)
6753 if (s->streams[i]->id == chapter_track) {
6758 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
6763 cur_pos = avio_tell(sc->pb);
6765 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6766 st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
6767 if (st->nb_index_entries) {
6768 // Retrieve the first frame, if possible
6770 AVIndexEntry *sample = &st->index_entries[0];
6771 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6772 av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
6776 if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
6779 st->attached_pic = pkt;
6780 st->attached_pic.stream_index = st->index;
6781 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
6784 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
6785 st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
6786 st->discard = AVDISCARD_ALL;
6787 for (i = 0; i < st->nb_index_entries; i++) {
6788 AVIndexEntry *sample = &st->index_entries[i];
6789 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
6794 if (end < sample->timestamp) {
6795 av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
6796 end = AV_NOPTS_VALUE;
6799 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6800 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
6804 // the first two bytes are the length of the title
6805 len = avio_rb16(sc->pb);
6806 if (len > sample->size-2)
6808 title_len = 2*len + 1;
6809 if (!(title = av_mallocz(title_len)))
6812 // The samples could theoretically be in any encoding if there's an encd
6813 // atom following, but in practice are only utf-8 or utf-16, distinguished
6814 // instead by the presence of a BOM
6818 ch = avio_rb16(sc->pb);
6820 avio_get_str16be(sc->pb, len, title, title_len);
6821 else if (ch == 0xfffe)
6822 avio_get_str16le(sc->pb, len, title, title_len);
6825 if (len == 1 || len == 2)
6828 avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
6832 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
6837 avio_seek(sc->pb, cur_pos, SEEK_SET);
6841 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
6842 uint32_t value, int flags)
6845 char buf[AV_TIMECODE_STR_SIZE];
6846 AVRational rate = st->avg_frame_rate;
6847 int ret = av_timecode_init(&tc, rate, flags, 0, s);
6850 av_dict_set(&st->metadata, "timecode",
6851 av_timecode_make_string(&tc, buf, value), 0);
6855 static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
6857 MOVStreamContext *sc = st->priv_data;
6858 char buf[AV_TIMECODE_STR_SIZE];
6859 int64_t cur_pos = avio_tell(sc->pb);
6860 int hh, mm, ss, ff, drop;
6862 if (!st->nb_index_entries)
6865 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6866 avio_skip(s->pb, 13);
6867 hh = avio_r8(s->pb);
6868 mm = avio_r8(s->pb);
6869 ss = avio_r8(s->pb);
6870 drop = avio_r8(s->pb);
6871 ff = avio_r8(s->pb);
6872 snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
6873 hh, mm, ss, drop ? ';' : ':', ff);
6874 av_dict_set(&st->metadata, "timecode", buf, 0);
6876 avio_seek(sc->pb, cur_pos, SEEK_SET);
6880 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
6882 MOVStreamContext *sc = st->priv_data;
6884 int64_t cur_pos = avio_tell(sc->pb);
6887 if (!st->nb_index_entries)
6890 avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6891 value = avio_rb32(s->pb);
6893 if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
6894 if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
6895 if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
6897 /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
6898 * not the case) and thus assume "frame number format" instead of QT one.
6899 * No sample with tmcd track can be found with a QT timecode at the moment,
6900 * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
6902 parse_timecode_in_framenum_format(s, st, value, flags);
6904 avio_seek(sc->pb, cur_pos, SEEK_SET);
6908 static void mov_free_encryption_index(MOVEncryptionIndex **index) {
6910 if (!index || !*index) return;
6911 for (i = 0; i < (*index)->nb_encrypted_samples; i++) {
6912 av_encryption_info_free((*index)->encrypted_samples[i]);
6914 av_freep(&(*index)->encrypted_samples);
6915 av_freep(&(*index)->auxiliary_info_sizes);
6916 av_freep(&(*index)->auxiliary_offsets);
6920 static int mov_read_close(AVFormatContext *s)
6922 MOVContext *mov = s->priv_data;
6925 for (i = 0; i < s->nb_streams; i++) {
6926 AVStream *st = s->streams[i];
6927 MOVStreamContext *sc = st->priv_data;
6932 av_freep(&sc->ctts_data);
6933 for (j = 0; j < sc->drefs_count; j++) {
6934 av_freep(&sc->drefs[j].path);
6935 av_freep(&sc->drefs[j].dir);
6937 av_freep(&sc->drefs);
6939 sc->drefs_count = 0;
6941 if (!sc->pb_is_copied)
6942 ff_format_io_close(s, &sc->pb);
6945 av_freep(&sc->chunk_offsets);
6946 av_freep(&sc->stsc_data);
6947 av_freep(&sc->sample_sizes);
6948 av_freep(&sc->keyframes);
6949 av_freep(&sc->stts_data);
6950 av_freep(&sc->stps_data);
6951 av_freep(&sc->elst_data);
6952 av_freep(&sc->rap_group);
6953 av_freep(&sc->display_matrix);
6954 av_freep(&sc->index_ranges);
6957 for (j = 0; j < sc->stsd_count; j++)
6958 av_free(sc->extradata[j]);
6959 av_freep(&sc->extradata);
6960 av_freep(&sc->extradata_size);
6962 mov_free_encryption_index(&sc->cenc.encryption_index);
6963 av_encryption_info_free(sc->cenc.default_encrypted_sample);
6964 av_aes_ctr_free(sc->cenc.aes_ctr);
6966 av_freep(&sc->stereo3d);
6967 av_freep(&sc->spherical);
6968 av_freep(&sc->mastering);
6969 av_freep(&sc->coll);
6972 if (mov->dv_demux) {
6973 avformat_free_context(mov->dv_fctx);
6974 mov->dv_fctx = NULL;
6977 if (mov->meta_keys) {
6978 for (i = 1; i < mov->meta_keys_count; i++) {
6979 av_freep(&mov->meta_keys[i]);
6981 av_freep(&mov->meta_keys);
6984 av_freep(&mov->trex_data);
6985 av_freep(&mov->bitrates);
6987 for (i = 0; i < mov->frag_index.nb_items; i++) {
6988 MOVFragmentStreamInfo *frag = mov->frag_index.item[i].stream_info;
6989 for (j = 0; j < mov->frag_index.item[i].nb_stream_info; j++) {
6990 mov_free_encryption_index(&frag[j].encryption_index);
6992 av_freep(&mov->frag_index.item[i].stream_info);
6994 av_freep(&mov->frag_index.item);
6996 av_freep(&mov->aes_decrypt);
6997 av_freep(&mov->chapter_tracks);
7002 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
7006 for (i = 0; i < s->nb_streams; i++) {
7007 AVStream *st = s->streams[i];
7008 MOVStreamContext *sc = st->priv_data;
7010 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
7011 sc->timecode_track == tmcd_id)
7017 /* look for a tmcd track not referenced by any video track, and export it globally */
7018 static void export_orphan_timecode(AVFormatContext *s)
7022 for (i = 0; i < s->nb_streams; i++) {
7023 AVStream *st = s->streams[i];
7025 if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
7026 !tmcd_is_referenced(s, i + 1)) {
7027 AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
7029 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
7036 static int read_tfra(MOVContext *mov, AVIOContext *f)
7038 int version, fieldlength, i, j;
7039 int64_t pos = avio_tell(f);
7040 uint32_t size = avio_rb32(f);
7041 unsigned track_id, item_count;
7043 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
7046 av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
7048 version = avio_r8(f);
7050 track_id = avio_rb32(f);
7051 fieldlength = avio_rb32(f);
7052 item_count = avio_rb32(f);
7053 for (i = 0; i < item_count; i++) {
7054 int64_t time, offset;
7056 MOVFragmentStreamInfo * frag_stream_info;
7059 return AVERROR_INVALIDDATA;
7063 time = avio_rb64(f);
7064 offset = avio_rb64(f);
7066 time = avio_rb32(f);
7067 offset = avio_rb32(f);
7070 // The first sample of each stream in a fragment is always a random
7071 // access sample. So it's entry in the tfra can be used as the
7072 // initial PTS of the fragment.
7073 index = update_frag_index(mov, offset);
7074 frag_stream_info = get_frag_stream_info(&mov->frag_index, index, track_id);
7075 if (frag_stream_info &&
7076 frag_stream_info->first_tfra_pts == AV_NOPTS_VALUE)
7077 frag_stream_info->first_tfra_pts = time;
7079 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
7081 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
7083 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
7087 avio_seek(f, pos + size, SEEK_SET);
7091 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
7093 int64_t stream_size = avio_size(f);
7094 int64_t original_pos = avio_tell(f);
7098 if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
7102 mfra_size = avio_rb32(f);
7103 if (mfra_size < 0 || mfra_size > stream_size) {
7104 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
7107 if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
7111 if (avio_rb32(f) != mfra_size) {
7112 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
7115 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
7116 av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
7119 av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
7121 ret = read_tfra(c, f);
7127 seek_ret = avio_seek(f, original_pos, SEEK_SET);
7129 av_log(c->fc, AV_LOG_ERROR,
7130 "failed to seek back after looking for mfra\n");
7136 static int mov_read_header(AVFormatContext *s)
7138 MOVContext *mov = s->priv_data;
7139 AVIOContext *pb = s->pb;
7141 MOVAtom atom = { AV_RL32("root") };
7144 if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
7145 av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
7146 mov->decryption_key_len, AES_CTR_KEY_SIZE);
7147 return AVERROR(EINVAL);
7151 mov->trak_index = -1;
7152 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
7153 if (pb->seekable & AVIO_SEEKABLE_NORMAL)
7154 atom.size = avio_size(pb);
7156 atom.size = INT64_MAX;
7158 /* check MOV header */
7160 if (mov->moov_retry)
7161 avio_seek(pb, 0, SEEK_SET);
7162 if ((err = mov_read_default(mov, pb, atom)) < 0) {
7163 av_log(s, AV_LOG_ERROR, "error reading header\n");
7167 } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
7168 if (!mov->found_moov) {
7169 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
7171 return AVERROR_INVALIDDATA;
7173 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
7175 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
7176 if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
7177 mov_read_chapters(s);
7178 for (i = 0; i < s->nb_streams; i++)
7179 if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
7180 mov_read_timecode_track(s, s->streams[i]);
7181 } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
7182 mov_read_rtmd_track(s, s->streams[i]);
7186 /* copy timecode metadata from tmcd tracks to the related video streams */
7187 for (i = 0; i < s->nb_streams; i++) {
7188 AVStream *st = s->streams[i];
7189 MOVStreamContext *sc = st->priv_data;
7190 if (sc->timecode_track > 0) {
7191 AVDictionaryEntry *tcr;
7192 int tmcd_st_id = -1;
7194 for (j = 0; j < s->nb_streams; j++)
7195 if (s->streams[j]->id == sc->timecode_track)
7198 if (tmcd_st_id < 0 || tmcd_st_id == i)
7200 tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
7202 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
7205 export_orphan_timecode(s);
7207 for (i = 0; i < s->nb_streams; i++) {
7208 AVStream *st = s->streams[i];
7209 MOVStreamContext *sc = st->priv_data;
7210 fix_timescale(mov, sc);
7211 if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
7212 st->skip_samples = sc->start_pad;
7214 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
7215 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
7216 sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
7217 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
7218 if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
7219 st->codecpar->width = sc->width;
7220 st->codecpar->height = sc->height;
7222 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
7223 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
7227 if (mov->handbrake_version &&
7228 mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
7229 st->codecpar->codec_id == AV_CODEC_ID_MP3
7231 av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
7232 st->need_parsing = AVSTREAM_PARSE_FULL;
7236 if (mov->trex_data) {
7237 for (i = 0; i < s->nb_streams; i++) {
7238 AVStream *st = s->streams[i];
7239 MOVStreamContext *sc = st->priv_data;
7240 if (st->duration > 0) {
7241 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
7242 av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
7243 sc->data_size, sc->time_scale);
7245 return AVERROR_INVALIDDATA;
7247 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
7252 if (mov->use_mfra_for > 0) {
7253 for (i = 0; i < s->nb_streams; i++) {
7254 AVStream *st = s->streams[i];
7255 MOVStreamContext *sc = st->priv_data;
7256 if (sc->duration_for_fps > 0) {
7257 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
7258 av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
7259 sc->data_size, sc->time_scale);
7261 return AVERROR_INVALIDDATA;
7263 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
7264 sc->duration_for_fps;
7269 for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
7270 if (mov->bitrates[i]) {
7271 s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
7275 ff_rfps_calculate(s);
7277 for (i = 0; i < s->nb_streams; i++) {
7278 AVStream *st = s->streams[i];
7279 MOVStreamContext *sc = st->priv_data;
7281 switch (st->codecpar->codec_type) {
7282 case AVMEDIA_TYPE_AUDIO:
7283 err = ff_replaygain_export(st, s->metadata);
7289 case AVMEDIA_TYPE_VIDEO:
7290 if (sc->display_matrix) {
7291 err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix,
7292 sizeof(int32_t) * 9);
7296 sc->display_matrix = NULL;
7299 err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
7300 (uint8_t *)sc->stereo3d,
7301 sizeof(*sc->stereo3d));
7305 sc->stereo3d = NULL;
7307 if (sc->spherical) {
7308 err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
7309 (uint8_t *)sc->spherical,
7310 sc->spherical_size);
7314 sc->spherical = NULL;
7316 if (sc->mastering) {
7317 err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
7318 (uint8_t *)sc->mastering,
7319 sizeof(*sc->mastering));
7323 sc->mastering = NULL;
7326 err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
7327 (uint8_t *)sc->coll,
7337 ff_configure_buffers_for_index(s, AV_TIME_BASE);
7339 for (i = 0; i < mov->frag_index.nb_items; i++)
7340 if (mov->frag_index.item[i].moof_offset <= mov->fragment.moof_offset)
7341 mov->frag_index.item[i].headers_read = 1;
7346 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
7348 AVIndexEntry *sample = NULL;
7349 int64_t best_dts = INT64_MAX;
7351 for (i = 0; i < s->nb_streams; i++) {
7352 AVStream *avst = s->streams[i];
7353 MOVStreamContext *msc = avst->priv_data;
7354 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
7355 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
7356 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
7357 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
7358 if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
7359 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
7360 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
7361 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
7362 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
7363 sample = current_sample;
7372 static int should_retry(AVIOContext *pb, int error_code) {
7373 if (error_code == AVERROR_EOF || avio_feof(pb))
7379 static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
7382 MOVContext *mov = s->priv_data;
7384 if (index >= 0 && index < mov->frag_index.nb_items)
7385 target = mov->frag_index.item[index].moof_offset;
7386 if (avio_seek(s->pb, target, SEEK_SET) != target) {
7387 av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
7388 return AVERROR_INVALIDDATA;
7391 mov->next_root_atom = 0;
7392 if (index < 0 || index >= mov->frag_index.nb_items)
7393 index = search_frag_moof_offset(&mov->frag_index, target);
7394 if (index < mov->frag_index.nb_items) {
7395 if (index + 1 < mov->frag_index.nb_items)
7396 mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
7397 if (mov->frag_index.item[index].headers_read)
7399 mov->frag_index.item[index].headers_read = 1;
7402 mov->found_mdat = 0;
7404 ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
7407 if (avio_feof(s->pb))
7409 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
7414 static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
7416 uint8_t *side, *extradata;
7419 /* Save the current index. */
7420 sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
7422 /* Notify the decoder that extradata changed. */
7423 extradata_size = sc->extradata_size[sc->last_stsd_index];
7424 extradata = sc->extradata[sc->last_stsd_index];
7425 if (extradata_size > 0 && extradata) {
7426 side = av_packet_new_side_data(pkt,
7427 AV_PKT_DATA_NEW_EXTRADATA,
7430 return AVERROR(ENOMEM);
7431 memcpy(side, extradata, extradata_size);
7437 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
7439 MOVContext *mov = s->priv_data;
7440 MOVStreamContext *sc;
7441 AVIndexEntry *sample;
7442 AVStream *st = NULL;
7443 int64_t current_index;
7447 sample = mov_find_next_sample(s, &st);
7448 if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
7449 if (!mov->next_root_atom)
7451 if ((ret = mov_switch_root(s, mov->next_root_atom, -1)) < 0)
7456 /* must be done just before reading, to avoid infinite loop on sample */
7457 current_index = sc->current_index;
7458 mov_current_sample_inc(sc);
7460 if (mov->next_root_atom) {
7461 sample->pos = FFMIN(sample->pos, mov->next_root_atom);
7462 sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
7465 if (st->discard != AVDISCARD_ALL) {
7466 int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
7467 if (ret64 != sample->pos) {
7468 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
7469 sc->ffindex, sample->pos);
7470 if (should_retry(sc->pb, ret64)) {
7471 mov_current_sample_dec(sc);
7473 return AVERROR_INVALIDDATA;
7476 if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
7477 av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
7481 ret = av_get_packet(sc->pb, pkt, sample->size);
7483 if (should_retry(sc->pb, ret)) {
7484 mov_current_sample_dec(sc);
7488 if (sc->has_palette) {
7491 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
7493 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
7495 memcpy(pal, sc->palette, AVPALETTE_SIZE);
7496 sc->has_palette = 0;
7499 #if CONFIG_DV_DEMUXER
7500 if (mov->dv_demux && sc->dv_audio_container) {
7501 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
7502 av_freep(&pkt->data);
7504 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
7509 if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
7510 if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
7511 st->need_parsing = AVSTREAM_PARSE_FULL;
7515 pkt->stream_index = sc->ffindex;
7516 pkt->dts = sample->timestamp;
7517 if (sample->flags & AVINDEX_DISCARD_FRAME) {
7518 pkt->flags |= AV_PKT_FLAG_DISCARD;
7520 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
7521 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
7522 /* update ctts context */
7524 if (sc->ctts_index < sc->ctts_count &&
7525 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
7527 sc->ctts_sample = 0;
7530 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
7531 st->index_entries[sc->current_sample].timestamp : st->duration;
7532 pkt->duration = next_dts - pkt->dts;
7533 pkt->pts = pkt->dts;
7535 if (st->discard == AVDISCARD_ALL)
7537 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
7538 pkt->pos = sample->pos;
7540 /* Multiple stsd handling. */
7541 if (sc->stsc_data) {
7542 /* Keep track of the stsc index for the given sample, then check
7543 * if the stsd index is different from the last used one. */
7545 if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
7546 mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
7548 sc->stsc_sample = 0;
7549 /* Do not check indexes after a switch. */
7550 } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
7551 sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
7552 sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
7553 ret = mov_change_extradata(sc, pkt);
7560 aax_filter(pkt->data, pkt->size, mov);
7562 ret = cenc_filter(mov, sc, pkt, current_index);
7569 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
7571 MOVContext *mov = s->priv_data;
7574 if (!mov->frag_index.complete)
7577 index = search_frag_timestamp(&mov->frag_index, st, timestamp);
7580 if (!mov->frag_index.item[index].headers_read)
7581 return mov_switch_root(s, -1, index);
7582 if (index + 1 < mov->frag_index.nb_items)
7583 mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
7588 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
7590 MOVStreamContext *sc = st->priv_data;
7591 int sample, time_sample, ret;
7594 // Here we consider timestamp to be PTS, hence try to offset it so that we
7595 // can search over the DTS timeline.
7596 timestamp -= (sc->min_corrected_pts + sc->dts_shift);
7598 ret = mov_seek_fragment(s, st, timestamp);
7602 sample = av_index_search_timestamp(st, timestamp, flags);
7603 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
7604 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
7606 if (sample < 0) /* not sure what to do */
7607 return AVERROR_INVALIDDATA;
7608 mov_current_sample_set(sc, sample);
7609 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
7610 /* adjust ctts index */
7611 if (sc->ctts_data) {
7613 for (i = 0; i < sc->ctts_count; i++) {
7614 int next = time_sample + sc->ctts_data[i].count;
7615 if (next > sc->current_sample) {
7617 sc->ctts_sample = sc->current_sample - time_sample;
7624 /* adjust stsd index */
7626 for (i = 0; i < sc->stsc_count; i++) {
7627 int64_t next = time_sample + mov_get_stsc_samples(sc, i);
7628 if (next > sc->current_sample) {
7630 sc->stsc_sample = sc->current_sample - time_sample;
7633 av_assert0(next == (int)next);
7640 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
7642 MOVContext *mc = s->priv_data;
7647 if (stream_index >= s->nb_streams)
7648 return AVERROR_INVALIDDATA;
7650 st = s->streams[stream_index];
7651 sample = mov_seek_stream(s, st, sample_time, flags);
7655 if (mc->seek_individually) {
7656 /* adjust seek timestamp to found sample timestamp */
7657 int64_t seek_timestamp = st->index_entries[sample].timestamp;
7659 for (i = 0; i < s->nb_streams; i++) {
7661 MOVStreamContext *sc = s->streams[i]->priv_data;
7663 st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
7665 if (stream_index == i)
7668 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
7669 mov_seek_stream(s, st, timestamp, flags);
7672 for (i = 0; i < s->nb_streams; i++) {
7673 MOVStreamContext *sc;
7676 mov_current_sample_set(sc, 0);
7679 MOVStreamContext *sc;
7680 AVIndexEntry *entry = mov_find_next_sample(s, &st);
7682 return AVERROR_INVALIDDATA;
7684 if (sc->ffindex == stream_index && sc->current_sample == sample)
7686 mov_current_sample_inc(sc);
7692 #define OFFSET(x) offsetof(MOVContext, x)
7693 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
7694 static const AVOption mov_options[] = {
7695 {"use_absolute_path",
7696 "allow using absolute path when opening alias, this is a possible security issue",
7697 OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
7699 {"seek_streams_individually",
7700 "Seek each stream individually to the to the closest point",
7701 OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
7703 {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
7705 {"advanced_editlist",
7706 "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
7707 OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
7709 {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
7712 "use mfra for fragment timestamps",
7713 OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
7714 -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
7716 {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
7717 FLAGS, "use_mfra_for" },
7718 {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
7719 FLAGS, "use_mfra_for" },
7720 {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
7721 FLAGS, "use_mfra_for" },
7722 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
7723 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7724 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
7725 AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7726 { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
7727 AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7728 { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
7729 "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
7730 AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
7731 .flags = AV_OPT_FLAG_DECODING_PARAM },
7732 { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7733 { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
7734 {.i64 = 0}, 0, 1, FLAGS },
7739 static const AVClass mov_class = {
7740 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
7741 .item_name = av_default_item_name,
7742 .option = mov_options,
7743 .version = LIBAVUTIL_VERSION_INT,
7746 AVInputFormat ff_mov_demuxer = {
7747 .name = "mov,mp4,m4a,3gp,3g2,mj2",
7748 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
7749 .priv_class = &mov_class,
7750 .priv_data_size = sizeof(MOVContext),
7751 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
7752 .read_probe = mov_probe,
7753 .read_header = mov_read_header,
7754 .read_packet = mov_read_packet,
7755 .read_close = mov_read_close,
7756 .read_seek = mov_read_seek,
7757 .flags = AVFMT_NO_BYTE_SEEK,