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 Libav.
11 * Libav 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 * Libav 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 Libav; 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/intreadwrite.h"
33 #include "libavutil/intfloat.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/time_internal.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/dict.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/pixdesc.h"
40 #include "libavutil/spherical.h"
41 #include "libavutil/stereo3d.h"
42 #include "libavcodec/ac3tab.h"
45 #include "avio_internal.h"
48 #include "libavcodec/get_bits.h"
51 #include "replaygain.h"
57 #include "qtpalette.h"
60 /* those functions parse an atom */
61 /* links atom IDs to parse functions */
62 typedef struct MOVParseTableEntry {
64 int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
67 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
69 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
70 unsigned len, const char *key)
74 short current, total = 0;
75 avio_rb16(pb); // unknown
76 current = avio_rb16(pb);
78 total = avio_rb16(pb);
80 snprintf(buf, sizeof(buf), "%d", current);
82 snprintf(buf, sizeof(buf), "%d/%d", current, total);
83 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
84 av_dict_set(&c->fc->metadata, key, buf, 0);
89 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
90 unsigned len, const char *key)
94 /* bypass padding bytes */
99 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
100 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
101 av_dict_set(&c->fc->metadata, key, buf, 0);
106 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
107 unsigned len, const char *key)
111 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
112 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
113 av_dict_set(&c->fc->metadata, key, buf, 0);
118 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
119 unsigned len, const char *key)
124 avio_r8(pb); // unknown
127 if (genre < 1 || genre > ID3v1_GENRE_MAX)
129 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
130 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
131 av_dict_set(&c->fc->metadata, key, buf, 0);
136 static const uint32_t mac_to_unicode[128] = {
137 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
138 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
139 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
140 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
141 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
142 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
143 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
144 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
145 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
146 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
147 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
148 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
149 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
150 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
151 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
152 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
155 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
156 char *dst, int dstlen)
159 char *end = dst+dstlen-1;
162 for (i = 0; i < len; i++) {
163 uint8_t t, c = avio_r8(pb);
171 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
177 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
181 MOVStreamContext *sc;
186 case 0xd: id = AV_CODEC_ID_MJPEG; break;
187 case 0xe: id = AV_CODEC_ID_PNG; break;
188 case 0x1b: id = AV_CODEC_ID_BMP; break;
190 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
195 st = avformat_new_stream(c->fc, NULL);
197 return AVERROR(ENOMEM);
198 sc = av_mallocz(sizeof(*sc));
200 return AVERROR(ENOMEM);
203 ret = av_get_packet(pb, &pkt, len);
207 if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
208 if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
209 id = AV_CODEC_ID_PNG;
211 id = AV_CODEC_ID_MJPEG;
215 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
217 st->attached_pic = pkt;
218 st->attached_pic.stream_index = st->index;
219 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
221 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
222 st->codecpar->codec_id = id;
228 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
230 char language[4] = { 0 };
231 char buf[200], place[100];
232 uint16_t langcode = 0;
233 double longitude, latitude, altitude;
234 const char *key = "location";
236 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
237 av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
238 return AVERROR_INVALIDDATA;
241 avio_skip(pb, 4); // version+flags
242 langcode = avio_rb16(pb);
243 ff_mov_lang_to_iso639(langcode, language);
246 len -= avio_get_str(pb, len, place, sizeof(place));
248 av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
249 return AVERROR_INVALIDDATA;
251 avio_skip(pb, 1); // role
255 av_log(c->fc, AV_LOG_ERROR,
256 "loci too short (%u bytes left, need at least %d)\n", len, 12);
257 return AVERROR_INVALIDDATA;
259 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
260 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
261 altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
263 // Try to output in the same format as the ?xyz field
264 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
266 av_strlcatf(buf, sizeof(buf), "%+f", altitude);
267 av_strlcatf(buf, sizeof(buf), "/%s", place);
269 if (*language && strcmp(language, "und")) {
271 snprintf(key2, sizeof(key2), "%s-%s", key, language);
272 av_dict_set(&c->fc->metadata, key2, buf, 0);
274 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
275 return av_dict_set(&c->fc->metadata, key, buf, 0);
278 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
281 char *str, key2[32], language[4] = {0};
282 const char *key = NULL;
283 uint16_t langcode = 0;
284 uint32_t data_type = 0, str_size, str_size_alloc;
285 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
289 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
290 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
291 case MKTAG( 'X','M','P','_'):
292 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
293 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
294 case MKTAG( 'a','k','I','D'): key = "account_type";
295 parse = mov_metadata_int8_no_padding; break;
296 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
297 case MKTAG( 'c','a','t','g'): key = "category"; break;
298 case MKTAG( 'c','p','i','l'): key = "compilation";
299 parse = mov_metadata_int8_no_padding; break;
300 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
301 case MKTAG( 'd','e','s','c'): key = "description"; break;
302 case MKTAG( 'd','i','s','k'): key = "disc";
303 parse = mov_metadata_track_or_disc_number; break;
304 case MKTAG( 'e','g','i','d'): key = "episode_uid";
305 parse = mov_metadata_int8_no_padding; break;
306 case MKTAG( 'g','n','r','e'): key = "genre";
307 parse = mov_metadata_gnre; break;
308 case MKTAG( 'h','d','v','d'): key = "hd_video";
309 parse = mov_metadata_int8_no_padding; break;
310 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
311 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
312 case MKTAG( 'l','o','c','i'):
313 return mov_metadata_loci(c, pb, atom.size);
314 case MKTAG( 'p','c','s','t'): key = "podcast";
315 parse = mov_metadata_int8_no_padding; break;
316 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
317 parse = mov_metadata_int8_no_padding; break;
318 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
319 case MKTAG( 'r','t','n','g'): key = "rating";
320 parse = mov_metadata_int8_no_padding; break;
321 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
322 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
323 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
324 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
325 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
326 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
327 case MKTAG( 's','t','i','k'): key = "media_type";
328 parse = mov_metadata_int8_no_padding; break;
329 case MKTAG( 't','r','k','n'): key = "track";
330 parse = mov_metadata_track_or_disc_number; break;
331 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
332 case MKTAG( 't','v','e','s'): key = "episode_sort";
333 parse = mov_metadata_int8_bypass_padding; break;
334 case MKTAG( 't','v','n','n'): key = "network"; break;
335 case MKTAG( 't','v','s','h'): key = "show"; break;
336 case MKTAG( 't','v','s','n'): key = "season_number";
337 parse = mov_metadata_int8_bypass_padding; break;
338 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
339 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
340 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
341 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
342 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
343 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
344 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
345 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
346 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
347 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
348 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
349 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
350 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
351 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
352 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
353 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
354 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
355 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
356 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
357 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
358 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
359 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
360 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
361 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
362 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
363 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
364 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
365 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
366 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
367 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
368 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
369 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
370 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
371 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
372 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
375 if (c->itunes_metadata && atom.size > 8) {
376 int data_size = avio_rb32(pb);
377 int tag = avio_rl32(pb);
378 if (tag == MKTAG('d','a','t','a')) {
379 data_type = avio_rb32(pb); // type
380 avio_rb32(pb); // unknown
381 str_size = data_size - 16;
384 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
385 int ret = mov_read_covr(c, pb, data_type, str_size);
387 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
392 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
393 str_size = avio_rb16(pb); // string length
394 langcode = avio_rb16(pb);
395 ff_mov_lang_to_iso639(langcode, language);
398 str_size = atom.size;
400 if (c->export_all && !key) {
401 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
408 return AVERROR_INVALIDDATA;
410 // allocate twice as much as worst-case
411 str_size_alloc = (raw ? str_size : str_size * 2) + 1;
412 str = av_malloc(str_size_alloc);
414 return AVERROR(ENOMEM);
417 parse(c, pb, str_size, key);
419 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
420 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
422 int ret = ffio_read_size(pb, str, str_size);
429 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
430 av_dict_set(&c->fc->metadata, key, str, 0);
431 if (*language && strcmp(language, "und")) {
432 snprintf(key2, sizeof(key2), "%s-%s", key, language);
433 av_dict_set(&c->fc->metadata, key2, str, 0);
441 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
444 int i, nb_chapters, str_len, version;
448 if ((atom.size -= 5) < 0)
451 version = avio_r8(pb);
454 avio_rb32(pb); // ???
455 nb_chapters = avio_r8(pb);
457 for (i = 0; i < nb_chapters; i++) {
461 start = avio_rb64(pb);
462 str_len = avio_r8(pb);
464 if ((atom.size -= 9+str_len) < 0)
467 ret = ffio_read_size(pb, str, str_len);
471 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
476 #define MIN_DATA_ENTRY_BOX_SIZE 12
477 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
480 MOVStreamContext *sc;
483 if (c->fc->nb_streams < 1)
485 st = c->fc->streams[c->fc->nb_streams-1];
488 avio_rb32(pb); // version + flags
489 entries = avio_rb32(pb);
491 entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
492 entries >= UINT_MAX / sizeof(*sc->drefs))
493 return AVERROR_INVALIDDATA;
496 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
498 return AVERROR(ENOMEM);
499 sc->drefs_count = entries;
501 for (i = 0; i < entries; i++) {
502 MOVDref *dref = &sc->drefs[i];
503 uint32_t size = avio_rb32(pb);
504 int64_t next = avio_tell(pb) + size - 4;
507 return AVERROR_INVALIDDATA;
509 dref->type = avio_rl32(pb);
510 avio_rb32(pb); // version + flags
512 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
513 /* macintosh alias record */
514 uint16_t volume_len, len;
520 volume_len = avio_r8(pb);
521 volume_len = FFMIN(volume_len, 27);
522 ret = ffio_read_size(pb, dref->volume, 27);
525 dref->volume[volume_len] = 0;
526 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %"PRIu16"\n",
527 dref->volume, volume_len);
532 len = FFMIN(len, 63);
533 ret = ffio_read_size(pb, dref->filename, 63);
536 dref->filename[len] = 0;
537 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %"PRIu16"\n",
538 dref->filename, len);
542 /* read next level up_from_alias/down_to_target */
543 dref->nlvl_from = avio_rb16(pb);
544 dref->nlvl_to = avio_rb16(pb);
545 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %"PRId16", nlvl to %"PRId16"\n",
546 dref->nlvl_from, dref->nlvl_to);
550 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
553 type = avio_rb16(pb);
555 av_log(c->fc, AV_LOG_DEBUG, "type %"PRId16", len %"PRIu16"\n",
559 if (type == 2) { // absolute path
561 dref->path = av_mallocz(len+1);
563 return AVERROR(ENOMEM);
565 ret = ffio_read_size(pb, dref->path, len);
567 av_freep(&dref->path);
570 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
572 memmove(dref->path, dref->path+volume_len, len);
575 // trim string of any ending zeros
576 for (j = len - 1; j >= 0; j--) {
577 if (dref->path[j] == 0)
582 for (j = 0; j < len; j++)
583 if (dref->path[j] == ':' || dref->path[j] == 0)
585 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
586 } else if (type == 0) { // directory name
588 dref->dir = av_malloc(len+1);
590 return AVERROR(ENOMEM);
592 ret = ffio_read_size(pb, dref->dir, len);
594 av_freep(&dref->dir);
598 for (j = 0; j < len; j++)
599 if (dref->dir[j] == ':')
601 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
606 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x08%"PRIx32" size %"PRIu32"\n",
611 avio_seek(pb, next, SEEK_SET);
616 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
620 uint32_t av_unused ctype;
625 if (c->fc->nb_streams < 1) // meta before first trak
628 st = c->fc->streams[c->fc->nb_streams-1];
630 avio_r8(pb); /* version */
631 avio_rb24(pb); /* flags */
634 ctype = avio_rl32(pb);
635 type = avio_rl32(pb); /* component subtype */
637 av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08"PRIx32")\n", (char *)&ctype, ctype);
638 av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
640 if (type == MKTAG('v','i','d','e'))
641 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
642 else if (type == MKTAG('s','o','u','n'))
643 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
644 else if (type == MKTAG('m','1','a',' '))
645 st->codecpar->codec_id = AV_CODEC_ID_MP2;
646 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
647 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
649 avio_rb32(pb); /* component manufacture */
650 avio_rb32(pb); /* component flags */
651 avio_rb32(pb); /* component flags mask */
653 title_size = atom.size - 24;
654 if (title_size > 0) {
655 title_str = av_malloc(title_size + 1); /* Add null terminator */
657 return AVERROR(ENOMEM);
659 ret = ffio_read_size(pb, title_str, title_size);
661 av_freep(&title_str);
664 title_str[title_size] = 0;
666 int off = (!c->isom && title_str[0] == title_size - 1);
667 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
669 av_freep(&title_str);
675 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
680 if (fc->nb_streams < 1)
682 st = fc->streams[fc->nb_streams-1];
684 avio_rb32(pb); /* version + flags */
685 ff_mp4_read_descr(fc, pb, &tag);
686 if (tag == MP4ESDescrTag) {
687 ff_mp4_parse_es_descr(pb, NULL);
689 avio_rb16(pb); /* ID */
691 ff_mp4_read_descr(fc, pb, &tag);
692 if (tag == MP4DecConfigDescrTag)
693 ff_mp4_read_dec_config_descr(fc, st, pb);
697 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
699 return ff_mov_read_esds(c->fc, pb);
702 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
705 enum AVAudioServiceType *ast;
706 int ac3info, acmod, lfeon, bsmod;
708 if (c->fc->nb_streams < 1)
710 st = c->fc->streams[c->fc->nb_streams-1];
712 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
715 return AVERROR(ENOMEM);
717 ac3info = avio_rb24(pb);
718 bsmod = (ac3info >> 14) & 0x7;
719 acmod = (ac3info >> 11) & 0x7;
720 lfeon = (ac3info >> 10) & 0x1;
721 st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
722 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
724 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
726 if (st->codecpar->channels > 1 && bsmod == 0x7)
727 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
729 #if FF_API_LAVF_AVCTX
730 FF_DISABLE_DEPRECATION_WARNINGS
731 st->codec->audio_service_type = *ast;
732 FF_ENABLE_DEPRECATION_WARNINGS
738 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
741 enum AVAudioServiceType *ast;
742 int eac3info, acmod, lfeon, bsmod;
744 if (c->fc->nb_streams < 1)
746 st = c->fc->streams[c->fc->nb_streams-1];
748 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
751 return AVERROR(ENOMEM);
753 /* No need to parse fields for additional independent substreams and its
754 * associated dependent substreams since libavcodec's E-AC-3 decoder
755 * does not support them yet. */
756 avio_rb16(pb); /* data_rate and num_ind_sub */
757 eac3info = avio_rb24(pb);
758 bsmod = (eac3info >> 12) & 0x1f;
759 acmod = (eac3info >> 9) & 0x7;
760 lfeon = (eac3info >> 8) & 0x1;
761 st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
763 st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
764 st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
766 if (st->codecpar->channels > 1 && bsmod == 0x7)
767 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
769 #if FF_API_LAVF_AVCTX
770 FF_DISABLE_DEPRECATION_WARNINGS
771 st->codec->audio_service_type = *ast;
772 FF_ENABLE_DEPRECATION_WARNINGS
778 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
782 if (c->fc->nb_streams < 1)
784 st = c->fc->streams[c->fc->nb_streams-1];
789 /* skip version and flags */
792 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
797 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
801 if (c->fc->nb_streams < 1)
803 st = c->fc->streams[c->fc->nb_streams-1];
805 return ff_get_wav_header(c->fc, pb, st->codecpar, atom.size);
808 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
810 const int num = avio_rb32(pb);
811 const int den = avio_rb32(pb);
814 if (c->fc->nb_streams < 1)
816 st = c->fc->streams[c->fc->nb_streams-1];
818 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
819 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
820 av_log(c->fc, AV_LOG_WARNING,
821 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
822 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
824 } else if (den != 0) {
825 st->sample_aspect_ratio.num = num;
826 st->sample_aspect_ratio.den = den;
831 /* this atom contains actual media data */
832 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
834 if (atom.size == 0) /* wrong one (MP4) */
837 return 0; /* now go for moov */
840 /* read major brand, minor version and compatible brands and store them as metadata */
841 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
845 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
846 char* comp_brands_str;
847 uint8_t type[5] = {0};
848 int ret = ffio_read_size(pb, type, 4);
852 if (strcmp(type, "qt "))
854 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
855 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
856 minor_ver = avio_rb32(pb); /* minor version */
857 snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);
858 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
860 comp_brand_size = atom.size - 8;
861 if (comp_brand_size < 0)
862 return AVERROR_INVALIDDATA;
863 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
864 if (!comp_brands_str)
865 return AVERROR(ENOMEM);
867 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
869 av_freep(&comp_brands_str);
872 comp_brands_str[comp_brand_size] = 0;
873 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
874 av_freep(&comp_brands_str);
879 /* this atom should contain all header atoms */
880 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
884 if ((ret = mov_read_default(c, pb, atom)) < 0)
886 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
887 /* so we don't parse the whole file if over a network */
889 return 0; /* now go for mdat */
892 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
894 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
895 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
896 return mov_read_default(c, pb, atom);
899 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
903 struct tm *ptm, tmbuf;
904 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
905 ptm = gmtime_r(&time, &tmbuf);
907 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
908 av_dict_set(metadata, "creation_time", buffer, 0);
912 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
915 MOVStreamContext *sc;
917 char language[4] = {0};
919 time_t creation_time;
921 if (c->fc->nb_streams < 1)
923 st = c->fc->streams[c->fc->nb_streams-1];
926 if (sc->time_scale) {
927 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
928 return AVERROR_INVALIDDATA;
931 version = avio_r8(pb);
933 avpriv_request_sample(c->fc, "Version %d", version);
934 return AVERROR_PATCHWELCOME;
936 avio_rb24(pb); /* flags */
938 creation_time = avio_rb64(pb);
941 creation_time = avio_rb32(pb);
942 avio_rb32(pb); /* modification time */
944 mov_metadata_creation_time(&st->metadata, creation_time);
946 sc->time_scale = avio_rb32(pb);
947 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
949 lang = avio_rb16(pb); /* language */
950 if (ff_mov_lang_to_iso639(lang, language))
951 av_dict_set(&st->metadata, "language", language, 0);
952 avio_rb16(pb); /* quality */
957 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
960 time_t creation_time;
961 int version = avio_r8(pb); /* version */
962 avio_rb24(pb); /* flags */
965 creation_time = avio_rb64(pb);
968 creation_time = avio_rb32(pb);
969 avio_rb32(pb); /* modification time */
971 mov_metadata_creation_time(&c->fc->metadata, creation_time);
972 c->time_scale = avio_rb32(pb); /* time scale */
974 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
976 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
977 avio_rb32(pb); /* preferred scale */
979 avio_rb16(pb); /* preferred volume */
981 avio_skip(pb, 10); /* reserved */
983 /* movie display matrix, store it in main context and use it later on */
984 for (i = 0; i < 3; i++) {
985 c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
986 c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
987 c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
990 avio_rb32(pb); /* preview time */
991 avio_rb32(pb); /* preview duration */
992 avio_rb32(pb); /* poster time */
993 avio_rb32(pb); /* selection time */
994 avio_rb32(pb); /* selection duration */
995 avio_rb32(pb); /* current time */
996 avio_rb32(pb); /* next track ID */
1001 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1006 if (c->fc->nb_streams < 1)
1008 st = c->fc->streams[c->fc->nb_streams-1];
1010 if ((uint64_t)atom.size > (1<<30))
1011 return AVERROR_INVALIDDATA;
1013 // currently SVQ3 decoder expect full STSD header - so let's fake it
1014 // this should be fixed and just SMI header should be passed
1015 av_free(st->codecpar->extradata);
1016 st->codecpar->extradata = av_mallocz(atom.size + 0x5a + AV_INPUT_BUFFER_PADDING_SIZE);
1017 if (!st->codecpar->extradata)
1018 return AVERROR(ENOMEM);
1019 st->codecpar->extradata_size = 0x5a + atom.size;
1020 memcpy(st->codecpar->extradata, "SVQ3", 4); // fake
1022 ret = ffio_read_size(pb, st->codecpar->extradata + 0x5a, atom.size);
1026 av_log(c->fc, AV_LOG_TRACE, "Reading SMI %"PRId64" %s\n", atom.size, st->codecpar->extradata + 0x5a);
1030 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1035 if (c->fc->nb_streams < 1)
1037 st = c->fc->streams[c->fc->nb_streams-1];
1039 little_endian = !!avio_rb16(pb);
1040 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1041 if (little_endian == 1) {
1042 switch (st->codecpar->codec_id) {
1043 case AV_CODEC_ID_PCM_S24BE:
1044 st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
1046 case AV_CODEC_ID_PCM_S32BE:
1047 st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
1049 case AV_CODEC_ID_PCM_F32BE:
1050 st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
1052 case AV_CODEC_ID_PCM_F64BE:
1053 st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
1062 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1065 char color_parameter_type[5] = { 0 };
1066 uint16_t color_primaries, color_trc, color_matrix;
1069 if (c->fc->nb_streams < 1)
1071 st = c->fc->streams[c->fc->nb_streams - 1];
1073 ret = ffio_read_size(pb, color_parameter_type, 4);
1076 if (strncmp(color_parameter_type, "nclx", 4) &&
1077 strncmp(color_parameter_type, "nclc", 4)) {
1078 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1079 color_parameter_type);
1083 color_primaries = avio_rb16(pb);
1084 color_trc = avio_rb16(pb);
1085 color_matrix = avio_rb16(pb);
1087 av_log(c->fc, AV_LOG_TRACE,
1088 "%s: pri %"PRIu16" trc %"PRIu16" matrix %"PRIu16"",
1089 color_parameter_type, color_primaries, color_trc, color_matrix);
1091 if (!strncmp(color_parameter_type, "nclx", 4)) {
1092 uint8_t color_range = avio_r8(pb) >> 7;
1093 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1095 st->codecpar->color_range = AVCOL_RANGE_JPEG;
1097 st->codecpar->color_range = AVCOL_RANGE_MPEG;
1099 if (!av_color_primaries_name(color_primaries))
1100 color_primaries = AVCOL_PRI_UNSPECIFIED;
1101 if (!av_color_transfer_name(color_trc))
1102 color_trc = AVCOL_TRC_UNSPECIFIED;
1103 if (!av_color_space_name(color_matrix))
1104 color_matrix = AVCOL_SPC_UNSPECIFIED;
1106 st->codecpar->color_primaries = color_primaries;
1107 st->codecpar->color_trc = color_trc;
1108 st->codecpar->color_space = color_matrix;
1109 } else if (!strncmp(color_parameter_type, "nclc", 4)) {
1110 /* color primaries, Table 4-4 */
1111 switch (color_primaries) {
1112 case 1: st->codecpar->color_primaries = AVCOL_PRI_BT709; break;
1113 case 5: st->codecpar->color_primaries = AVCOL_PRI_SMPTE170M; break;
1114 case 6: st->codecpar->color_primaries = AVCOL_PRI_SMPTE240M; break;
1115 case 9: st->codecpar->color_primaries = AVCOL_PRI_BT2020; break;
1116 case 10: st->codecpar->color_primaries = AVCOL_PRI_SMPTE431; break;
1117 case 11: st->codecpar->color_primaries = AVCOL_PRI_SMPTE432; break;
1119 /* color transfer, Table 4-5 */
1120 switch (color_trc) {
1121 case 1: st->codecpar->color_trc = AVCOL_TRC_BT709; break;
1122 case 7: st->codecpar->color_trc = AVCOL_TRC_SMPTE240M; break;
1123 case 17: st->codecpar->color_trc = AVCOL_TRC_SMPTE428; break;
1125 /* color matrix, Table 4-6 */
1126 switch (color_matrix) {
1127 case 1: st->codecpar->color_space = AVCOL_SPC_BT709; break;
1128 case 6: st->codecpar->color_space = AVCOL_SPC_BT470BG; break;
1129 case 7: st->codecpar->color_space = AVCOL_SPC_SMPTE240M; break;
1130 case 9: st->codecpar->color_space = AVCOL_SPC_BT2020_NCL; break;
1133 av_log(c->fc, AV_LOG_TRACE, "\n");
1138 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1141 unsigned mov_field_order;
1142 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1144 if (c->fc->nb_streams < 1) // will happen with jp2 files
1146 st = c->fc->streams[c->fc->nb_streams-1];
1148 return AVERROR_INVALIDDATA;
1149 mov_field_order = avio_rb16(pb);
1150 if ((mov_field_order & 0xFF00) == 0x0100)
1151 decoded_field_order = AV_FIELD_PROGRESSIVE;
1152 else if ((mov_field_order & 0xFF00) == 0x0200) {
1153 switch (mov_field_order & 0xFF) {
1154 case 0x01: decoded_field_order = AV_FIELD_TT;
1156 case 0x06: decoded_field_order = AV_FIELD_BB;
1158 case 0x09: decoded_field_order = AV_FIELD_TB;
1160 case 0x0E: decoded_field_order = AV_FIELD_BT;
1164 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1165 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1167 st->codecpar->field_order = decoded_field_order;
1172 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1173 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1180 if (c->fc->nb_streams < 1) // will happen with jp2 files
1182 st= c->fc->streams[c->fc->nb_streams-1];
1183 size= (uint64_t)st->codecpar->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1184 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1185 return AVERROR_INVALIDDATA;
1186 if ((err = av_reallocp(&st->codecpar->extradata, size)) < 0) {
1187 st->codecpar->extradata_size = 0;
1190 buf = st->codecpar->extradata + st->codecpar->extradata_size;
1191 st->codecpar->extradata_size= size - AV_INPUT_BUFFER_PADDING_SIZE;
1192 AV_WB32( buf , atom.size + 8);
1193 AV_WL32( buf + 4, atom.type);
1195 err = ffio_read_size(pb, buf + 8, atom.size);
1202 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1207 if (c->fc->nb_streams < 1)
1209 st = c->fc->streams[c->fc->nb_streams-1];
1211 if ((uint64_t)atom.size > (1<<30))
1212 return AVERROR_INVALIDDATA;
1214 if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 || st->codecpar->codec_id == AV_CODEC_ID_QDMC) {
1215 // pass all frma atom to codec, needed at least for QDMC and QDM2
1216 av_free(st->codecpar->extradata);
1217 st->codecpar->extradata = av_mallocz(atom.size + AV_INPUT_BUFFER_PADDING_SIZE);
1218 if (!st->codecpar->extradata)
1219 return AVERROR(ENOMEM);
1220 st->codecpar->extradata_size = atom.size;
1222 ret = ffio_read_size(pb, st->codecpar->extradata, atom.size);
1225 } else if (atom.size > 8) { /* to read frma, esds atoms */
1226 if ((ret = mov_read_default(c, pb, atom)) < 0)
1229 avio_skip(pb, atom.size);
1234 * This function reads atom content and puts data in extradata without tag
1235 * nor size unlike mov_read_extradata.
1237 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1242 if (c->fc->nb_streams < 1)
1244 st = c->fc->streams[c->fc->nb_streams-1];
1246 if ((uint64_t)atom.size > (1<<30))
1247 return AVERROR_INVALIDDATA;
1249 if (atom.size >= 10) {
1250 // Broken files created by legacy versions of libavformat will
1251 // wrap a whole fiel atom inside of a glbl atom.
1252 unsigned size = avio_rb32(pb);
1253 unsigned type = avio_rl32(pb);
1254 avio_seek(pb, -8, SEEK_CUR);
1255 if (type == MKTAG('f','i','e','l') && size == atom.size)
1256 return mov_read_default(c, pb, atom);
1258 av_free(st->codecpar->extradata);
1259 st->codecpar->extradata = av_mallocz(atom.size + AV_INPUT_BUFFER_PADDING_SIZE);
1260 if (!st->codecpar->extradata)
1261 return AVERROR(ENOMEM);
1262 st->codecpar->extradata_size = atom.size;
1264 ret = ffio_read_size(pb, st->codecpar->extradata, atom.size);
1271 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1274 uint8_t profile_level;
1277 if (c->fc->nb_streams < 1)
1279 st = c->fc->streams[c->fc->nb_streams-1];
1281 if (atom.size >= (1<<28) || atom.size < 7)
1282 return AVERROR_INVALIDDATA;
1284 profile_level = avio_r8(pb);
1285 if ((profile_level & 0xf0) != 0xc0)
1288 av_free(st->codecpar->extradata);
1289 st->codecpar->extradata = av_mallocz(atom.size - 7 + AV_INPUT_BUFFER_PADDING_SIZE);
1290 if (!st->codecpar->extradata)
1291 return AVERROR(ENOMEM);
1292 st->codecpar->extradata_size = atom.size - 7;
1293 avio_seek(pb, 6, SEEK_CUR);
1295 ret = ffio_read_size(pb, st->codecpar->extradata, st->codecpar->extradata_size);
1303 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1304 * but can have extradata appended at the end after the 40 bytes belonging
1307 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1312 if (c->fc->nb_streams < 1)
1314 if (atom.size <= 40)
1316 st = c->fc->streams[c->fc->nb_streams-1];
1318 if ((uint64_t)atom.size > (1<<30))
1319 return AVERROR_INVALIDDATA;
1321 av_free(st->codecpar->extradata);
1322 st->codecpar->extradata = av_mallocz(atom.size - 40 + AV_INPUT_BUFFER_PADDING_SIZE);
1323 if (!st->codecpar->extradata)
1324 return AVERROR(ENOMEM);
1325 st->codecpar->extradata_size = atom.size - 40;
1328 ret = ffio_read_size(pb, st->codecpar->extradata, atom.size - 40);
1335 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1338 MOVStreamContext *sc;
1339 unsigned int i, entries;
1341 if (c->fc->nb_streams < 1)
1343 st = c->fc->streams[c->fc->nb_streams-1];
1346 avio_r8(pb); /* version */
1347 avio_rb24(pb); /* flags */
1349 entries = avio_rb32(pb);
1353 if (entries >= UINT_MAX/sizeof(int64_t))
1354 return AVERROR_INVALIDDATA;
1356 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1357 if (!sc->chunk_offsets)
1358 return AVERROR(ENOMEM);
1359 sc->chunk_count = entries;
1361 if (atom.type == MKTAG('s','t','c','o'))
1362 for (i = 0; i < entries && !pb->eof_reached; i++)
1363 sc->chunk_offsets[i] = avio_rb32(pb);
1364 else if (atom.type == MKTAG('c','o','6','4'))
1365 for (i = 0; i < entries && !pb->eof_reached; i++)
1366 sc->chunk_offsets[i] = avio_rb64(pb);
1368 return AVERROR_INVALIDDATA;
1370 sc->chunk_count = i;
1372 if (pb->eof_reached)
1379 * Compute codec id for 'lpcm' tag.
1380 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1382 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1389 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1392 static int mov_codec_id(AVStream *st, uint32_t format)
1394 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1397 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1398 (format & 0xFFFF) == 'T' + ('S' << 8)))
1399 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1401 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1402 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1403 } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
1404 /* skip old ASF MPEG-4 tag */
1405 format && format != MKTAG('m','p','4','s')) {
1406 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1408 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1410 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
1411 else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
1412 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1414 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
1418 st->codecpar->codec_tag = format;
1423 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1424 AVStream *st, MOVStreamContext *sc)
1426 uint8_t codec_name[32];
1427 unsigned int color_depth, len, j;
1428 int color_greyscale;
1431 avio_rb16(pb); /* version */
1432 avio_rb16(pb); /* revision level */
1433 avio_rb32(pb); /* vendor */
1434 avio_rb32(pb); /* temporal quality */
1435 avio_rb32(pb); /* spatial quality */
1437 st->codecpar->width = avio_rb16(pb); /* width */
1438 st->codecpar->height = avio_rb16(pb); /* height */
1440 avio_rb32(pb); /* horiz resolution */
1441 avio_rb32(pb); /* vert resolution */
1442 avio_rb32(pb); /* data size, always 0 */
1443 avio_rb16(pb); /* frames per samples */
1445 len = avio_r8(pb); /* codec name, pascal string */
1448 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1450 avio_skip(pb, 31 - len);
1453 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1455 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1456 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1457 st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
1458 /* Flash Media Server uses tag H.263 with Sorenson Spark */
1459 if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
1460 !memcmp(codec_name, "Sorenson H263", 13))
1461 st->codecpar->codec_id = AV_CODEC_ID_FLV1;
1463 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
1464 color_table_id = avio_rb16(pb); /* colortable id */
1465 av_log(c->fc, AV_LOG_TRACE, "depth %d, ctab id %d\n",
1466 st->codecpar->bits_per_coded_sample, color_table_id);
1467 /* figure out the palette situation */
1468 color_depth = st->codecpar->bits_per_coded_sample & 0x1F;
1469 color_greyscale = st->codecpar->bits_per_coded_sample & 0x20;
1471 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1472 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1473 /* for palette traversal */
1474 unsigned int color_start, color_count, color_end;
1475 unsigned char r, g, b;
1477 if (color_greyscale) {
1478 int color_index, color_dec;
1479 /* compute the greyscale palette */
1480 st->codecpar->bits_per_coded_sample = color_depth;
1481 color_count = 1 << color_depth;
1483 color_dec = 256 / (color_count - 1);
1484 for (j = 0; j < color_count; j++) {
1485 r = g = b = color_index;
1486 sc->palette[j] = (r << 16) | (g << 8) | (b);
1487 color_index -= color_dec;
1488 if (color_index < 0)
1491 } else if (color_table_id) {
1492 const uint8_t *color_table;
1493 /* if flag bit 3 is set, use the default palette */
1494 color_count = 1 << color_depth;
1495 if (color_depth == 2)
1496 color_table = ff_qt_default_palette_4;
1497 else if (color_depth == 4)
1498 color_table = ff_qt_default_palette_16;
1500 color_table = ff_qt_default_palette_256;
1502 for (j = 0; j < color_count; j++) {
1503 r = color_table[j * 3 + 0];
1504 g = color_table[j * 3 + 1];
1505 b = color_table[j * 3 + 2];
1506 sc->palette[j] = (r << 16) | (g << 8) | (b);
1509 /* load the palette from the file */
1510 color_start = avio_rb32(pb);
1511 color_count = avio_rb16(pb);
1512 color_end = avio_rb16(pb);
1513 if ((color_start <= 255) && (color_end <= 255)) {
1514 for (j = color_start; j <= color_end; j++) {
1515 /* each R, G, or B component is 16 bits;
1516 * only use the top 8 bits; skip alpha bytes
1526 sc->palette[j] = (r << 16) | (g << 8) | (b);
1530 sc->has_palette = 1;
1534 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1535 AVStream *st, MOVStreamContext *sc)
1537 int bits_per_sample, flags;
1538 uint16_t version = avio_rb16(pb);
1540 avio_rb16(pb); /* revision level */
1541 avio_rb32(pb); /* vendor */
1543 st->codecpar->channels = avio_rb16(pb); /* channel count */
1544 st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1545 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
1547 sc->audio_cid = avio_rb16(pb);
1548 avio_rb16(pb); /* packet size = 0 */
1550 st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
1552 // Read QT version 1 fields. In version 0 these do not exist.
1553 av_log(c->fc, AV_LOG_TRACE, "version =%"PRIu16", isom =%d\n", version, c->isom);
1556 sc->samples_per_frame = avio_rb32(pb);
1557 avio_rb32(pb); /* bytes per packet */
1558 sc->bytes_per_frame = avio_rb32(pb);
1559 avio_rb32(pb); /* bytes per sample */
1560 } else if (version == 2) {
1561 avio_rb32(pb); /* sizeof struct only */
1562 st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
1563 st->codecpar->channels = avio_rb32(pb);
1564 avio_rb32(pb); /* always 0x7F000000 */
1565 st->codecpar->bits_per_coded_sample = avio_rb32(pb);
1567 flags = avio_rb32(pb); /* lpcm format specific flag */
1568 sc->bytes_per_frame = avio_rb32(pb);
1569 sc->samples_per_frame = avio_rb32(pb);
1570 if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
1571 st->codecpar->codec_id =
1572 ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
1575 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1576 /* can't correctly handle variable sized packet as audio unit */
1577 switch (st->codecpar->codec_id) {
1578 case AV_CODEC_ID_MP2:
1579 case AV_CODEC_ID_MP3:
1580 st->need_parsing = AVSTREAM_PARSE_FULL;
1586 switch (st->codecpar->codec_id) {
1587 case AV_CODEC_ID_PCM_S8:
1588 case AV_CODEC_ID_PCM_U8:
1589 if (st->codecpar->bits_per_coded_sample == 16)
1590 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
1592 case AV_CODEC_ID_PCM_S16LE:
1593 case AV_CODEC_ID_PCM_S16BE:
1594 if (st->codecpar->bits_per_coded_sample == 8)
1595 st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
1596 else if (st->codecpar->bits_per_coded_sample == 24)
1597 st->codecpar->codec_id =
1598 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
1599 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1601 /* set values for old format before stsd version 1 appeared */
1602 case AV_CODEC_ID_MACE3:
1603 sc->samples_per_frame = 6;
1604 sc->bytes_per_frame = 2 * st->codecpar->channels;
1606 case AV_CODEC_ID_MACE6:
1607 sc->samples_per_frame = 6;
1608 sc->bytes_per_frame = 1 * st->codecpar->channels;
1610 case AV_CODEC_ID_ADPCM_IMA_QT:
1611 sc->samples_per_frame = 64;
1612 sc->bytes_per_frame = 34 * st->codecpar->channels;
1614 case AV_CODEC_ID_GSM:
1615 sc->samples_per_frame = 160;
1616 sc->bytes_per_frame = 33;
1622 bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
1623 if (bits_per_sample) {
1624 st->codecpar->bits_per_coded_sample = bits_per_sample;
1625 sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
1629 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1630 AVStream *st, MOVStreamContext *sc,
1633 // ttxt stsd contains display flags, justification, background
1634 // color, fonts, and default styles, so fake an atom to read it
1635 MOVAtom fake_atom = { .size = size };
1636 // mp4s contains a regular esds atom
1637 if (st->codecpar->codec_tag != AV_RL32("mp4s"))
1638 mov_read_glbl(c, pb, fake_atom);
1639 st->codecpar->width = sc->width;
1640 st->codecpar->height = sc->height;
1643 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1648 y = (ycbcr >> 16) & 0xFF;
1649 cr = (ycbcr >> 8) & 0xFF;
1652 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1653 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1654 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1656 return (r << 16) | (g << 8) | b;
1659 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1661 char buf[256] = {0};
1662 uint8_t *src = st->codecpar->extradata;
1665 if (st->codecpar->extradata_size != 64)
1668 if (st->codecpar->width > 0 && st->codecpar->height > 0)
1669 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1670 st->codecpar->width, st->codecpar->height);
1671 av_strlcat(buf, "palette: ", sizeof(buf));
1673 for (i = 0; i < 16; i++) {
1674 uint32_t yuv = AV_RB32(src + i * 4);
1675 uint32_t rgba = yuv_to_rgba(yuv);
1677 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1680 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1683 av_freep(&st->codecpar->extradata);
1684 st->codecpar->extradata_size = 0;
1685 st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
1686 if (!st->codecpar->extradata)
1687 return AVERROR(ENOMEM);
1688 st->codecpar->extradata_size = strlen(buf);
1689 memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
1694 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1695 AVStream *st, MOVStreamContext *sc,
1700 if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
1701 st->codecpar->extradata_size = size;
1702 st->codecpar->extradata = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
1703 if (!st->codecpar->extradata)
1704 return AVERROR(ENOMEM);
1705 ret = ffio_read_size(pb, st->codecpar->extradata, size);
1709 /* other codec type, just skip (rtp, mp4s ...) */
1710 avio_skip(pb, size);
1715 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1716 AVStream *st, MOVStreamContext *sc)
1718 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1719 !st->codecpar->sample_rate && sc->time_scale > 1)
1720 st->codecpar->sample_rate = sc->time_scale;
1722 /* special codec parameters handling */
1723 switch (st->codecpar->codec_id) {
1724 #if CONFIG_DV_DEMUXER
1725 case AV_CODEC_ID_DVAUDIO:
1726 c->dv_fctx = avformat_alloc_context();
1728 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
1729 return AVERROR(ENOMEM);
1731 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1733 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1734 return AVERROR(ENOMEM);
1736 sc->dv_audio_container = 1;
1737 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
1740 /* no ifdef since parameters are always those */
1741 case AV_CODEC_ID_QCELP:
1742 st->codecpar->channels = 1;
1743 // force sample rate for qcelp when not stored in mov
1744 if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
1745 st->codecpar->sample_rate = 8000;
1747 case AV_CODEC_ID_AMR_NB:
1748 st->codecpar->channels = 1;
1749 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1750 st->codecpar->sample_rate = 8000;
1752 case AV_CODEC_ID_AMR_WB:
1753 st->codecpar->channels = 1;
1754 st->codecpar->sample_rate = 16000;
1756 case AV_CODEC_ID_MP2:
1757 case AV_CODEC_ID_MP3:
1758 /* force type after stsd for m1a hdlr */
1759 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1761 case AV_CODEC_ID_GSM:
1762 case AV_CODEC_ID_ADPCM_MS:
1763 case AV_CODEC_ID_ADPCM_IMA_WAV:
1764 case AV_CODEC_ID_ILBC:
1765 st->codecpar->block_align = sc->bytes_per_frame;
1767 case AV_CODEC_ID_ALAC:
1768 if (st->codecpar->extradata_size == 36) {
1769 st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
1770 st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
1773 case AV_CODEC_ID_VC1:
1774 st->need_parsing = AVSTREAM_PARSE_FULL;
1782 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1783 int codec_tag, int format,
1786 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1789 (codec_tag != format &&
1790 // prores is allowed to have differing data format and codec tag
1791 codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
1793 codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
1794 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1795 : codec_tag != MKTAG('j','p','e','g')))) {
1796 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1797 * export it as a separate AVStream but this needs a few changes
1798 * in the MOV demuxer, patch welcome. */
1800 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1801 avio_skip(pb, size);
1808 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1811 MOVStreamContext *sc;
1812 int pseudo_stream_id;
1814 if (c->fc->nb_streams < 1)
1816 st = c->fc->streams[c->fc->nb_streams-1];
1819 for (pseudo_stream_id = 0;
1820 pseudo_stream_id < entries && !pb->eof_reached;
1821 pseudo_stream_id++) {
1822 //Parsing Sample description table
1824 int ret, dref_id = 1;
1825 MOVAtom a = { AV_RL32("stsd") };
1826 int64_t start_pos = avio_tell(pb);
1827 int64_t size = avio_rb32(pb); /* size */
1828 uint32_t format = avio_rl32(pb); /* data format */
1831 avio_rb32(pb); /* reserved */
1832 avio_rb16(pb); /* reserved */
1833 dref_id = avio_rb16(pb);
1835 av_log(c->fc, AV_LOG_ERROR,
1836 "invalid size %"PRId64" in stsd\n", size);
1837 return AVERROR_INVALIDDATA;
1840 if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
1841 size - (avio_tell(pb) - start_pos)))
1844 sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
1845 sc->dref_id= dref_id;
1847 id = mov_codec_id(st, format);
1849 av_log(c->fc, AV_LOG_TRACE,
1850 "size=%"PRId64" format=0x%08"PRIx32" codec_type=%d\n",
1851 size, format, st->codecpar->codec_type);
1853 if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
1854 st->codecpar->codec_id = id;
1855 mov_parse_stsd_video(c, pb, st, sc);
1856 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
1857 st->codecpar->codec_id = id;
1858 mov_parse_stsd_audio(c, pb, st, sc);
1859 } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
1860 st->codecpar->codec_id = id;
1861 mov_parse_stsd_subtitle(c, pb, st, sc,
1862 size - (avio_tell(pb) - start_pos));
1864 ret = mov_parse_stsd_data(c, pb, st, sc,
1865 size - (avio_tell(pb) - start_pos));
1869 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1870 a.size = size - (avio_tell(pb) - start_pos);
1872 if ((ret = mov_read_default(c, pb, a)) < 0)
1874 } else if (a.size > 0)
1875 avio_skip(pb, a.size);
1877 if (sc->extradata) {
1878 int extra_size = st->codecpar->extradata_size;
1880 /* Move the current stream extradata to the stream context one. */
1881 sc->extradata_size[pseudo_stream_id] = extra_size;
1882 sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
1883 if (!sc->extradata[pseudo_stream_id])
1884 return AVERROR(ENOMEM);
1885 memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
1886 av_freep(&st->codecpar->extradata);
1887 st->codecpar->extradata_size = 0;
1891 if (pb->eof_reached)
1894 return mov_finalize_stsd_codec(c, pb, st, sc);
1897 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1900 MOVStreamContext *sc;
1903 if (c->fc->nb_streams < 1)
1905 st = c->fc->streams[c->fc->nb_streams - 1];
1908 avio_r8(pb); /* version */
1909 avio_rb24(pb); /* flags */
1910 entries = avio_rb32(pb);
1912 /* Prepare space for hosting multiple extradata. */
1913 sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
1915 return AVERROR(ENOMEM);
1917 sc->stsd_count = entries;
1918 sc->extradata_size = av_mallocz_array(sc->stsd_count, sizeof(*sc->extradata_size));
1919 if (!sc->extradata_size)
1920 return AVERROR(ENOMEM);
1922 ret = ff_mov_read_stsd_entries(c, pb, sc->stsd_count);
1926 /* Restore back the primary extradata. */
1927 av_free(st->codecpar->extradata);
1928 st->codecpar->extradata_size = sc->extradata_size[0];
1929 st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
1930 if (!st->codecpar->extradata)
1931 return AVERROR(ENOMEM);
1932 memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
1937 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1940 MOVStreamContext *sc;
1941 unsigned int i, entries;
1943 if (c->fc->nb_streams < 1)
1945 st = c->fc->streams[c->fc->nb_streams-1];
1948 avio_r8(pb); /* version */
1949 avio_rb24(pb); /* flags */
1951 entries = avio_rb32(pb);
1953 av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
1957 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1958 return AVERROR_INVALIDDATA;
1959 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1961 return AVERROR(ENOMEM);
1963 for (i = 0; i < entries && !pb->eof_reached; i++) {
1964 sc->stsc_data[i].first = avio_rb32(pb);
1965 sc->stsc_data[i].count = avio_rb32(pb);
1966 sc->stsc_data[i].id = avio_rb32(pb);
1967 if (sc->stsc_data[i].id <= 0 || sc->stsc_data[i].id > sc->stsd_count) {
1968 sc->stsc_data[i].id = 1;
1969 if (c->fc->error_recognition & AV_EF_EXPLODE) {
1970 av_log(c->fc, AV_LOG_ERROR, "Invalid stsc index.\n");
1971 return AVERROR_INVALIDDATA;
1978 if (pb->eof_reached)
1984 static inline int mov_stsc_index_valid(int index, int count)
1986 return index + 1 < count;
1989 /* Compute the samples value for the stsc entry at the given index. */
1990 static inline int mov_get_stsc_samples(MOVStreamContext *sc, int index)
1994 if (mov_stsc_index_valid(index, sc->stsc_count))
1995 chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
1997 chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
1999 return sc->stsc_data[index].count * chunk_count;
2002 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2005 MOVStreamContext *sc;
2006 unsigned i, entries;
2008 if (c->fc->nb_streams < 1)
2010 st = c->fc->streams[c->fc->nb_streams-1];
2013 avio_rb32(pb); // version + flags
2015 entries = avio_rb32(pb);
2016 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
2017 return AVERROR_INVALIDDATA;
2018 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
2020 return AVERROR(ENOMEM);
2022 for (i = 0; i < entries && !pb->eof_reached; i++) {
2023 sc->stps_data[i] = avio_rb32(pb);
2028 if (pb->eof_reached)
2034 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2037 MOVStreamContext *sc;
2038 unsigned int i, entries;
2040 if (c->fc->nb_streams < 1)
2042 st = c->fc->streams[c->fc->nb_streams-1];
2045 avio_r8(pb); /* version */
2046 avio_rb24(pb); /* flags */
2048 entries = avio_rb32(pb);
2050 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
2054 sc->keyframe_absent = 1;
2057 if (entries >= UINT_MAX / sizeof(int))
2058 return AVERROR_INVALIDDATA;
2059 av_freep(&sc->keyframes);
2060 sc->keyframes = av_malloc(entries * sizeof(int));
2062 return AVERROR(ENOMEM);
2064 for (i = 0; i < entries && !pb->eof_reached; i++) {
2065 sc->keyframes[i] = avio_rb32(pb);
2068 sc->keyframe_count = i;
2070 if (pb->eof_reached)
2076 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2079 MOVStreamContext *sc;
2080 unsigned int i, entries, sample_size, field_size, num_bytes;
2085 if (c->fc->nb_streams < 1)
2087 st = c->fc->streams[c->fc->nb_streams-1];
2090 avio_r8(pb); /* version */
2091 avio_rb24(pb); /* flags */
2093 if (atom.type == MKTAG('s','t','s','z')) {
2094 sample_size = avio_rb32(pb);
2095 if (!sc->sample_size) /* do not overwrite value computed in stsd */
2096 sc->sample_size = sample_size;
2100 avio_rb24(pb); /* reserved */
2101 field_size = avio_r8(pb);
2103 entries = avio_rb32(pb);
2105 av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
2107 sc->sample_count = entries;
2111 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2112 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
2113 return AVERROR_INVALIDDATA;
2118 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
2119 return AVERROR_INVALIDDATA;
2120 sc->sample_sizes = av_malloc(entries * sizeof(int));
2121 if (!sc->sample_sizes)
2122 return AVERROR(ENOMEM);
2124 num_bytes = (entries*field_size+4)>>3;
2126 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2128 av_freep(&sc->sample_sizes);
2129 return AVERROR(ENOMEM);
2132 ret = ffio_read_size(pb, buf, num_bytes);
2134 av_freep(&sc->sample_sizes);
2139 init_get_bits(&gb, buf, 8*num_bytes);
2141 for (i = 0; i < entries && !pb->eof_reached; i++) {
2142 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2143 sc->data_size += sc->sample_sizes[i];
2146 sc->sample_count = i;
2150 if (pb->eof_reached)
2156 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2159 MOVStreamContext *sc;
2160 unsigned int i, entries;
2162 int64_t total_sample_count=0;
2164 if (c->fc->nb_streams < 1)
2166 st = c->fc->streams[c->fc->nb_streams-1];
2169 avio_r8(pb); /* version */
2170 avio_rb24(pb); /* flags */
2171 entries = avio_rb32(pb);
2173 av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
2174 c->fc->nb_streams-1, entries);
2178 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
2179 return AVERROR(EINVAL);
2181 av_free(sc->stts_data);
2182 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
2184 return AVERROR(ENOMEM);
2186 for (i = 0; i < entries && !pb->eof_reached; i++) {
2187 int sample_duration;
2190 sample_count=avio_rb32(pb);
2191 sample_duration = avio_rb32(pb);
2192 if (sample_count < 0) {
2193 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2194 return AVERROR_INVALIDDATA;
2196 sc->stts_data[i].count= sample_count;
2197 sc->stts_data[i].duration= sample_duration;
2199 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2200 sample_count, sample_duration);
2202 duration+=(int64_t)sample_duration*sample_count;
2203 total_sample_count+=sample_count;
2208 if (pb->eof_reached)
2211 st->nb_frames= total_sample_count;
2213 st->duration= duration;
2214 sc->track_end = duration;
2218 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2221 MOVStreamContext *sc;
2222 unsigned int i, entries;
2224 if (c->fc->nb_streams < 1)
2226 st = c->fc->streams[c->fc->nb_streams-1];
2229 avio_r8(pb); /* version */
2230 avio_rb24(pb); /* flags */
2231 entries = avio_rb32(pb);
2233 av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
2235 av_freep(&sc->ctts_data);
2239 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2240 return AVERROR_INVALIDDATA;
2241 sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2243 return AVERROR(ENOMEM);
2245 for (i = 0; i < entries && !pb->eof_reached; i++) {
2246 int count =avio_rb32(pb);
2247 int duration =avio_rb32(pb);
2249 sc->ctts_data[i].count = count;
2250 sc->ctts_data[i].duration= duration;
2252 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2257 if (pb->eof_reached)
2260 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2265 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2268 MOVStreamContext *sc;
2269 unsigned int i, entries;
2271 uint32_t grouping_type;
2273 if (c->fc->nb_streams < 1)
2275 st = c->fc->streams[c->fc->nb_streams-1];
2278 version = avio_r8(pb); /* version */
2279 avio_rb24(pb); /* flags */
2280 grouping_type = avio_rl32(pb);
2281 if (grouping_type != MKTAG( 'r','a','p',' '))
2282 return 0; /* only support 'rap ' grouping */
2284 avio_rb32(pb); /* grouping_type_parameter */
2286 entries = avio_rb32(pb);
2289 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2290 return AVERROR_INVALIDDATA;
2291 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2293 return AVERROR(ENOMEM);
2295 for (i = 0; i < entries && !pb->eof_reached; i++) {
2296 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2297 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2300 sc->rap_group_count = i;
2302 return pb->eof_reached ? AVERROR_EOF : 0;
2305 static void mov_build_index(MOVContext *mov, AVStream *st)
2307 MOVStreamContext *sc = st->priv_data;
2308 int64_t current_offset;
2309 int64_t current_dts = 0;
2310 unsigned int stts_index = 0;
2311 unsigned int stsc_index = 0;
2312 unsigned int stss_index = 0;
2313 unsigned int stps_index = 0;
2315 uint64_t stream_size = 0;
2317 /* adjust first dts according to edit list */
2318 if (sc->time_offset && mov->time_scale > 0) {
2319 if (sc->time_offset < 0)
2320 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
2321 current_dts = -sc->time_offset;
2324 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2325 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2326 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2327 unsigned int current_sample = 0;
2328 unsigned int stts_sample = 0;
2329 unsigned int sample_size;
2330 unsigned int distance = 0;
2331 unsigned int rap_group_index = 0;
2332 unsigned int rap_group_sample = 0;
2333 int rap_group_present = sc->rap_group_count && sc->rap_group;
2334 int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
2336 current_dts -= sc->dts_shift;
2338 if (!sc->sample_count)
2340 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2342 if (av_reallocp_array(&st->index_entries,
2343 st->nb_index_entries + sc->sample_count,
2344 sizeof(*st->index_entries)) < 0) {
2345 st->nb_index_entries = 0;
2348 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2350 for (i = 0; i < sc->chunk_count; i++) {
2351 current_offset = sc->chunk_offsets[i];
2352 while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
2353 i + 1 == sc->stsc_data[stsc_index + 1].first)
2355 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2357 if (current_sample >= sc->sample_count) {
2358 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2362 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2364 if (stss_index + 1 < sc->keyframe_count)
2366 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2368 if (stps_index + 1 < sc->stps_count)
2371 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2372 if (sc->rap_group[rap_group_index].index > 0)
2374 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2375 rap_group_sample = 0;
2381 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
2382 if (sc->pseudo_stream_id == -1 ||
2383 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2384 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2385 e->pos = current_offset;
2386 e->timestamp = current_dts;
2387 e->size = sample_size;
2388 e->min_distance = distance;
2389 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2390 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
2391 "size %u, distance %u, keyframe %d\n", st->index, current_sample,
2392 current_offset, current_dts, sample_size, distance, keyframe);
2395 current_offset += sample_size;
2396 stream_size += sample_size;
2397 current_dts += sc->stts_data[stts_index].duration;
2401 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2407 if (st->duration > 0)
2408 st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
2410 unsigned chunk_samples, total = 0;
2412 // compute total chunk count
2413 for (i = 0; i < sc->stsc_count; i++) {
2414 unsigned count, chunk_count;
2416 chunk_samples = sc->stsc_data[i].count;
2417 if (i != sc->stsc_count - 1 &&
2418 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2419 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2423 if (sc->samples_per_frame >= 160) { // gsm
2424 count = chunk_samples / sc->samples_per_frame;
2425 } else if (sc->samples_per_frame > 1) {
2426 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2427 count = (chunk_samples+samples-1) / samples;
2429 count = (chunk_samples+1023) / 1024;
2432 if (mov_stsc_index_valid(i, sc->stsc_count))
2433 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2435 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2436 total += chunk_count * count;
2439 av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
2440 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2442 if (av_reallocp_array(&st->index_entries,
2443 st->nb_index_entries + total,
2444 sizeof(*st->index_entries)) < 0) {
2445 st->nb_index_entries = 0;
2448 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2451 for (i = 0; i < sc->chunk_count; i++) {
2452 current_offset = sc->chunk_offsets[i];
2453 if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
2454 i + 1 == sc->stsc_data[stsc_index + 1].first)
2456 chunk_samples = sc->stsc_data[stsc_index].count;
2458 while (chunk_samples > 0) {
2460 unsigned size, samples;
2462 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2463 avpriv_request_sample(mov->fc,
2464 "Zero bytes per frame, but %d samples per frame",
2465 sc->samples_per_frame);
2469 if (sc->samples_per_frame >= 160) { // gsm
2470 samples = sc->samples_per_frame;
2471 size = sc->bytes_per_frame;
2473 if (sc->samples_per_frame > 1) {
2474 samples = FFMIN((1024 / sc->samples_per_frame)*
2475 sc->samples_per_frame, chunk_samples);
2476 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2478 samples = FFMIN(1024, chunk_samples);
2479 size = samples * sc->sample_size;
2483 if (st->nb_index_entries >= total) {
2484 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
2487 e = &st->index_entries[st->nb_index_entries++];
2488 e->pos = current_offset;
2489 e->timestamp = current_dts;
2491 e->min_distance = 0;
2492 e->flags = AVINDEX_KEYFRAME;
2493 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
2494 "size %u, duration %u\n", st->index, i, current_offset, current_dts,
2497 current_offset += size;
2498 current_dts += samples;
2499 chunk_samples -= samples;
2505 static int mov_open_dref(AVFormatContext *s, AVIOContext **pb, char *src,
2508 /* try relative path, we do not try the absolute because it can leak information about our
2509 system to an attacker */
2510 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2511 char filename[1024];
2515 /* find a source dir */
2516 src_path = strrchr(src, '/');
2522 /* find a next level down to target */
2523 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2524 if (ref->path[l] == '/') {
2525 if (i == ref->nlvl_to - 1)
2531 /* compose filename if next level down to target was found */
2532 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2533 memcpy(filename, src, src_path - src);
2534 filename[src_path - src] = 0;
2536 for (i = 1; i < ref->nlvl_from; i++)
2537 av_strlcat(filename, "../", 1024);
2539 av_strlcat(filename, ref->path + l + 1, 1024);
2541 if (!s->io_open(s, pb, filename, AVIO_FLAG_READ, NULL))
2546 return AVERROR(ENOENT);
2549 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2552 MOVStreamContext *sc;
2555 st = avformat_new_stream(c->fc, NULL);
2556 if (!st) return AVERROR(ENOMEM);
2557 st->id = c->fc->nb_streams;
2558 sc = av_mallocz(sizeof(MOVStreamContext));
2559 if (!sc) return AVERROR(ENOMEM);
2562 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2563 sc->ffindex = st->index;
2565 if ((ret = mov_read_default(c, pb, atom)) < 0)
2569 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2570 (!sc->sample_size && !sc->sample_count))) {
2571 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2576 if (sc->time_scale <= 0) {
2577 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2578 sc->time_scale = c->time_scale;
2579 if (sc->time_scale <= 0)
2583 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2585 mov_build_index(c, st);
2587 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2588 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2589 if (c->enable_drefs) {
2590 if (mov_open_dref(c->fc, &sc->pb, c->fc->filename, dref) < 0)
2591 av_log(c->fc, AV_LOG_ERROR,
2592 "stream %d, error opening alias: path='%s', dir='%s', "
2593 "filename='%s', volume='%s', nlvl_from=%"PRId16", nlvl_to=%"PRId16"\n",
2594 st->index, dref->path, dref->dir, dref->filename,
2595 dref->volume, dref->nlvl_from, dref->nlvl_to);
2597 av_log(c->fc, AV_LOG_WARNING,
2598 "Skipped opening external track: "
2599 "stream %d, alias: path='%s', dir='%s', "
2600 "filename='%s', volume='%s', nlvl_from=%"PRId16", nlvl_to=%"PRId16"."
2601 "Set enable_drefs to allow this.\n",
2602 st->index, dref->path, dref->dir, dref->filename,
2603 dref->volume, dref->nlvl_from, dref->nlvl_to);
2608 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2609 if (!st->sample_aspect_ratio.num &&
2610 (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
2611 st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
2612 ((double)st->codecpar->width * sc->height), INT_MAX);
2616 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2617 if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
2618 TAG_IS_AVCI(st->codecpar->codec_tag)) {
2619 ret = ff_generate_avci_extradata(st);
2624 switch (st->codecpar->codec_id) {
2625 #if CONFIG_H261_DECODER
2626 case AV_CODEC_ID_H261:
2628 #if CONFIG_H263_DECODER
2629 case AV_CODEC_ID_H263:
2631 #if CONFIG_MPEG4_DECODER
2632 case AV_CODEC_ID_MPEG4:
2634 st->codecpar->width = 0; /* let decoder init width/height */
2635 st->codecpar->height= 0;
2637 case AV_CODEC_ID_MP3:
2638 st->need_parsing = AVSTREAM_PARSE_FULL;
2642 /* Do not need those anymore. */
2643 av_freep(&sc->chunk_offsets);
2644 av_freep(&sc->sample_sizes);
2645 av_freep(&sc->keyframes);
2646 av_freep(&sc->stts_data);
2647 av_freep(&sc->stps_data);
2648 av_freep(&sc->rap_group);
2653 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2656 c->itunes_metadata = 1;
2657 ret = mov_read_default(c, pb, atom);
2658 c->itunes_metadata = 0;
2662 static int mov_read_replaygain(MOVContext *c, AVIOContext *pb, int64_t size)
2664 int64_t end = avio_tell(pb) + size;
2665 uint8_t *key = NULL, *val = NULL;
2668 for (i = 0; i < 2; i++) {
2673 if (end - avio_tell(pb) <= 12)
2676 len = avio_rb32(pb);
2677 tag = avio_rl32(pb);
2678 avio_skip(pb, 4); // flags
2680 if (len < 12 || len - 12 > end - avio_tell(pb))
2684 if (tag == MKTAG('n', 'a', 'm', 'e'))
2686 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2693 *p = av_malloc(len + 1);
2696 ret = ffio_read_size(pb, *p, len);
2705 av_dict_set(&c->fc->metadata, key, val,
2706 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2710 avio_seek(pb, end, SEEK_SET);
2716 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2718 int64_t end = avio_tell(pb) + atom.size;
2724 len = avio_rb32(pb);
2725 tag = avio_rl32(pb);
2727 if (len > atom.size)
2730 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2731 uint8_t domain[128];
2734 avio_skip(pb, 4); // flags
2737 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2738 avio_skip(pb, len - domain_len);
2739 if (!strcmp(domain, "org.hydrogenaudio.replaygain"))
2740 return mov_read_replaygain(c, pb, end - avio_tell(pb));
2744 av_log(c->fc, AV_LOG_VERBOSE,
2745 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2749 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2751 while (atom.size > 8) {
2752 uint32_t tag = avio_rl32(pb);
2754 if (tag == MKTAG('h','d','l','r')) {
2755 avio_seek(pb, -8, SEEK_CUR);
2757 return mov_read_default(c, pb, atom);
2763 // return 1 when matrix is identity, 0 otherwise
2764 #define IS_MATRIX_IDENT(matrix) \
2765 ( (matrix)[0][0] == (1 << 16) && \
2766 (matrix)[1][1] == (1 << 16) && \
2767 (matrix)[2][2] == (1 << 30) && \
2768 !(matrix)[0][1] && !(matrix)[0][2] && \
2769 !(matrix)[1][0] && !(matrix)[1][2] && \
2770 !(matrix)[2][0] && !(matrix)[2][1])
2772 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2777 int64_t disp_transform[2];
2778 int display_matrix[3][3];
2779 int res_display_matrix[3][3] = { { 0 } };
2781 MOVStreamContext *sc;
2785 if (c->fc->nb_streams < 1)
2787 st = c->fc->streams[c->fc->nb_streams-1];
2790 version = avio_r8(pb);
2791 flags = avio_rb24(pb);
2792 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2798 avio_rb32(pb); /* creation time */
2799 avio_rb32(pb); /* modification time */
2801 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2802 avio_rb32(pb); /* reserved */
2804 /* highlevel (considering edits) duration in movie timebase */
2805 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2806 avio_rb32(pb); /* reserved */
2807 avio_rb32(pb); /* reserved */
2809 avio_rb16(pb); /* layer */
2810 avio_rb16(pb); /* alternate group */
2811 avio_rb16(pb); /* volume */
2812 avio_rb16(pb); /* reserved */
2814 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2815 // they're kept in fixed point format through all calculations
2816 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2817 // side data, but the scale factor is not needed to calculate aspect ratio
2818 for (i = 0; i < 3; i++) {
2819 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2820 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2821 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2824 width = avio_rb32(pb); // 16.16 fixed point track width
2825 height = avio_rb32(pb); // 16.16 fixed point track height
2826 sc->width = width >> 16;
2827 sc->height = height >> 16;
2829 // apply the moov display matrix (after the tkhd one)
2830 for (i = 0; i < 3; i++) {
2831 const int sh[3] = { 16, 16, 30 };
2832 for (j = 0; j < 3; j++) {
2833 for (e = 0; e < 3; e++) {
2834 res_display_matrix[i][j] +=
2835 ((int64_t) display_matrix[i][e] *
2836 c->movie_display_matrix[e][j]) >> sh[e];
2841 // save the matrix when it is not the default identity
2842 if (!IS_MATRIX_IDENT(res_display_matrix)) {
2843 av_freep(&sc->display_matrix);
2844 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2845 if (!sc->display_matrix)
2846 return AVERROR(ENOMEM);
2848 for (i = 0; i < 3; i++)
2849 for (j = 0; j < 3; j++)
2850 sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
2853 // transform the display width/height according to the matrix
2854 // skip this when the display matrix is the identity one
2855 // to keep the same scale, use [width height 1<<16]
2856 if (width && height && sc->display_matrix) {
2857 for (i = 0; i < 2; i++)
2859 (int64_t) width * sc->display_matrix[0 + i] +
2860 (int64_t) height * sc->display_matrix[3 + i] +
2861 ((int64_t) sc->display_matrix[6 + i] << 16);
2863 //sample aspect ratio is new width/height divided by old width/height
2864 if (disp_transform[0] > 0 && disp_transform[1] > 0)
2865 st->sample_aspect_ratio = av_d2q(
2866 ((double) disp_transform[0] * height) /
2867 ((double) disp_transform[1] * width), INT_MAX);
2872 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2874 MOVFragment *frag = &c->fragment;
2875 MOVTrackExt *trex = NULL;
2876 int flags, track_id, i;
2878 avio_r8(pb); /* version */
2879 flags = avio_rb24(pb);
2881 track_id = avio_rb32(pb);
2883 return AVERROR_INVALIDDATA;
2884 frag->track_id = track_id;
2885 for (i = 0; i < c->trex_count; i++)
2886 if (c->trex_data[i].track_id == frag->track_id) {
2887 trex = &c->trex_data[i];
2891 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2892 return AVERROR_INVALIDDATA;
2895 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2896 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
2897 frag->moof_offset : frag->implicit_offset;
2898 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2900 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2901 avio_rb32(pb) : trex->duration;
2902 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2903 avio_rb32(pb) : trex->size;
2904 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2905 avio_rb32(pb) : trex->flags;
2906 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
2910 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2912 c->chapter_track = avio_rb32(pb);
2916 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2921 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2922 return AVERROR_INVALIDDATA;
2923 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2924 sizeof(*c->trex_data))) < 0) {
2928 trex = &c->trex_data[c->trex_count++];
2929 avio_r8(pb); /* version */
2930 avio_rb24(pb); /* flags */
2931 trex->track_id = avio_rb32(pb);
2932 trex->stsd_id = avio_rb32(pb);
2933 trex->duration = avio_rb32(pb);
2934 trex->size = avio_rb32(pb);
2935 trex->flags = avio_rb32(pb);
2939 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2941 MOVFragment *frag = &c->fragment;
2942 AVStream *st = NULL;
2943 MOVStreamContext *sc;
2946 for (i = 0; i < c->fc->nb_streams; i++) {
2947 if (c->fc->streams[i]->id == frag->track_id) {
2948 st = c->fc->streams[i];
2953 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
2954 return AVERROR_INVALIDDATA;
2957 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
2959 version = avio_r8(pb);
2960 avio_rb24(pb); /* flags */
2962 sc->track_end = avio_rb64(pb);
2964 sc->track_end = avio_rb32(pb);
2969 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2971 MOVFragment *frag = &c->fragment;
2972 AVStream *st = NULL;
2973 MOVStreamContext *sc;
2977 int data_offset = 0;
2978 unsigned entries, first_sample_flags = frag->flags;
2979 int flags, distance, i, err;
2981 for (i = 0; i < c->fc->nb_streams; i++) {
2982 if (c->fc->streams[i]->id == frag->track_id) {
2983 st = c->fc->streams[i];
2988 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
2989 return AVERROR_INVALIDDATA;
2992 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2994 avio_r8(pb); /* version */
2995 flags = avio_rb24(pb);
2996 entries = avio_rb32(pb);
2997 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
2999 /* Always assume the presence of composition time offsets.
3000 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3001 * 1) in the initial movie, there are no samples.
3002 * 2) in the first movie fragment, there is only one sample without composition time offset.
3003 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
3004 if (!sc->ctts_count && sc->sample_count)
3006 /* Complement ctts table if moov atom doesn't have ctts atom. */
3007 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3009 return AVERROR(ENOMEM);
3010 sc->ctts_data = ctts_data;
3011 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3012 sc->ctts_data[sc->ctts_count].duration = 0;
3015 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3016 return AVERROR_INVALIDDATA;
3017 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3018 sizeof(*sc->ctts_data))) < 0) {
3022 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
3023 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3024 dts = sc->track_end - sc->time_offset;
3025 offset = frag->base_data_offset + data_offset;
3027 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3028 for (i = 0; i < entries && !pb->eof_reached; i++) {
3029 unsigned sample_size = frag->size;
3030 int sample_flags = i ? frag->flags : first_sample_flags;
3031 unsigned sample_duration = frag->duration;
3034 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3035 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
3036 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
3037 sc->ctts_data[sc->ctts_count].count = 1;
3038 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3041 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
3045 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3046 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3049 av_add_index_entry(st, offset, dts, sample_size, distance,
3050 keyframe ? AVINDEX_KEYFRAME : 0);
3051 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
3052 "size %u, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3053 offset, dts, sample_size, distance, keyframe);
3055 dts += sample_duration;
3056 offset += sample_size;
3057 sc->data_size += sample_size;
3060 if (pb->eof_reached)
3063 frag->implicit_offset = offset;
3064 st->duration = sc->track_end = dts + sc->time_offset;
3068 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3069 /* like the files created with Adobe Premiere 5.0, for samples see */
3070 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3071 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3076 return 0; /* continue */
3077 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3078 avio_skip(pb, atom.size - 4);
3081 atom.type = avio_rl32(pb);
3083 if (atom.type != MKTAG('m','d','a','t')) {
3084 avio_skip(pb, atom.size);
3087 err = mov_read_mdat(c, pb, atom);
3091 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3096 uint8_t *moov_data; /* uncompressed data */
3097 long cmov_len, moov_len;
3100 avio_rb32(pb); /* dcom atom */
3101 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3102 return AVERROR_INVALIDDATA;
3103 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3104 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
3105 return AVERROR_INVALIDDATA;
3107 avio_rb32(pb); /* cmvd atom */
3108 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3109 return AVERROR_INVALIDDATA;
3110 moov_len = avio_rb32(pb); /* uncompressed size */
3111 cmov_len = atom.size - 6 * 4;
3113 cmov_data = av_malloc(cmov_len);
3115 return AVERROR(ENOMEM);
3116 moov_data = av_malloc(moov_len);
3119 return AVERROR(ENOMEM);
3121 ret = ffio_read_size(pb, cmov_data, cmov_len);
3123 goto free_and_return;
3125 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3126 goto free_and_return;
3127 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3128 goto free_and_return;
3129 atom.type = MKTAG('m','o','o','v');
3130 atom.size = moov_len;
3131 ret = mov_read_default(c, &ctx, atom);
3137 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3138 return AVERROR(ENOSYS);
3142 /* edit list atom */
3143 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3145 MOVStreamContext *sc;
3146 int i, edit_count, version;
3148 if (c->fc->nb_streams < 1)
3150 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3152 version = avio_r8(pb); /* version */
3153 avio_rb24(pb); /* flags */
3154 edit_count = avio_rb32(pb); /* entries */
3156 if ((uint64_t)edit_count*12+8 > atom.size)
3157 return AVERROR_INVALIDDATA;
3159 for (i=0; i<edit_count; i++){
3163 duration = avio_rb64(pb);
3164 time = avio_rb64(pb);
3166 duration = avio_rb32(pb); /* segment duration */
3167 time = (int32_t)avio_rb32(pb); /* media time */
3169 avio_rb32(pb); /* Media rate */
3170 if (i == 0 && time >= -1) {
3171 sc->time_offset = time != -1 ? time : -duration;
3176 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
3177 "a/v desync might occur, patch welcome\n");
3179 av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
3183 static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3186 MOVStreamContext *sc;
3187 enum AVStereo3DType type;
3190 if (c->fc->nb_streams < 1)
3193 st = c->fc->streams[c->fc->nb_streams - 1];
3196 if (atom.size < 5) {
3197 av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
3198 return AVERROR_INVALIDDATA;
3200 avio_skip(pb, 4); /* version + flags */
3205 type = AV_STEREO3D_2D;
3208 type = AV_STEREO3D_TOPBOTTOM;
3211 type = AV_STEREO3D_SIDEBYSIDE;
3214 av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
3218 sc->stereo3d = av_stereo3d_alloc();
3220 return AVERROR(ENOMEM);
3222 sc->stereo3d->type = type;
3226 static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3229 MOVStreamContext *sc;
3231 int32_t yaw, pitch, roll;
3233 enum AVSphericalProjection projection;
3235 if (c->fc->nb_streams < 1)
3238 st = c->fc->streams[c->fc->nb_streams - 1];
3241 if (atom.size < 8) {
3242 av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
3243 return AVERROR_INVALIDDATA;
3246 size = avio_rb32(pb);
3247 if (size > atom.size)
3248 return AVERROR_INVALIDDATA;
3250 tag = avio_rl32(pb);
3251 if (tag != MKTAG('s','v','h','d')) {
3252 av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
3255 avio_skip(pb, 4); /* version + flags */
3256 avio_skip(pb, avio_r8(pb)); /* metadata_source */
3258 size = avio_rb32(pb);
3259 if (size > atom.size)
3260 return AVERROR_INVALIDDATA;
3262 tag = avio_rl32(pb);
3263 if (tag != MKTAG('p','r','o','j')) {
3264 av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
3268 size = avio_rb32(pb);
3269 if (size > atom.size)
3270 return AVERROR_INVALIDDATA;
3272 tag = avio_rl32(pb);
3273 if (tag != MKTAG('p','r','h','d')) {
3274 av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
3277 avio_skip(pb, 4); /* version + flags */
3279 /* 16.16 fixed point */
3280 yaw = avio_rb32(pb);
3281 pitch = avio_rb32(pb);
3282 roll = avio_rb32(pb);
3284 size = avio_rb32(pb);
3285 if (size > atom.size)
3286 return AVERROR_INVALIDDATA;
3288 tag = avio_rl32(pb);
3289 avio_skip(pb, 4); /* version + flags */
3291 case MKTAG('c','b','m','p'):
3292 projection = AV_SPHERICAL_CUBEMAP;
3294 case MKTAG('e','q','u','i'):
3295 projection = AV_SPHERICAL_EQUIRECTANGULAR;
3298 av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n");
3302 sc->spherical = av_spherical_alloc(&sc->spherical_size);
3304 return AVERROR(ENOMEM);
3306 sc->spherical->projection = projection;
3308 sc->spherical->yaw = yaw;
3309 sc->spherical->pitch = pitch;
3310 sc->spherical->roll = roll;
3315 static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
3318 uint8_t *buffer = av_malloc(len + 1);
3322 return AVERROR(ENOMEM);
3325 ret = ffio_read_size(pb, buffer, len);
3329 /* Check for mandatory keys and values, try to support XML as best-effort */
3330 if (av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
3331 (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
3332 av_stristr(val, "true") &&
3333 (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
3334 av_stristr(val, "true") &&
3335 (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
3336 av_stristr(val, "equirectangular")) {
3337 sc->spherical = av_spherical_alloc(&sc->spherical_size);
3341 sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
3343 if (av_stristr(buffer, "<GSpherical:StereoMode>")) {
3344 enum AVStereo3DType mode;
3346 if (av_stristr(buffer, "left-right"))
3347 mode = AV_STEREO3D_SIDEBYSIDE;
3348 else if (av_stristr(buffer, "top-bottom"))
3349 mode = AV_STEREO3D_TOPBOTTOM;
3351 mode = AV_STEREO3D_2D;
3353 sc->stereo3d = av_stereo3d_alloc();
3357 sc->stereo3d->type = mode;
3361 val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
3363 sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
3364 val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
3366 sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
3367 val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
3369 sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
3377 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3380 MOVStreamContext *sc;
3384 static const uint8_t uuid_spherical[] = {
3385 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
3386 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
3389 if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3390 return AVERROR_INVALIDDATA;
3392 if (c->fc->nb_streams < 1)
3394 st = c->fc->streams[c->fc->nb_streams - 1];
3397 ret = ffio_read_size(pb, uuid, sizeof(uuid));
3401 if (!memcmp(uuid, uuid_spherical, sizeof(uuid)) && !sc->spherical) {
3402 size_t len = atom.size - sizeof(uuid);
3403 ret = mov_parse_uuid_spherical(sc, pb, len);
3407 av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
3410 av_log(c->fc, AV_LOG_VERBOSE, "Unknown UUID found: 0x");
3411 for (i = 0; i < sizeof(uuid); i++)
3412 av_log(c->fc, AV_LOG_WARNING, "%02x", uuid[i]);
3413 av_log(c->fc, AV_LOG_WARNING, "\n");
3419 static const MOVParseTableEntry mov_default_parse_table[] = {
3420 { MKTAG('a','v','s','s'), mov_read_extradata },
3421 { MKTAG('c','h','p','l'), mov_read_chpl },
3422 { MKTAG('c','o','6','4'), mov_read_stco },
3423 { MKTAG('c','o','l','r'), mov_read_colr },
3424 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3425 { MKTAG('d','i','n','f'), mov_read_default },
3426 { MKTAG('d','r','e','f'), mov_read_dref },
3427 { MKTAG('e','d','t','s'), mov_read_default },
3428 { MKTAG('e','l','s','t'), mov_read_elst },
3429 { MKTAG('e','n','d','a'), mov_read_enda },
3430 { MKTAG('f','i','e','l'), mov_read_fiel },
3431 { MKTAG('f','t','y','p'), mov_read_ftyp },
3432 { MKTAG('g','l','b','l'), mov_read_glbl },
3433 { MKTAG('h','d','l','r'), mov_read_hdlr },
3434 { MKTAG('i','l','s','t'), mov_read_ilst },
3435 { MKTAG('j','p','2','h'), mov_read_extradata },
3436 { MKTAG('m','d','a','t'), mov_read_mdat },
3437 { MKTAG('m','d','h','d'), mov_read_mdhd },
3438 { MKTAG('m','d','i','a'), mov_read_default },
3439 { MKTAG('m','e','t','a'), mov_read_meta },
3440 { MKTAG('m','i','n','f'), mov_read_default },
3441 { MKTAG('m','o','o','f'), mov_read_moof },
3442 { MKTAG('m','o','o','v'), mov_read_moov },
3443 { MKTAG('m','v','e','x'), mov_read_default },
3444 { MKTAG('m','v','h','d'), mov_read_mvhd },
3445 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
3446 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
3447 { MKTAG('a','v','c','C'), mov_read_glbl },
3448 { MKTAG('p','a','s','p'), mov_read_pasp },
3449 { MKTAG('s','t','b','l'), mov_read_default },
3450 { MKTAG('s','t','c','o'), mov_read_stco },
3451 { MKTAG('s','t','p','s'), mov_read_stps },
3452 { MKTAG('s','t','r','f'), mov_read_strf },
3453 { MKTAG('s','t','s','c'), mov_read_stsc },
3454 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3455 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3456 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3457 { MKTAG('s','t','t','s'), mov_read_stts },
3458 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3459 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3460 { MKTAG('t','f','d','t'), mov_read_tfdt },
3461 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3462 { MKTAG('t','r','a','k'), mov_read_trak },
3463 { MKTAG('t','r','a','f'), mov_read_default },
3464 { MKTAG('t','r','e','f'), mov_read_default },
3465 { MKTAG('c','h','a','p'), mov_read_chap },
3466 { MKTAG('t','r','e','x'), mov_read_trex },
3467 { MKTAG('t','r','u','n'), mov_read_trun },
3468 { MKTAG('u','d','t','a'), mov_read_default },
3469 { MKTAG('w','a','v','e'), mov_read_wave },
3470 { MKTAG('e','s','d','s'), mov_read_esds },
3471 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3472 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3473 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3474 { MKTAG('w','f','e','x'), mov_read_wfex },
3475 { MKTAG('c','m','o','v'), mov_read_cmov },
3476 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3477 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3478 { MKTAG('s','b','g','p'), mov_read_sbgp },
3479 { MKTAG('h','v','c','C'), mov_read_glbl },
3480 { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
3481 { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
3482 { MKTAG('u','u','i','d'), mov_read_uuid }, /* universal unique identifier */
3483 { MKTAG('-','-','-','-'), mov_read_custom },
3487 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3489 int64_t total_size = 0;
3494 atom.size = INT64_MAX;
3495 while (total_size + 8 < atom.size && !pb->eof_reached) {
3496 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3499 if (atom.size >= 8) {
3500 a.size = avio_rb32(pb);
3501 a.type = avio_rl32(pb);
3503 av_log(c->fc, AV_LOG_TRACE, "type: %08"PRIx32" '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3504 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3506 if (a.size == 1) { /* 64 bit extended size */
3507 a.size = avio_rb64(pb) - 8;
3511 a.size = atom.size - total_size;
3518 a.size = FFMIN(a.size, atom.size - total_size);
3520 for (i = 0; mov_default_parse_table[i].type; i++)
3521 if (mov_default_parse_table[i].type == a.type) {
3522 parse = mov_default_parse_table[i].parse;
3526 // container is user data
3527 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3528 atom.type == MKTAG('i','l','s','t')))
3529 parse = mov_read_udta_string;
3531 if (!parse) { /* skip leaf atoms data */
3532 avio_skip(pb, a.size);
3534 int64_t start_pos = avio_tell(pb);
3536 int err = parse(c, pb, a);
3539 if (c->found_moov && c->found_mdat &&
3540 ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3541 start_pos + a.size == avio_size(pb))) {
3542 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX)
3543 c->next_root_atom = start_pos + a.size;
3546 left = a.size - avio_tell(pb) + start_pos;
3547 if (left > 0) /* skip garbage at atom end */
3548 avio_skip(pb, left);
3549 else if (left < 0) {
3550 av_log(c->fc, AV_LOG_WARNING,
3551 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3552 (char*)&a.type, -left);
3553 avio_seek(pb, left, SEEK_CUR);
3557 total_size += a.size;
3560 if (total_size < atom.size && atom.size < 0x7ffff)
3561 avio_skip(pb, atom.size - total_size);
3566 static int mov_probe(AVProbeData *p)
3568 unsigned int offset;
3572 /* check file header */
3575 /* ignore invalid offset */
3576 if ((offset + 8) > (unsigned int)p->buf_size)
3578 tag = AV_RL32(p->buf + offset + 4);
3580 /* check for obvious tags */
3581 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
3582 case MKTAG('m','o','o','v'):
3583 case MKTAG('m','d','a','t'):
3584 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3585 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3586 case MKTAG('f','t','y','p'):
3587 return AVPROBE_SCORE_MAX;
3588 /* those are more common words, so rate then a bit less */
3589 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3590 case MKTAG('w','i','d','e'):
3591 case MKTAG('f','r','e','e'):
3592 case MKTAG('j','u','n','k'):
3593 case MKTAG('p','i','c','t'):
3594 return AVPROBE_SCORE_MAX - 5;
3595 case MKTAG(0x82,0x82,0x7f,0x7d):
3596 case MKTAG('s','k','i','p'):
3597 case MKTAG('u','u','i','d'):
3598 case MKTAG('p','r','f','l'):
3599 offset = AV_RB32(p->buf+offset) + offset;
3600 /* if we only find those cause probedata is too small at least rate them */
3601 score = AVPROBE_SCORE_EXTENSION;
3604 /* unrecognized tag */
3610 // must be done after parsing all trak because there's no order requirement
3611 static void mov_read_chapters(AVFormatContext *s)
3613 MOVContext *mov = s->priv_data;
3614 AVStream *st = NULL;
3615 MOVStreamContext *sc;
3619 for (i = 0; i < s->nb_streams; i++)
3620 if (s->streams[i]->id == mov->chapter_track) {
3625 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3629 st->discard = AVDISCARD_ALL;
3631 cur_pos = avio_tell(sc->pb);
3633 for (i = 0; i < st->nb_index_entries; i++) {
3634 AVIndexEntry *sample = &st->index_entries[i];
3635 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3640 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3641 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3645 // the first two bytes are the length of the title
3646 len = avio_rb16(sc->pb);
3647 if (len > sample->size-2)
3649 title_len = 2*len + 1;
3650 if (!(title = av_mallocz(title_len)))
3653 // The samples could theoretically be in any encoding if there's an encd
3654 // atom following, but in practice are only utf-8 or utf-16, distinguished
3655 // instead by the presence of a BOM
3659 ch = avio_rb16(sc->pb);
3661 avio_get_str16be(sc->pb, len, title, title_len);
3662 else if (ch == 0xfffe)
3663 avio_get_str16le(sc->pb, len, title, title_len);
3666 if (len == 1 || len == 2)
3669 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
3673 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3677 avio_seek(sc->pb, cur_pos, SEEK_SET);
3680 static int mov_read_close(AVFormatContext *s)
3682 MOVContext *mov = s->priv_data;
3685 for (i = 0; i < s->nb_streams; i++) {
3686 AVStream *st = s->streams[i];
3687 MOVStreamContext *sc = st->priv_data;
3689 av_freep(&sc->ctts_data);
3690 for (j = 0; j < sc->drefs_count; j++) {
3691 av_freep(&sc->drefs[j].path);
3692 av_freep(&sc->drefs[j].dir);
3694 av_freep(&sc->drefs);
3695 if (sc->pb && sc->pb != s->pb)
3696 ff_format_io_close(s, &sc->pb);
3698 av_freep(&sc->chunk_offsets);
3699 av_freep(&sc->stsc_data);
3700 av_freep(&sc->sample_sizes);
3701 av_freep(&sc->keyframes);
3702 av_freep(&sc->stts_data);
3703 av_freep(&sc->stps_data);
3704 av_freep(&sc->rap_group);
3705 av_freep(&sc->display_matrix);
3707 for (j = 0; j < sc->stsd_count; j++)
3708 av_free(sc->extradata[j]);
3709 av_freep(&sc->extradata);
3710 av_freep(&sc->extradata_size);
3712 av_freep(&sc->stereo3d);
3713 av_freep(&sc->spherical);
3716 if (mov->dv_demux) {
3717 avformat_free_context(mov->dv_fctx);
3718 mov->dv_fctx = NULL;
3721 av_freep(&mov->trex_data);
3726 static int mov_read_header(AVFormatContext *s)
3728 MOVContext *mov = s->priv_data;
3729 AVIOContext *pb = s->pb;
3731 MOVAtom atom = { AV_RL32("root") };
3735 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3736 if (pb->seekable & AVIO_SEEKABLE_NORMAL)
3737 atom.size = avio_size(pb);
3739 atom.size = INT64_MAX;
3741 /* check MOV header */
3742 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3743 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3747 if (!mov->found_moov) {
3748 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3750 return AVERROR_INVALIDDATA;
3752 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3754 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && mov->chapter_track > 0)
3755 mov_read_chapters(s);
3757 for (i = 0; i < s->nb_streams; i++) {
3758 AVStream *st = s->streams[i];
3759 MOVStreamContext *sc = st->priv_data;
3761 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3762 if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
3763 st->codecpar->width = sc->width;
3764 st->codecpar->height = sc->height;
3766 if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3767 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3773 if (mov->trex_data) {
3774 for (i = 0; i < s->nb_streams; i++) {
3775 AVStream *st = s->streams[i];
3776 MOVStreamContext *sc = st->priv_data;
3777 if (st->duration > 0)
3778 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3782 for (i = 0; i < s->nb_streams; i++) {
3783 AVStream *st = s->streams[i];
3784 MOVStreamContext *sc = st->priv_data;
3786 switch (st->codecpar->codec_type) {
3787 case AVMEDIA_TYPE_AUDIO:
3788 err = ff_replaygain_export(st, s->metadata);
3794 case AVMEDIA_TYPE_VIDEO:
3795 if (sc->display_matrix) {
3796 err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
3797 (uint8_t *)sc->display_matrix,
3798 sizeof(int32_t) * 9);
3802 sc->display_matrix = NULL;
3805 err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
3806 (uint8_t *)sc->stereo3d,
3807 sizeof(*sc->stereo3d));
3811 sc->stereo3d = NULL;
3813 if (sc->spherical) {
3814 err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
3815 (uint8_t *)sc->spherical,
3816 sc->spherical_size);
3820 sc->spherical = NULL;
3829 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3831 AVIndexEntry *sample = NULL;
3832 int64_t best_dts = INT64_MAX;
3834 for (i = 0; i < s->nb_streams; i++) {
3835 AVStream *avst = s->streams[i];
3836 MOVStreamContext *msc = avst->priv_data;
3837 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3838 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3839 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3840 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3841 if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
3842 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
3843 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3844 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3845 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3846 sample = current_sample;
3855 static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
3857 uint8_t *side, *extradata;
3860 /* Save the current index. */
3861 sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
3863 /* Notify the decoder that extradata changed. */
3864 extradata_size = sc->extradata_size[sc->last_stsd_index];
3865 extradata = sc->extradata[sc->last_stsd_index];
3866 if (extradata_size > 0 && extradata) {
3867 side = av_packet_new_side_data(pkt,
3868 AV_PKT_DATA_NEW_EXTRADATA,
3871 return AVERROR(ENOMEM);
3872 memcpy(side, extradata, extradata_size);
3878 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3880 MOVContext *mov = s->priv_data;
3881 MOVStreamContext *sc;
3882 AVIndexEntry *sample;
3883 AVStream *st = NULL;
3886 sample = mov_find_next_sample(s, &st);
3888 mov->found_mdat = 0;
3889 if (!mov->next_root_atom)
3891 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3892 mov->next_root_atom = 0;
3893 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3896 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3900 /* must be done just before reading, to avoid infinite loop on sample */
3901 sc->current_sample++;
3903 if (st->discard != AVDISCARD_ALL) {
3904 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3905 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3906 sc->ffindex, sample->pos);
3907 return AVERROR_INVALIDDATA;
3909 ret = av_get_packet(sc->pb, pkt, sample->size);
3912 if (sc->has_palette) {
3915 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3917 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3919 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3920 sc->has_palette = 0;
3923 #if CONFIG_DV_DEMUXER
3924 if (mov->dv_demux && sc->dv_audio_container) {
3925 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
3928 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3935 pkt->stream_index = sc->ffindex;
3936 pkt->dts = sample->timestamp;
3937 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3938 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3939 /* update ctts context */
3941 if (sc->ctts_index < sc->ctts_count &&
3942 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3944 sc->ctts_sample = 0;
3947 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3948 st->index_entries[sc->current_sample].timestamp : st->duration;
3949 pkt->duration = next_dts - pkt->dts;
3950 pkt->pts = pkt->dts;
3952 if (st->discard == AVDISCARD_ALL)
3954 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3955 pkt->pos = sample->pos;
3956 av_log(s, AV_LOG_TRACE, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %"PRId64"\n",
3957 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3959 /* Multiple stsd handling. */
3960 if (sc->stsc_data) {
3961 /* Keep track of the stsc index for the given sample, then check
3962 * if the stsd index is different from the last used one. */
3964 if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
3965 mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
3967 sc->stsc_sample = 0;
3968 /* Do not check indexes after a switch. */
3969 } else if (sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
3970 ret = mov_change_extradata(sc, pkt);
3979 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3981 MOVStreamContext *sc = st->priv_data;
3982 int sample, time_sample;
3985 sample = av_index_search_timestamp(st, timestamp, flags);
3986 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3987 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3989 if (sample < 0) /* not sure what to do */
3990 return AVERROR_INVALIDDATA;
3991 sc->current_sample = sample;
3992 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
3993 /* adjust ctts index */
3994 if (sc->ctts_data) {
3996 for (i = 0; i < sc->ctts_count; i++) {
3997 int next = time_sample + sc->ctts_data[i].count;
3998 if (next > sc->current_sample) {
4000 sc->ctts_sample = sc->current_sample - time_sample;
4007 /* adjust stsd index */
4009 for (i = 0; i < sc->stsc_count; i++) {
4010 int next = time_sample + mov_get_stsc_samples(sc, i);
4011 if (next > sc->current_sample) {
4013 sc->stsc_sample = sc->current_sample - time_sample;
4022 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
4024 MOVContext *mc = s->priv_data;
4029 if (stream_index >= s->nb_streams)
4030 return AVERROR_INVALIDDATA;
4031 if (sample_time < 0)
4034 st = s->streams[stream_index];
4035 sample = mov_seek_stream(s, st, sample_time, flags);
4039 if (mc->seek_individually) {
4040 /* adjust seek timestamp to found sample timestamp */
4041 int64_t seek_timestamp = st->index_entries[sample].timestamp;
4043 for (i = 0; i < s->nb_streams; i++) {
4046 if (stream_index == i)
4049 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
4050 mov_seek_stream(s, st, timestamp, flags);
4053 for (i = 0; i < s->nb_streams; i++) {
4054 MOVStreamContext *sc;
4057 sc->current_sample = 0;
4060 MOVStreamContext *sc;
4061 AVIndexEntry *entry = mov_find_next_sample(s, &st);
4063 return AVERROR_INVALIDDATA;
4065 if (sc->ffindex == stream_index && sc->current_sample == sample)
4067 sc->current_sample++;
4073 #define OFFSET(x) offsetof(MOVContext, x)
4074 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
4075 static const AVOption mov_options[] = {
4076 {"seek_streams_individually",
4077 "Seek each stream individually to the to the closest point",
4078 OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
4080 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
4081 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
4082 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
4083 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
4084 { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs),
4085 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
4089 static const AVClass mov_class = {
4090 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
4091 .item_name = av_default_item_name,
4092 .option = mov_options,
4093 .version = LIBAVUTIL_VERSION_INT,
4096 AVInputFormat ff_mov_demuxer = {
4097 .name = "mov,mp4,m4a,3gp,3g2,mj2",
4098 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
4099 .priv_class = &mov_class,
4100 .priv_data_size = sizeof(MOVContext),
4101 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
4102 .read_probe = mov_probe,
4103 .read_header = mov_read_header,
4104 .read_packet = mov_read_packet,
4105 .read_close = mov_read_close,
4106 .read_seek = mov_read_seek,