3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6 * This file is part of Libav.
8 * Libav is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * Libav is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with Libav; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 //#define MOV_EXPORT_ALL_METADATA
28 #include "libavutil/attributes.h"
29 #include "libavutil/audioconvert.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/intfloat.h"
32 #include "libavutil/mathematics.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/dict.h"
35 #include "libavcodec/ac3tab.h"
38 #include "avio_internal.h"
41 #include "libavcodec/get_bits.h"
50 * First version by Francois Revol revol@free.fr
51 * Seek function by Gael Chardon gael.dev@4now.net
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 const MOVParseTableEntry mov_default_parse_table[];
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 av_dict_set(&c->fc->metadata, key, buf, 0);
88 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
89 unsigned len, const char *key)
93 /* bypass padding bytes */
98 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
99 av_dict_set(&c->fc->metadata, key, buf, 0);
104 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
105 unsigned len, const char *key)
109 snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
110 av_dict_set(&c->fc->metadata, key, buf, 0);
115 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
116 unsigned len, const char *key)
121 avio_r8(pb); // unknown
124 if (genre < 1 || genre > ID3v1_GENRE_MAX)
126 snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
127 av_dict_set(&c->fc->metadata, key, buf, 0);
132 static const uint32_t mac_to_unicode[128] = {
133 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
134 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
135 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
136 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
137 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
138 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
139 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
140 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
141 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
142 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
143 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
144 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
145 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
146 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
147 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
148 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
151 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
152 char *dst, int dstlen)
155 char *end = dst+dstlen-1;
158 for (i = 0; i < len; i++) {
159 uint8_t t, c = avio_r8(pb);
160 if (c < 0x80 && p < end)
163 PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
169 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
171 #ifdef MOV_EXPORT_ALL_METADATA
174 char str[1024], key2[16], language[4] = {0};
175 const char *key = NULL;
176 uint16_t langcode = 0;
177 uint32_t data_type = 0, str_size;
178 int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
181 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
182 case MKTAG(0xa9,'a','u','t'):
183 case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
184 case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
185 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
186 case MKTAG( 'c','p','r','t'):
187 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
188 case MKTAG(0xa9,'c','m','t'):
189 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
190 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
191 case MKTAG(0xa9,'d','a','y'): key = "date"; break;
192 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
193 case MKTAG( 'g','n','r','e'): key = "genre";
194 parse = mov_metadata_gnre; break;
195 case MKTAG(0xa9,'t','o','o'):
196 case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
197 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
198 case MKTAG( 'd','e','s','c'): key = "description";break;
199 case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
200 case MKTAG( 't','v','s','h'): key = "show"; break;
201 case MKTAG( 't','v','e','n'): key = "episode_id";break;
202 case MKTAG( 't','v','n','n'): key = "network"; break;
203 case MKTAG( 't','r','k','n'): key = "track";
204 parse = mov_metadata_track_or_disc_number; break;
205 case MKTAG( 'd','i','s','k'): key = "disc";
206 parse = mov_metadata_track_or_disc_number; break;
207 case MKTAG( 't','v','e','s'): key = "episode_sort";
208 parse = mov_metadata_int8_bypass_padding; break;
209 case MKTAG( 't','v','s','n'): key = "season_number";
210 parse = mov_metadata_int8_bypass_padding; break;
211 case MKTAG( 's','t','i','k'): key = "media_type";
212 parse = mov_metadata_int8_no_padding; break;
213 case MKTAG( 'h','d','v','d'): key = "hd_video";
214 parse = mov_metadata_int8_no_padding; break;
215 case MKTAG( 'p','g','a','p'): key = "gapless_playback";
216 parse = mov_metadata_int8_no_padding; break;
219 if (c->itunes_metadata && atom.size > 8) {
220 int data_size = avio_rb32(pb);
221 int tag = avio_rl32(pb);
222 if (tag == MKTAG('d','a','t','a')) {
223 data_type = avio_rb32(pb); // type
224 avio_rb32(pb); // unknown
225 str_size = data_size - 16;
228 } else if (atom.size > 4 && key && !c->itunes_metadata) {
229 str_size = avio_rb16(pb); // string length
230 langcode = avio_rb16(pb);
231 ff_mov_lang_to_iso639(langcode, language);
234 str_size = atom.size;
236 #ifdef MOV_EXPORT_ALL_METADATA
238 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
246 return AVERROR_INVALIDDATA;
248 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
251 parse(c, pb, str_size, key);
253 if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
254 mov_read_mac_string(c, pb, str_size, str, sizeof(str));
256 avio_read(pb, str, str_size);
259 av_dict_set(&c->fc->metadata, key, str, 0);
260 if (*language && strcmp(language, "und")) {
261 snprintf(key2, sizeof(key2), "%s-%s", key, language);
262 av_dict_set(&c->fc->metadata, key2, str, 0);
265 av_dlog(c->fc, "lang \"%3s\" ", language);
266 av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
267 key, str, (char*)&atom.type, str_size, atom.size);
272 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
275 int i, nb_chapters, str_len, version;
278 if ((atom.size -= 5) < 0)
281 version = avio_r8(pb);
284 avio_rb32(pb); // ???
285 nb_chapters = avio_r8(pb);
287 for (i = 0; i < nb_chapters; i++) {
291 start = avio_rb64(pb);
292 str_len = avio_r8(pb);
294 if ((atom.size -= 9+str_len) < 0)
297 avio_read(pb, str, str_len);
299 avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
304 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
306 int64_t total_size = 0;
311 atom.size = INT64_MAX;
312 while (total_size + 8 < atom.size && !pb->eof_reached) {
313 int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
316 if (atom.size >= 8) {
317 a.size = avio_rb32(pb);
318 a.type = avio_rl32(pb);
320 av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
321 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
323 if (a.size == 1) { /* 64 bit extended size */
324 a.size = avio_rb64(pb) - 8;
328 a.size = atom.size - total_size;
335 a.size = FFMIN(a.size, atom.size - total_size);
337 for (i = 0; mov_default_parse_table[i].type; i++)
338 if (mov_default_parse_table[i].type == a.type) {
339 parse = mov_default_parse_table[i].parse;
343 // container is user data
344 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
345 atom.type == MKTAG('i','l','s','t')))
346 parse = mov_read_udta_string;
348 if (!parse) { /* skip leaf atoms data */
349 avio_skip(pb, a.size);
351 int64_t start_pos = avio_tell(pb);
353 int err = parse(c, pb, a);
356 if (c->found_moov && c->found_mdat &&
357 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
358 start_pos + a.size == avio_size(pb))) {
359 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
360 c->next_root_atom = start_pos + a.size;
363 left = a.size - avio_tell(pb) + start_pos;
364 if (left > 0) /* skip garbage at atom end */
368 total_size += a.size;
371 if (total_size < atom.size && atom.size < 0x7ffff)
372 avio_skip(pb, atom.size - total_size);
377 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
380 MOVStreamContext *sc;
383 if (c->fc->nb_streams < 1)
385 st = c->fc->streams[c->fc->nb_streams-1];
388 avio_rb32(pb); // version + flags
389 entries = avio_rb32(pb);
390 if (entries >= UINT_MAX / sizeof(*sc->drefs))
391 return AVERROR_INVALIDDATA;
393 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
395 return AVERROR(ENOMEM);
396 sc->drefs_count = entries;
398 for (i = 0; i < sc->drefs_count; i++) {
399 MOVDref *dref = &sc->drefs[i];
400 uint32_t size = avio_rb32(pb);
401 int64_t next = avio_tell(pb) + size - 4;
404 return AVERROR_INVALIDDATA;
406 dref->type = avio_rl32(pb);
407 avio_rb32(pb); // version + flags
408 av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
410 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
411 /* macintosh alias record */
412 uint16_t volume_len, len;
417 volume_len = avio_r8(pb);
418 volume_len = FFMIN(volume_len, 27);
419 avio_read(pb, dref->volume, 27);
420 dref->volume[volume_len] = 0;
421 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
426 len = FFMIN(len, 63);
427 avio_read(pb, dref->filename, 63);
428 dref->filename[len] = 0;
429 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
433 /* read next level up_from_alias/down_to_target */
434 dref->nlvl_from = avio_rb16(pb);
435 dref->nlvl_to = avio_rb16(pb);
436 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
437 dref->nlvl_from, dref->nlvl_to);
441 for (type = 0; type != -1 && avio_tell(pb) < next; ) {
442 type = avio_rb16(pb);
444 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
447 if (type == 2) { // absolute path
449 dref->path = av_mallocz(len+1);
451 return AVERROR(ENOMEM);
452 avio_read(pb, dref->path, len);
453 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
455 memmove(dref->path, dref->path+volume_len, len);
458 for (j = 0; j < len; j++)
459 if (dref->path[j] == ':')
461 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
462 } else if (type == 0) { // directory name
464 dref->dir = av_malloc(len+1);
466 return AVERROR(ENOMEM);
467 avio_read(pb, dref->dir, len);
469 for (j = 0; j < len; j++)
470 if (dref->dir[j] == ':')
472 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
477 avio_seek(pb, next, SEEK_SET);
482 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
486 uint32_t av_unused ctype;
488 if (c->fc->nb_streams < 1) // meta before first trak
491 st = c->fc->streams[c->fc->nb_streams-1];
493 avio_r8(pb); /* version */
494 avio_rb24(pb); /* flags */
497 ctype = avio_rl32(pb);
498 type = avio_rl32(pb); /* component subtype */
500 av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
501 av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
503 if (type == MKTAG('v','i','d','e'))
504 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
505 else if (type == MKTAG('s','o','u','n'))
506 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
507 else if (type == MKTAG('m','1','a',' '))
508 st->codec->codec_id = CODEC_ID_MP2;
509 else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
510 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
512 avio_rb32(pb); /* component manufacture */
513 avio_rb32(pb); /* component flags */
514 avio_rb32(pb); /* component flags mask */
519 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
524 if (fc->nb_streams < 1)
526 st = fc->streams[fc->nb_streams-1];
528 avio_rb32(pb); /* version + flags */
529 ff_mp4_read_descr(fc, pb, &tag);
530 if (tag == MP4ESDescrTag) {
531 ff_mp4_parse_es_descr(pb, NULL);
533 avio_rb16(pb); /* ID */
535 ff_mp4_read_descr(fc, pb, &tag);
536 if (tag == MP4DecConfigDescrTag)
537 ff_mp4_read_dec_config_descr(fc, st, pb);
541 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
543 return ff_mov_read_esds(c->fc, pb, atom);
546 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
549 int ac3info, acmod, lfeon, bsmod;
551 if (c->fc->nb_streams < 1)
553 st = c->fc->streams[c->fc->nb_streams-1];
555 ac3info = avio_rb24(pb);
556 bsmod = (ac3info >> 14) & 0x7;
557 acmod = (ac3info >> 11) & 0x7;
558 lfeon = (ac3info >> 10) & 0x1;
559 st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
560 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
562 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
563 st->codec->audio_service_type = bsmod;
564 if (st->codec->channels > 1 && bsmod == 0x7)
565 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
570 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
573 int eac3info, acmod, lfeon, bsmod;
575 if (c->fc->nb_streams < 1)
577 st = c->fc->streams[c->fc->nb_streams-1];
579 /* No need to parse fields for additional independent substreams and its
580 * associated dependent substreams since libavcodec's E-AC-3 decoder
581 * does not support them yet. */
582 avio_rb16(pb); /* data_rate and num_ind_sub */
583 eac3info = avio_rb24(pb);
584 bsmod = (eac3info >> 12) & 0x1f;
585 acmod = (eac3info >> 9) & 0x7;
586 lfeon = (eac3info >> 8) & 0x1;
587 st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
589 st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
590 st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
591 st->codec->audio_service_type = bsmod;
592 if (st->codec->channels > 1 && bsmod == 0x7)
593 st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
598 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
601 uint8_t av_unused version;
602 uint32_t av_unused flags;
603 uint32_t layout_tag, bitmap, num_descr, label_mask;
606 if (c->fc->nb_streams < 1)
608 st = c->fc->streams[c->fc->nb_streams-1];
613 version = avio_r8(pb);
614 flags = avio_rb24(pb);
616 layout_tag = avio_rb32(pb);
617 bitmap = avio_rb32(pb);
618 num_descr = avio_rb32(pb);
620 if (atom.size < 16ULL + num_descr * 20ULL)
623 av_dlog(c->fc, "chan: size=%ld version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
624 atom.size, version, flags, layout_tag, bitmap, num_descr);
627 for (i = 0; i < num_descr; i++) {
629 label = avio_rb32(pb); // mChannelLabel
630 avio_rb32(pb); // mChannelFlags
631 avio_rl32(pb); // mCoordinates[0]
632 avio_rl32(pb); // mCoordinates[1]
633 avio_rl32(pb); // mCoordinates[2]
634 if (layout_tag == 0) {
635 uint32_t mask_incr = ff_mov_get_channel_label(label);
636 if (mask_incr == 0) {
640 label_mask |= mask_incr;
644 st->codec->channel_layout = label_mask;
646 st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
651 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
655 if (c->fc->nb_streams < 1)
657 st = c->fc->streams[c->fc->nb_streams-1];
659 ff_get_wav_header(pb, st->codec, atom.size);
664 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
666 const int num = avio_rb32(pb);
667 const int den = avio_rb32(pb);
670 if (c->fc->nb_streams < 1)
672 st = c->fc->streams[c->fc->nb_streams-1];
674 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
675 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
676 av_log(c->fc, AV_LOG_WARNING,
677 "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
678 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
680 } else if (den != 0) {
681 st->sample_aspect_ratio.num = num;
682 st->sample_aspect_ratio.den = den;
687 /* this atom contains actual media data */
688 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
690 if (atom.size == 0) /* wrong one (MP4) */
693 return 0; /* now go for moov */
696 /* read major brand, minor version and compatible brands and store them as metadata */
697 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
701 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
702 char* comp_brands_str;
703 uint8_t type[5] = {0};
705 avio_read(pb, type, 4);
706 if (strcmp(type, "qt "))
708 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
709 av_dict_set(&c->fc->metadata, "major_brand", type, 0);
710 minor_ver = avio_rb32(pb); /* minor version */
711 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
712 av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
714 comp_brand_size = atom.size - 8;
715 if (comp_brand_size < 0)
716 return AVERROR_INVALIDDATA;
717 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
718 if (!comp_brands_str)
719 return AVERROR(ENOMEM);
720 avio_read(pb, comp_brands_str, comp_brand_size);
721 comp_brands_str[comp_brand_size] = 0;
722 av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
723 av_freep(&comp_brands_str);
728 /* this atom should contain all header atoms */
729 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
733 if ((ret = mov_read_default(c, pb, atom)) < 0)
735 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
736 /* so we don't parse the whole file if over a network */
738 return 0; /* now go for mdat */
741 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
743 c->fragment.moof_offset = avio_tell(pb) - 8;
744 av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
745 return mov_read_default(c, pb, atom);
748 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
753 time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
756 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
757 av_dict_set(metadata, "creation_time", buffer, 0);
761 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
764 MOVStreamContext *sc;
766 char language[4] = {0};
768 time_t creation_time;
770 if (c->fc->nb_streams < 1)
772 st = c->fc->streams[c->fc->nb_streams-1];
775 version = avio_r8(pb);
777 av_log_ask_for_sample(c, "unsupported version %d\n", version);
778 return AVERROR_PATCHWELCOME;
780 avio_rb24(pb); /* flags */
782 creation_time = avio_rb64(pb);
785 creation_time = avio_rb32(pb);
786 avio_rb32(pb); /* modification time */
788 mov_metadata_creation_time(&st->metadata, creation_time);
790 sc->time_scale = avio_rb32(pb);
791 st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
793 lang = avio_rb16(pb); /* language */
794 if (ff_mov_lang_to_iso639(lang, language))
795 av_dict_set(&st->metadata, "language", language, 0);
796 avio_rb16(pb); /* quality */
801 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
803 time_t creation_time;
804 int version = avio_r8(pb); /* version */
805 avio_rb24(pb); /* flags */
808 creation_time = avio_rb64(pb);
811 creation_time = avio_rb32(pb);
812 avio_rb32(pb); /* modification time */
814 mov_metadata_creation_time(&c->fc->metadata, creation_time);
815 c->time_scale = avio_rb32(pb); /* time scale */
817 av_dlog(c->fc, "time scale = %i\n", c->time_scale);
819 c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
820 avio_rb32(pb); /* preferred scale */
822 avio_rb16(pb); /* preferred volume */
824 avio_skip(pb, 10); /* reserved */
826 avio_skip(pb, 36); /* display matrix */
828 avio_rb32(pb); /* preview time */
829 avio_rb32(pb); /* preview duration */
830 avio_rb32(pb); /* poster time */
831 avio_rb32(pb); /* selection time */
832 avio_rb32(pb); /* selection duration */
833 avio_rb32(pb); /* current time */
834 avio_rb32(pb); /* next track ID */
839 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
843 if (c->fc->nb_streams < 1)
845 st = c->fc->streams[c->fc->nb_streams-1];
847 if ((uint64_t)atom.size > (1<<30))
848 return AVERROR_INVALIDDATA;
850 // currently SVQ3 decoder expect full STSD header - so let's fake it
851 // this should be fixed and just SMI header should be passed
852 av_free(st->codec->extradata);
853 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
854 if (!st->codec->extradata)
855 return AVERROR(ENOMEM);
856 st->codec->extradata_size = 0x5a + atom.size;
857 memcpy(st->codec->extradata, "SVQ3", 4); // fake
858 avio_read(pb, st->codec->extradata + 0x5a, atom.size);
859 av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
863 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
868 if (c->fc->nb_streams < 1)
870 st = c->fc->streams[c->fc->nb_streams-1];
872 little_endian = avio_rb16(pb);
873 av_dlog(c->fc, "enda %d\n", little_endian);
874 if (little_endian == 1) {
875 switch (st->codec->codec_id) {
876 case CODEC_ID_PCM_S24BE:
877 st->codec->codec_id = CODEC_ID_PCM_S24LE;
879 case CODEC_ID_PCM_S32BE:
880 st->codec->codec_id = CODEC_ID_PCM_S32LE;
882 case CODEC_ID_PCM_F32BE:
883 st->codec->codec_id = CODEC_ID_PCM_F32LE;
885 case CODEC_ID_PCM_F64BE:
886 st->codec->codec_id = CODEC_ID_PCM_F64LE;
895 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
898 unsigned mov_field_order;
899 enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
901 if (c->fc->nb_streams < 1) // will happen with jp2 files
903 st = c->fc->streams[c->fc->nb_streams-1];
905 return AVERROR_INVALIDDATA;
906 mov_field_order = avio_rb16(pb);
907 if ((mov_field_order & 0xFF00) == 0x0100)
908 decoded_field_order = AV_FIELD_PROGRESSIVE;
909 else if ((mov_field_order & 0xFF00) == 0x0200) {
910 switch (mov_field_order & 0xFF) {
911 case 0x01: decoded_field_order = AV_FIELD_TT;
913 case 0x06: decoded_field_order = AV_FIELD_BB;
915 case 0x09: decoded_field_order = AV_FIELD_TB;
917 case 0x0E: decoded_field_order = AV_FIELD_BT;
921 if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
922 av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
924 st->codec->field_order = decoded_field_order;
929 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
930 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
936 if (c->fc->nb_streams < 1) // will happen with jp2 files
938 st= c->fc->streams[c->fc->nb_streams-1];
939 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
940 if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
941 return AVERROR_INVALIDDATA;
942 buf= av_realloc(st->codec->extradata, size);
944 return AVERROR(ENOMEM);
945 st->codec->extradata= buf;
946 buf+= st->codec->extradata_size;
947 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
948 AV_WB32( buf , atom.size + 8);
949 AV_WL32( buf + 4, atom.type);
950 avio_read(pb, buf + 8, atom.size);
954 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
958 if (c->fc->nb_streams < 1)
960 st = c->fc->streams[c->fc->nb_streams-1];
962 if ((uint64_t)atom.size > (1<<30))
963 return AVERROR_INVALIDDATA;
965 if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
966 // pass all frma atom to codec, needed at least for QDMC and QDM2
967 av_free(st->codec->extradata);
968 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
969 if (!st->codec->extradata)
970 return AVERROR(ENOMEM);
971 st->codec->extradata_size = atom.size;
972 avio_read(pb, st->codec->extradata, atom.size);
973 } else if (atom.size > 8) { /* to read frma, esds atoms */
975 if ((ret = mov_read_default(c, pb, atom)) < 0)
978 avio_skip(pb, atom.size);
983 * This function reads atom content and puts data in extradata without tag
984 * nor size unlike mov_read_extradata.
986 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
990 if (c->fc->nb_streams < 1)
992 st = c->fc->streams[c->fc->nb_streams-1];
994 if ((uint64_t)atom.size > (1<<30))
995 return AVERROR_INVALIDDATA;
997 if (atom.size >= 10) {
998 // Broken files created by legacy versions of libavformat will
999 // wrap a whole fiel atom inside of a glbl atom.
1000 unsigned size = avio_rb32(pb);
1001 unsigned type = avio_rl32(pb);
1002 avio_seek(pb, -8, SEEK_CUR);
1003 if (type == MKTAG('f','i','e','l') && size == atom.size)
1004 return mov_read_default(c, pb, atom);
1006 av_free(st->codec->extradata);
1007 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1008 if (!st->codec->extradata)
1009 return AVERROR(ENOMEM);
1010 st->codec->extradata_size = atom.size;
1011 avio_read(pb, st->codec->extradata, atom.size);
1015 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1018 uint8_t profile_level;
1020 if (c->fc->nb_streams < 1)
1022 st = c->fc->streams[c->fc->nb_streams-1];
1024 if (atom.size >= (1<<28) || atom.size < 7)
1025 return AVERROR_INVALIDDATA;
1027 profile_level = avio_r8(pb);
1028 if ((profile_level & 0xf0) != 0xc0)
1031 av_free(st->codec->extradata);
1032 st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
1033 if (!st->codec->extradata)
1034 return AVERROR(ENOMEM);
1035 st->codec->extradata_size = atom.size - 7;
1036 avio_seek(pb, 6, SEEK_CUR);
1037 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
1042 * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1043 * but can have extradata appended at the end after the 40 bytes belonging
1046 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1050 if (c->fc->nb_streams < 1)
1052 if (atom.size <= 40)
1054 st = c->fc->streams[c->fc->nb_streams-1];
1056 if ((uint64_t)atom.size > (1<<30))
1057 return AVERROR_INVALIDDATA;
1059 av_free(st->codec->extradata);
1060 st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1061 if (!st->codec->extradata)
1062 return AVERROR(ENOMEM);
1063 st->codec->extradata_size = atom.size - 40;
1065 avio_read(pb, st->codec->extradata, atom.size - 40);
1069 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1072 MOVStreamContext *sc;
1073 unsigned int i, entries;
1075 if (c->fc->nb_streams < 1)
1077 st = c->fc->streams[c->fc->nb_streams-1];
1080 avio_r8(pb); /* version */
1081 avio_rb24(pb); /* flags */
1083 entries = avio_rb32(pb);
1087 if (entries >= UINT_MAX/sizeof(int64_t))
1088 return AVERROR_INVALIDDATA;
1090 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1091 if (!sc->chunk_offsets)
1092 return AVERROR(ENOMEM);
1093 sc->chunk_count = entries;
1095 if (atom.type == MKTAG('s','t','c','o'))
1096 for (i=0; i<entries; i++)
1097 sc->chunk_offsets[i] = avio_rb32(pb);
1098 else if (atom.type == MKTAG('c','o','6','4'))
1099 for (i=0; i<entries; i++)
1100 sc->chunk_offsets[i] = avio_rb64(pb);
1102 return AVERROR_INVALIDDATA;
1108 * Compute codec id for 'lpcm' tag.
1109 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1111 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1113 if (flags & 1) { // floating point
1114 if (flags & 2) { // big endian
1115 if (bps == 32) return CODEC_ID_PCM_F32BE;
1116 else if (bps == 64) return CODEC_ID_PCM_F64BE;
1118 if (bps == 32) return CODEC_ID_PCM_F32LE;
1119 else if (bps == 64) return CODEC_ID_PCM_F64LE;
1125 if (flags & 4) return CODEC_ID_PCM_S8;
1126 else return CODEC_ID_PCM_U8;
1127 else if (bps == 16) return CODEC_ID_PCM_S16BE;
1128 else if (bps == 24) return CODEC_ID_PCM_S24BE;
1129 else if (bps == 32) return CODEC_ID_PCM_S32BE;
1132 if (flags & 4) return CODEC_ID_PCM_S8;
1133 else return CODEC_ID_PCM_U8;
1134 else if (bps == 16) return CODEC_ID_PCM_S16LE;
1135 else if (bps == 24) return CODEC_ID_PCM_S24LE;
1136 else if (bps == 32) return CODEC_ID_PCM_S32LE;
1139 return CODEC_ID_NONE;
1142 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1145 MOVStreamContext *sc;
1146 int j, pseudo_stream_id;
1148 if (c->fc->nb_streams < 1)
1150 st = c->fc->streams[c->fc->nb_streams-1];
1153 for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
1154 //Parsing Sample description table
1157 MOVAtom a = { AV_RL32("stsd") };
1158 int64_t start_pos = avio_tell(pb);
1159 int size = avio_rb32(pb); /* size */
1160 uint32_t format = avio_rl32(pb); /* data format */
1163 avio_rb32(pb); /* reserved */
1164 avio_rb16(pb); /* reserved */
1165 dref_id = avio_rb16(pb);
1168 if (st->codec->codec_tag &&
1169 st->codec->codec_tag != format &&
1170 (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
1171 : st->codec->codec_tag != MKTAG('j','p','e','g'))
1173 /* Multiple fourcc, we skip JPEG. This is not correct, we should
1174 * export it as a separate AVStream but this needs a few changes
1175 * in the MOV demuxer, patch welcome. */
1177 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1178 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1181 /* we cannot demux concatenated h264 streams because of different extradata */
1182 if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1184 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1185 sc->dref_id= dref_id;
1187 st->codec->codec_tag = format;
1188 id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1189 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1190 id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1192 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1193 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1194 } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1195 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1196 id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1198 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1200 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1201 else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){
1202 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1204 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1208 av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1209 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1210 (format >> 24) & 0xff, st->codec->codec_type);
1212 if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1213 unsigned int color_depth, len;
1214 int color_greyscale;
1217 st->codec->codec_id = id;
1218 avio_rb16(pb); /* version */
1219 avio_rb16(pb); /* revision level */
1220 avio_rb32(pb); /* vendor */
1221 avio_rb32(pb); /* temporal quality */
1222 avio_rb32(pb); /* spatial quality */
1224 st->codec->width = avio_rb16(pb); /* width */
1225 st->codec->height = avio_rb16(pb); /* height */
1227 avio_rb32(pb); /* horiz resolution */
1228 avio_rb32(pb); /* vert resolution */
1229 avio_rb32(pb); /* data size, always 0 */
1230 avio_rb16(pb); /* frames per samples */
1232 len = avio_r8(pb); /* codec name, pascal string */
1235 mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1237 avio_skip(pb, 31 - len);
1238 /* codec_tag YV12 triggers an UV swap in rawdec.c */
1239 if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1240 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1242 st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1243 color_table_id = avio_rb16(pb); /* colortable id */
1244 av_dlog(c->fc, "depth %d, ctab id %d\n",
1245 st->codec->bits_per_coded_sample, color_table_id);
1246 /* figure out the palette situation */
1247 color_depth = st->codec->bits_per_coded_sample & 0x1F;
1248 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1250 /* if the depth is 2, 4, or 8 bpp, file is palettized */
1251 if ((color_depth == 2) || (color_depth == 4) ||
1252 (color_depth == 8)) {
1253 /* for palette traversal */
1254 unsigned int color_start, color_count, color_end;
1255 unsigned char r, g, b;
1257 if (color_greyscale) {
1258 int color_index, color_dec;
1259 /* compute the greyscale palette */
1260 st->codec->bits_per_coded_sample = color_depth;
1261 color_count = 1 << color_depth;
1263 color_dec = 256 / (color_count - 1);
1264 for (j = 0; j < color_count; j++) {
1265 r = g = b = color_index;
1267 (r << 16) | (g << 8) | (b);
1268 color_index -= color_dec;
1269 if (color_index < 0)
1272 } else if (color_table_id) {
1273 const uint8_t *color_table;
1274 /* if flag bit 3 is set, use the default palette */
1275 color_count = 1 << color_depth;
1276 if (color_depth == 2)
1277 color_table = ff_qt_default_palette_4;
1278 else if (color_depth == 4)
1279 color_table = ff_qt_default_palette_16;
1281 color_table = ff_qt_default_palette_256;
1283 for (j = 0; j < color_count; j++) {
1284 r = color_table[j * 3 + 0];
1285 g = color_table[j * 3 + 1];
1286 b = color_table[j * 3 + 2];
1288 (r << 16) | (g << 8) | (b);
1291 /* load the palette from the file */
1292 color_start = avio_rb32(pb);
1293 color_count = avio_rb16(pb);
1294 color_end = avio_rb16(pb);
1295 if ((color_start <= 255) &&
1296 (color_end <= 255)) {
1297 for (j = color_start; j <= color_end; j++) {
1298 /* each R, G, or B component is 16 bits;
1299 * only use the top 8 bits; skip alpha bytes
1310 (r << 16) | (g << 8) | (b);
1314 sc->has_palette = 1;
1316 } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1317 int bits_per_sample, flags;
1318 uint16_t version = avio_rb16(pb);
1320 st->codec->codec_id = id;
1321 avio_rb16(pb); /* revision level */
1322 avio_rb32(pb); /* vendor */
1324 st->codec->channels = avio_rb16(pb); /* channel count */
1325 av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1326 st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1328 sc->audio_cid = avio_rb16(pb);
1329 avio_rb16(pb); /* packet size = 0 */
1331 st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1333 //Read QT version 1 fields. In version 0 these do not exist.
1334 av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1337 sc->samples_per_frame = avio_rb32(pb);
1338 avio_rb32(pb); /* bytes per packet */
1339 sc->bytes_per_frame = avio_rb32(pb);
1340 avio_rb32(pb); /* bytes per sample */
1341 } else if (version==2) {
1342 avio_rb32(pb); /* sizeof struct only */
1343 st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
1344 st->codec->channels = avio_rb32(pb);
1345 avio_rb32(pb); /* always 0x7F000000 */
1346 st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1347 flags = avio_rb32(pb); /* lpcm format specific flag */
1348 sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1349 sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1350 if (format == MKTAG('l','p','c','m'))
1351 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1355 switch (st->codec->codec_id) {
1356 case CODEC_ID_PCM_S8:
1357 case CODEC_ID_PCM_U8:
1358 if (st->codec->bits_per_coded_sample == 16)
1359 st->codec->codec_id = CODEC_ID_PCM_S16BE;
1361 case CODEC_ID_PCM_S16LE:
1362 case CODEC_ID_PCM_S16BE:
1363 if (st->codec->bits_per_coded_sample == 8)
1364 st->codec->codec_id = CODEC_ID_PCM_S8;
1365 else if (st->codec->bits_per_coded_sample == 24)
1366 st->codec->codec_id =
1367 st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1368 CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1370 /* set values for old format before stsd version 1 appeared */
1371 case CODEC_ID_MACE3:
1372 sc->samples_per_frame = 6;
1373 sc->bytes_per_frame = 2*st->codec->channels;
1375 case CODEC_ID_MACE6:
1376 sc->samples_per_frame = 6;
1377 sc->bytes_per_frame = 1*st->codec->channels;
1379 case CODEC_ID_ADPCM_IMA_QT:
1380 sc->samples_per_frame = 64;
1381 sc->bytes_per_frame = 34*st->codec->channels;
1384 sc->samples_per_frame = 160;
1385 sc->bytes_per_frame = 33;
1391 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1392 if (bits_per_sample) {
1393 st->codec->bits_per_coded_sample = bits_per_sample;
1394 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1396 } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1397 // ttxt stsd contains display flags, justification, background
1398 // color, fonts, and default styles, so fake an atom to read it
1399 MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1400 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1401 mov_read_glbl(c, pb, fake_atom);
1402 st->codec->codec_id= id;
1403 st->codec->width = sc->width;
1404 st->codec->height = sc->height;
1406 /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1407 avio_skip(pb, size - (avio_tell(pb) - start_pos));
1409 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1410 a.size = size - (avio_tell(pb) - start_pos);
1413 if ((ret = mov_read_default(c, pb, a)) < 0)
1415 } else if (a.size > 0)
1416 avio_skip(pb, a.size);
1419 if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1420 st->codec->sample_rate= sc->time_scale;
1422 /* special codec parameters handling */
1423 switch (st->codec->codec_id) {
1424 #if CONFIG_DV_DEMUXER
1425 case CODEC_ID_DVAUDIO:
1426 c->dv_fctx = avformat_alloc_context();
1427 c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1429 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1430 return AVERROR(ENOMEM);
1432 sc->dv_audio_container = 1;
1433 st->codec->codec_id = CODEC_ID_PCM_S16LE;
1436 /* no ifdef since parameters are always those */
1437 case CODEC_ID_QCELP:
1438 // force sample rate for qcelp when not stored in mov
1439 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1440 st->codec->sample_rate = 8000;
1441 st->codec->channels= 1; /* really needed */
1443 case CODEC_ID_AMR_NB:
1444 st->codec->channels= 1; /* really needed */
1445 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1446 st->codec->sample_rate = 8000;
1448 case CODEC_ID_AMR_WB:
1449 st->codec->channels = 1;
1450 st->codec->sample_rate = 16000;
1454 st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1455 st->need_parsing = AVSTREAM_PARSE_FULL;
1458 case CODEC_ID_ADPCM_MS:
1459 case CODEC_ID_ADPCM_IMA_WAV:
1461 st->codec->block_align = sc->bytes_per_frame;
1464 if (st->codec->extradata_size == 36) {
1465 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1466 st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1470 st->need_parsing = AVSTREAM_PARSE_FULL;
1479 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1483 avio_r8(pb); /* version */
1484 avio_rb24(pb); /* flags */
1485 entries = avio_rb32(pb);
1487 return ff_mov_read_stsd_entries(c, pb, entries);
1490 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1493 MOVStreamContext *sc;
1494 unsigned int i, entries;
1496 if (c->fc->nb_streams < 1)
1498 st = c->fc->streams[c->fc->nb_streams-1];
1501 avio_r8(pb); /* version */
1502 avio_rb24(pb); /* flags */
1504 entries = avio_rb32(pb);
1506 av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1510 if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1511 return AVERROR_INVALIDDATA;
1512 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1514 return AVERROR(ENOMEM);
1515 sc->stsc_count = entries;
1517 for (i=0; i<entries; i++) {
1518 sc->stsc_data[i].first = avio_rb32(pb);
1519 sc->stsc_data[i].count = avio_rb32(pb);
1520 sc->stsc_data[i].id = avio_rb32(pb);
1525 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1528 MOVStreamContext *sc;
1529 unsigned i, entries;
1531 if (c->fc->nb_streams < 1)
1533 st = c->fc->streams[c->fc->nb_streams-1];
1536 avio_rb32(pb); // version + flags
1538 entries = avio_rb32(pb);
1539 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1540 return AVERROR_INVALIDDATA;
1541 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1543 return AVERROR(ENOMEM);
1544 sc->stps_count = entries;
1546 for (i = 0; i < entries; i++) {
1547 sc->stps_data[i] = avio_rb32(pb);
1548 //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1554 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1557 MOVStreamContext *sc;
1558 unsigned int i, entries;
1560 if (c->fc->nb_streams < 1)
1562 st = c->fc->streams[c->fc->nb_streams-1];
1565 avio_r8(pb); /* version */
1566 avio_rb24(pb); /* flags */
1568 entries = avio_rb32(pb);
1570 av_dlog(c->fc, "keyframe_count = %d\n", entries);
1574 sc->keyframe_absent = 1;
1577 if (entries >= UINT_MAX / sizeof(int))
1578 return AVERROR_INVALIDDATA;
1579 sc->keyframes = av_malloc(entries * sizeof(int));
1581 return AVERROR(ENOMEM);
1582 sc->keyframe_count = entries;
1584 for (i=0; i<entries; i++) {
1585 sc->keyframes[i] = avio_rb32(pb);
1586 //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1591 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1594 MOVStreamContext *sc;
1595 unsigned int i, entries, sample_size, field_size, num_bytes;
1599 if (c->fc->nb_streams < 1)
1601 st = c->fc->streams[c->fc->nb_streams-1];
1604 avio_r8(pb); /* version */
1605 avio_rb24(pb); /* flags */
1607 if (atom.type == MKTAG('s','t','s','z')) {
1608 sample_size = avio_rb32(pb);
1609 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1610 sc->sample_size = sample_size;
1614 avio_rb24(pb); /* reserved */
1615 field_size = avio_r8(pb);
1617 entries = avio_rb32(pb);
1619 av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1621 sc->sample_count = entries;
1625 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1626 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1627 return AVERROR_INVALIDDATA;
1632 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1633 return AVERROR_INVALIDDATA;
1634 sc->sample_sizes = av_malloc(entries * sizeof(int));
1635 if (!sc->sample_sizes)
1636 return AVERROR(ENOMEM);
1638 num_bytes = (entries*field_size+4)>>3;
1640 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1642 av_freep(&sc->sample_sizes);
1643 return AVERROR(ENOMEM);
1646 if (avio_read(pb, buf, num_bytes) < num_bytes) {
1647 av_freep(&sc->sample_sizes);
1649 return AVERROR_INVALIDDATA;
1652 init_get_bits(&gb, buf, 8*num_bytes);
1654 for (i = 0; i < entries; i++) {
1655 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1656 sc->data_size += sc->sample_sizes[i];
1663 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1666 MOVStreamContext *sc;
1667 unsigned int i, entries;
1669 int64_t total_sample_count=0;
1671 if (c->fc->nb_streams < 1)
1673 st = c->fc->streams[c->fc->nb_streams-1];
1676 avio_r8(pb); /* version */
1677 avio_rb24(pb); /* flags */
1678 entries = avio_rb32(pb);
1680 av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1681 c->fc->nb_streams-1, entries);
1685 if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1686 return AVERROR(EINVAL);
1688 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1690 return AVERROR(ENOMEM);
1692 sc->stts_count = entries;
1694 for (i=0; i<entries; i++) {
1695 int sample_duration;
1698 sample_count=avio_rb32(pb);
1699 sample_duration = avio_rb32(pb);
1700 sc->stts_data[i].count= sample_count;
1701 sc->stts_data[i].duration= sample_duration;
1703 av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1704 sample_count, sample_duration);
1706 duration+=(int64_t)sample_duration*sample_count;
1707 total_sample_count+=sample_count;
1710 st->nb_frames= total_sample_count;
1712 st->duration= duration;
1713 sc->track_end = duration;
1717 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1720 MOVStreamContext *sc;
1721 unsigned int i, entries;
1723 if (c->fc->nb_streams < 1)
1725 st = c->fc->streams[c->fc->nb_streams-1];
1728 avio_r8(pb); /* version */
1729 avio_rb24(pb); /* flags */
1730 entries = avio_rb32(pb);
1732 av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1736 if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1737 return AVERROR_INVALIDDATA;
1738 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1740 return AVERROR(ENOMEM);
1741 sc->ctts_count = entries;
1743 for (i=0; i<entries; i++) {
1744 int count =avio_rb32(pb);
1745 int duration =avio_rb32(pb);
1747 sc->ctts_data[i].count = count;
1748 sc->ctts_data[i].duration= duration;
1750 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1753 av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1758 static void mov_build_index(MOVContext *mov, AVStream *st)
1760 MOVStreamContext *sc = st->priv_data;
1761 int64_t current_offset;
1762 int64_t current_dts = 0;
1763 unsigned int stts_index = 0;
1764 unsigned int stsc_index = 0;
1765 unsigned int stss_index = 0;
1766 unsigned int stps_index = 0;
1768 uint64_t stream_size = 0;
1771 /* adjust first dts according to edit list */
1772 if (sc->time_offset && mov->time_scale > 0) {
1773 if (sc->time_offset < 0)
1774 sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
1775 current_dts = -sc->time_offset;
1776 if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
1777 sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1778 /* more than 16 frames delay, dts are likely wrong
1779 this happens with files created by iMovie */
1781 st->codec->has_b_frames = 1;
1785 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1786 if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1787 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1788 unsigned int current_sample = 0;
1789 unsigned int stts_sample = 0;
1790 unsigned int sample_size;
1791 unsigned int distance = 0;
1792 int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
1794 current_dts -= sc->dts_shift;
1796 if (!sc->sample_count)
1798 if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1800 mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1803 st->index_entries = mem;
1804 st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
1806 for (i = 0; i < sc->chunk_count; i++) {
1807 current_offset = sc->chunk_offsets[i];
1808 while (stsc_index + 1 < sc->stsc_count &&
1809 i + 1 == sc->stsc_data[stsc_index + 1].first)
1811 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1813 if (current_sample >= sc->sample_count) {
1814 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1818 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
1820 if (stss_index + 1 < sc->keyframe_count)
1822 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1824 if (stps_index + 1 < sc->stps_count)
1829 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1830 if (sc->pseudo_stream_id == -1 ||
1831 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1832 AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1833 e->pos = current_offset;
1834 e->timestamp = current_dts;
1835 e->size = sample_size;
1836 e->min_distance = distance;
1837 e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1838 av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1839 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1840 current_offset, current_dts, sample_size, distance, keyframe);
1843 current_offset += sample_size;
1844 stream_size += sample_size;
1845 current_dts += sc->stts_data[stts_index].duration;
1849 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1855 if (st->duration > 0)
1856 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1858 unsigned chunk_samples, total = 0;
1860 // compute total chunk count
1861 for (i = 0; i < sc->stsc_count; i++) {
1862 unsigned count, chunk_count;
1864 chunk_samples = sc->stsc_data[i].count;
1865 if (i != sc->stsc_count - 1 &&
1866 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1867 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1871 if (sc->samples_per_frame >= 160) { // gsm
1872 count = chunk_samples / sc->samples_per_frame;
1873 } else if (sc->samples_per_frame > 1) {
1874 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1875 count = (chunk_samples+samples-1) / samples;
1877 count = (chunk_samples+1023) / 1024;
1880 if (i < sc->stsc_count - 1)
1881 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1883 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1884 total += chunk_count * count;
1887 av_dlog(mov->fc, "chunk count %d\n", total);
1888 if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1890 mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
1893 st->index_entries = mem;
1894 st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
1897 for (i = 0; i < sc->chunk_count; i++) {
1898 current_offset = sc->chunk_offsets[i];
1899 if (stsc_index + 1 < sc->stsc_count &&
1900 i + 1 == sc->stsc_data[stsc_index + 1].first)
1902 chunk_samples = sc->stsc_data[stsc_index].count;
1904 while (chunk_samples > 0) {
1906 unsigned size, samples;
1908 if (sc->samples_per_frame >= 160) { // gsm
1909 samples = sc->samples_per_frame;
1910 size = sc->bytes_per_frame;
1912 if (sc->samples_per_frame > 1) {
1913 samples = FFMIN((1024 / sc->samples_per_frame)*
1914 sc->samples_per_frame, chunk_samples);
1915 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1917 samples = FFMIN(1024, chunk_samples);
1918 size = samples * sc->sample_size;
1922 if (st->nb_index_entries >= total) {
1923 av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1926 e = &st->index_entries[st->nb_index_entries++];
1927 e->pos = current_offset;
1928 e->timestamp = current_dts;
1930 e->min_distance = 0;
1931 e->flags = AVINDEX_KEYFRAME;
1932 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1933 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1936 current_offset += size;
1937 current_dts += samples;
1938 chunk_samples -= samples;
1944 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
1945 AVIOInterruptCB *int_cb)
1947 /* try relative path, we do not try the absolute because it can leak information about our
1948 system to an attacker */
1949 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1950 char filename[1024];
1954 /* find a source dir */
1955 src_path = strrchr(src, '/');
1961 /* find a next level down to target */
1962 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1963 if (ref->path[l] == '/') {
1964 if (i == ref->nlvl_to - 1)
1970 /* compose filename if next level down to target was found */
1971 if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
1972 memcpy(filename, src, src_path - src);
1973 filename[src_path - src] = 0;
1975 for (i = 1; i < ref->nlvl_from; i++)
1976 av_strlcat(filename, "../", 1024);
1978 av_strlcat(filename, ref->path + l + 1, 1024);
1980 if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
1985 return AVERROR(ENOENT);
1988 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1991 MOVStreamContext *sc;
1994 st = avformat_new_stream(c->fc, NULL);
1995 if (!st) return AVERROR(ENOMEM);
1996 st->id = c->fc->nb_streams;
1997 sc = av_mallocz(sizeof(MOVStreamContext));
1998 if (!sc) return AVERROR(ENOMEM);
2001 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2002 sc->ffindex = st->index;
2004 if ((ret = mov_read_default(c, pb, atom)) < 0)
2008 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2009 (!sc->sample_size && !sc->sample_count))) {
2010 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2015 if (sc->time_scale <= 0) {
2016 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2017 sc->time_scale = c->time_scale;
2018 if (sc->time_scale <= 0)
2022 avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2024 mov_build_index(c, st);
2026 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2027 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2028 if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
2029 av_log(c->fc, AV_LOG_ERROR,
2030 "stream %d, error opening alias: path='%s', dir='%s', "
2031 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2032 st->index, dref->path, dref->dir, dref->filename,
2033 dref->volume, dref->nlvl_from, dref->nlvl_to);
2037 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2038 if (!st->sample_aspect_ratio.num &&
2039 (st->codec->width != sc->width || st->codec->height != sc->height)) {
2040 st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2041 ((double)st->codec->width * sc->height), INT_MAX);
2044 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2045 sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2047 if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2048 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2049 sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2052 switch (st->codec->codec_id) {
2053 #if CONFIG_H261_DECODER
2056 #if CONFIG_H263_DECODER
2059 #if CONFIG_MPEG4_DECODER
2060 case CODEC_ID_MPEG4:
2062 st->codec->width = 0; /* let decoder init width/height */
2063 st->codec->height= 0;
2067 /* Do not need those anymore. */
2068 av_freep(&sc->chunk_offsets);
2069 av_freep(&sc->stsc_data);
2070 av_freep(&sc->sample_sizes);
2071 av_freep(&sc->keyframes);
2072 av_freep(&sc->stts_data);
2073 av_freep(&sc->stps_data);
2078 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2081 c->itunes_metadata = 1;
2082 ret = mov_read_default(c, pb, atom);
2083 c->itunes_metadata = 0;
2087 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2089 while (atom.size > 8) {
2090 uint32_t tag = avio_rl32(pb);
2092 if (tag == MKTAG('h','d','l','r')) {
2093 avio_seek(pb, -8, SEEK_CUR);
2095 return mov_read_default(c, pb, atom);
2101 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2106 int64_t disp_transform[2];
2107 int display_matrix[3][2];
2109 MOVStreamContext *sc;
2112 if (c->fc->nb_streams < 1)
2114 st = c->fc->streams[c->fc->nb_streams-1];
2117 version = avio_r8(pb);
2118 avio_rb24(pb); /* flags */
2120 MOV_TRACK_ENABLED 0x0001
2121 MOV_TRACK_IN_MOVIE 0x0002
2122 MOV_TRACK_IN_PREVIEW 0x0004
2123 MOV_TRACK_IN_POSTER 0x0008
2130 avio_rb32(pb); /* creation time */
2131 avio_rb32(pb); /* modification time */
2133 st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2134 avio_rb32(pb); /* reserved */
2136 /* highlevel (considering edits) duration in movie timebase */
2137 (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2138 avio_rb32(pb); /* reserved */
2139 avio_rb32(pb); /* reserved */
2141 avio_rb16(pb); /* layer */
2142 avio_rb16(pb); /* alternate group */
2143 avio_rb16(pb); /* volume */
2144 avio_rb16(pb); /* reserved */
2146 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2147 // they're kept in fixed point format through all calculations
2148 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2149 for (i = 0; i < 3; i++) {
2150 display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2151 display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2152 avio_rb32(pb); // 2.30 fixed point (not used)
2155 width = avio_rb32(pb); // 16.16 fixed point track width
2156 height = avio_rb32(pb); // 16.16 fixed point track height
2157 sc->width = width >> 16;
2158 sc->height = height >> 16;
2160 // transform the display width/height according to the matrix
2161 // skip this if the display matrix is the default identity matrix
2162 // or if it is rotating the picture, ex iPhone 3GS
2163 // to keep the same scale, use [width height 1<<16]
2164 if (width && height &&
2165 ((display_matrix[0][0] != 65536 ||
2166 display_matrix[1][1] != 65536) &&
2167 !display_matrix[0][1] &&
2168 !display_matrix[1][0] &&
2169 !display_matrix[2][0] && !display_matrix[2][1])) {
2170 for (i = 0; i < 2; i++)
2172 (int64_t) width * display_matrix[0][i] +
2173 (int64_t) height * display_matrix[1][i] +
2174 ((int64_t) display_matrix[2][i] << 16);
2176 //sample aspect ratio is new width/height divided by old width/height
2177 st->sample_aspect_ratio = av_d2q(
2178 ((double) disp_transform[0] * height) /
2179 ((double) disp_transform[1] * width), INT_MAX);
2184 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2186 MOVFragment *frag = &c->fragment;
2187 MOVTrackExt *trex = NULL;
2188 int flags, track_id, i;
2190 avio_r8(pb); /* version */
2191 flags = avio_rb24(pb);
2193 track_id = avio_rb32(pb);
2195 return AVERROR_INVALIDDATA;
2196 frag->track_id = track_id;
2197 for (i = 0; i < c->trex_count; i++)
2198 if (c->trex_data[i].track_id == frag->track_id) {
2199 trex = &c->trex_data[i];
2203 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2204 return AVERROR_INVALIDDATA;
2207 frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2208 avio_rb64(pb) : frag->moof_offset;
2209 frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2211 frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2212 avio_rb32(pb) : trex->duration;
2213 frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2214 avio_rb32(pb) : trex->size;
2215 frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2216 avio_rb32(pb) : trex->flags;
2217 av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2221 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2223 c->chapter_track = avio_rb32(pb);
2227 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2231 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2232 return AVERROR_INVALIDDATA;
2233 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2235 return AVERROR(ENOMEM);
2236 c->trex_data = trex;
2237 trex = &c->trex_data[c->trex_count++];
2238 avio_r8(pb); /* version */
2239 avio_rb24(pb); /* flags */
2240 trex->track_id = avio_rb32(pb);
2241 trex->stsd_id = avio_rb32(pb);
2242 trex->duration = avio_rb32(pb);
2243 trex->size = avio_rb32(pb);
2244 trex->flags = avio_rb32(pb);
2248 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2250 MOVFragment *frag = &c->fragment;
2251 AVStream *st = NULL;
2252 MOVStreamContext *sc;
2256 int data_offset = 0;
2257 unsigned entries, first_sample_flags = frag->flags;
2258 int flags, distance, i, found_keyframe = 0;
2260 for (i = 0; i < c->fc->nb_streams; i++) {
2261 if (c->fc->streams[i]->id == frag->track_id) {
2262 st = c->fc->streams[i];
2267 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2268 return AVERROR_INVALIDDATA;
2271 if (sc->pseudo_stream_id+1 != frag->stsd_id)
2273 avio_r8(pb); /* version */
2274 flags = avio_rb24(pb);
2275 entries = avio_rb32(pb);
2276 av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2278 /* Always assume the presence of composition time offsets.
2279 * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2280 * 1) in the initial movie, there are no samples.
2281 * 2) in the first movie fragment, there is only one sample without composition time offset.
2282 * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2283 if (!sc->ctts_count && sc->sample_count)
2285 /* Complement ctts table if moov atom doesn't have ctts atom. */
2286 ctts_data = av_malloc(sizeof(*sc->ctts_data));
2288 return AVERROR(ENOMEM);
2289 sc->ctts_data = ctts_data;
2290 sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2291 sc->ctts_data[sc->ctts_count].duration = 0;
2294 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2295 return AVERROR_INVALIDDATA;
2296 ctts_data = av_realloc(sc->ctts_data,
2297 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2299 return AVERROR(ENOMEM);
2300 sc->ctts_data = ctts_data;
2302 if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2303 if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2304 dts = sc->track_end - sc->time_offset;
2305 offset = frag->base_data_offset + data_offset;
2307 av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2308 for (i = 0; i < entries; i++) {
2309 unsigned sample_size = frag->size;
2310 int sample_flags = i ? frag->flags : first_sample_flags;
2311 unsigned sample_duration = frag->duration;
2314 if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2315 if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2316 if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2317 sc->ctts_data[sc->ctts_count].count = 1;
2318 sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2321 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2323 else if (!found_keyframe)
2324 keyframe = found_keyframe =
2325 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2326 MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2329 av_add_index_entry(st, offset, dts, sample_size, distance,
2330 keyframe ? AVINDEX_KEYFRAME : 0);
2331 av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2332 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2333 offset, dts, sample_size, distance, keyframe);
2335 dts += sample_duration;
2336 offset += sample_size;
2337 sc->data_size += sample_size;
2339 frag->moof_offset = offset;
2340 st->duration = sc->track_end = dts + sc->time_offset;
2344 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2345 /* like the files created with Adobe Premiere 5.0, for samples see */
2346 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2347 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2352 return 0; /* continue */
2353 if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2354 avio_skip(pb, atom.size - 4);
2357 atom.type = avio_rl32(pb);
2359 if (atom.type != MKTAG('m','d','a','t')) {
2360 avio_skip(pb, atom.size);
2363 err = mov_read_mdat(c, pb, atom);
2367 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2372 uint8_t *moov_data; /* uncompressed data */
2373 long cmov_len, moov_len;
2376 avio_rb32(pb); /* dcom atom */
2377 if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2378 return AVERROR_INVALIDDATA;
2379 if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2380 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2381 return AVERROR_INVALIDDATA;
2383 avio_rb32(pb); /* cmvd atom */
2384 if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2385 return AVERROR_INVALIDDATA;
2386 moov_len = avio_rb32(pb); /* uncompressed size */
2387 cmov_len = atom.size - 6 * 4;
2389 cmov_data = av_malloc(cmov_len);
2391 return AVERROR(ENOMEM);
2392 moov_data = av_malloc(moov_len);
2395 return AVERROR(ENOMEM);
2397 avio_read(pb, cmov_data, cmov_len);
2398 if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2399 goto free_and_return;
2400 if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2401 goto free_and_return;
2402 atom.type = MKTAG('m','o','o','v');
2403 atom.size = moov_len;
2404 ret = mov_read_default(c, &ctx, atom);
2410 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2411 return AVERROR(ENOSYS);
2415 /* edit list atom */
2416 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2418 MOVStreamContext *sc;
2419 int i, edit_count, version;
2421 if (c->fc->nb_streams < 1)
2423 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2425 version = avio_r8(pb); /* version */
2426 avio_rb24(pb); /* flags */
2427 edit_count = avio_rb32(pb); /* entries */
2429 if ((uint64_t)edit_count*12+8 > atom.size)
2430 return AVERROR_INVALIDDATA;
2432 for (i=0; i<edit_count; i++){
2436 duration = avio_rb64(pb);
2437 time = avio_rb64(pb);
2439 duration = avio_rb32(pb); /* segment duration */
2440 time = (int32_t)avio_rb32(pb); /* media time */
2442 avio_rb32(pb); /* Media rate */
2443 if (i == 0 && time >= -1) {
2444 sc->time_offset = time != -1 ? time : -duration;
2449 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2450 "a/v desync might occur, patch welcome\n");
2452 av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2456 static const MOVParseTableEntry mov_default_parse_table[] = {
2457 { MKTAG('a','v','s','s'), mov_read_extradata },
2458 { MKTAG('c','h','p','l'), mov_read_chpl },
2459 { MKTAG('c','o','6','4'), mov_read_stco },
2460 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2461 { MKTAG('d','i','n','f'), mov_read_default },
2462 { MKTAG('d','r','e','f'), mov_read_dref },
2463 { MKTAG('e','d','t','s'), mov_read_default },
2464 { MKTAG('e','l','s','t'), mov_read_elst },
2465 { MKTAG('e','n','d','a'), mov_read_enda },
2466 { MKTAG('f','i','e','l'), mov_read_fiel },
2467 { MKTAG('f','t','y','p'), mov_read_ftyp },
2468 { MKTAG('g','l','b','l'), mov_read_glbl },
2469 { MKTAG('h','d','l','r'), mov_read_hdlr },
2470 { MKTAG('i','l','s','t'), mov_read_ilst },
2471 { MKTAG('j','p','2','h'), mov_read_extradata },
2472 { MKTAG('m','d','a','t'), mov_read_mdat },
2473 { MKTAG('m','d','h','d'), mov_read_mdhd },
2474 { MKTAG('m','d','i','a'), mov_read_default },
2475 { MKTAG('m','e','t','a'), mov_read_meta },
2476 { MKTAG('m','i','n','f'), mov_read_default },
2477 { MKTAG('m','o','o','f'), mov_read_moof },
2478 { MKTAG('m','o','o','v'), mov_read_moov },
2479 { MKTAG('m','v','e','x'), mov_read_default },
2480 { MKTAG('m','v','h','d'), mov_read_mvhd },
2481 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2482 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2483 { MKTAG('a','v','c','C'), mov_read_glbl },
2484 { MKTAG('p','a','s','p'), mov_read_pasp },
2485 { MKTAG('s','t','b','l'), mov_read_default },
2486 { MKTAG('s','t','c','o'), mov_read_stco },
2487 { MKTAG('s','t','p','s'), mov_read_stps },
2488 { MKTAG('s','t','r','f'), mov_read_strf },
2489 { MKTAG('s','t','s','c'), mov_read_stsc },
2490 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2491 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2492 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2493 { MKTAG('s','t','t','s'), mov_read_stts },
2494 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2495 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2496 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2497 { MKTAG('t','r','a','k'), mov_read_trak },
2498 { MKTAG('t','r','a','f'), mov_read_default },
2499 { MKTAG('t','r','e','f'), mov_read_default },
2500 { MKTAG('c','h','a','p'), mov_read_chap },
2501 { MKTAG('t','r','e','x'), mov_read_trex },
2502 { MKTAG('t','r','u','n'), mov_read_trun },
2503 { MKTAG('u','d','t','a'), mov_read_default },
2504 { MKTAG('w','a','v','e'), mov_read_wave },
2505 { MKTAG('e','s','d','s'), mov_read_esds },
2506 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2507 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2508 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2509 { MKTAG('w','f','e','x'), mov_read_wfex },
2510 { MKTAG('c','m','o','v'), mov_read_cmov },
2511 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2512 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2516 static int mov_probe(AVProbeData *p)
2518 unsigned int offset;
2522 /* check file header */
2525 /* ignore invalid offset */
2526 if ((offset + 8) > (unsigned int)p->buf_size)
2528 tag = AV_RL32(p->buf + offset + 4);
2530 /* check for obvious tags */
2531 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2532 case MKTAG('m','o','o','v'):
2533 case MKTAG('m','d','a','t'):
2534 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2535 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2536 case MKTAG('f','t','y','p'):
2537 return AVPROBE_SCORE_MAX;
2538 /* those are more common words, so rate then a bit less */
2539 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2540 case MKTAG('w','i','d','e'):
2541 case MKTAG('f','r','e','e'):
2542 case MKTAG('j','u','n','k'):
2543 case MKTAG('p','i','c','t'):
2544 return AVPROBE_SCORE_MAX - 5;
2545 case MKTAG(0x82,0x82,0x7f,0x7d):
2546 case MKTAG('s','k','i','p'):
2547 case MKTAG('u','u','i','d'):
2548 case MKTAG('p','r','f','l'):
2549 offset = AV_RB32(p->buf+offset) + offset;
2550 /* if we only find those cause probedata is too small at least rate them */
2551 score = AVPROBE_SCORE_MAX - 50;
2554 /* unrecognized tag */
2560 // must be done after parsing all trak because there's no order requirement
2561 static void mov_read_chapters(AVFormatContext *s)
2563 MOVContext *mov = s->priv_data;
2564 AVStream *st = NULL;
2565 MOVStreamContext *sc;
2569 for (i = 0; i < s->nb_streams; i++)
2570 if (s->streams[i]->id == mov->chapter_track) {
2575 av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2579 st->discard = AVDISCARD_ALL;
2581 cur_pos = avio_tell(sc->pb);
2583 for (i = 0; i < st->nb_index_entries; i++) {
2584 AVIndexEntry *sample = &st->index_entries[i];
2585 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2590 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2591 av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2595 // the first two bytes are the length of the title
2596 len = avio_rb16(sc->pb);
2597 if (len > sample->size-2)
2599 title_len = 2*len + 1;
2600 if (!(title = av_mallocz(title_len)))
2603 // The samples could theoretically be in any encoding if there's an encd
2604 // atom following, but in practice are only utf-8 or utf-16, distinguished
2605 // instead by the presence of a BOM
2609 ch = avio_rb16(sc->pb);
2611 avio_get_str16be(sc->pb, len, title, title_len);
2612 else if (ch == 0xfffe)
2613 avio_get_str16le(sc->pb, len, title, title_len);
2616 if (len == 1 || len == 2)
2619 avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
2623 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2627 avio_seek(sc->pb, cur_pos, SEEK_SET);
2630 static int mov_read_close(AVFormatContext *s)
2632 MOVContext *mov = s->priv_data;
2635 for (i = 0; i < s->nb_streams; i++) {
2636 AVStream *st = s->streams[i];
2637 MOVStreamContext *sc = st->priv_data;
2639 av_freep(&sc->ctts_data);
2640 for (j = 0; j < sc->drefs_count; j++) {
2641 av_freep(&sc->drefs[j].path);
2642 av_freep(&sc->drefs[j].dir);
2644 av_freep(&sc->drefs);
2645 if (sc->pb && sc->pb != s->pb)
2649 if (mov->dv_demux) {
2650 for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2651 av_freep(&mov->dv_fctx->streams[i]->codec);
2652 av_freep(&mov->dv_fctx->streams[i]);
2654 av_freep(&mov->dv_fctx);
2655 av_freep(&mov->dv_demux);
2658 av_freep(&mov->trex_data);
2663 static int mov_read_header(AVFormatContext *s)
2665 MOVContext *mov = s->priv_data;
2666 AVIOContext *pb = s->pb;
2668 MOVAtom atom = { AV_RL32("root") };
2671 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2673 atom.size = avio_size(pb);
2675 atom.size = INT64_MAX;
2677 /* check MOV header */
2678 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2679 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2683 if (!mov->found_moov) {
2684 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2686 return AVERROR_INVALIDDATA;
2688 av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2690 if (pb->seekable && mov->chapter_track > 0)
2691 mov_read_chapters(s);
2693 if (mov->trex_data) {
2695 for (i = 0; i < s->nb_streams; i++) {
2696 AVStream *st = s->streams[i];
2697 MOVStreamContext *sc = st->priv_data;
2699 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
2706 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2708 AVIndexEntry *sample = NULL;
2709 int64_t best_dts = INT64_MAX;
2711 for (i = 0; i < s->nb_streams; i++) {
2712 AVStream *avst = s->streams[i];
2713 MOVStreamContext *msc = avst->priv_data;
2714 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2715 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2716 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2717 av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2718 if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2720 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2721 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2722 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2723 sample = current_sample;
2732 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2734 MOVContext *mov = s->priv_data;
2735 MOVStreamContext *sc;
2736 AVIndexEntry *sample;
2737 AVStream *st = NULL;
2740 sample = mov_find_next_sample(s, &st);
2742 mov->found_mdat = 0;
2743 if (!mov->next_root_atom)
2745 avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
2746 mov->next_root_atom = 0;
2747 if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2750 av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2754 /* must be done just before reading, to avoid infinite loop on sample */
2755 sc->current_sample++;
2757 if (st->discard != AVDISCARD_ALL) {
2758 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2759 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2760 sc->ffindex, sample->pos);
2761 return AVERROR_INVALIDDATA;
2763 ret = av_get_packet(sc->pb, pkt, sample->size);
2766 if (sc->has_palette) {
2769 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2771 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2773 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2774 sc->has_palette = 0;
2777 #if CONFIG_DV_DEMUXER
2778 if (mov->dv_demux && sc->dv_audio_container) {
2779 avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2782 ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
2789 pkt->stream_index = sc->ffindex;
2790 pkt->dts = sample->timestamp;
2791 if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
2792 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2793 /* update ctts context */
2795 if (sc->ctts_index < sc->ctts_count &&
2796 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2798 sc->ctts_sample = 0;
2801 pkt->dts = AV_NOPTS_VALUE;
2803 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2804 st->index_entries[sc->current_sample].timestamp : st->duration;
2805 pkt->duration = next_dts - pkt->dts;
2806 pkt->pts = pkt->dts;
2808 if (st->discard == AVDISCARD_ALL)
2810 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2811 pkt->pos = sample->pos;
2812 av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2813 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2817 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2819 MOVStreamContext *sc = st->priv_data;
2820 int sample, time_sample;
2823 sample = av_index_search_timestamp(st, timestamp, flags);
2824 av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2825 if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2827 if (sample < 0) /* not sure what to do */
2828 return AVERROR_INVALIDDATA;
2829 sc->current_sample = sample;
2830 av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2831 /* adjust ctts index */
2832 if (sc->ctts_data) {
2834 for (i = 0; i < sc->ctts_count; i++) {
2835 int next = time_sample + sc->ctts_data[i].count;
2836 if (next > sc->current_sample) {
2838 sc->ctts_sample = sc->current_sample - time_sample;
2847 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2850 int64_t seek_timestamp, timestamp;
2854 if (stream_index >= s->nb_streams)
2855 return AVERROR_INVALIDDATA;
2856 if (sample_time < 0)
2859 st = s->streams[stream_index];
2860 sample = mov_seek_stream(s, st, sample_time, flags);
2864 /* adjust seek timestamp to found sample timestamp */
2865 seek_timestamp = st->index_entries[sample].timestamp;
2867 for (i = 0; i < s->nb_streams; i++) {
2869 if (stream_index == i)
2872 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2873 mov_seek_stream(s, st, timestamp, flags);
2878 AVInputFormat ff_mov_demuxer = {
2879 .name = "mov,mp4,m4a,3gp,3g2,mj2",
2880 .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2881 .priv_data_size = sizeof(MOVContext),
2882 .read_probe = mov_probe,
2883 .read_header = mov_read_header,
2884 .read_packet = mov_read_packet,
2885 .read_close = mov_read_close,
2886 .read_seek = mov_read_seek,