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 "libavcodec/ac3tab.h"
42 #include "avio_internal.h"
45 #include "libavcodec/get_bits.h"
48 #include "replaygain.h"
54 #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);
164 if (c < 0x80 && p < end)
167 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
173 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
177 MOVStreamContext *sc;
182 case 0xd: id = AV_CODEC_ID_MJPEG; break;
183 case 0xe: id = AV_CODEC_ID_PNG; break;
184 case 0x1b: id = AV_CODEC_ID_BMP; break;
186 av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
191 st = avformat_new_stream(c->fc, NULL);
193 return AVERROR(ENOMEM);
194 sc = av_mallocz(sizeof(*sc));
196 return AVERROR(ENOMEM);
199 ret = av_get_packet(pb, &pkt, len);
203 if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
204 if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
205 id = AV_CODEC_ID_PNG;
207 id = AV_CODEC_ID_MJPEG;
211 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
213 st->attached_pic = pkt;
214 st->attached_pic.stream_index = st->index;
215 st->attached_pic.flags |= AV_PKT_FLAG_KEY;
217 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
218 st->codec->codec_id = id;
223 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
225 char language[4] = { 0 };
227 uint16_t langcode = 0;
228 double longitude, latitude;
229 const char *key = "location";
231 if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4)
232 return AVERROR_INVALIDDATA;
234 avio_skip(pb, 4); // version+flags
235 langcode = avio_rb16(pb);
236 ff_mov_lang_to_iso639(langcode, language);
239 len -= avio_get_str(pb, len, buf, sizeof(buf)); // place name
241 return AVERROR_INVALIDDATA;
242 avio_skip(pb, 1); // role
246 return AVERROR_INVALIDDATA;
247 longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
248 latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
250 // Try to output in the same format as the ?xyz field
251 snprintf(buf, sizeof(buf), "%+08.4f%+09.4f/", latitude, longitude);
252 if (*language && strcmp(language, "und")) {
254 snprintf(key2, sizeof(key2), "%s-%s", key, language);
255 av_dict_set(&c->fc->metadata, key2, buf, 0);
257 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
258 return av_dict_set(&c->fc->metadata, key, buf, 0);
261 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
264 char *str, key2[32], language[4] = {0};
265 const char *key = NULL;
266 uint16_t langcode = 0;
267 uint32_t data_type = 0, str_size, str_size_alloc;
268 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
272 case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
273 case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
274 case MKTAG( 'X','M','P','_'):
275 if (c->export_xmp) { key = "xmp"; raw = 1; } break;
276 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
277 case MKTAG( 'a','k','I','D'): key = "account_type";
278 parse = mov_metadata_int8_no_padding; break;
279 case MKTAG( 'a','p','I','D'): key = "account_id"; break;
280 case MKTAG( 'c','a','t','g'): key = "category"; break;
281 case MKTAG( 'c','p','i','l'): key = "compilation";
282 parse = mov_metadata_int8_no_padding; break;
283 case MKTAG( 'c','p','r','t'): key = "copyright"; break;
284 case MKTAG( 'd','e','s','c'): key = "description"; break;
285 case MKTAG( 'd','i','s','k'): key = "disc";
286 parse = mov_metadata_track_or_disc_number; break;
287 case MKTAG( 'e','g','i','d'): key = "episode_uid";
288 parse = mov_metadata_int8_no_padding; break;
289 case MKTAG( 'g','n','r','e'): key = "genre";
290 parse = mov_metadata_gnre; break;
291 case MKTAG( 'h','d','v','d'): key = "hd_video";
292 parse = mov_metadata_int8_no_padding; break;
293 case MKTAG( 'k','e','y','w'): key = "keywords"; break;
294 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
295 case MKTAG( 'l','o','c','i'):
296 return mov_metadata_loci(c, pb, atom.size);
297 case MKTAG( 'p','c','s','t'): key = "podcast";
298 parse = mov_metadata_int8_no_padding; break;
299 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
300 parse = mov_metadata_int8_no_padding; break;
301 case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
302 case MKTAG( 'r','t','n','g'): key = "rating";
303 parse = mov_metadata_int8_no_padding; break;
304 case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
305 case MKTAG( 's','o','a','l'): key = "sort_album"; break;
306 case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
307 case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
308 case MKTAG( 's','o','n','m'): key = "sort_name"; break;
309 case MKTAG( 's','o','s','n'): key = "sort_show"; break;
310 case MKTAG( 's','t','i','k'): key = "media_type";
311 parse = mov_metadata_int8_no_padding; break;
312 case MKTAG( 't','r','k','n'): key = "track";
313 parse = mov_metadata_track_or_disc_number; break;
314 case MKTAG( 't','v','e','n'): key = "episode_id"; break;
315 case MKTAG( 't','v','e','s'): key = "episode_sort";
316 parse = mov_metadata_int8_bypass_padding; break;
317 case MKTAG( 't','v','n','n'): key = "network"; break;
318 case MKTAG( 't','v','s','h'): key = "show"; break;
319 case MKTAG( 't','v','s','n'): key = "season_number";
320 parse = mov_metadata_int8_bypass_padding; break;
321 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
322 case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
323 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
324 case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
325 case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
326 case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
327 case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
328 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
329 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
330 case MKTAG(0xa9,'d','i','r'): key = "director"; break;
331 case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
332 case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
333 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
334 case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
335 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
336 case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
337 case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
338 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
339 case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
340 case MKTAG(0xa9,'m','a','k'): key = "make"; break;
341 case MKTAG(0xa9,'m','o','d'): key = "model"; break;
342 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
343 case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
344 case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
345 case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
346 case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
347 case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
348 case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
349 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
350 case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
351 case MKTAG(0xa9,'t','r','k'): key = "track"; break;
352 case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
353 case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
354 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
355 case MKTAG(0xa9,'x','y','z'): key = "location"; break;
358 if (c->itunes_metadata && atom.size > 8) {
359 int data_size = avio_rb32(pb);
360 int tag = avio_rl32(pb);
361 if (tag == MKTAG('d','a','t','a')) {
362 data_type = avio_rb32(pb); // type
363 avio_rb32(pb); // unknown
364 str_size = data_size - 16;
367 if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
368 int ret = mov_read_covr(c, pb, data_type, str_size);
370 av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
375 } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
376 str_size = avio_rb16(pb); // string length
377 langcode = avio_rb16(pb);
378 ff_mov_lang_to_iso639(langcode, language);
381 str_size = atom.size;
383 if (c->export_all && !key) {
384 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
391 return AVERROR_INVALIDDATA;
393 // allocate twice as much as worst-case
394 str_size_alloc = (raw ? str_size : str_size * 2) + 1;
395 str = av_malloc(str_size_alloc);
397 return AVERROR(ENOMEM);
400 parse(c, pb, str_size, key);
402 if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
403 mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
405 int ret = ffio_read_size(pb, str, str_size);
412 c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
413 av_dict_set(&c->fc->metadata, key, str, 0);
414 if (*language && strcmp(language, "und")) {
415 snprintf(key2, sizeof(key2), "%s-%s", key, language);
416 av_dict_set(&c->fc->metadata, key2, str, 0);
419 av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
420 av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
421 key, str, (char*)&atom.type, str_size_alloc, atom.size);
427 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
430 int i, nb_chapters, str_len, version;
434 if ((atom.size -= 5) < 0)
437 version = avio_r8(pb);
440 avio_rb32(pb); // ???
441 nb_chapters = avio_r8(pb);
443 for (i = 0; i < nb_chapters; i++) {
447 start = avio_rb64(pb);
448 str_len = avio_r8(pb);
450 if ((atom.size -= 9+str_len) < 0)
453 ret = ffio_read_size(pb, str, str_len);
457 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
462 #define MIN_DATA_ENTRY_BOX_SIZE 12
463 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
466 MOVStreamContext *sc;
469 if (c->fc->nb_streams < 1)
471 st = c->fc->streams[c->fc->nb_streams-1];
474 avio_rb32(pb); // version + flags
475 entries = avio_rb32(pb);
476 if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
477 entries >= UINT_MAX / sizeof(*sc->drefs))
478 return AVERROR_INVALIDDATA;
480 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
482 return AVERROR(ENOMEM);
483 sc->drefs_count = entries;
485 for (i = 0; i < entries; i++) {
486 MOVDref *dref = &sc->drefs[i];
487 uint32_t size = avio_rb32(pb);
488 int64_t next = avio_tell(pb) + size - 4;
491 return AVERROR_INVALIDDATA;
493 dref->type = avio_rl32(pb);
494 avio_rb32(pb); // version + flags
495 av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
497 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
498 /* macintosh alias record */
499 uint16_t volume_len, len;
505 volume_len = avio_r8(pb);
506 volume_len = FFMIN(volume_len, 27);
507 ret = ffio_read_size(pb, dref->volume, 27);
510 dref->volume[volume_len] = 0;
511 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
516 len = FFMIN(len, 63);
517 ret = ffio_read_size(pb, dref->filename, 63);
520 dref->filename[len] = 0;
521 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
525 /* read next level up_from_alias/down_to_target */
526 dref->nlvl_from = avio_rb16(pb);
527 dref->nlvl_to = avio_rb16(pb);
528 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
529 dref->nlvl_from, dref->nlvl_to);
533 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
536 type = avio_rb16(pb);
538 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
541 if (type == 2) { // absolute path
543 dref->path = av_mallocz(len+1);
545 return AVERROR(ENOMEM);
547 ret = ffio_read_size(pb, dref->path, len);
549 av_freep(&dref->path);
552 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
554 memmove(dref->path, dref->path+volume_len, len);
557 for (j = 0; j < len; j++)
558 if (dref->path[j] == ':' || dref->path[j] == 0)
560 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
561 } else if (type == 0) { // directory name
563 dref->dir = av_malloc(len+1);
565 return AVERROR(ENOMEM);
567 ret = ffio_read_size(pb, dref->dir, len);
569 av_freep(&dref->dir);
573 for (j = 0; j < len; j++)
574 if (dref->dir[j] == ':')
576 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
581 av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x08%x size %d\n",
586 avio_seek(pb, next, SEEK_SET);
591 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
595 uint32_t av_unused ctype;
600 if (c->fc->nb_streams < 1) // meta before first trak
603 st = c->fc->streams[c->fc->nb_streams-1];
605 avio_r8(pb); /* version */
606 avio_rb24(pb); /* flags */
609 ctype = avio_rl32(pb);
610 type = avio_rl32(pb); /* component subtype */
612 av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
613 av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
615 if (type == MKTAG('v','i','d','e'))
616 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
617 else if (type == MKTAG('s','o','u','n'))
618 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
619 else if (type == MKTAG('m','1','a',' '))
620 st->codec->codec_id = AV_CODEC_ID_MP2;
621 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
622 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
624 avio_rb32(pb); /* component manufacture */
625 avio_rb32(pb); /* component flags */
626 avio_rb32(pb); /* component flags mask */
628 title_size = atom.size - 24;
629 if (title_size > 0) {
630 title_str = av_malloc(title_size + 1); /* Add null terminator */
632 return AVERROR(ENOMEM);
634 ret = ffio_read_size(pb, title_str, title_size);
636 av_freep(&title_str);
639 title_str[title_size] = 0;
641 int off = (!c->isom && title_str[0] == title_size - 1);
642 av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
644 av_freep(&title_str);
650 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
655 if (fc->nb_streams < 1)
657 st = fc->streams[fc->nb_streams-1];
659 avio_rb32(pb); /* version + flags */
660 ff_mp4_read_descr(fc, pb, &tag);
661 if (tag == MP4ESDescrTag) {
662 ff_mp4_parse_es_descr(pb, NULL);
664 avio_rb16(pb); /* ID */
666 ff_mp4_read_descr(fc, pb, &tag);
667 if (tag == MP4DecConfigDescrTag)
668 ff_mp4_read_dec_config_descr(fc, st, pb);
672 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
674 return ff_mov_read_esds(c->fc, pb);
677 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
680 enum AVAudioServiceType *ast;
681 int ac3info, acmod, lfeon, bsmod;
683 if (c->fc->nb_streams < 1)
685 st = c->fc->streams[c->fc->nb_streams-1];
687 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
690 return AVERROR(ENOMEM);
692 ac3info = avio_rb24(pb);
693 bsmod = (ac3info >> 14) & 0x7;
694 acmod = (ac3info >> 11) & 0x7;
695 lfeon = (ac3info >> 10) & 0x1;
696 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
697 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
699 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
701 if (st->codec->channels > 1 && bsmod == 0x7)
702 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
704 st->codec->audio_service_type = *ast;
709 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
712 enum AVAudioServiceType *ast;
713 int eac3info, acmod, lfeon, bsmod;
715 if (c->fc->nb_streams < 1)
717 st = c->fc->streams[c->fc->nb_streams-1];
719 ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
722 return AVERROR(ENOMEM);
724 /* No need to parse fields for additional independent substreams and its
725 * associated dependent substreams since libavcodec's E-AC-3 decoder
726 * does not support them yet. */
727 avio_rb16(pb); /* data_rate and num_ind_sub */
728 eac3info = avio_rb24(pb);
729 bsmod = (eac3info >> 12) & 0x1f;
730 acmod = (eac3info >> 9) & 0x7;
731 lfeon = (eac3info >> 8) & 0x1;
732 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
734 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
735 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
737 if (st->codec->channels > 1 && bsmod == 0x7)
738 *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
740 st->codec->audio_service_type = *ast;
745 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
749 if (c->fc->nb_streams < 1)
751 st = c->fc->streams[c->fc->nb_streams-1];
756 /* skip version and flags */
759 ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
764 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
768 if (c->fc->nb_streams < 1)
770 st = c->fc->streams[c->fc->nb_streams-1];
772 return ff_get_wav_header(c->fc, pb, st->codec, atom.size);
775 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
777 const int num = avio_rb32(pb);
778 const int den = avio_rb32(pb);
781 if (c->fc->nb_streams < 1)
783 st = c->fc->streams[c->fc->nb_streams-1];
785 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
786 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
787 av_log(c->fc, AV_LOG_WARNING,
788 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
789 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
791 } else if (den != 0) {
792 st->sample_aspect_ratio.num = num;
793 st->sample_aspect_ratio.den = den;
798 /* this atom contains actual media data */
799 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
801 if (atom.size == 0) /* wrong one (MP4) */
804 return 0; /* now go for moov */
807 /* read major brand, minor version and compatible brands and store them as metadata */
808 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
812 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
813 char* comp_brands_str;
814 uint8_t type[5] = {0};
815 int ret = ffio_read_size(pb, type, 4);
819 if (strcmp(type, "qt "))
821 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
822 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
823 minor_ver = avio_rb32(pb); /* minor version */
824 snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);
825 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
827 comp_brand_size = atom.size - 8;
828 if (comp_brand_size < 0)
829 return AVERROR_INVALIDDATA;
830 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
831 if (!comp_brands_str)
832 return AVERROR(ENOMEM);
834 ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
836 av_freep(&comp_brands_str);
839 comp_brands_str[comp_brand_size] = 0;
840 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
841 av_freep(&comp_brands_str);
846 /* this atom should contain all header atoms */
847 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
851 if ((ret = mov_read_default(c, pb, atom)) < 0)
853 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
854 /* so we don't parse the whole file if over a network */
856 return 0; /* now go for mdat */
859 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
861 c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
862 av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
863 return mov_read_default(c, pb, atom);
866 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
870 struct tm *ptm, tmbuf;
871 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
872 ptm = gmtime_r(&time, &tmbuf);
874 if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
875 av_dict_set(metadata, "creation_time", buffer, 0);
879 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
882 MOVStreamContext *sc;
884 char language[4] = {0};
886 time_t creation_time;
888 if (c->fc->nb_streams < 1)
890 st = c->fc->streams[c->fc->nb_streams-1];
893 if (sc->time_scale) {
894 av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
895 return AVERROR_INVALIDDATA;
898 version = avio_r8(pb);
900 avpriv_request_sample(c->fc, "Version %d", version);
901 return AVERROR_PATCHWELCOME;
903 avio_rb24(pb); /* flags */
905 creation_time = avio_rb64(pb);
908 creation_time = avio_rb32(pb);
909 avio_rb32(pb); /* modification time */
911 mov_metadata_creation_time(&st->metadata, creation_time);
913 sc->time_scale = avio_rb32(pb);
914 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
916 lang = avio_rb16(pb); /* language */
917 if (ff_mov_lang_to_iso639(lang, language))
918 av_dict_set(&st->metadata, "language", language, 0);
919 avio_rb16(pb); /* quality */
924 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
926 time_t creation_time;
927 int version = avio_r8(pb); /* version */
928 avio_rb24(pb); /* flags */
931 creation_time = avio_rb64(pb);
934 creation_time = avio_rb32(pb);
935 avio_rb32(pb); /* modification time */
937 mov_metadata_creation_time(&c->fc->metadata, creation_time);
938 c->time_scale = avio_rb32(pb); /* time scale */
940 av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
942 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
943 avio_rb32(pb); /* preferred scale */
945 avio_rb16(pb); /* preferred volume */
947 avio_skip(pb, 10); /* reserved */
949 avio_skip(pb, 36); /* display matrix */
951 avio_rb32(pb); /* preview time */
952 avio_rb32(pb); /* preview duration */
953 avio_rb32(pb); /* poster time */
954 avio_rb32(pb); /* selection time */
955 avio_rb32(pb); /* selection duration */
956 avio_rb32(pb); /* current time */
957 avio_rb32(pb); /* next track ID */
962 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
967 if (c->fc->nb_streams < 1)
969 st = c->fc->streams[c->fc->nb_streams-1];
971 if ((uint64_t)atom.size > (1<<30))
972 return AVERROR_INVALIDDATA;
974 // currently SVQ3 decoder expect full STSD header - so let's fake it
975 // this should be fixed and just SMI header should be passed
976 av_free(st->codec->extradata);
977 st->codec->extradata = av_mallocz(atom.size + 0x5a + AV_INPUT_BUFFER_PADDING_SIZE);
978 if (!st->codec->extradata)
979 return AVERROR(ENOMEM);
980 st->codec->extradata_size = 0x5a + atom.size;
981 memcpy(st->codec->extradata, "SVQ3", 4); // fake
983 ret = ffio_read_size(pb, st->codec->extradata + 0x5a, atom.size);
987 av_log(c->fc, AV_LOG_TRACE, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
991 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
996 if (c->fc->nb_streams < 1)
998 st = c->fc->streams[c->fc->nb_streams-1];
1000 little_endian = !!avio_rb16(pb);
1001 av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1002 if (little_endian == 1) {
1003 switch (st->codec->codec_id) {
1004 case AV_CODEC_ID_PCM_S24BE:
1005 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
1007 case AV_CODEC_ID_PCM_S32BE:
1008 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
1010 case AV_CODEC_ID_PCM_F32BE:
1011 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
1013 case AV_CODEC_ID_PCM_F64BE:
1014 st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
1023 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1026 char color_parameter_type[5] = { 0 };
1027 uint16_t color_primaries, color_trc, color_matrix;
1030 if (c->fc->nb_streams < 1)
1032 st = c->fc->streams[c->fc->nb_streams - 1];
1034 ret = ffio_read_size(pb, color_parameter_type, 4);
1037 if (strncmp(color_parameter_type, "nclx", 4) &&
1038 strncmp(color_parameter_type, "nclc", 4)) {
1039 av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1040 color_parameter_type);
1044 color_primaries = avio_rb16(pb);
1045 color_trc = avio_rb16(pb);
1046 color_matrix = avio_rb16(pb);
1048 av_log(c->fc, AV_LOG_TRACE,
1049 "%s: pri %"PRIu16" trc %"PRIu16" matrix %"PRIu16"",
1050 color_parameter_type, color_primaries, color_trc, color_matrix);
1052 if (!strncmp(color_parameter_type, "nclx", 4)) {
1053 uint8_t color_range = avio_r8(pb) >> 7;
1054 av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1056 st->codec->color_range = AVCOL_RANGE_JPEG;
1058 st->codec->color_range = AVCOL_RANGE_MPEG;
1059 /* 14496-12 references JPEG XR specs (rather than the more complete
1060 * 23001-8) so some adjusting is required */
1061 if (color_primaries >= AVCOL_PRI_FILM)
1062 color_primaries = AVCOL_PRI_UNSPECIFIED;
1063 if ((color_trc >= AVCOL_TRC_LINEAR &&
1064 color_trc <= AVCOL_TRC_LOG_SQRT) ||
1065 color_trc >= AVCOL_TRC_BT2020_10)
1066 color_trc = AVCOL_TRC_UNSPECIFIED;
1067 if (color_matrix >= AVCOL_SPC_BT2020_NCL)
1068 color_matrix = AVCOL_SPC_UNSPECIFIED;
1069 st->codec->color_primaries = color_primaries;
1070 st->codec->color_trc = color_trc;
1071 st->codec->colorspace = color_matrix;
1072 } else if (!strncmp(color_parameter_type, "nclc", 4)) {
1073 /* color primaries, Table 4-4 */
1074 switch (color_primaries) {
1075 case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
1076 case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
1077 case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
1079 /* color transfer, Table 4-5 */
1080 switch (color_trc) {
1081 case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
1082 case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
1084 /* color matrix, Table 4-6 */
1085 switch (color_matrix) {
1086 case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
1087 case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
1088 case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
1091 av_log(c->fc, AV_LOG_TRACE, "\n");
1096 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1099 unsigned mov_field_order;
1100 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1102 if (c->fc->nb_streams < 1) // will happen with jp2 files
1104 st = c->fc->streams[c->fc->nb_streams-1];
1106 return AVERROR_INVALIDDATA;
1107 mov_field_order = avio_rb16(pb);
1108 if ((mov_field_order & 0xFF00) == 0x0100)
1109 decoded_field_order = AV_FIELD_PROGRESSIVE;
1110 else if ((mov_field_order & 0xFF00) == 0x0200) {
1111 switch (mov_field_order & 0xFF) {
1112 case 0x01: decoded_field_order = AV_FIELD_TT;
1114 case 0x06: decoded_field_order = AV_FIELD_BB;
1116 case 0x09: decoded_field_order = AV_FIELD_TB;
1118 case 0x0E: decoded_field_order = AV_FIELD_BT;
1122 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1123 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1125 st->codec->field_order = decoded_field_order;
1130 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
1131 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1138 if (c->fc->nb_streams < 1) // will happen with jp2 files
1140 st= c->fc->streams[c->fc->nb_streams-1];
1141 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1142 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1143 return AVERROR_INVALIDDATA;
1144 if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
1145 st->codec->extradata_size = 0;
1148 buf = st->codec->extradata + st->codec->extradata_size;
1149 st->codec->extradata_size= size - AV_INPUT_BUFFER_PADDING_SIZE;
1150 AV_WB32( buf , atom.size + 8);
1151 AV_WL32( buf + 4, atom.type);
1153 err = ffio_read_size(pb, buf + 8, atom.size);
1160 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1165 if (c->fc->nb_streams < 1)
1167 st = c->fc->streams[c->fc->nb_streams-1];
1169 if ((uint64_t)atom.size > (1<<30))
1170 return AVERROR_INVALIDDATA;
1172 if (st->codec->codec_id == AV_CODEC_ID_QDM2 || st->codec->codec_id == AV_CODEC_ID_QDMC) {
1173 // pass all frma atom to codec, needed at least for QDMC and QDM2
1174 av_free(st->codec->extradata);
1175 st->codec->extradata = av_mallocz(atom.size + AV_INPUT_BUFFER_PADDING_SIZE);
1176 if (!st->codec->extradata)
1177 return AVERROR(ENOMEM);
1178 st->codec->extradata_size = atom.size;
1180 ret = ffio_read_size(pb, st->codec->extradata, atom.size);
1183 } else if (atom.size > 8) { /* to read frma, esds atoms */
1184 if ((ret = mov_read_default(c, pb, atom)) < 0)
1187 avio_skip(pb, atom.size);
1192 * This function reads atom content and puts data in extradata without tag
1193 * nor size unlike mov_read_extradata.
1195 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1200 if (c->fc->nb_streams < 1)
1202 st = c->fc->streams[c->fc->nb_streams-1];
1204 if ((uint64_t)atom.size > (1<<30))
1205 return AVERROR_INVALIDDATA;
1207 if (atom.size >= 10) {
1208 // Broken files created by legacy versions of libavformat will
1209 // wrap a whole fiel atom inside of a glbl atom.
1210 unsigned size = avio_rb32(pb);
1211 unsigned type = avio_rl32(pb);
1212 avio_seek(pb, -8, SEEK_CUR);
1213 if (type == MKTAG('f','i','e','l') && size == atom.size)
1214 return mov_read_default(c, pb, atom);
1216 av_free(st->codec->extradata);
1217 st->codec->extradata = av_mallocz(atom.size + AV_INPUT_BUFFER_PADDING_SIZE);
1218 if (!st->codec->extradata)
1219 return AVERROR(ENOMEM);
1220 st->codec->extradata_size = atom.size;
1222 ret = ffio_read_size(pb, st->codec->extradata, atom.size);
1229 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1232 uint8_t profile_level;
1235 if (c->fc->nb_streams < 1)
1237 st = c->fc->streams[c->fc->nb_streams-1];
1239 if (atom.size >= (1<<28) || atom.size < 7)
1240 return AVERROR_INVALIDDATA;
1242 profile_level = avio_r8(pb);
1243 if ((profile_level & 0xf0) != 0xc0)
1246 av_free(st->codec->extradata);
1247 st->codec->extradata = av_mallocz(atom.size - 7 + AV_INPUT_BUFFER_PADDING_SIZE);
1248 if (!st->codec->extradata)
1249 return AVERROR(ENOMEM);
1250 st->codec->extradata_size = atom.size - 7;
1251 avio_seek(pb, 6, SEEK_CUR);
1253 ret = ffio_read_size(pb, st->codec->extradata, st->codec->extradata_size);
1261 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1262 * but can have extradata appended at the end after the 40 bytes belonging
1265 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1270 if (c->fc->nb_streams < 1)
1272 if (atom.size <= 40)
1274 st = c->fc->streams[c->fc->nb_streams-1];
1276 if ((uint64_t)atom.size > (1<<30))
1277 return AVERROR_INVALIDDATA;
1279 av_free(st->codec->extradata);
1280 st->codec->extradata = av_mallocz(atom.size - 40 + AV_INPUT_BUFFER_PADDING_SIZE);
1281 if (!st->codec->extradata)
1282 return AVERROR(ENOMEM);
1283 st->codec->extradata_size = atom.size - 40;
1286 ret = ffio_read_size(pb, st->codec->extradata, atom.size - 40);
1293 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1296 MOVStreamContext *sc;
1297 unsigned int i, entries;
1299 if (c->fc->nb_streams < 1)
1301 st = c->fc->streams[c->fc->nb_streams-1];
1304 avio_r8(pb); /* version */
1305 avio_rb24(pb); /* flags */
1307 entries = avio_rb32(pb);
1311 if (entries >= UINT_MAX/sizeof(int64_t))
1312 return AVERROR_INVALIDDATA;
1314 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1315 if (!sc->chunk_offsets)
1316 return AVERROR(ENOMEM);
1317 sc->chunk_count = entries;
1319 if (atom.type == MKTAG('s','t','c','o'))
1320 for (i = 0; i < entries && !pb->eof_reached; i++)
1321 sc->chunk_offsets[i] = avio_rb32(pb);
1322 else if (atom.type == MKTAG('c','o','6','4'))
1323 for (i = 0; i < entries && !pb->eof_reached; i++)
1324 sc->chunk_offsets[i] = avio_rb64(pb);
1326 return AVERROR_INVALIDDATA;
1328 sc->chunk_count = i;
1330 if (pb->eof_reached)
1337 * Compute codec id for 'lpcm' tag.
1338 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1340 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1347 return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1350 static int mov_codec_id(AVStream *st, uint32_t format)
1352 int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1355 ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1356 (format & 0xFFFF) == 'T' + ('S' << 8)))
1357 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1359 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1360 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1361 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1362 /* skip old asf mpeg4 tag */
1363 format && format != MKTAG('m','p','4','s')) {
1364 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1366 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1368 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1369 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
1370 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1372 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1376 st->codec->codec_tag = format;
1381 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1382 AVStream *st, MOVStreamContext *sc)
1384 uint8_t codec_name[32];
1385 unsigned int color_depth, len, j;
1386 int color_greyscale;
1389 avio_rb16(pb); /* version */
1390 avio_rb16(pb); /* revision level */
1391 avio_rb32(pb); /* vendor */
1392 avio_rb32(pb); /* temporal quality */
1393 avio_rb32(pb); /* spatial quality */
1395 st->codec->width = avio_rb16(pb); /* width */
1396 st->codec->height = avio_rb16(pb); /* height */
1398 avio_rb32(pb); /* horiz resolution */
1399 avio_rb32(pb); /* vert resolution */
1400 avio_rb32(pb); /* data size, always 0 */
1401 avio_rb16(pb); /* frames per samples */
1403 len = avio_r8(pb); /* codec name, pascal string */
1406 mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1408 avio_skip(pb, 31 - len);
1411 av_dict_set(&st->metadata, "encoder", codec_name, 0);
1413 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1414 if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1415 st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1416 /* Flash Media Server uses tag H263 with Sorenson Spark */
1417 if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1418 !memcmp(codec_name, "Sorenson H263", 13))
1419 st->codec->codec_id = AV_CODEC_ID_FLV1;
1421 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1422 color_table_id = avio_rb16(pb); /* colortable id */
1423 av_log(c->fc, AV_LOG_TRACE, "depth %d, ctab id %d\n",
1424 st->codec->bits_per_coded_sample, color_table_id);
1425 /* figure out the palette situation */
1426 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1427 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1429 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1430 if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1431 /* for palette traversal */
1432 unsigned int color_start, color_count, color_end;
1433 unsigned char r, g, b;
1435 if (color_greyscale) {
1436 int color_index, color_dec;
1437 /* compute the greyscale palette */
1438 st->codec->bits_per_coded_sample = color_depth;
1439 color_count = 1 << color_depth;
1441 color_dec = 256 / (color_count - 1);
1442 for (j = 0; j < color_count; j++) {
1443 r = g = b = color_index;
1444 sc->palette[j] = (r << 16) | (g << 8) | (b);
1445 color_index -= color_dec;
1446 if (color_index < 0)
1449 } else if (color_table_id) {
1450 const uint8_t *color_table;
1451 /* if flag bit 3 is set, use the default palette */
1452 color_count = 1 << color_depth;
1453 if (color_depth == 2)
1454 color_table = ff_qt_default_palette_4;
1455 else if (color_depth == 4)
1456 color_table = ff_qt_default_palette_16;
1458 color_table = ff_qt_default_palette_256;
1460 for (j = 0; j < color_count; j++) {
1461 r = color_table[j * 3 + 0];
1462 g = color_table[j * 3 + 1];
1463 b = color_table[j * 3 + 2];
1464 sc->palette[j] = (r << 16) | (g << 8) | (b);
1467 /* load the palette from the file */
1468 color_start = avio_rb32(pb);
1469 color_count = avio_rb16(pb);
1470 color_end = avio_rb16(pb);
1471 if ((color_start <= 255) && (color_end <= 255)) {
1472 for (j = color_start; j <= color_end; j++) {
1473 /* each R, G, or B component is 16 bits;
1474 * only use the top 8 bits; skip alpha bytes
1484 sc->palette[j] = (r << 16) | (g << 8) | (b);
1488 sc->has_palette = 1;
1492 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1493 AVStream *st, MOVStreamContext *sc)
1495 int bits_per_sample, flags;
1496 uint16_t version = avio_rb16(pb);
1498 avio_rb16(pb); /* revision level */
1499 avio_rb32(pb); /* vendor */
1501 st->codec->channels = avio_rb16(pb); /* channel count */
1502 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1503 av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codec->channels);
1505 sc->audio_cid = avio_rb16(pb);
1506 avio_rb16(pb); /* packet size = 0 */
1508 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1510 // Read QT version 1 fields. In version 0 these do not exist.
1511 av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1514 sc->samples_per_frame = avio_rb32(pb);
1515 avio_rb32(pb); /* bytes per packet */
1516 sc->bytes_per_frame = avio_rb32(pb);
1517 avio_rb32(pb); /* bytes per sample */
1518 } else if (version == 2) {
1519 avio_rb32(pb); /* sizeof struct only */
1520 st->codec->sample_rate = av_int2double(avio_rb64(pb));
1521 st->codec->channels = avio_rb32(pb);
1522 avio_rb32(pb); /* always 0x7F000000 */
1523 st->codec->bits_per_coded_sample = avio_rb32(pb);
1525 flags = avio_rb32(pb); /* lpcm format specific flag */
1526 sc->bytes_per_frame = avio_rb32(pb);
1527 sc->samples_per_frame = avio_rb32(pb);
1528 if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1529 st->codec->codec_id =
1530 ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1533 if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1534 /* can't correctly handle variable sized packet as audio unit */
1535 switch (st->codec->codec_id) {
1536 case AV_CODEC_ID_MP2:
1537 case AV_CODEC_ID_MP3:
1538 st->need_parsing = AVSTREAM_PARSE_FULL;
1544 switch (st->codec->codec_id) {
1545 case AV_CODEC_ID_PCM_S8:
1546 case AV_CODEC_ID_PCM_U8:
1547 if (st->codec->bits_per_coded_sample == 16)
1548 st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1550 case AV_CODEC_ID_PCM_S16LE:
1551 case AV_CODEC_ID_PCM_S16BE:
1552 if (st->codec->bits_per_coded_sample == 8)
1553 st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1554 else if (st->codec->bits_per_coded_sample == 24)
1555 st->codec->codec_id =
1556 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1557 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1559 /* set values for old format before stsd version 1 appeared */
1560 case AV_CODEC_ID_MACE3:
1561 sc->samples_per_frame = 6;
1562 sc->bytes_per_frame = 2 * st->codec->channels;
1564 case AV_CODEC_ID_MACE6:
1565 sc->samples_per_frame = 6;
1566 sc->bytes_per_frame = 1 * st->codec->channels;
1568 case AV_CODEC_ID_ADPCM_IMA_QT:
1569 sc->samples_per_frame = 64;
1570 sc->bytes_per_frame = 34 * st->codec->channels;
1572 case AV_CODEC_ID_GSM:
1573 sc->samples_per_frame = 160;
1574 sc->bytes_per_frame = 33;
1580 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1581 if (bits_per_sample) {
1582 st->codec->bits_per_coded_sample = bits_per_sample;
1583 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1587 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1588 AVStream *st, MOVStreamContext *sc,
1591 // ttxt stsd contains display flags, justification, background
1592 // color, fonts, and default styles, so fake an atom to read it
1593 MOVAtom fake_atom = { .size = size };
1594 // mp4s contains a regular esds atom
1595 if (st->codec->codec_tag != AV_RL32("mp4s"))
1596 mov_read_glbl(c, pb, fake_atom);
1597 st->codec->width = sc->width;
1598 st->codec->height = sc->height;
1601 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1606 y = (ycbcr >> 16) & 0xFF;
1607 cr = (ycbcr >> 8) & 0xFF;
1610 b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
1611 g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
1612 r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
1614 return (r << 16) | (g << 8) | b;
1617 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1619 char buf[256] = {0};
1620 uint8_t *src = st->codec->extradata;
1623 if (st->codec->extradata_size != 64)
1626 if (st->codec->width > 0 && st->codec->height > 0)
1627 snprintf(buf, sizeof(buf), "size: %dx%d\n",
1628 st->codec->width, st->codec->height);
1629 av_strlcat(buf, "palette: ", sizeof(buf));
1631 for (i = 0; i < 16; i++) {
1632 uint32_t yuv = AV_RB32(src + i * 4);
1633 uint32_t rgba = yuv_to_rgba(yuv);
1635 av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1638 if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1641 av_freep(&st->codec->extradata);
1642 st->codec->extradata_size = 0;
1643 st->codec->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
1644 if (!st->codec->extradata)
1645 return AVERROR(ENOMEM);
1646 st->codec->extradata_size = strlen(buf);
1647 memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1652 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1653 AVStream *st, MOVStreamContext *sc,
1658 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1659 st->codec->extradata_size = size;
1660 st->codec->extradata = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
1661 if (!st->codec->extradata)
1662 return AVERROR(ENOMEM);
1663 ret = ffio_read_size(pb, st->codec->extradata, size);
1667 /* other codec type, just skip (rtp, mp4s ...) */
1668 avio_skip(pb, size);
1673 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1674 AVStream *st, MOVStreamContext *sc)
1676 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1677 !st->codec->sample_rate && sc->time_scale > 1)
1678 st->codec->sample_rate = sc->time_scale;
1680 /* special codec parameters handling */
1681 switch (st->codec->codec_id) {
1682 #if CONFIG_DV_DEMUXER
1683 case AV_CODEC_ID_DVAUDIO:
1684 c->dv_fctx = avformat_alloc_context();
1686 av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
1687 return AVERROR(ENOMEM);
1689 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1691 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1692 return AVERROR(ENOMEM);
1694 sc->dv_audio_container = 1;
1695 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1698 /* no ifdef since parameters are always those */
1699 case AV_CODEC_ID_QCELP:
1700 st->codec->channels = 1;
1701 // force sample rate for qcelp when not stored in mov
1702 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1703 st->codec->sample_rate = 8000;
1705 case AV_CODEC_ID_AMR_NB:
1706 st->codec->channels = 1;
1707 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1708 st->codec->sample_rate = 8000;
1710 case AV_CODEC_ID_AMR_WB:
1711 st->codec->channels = 1;
1712 st->codec->sample_rate = 16000;
1714 case AV_CODEC_ID_MP2:
1715 case AV_CODEC_ID_MP3:
1716 /* force type after stsd for m1a hdlr */
1717 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1719 case AV_CODEC_ID_GSM:
1720 case AV_CODEC_ID_ADPCM_MS:
1721 case AV_CODEC_ID_ADPCM_IMA_WAV:
1722 case AV_CODEC_ID_ILBC:
1723 st->codec->block_align = sc->bytes_per_frame;
1725 case AV_CODEC_ID_ALAC:
1726 if (st->codec->extradata_size == 36) {
1727 st->codec->channels = AV_RB8 (st->codec->extradata + 21);
1728 st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
1731 case AV_CODEC_ID_VC1:
1732 st->need_parsing = AVSTREAM_PARSE_FULL;
1740 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
1741 int codec_tag, int format,
1744 int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1747 (codec_tag == AV_RL32("avc1") ||
1748 codec_tag == AV_RL32("hvc1") ||
1749 codec_tag == AV_RL32("hev1") ||
1750 (codec_tag != format &&
1751 (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1752 : codec_tag != MKTAG('j','p','e','g'))))) {
1753 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1754 * export it as a separate AVStream but this needs a few changes
1755 * in the MOV demuxer, patch welcome. */
1757 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1758 avio_skip(pb, size);
1765 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1768 MOVStreamContext *sc;
1769 int pseudo_stream_id;
1771 if (c->fc->nb_streams < 1)
1773 st = c->fc->streams[c->fc->nb_streams-1];
1776 for (pseudo_stream_id = 0;
1777 pseudo_stream_id < entries && !pb->eof_reached;
1778 pseudo_stream_id++) {
1779 //Parsing Sample description table
1781 int ret, dref_id = 1;
1782 MOVAtom a = { AV_RL32("stsd") };
1783 int64_t start_pos = avio_tell(pb);
1784 uint32_t size = avio_rb32(pb); /* size */
1785 uint32_t format = avio_rl32(pb); /* data format */
1788 avio_rb32(pb); /* reserved */
1789 avio_rb16(pb); /* reserved */
1790 dref_id = avio_rb16(pb);
1792 av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRIu32" in stsd\n", size);
1793 return AVERROR_INVALIDDATA;
1796 if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
1797 size - (avio_tell(pb) - start_pos)))
1800 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1801 sc->dref_id= dref_id;
1803 id = mov_codec_id(st, format);
1805 av_log(c->fc, AV_LOG_TRACE,
1806 "size=%"PRIu32" format=0x%08x codec_type=%d\n",
1807 size, format, st->codec->codec_type);
1809 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1810 st->codec->codec_id = id;
1811 mov_parse_stsd_video(c, pb, st, sc);
1812 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1813 st->codec->codec_id = id;
1814 mov_parse_stsd_audio(c, pb, st, sc);
1815 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1816 st->codec->codec_id = id;
1817 mov_parse_stsd_subtitle(c, pb, st, sc,
1818 size - (avio_tell(pb) - start_pos));
1820 ret = mov_parse_stsd_data(c, pb, st, sc,
1821 size - (avio_tell(pb) - start_pos));
1825 /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1826 a.size = size - (avio_tell(pb) - start_pos);
1828 if ((ret = mov_read_default(c, pb, a)) < 0)
1830 } else if (a.size > 0)
1831 avio_skip(pb, a.size);
1834 if (pb->eof_reached)
1837 return mov_finalize_stsd_codec(c, pb, st, sc);
1840 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1844 avio_r8(pb); /* version */
1845 avio_rb24(pb); /* flags */
1846 entries = avio_rb32(pb);
1848 return ff_mov_read_stsd_entries(c, pb, entries);
1851 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1854 MOVStreamContext *sc;
1855 unsigned int i, entries;
1857 if (c->fc->nb_streams < 1)
1859 st = c->fc->streams[c->fc->nb_streams-1];
1862 avio_r8(pb); /* version */
1863 avio_rb24(pb); /* flags */
1865 entries = avio_rb32(pb);
1867 av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1871 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1872 return AVERROR_INVALIDDATA;
1873 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1875 return AVERROR(ENOMEM);
1877 for (i = 0; i < entries && !pb->eof_reached; i++) {
1878 sc->stsc_data[i].first = avio_rb32(pb);
1879 sc->stsc_data[i].count = avio_rb32(pb);
1880 sc->stsc_data[i].id = avio_rb32(pb);
1885 if (pb->eof_reached)
1891 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1894 MOVStreamContext *sc;
1895 unsigned i, entries;
1897 if (c->fc->nb_streams < 1)
1899 st = c->fc->streams[c->fc->nb_streams-1];
1902 avio_rb32(pb); // version + flags
1904 entries = avio_rb32(pb);
1905 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1906 return AVERROR_INVALIDDATA;
1907 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1909 return AVERROR(ENOMEM);
1911 for (i = 0; i < entries && !pb->eof_reached; i++) {
1912 sc->stps_data[i] = avio_rb32(pb);
1913 //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
1918 if (pb->eof_reached)
1924 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1927 MOVStreamContext *sc;
1928 unsigned int i, entries;
1930 if (c->fc->nb_streams < 1)
1932 st = c->fc->streams[c->fc->nb_streams-1];
1935 avio_r8(pb); /* version */
1936 avio_rb24(pb); /* flags */
1938 entries = avio_rb32(pb);
1940 av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
1944 sc->keyframe_absent = 1;
1947 if (entries >= UINT_MAX / sizeof(int))
1948 return AVERROR_INVALIDDATA;
1949 av_freep(&sc->keyframes);
1950 sc->keyframes = av_malloc(entries * sizeof(int));
1952 return AVERROR(ENOMEM);
1954 for (i = 0; i < entries && !pb->eof_reached; i++) {
1955 sc->keyframes[i] = avio_rb32(pb);
1956 //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
1959 sc->keyframe_count = i;
1961 if (pb->eof_reached)
1967 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1970 MOVStreamContext *sc;
1971 unsigned int i, entries, sample_size, field_size, num_bytes;
1976 if (c->fc->nb_streams < 1)
1978 st = c->fc->streams[c->fc->nb_streams-1];
1981 avio_r8(pb); /* version */
1982 avio_rb24(pb); /* flags */
1984 if (atom.type == MKTAG('s','t','s','z')) {
1985 sample_size = avio_rb32(pb);
1986 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1987 sc->sample_size = sample_size;
1991 avio_rb24(pb); /* reserved */
1992 field_size = avio_r8(pb);
1994 entries = avio_rb32(pb);
1996 av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1998 sc->sample_count = entries;
2002 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2003 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2004 return AVERROR_INVALIDDATA;
2009 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
2010 return AVERROR_INVALIDDATA;
2011 sc->sample_sizes = av_malloc(entries * sizeof(int));
2012 if (!sc->sample_sizes)
2013 return AVERROR(ENOMEM);
2015 num_bytes = (entries*field_size+4)>>3;
2017 buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2019 av_freep(&sc->sample_sizes);
2020 return AVERROR(ENOMEM);
2023 ret = ffio_read_size(pb, buf, num_bytes);
2025 av_freep(&sc->sample_sizes);
2030 init_get_bits(&gb, buf, 8*num_bytes);
2032 for (i = 0; i < entries && !pb->eof_reached; i++) {
2033 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2034 sc->data_size += sc->sample_sizes[i];
2037 sc->sample_count = i;
2041 if (pb->eof_reached)
2047 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2050 MOVStreamContext *sc;
2051 unsigned int i, entries;
2053 int64_t total_sample_count=0;
2055 if (c->fc->nb_streams < 1)
2057 st = c->fc->streams[c->fc->nb_streams-1];
2060 avio_r8(pb); /* version */
2061 avio_rb24(pb); /* flags */
2062 entries = avio_rb32(pb);
2064 av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2065 c->fc->nb_streams-1, entries);
2069 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
2070 return AVERROR(EINVAL);
2072 av_free(sc->stts_data);
2073 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
2075 return AVERROR(ENOMEM);
2077 for (i = 0; i < entries && !pb->eof_reached; i++) {
2078 int sample_duration;
2081 sample_count=avio_rb32(pb);
2082 sample_duration = avio_rb32(pb);
2083 if (sample_count < 0) {
2084 av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2085 return AVERROR_INVALIDDATA;
2087 sc->stts_data[i].count= sample_count;
2088 sc->stts_data[i].duration= sample_duration;
2090 av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2091 sample_count, sample_duration);
2093 duration+=(int64_t)sample_duration*sample_count;
2094 total_sample_count+=sample_count;
2099 if (pb->eof_reached)
2102 st->nb_frames= total_sample_count;
2104 st->duration= duration;
2105 sc->track_end = duration;
2109 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2112 MOVStreamContext *sc;
2113 unsigned int i, entries;
2115 if (c->fc->nb_streams < 1)
2117 st = c->fc->streams[c->fc->nb_streams-1];
2120 avio_r8(pb); /* version */
2121 avio_rb24(pb); /* flags */
2122 entries = avio_rb32(pb);
2124 av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2126 av_freep(&sc->ctts_data);
2130 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2131 return AVERROR_INVALIDDATA;
2132 sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2134 return AVERROR(ENOMEM);
2136 for (i = 0; i < entries && !pb->eof_reached; i++) {
2137 int count =avio_rb32(pb);
2138 int duration =avio_rb32(pb);
2140 sc->ctts_data[i].count = count;
2141 sc->ctts_data[i].duration= duration;
2143 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2148 if (pb->eof_reached)
2151 av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2156 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2159 MOVStreamContext *sc;
2160 unsigned int i, entries;
2162 uint32_t grouping_type;
2164 if (c->fc->nb_streams < 1)
2166 st = c->fc->streams[c->fc->nb_streams-1];
2169 version = avio_r8(pb); /* version */
2170 avio_rb24(pb); /* flags */
2171 grouping_type = avio_rl32(pb);
2172 if (grouping_type != MKTAG( 'r','a','p',' '))
2173 return 0; /* only support 'rap ' grouping */
2175 avio_rb32(pb); /* grouping_type_parameter */
2177 entries = avio_rb32(pb);
2180 if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2181 return AVERROR_INVALIDDATA;
2182 sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2184 return AVERROR(ENOMEM);
2186 for (i = 0; i < entries && !pb->eof_reached; i++) {
2187 sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2188 sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2191 sc->rap_group_count = i;
2193 return pb->eof_reached ? AVERROR_EOF : 0;
2196 static void mov_build_index(MOVContext *mov, AVStream *st)
2198 MOVStreamContext *sc = st->priv_data;
2199 int64_t current_offset;
2200 int64_t current_dts = 0;
2201 unsigned int stts_index = 0;
2202 unsigned int stsc_index = 0;
2203 unsigned int stss_index = 0;
2204 unsigned int stps_index = 0;
2206 uint64_t stream_size = 0;
2208 /* adjust first dts according to edit list */
2209 if (sc->time_offset && mov->time_scale > 0) {
2210 if (sc->time_offset < 0)
2211 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
2212 current_dts = -sc->time_offset;
2213 if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
2214 sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
2215 /* more than 16 frames delay, dts are likely wrong
2216 this happens with files created by iMovie */
2218 st->codec->has_b_frames = 1;
2222 /* only use old uncompressed audio chunk demuxing when stts specifies it */
2223 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2224 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2225 unsigned int current_sample = 0;
2226 unsigned int stts_sample = 0;
2227 unsigned int sample_size;
2228 unsigned int distance = 0;
2229 unsigned int rap_group_index = 0;
2230 unsigned int rap_group_sample = 0;
2231 int rap_group_present = sc->rap_group_count && sc->rap_group;
2232 int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
2234 current_dts -= sc->dts_shift;
2236 if (!sc->sample_count)
2238 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2240 if (av_reallocp_array(&st->index_entries,
2241 st->nb_index_entries + sc->sample_count,
2242 sizeof(*st->index_entries)) < 0) {
2243 st->nb_index_entries = 0;
2246 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2248 for (i = 0; i < sc->chunk_count; i++) {
2249 current_offset = sc->chunk_offsets[i];
2250 while (stsc_index + 1 < sc->stsc_count &&
2251 i + 1 == sc->stsc_data[stsc_index + 1].first)
2253 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2255 if (current_sample >= sc->sample_count) {
2256 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2260 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2262 if (stss_index + 1 < sc->keyframe_count)
2264 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2266 if (stps_index + 1 < sc->stps_count)
2269 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2270 if (sc->rap_group[rap_group_index].index > 0)
2272 if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2273 rap_group_sample = 0;
2279 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
2280 if (sc->pseudo_stream_id == -1 ||
2281 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2282 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2283 e->pos = current_offset;
2284 e->timestamp = current_dts;
2285 e->size = sample_size;
2286 e->min_distance = distance;
2287 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2288 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2289 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2290 current_offset, current_dts, sample_size, distance, keyframe);
2293 current_offset += sample_size;
2294 stream_size += sample_size;
2295 current_dts += sc->stts_data[stts_index].duration;
2299 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2305 if (st->duration > 0)
2306 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2308 unsigned chunk_samples, total = 0;
2310 // compute total chunk count
2311 for (i = 0; i < sc->stsc_count; i++) {
2312 unsigned count, chunk_count;
2314 chunk_samples = sc->stsc_data[i].count;
2315 if (i != sc->stsc_count - 1 &&
2316 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2317 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2321 if (sc->samples_per_frame >= 160) { // gsm
2322 count = chunk_samples / sc->samples_per_frame;
2323 } else if (sc->samples_per_frame > 1) {
2324 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2325 count = (chunk_samples+samples-1) / samples;
2327 count = (chunk_samples+1023) / 1024;
2330 if (i < sc->stsc_count - 1)
2331 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2333 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2334 total += chunk_count * count;
2337 av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2338 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2340 if (av_reallocp_array(&st->index_entries,
2341 st->nb_index_entries + total,
2342 sizeof(*st->index_entries)) < 0) {
2343 st->nb_index_entries = 0;
2346 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2349 for (i = 0; i < sc->chunk_count; i++) {
2350 current_offset = sc->chunk_offsets[i];
2351 if (stsc_index + 1 < sc->stsc_count &&
2352 i + 1 == sc->stsc_data[stsc_index + 1].first)
2354 chunk_samples = sc->stsc_data[stsc_index].count;
2356 while (chunk_samples > 0) {
2358 unsigned size, samples;
2360 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2361 avpriv_request_sample(mov->fc,
2362 "Zero bytes per frame, but %d samples per frame",
2363 sc->samples_per_frame);
2367 if (sc->samples_per_frame >= 160) { // gsm
2368 samples = sc->samples_per_frame;
2369 size = sc->bytes_per_frame;
2371 if (sc->samples_per_frame > 1) {
2372 samples = FFMIN((1024 / sc->samples_per_frame)*
2373 sc->samples_per_frame, chunk_samples);
2374 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2376 samples = FFMIN(1024, chunk_samples);
2377 size = samples * sc->sample_size;
2381 if (st->nb_index_entries >= total) {
2382 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2385 e = &st->index_entries[st->nb_index_entries++];
2386 e->pos = current_offset;
2387 e->timestamp = current_dts;
2389 e->min_distance = 0;
2390 e->flags = AVINDEX_KEYFRAME;
2391 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2392 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2395 current_offset += size;
2396 current_dts += samples;
2397 chunk_samples -= samples;
2403 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
2404 AVIOInterruptCB *int_cb)
2406 /* try relative path, we do not try the absolute because it can leak information about our
2407 system to an attacker */
2408 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2409 char filename[1024];
2413 /* find a source dir */
2414 src_path = strrchr(src, '/');
2420 /* find a next level down to target */
2421 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2422 if (ref->path[l] == '/') {
2423 if (i == ref->nlvl_to - 1)
2429 /* compose filename if next level down to target was found */
2430 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2431 memcpy(filename, src, src_path - src);
2432 filename[src_path - src] = 0;
2434 for (i = 1; i < ref->nlvl_from; i++)
2435 av_strlcat(filename, "../", 1024);
2437 av_strlcat(filename, ref->path + l + 1, 1024);
2439 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2444 return AVERROR(ENOENT);
2447 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2450 MOVStreamContext *sc;
2453 st = avformat_new_stream(c->fc, NULL);
2454 if (!st) return AVERROR(ENOMEM);
2455 st->id = c->fc->nb_streams;
2456 sc = av_mallocz(sizeof(MOVStreamContext));
2457 if (!sc) return AVERROR(ENOMEM);
2460 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2461 sc->ffindex = st->index;
2463 if ((ret = mov_read_default(c, pb, atom)) < 0)
2467 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2468 (!sc->sample_size && !sc->sample_count))) {
2469 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2474 if (sc->time_scale <= 0) {
2475 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2476 sc->time_scale = c->time_scale;
2477 if (sc->time_scale <= 0)
2481 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2483 mov_build_index(c, st);
2485 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2486 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2487 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
2488 av_log(c->fc, AV_LOG_ERROR,
2489 "stream %d, error opening alias: path='%s', dir='%s', "
2490 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2491 st->index, dref->path, dref->dir, dref->filename,
2492 dref->volume, dref->nlvl_from, dref->nlvl_to);
2496 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2497 if (!st->sample_aspect_ratio.num &&
2498 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2499 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2500 ((double)st->codec->width * sc->height), INT_MAX);
2504 // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2505 if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2506 TAG_IS_AVCI(st->codec->codec_tag)) {
2507 ret = ff_generate_avci_extradata(st);
2512 switch (st->codec->codec_id) {
2513 #if CONFIG_H261_DECODER
2514 case AV_CODEC_ID_H261:
2516 #if CONFIG_H263_DECODER
2517 case AV_CODEC_ID_H263:
2519 #if CONFIG_MPEG4_DECODER
2520 case AV_CODEC_ID_MPEG4:
2522 st->codec->width = 0; /* let decoder init width/height */
2523 st->codec->height= 0;
2527 /* Do not need those anymore. */
2528 av_freep(&sc->chunk_offsets);
2529 av_freep(&sc->stsc_data);
2530 av_freep(&sc->sample_sizes);
2531 av_freep(&sc->keyframes);
2532 av_freep(&sc->stts_data);
2533 av_freep(&sc->stps_data);
2534 av_freep(&sc->rap_group);
2539 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2542 c->itunes_metadata = 1;
2543 ret = mov_read_default(c, pb, atom);
2544 c->itunes_metadata = 0;
2548 static int mov_read_replaygain(MOVContext *c, AVIOContext *pb, int size)
2550 int64_t end = avio_tell(pb) + size;
2551 uint8_t *key = NULL, *val = NULL;
2554 for (i = 0; i < 2; i++) {
2559 if (end - avio_tell(pb) <= 12)
2562 len = avio_rb32(pb);
2563 tag = avio_rl32(pb);
2564 avio_skip(pb, 4); // flags
2566 if (len < 12 || len - 12 > end - avio_tell(pb))
2570 if (tag == MKTAG('n', 'a', 'm', 'e'))
2572 else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2579 *p = av_malloc(len + 1);
2582 ret = ffio_read_size(pb, *p, len);
2591 av_dict_set(&c->fc->metadata, key, val,
2592 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2596 avio_seek(pb, end, SEEK_SET);
2602 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2604 int64_t end = avio_tell(pb) + atom.size;
2610 len = avio_rb32(pb);
2611 tag = avio_rl32(pb);
2613 if (len > atom.size)
2616 if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2617 uint8_t domain[128];
2620 avio_skip(pb, 4); // flags
2623 domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2624 avio_skip(pb, len - domain_len);
2625 if (!strcmp(domain, "org.hydrogenaudio.replaygain"))
2626 return mov_read_replaygain(c, pb, end - avio_tell(pb));
2630 av_log(c->fc, AV_LOG_VERBOSE,
2631 "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2635 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2637 while (atom.size > 8) {
2638 uint32_t tag = avio_rl32(pb);
2640 if (tag == MKTAG('h','d','l','r')) {
2641 avio_seek(pb, -8, SEEK_CUR);
2643 return mov_read_default(c, pb, atom);
2649 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2654 int64_t disp_transform[2];
2655 int display_matrix[3][3];
2657 MOVStreamContext *sc;
2661 if (c->fc->nb_streams < 1)
2663 st = c->fc->streams[c->fc->nb_streams-1];
2666 version = avio_r8(pb);
2667 flags = avio_rb24(pb);
2668 st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2674 avio_rb32(pb); /* creation time */
2675 avio_rb32(pb); /* modification time */
2677 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2678 avio_rb32(pb); /* reserved */
2680 /* highlevel (considering edits) duration in movie timebase */
2681 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2682 avio_rb32(pb); /* reserved */
2683 avio_rb32(pb); /* reserved */
2685 avio_rb16(pb); /* layer */
2686 avio_rb16(pb); /* alternate group */
2687 avio_rb16(pb); /* volume */
2688 avio_rb16(pb); /* reserved */
2690 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2691 // they're kept in fixed point format through all calculations
2692 // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2693 // side data, but the scale factor is not needed to calculate aspect ratio
2694 for (i = 0; i < 3; i++) {
2695 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2696 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2697 display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
2700 width = avio_rb32(pb); // 16.16 fixed point track width
2701 height = avio_rb32(pb); // 16.16 fixed point track height
2702 sc->width = width >> 16;
2703 sc->height = height >> 16;
2705 // save the matrix when it is not the default identity
2706 if (display_matrix[0][0] != (1 << 16) ||
2707 display_matrix[1][1] != (1 << 16) ||
2708 display_matrix[2][2] != (1 << 30) ||
2709 display_matrix[0][1] || display_matrix[0][2] ||
2710 display_matrix[1][0] || display_matrix[1][2] ||
2711 display_matrix[2][0] || display_matrix[2][1]) {
2714 av_freep(&sc->display_matrix);
2715 sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2716 if (!sc->display_matrix)
2717 return AVERROR(ENOMEM);
2719 for (i = 0; i < 3; i++)
2720 for (j = 0; j < 3; j++)
2721 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
2724 // transform the display width/height according to the matrix
2725 // skip this when the display matrix is the identity one
2726 // to keep the same scale, use [width height 1<<16]
2727 if (width && height && sc->display_matrix) {
2728 for (i = 0; i < 2; i++)
2730 (int64_t) width * display_matrix[0][i] +
2731 (int64_t) height * display_matrix[1][i] +
2732 ((int64_t) display_matrix[2][i] << 16);
2734 //sample aspect ratio is new width/height divided by old width/height
2735 if (disp_transform[0] > 0 && disp_transform[1] > 0)
2736 st->sample_aspect_ratio = av_d2q(
2737 ((double) disp_transform[0] * height) /
2738 ((double) disp_transform[1] * width), INT_MAX);
2743 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2745 MOVFragment *frag = &c->fragment;
2746 MOVTrackExt *trex = NULL;
2747 int flags, track_id, i;
2749 avio_r8(pb); /* version */
2750 flags = avio_rb24(pb);
2752 track_id = avio_rb32(pb);
2754 return AVERROR_INVALIDDATA;
2755 frag->track_id = track_id;
2756 for (i = 0; i < c->trex_count; i++)
2757 if (c->trex_data[i].track_id == frag->track_id) {
2758 trex = &c->trex_data[i];
2762 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2763 return AVERROR_INVALIDDATA;
2766 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2767 avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
2768 frag->moof_offset : frag->implicit_offset;
2769 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2771 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2772 avio_rb32(pb) : trex->duration;
2773 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2774 avio_rb32(pb) : trex->size;
2775 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2776 avio_rb32(pb) : trex->flags;
2777 av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
2781 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2783 c->chapter_track = avio_rb32(pb);
2787 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2792 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2793 return AVERROR_INVALIDDATA;
2794 if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2795 sizeof(*c->trex_data))) < 0) {
2799 trex = &c->trex_data[c->trex_count++];
2800 avio_r8(pb); /* version */
2801 avio_rb24(pb); /* flags */
2802 trex->track_id = avio_rb32(pb);
2803 trex->stsd_id = avio_rb32(pb);
2804 trex->duration = avio_rb32(pb);
2805 trex->size = avio_rb32(pb);
2806 trex->flags = avio_rb32(pb);
2810 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2812 MOVFragment *frag = &c->fragment;
2813 AVStream *st = NULL;
2814 MOVStreamContext *sc;
2817 for (i = 0; i < c->fc->nb_streams; i++) {
2818 if (c->fc->streams[i]->id == frag->track_id) {
2819 st = c->fc->streams[i];
2824 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2825 return AVERROR_INVALIDDATA;
2828 if (sc->pseudo_stream_id + 1 != frag->stsd_id)
2830 version = avio_r8(pb);
2831 avio_rb24(pb); /* flags */
2833 sc->track_end = avio_rb64(pb);
2835 sc->track_end = avio_rb32(pb);
2840 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2842 MOVFragment *frag = &c->fragment;
2843 AVStream *st = NULL;
2844 MOVStreamContext *sc;
2848 int data_offset = 0;
2849 unsigned entries, first_sample_flags = frag->flags;
2850 int flags, distance, i, err;
2852 for (i = 0; i < c->fc->nb_streams; i++) {
2853 if (c->fc->streams[i]->id == frag->track_id) {
2854 st = c->fc->streams[i];
2859 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2860 return AVERROR_INVALIDDATA;
2863 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2865 avio_r8(pb); /* version */
2866 flags = avio_rb24(pb);
2867 entries = avio_rb32(pb);
2868 av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
2870 /* Always assume the presence of composition time offsets.
2871 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2872 * 1) in the initial movie, there are no samples.
2873 * 2) in the first movie fragment, there is only one sample without composition time offset.
2874 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2875 if (!sc->ctts_count && sc->sample_count)
2877 /* Complement ctts table if moov atom doesn't have ctts atom. */
2878 ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
2880 return AVERROR(ENOMEM);
2881 sc->ctts_data = ctts_data;
2882 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2883 sc->ctts_data[sc->ctts_count].duration = 0;
2886 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2887 return AVERROR_INVALIDDATA;
2888 if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
2889 sizeof(*sc->ctts_data))) < 0) {
2893 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2894 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2895 dts = sc->track_end - sc->time_offset;
2896 offset = frag->base_data_offset + data_offset;
2898 av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
2899 for (i = 0; i < entries && !pb->eof_reached; i++) {
2900 unsigned sample_size = frag->size;
2901 int sample_flags = i ? frag->flags : first_sample_flags;
2902 unsigned sample_duration = frag->duration;
2905 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2906 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2907 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2908 sc->ctts_data[sc->ctts_count].count = 1;
2909 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2912 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2916 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2917 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2920 av_add_index_entry(st, offset, dts, sample_size, distance,
2921 keyframe ? AVINDEX_KEYFRAME : 0);
2922 av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2923 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2924 offset, dts, sample_size, distance, keyframe);
2926 dts += sample_duration;
2927 offset += sample_size;
2928 sc->data_size += sample_size;
2931 if (pb->eof_reached)
2934 frag->implicit_offset = offset;
2935 st->duration = sc->track_end = dts + sc->time_offset;
2939 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2940 /* like the files created with Adobe Premiere 5.0, for samples see */
2941 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2942 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2947 return 0; /* continue */
2948 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2949 avio_skip(pb, atom.size - 4);
2952 atom.type = avio_rl32(pb);
2954 if (atom.type != MKTAG('m','d','a','t')) {
2955 avio_skip(pb, atom.size);
2958 err = mov_read_mdat(c, pb, atom);
2962 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2967 uint8_t *moov_data; /* uncompressed data */
2968 long cmov_len, moov_len;
2971 avio_rb32(pb); /* dcom atom */
2972 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2973 return AVERROR_INVALIDDATA;
2974 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2975 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2976 return AVERROR_INVALIDDATA;
2978 avio_rb32(pb); /* cmvd atom */
2979 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2980 return AVERROR_INVALIDDATA;
2981 moov_len = avio_rb32(pb); /* uncompressed size */
2982 cmov_len = atom.size - 6 * 4;
2984 cmov_data = av_malloc(cmov_len);
2986 return AVERROR(ENOMEM);
2987 moov_data = av_malloc(moov_len);
2990 return AVERROR(ENOMEM);
2992 ret = ffio_read_size(pb, cmov_data, cmov_len);
2994 goto free_and_return;
2996 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2997 goto free_and_return;
2998 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2999 goto free_and_return;
3000 atom.type = MKTAG('m','o','o','v');
3001 atom.size = moov_len;
3002 ret = mov_read_default(c, &ctx, atom);
3008 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3009 return AVERROR(ENOSYS);
3013 /* edit list atom */
3014 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3016 MOVStreamContext *sc;
3017 int i, edit_count, version;
3019 if (c->fc->nb_streams < 1)
3021 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3023 version = avio_r8(pb); /* version */
3024 avio_rb24(pb); /* flags */
3025 edit_count = avio_rb32(pb); /* entries */
3027 if ((uint64_t)edit_count*12+8 > atom.size)
3028 return AVERROR_INVALIDDATA;
3030 for (i=0; i<edit_count; i++){
3034 duration = avio_rb64(pb);
3035 time = avio_rb64(pb);
3037 duration = avio_rb32(pb); /* segment duration */
3038 time = (int32_t)avio_rb32(pb); /* media time */
3040 avio_rb32(pb); /* Media rate */
3041 if (i == 0 && time >= -1) {
3042 sc->time_offset = time != -1 ? time : -duration;
3047 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
3048 "a/v desync might occur, patch welcome\n");
3050 av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3054 static const MOVParseTableEntry mov_default_parse_table[] = {
3055 { MKTAG('a','v','s','s'), mov_read_extradata },
3056 { MKTAG('c','h','p','l'), mov_read_chpl },
3057 { MKTAG('c','o','6','4'), mov_read_stco },
3058 { MKTAG('c','o','l','r'), mov_read_colr },
3059 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3060 { MKTAG('d','i','n','f'), mov_read_default },
3061 { MKTAG('d','r','e','f'), mov_read_dref },
3062 { MKTAG('e','d','t','s'), mov_read_default },
3063 { MKTAG('e','l','s','t'), mov_read_elst },
3064 { MKTAG('e','n','d','a'), mov_read_enda },
3065 { MKTAG('f','i','e','l'), mov_read_fiel },
3066 { MKTAG('f','t','y','p'), mov_read_ftyp },
3067 { MKTAG('g','l','b','l'), mov_read_glbl },
3068 { MKTAG('h','d','l','r'), mov_read_hdlr },
3069 { MKTAG('i','l','s','t'), mov_read_ilst },
3070 { MKTAG('j','p','2','h'), mov_read_extradata },
3071 { MKTAG('m','d','a','t'), mov_read_mdat },
3072 { MKTAG('m','d','h','d'), mov_read_mdhd },
3073 { MKTAG('m','d','i','a'), mov_read_default },
3074 { MKTAG('m','e','t','a'), mov_read_meta },
3075 { MKTAG('m','i','n','f'), mov_read_default },
3076 { MKTAG('m','o','o','f'), mov_read_moof },
3077 { MKTAG('m','o','o','v'), mov_read_moov },
3078 { MKTAG('m','v','e','x'), mov_read_default },
3079 { MKTAG('m','v','h','d'), mov_read_mvhd },
3080 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
3081 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
3082 { MKTAG('a','v','c','C'), mov_read_glbl },
3083 { MKTAG('p','a','s','p'), mov_read_pasp },
3084 { MKTAG('s','t','b','l'), mov_read_default },
3085 { MKTAG('s','t','c','o'), mov_read_stco },
3086 { MKTAG('s','t','p','s'), mov_read_stps },
3087 { MKTAG('s','t','r','f'), mov_read_strf },
3088 { MKTAG('s','t','s','c'), mov_read_stsc },
3089 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3090 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3091 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3092 { MKTAG('s','t','t','s'), mov_read_stts },
3093 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3094 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3095 { MKTAG('t','f','d','t'), mov_read_tfdt },
3096 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3097 { MKTAG('t','r','a','k'), mov_read_trak },
3098 { MKTAG('t','r','a','f'), mov_read_default },
3099 { MKTAG('t','r','e','f'), mov_read_default },
3100 { MKTAG('c','h','a','p'), mov_read_chap },
3101 { MKTAG('t','r','e','x'), mov_read_trex },
3102 { MKTAG('t','r','u','n'), mov_read_trun },
3103 { MKTAG('u','d','t','a'), mov_read_default },
3104 { MKTAG('w','a','v','e'), mov_read_wave },
3105 { MKTAG('e','s','d','s'), mov_read_esds },
3106 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3107 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3108 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3109 { MKTAG('w','f','e','x'), mov_read_wfex },
3110 { MKTAG('c','m','o','v'), mov_read_cmov },
3111 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3112 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3113 { MKTAG('s','b','g','p'), mov_read_sbgp },
3114 { MKTAG('h','v','c','C'), mov_read_glbl },
3115 { MKTAG('-','-','-','-'), mov_read_custom },
3119 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3121 int64_t total_size = 0;
3126 atom.size = INT64_MAX;
3127 while (total_size + 8 < atom.size && !pb->eof_reached) {
3128 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3131 if (atom.size >= 8) {
3132 a.size = avio_rb32(pb);
3133 a.type = avio_rl32(pb);
3135 av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3136 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3138 if (a.size == 1) { /* 64 bit extended size */
3139 a.size = avio_rb64(pb) - 8;
3143 a.size = atom.size - total_size;
3150 a.size = FFMIN(a.size, atom.size - total_size);
3152 for (i = 0; mov_default_parse_table[i].type; i++)
3153 if (mov_default_parse_table[i].type == a.type) {
3154 parse = mov_default_parse_table[i].parse;
3158 // container is user data
3159 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3160 atom.type == MKTAG('i','l','s','t')))
3161 parse = mov_read_udta_string;
3163 if (!parse) { /* skip leaf atoms data */
3164 avio_skip(pb, a.size);
3166 int64_t start_pos = avio_tell(pb);
3168 int err = parse(c, pb, a);
3171 if (c->found_moov && c->found_mdat &&
3172 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3173 start_pos + a.size == avio_size(pb))) {
3174 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3175 c->next_root_atom = start_pos + a.size;
3178 left = a.size - avio_tell(pb) + start_pos;
3179 if (left > 0) /* skip garbage at atom end */
3180 avio_skip(pb, left);
3181 else if (left < 0) {
3182 av_log(c->fc, AV_LOG_WARNING,
3183 "overread end of atom '%.4s' by %"PRId64" bytes\n",
3184 (char*)&a.type, -left);
3185 avio_seek(pb, left, SEEK_CUR);
3189 total_size += a.size;
3192 if (total_size < atom.size && atom.size < 0x7ffff)
3193 avio_skip(pb, atom.size - total_size);
3198 static int mov_probe(AVProbeData *p)
3200 unsigned int offset;
3204 /* check file header */
3207 /* ignore invalid offset */
3208 if ((offset + 8) > (unsigned int)p->buf_size)
3210 tag = AV_RL32(p->buf + offset + 4);
3212 /* check for obvious tags */
3213 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
3214 case MKTAG('m','o','o','v'):
3215 case MKTAG('m','d','a','t'):
3216 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3217 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3218 case MKTAG('f','t','y','p'):
3219 return AVPROBE_SCORE_MAX;
3220 /* those are more common words, so rate then a bit less */
3221 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3222 case MKTAG('w','i','d','e'):
3223 case MKTAG('f','r','e','e'):
3224 case MKTAG('j','u','n','k'):
3225 case MKTAG('p','i','c','t'):
3226 return AVPROBE_SCORE_MAX - 5;
3227 case MKTAG(0x82,0x82,0x7f,0x7d):
3228 case MKTAG('s','k','i','p'):
3229 case MKTAG('u','u','i','d'):
3230 case MKTAG('p','r','f','l'):
3231 offset = AV_RB32(p->buf+offset) + offset;
3232 /* if we only find those cause probedata is too small at least rate them */
3233 score = AVPROBE_SCORE_EXTENSION;
3236 /* unrecognized tag */
3242 // must be done after parsing all trak because there's no order requirement
3243 static void mov_read_chapters(AVFormatContext *s)
3245 MOVContext *mov = s->priv_data;
3246 AVStream *st = NULL;
3247 MOVStreamContext *sc;
3251 for (i = 0; i < s->nb_streams; i++)
3252 if (s->streams[i]->id == mov->chapter_track) {
3257 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3261 st->discard = AVDISCARD_ALL;
3263 cur_pos = avio_tell(sc->pb);
3265 for (i = 0; i < st->nb_index_entries; i++) {
3266 AVIndexEntry *sample = &st->index_entries[i];
3267 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3272 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3273 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3277 // the first two bytes are the length of the title
3278 len = avio_rb16(sc->pb);
3279 if (len > sample->size-2)
3281 title_len = 2*len + 1;
3282 if (!(title = av_mallocz(title_len)))
3285 // The samples could theoretically be in any encoding if there's an encd
3286 // atom following, but in practice are only utf-8 or utf-16, distinguished
3287 // instead by the presence of a BOM
3291 ch = avio_rb16(sc->pb);
3293 avio_get_str16be(sc->pb, len, title, title_len);
3294 else if (ch == 0xfffe)
3295 avio_get_str16le(sc->pb, len, title, title_len);
3298 if (len == 1 || len == 2)
3301 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
3305 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3309 avio_seek(sc->pb, cur_pos, SEEK_SET);
3312 static int mov_read_close(AVFormatContext *s)
3314 MOVContext *mov = s->priv_data;
3317 for (i = 0; i < s->nb_streams; i++) {
3318 AVStream *st = s->streams[i];
3319 MOVStreamContext *sc = st->priv_data;
3321 av_freep(&sc->ctts_data);
3322 for (j = 0; j < sc->drefs_count; j++) {
3323 av_freep(&sc->drefs[j].path);
3324 av_freep(&sc->drefs[j].dir);
3326 av_freep(&sc->drefs);
3327 if (sc->pb && sc->pb != s->pb)
3330 av_freep(&sc->chunk_offsets);
3331 av_freep(&sc->stsc_data);
3332 av_freep(&sc->sample_sizes);
3333 av_freep(&sc->keyframes);
3334 av_freep(&sc->stts_data);
3335 av_freep(&sc->stps_data);
3336 av_freep(&sc->rap_group);
3337 av_freep(&sc->display_matrix);
3340 if (mov->dv_demux) {
3341 avformat_free_context(mov->dv_fctx);
3342 mov->dv_fctx = NULL;
3345 av_freep(&mov->trex_data);
3350 static int mov_read_header(AVFormatContext *s)
3352 MOVContext *mov = s->priv_data;
3353 AVIOContext *pb = s->pb;
3355 MOVAtom atom = { AV_RL32("root") };
3359 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3361 atom.size = avio_size(pb);
3363 atom.size = INT64_MAX;
3365 /* check MOV header */
3366 if ((err = mov_read_default(mov, pb, atom)) < 0) {
3367 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3371 if (!mov->found_moov) {
3372 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3374 return AVERROR_INVALIDDATA;
3376 av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3378 if (pb->seekable && mov->chapter_track > 0)
3379 mov_read_chapters(s);
3381 for (i = 0; i < s->nb_streams; i++) {
3382 AVStream *st = s->streams[i];
3383 MOVStreamContext *sc = st->priv_data;
3385 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3386 if (st->codec->width <= 0 || st->codec->height <= 0) {
3387 st->codec->width = sc->width;
3388 st->codec->height = sc->height;
3390 if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3391 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3397 if (mov->trex_data) {
3398 for (i = 0; i < s->nb_streams; i++) {
3399 AVStream *st = s->streams[i];
3400 MOVStreamContext *sc = st->priv_data;
3401 if (st->duration > 0)
3402 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3406 for (i = 0; i < s->nb_streams; i++) {
3407 AVStream *st = s->streams[i];
3408 MOVStreamContext *sc = st->priv_data;
3410 switch (st->codec->codec_type) {
3411 case AVMEDIA_TYPE_AUDIO:
3412 err = ff_replaygain_export(st, s->metadata);
3418 case AVMEDIA_TYPE_VIDEO:
3419 if (sc->display_matrix) {
3420 AVPacketSideData *sd, *tmp;
3422 tmp = av_realloc_array(st->side_data,
3423 st->nb_side_data + 1, sizeof(*tmp));
3425 return AVERROR(ENOMEM);
3427 st->side_data = tmp;
3430 sd = &st->side_data[st->nb_side_data - 1];
3431 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
3432 sd->size = sizeof(int32_t) * 9;
3433 sd->data = (uint8_t*)sc->display_matrix;
3434 sc->display_matrix = NULL;
3443 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3445 AVIndexEntry *sample = NULL;
3446 int64_t best_dts = INT64_MAX;
3448 for (i = 0; i < s->nb_streams; i++) {
3449 AVStream *avst = s->streams[i];
3450 MOVStreamContext *msc = avst->priv_data;
3451 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3452 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3453 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3454 av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3455 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3457 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3458 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3459 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3460 sample = current_sample;
3469 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3471 MOVContext *mov = s->priv_data;
3472 MOVStreamContext *sc;
3473 AVIndexEntry *sample;
3474 AVStream *st = NULL;
3477 sample = mov_find_next_sample(s, &st);
3479 mov->found_mdat = 0;
3480 if (!mov->next_root_atom)
3482 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3483 mov->next_root_atom = 0;
3484 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3487 av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3491 /* must be done just before reading, to avoid infinite loop on sample */
3492 sc->current_sample++;
3494 if (st->discard != AVDISCARD_ALL) {
3495 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3496 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3497 sc->ffindex, sample->pos);
3498 return AVERROR_INVALIDDATA;
3500 ret = av_get_packet(sc->pb, pkt, sample->size);
3503 if (sc->has_palette) {
3506 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3508 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3510 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3511 sc->has_palette = 0;
3514 #if CONFIG_DV_DEMUXER
3515 if (mov->dv_demux && sc->dv_audio_container) {
3516 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
3519 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3526 pkt->stream_index = sc->ffindex;
3527 pkt->dts = sample->timestamp;
3528 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3529 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3530 /* update ctts context */
3532 if (sc->ctts_index < sc->ctts_count &&
3533 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3535 sc->ctts_sample = 0;
3538 pkt->dts = AV_NOPTS_VALUE;
3540 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3541 st->index_entries[sc->current_sample].timestamp : st->duration;
3542 pkt->duration = next_dts - pkt->dts;
3543 pkt->pts = pkt->dts;
3545 if (st->discard == AVDISCARD_ALL)
3547 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3548 pkt->pos = sample->pos;
3549 av_log(s, AV_LOG_TRACE, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %"PRId64"\n",
3550 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3554 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3556 MOVStreamContext *sc = st->priv_data;
3557 int sample, time_sample;
3560 sample = av_index_search_timestamp(st, timestamp, flags);
3561 av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3562 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3564 if (sample < 0) /* not sure what to do */
3565 return AVERROR_INVALIDDATA;
3566 sc->current_sample = sample;
3567 av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
3568 /* adjust ctts index */
3569 if (sc->ctts_data) {
3571 for (i = 0; i < sc->ctts_count; i++) {
3572 int next = time_sample + sc->ctts_data[i].count;
3573 if (next > sc->current_sample) {
3575 sc->ctts_sample = sc->current_sample - time_sample;
3584 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3586 MOVContext *mc = s->priv_data;
3591 if (stream_index >= s->nb_streams)
3592 return AVERROR_INVALIDDATA;
3593 if (sample_time < 0)
3596 st = s->streams[stream_index];
3597 sample = mov_seek_stream(s, st, sample_time, flags);
3601 if (mc->seek_individually) {
3602 /* adjust seek timestamp to found sample timestamp */
3603 int64_t seek_timestamp = st->index_entries[sample].timestamp;
3605 for (i = 0; i < s->nb_streams; i++) {
3608 if (stream_index == i)
3611 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3612 mov_seek_stream(s, st, timestamp, flags);
3615 for (i = 0; i < s->nb_streams; i++) {
3616 MOVStreamContext *sc;
3619 sc->current_sample = 0;
3622 MOVStreamContext *sc;
3623 AVIndexEntry *entry = mov_find_next_sample(s, &st);
3625 return AVERROR_INVALIDDATA;
3627 if (sc->ffindex == stream_index && sc->current_sample == sample)
3629 sc->current_sample++;
3635 #define OFFSET(x) offsetof(MOVContext, x)
3636 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
3637 static const AVOption mov_options[] = {
3638 {"seek_streams_individually",
3639 "Seek each stream individually to the to the closest point",
3640 OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
3642 { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
3643 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
3644 { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
3645 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
3649 static const AVClass mov_class = {
3650 .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3651 .item_name = av_default_item_name,
3652 .option = mov_options,
3653 .version = LIBAVUTIL_VERSION_INT,
3656 AVInputFormat ff_mov_demuxer = {
3657 .name = "mov,mp4,m4a,3gp,3g2,mj2",
3658 .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3659 .priv_class = &mov_class,
3660 .priv_data_size = sizeof(MOVContext),
3661 .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
3662 .read_probe = mov_probe,
3663 .read_header = mov_read_header,
3664 .read_packet = mov_read_packet,
3665 .read_close = mov_read_close,
3666 .read_seek = mov_read_seek,