3 * Copyright (c) 2001 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "libavutil/intreadwrite.h"
31 #include "libavcodec/mpeg4audio.h"
32 #include "libavcodec/mpegaudiodata.h"
39 * First version by Francois Revol revol@free.fr
40 * Seek function by Gael Chardon gael.dev@4now.net
42 * Features and limitations:
43 * - reads most of the QT files I have (at least the structure),
44 * Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
45 * - the code is quite ugly... maybe I won't do it recursive next time :-)
47 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
48 * when coding this :) (it's a writer anyway)
50 * Reference documents:
51 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
53 * http://developer.apple.com/documentation/QuickTime/QTFF/
54 * http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
55 * QuickTime is a trademark of Apple (AFAIK :))
58 #include "qtpalette.h"
64 /* the QuickTime file format is quite convoluted...
65 * it has lots of index tables, each indexing something in another one...
66 * Here we just use what is needed to read the chunks
83 int64_t size; /* total size (excluding the size and type fields) */
86 struct MOVParseTableEntry;
90 uint64_t base_data_offset;
106 typedef struct MOVStreamContext {
108 int ffindex; /* the ffmpeg stream id */
110 unsigned int chunk_count;
111 int64_t *chunk_offsets;
112 unsigned int stts_count;
114 unsigned int ctts_count;
116 unsigned int stsc_count;
120 unsigned int sample_size;
121 unsigned int sample_count;
123 unsigned int keyframe_count;
127 int time_offset; ///< time offset of the first edit list entry
129 unsigned int bytes_per_frame;
130 unsigned int samples_per_frame;
131 int dv_audio_container;
132 int pseudo_stream_id; ///< -1 means demux all ids
133 int16_t audio_cid; ///< stsd audio compression id
134 unsigned drefs_count;
137 int wrong_dts; ///< dts are wrong due to negative ctts
138 int width; ///< tkhd width
139 int height; ///< tkhd height
142 typedef struct MOVContext {
145 int64_t duration; /* duration of the longest track */
146 int found_moov; /* when both 'moov' and 'mdat' sections has been found */
147 int found_mdat; /* we suppose we have enough data to read the file */
148 AVPaletteControl palette_control;
149 DVDemuxContext *dv_demux;
150 AVFormatContext *dv_fctx;
151 int isom; /* 1 if file is ISO Media (mp4/3gp) */
152 MOVFragment fragment; ///< current fragment in moof atom
153 MOVTrackExt *trex_data;
155 int itunes_metadata; ///< metadata are itunes style
159 /* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
161 /* those functions parse an atom */
163 0: continue to parse next atom
164 <0: error occurred, exit
166 /* links atom IDs to parse functions */
167 typedef struct MOVParseTableEntry {
169 int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOVAtom atom);
170 } MOVParseTableEntry;
172 static const MOVParseTableEntry mov_default_parse_table[];
174 static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
176 int64_t total_size = 0;
181 a.offset = atom.offset;
184 atom.size = INT64_MAX;
185 while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
189 a.size = get_be32(pb);
190 a.type = get_le32(pb);
194 dprintf(c->fc, "type: %08x %.4s sz: %"PRIx64" %"PRIx64" %"PRIx64"\n",
195 a.type, (char*)&a.type, a.size, atom.size, total_size);
196 if (a.size == 1) { /* 64 bit extended size */
197 a.size = get_be64(pb) - 8;
202 a.size = atom.size - total_size;
209 a.size = FFMIN(a.size, atom.size - total_size);
211 for (i = 0; mov_default_parse_table[i].type != 0
212 && mov_default_parse_table[i].type != a.type; i++)
215 if (mov_default_parse_table[i].type == 0) { /* skip leaf atoms data */
216 url_fskip(pb, a.size);
218 int64_t start_pos = url_ftell(pb);
220 err = mov_default_parse_table[i].parse(c, pb, a);
221 if (url_is_streamed(pb) && c->found_moov && c->found_mdat)
223 left = a.size - url_ftell(pb) + start_pos;
224 if (left > 0) /* skip garbage at atom end */
229 total_size += a.size;
232 if (!err && total_size < atom.size && atom.size < 0x7ffff)
233 url_fskip(pb, atom.size - total_size);
238 static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
240 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
241 MOVStreamContext *sc = st->priv_data;
244 get_be32(pb); // version + flags
245 entries = get_be32(pb);
246 if (entries >= UINT_MAX / sizeof(*sc->drefs))
248 sc->drefs_count = entries;
249 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
251 for (i = 0; i < sc->drefs_count; i++) {
252 MOVDref *dref = &sc->drefs[i];
253 uint32_t size = get_be32(pb);
254 int64_t next = url_ftell(pb) + size - 4;
256 dref->type = get_le32(pb);
257 get_be32(pb); // version + flags
258 dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
260 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
261 /* macintosh alias record */
262 uint16_t volume_len, len;
268 volume_len = get_byte(pb);
269 volume_len = FFMIN(volume_len, 27);
270 get_buffer(pb, volume, 27);
271 volume[volume_len] = 0;
272 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", volume, volume_len);
276 for (type = 0; type != -1 && url_ftell(pb) < next; ) {
279 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
282 if (type == 2) { // absolute path
284 dref->path = av_mallocz(len+1);
286 return AVERROR(ENOMEM);
287 get_buffer(pb, dref->path, len);
288 if (len > volume_len && !strncmp(dref->path, volume, volume_len)) {
290 memmove(dref->path, dref->path+volume_len, len);
293 for (j = 0; j < len; j++)
294 if (dref->path[j] == ':')
296 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
301 url_fseek(pb, next, SEEK_SET);
306 static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
308 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
312 get_byte(pb); /* version */
313 get_be24(pb); /* flags */
316 ctype = get_le32(pb);
317 type = get_le32(pb); /* component subtype */
319 dprintf(c->fc, "ctype= %c%c%c%c (0x%08x)\n", *((char *)&ctype), ((char *)&ctype)[1],
320 ((char *)&ctype)[2], ((char *)&ctype)[3], (int) ctype);
321 dprintf(c->fc, "stype= %c%c%c%c\n",
322 *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
325 if (type == MKTAG('v','i','d','e'))
326 st->codec->codec_type = CODEC_TYPE_VIDEO;
327 else if(type == MKTAG('s','o','u','n'))
328 st->codec->codec_type = CODEC_TYPE_AUDIO;
329 else if(type == MKTAG('m','1','a',' '))
330 st->codec->codec_id = CODEC_ID_MP2;
331 else if(type == MKTAG('s','u','b','p')) {
332 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
334 get_be32(pb); /* component manufacture */
335 get_be32(pb); /* component flags */
336 get_be32(pb); /* component flags mask */
339 return 0; /* nothing left to read */
341 url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
345 static int mp4_read_descr_len(ByteIOContext *pb)
350 int c = get_byte(pb);
351 len = (len << 7) | (c & 0x7f);
358 static int mp4_read_descr(MOVContext *c, ByteIOContext *pb, int *tag)
362 len = mp4_read_descr_len(pb);
363 dprintf(c->fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
367 #define MP4ESDescrTag 0x03
368 #define MP4DecConfigDescrTag 0x04
369 #define MP4DecSpecificDescrTag 0x05
371 static const AVCodecTag mp4_audio_types[] = {
372 { CODEC_ID_MP3ON4, 29 }, /* old mp3on4 draft */
373 { CODEC_ID_MP3ON4, 32 }, /* layer 1 */
374 { CODEC_ID_MP3ON4, 33 }, /* layer 2 */
375 { CODEC_ID_MP3ON4, 34 }, /* layer 3 */
376 { CODEC_ID_NONE, 0 },
379 static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
381 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
384 get_be32(pb); /* version + flags */
385 len = mp4_read_descr(c, pb, &tag);
386 if (tag == MP4ESDescrTag) {
387 get_be16(pb); /* ID */
388 get_byte(pb); /* priority */
390 get_be16(pb); /* ID */
392 len = mp4_read_descr(c, pb, &tag);
393 if (tag == MP4DecConfigDescrTag) {
394 int object_type_id = get_byte(pb);
395 get_byte(pb); /* stream type */
396 get_be24(pb); /* buffer size db */
397 get_be32(pb); /* max bitrate */
398 get_be32(pb); /* avg bitrate */
400 st->codec->codec_id= codec_get_id(ff_mp4_obj_type, object_type_id);
401 dprintf(c->fc, "esds object type id %d\n", object_type_id);
402 len = mp4_read_descr(c, pb, &tag);
403 if (tag == MP4DecSpecificDescrTag) {
404 dprintf(c->fc, "Specific MPEG4 header len=%d\n", len);
405 if((uint64_t)len > (1<<30))
407 st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
408 if (!st->codec->extradata)
409 return AVERROR(ENOMEM);
410 get_buffer(pb, st->codec->extradata, len);
411 st->codec->extradata_size = len;
412 if (st->codec->codec_id == CODEC_ID_AAC) {
413 MPEG4AudioConfig cfg;
414 ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
415 st->codec->extradata_size);
416 if (cfg.chan_config > 7)
418 st->codec->channels = ff_mpeg4audio_channels[cfg.chan_config];
419 if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
420 st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
422 st->codec->sample_rate = cfg.sample_rate; // ext sample rate ?
423 dprintf(c->fc, "mp4a config channels %d obj %d ext obj %d "
424 "sample rate %d ext sample rate %d\n", st->codec->channels,
425 cfg.object_type, cfg.ext_object_type,
426 cfg.sample_rate, cfg.ext_sample_rate);
427 if (!(st->codec->codec_id = codec_get_id(mp4_audio_types,
429 st->codec->codec_id = CODEC_ID_AAC;
436 static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
438 const int num = get_be32(pb);
439 const int den = get_be32(pb);
440 AVStream * const st = c->fc->streams[c->fc->nb_streams-1];
442 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
443 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))
444 av_log(c->fc, AV_LOG_WARNING,
445 "sample aspect ratio already set to %d:%d, overriding by 'pasp' atom\n",
446 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
447 st->sample_aspect_ratio.num = num;
448 st->sample_aspect_ratio.den = den;
453 /* this atom contains actual media data */
454 static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
456 if(atom.size == 0) /* wrong one (MP4) */
459 return 0; /* now go for moov */
462 static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
464 uint32_t type = get_le32(pb);
466 if (type != MKTAG('q','t',' ',' '))
468 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
469 get_be32(pb); /* minor version */
470 url_fskip(pb, atom.size - 8);
474 /* this atom should contain all header atoms */
475 static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
477 if (mov_read_default(c, pb, atom) < 0)
479 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
480 /* so we don't parse the whole file if over a network */
482 return 0; /* now go for mdat */
485 static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
487 c->fragment.moof_offset = url_ftell(pb) - 8;
488 dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
489 return mov_read_default(c, pb, atom);
492 static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
494 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
495 MOVStreamContext *sc = st->priv_data;
496 int version = get_byte(pb);
500 return -1; /* unsupported */
502 get_be24(pb); /* flags */
507 get_be32(pb); /* creation time */
508 get_be32(pb); /* modification time */
511 sc->time_scale = get_be32(pb);
512 st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
514 lang = get_be16(pb); /* language */
515 ff_mov_lang_to_iso639(lang, st->language);
516 get_be16(pb); /* quality */
521 static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
523 int version = get_byte(pb); /* version */
524 get_be24(pb); /* flags */
530 get_be32(pb); /* creation time */
531 get_be32(pb); /* modification time */
533 c->time_scale = get_be32(pb); /* time scale */
535 dprintf(c->fc, "time scale = %i\n", c->time_scale);
537 c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
538 get_be32(pb); /* preferred scale */
540 get_be16(pb); /* preferred volume */
542 url_fskip(pb, 10); /* reserved */
544 url_fskip(pb, 36); /* display matrix */
546 get_be32(pb); /* preview time */
547 get_be32(pb); /* preview duration */
548 get_be32(pb); /* poster time */
549 get_be32(pb); /* selection time */
550 get_be32(pb); /* selection duration */
551 get_be32(pb); /* current time */
552 get_be32(pb); /* next track ID */
557 static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
559 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
561 if((uint64_t)atom.size > (1<<30))
564 // currently SVQ3 decoder expect full STSD header - so let's fake it
565 // this should be fixed and just SMI header should be passed
566 av_free(st->codec->extradata);
567 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
568 if (!st->codec->extradata)
569 return AVERROR(ENOMEM);
570 st->codec->extradata_size = 0x5a + atom.size;
571 memcpy(st->codec->extradata, "SVQ3", 4); // fake
572 get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
573 dprintf(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
577 static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
579 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
580 int little_endian = get_be16(pb);
582 dprintf(c->fc, "enda %d\n", little_endian);
583 if (little_endian == 1) {
584 switch (st->codec->codec_id) {
585 case CODEC_ID_PCM_S24BE:
586 st->codec->codec_id = CODEC_ID_PCM_S24LE;
588 case CODEC_ID_PCM_S32BE:
589 st->codec->codec_id = CODEC_ID_PCM_S32LE;
591 case CODEC_ID_PCM_F32BE:
592 st->codec->codec_id = CODEC_ID_PCM_F32LE;
594 case CODEC_ID_PCM_F64BE:
595 st->codec->codec_id = CODEC_ID_PCM_F64LE;
604 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
605 static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
611 if (c->fc->nb_streams < 1) // will happen with jp2 files
613 st= c->fc->streams[c->fc->nb_streams-1];
614 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
615 if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
617 buf= av_realloc(st->codec->extradata, size);
620 st->codec->extradata= buf;
621 buf+= st->codec->extradata_size;
622 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
623 AV_WB32( buf , atom.size + 8);
624 AV_WL32( buf + 4, atom.type);
625 get_buffer(pb, buf + 8, atom.size);
629 static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
631 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
633 if((uint64_t)atom.size > (1<<30))
636 if (st->codec->codec_id == CODEC_ID_QDM2) {
637 // pass all frma atom to codec, needed at least for QDM2
638 av_free(st->codec->extradata);
639 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
640 if (!st->codec->extradata)
641 return AVERROR(ENOMEM);
642 st->codec->extradata_size = atom.size;
643 get_buffer(pb, st->codec->extradata, atom.size);
644 } else if (atom.size > 8) { /* to read frma, esds atoms */
645 if (mov_read_default(c, pb, atom) < 0)
648 url_fskip(pb, atom.size);
653 * This function reads atom content and puts data in extradata without tag
654 * nor size unlike mov_read_extradata.
656 static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
658 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
660 if((uint64_t)atom.size > (1<<30))
663 av_free(st->codec->extradata);
664 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
665 if (!st->codec->extradata)
666 return AVERROR(ENOMEM);
667 st->codec->extradata_size = atom.size;
668 get_buffer(pb, st->codec->extradata, atom.size);
672 static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
674 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
675 MOVStreamContext *sc = st->priv_data;
676 unsigned int i, entries;
678 get_byte(pb); /* version */
679 get_be24(pb); /* flags */
681 entries = get_be32(pb);
683 if(entries >= UINT_MAX/sizeof(int64_t))
686 sc->chunk_count = entries;
687 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
688 if (!sc->chunk_offsets)
690 if (atom.type == MKTAG('s','t','c','o'))
691 for(i=0; i<entries; i++)
692 sc->chunk_offsets[i] = get_be32(pb);
693 else if (atom.type == MKTAG('c','o','6','4'))
694 for(i=0; i<entries; i++)
695 sc->chunk_offsets[i] = get_be64(pb);
703 * Compute codec id for 'lpcm' tag.
704 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
706 static enum CodecID mov_get_lpcm_codec_id(int bps, int flags)
708 if (flags & 1) { // floating point
709 if (flags & 2) { // big endian
710 if (bps == 32) return CODEC_ID_PCM_F32BE;
711 else if (bps == 64) return CODEC_ID_PCM_F64BE;
713 if (bps == 32) return CODEC_ID_PCM_F32LE;
714 else if (bps == 64) return CODEC_ID_PCM_F64LE;
720 if (flags & 4) return CODEC_ID_PCM_S8;
721 else return CODEC_ID_PCM_U8;
722 else if (bps == 16) return CODEC_ID_PCM_S16BE;
723 else if (bps == 24) return CODEC_ID_PCM_S24BE;
724 else if (bps == 32) return CODEC_ID_PCM_S32BE;
727 if (flags & 4) return CODEC_ID_PCM_S8;
728 else return CODEC_ID_PCM_U8;
729 else if (bps == 16) return CODEC_ID_PCM_S16LE;
730 else if (bps == 24) return CODEC_ID_PCM_S24LE;
731 else if (bps == 32) return CODEC_ID_PCM_S32LE;
734 return CODEC_ID_NONE;
737 static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
739 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
740 MOVStreamContext *sc = st->priv_data;
741 int j, entries, pseudo_stream_id;
743 get_byte(pb); /* version */
744 get_be24(pb); /* flags */
746 entries = get_be32(pb);
748 for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
749 //Parsing Sample description table
752 MOVAtom a = { 0, 0, 0 };
753 int64_t start_pos = url_ftell(pb);
754 int size = get_be32(pb); /* size */
755 uint32_t format = get_le32(pb); /* data format */
757 get_be32(pb); /* reserved */
758 get_be16(pb); /* reserved */
759 dref_id = get_be16(pb);
761 if (st->codec->codec_tag &&
762 st->codec->codec_tag != format &&
763 (c->fc->video_codec_id ? codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
764 : st->codec->codec_tag != MKTAG('j','p','e','g'))
766 /* Multiple fourcc, we skip JPEG. This is not correct, we should
767 * export it as a separate AVStream but this needs a few changes
768 * in the MOV demuxer, patch welcome. */
769 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
770 url_fskip(pb, size - (url_ftell(pb) - start_pos));
773 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
774 sc->dref_id= dref_id;
776 st->codec->codec_tag = format;
777 id = codec_get_id(codec_movaudio_tags, format);
778 if (id<=0 && (format&0xFFFF) == 'm'+('s'<<8))
779 id = codec_get_id(codec_wav_tags, bswap_32(format)&0xFFFF);
781 if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
782 st->codec->codec_type = CODEC_TYPE_AUDIO;
783 } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
784 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
785 id = codec_get_id(codec_movvideo_tags, format);
787 id = codec_get_id(codec_bmp_tags, format);
789 st->codec->codec_type = CODEC_TYPE_VIDEO;
790 else if(st->codec->codec_type == CODEC_TYPE_DATA){
791 id = codec_get_id(ff_codec_movsubtitle_tags, format);
793 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
797 dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
798 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
799 (format >> 24) & 0xff, st->codec->codec_type);
801 if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
802 uint8_t codec_name[32];
803 unsigned int color_depth;
806 st->codec->codec_id = id;
807 get_be16(pb); /* version */
808 get_be16(pb); /* revision level */
809 get_be32(pb); /* vendor */
810 get_be32(pb); /* temporal quality */
811 get_be32(pb); /* spatial quality */
813 st->codec->width = get_be16(pb); /* width */
814 st->codec->height = get_be16(pb); /* height */
816 get_be32(pb); /* horiz resolution */
817 get_be32(pb); /* vert resolution */
818 get_be32(pb); /* data size, always 0 */
819 get_be16(pb); /* frames per samples */
821 get_buffer(pb, codec_name, 32); /* codec name, pascal string */
822 if (codec_name[0] <= 31) {
823 memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
824 st->codec->codec_name[codec_name[0]] = 0;
827 st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
828 st->codec->color_table_id = get_be16(pb); /* colortable id */
829 dprintf(c->fc, "depth %d, ctab id %d\n",
830 st->codec->bits_per_coded_sample, st->codec->color_table_id);
831 /* figure out the palette situation */
832 color_depth = st->codec->bits_per_coded_sample & 0x1F;
833 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
835 /* if the depth is 2, 4, or 8 bpp, file is palettized */
836 if ((color_depth == 2) || (color_depth == 4) ||
837 (color_depth == 8)) {
838 /* for palette traversal */
839 unsigned int color_start, color_count, color_end;
840 unsigned char r, g, b;
842 if (color_greyscale) {
843 int color_index, color_dec;
844 /* compute the greyscale palette */
845 st->codec->bits_per_coded_sample = color_depth;
846 color_count = 1 << color_depth;
848 color_dec = 256 / (color_count - 1);
849 for (j = 0; j < color_count; j++) {
850 r = g = b = color_index;
851 c->palette_control.palette[j] =
852 (r << 16) | (g << 8) | (b);
853 color_index -= color_dec;
857 } else if (st->codec->color_table_id) {
858 const uint8_t *color_table;
859 /* if flag bit 3 is set, use the default palette */
860 color_count = 1 << color_depth;
861 if (color_depth == 2)
862 color_table = ff_qt_default_palette_4;
863 else if (color_depth == 4)
864 color_table = ff_qt_default_palette_16;
866 color_table = ff_qt_default_palette_256;
868 for (j = 0; j < color_count; j++) {
869 r = color_table[j * 4 + 0];
870 g = color_table[j * 4 + 1];
871 b = color_table[j * 4 + 2];
872 c->palette_control.palette[j] =
873 (r << 16) | (g << 8) | (b);
876 /* load the palette from the file */
877 color_start = get_be32(pb);
878 color_count = get_be16(pb);
879 color_end = get_be16(pb);
880 if ((color_start <= 255) &&
881 (color_end <= 255)) {
882 for (j = color_start; j <= color_end; j++) {
883 /* each R, G, or B component is 16 bits;
884 * only use the top 8 bits; skip alpha bytes
894 c->palette_control.palette[j] =
895 (r << 16) | (g << 8) | (b);
899 st->codec->palctrl = &c->palette_control;
900 st->codec->palctrl->palette_changed = 1;
902 st->codec->palctrl = NULL;
903 } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
904 int bits_per_sample, flags;
905 uint16_t version = get_be16(pb);
907 st->codec->codec_id = id;
908 get_be16(pb); /* revision level */
909 get_be32(pb); /* vendor */
911 st->codec->channels = get_be16(pb); /* channel count */
912 dprintf(c->fc, "audio channels %d\n", st->codec->channels);
913 st->codec->bits_per_coded_sample = get_be16(pb); /* sample size */
915 sc->audio_cid = get_be16(pb);
916 get_be16(pb); /* packet size = 0 */
918 st->codec->sample_rate = ((get_be32(pb) >> 16));
920 //Read QT version 1 fields. In version 0 these do not exist.
921 dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
924 sc->samples_per_frame = get_be32(pb);
925 get_be32(pb); /* bytes per packet */
926 sc->bytes_per_frame = get_be32(pb);
927 get_be32(pb); /* bytes per sample */
928 } else if(version==2) {
929 get_be32(pb); /* sizeof struct only */
930 st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
931 st->codec->channels = get_be32(pb);
932 get_be32(pb); /* always 0x7F000000 */
933 st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
934 flags = get_be32(pb); /* lcpm format specific flag */
935 sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
936 sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
937 if (format == MKTAG('l','p','c','m'))
938 st->codec->codec_id = mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
942 switch (st->codec->codec_id) {
943 case CODEC_ID_PCM_S8:
944 case CODEC_ID_PCM_U8:
945 if (st->codec->bits_per_coded_sample == 16)
946 st->codec->codec_id = CODEC_ID_PCM_S16BE;
948 case CODEC_ID_PCM_S16LE:
949 case CODEC_ID_PCM_S16BE:
950 if (st->codec->bits_per_coded_sample == 8)
951 st->codec->codec_id = CODEC_ID_PCM_S8;
952 else if (st->codec->bits_per_coded_sample == 24)
953 st->codec->codec_id =
954 st->codec->codec_id == CODEC_ID_PCM_S16BE ?
955 CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
957 /* set values for old format before stsd version 1 appeared */
959 sc->samples_per_frame = 6;
960 sc->bytes_per_frame = 2*st->codec->channels;
963 sc->samples_per_frame = 6;
964 sc->bytes_per_frame = 1*st->codec->channels;
966 case CODEC_ID_ADPCM_IMA_QT:
967 sc->samples_per_frame = 64;
968 sc->bytes_per_frame = 34*st->codec->channels;
971 sc->samples_per_frame = 160;
972 sc->bytes_per_frame = 33;
978 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
979 if (bits_per_sample) {
980 st->codec->bits_per_coded_sample = bits_per_sample;
981 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
983 } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){
984 // ttxt stsd contains display flags, justification, background
985 // color, fonts, and default styles, so fake an atom to read it
986 MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
987 mov_read_glbl(c, pb, fake_atom);
988 st->codec->codec_id= id;
989 st->codec->width = sc->width;
990 st->codec->height = sc->height;
992 /* other codec type, just skip (rtp, mp4s, tmcd ...) */
993 url_fskip(pb, size - (url_ftell(pb) - start_pos));
995 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
996 a.size = size - (url_ftell(pb) - start_pos);
998 if (mov_read_default(c, pb, a) < 0)
1000 } else if (a.size > 0)
1001 url_fskip(pb, a.size);
1004 if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1005 st->codec->sample_rate= sc->time_scale;
1007 /* special codec parameters handling */
1008 switch (st->codec->codec_id) {
1009 #if CONFIG_DV_DEMUXER
1010 case CODEC_ID_DVAUDIO:
1011 c->dv_fctx = avformat_alloc_context();
1012 c->dv_demux = dv_init_demux(c->dv_fctx);
1014 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1017 sc->dv_audio_container = 1;
1018 st->codec->codec_id = CODEC_ID_PCM_S16LE;
1021 /* no ifdef since parameters are always those */
1022 case CODEC_ID_QCELP:
1023 st->codec->frame_size= 160;
1024 st->codec->channels= 1; /* really needed */
1026 case CODEC_ID_AMR_NB:
1027 case CODEC_ID_AMR_WB:
1028 st->codec->frame_size= sc->samples_per_frame;
1029 st->codec->channels= 1; /* really needed */
1030 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1031 if (st->codec->codec_id == CODEC_ID_AMR_NB)
1032 st->codec->sample_rate = 8000;
1033 else if (st->codec->codec_id == CODEC_ID_AMR_WB)
1034 st->codec->sample_rate = 16000;
1038 st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1039 st->need_parsing = AVSTREAM_PARSE_FULL;
1042 case CODEC_ID_ADPCM_MS:
1043 case CODEC_ID_ADPCM_IMA_WAV:
1044 st->codec->block_align = sc->bytes_per_frame;
1047 if (st->codec->extradata_size == 36) {
1048 st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1049 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1059 static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1061 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1062 MOVStreamContext *sc = st->priv_data;
1063 unsigned int i, entries;
1065 get_byte(pb); /* version */
1066 get_be24(pb); /* flags */
1068 entries = get_be32(pb);
1070 if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
1073 dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1075 sc->stsc_count = entries;
1076 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1079 for(i=0; i<entries; i++) {
1080 sc->stsc_data[i].first = get_be32(pb);
1081 sc->stsc_data[i].count = get_be32(pb);
1082 sc->stsc_data[i].id = get_be32(pb);
1087 static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1089 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1090 MOVStreamContext *sc = st->priv_data;
1091 unsigned int i, entries;
1093 get_byte(pb); /* version */
1094 get_be24(pb); /* flags */
1096 entries = get_be32(pb);
1098 if(entries >= UINT_MAX / sizeof(int))
1101 sc->keyframe_count = entries;
1103 dprintf(c->fc, "keyframe_count = %d\n", sc->keyframe_count);
1105 sc->keyframes = av_malloc(entries * sizeof(int));
1108 for(i=0; i<entries; i++) {
1109 sc->keyframes[i] = get_be32(pb);
1110 //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1115 static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1117 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1118 MOVStreamContext *sc = st->priv_data;
1119 unsigned int i, entries, sample_size;
1121 get_byte(pb); /* version */
1122 get_be24(pb); /* flags */
1124 sample_size = get_be32(pb);
1125 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1126 sc->sample_size = sample_size;
1127 entries = get_be32(pb);
1128 if(entries >= UINT_MAX / sizeof(int))
1131 sc->sample_count = entries;
1135 dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, sc->sample_count);
1137 sc->sample_sizes = av_malloc(entries * sizeof(int));
1138 if (!sc->sample_sizes)
1140 for(i=0; i<entries; i++)
1141 sc->sample_sizes[i] = get_be32(pb);
1145 static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1147 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1148 MOVStreamContext *sc = st->priv_data;
1149 unsigned int i, entries;
1151 int64_t total_sample_count=0;
1153 get_byte(pb); /* version */
1154 get_be24(pb); /* flags */
1155 entries = get_be32(pb);
1156 if(entries >= UINT_MAX / sizeof(*sc->stts_data))
1159 sc->stts_count = entries;
1160 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1163 dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1165 for(i=0; i<entries; i++) {
1166 int sample_duration;
1169 sample_count=get_be32(pb);
1170 sample_duration = get_be32(pb);
1171 sc->stts_data[i].count= sample_count;
1172 sc->stts_data[i].duration= sample_duration;
1174 sc->time_rate= av_gcd(sc->time_rate, sample_duration);
1176 dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1178 duration+=(int64_t)sample_duration*sample_count;
1179 total_sample_count+=sample_count;
1182 st->nb_frames= total_sample_count;
1184 st->duration= duration;
1188 static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1190 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1191 MOVStreamContext *sc = st->priv_data;
1192 unsigned int i, entries;
1194 get_byte(pb); /* version */
1195 get_be24(pb); /* flags */
1196 entries = get_be32(pb);
1197 if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
1200 sc->ctts_count = entries;
1201 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1204 dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1206 for(i=0; i<entries; i++) {
1207 int count =get_be32(pb);
1208 int duration =get_be32(pb);
1212 st->codec->has_b_frames = 1;
1214 sc->ctts_data[i].count = count;
1215 sc->ctts_data[i].duration= duration;
1217 sc->time_rate= av_gcd(sc->time_rate, FFABS(duration));
1222 static void mov_build_index(MOVContext *mov, AVStream *st)
1224 MOVStreamContext *sc = st->priv_data;
1225 int64_t current_offset;
1226 int64_t current_dts = 0;
1227 unsigned int stts_index = 0;
1228 unsigned int stsc_index = 0;
1229 unsigned int stss_index = 0;
1232 /* adjust first dts according to edit list */
1233 if (sc->time_offset) {
1234 assert(sc->time_offset % sc->time_rate == 0);
1235 current_dts = - (sc->time_offset / sc->time_rate);
1238 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1239 if (!(st->codec->codec_type == CODEC_TYPE_AUDIO &&
1240 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1241 unsigned int current_sample = 0;
1242 unsigned int stts_sample = 0;
1243 unsigned int keyframe, sample_size;
1244 unsigned int distance = 0;
1245 int key_off = sc->keyframes && sc->keyframes[0] == 1;
1247 st->nb_frames = sc->sample_count;
1248 for (i = 0; i < sc->chunk_count; i++) {
1249 current_offset = sc->chunk_offsets[i];
1250 if (stsc_index + 1 < sc->stsc_count &&
1251 i + 1 == sc->stsc_data[stsc_index + 1].first)
1253 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1254 if (current_sample >= sc->sample_count) {
1255 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1258 keyframe = !sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index];
1261 if (stss_index + 1 < sc->keyframe_count)
1264 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1265 if(sc->pseudo_stream_id == -1 ||
1266 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1267 av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
1268 keyframe ? AVINDEX_KEYFRAME : 0);
1269 dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1270 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1271 current_offset, current_dts, sample_size, distance, keyframe);
1273 current_offset += sample_size;
1274 assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
1275 current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
1279 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1285 } else { /* read whole chunk */
1286 unsigned int chunk_samples, chunk_size, chunk_duration;
1287 unsigned int frames = 1;
1288 for (i = 0; i < sc->chunk_count; i++) {
1289 current_offset = sc->chunk_offsets[i];
1290 if (stsc_index + 1 < sc->stsc_count &&
1291 i + 1 == sc->stsc_data[stsc_index + 1].first)
1293 chunk_samples = sc->stsc_data[stsc_index].count;
1294 /* get chunk size, beware of alaw/ulaw/mace */
1295 if (sc->samples_per_frame > 0 &&
1296 (chunk_samples * sc->bytes_per_frame % sc->samples_per_frame == 0)) {
1297 if (sc->samples_per_frame < 160)
1298 chunk_size = chunk_samples * sc->bytes_per_frame / sc->samples_per_frame;
1300 chunk_size = sc->bytes_per_frame;
1301 frames = chunk_samples / sc->samples_per_frame;
1302 chunk_samples = sc->samples_per_frame;
1305 chunk_size = chunk_samples * sc->sample_size;
1306 for (j = 0; j < frames; j++) {
1307 av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
1308 /* get chunk duration */
1310 while (chunk_samples > 0) {
1311 if (chunk_samples < sc->stts_data[stts_index].count) {
1312 chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1313 sc->stts_data[stts_index].count -= chunk_samples;
1316 chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1317 chunk_samples -= sc->stts_data[stts_index].count;
1318 if (stts_index + 1 < sc->stts_count)
1322 current_offset += sc->bytes_per_frame;
1323 dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1324 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1325 chunk_size, chunk_duration);
1326 assert(chunk_duration % sc->time_rate == 0);
1327 current_dts += chunk_duration / sc->time_rate;
1332 /* adjust sample count to avindex entries */
1333 sc->sample_count = st->nb_index_entries;
1336 static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1339 MOVStreamContext *sc;
1342 st = av_new_stream(c->fc, c->fc->nb_streams);
1343 if (!st) return AVERROR(ENOMEM);
1344 sc = av_mallocz(sizeof(MOVStreamContext));
1345 if (!sc) return AVERROR(ENOMEM);
1348 st->codec->codec_type = CODEC_TYPE_DATA;
1349 st->start_time = 0; /* XXX: check */
1350 sc->ffindex = st->index;
1352 if ((ret = mov_read_default(c, pb, atom)) < 0)
1356 if(sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1357 (!sc->sample_size && !sc->sample_count))){
1358 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1360 sc->sample_count = 0; //ignore track
1366 sc->time_scale= c->time_scale;
1367 av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
1369 if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
1370 !st->codec->frame_size && sc->stts_count == 1)
1371 st->codec->frame_size = av_rescale(sc->time_rate, st->codec->sample_rate, sc->time_scale);
1373 if(st->duration != AV_NOPTS_VALUE){
1374 assert(st->duration % sc->time_rate == 0);
1375 st->duration /= sc->time_rate;
1378 mov_build_index(c, st);
1380 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1381 if (url_fopen(&sc->pb, sc->drefs[sc->dref_id-1].path, URL_RDONLY) < 0)
1382 av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening file %s: %s\n",
1383 st->index, sc->drefs[sc->dref_id-1].path, strerror(errno));
1387 switch (st->codec->codec_id) {
1388 #if CONFIG_H261_DECODER
1391 #if CONFIG_H263_DECODER
1394 #if CONFIG_MPEG4_DECODER
1395 case CODEC_ID_MPEG4:
1397 st->codec->width= 0; /* let decoder init width/height */
1398 st->codec->height= 0;
1402 /* Do not need those anymore. */
1403 av_freep(&sc->chunk_offsets);
1404 av_freep(&sc->stsc_data);
1405 av_freep(&sc->sample_sizes);
1406 av_freep(&sc->keyframes);
1407 av_freep(&sc->stts_data);
1412 static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1415 c->itunes_metadata = 1;
1416 ret = mov_read_default(c, pb, atom);
1417 c->itunes_metadata = 0;
1421 static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1423 url_fskip(pb, 4); // version + flags
1425 return mov_read_default(c, pb, atom);
1428 static int mov_read_trkn(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1430 get_be32(pb); // type
1431 get_be32(pb); // unknown
1432 c->fc->track = get_be32(pb);
1433 dprintf(c->fc, "%.4s %d\n", (char*)&atom.type, c->fc->track);
1437 static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1443 if (c->itunes_metadata) {
1444 int data_size = get_be32(pb);
1445 int tag = get_le32(pb);
1446 if (tag == MKTAG('d','a','t','a')) {
1447 get_be32(pb); // type
1448 get_be32(pb); // unknown
1449 str_size = data_size - 16;
1453 str_size = get_be16(pb); // string length
1454 get_be16(pb); // language
1457 switch (atom.type) {
1458 case MKTAG(0xa9,'n','a','m'):
1459 str = c->fc->title; size = sizeof(c->fc->title); break;
1460 case MKTAG(0xa9,'A','R','T'):
1461 case MKTAG(0xa9,'w','r','t'):
1462 str = c->fc->author; size = sizeof(c->fc->author); break;
1463 case MKTAG(0xa9,'c','p','y'):
1464 str = c->fc->copyright; size = sizeof(c->fc->copyright); break;
1465 case MKTAG(0xa9,'c','m','t'):
1466 case MKTAG(0xa9,'i','n','f'):
1467 str = c->fc->comment; size = sizeof(c->fc->comment); break;
1468 case MKTAG(0xa9,'a','l','b'):
1469 str = c->fc->album; size = sizeof(c->fc->album); break;
1476 get_buffer(pb, str, FFMIN3(size, str_size, atom.size));
1477 dprintf(c->fc, "%.4s %s %d %lld\n", (char*)&atom.type, str, str_size, atom.size);
1481 static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1486 int64_t disp_transform[2];
1487 int display_matrix[3][2];
1488 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1489 MOVStreamContext *sc = st->priv_data;
1490 int version = get_byte(pb);
1492 get_be24(pb); /* flags */
1494 MOV_TRACK_ENABLED 0x0001
1495 MOV_TRACK_IN_MOVIE 0x0002
1496 MOV_TRACK_IN_PREVIEW 0x0004
1497 MOV_TRACK_IN_POSTER 0x0008
1504 get_be32(pb); /* creation time */
1505 get_be32(pb); /* modification time */
1507 st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1508 get_be32(pb); /* reserved */
1509 st->start_time = 0; /* check */
1510 /* highlevel (considering edits) duration in movie timebase */
1511 (version == 1) ? get_be64(pb) : get_be32(pb);
1512 get_be32(pb); /* reserved */
1513 get_be32(pb); /* reserved */
1515 get_be16(pb); /* layer */
1516 get_be16(pb); /* alternate group */
1517 get_be16(pb); /* volume */
1518 get_be16(pb); /* reserved */
1520 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
1521 // they're kept in fixed point format through all calculations
1522 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
1523 for (i = 0; i < 3; i++) {
1524 display_matrix[i][0] = get_be32(pb); // 16.16 fixed point
1525 display_matrix[i][1] = get_be32(pb); // 16.16 fixed point
1526 get_be32(pb); // 2.30 fixed point (not used)
1529 width = get_be32(pb); // 16.16 fixed point track width
1530 height = get_be32(pb); // 16.16 fixed point track height
1531 sc->width = width >> 16;
1532 sc->height = height >> 16;
1534 //transform the display width/height according to the matrix
1535 // skip this if the display matrix is the default identity matrix
1536 // to keep the same scale, use [width height 1<<16]
1537 if (width && height &&
1538 (display_matrix[0][0] != 65536 || display_matrix[0][1] ||
1539 display_matrix[1][0] || display_matrix[1][1] != 65536 ||
1540 display_matrix[2][0] || display_matrix[2][1])) {
1541 for (i = 0; i < 2; i++)
1543 (int64_t) width * display_matrix[0][i] +
1544 (int64_t) height * display_matrix[1][i] +
1545 ((int64_t) display_matrix[2][i] << 16);
1547 //sample aspect ratio is new width/height divided by old width/height
1548 st->sample_aspect_ratio = av_d2q(
1549 ((double) disp_transform[0] * height) /
1550 ((double) disp_transform[1] * width), INT_MAX);
1555 static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1557 MOVFragment *frag = &c->fragment;
1558 MOVTrackExt *trex = NULL;
1559 int flags, track_id, i;
1561 get_byte(pb); /* version */
1562 flags = get_be24(pb);
1564 track_id = get_be32(pb);
1565 if (!track_id || track_id > c->fc->nb_streams)
1567 frag->track_id = track_id;
1568 for (i = 0; i < c->trex_count; i++)
1569 if (c->trex_data[i].track_id == frag->track_id) {
1570 trex = &c->trex_data[i];
1574 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
1578 if (flags & 0x01) frag->base_data_offset = get_be64(pb);
1579 else frag->base_data_offset = frag->moof_offset;
1580 if (flags & 0x02) frag->stsd_id = get_be32(pb);
1581 else frag->stsd_id = trex->stsd_id;
1583 frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
1584 frag->size = flags & 0x10 ? get_be32(pb) : trex->size;
1585 frag->flags = flags & 0x20 ? get_be32(pb) : trex->flags;
1586 dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
1590 static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1594 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
1596 c->trex_data = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
1598 return AVERROR(ENOMEM);
1599 trex = &c->trex_data[c->trex_count++];
1600 get_byte(pb); /* version */
1601 get_be24(pb); /* flags */
1602 trex->track_id = get_be32(pb);
1603 trex->stsd_id = get_be32(pb);
1604 trex->duration = get_be32(pb);
1605 trex->size = get_be32(pb);
1606 trex->flags = get_be32(pb);
1610 static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1612 MOVFragment *frag = &c->fragment;
1614 MOVStreamContext *sc;
1617 int data_offset = 0;
1618 unsigned entries, first_sample_flags = frag->flags;
1619 int flags, distance, i;
1621 if (!frag->track_id || frag->track_id > c->fc->nb_streams)
1623 st = c->fc->streams[frag->track_id-1];
1625 if (sc->pseudo_stream_id+1 != frag->stsd_id)
1627 get_byte(pb); /* version */
1628 flags = get_be24(pb);
1629 entries = get_be32(pb);
1630 dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
1631 if (flags & 0x001) data_offset = get_be32(pb);
1632 if (flags & 0x004) first_sample_flags = get_be32(pb);
1633 if (flags & 0x800) {
1634 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
1636 sc->ctts_data = av_realloc(sc->ctts_data,
1637 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
1639 return AVERROR(ENOMEM);
1642 offset = frag->base_data_offset + data_offset;
1644 dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
1645 for (i = 0; i < entries; i++) {
1646 unsigned sample_size = frag->size;
1647 int sample_flags = i ? frag->flags : first_sample_flags;
1648 unsigned sample_duration = frag->duration;
1651 if (flags & 0x100) sample_duration = get_be32(pb);
1652 if (flags & 0x200) sample_size = get_be32(pb);
1653 if (flags & 0x400) sample_flags = get_be32(pb);
1654 if (flags & 0x800) {
1655 sc->ctts_data[sc->ctts_count].count = 1;
1656 sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
1659 if ((keyframe = st->codec->codec_type == CODEC_TYPE_AUDIO ||
1660 (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
1662 av_add_index_entry(st, offset, dts, sample_size, distance,
1663 keyframe ? AVINDEX_KEYFRAME : 0);
1664 dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1665 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
1666 offset, dts, sample_size, distance, keyframe);
1668 assert(sample_duration % sc->time_rate == 0);
1669 dts += sample_duration / sc->time_rate;
1670 offset += sample_size;
1672 frag->moof_offset = offset;
1673 sc->sample_count = st->nb_index_entries;
1678 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1679 /* like the files created with Adobe Premiere 5.0, for samples see */
1680 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1681 static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1686 return 0; /* continue */
1687 if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1688 url_fskip(pb, atom.size - 4);
1691 atom.type = get_le32(pb);
1694 if (atom.type != MKTAG('m','d','a','t')) {
1695 url_fskip(pb, atom.size);
1698 err = mov_read_mdat(c, pb, atom);
1702 static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1707 uint8_t *moov_data; /* uncompressed data */
1708 long cmov_len, moov_len;
1711 get_be32(pb); /* dcom atom */
1712 if (get_le32(pb) != MKTAG('d','c','o','m'))
1714 if (get_le32(pb) != MKTAG('z','l','i','b')) {
1715 av_log(NULL, AV_LOG_ERROR, "unknown compression for cmov atom !");
1718 get_be32(pb); /* cmvd atom */
1719 if (get_le32(pb) != MKTAG('c','m','v','d'))
1721 moov_len = get_be32(pb); /* uncompressed size */
1722 cmov_len = atom.size - 6 * 4;
1724 cmov_data = av_malloc(cmov_len);
1727 moov_data = av_malloc(moov_len);
1732 get_buffer(pb, cmov_data, cmov_len);
1733 if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1734 goto free_and_return;
1735 if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
1736 goto free_and_return;
1737 atom.type = MKTAG('m','o','o','v');
1739 atom.size = moov_len;
1741 // { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1743 ret = mov_read_default(c, &ctx, atom);
1749 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
1754 /* edit list atom */
1755 static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1757 MOVStreamContext *sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
1760 get_byte(pb); /* version */
1761 get_be24(pb); /* flags */
1762 edit_count = get_be32(pb); /* entries */
1764 for(i=0; i<edit_count; i++){
1766 get_be32(pb); /* Track duration */
1767 time = get_be32(pb); /* Media time */
1768 get_be32(pb); /* Media rate */
1769 if (i == 0 && time != -1) {
1770 sc->time_offset = time;
1771 sc->time_rate = av_gcd(sc->time_rate, time);
1776 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
1777 "a/v desync might occur, patch welcome\n");
1779 dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
1783 static const MOVParseTableEntry mov_default_parse_table[] = {
1784 { MKTAG('a','v','s','s'), mov_read_extradata },
1785 { MKTAG('c','o','6','4'), mov_read_stco },
1786 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
1787 { MKTAG('d','i','n','f'), mov_read_default },
1788 { MKTAG('d','r','e','f'), mov_read_dref },
1789 { MKTAG('e','d','t','s'), mov_read_default },
1790 { MKTAG('e','l','s','t'), mov_read_elst },
1791 { MKTAG('e','n','d','a'), mov_read_enda },
1792 { MKTAG('f','i','e','l'), mov_read_extradata },
1793 { MKTAG('f','t','y','p'), mov_read_ftyp },
1794 { MKTAG('g','l','b','l'), mov_read_glbl },
1795 { MKTAG('h','d','l','r'), mov_read_hdlr },
1796 { MKTAG('i','l','s','t'), mov_read_ilst },
1797 { MKTAG('j','p','2','h'), mov_read_extradata },
1798 { MKTAG('m','d','a','t'), mov_read_mdat },
1799 { MKTAG('m','d','h','d'), mov_read_mdhd },
1800 { MKTAG('m','d','i','a'), mov_read_default },
1801 { MKTAG('m','e','t','a'), mov_read_meta },
1802 { MKTAG('m','i','n','f'), mov_read_default },
1803 { MKTAG('m','o','o','f'), mov_read_moof },
1804 { MKTAG('m','o','o','v'), mov_read_moov },
1805 { MKTAG('m','v','e','x'), mov_read_default },
1806 { MKTAG('m','v','h','d'), mov_read_mvhd },
1807 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
1808 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
1809 { MKTAG('a','v','c','C'), mov_read_glbl },
1810 { MKTAG('p','a','s','p'), mov_read_pasp },
1811 { MKTAG('s','t','b','l'), mov_read_default },
1812 { MKTAG('s','t','c','o'), mov_read_stco },
1813 { MKTAG('s','t','s','c'), mov_read_stsc },
1814 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
1815 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
1816 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
1817 { MKTAG('s','t','t','s'), mov_read_stts },
1818 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
1819 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
1820 { MKTAG('t','r','a','k'), mov_read_trak },
1821 { MKTAG('t','r','a','f'), mov_read_default },
1822 { MKTAG('t','r','e','x'), mov_read_trex },
1823 { MKTAG('t','r','k','n'), mov_read_trkn },
1824 { MKTAG('t','r','u','n'), mov_read_trun },
1825 { MKTAG('u','d','t','a'), mov_read_default },
1826 { MKTAG('w','a','v','e'), mov_read_wave },
1827 { MKTAG('e','s','d','s'), mov_read_esds },
1828 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
1829 { MKTAG('c','m','o','v'), mov_read_cmov },
1830 { MKTAG(0xa9,'n','a','m'), mov_read_udta_string },
1831 { MKTAG(0xa9,'w','r','t'), mov_read_udta_string },
1832 { MKTAG(0xa9,'c','p','y'), mov_read_udta_string },
1833 { MKTAG(0xa9,'i','n','f'), mov_read_udta_string },
1834 { MKTAG(0xa9,'i','n','f'), mov_read_udta_string },
1835 { MKTAG(0xa9,'A','R','T'), mov_read_udta_string },
1836 { MKTAG(0xa9,'a','l','b'), mov_read_udta_string },
1837 { MKTAG(0xa9,'c','m','t'), mov_read_udta_string },
1841 static int mov_probe(AVProbeData *p)
1843 unsigned int offset;
1847 /* check file header */
1850 /* ignore invalid offset */
1851 if ((offset + 8) > (unsigned int)p->buf_size)
1853 tag = AV_RL32(p->buf + offset + 4);
1855 /* check for obvious tags */
1856 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
1857 case MKTAG('m','o','o','v'):
1858 case MKTAG('m','d','a','t'):
1859 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
1860 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
1861 case MKTAG('f','t','y','p'):
1862 return AVPROBE_SCORE_MAX;
1863 /* those are more common words, so rate then a bit less */
1864 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
1865 case MKTAG('w','i','d','e'):
1866 case MKTAG('f','r','e','e'):
1867 case MKTAG('j','u','n','k'):
1868 case MKTAG('p','i','c','t'):
1869 return AVPROBE_SCORE_MAX - 5;
1870 case MKTAG(0x82,0x82,0x7f,0x7d):
1871 case MKTAG('s','k','i','p'):
1872 case MKTAG('u','u','i','d'):
1873 case MKTAG('p','r','f','l'):
1874 offset = AV_RB32(p->buf+offset) + offset;
1875 /* if we only find those cause probedata is too small at least rate them */
1876 score = AVPROBE_SCORE_MAX - 50;
1879 /* unrecognized tag */
1886 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1888 MOVContext *mov = s->priv_data;
1889 ByteIOContext *pb = s->pb;
1891 MOVAtom atom = { 0, 0, 0 };
1894 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1895 if(!url_is_streamed(pb))
1896 atom.size = url_fsize(pb);
1898 atom.size = INT64_MAX;
1900 /* check MOV header */
1901 if ((err = mov_read_default(mov, pb, atom)) < 0) {
1902 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
1905 if (!mov->found_moov) {
1906 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
1909 dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
1914 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1916 MOVContext *mov = s->priv_data;
1917 MOVStreamContext *sc = 0;
1918 AVIndexEntry *sample = 0;
1919 int64_t best_dts = INT64_MAX;
1922 for (i = 0; i < s->nb_streams; i++) {
1923 AVStream *st = s->streams[i];
1924 MOVStreamContext *msc = st->priv_data;
1925 if (st->discard != AVDISCARD_ALL && msc->pb && msc->current_sample < msc->sample_count) {
1926 AVIndexEntry *current_sample = &st->index_entries[msc->current_sample];
1927 int64_t dts = av_rescale(current_sample->timestamp * (int64_t)msc->time_rate,
1928 AV_TIME_BASE, msc->time_scale);
1929 dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
1930 if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
1931 (!url_is_streamed(s->pb) &&
1932 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
1933 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
1934 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
1935 sample = current_sample;
1942 mov->found_mdat = 0;
1943 if (!url_is_streamed(s->pb) ||
1944 mov_read_default(mov, s->pb, (MOVAtom){ 0, 0, INT64_MAX }) < 0 ||
1947 dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
1950 /* must be done just before reading, to avoid infinite loop on sample */
1951 sc->current_sample++;
1952 if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
1953 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
1954 sc->ffindex, sample->pos);
1957 av_get_packet(sc->pb, pkt, sample->size);
1958 #if CONFIG_DV_DEMUXER
1959 if (mov->dv_demux && sc->dv_audio_container) {
1960 dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
1963 if (dv_get_packet(mov->dv_demux, pkt) < 0)
1967 pkt->stream_index = sc->ffindex;
1968 pkt->dts = sample->timestamp;
1969 if (sc->ctts_data) {
1970 assert(sc->ctts_data[sc->ctts_index].duration % sc->time_rate == 0);
1971 pkt->pts = pkt->dts + sc->ctts_data[sc->ctts_index].duration / sc->time_rate;
1972 /* update ctts context */
1974 if (sc->ctts_index < sc->ctts_count &&
1975 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
1977 sc->ctts_sample = 0;
1980 pkt->dts = AV_NOPTS_VALUE;
1982 AVStream *st = s->streams[sc->ffindex];
1983 int64_t next_dts = (sc->current_sample < sc->sample_count) ?
1984 st->index_entries[sc->current_sample].timestamp : st->duration;
1985 pkt->duration = next_dts - pkt->dts;
1986 pkt->pts = pkt->dts;
1988 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
1989 pkt->pos = sample->pos;
1990 dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
1991 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
1995 static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
1997 MOVStreamContext *sc = st->priv_data;
1998 int sample, time_sample;
2001 sample = av_index_search_timestamp(st, timestamp, flags);
2002 dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2003 if (sample < 0) /* not sure what to do */
2005 sc->current_sample = sample;
2006 dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
2007 /* adjust ctts index */
2008 if (sc->ctts_data) {
2010 for (i = 0; i < sc->ctts_count; i++) {
2011 int next = time_sample + sc->ctts_data[i].count;
2012 if (next > sc->current_sample) {
2014 sc->ctts_sample = sc->current_sample - time_sample;
2023 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2026 int64_t seek_timestamp, timestamp;
2030 if (stream_index >= s->nb_streams)
2032 if (sample_time < 0)
2035 st = s->streams[stream_index];
2036 sample = mov_seek_stream(st, sample_time, flags);
2040 /* adjust seek timestamp to found sample timestamp */
2041 seek_timestamp = st->index_entries[sample].timestamp;
2043 for (i = 0; i < s->nb_streams; i++) {
2045 if (stream_index == i || st->discard == AVDISCARD_ALL)
2048 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2049 mov_seek_stream(st, timestamp, flags);
2054 static int mov_read_close(AVFormatContext *s)
2057 MOVContext *mov = s->priv_data;
2058 for(i=0; i<s->nb_streams; i++) {
2059 MOVStreamContext *sc = s->streams[i]->priv_data;
2060 av_freep(&sc->ctts_data);
2061 for (j=0; j<sc->drefs_count; j++)
2062 av_freep(&sc->drefs[j].path);
2063 av_freep(&sc->drefs);
2064 if (sc->pb && sc->pb != s->pb)
2068 for(i=0; i<mov->dv_fctx->nb_streams; i++){
2069 av_freep(&mov->dv_fctx->streams[i]->codec);
2070 av_freep(&mov->dv_fctx->streams[i]);
2072 av_freep(&mov->dv_fctx);
2073 av_freep(&mov->dv_demux);
2075 av_freep(&mov->trex_data);
2079 AVInputFormat mov_demuxer = {
2080 "mov,mp4,m4a,3gp,3g2,mj2",
2081 NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),