Add a VorbisComment metadata conversion table and use it in the FLAC and
[FFMpeg-mirror/lagarith.git] / libavformat / mov.c
blobaf94394516c5de76932e9da9c9bd775e2d9fc8f4
1 /*
2 * MOV demuxer
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 FFmpeg.
8 * FFmpeg 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 * FFmpeg 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 FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include <limits.h>
25 //#define DEBUG
26 //#define DEBUG_METADATA
27 //#define MOV_EXPORT_ALL_METADATA
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/avstring.h"
31 #include "avformat.h"
32 #include "riff.h"
33 #include "isom.h"
34 #include "libavcodec/mpeg4audio.h"
35 #include "libavcodec/mpegaudiodata.h"
36 #include "libavcodec/get_bits.h"
38 #if CONFIG_ZLIB
39 #include <zlib.h>
40 #endif
43 * First version by Francois Revol revol@free.fr
44 * Seek function by Gael Chardon gael.dev@4now.net
46 * Features and limitations:
47 * - reads most of the QT files I have (at least the structure),
48 * Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
49 * - the code is quite ugly... maybe I won't do it recursive next time :-)
51 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
52 * when coding this :) (it's a writer anyway)
54 * Reference documents:
55 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
56 * Apple:
57 * http://developer.apple.com/documentation/QuickTime/QTFF/
58 * http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
59 * QuickTime is a trademark of Apple (AFAIK :))
62 #include "qtpalette.h"
65 #undef NDEBUG
66 #include <assert.h>
68 /* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
70 /* those functions parse an atom */
71 /* return code:
72 0: continue to parse next atom
73 <0: error occurred, exit
75 /* links atom IDs to parse functions */
76 typedef struct MOVParseTableEntry {
77 uint32_t type;
78 int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOVAtom atom);
79 } MOVParseTableEntry;
81 static const MOVParseTableEntry mov_default_parse_table[];
83 static int mov_metadata_trkn(MOVContext *c, ByteIOContext *pb, unsigned len)
85 char buf[16];
87 get_be16(pb); // unknown
88 snprintf(buf, sizeof(buf), "%d", get_be16(pb));
89 av_metadata_set(&c->fc->metadata, "track", buf);
91 get_be16(pb); // total tracks
93 return 0;
96 static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
98 #ifdef MOV_EXPORT_ALL_METADATA
99 char tmp_key[5];
100 #endif
101 char str[1024], key2[16], language[4] = {0};
102 const char *key = NULL;
103 uint16_t str_size;
104 int (*parse)(MOVContext*, ByteIOContext*, unsigned) = NULL;
106 switch (atom.type) {
107 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
108 case MKTAG(0xa9,'a','u','t'):
109 case MKTAG(0xa9,'A','R','T'):
110 case MKTAG(0xa9,'w','r','t'): key = "author"; break;
111 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
112 case MKTAG(0xa9,'c','m','t'):
113 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
114 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
115 case MKTAG(0xa9,'d','a','y'): key = "year"; break;
116 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
117 case MKTAG(0xa9,'t','o','o'):
118 case MKTAG(0xa9,'e','n','c'): key = "muxer"; break;
119 case MKTAG( 't','r','k','n'): key = "track";
120 parse = mov_metadata_trkn; break;
123 if (c->itunes_metadata && atom.size > 8) {
124 int data_size = get_be32(pb);
125 int tag = get_le32(pb);
126 if (tag == MKTAG('d','a','t','a')) {
127 get_be32(pb); // type
128 get_be32(pb); // unknown
129 str_size = data_size - 16;
130 atom.size -= 16;
131 } else return 0;
132 } else if (atom.size > 4 && key && !c->itunes_metadata) {
133 str_size = get_be16(pb); // string length
134 ff_mov_lang_to_iso639(get_be16(pb), language);
135 atom.size -= 4;
136 } else
137 str_size = atom.size;
139 #ifdef MOV_EXPORT_ALL_METADATA
140 if (!key) {
141 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
142 key = tmp_key;
144 #endif
146 if (!key)
147 return 0;
148 if (atom.size < 0)
149 return -1;
151 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
153 if (parse)
154 parse(c, pb, str_size);
155 else {
156 get_buffer(pb, str, str_size);
157 str[str_size] = 0;
158 av_metadata_set(&c->fc->metadata, key, str);
159 if (*language && strcmp(language, "und")) {
160 snprintf(key2, sizeof(key2), "%s-%s", key, language);
161 av_metadata_set(&c->fc->metadata, key2, str);
164 #ifdef DEBUG_METADATA
165 av_log(c->fc, AV_LOG_DEBUG, "lang \"%3s\" ", language);
166 av_log(c->fc, AV_LOG_DEBUG, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %lld\n",
167 key, str, (char*)&atom.type, str_size, atom.size);
168 #endif
170 return 0;
173 static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
175 int64_t total_size = 0;
176 MOVAtom a;
177 int i;
178 int err = 0;
180 a.offset = atom.offset;
182 if (atom.size < 0)
183 atom.size = INT64_MAX;
184 while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
185 int (*parse)(MOVContext*, ByteIOContext*, MOVAtom) = NULL;
186 a.size = atom.size;
187 a.type=0;
188 if(atom.size >= 8) {
189 a.size = get_be32(pb);
190 a.type = get_le32(pb);
192 total_size += 8;
193 a.offset += 8;
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;
198 a.offset += 8;
199 total_size += 8;
201 if (a.size == 0) {
202 a.size = atom.size - total_size;
203 if (a.size <= 8)
204 break;
206 a.size -= 8;
207 if(a.size < 0)
208 break;
209 a.size = FFMIN(a.size, atom.size - total_size);
211 for (i = 0; mov_default_parse_table[i].type; i++)
212 if (mov_default_parse_table[i].type == a.type) {
213 parse = mov_default_parse_table[i].parse;
214 break;
217 // container is user data
218 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
219 atom.type == MKTAG('i','l','s','t')))
220 parse = mov_read_udta_string;
222 if (!parse) { /* skip leaf atoms data */
223 url_fskip(pb, a.size);
224 } else {
225 int64_t start_pos = url_ftell(pb);
226 int64_t left;
227 err = parse(c, pb, a);
228 if (url_is_streamed(pb) && c->found_moov && c->found_mdat)
229 break;
230 left = a.size - url_ftell(pb) + start_pos;
231 if (left > 0) /* skip garbage at atom end */
232 url_fskip(pb, left);
235 a.offset += a.size;
236 total_size += a.size;
239 if (!err && total_size < atom.size && atom.size < 0x7ffff)
240 url_fskip(pb, atom.size - total_size);
242 return err;
245 static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
247 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
248 MOVStreamContext *sc = st->priv_data;
249 int entries, i, j;
251 get_be32(pb); // version + flags
252 entries = get_be32(pb);
253 if (entries >= UINT_MAX / sizeof(*sc->drefs))
254 return -1;
255 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
256 if (!sc->drefs)
257 return AVERROR(ENOMEM);
258 sc->drefs_count = entries;
260 for (i = 0; i < sc->drefs_count; i++) {
261 MOVDref *dref = &sc->drefs[i];
262 uint32_t size = get_be32(pb);
263 int64_t next = url_ftell(pb) + size - 4;
265 dref->type = get_le32(pb);
266 get_be32(pb); // version + flags
267 dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
269 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
270 /* macintosh alias record */
271 uint16_t volume_len, len;
272 char volume[28];
273 int16_t type;
275 url_fskip(pb, 10);
277 volume_len = get_byte(pb);
278 volume_len = FFMIN(volume_len, 27);
279 get_buffer(pb, volume, 27);
280 volume[volume_len] = 0;
281 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", volume, volume_len);
283 url_fskip(pb, 112);
285 for (type = 0; type != -1 && url_ftell(pb) < next; ) {
286 type = get_be16(pb);
287 len = get_be16(pb);
288 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
289 if (len&1)
290 len += 1;
291 if (type == 2) { // absolute path
292 av_free(dref->path);
293 dref->path = av_mallocz(len+1);
294 if (!dref->path)
295 return AVERROR(ENOMEM);
296 get_buffer(pb, dref->path, len);
297 if (len > volume_len && !strncmp(dref->path, volume, volume_len)) {
298 len -= volume_len;
299 memmove(dref->path, dref->path+volume_len, len);
300 dref->path[len] = 0;
302 for (j = 0; j < len; j++)
303 if (dref->path[j] == ':')
304 dref->path[j] = '/';
305 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
306 } else
307 url_fskip(pb, len);
310 url_fseek(pb, next, SEEK_SET);
312 return 0;
315 static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
317 AVStream *st;
318 uint32_t type;
319 uint32_t ctype;
321 if (c->fc->nb_streams < 1) // meta before first trak
322 return 0;
324 st = c->fc->streams[c->fc->nb_streams-1];
326 get_byte(pb); /* version */
327 get_be24(pb); /* flags */
329 /* component type */
330 ctype = get_le32(pb);
331 type = get_le32(pb); /* component subtype */
333 dprintf(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
334 dprintf(c->fc, "stype= %.4s\n", (char*)&type);
336 if (type == MKTAG('v','i','d','e'))
337 st->codec->codec_type = CODEC_TYPE_VIDEO;
338 else if(type == MKTAG('s','o','u','n'))
339 st->codec->codec_type = CODEC_TYPE_AUDIO;
340 else if(type == MKTAG('m','1','a',' '))
341 st->codec->codec_id = CODEC_ID_MP2;
342 else if(type == MKTAG('s','u','b','p'))
343 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
345 get_be32(pb); /* component manufacture */
346 get_be32(pb); /* component flags */
347 get_be32(pb); /* component flags mask */
349 if(atom.size <= 24)
350 return 0; /* nothing left to read */
352 url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
353 return 0;
356 static int mp4_read_descr_len(ByteIOContext *pb)
358 int len = 0;
359 int count = 4;
360 while (count--) {
361 int c = get_byte(pb);
362 len = (len << 7) | (c & 0x7f);
363 if (!(c & 0x80))
364 break;
366 return len;
369 static int mp4_read_descr(MOVContext *c, ByteIOContext *pb, int *tag)
371 int len;
372 *tag = get_byte(pb);
373 len = mp4_read_descr_len(pb);
374 dprintf(c->fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
375 return len;
378 #define MP4ESDescrTag 0x03
379 #define MP4DecConfigDescrTag 0x04
380 #define MP4DecSpecificDescrTag 0x05
382 static const AVCodecTag mp4_audio_types[] = {
383 { CODEC_ID_MP3ON4, AOT_PS }, /* old mp3on4 draft */
384 { CODEC_ID_MP3ON4, AOT_L1 }, /* layer 1 */
385 { CODEC_ID_MP3ON4, AOT_L2 }, /* layer 2 */
386 { CODEC_ID_MP3ON4, AOT_L3 }, /* layer 3 */
387 { CODEC_ID_MP4ALS, AOT_ALS }, /* MPEG-4 ALS */
388 { CODEC_ID_NONE, AOT_NULL },
391 static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
393 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
394 int tag, len;
396 get_be32(pb); /* version + flags */
397 len = mp4_read_descr(c, pb, &tag);
398 if (tag == MP4ESDescrTag) {
399 get_be16(pb); /* ID */
400 get_byte(pb); /* priority */
401 } else
402 get_be16(pb); /* ID */
404 len = mp4_read_descr(c, pb, &tag);
405 if (tag == MP4DecConfigDescrTag) {
406 int object_type_id = get_byte(pb);
407 get_byte(pb); /* stream type */
408 get_be24(pb); /* buffer size db */
409 get_be32(pb); /* max bitrate */
410 get_be32(pb); /* avg bitrate */
412 st->codec->codec_id= codec_get_id(ff_mp4_obj_type, object_type_id);
413 dprintf(c->fc, "esds object type id %d\n", object_type_id);
414 len = mp4_read_descr(c, pb, &tag);
415 if (tag == MP4DecSpecificDescrTag) {
416 dprintf(c->fc, "Specific MPEG4 header len=%d\n", len);
417 if((uint64_t)len > (1<<30))
418 return -1;
419 st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
420 if (!st->codec->extradata)
421 return AVERROR(ENOMEM);
422 get_buffer(pb, st->codec->extradata, len);
423 st->codec->extradata_size = len;
424 if (st->codec->codec_id == CODEC_ID_AAC) {
425 MPEG4AudioConfig cfg;
426 ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
427 st->codec->extradata_size);
428 if (cfg.chan_config > 7)
429 return -1;
430 st->codec->channels = ff_mpeg4audio_channels[cfg.chan_config];
431 if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
432 st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
433 else
434 st->codec->sample_rate = cfg.sample_rate; // ext sample rate ?
435 dprintf(c->fc, "mp4a config channels %d obj %d ext obj %d "
436 "sample rate %d ext sample rate %d\n", st->codec->channels,
437 cfg.object_type, cfg.ext_object_type,
438 cfg.sample_rate, cfg.ext_sample_rate);
439 if (!(st->codec->codec_id = codec_get_id(mp4_audio_types,
440 cfg.object_type)))
441 st->codec->codec_id = CODEC_ID_AAC;
445 return 0;
448 static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
450 const int num = get_be32(pb);
451 const int den = get_be32(pb);
452 AVStream * const st = c->fc->streams[c->fc->nb_streams-1];
453 if (den != 0) {
454 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
455 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))
456 av_log(c->fc, AV_LOG_WARNING,
457 "sample aspect ratio already set to %d:%d, overriding by 'pasp' atom\n",
458 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
459 st->sample_aspect_ratio.num = num;
460 st->sample_aspect_ratio.den = den;
462 return 0;
465 /* this atom contains actual media data */
466 static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
468 if(atom.size == 0) /* wrong one (MP4) */
469 return 0;
470 c->found_mdat=1;
471 return 0; /* now go for moov */
474 static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
476 uint32_t type = get_le32(pb);
478 if (type != MKTAG('q','t',' ',' '))
479 c->isom = 1;
480 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
481 get_be32(pb); /* minor version */
482 url_fskip(pb, atom.size - 8);
483 return 0;
486 /* this atom should contain all header atoms */
487 static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
489 if (mov_read_default(c, pb, atom) < 0)
490 return -1;
491 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
492 /* so we don't parse the whole file if over a network */
493 c->found_moov=1;
494 return 0; /* now go for mdat */
497 static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
499 c->fragment.moof_offset = url_ftell(pb) - 8;
500 dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
501 return mov_read_default(c, pb, atom);
504 static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
506 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
507 MOVStreamContext *sc = st->priv_data;
508 int version = get_byte(pb);
509 char language[4] = {0};
510 unsigned lang;
512 if (version > 1)
513 return -1; /* unsupported */
515 get_be24(pb); /* flags */
516 if (version == 1) {
517 get_be64(pb);
518 get_be64(pb);
519 } else {
520 get_be32(pb); /* creation time */
521 get_be32(pb); /* modification time */
524 sc->time_scale = get_be32(pb);
525 st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
527 lang = get_be16(pb); /* language */
528 if (ff_mov_lang_to_iso639(lang, language))
529 av_metadata_set(&st->metadata, "language", language);
530 get_be16(pb); /* quality */
532 return 0;
535 static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
537 int version = get_byte(pb); /* version */
538 get_be24(pb); /* flags */
540 if (version == 1) {
541 get_be64(pb);
542 get_be64(pb);
543 } else {
544 get_be32(pb); /* creation time */
545 get_be32(pb); /* modification time */
547 c->time_scale = get_be32(pb); /* time scale */
549 dprintf(c->fc, "time scale = %i\n", c->time_scale);
551 c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
552 get_be32(pb); /* preferred scale */
554 get_be16(pb); /* preferred volume */
556 url_fskip(pb, 10); /* reserved */
558 url_fskip(pb, 36); /* display matrix */
560 get_be32(pb); /* preview time */
561 get_be32(pb); /* preview duration */
562 get_be32(pb); /* poster time */
563 get_be32(pb); /* selection time */
564 get_be32(pb); /* selection duration */
565 get_be32(pb); /* current time */
566 get_be32(pb); /* next track ID */
568 return 0;
571 static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
573 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
575 if((uint64_t)atom.size > (1<<30))
576 return -1;
578 // currently SVQ3 decoder expect full STSD header - so let's fake it
579 // this should be fixed and just SMI header should be passed
580 av_free(st->codec->extradata);
581 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
582 if (!st->codec->extradata)
583 return AVERROR(ENOMEM);
584 st->codec->extradata_size = 0x5a + atom.size;
585 memcpy(st->codec->extradata, "SVQ3", 4); // fake
586 get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
587 dprintf(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
588 return 0;
591 static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
593 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
594 int little_endian = get_be16(pb);
596 dprintf(c->fc, "enda %d\n", little_endian);
597 if (little_endian == 1) {
598 switch (st->codec->codec_id) {
599 case CODEC_ID_PCM_S24BE:
600 st->codec->codec_id = CODEC_ID_PCM_S24LE;
601 break;
602 case CODEC_ID_PCM_S32BE:
603 st->codec->codec_id = CODEC_ID_PCM_S32LE;
604 break;
605 case CODEC_ID_PCM_F32BE:
606 st->codec->codec_id = CODEC_ID_PCM_F32LE;
607 break;
608 case CODEC_ID_PCM_F64BE:
609 st->codec->codec_id = CODEC_ID_PCM_F64LE;
610 break;
611 default:
612 break;
615 return 0;
618 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
619 static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
621 AVStream *st;
622 uint64_t size;
623 uint8_t *buf;
625 if (c->fc->nb_streams < 1) // will happen with jp2 files
626 return 0;
627 st= c->fc->streams[c->fc->nb_streams-1];
628 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
629 if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
630 return -1;
631 buf= av_realloc(st->codec->extradata, size);
632 if(!buf)
633 return -1;
634 st->codec->extradata= buf;
635 buf+= st->codec->extradata_size;
636 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
637 AV_WB32( buf , atom.size + 8);
638 AV_WL32( buf + 4, atom.type);
639 get_buffer(pb, buf + 8, atom.size);
640 return 0;
643 static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
645 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
647 if((uint64_t)atom.size > (1<<30))
648 return -1;
650 if (st->codec->codec_id == CODEC_ID_QDM2) {
651 // pass all frma atom to codec, needed at least for QDM2
652 av_free(st->codec->extradata);
653 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
654 if (!st->codec->extradata)
655 return AVERROR(ENOMEM);
656 st->codec->extradata_size = atom.size;
657 get_buffer(pb, st->codec->extradata, atom.size);
658 } else if (atom.size > 8) { /* to read frma, esds atoms */
659 if (mov_read_default(c, pb, atom) < 0)
660 return -1;
661 } else
662 url_fskip(pb, atom.size);
663 return 0;
667 * This function reads atom content and puts data in extradata without tag
668 * nor size unlike mov_read_extradata.
670 static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
672 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
674 if((uint64_t)atom.size > (1<<30))
675 return -1;
677 av_free(st->codec->extradata);
678 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
679 if (!st->codec->extradata)
680 return AVERROR(ENOMEM);
681 st->codec->extradata_size = atom.size;
682 get_buffer(pb, st->codec->extradata, atom.size);
683 return 0;
686 static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
688 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
689 MOVStreamContext *sc = st->priv_data;
690 unsigned int i, entries;
692 get_byte(pb); /* version */
693 get_be24(pb); /* flags */
695 entries = get_be32(pb);
697 if(entries >= UINT_MAX/sizeof(int64_t))
698 return -1;
700 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
701 if (!sc->chunk_offsets)
702 return AVERROR(ENOMEM);
703 sc->chunk_count = entries;
705 if (atom.type == MKTAG('s','t','c','o'))
706 for(i=0; i<entries; i++)
707 sc->chunk_offsets[i] = get_be32(pb);
708 else if (atom.type == MKTAG('c','o','6','4'))
709 for(i=0; i<entries; i++)
710 sc->chunk_offsets[i] = get_be64(pb);
711 else
712 return -1;
714 return 0;
718 * Compute codec id for 'lpcm' tag.
719 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
721 static enum CodecID mov_get_lpcm_codec_id(int bps, int flags)
723 if (flags & 1) { // floating point
724 if (flags & 2) { // big endian
725 if (bps == 32) return CODEC_ID_PCM_F32BE;
726 else if (bps == 64) return CODEC_ID_PCM_F64BE;
727 } else {
728 if (bps == 32) return CODEC_ID_PCM_F32LE;
729 else if (bps == 64) return CODEC_ID_PCM_F64LE;
731 } else {
732 if (flags & 2) {
733 if (bps == 8)
734 // signed integer
735 if (flags & 4) return CODEC_ID_PCM_S8;
736 else return CODEC_ID_PCM_U8;
737 else if (bps == 16) return CODEC_ID_PCM_S16BE;
738 else if (bps == 24) return CODEC_ID_PCM_S24BE;
739 else if (bps == 32) return CODEC_ID_PCM_S32BE;
740 } else {
741 if (bps == 8)
742 if (flags & 4) return CODEC_ID_PCM_S8;
743 else return CODEC_ID_PCM_U8;
744 else if (bps == 16) return CODEC_ID_PCM_S16LE;
745 else if (bps == 24) return CODEC_ID_PCM_S24LE;
746 else if (bps == 32) return CODEC_ID_PCM_S32LE;
749 return CODEC_ID_NONE;
752 static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
754 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
755 MOVStreamContext *sc = st->priv_data;
756 int j, entries, pseudo_stream_id;
758 get_byte(pb); /* version */
759 get_be24(pb); /* flags */
761 entries = get_be32(pb);
763 for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
764 //Parsing Sample description table
765 enum CodecID id;
766 int dref_id = 1;
767 MOVAtom a = { 0, 0, 0 };
768 int64_t start_pos = url_ftell(pb);
769 int size = get_be32(pb); /* size */
770 uint32_t format = get_le32(pb); /* data format */
772 if (size >= 16) {
773 get_be32(pb); /* reserved */
774 get_be16(pb); /* reserved */
775 dref_id = get_be16(pb);
778 if (st->codec->codec_tag &&
779 st->codec->codec_tag != format &&
780 (c->fc->video_codec_id ? codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
781 : st->codec->codec_tag != MKTAG('j','p','e','g'))
783 /* Multiple fourcc, we skip JPEG. This is not correct, we should
784 * export it as a separate AVStream but this needs a few changes
785 * in the MOV demuxer, patch welcome. */
786 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
787 url_fskip(pb, size - (url_ftell(pb) - start_pos));
788 continue;
790 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
791 sc->dref_id= dref_id;
793 st->codec->codec_tag = format;
794 id = codec_get_id(codec_movaudio_tags, format);
795 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
796 id = codec_get_id(codec_wav_tags, bswap_32(format)&0xFFFF);
798 if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
799 st->codec->codec_type = CODEC_TYPE_AUDIO;
800 } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
801 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
802 id = codec_get_id(codec_movvideo_tags, format);
803 if (id <= 0)
804 id = codec_get_id(codec_bmp_tags, format);
805 if (id > 0)
806 st->codec->codec_type = CODEC_TYPE_VIDEO;
807 else if(st->codec->codec_type == CODEC_TYPE_DATA){
808 id = codec_get_id(ff_codec_movsubtitle_tags, format);
809 if(id > 0)
810 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
814 dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
815 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
816 (format >> 24) & 0xff, st->codec->codec_type);
818 if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
819 uint8_t codec_name[32];
820 unsigned int color_depth;
821 int color_greyscale;
823 st->codec->codec_id = id;
824 get_be16(pb); /* version */
825 get_be16(pb); /* revision level */
826 get_be32(pb); /* vendor */
827 get_be32(pb); /* temporal quality */
828 get_be32(pb); /* spatial quality */
830 st->codec->width = get_be16(pb); /* width */
831 st->codec->height = get_be16(pb); /* height */
833 get_be32(pb); /* horiz resolution */
834 get_be32(pb); /* vert resolution */
835 get_be32(pb); /* data size, always 0 */
836 get_be16(pb); /* frames per samples */
838 get_buffer(pb, codec_name, 32); /* codec name, pascal string */
839 if (codec_name[0] <= 31) {
840 memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
841 st->codec->codec_name[codec_name[0]] = 0;
844 st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
845 st->codec->color_table_id = get_be16(pb); /* colortable id */
846 dprintf(c->fc, "depth %d, ctab id %d\n",
847 st->codec->bits_per_coded_sample, st->codec->color_table_id);
848 /* figure out the palette situation */
849 color_depth = st->codec->bits_per_coded_sample & 0x1F;
850 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
852 /* if the depth is 2, 4, or 8 bpp, file is palettized */
853 if ((color_depth == 2) || (color_depth == 4) ||
854 (color_depth == 8)) {
855 /* for palette traversal */
856 unsigned int color_start, color_count, color_end;
857 unsigned char r, g, b;
859 st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
860 if (color_greyscale) {
861 int color_index, color_dec;
862 /* compute the greyscale palette */
863 st->codec->bits_per_coded_sample = color_depth;
864 color_count = 1 << color_depth;
865 color_index = 255;
866 color_dec = 256 / (color_count - 1);
867 for (j = 0; j < color_count; j++) {
868 r = g = b = color_index;
869 st->codec->palctrl->palette[j] =
870 (r << 16) | (g << 8) | (b);
871 color_index -= color_dec;
872 if (color_index < 0)
873 color_index = 0;
875 } else if (st->codec->color_table_id) {
876 const uint8_t *color_table;
877 /* if flag bit 3 is set, use the default palette */
878 color_count = 1 << color_depth;
879 if (color_depth == 2)
880 color_table = ff_qt_default_palette_4;
881 else if (color_depth == 4)
882 color_table = ff_qt_default_palette_16;
883 else
884 color_table = ff_qt_default_palette_256;
886 for (j = 0; j < color_count; j++) {
887 r = color_table[j * 3 + 0];
888 g = color_table[j * 3 + 1];
889 b = color_table[j * 3 + 2];
890 st->codec->palctrl->palette[j] =
891 (r << 16) | (g << 8) | (b);
893 } else {
894 /* load the palette from the file */
895 color_start = get_be32(pb);
896 color_count = get_be16(pb);
897 color_end = get_be16(pb);
898 if ((color_start <= 255) &&
899 (color_end <= 255)) {
900 for (j = color_start; j <= color_end; j++) {
901 /* each R, G, or B component is 16 bits;
902 * only use the top 8 bits; skip alpha bytes
903 * up front */
904 get_byte(pb);
905 get_byte(pb);
906 r = get_byte(pb);
907 get_byte(pb);
908 g = get_byte(pb);
909 get_byte(pb);
910 b = get_byte(pb);
911 get_byte(pb);
912 st->codec->palctrl->palette[j] =
913 (r << 16) | (g << 8) | (b);
917 st->codec->palctrl->palette_changed = 1;
919 } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
920 int bits_per_sample, flags;
921 uint16_t version = get_be16(pb);
923 st->codec->codec_id = id;
924 get_be16(pb); /* revision level */
925 get_be32(pb); /* vendor */
927 st->codec->channels = get_be16(pb); /* channel count */
928 dprintf(c->fc, "audio channels %d\n", st->codec->channels);
929 st->codec->bits_per_coded_sample = get_be16(pb); /* sample size */
931 sc->audio_cid = get_be16(pb);
932 get_be16(pb); /* packet size = 0 */
934 st->codec->sample_rate = ((get_be32(pb) >> 16));
936 //Read QT version 1 fields. In version 0 these do not exist.
937 dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
938 if(!c->isom) {
939 if(version==1) {
940 sc->samples_per_frame = get_be32(pb);
941 get_be32(pb); /* bytes per packet */
942 sc->bytes_per_frame = get_be32(pb);
943 get_be32(pb); /* bytes per sample */
944 } else if(version==2) {
945 get_be32(pb); /* sizeof struct only */
946 st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
947 st->codec->channels = get_be32(pb);
948 get_be32(pb); /* always 0x7F000000 */
949 st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
950 flags = get_be32(pb); /* lcpm format specific flag */
951 sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
952 sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
953 if (format == MKTAG('l','p','c','m'))
954 st->codec->codec_id = mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
958 switch (st->codec->codec_id) {
959 case CODEC_ID_PCM_S8:
960 case CODEC_ID_PCM_U8:
961 if (st->codec->bits_per_coded_sample == 16)
962 st->codec->codec_id = CODEC_ID_PCM_S16BE;
963 break;
964 case CODEC_ID_PCM_S16LE:
965 case CODEC_ID_PCM_S16BE:
966 if (st->codec->bits_per_coded_sample == 8)
967 st->codec->codec_id = CODEC_ID_PCM_S8;
968 else if (st->codec->bits_per_coded_sample == 24)
969 st->codec->codec_id =
970 st->codec->codec_id == CODEC_ID_PCM_S16BE ?
971 CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
972 break;
973 /* set values for old format before stsd version 1 appeared */
974 case CODEC_ID_MACE3:
975 sc->samples_per_frame = 6;
976 sc->bytes_per_frame = 2*st->codec->channels;
977 break;
978 case CODEC_ID_MACE6:
979 sc->samples_per_frame = 6;
980 sc->bytes_per_frame = 1*st->codec->channels;
981 break;
982 case CODEC_ID_ADPCM_IMA_QT:
983 sc->samples_per_frame = 64;
984 sc->bytes_per_frame = 34*st->codec->channels;
985 break;
986 case CODEC_ID_GSM:
987 sc->samples_per_frame = 160;
988 sc->bytes_per_frame = 33;
989 break;
990 default:
991 break;
994 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
995 if (bits_per_sample) {
996 st->codec->bits_per_coded_sample = bits_per_sample;
997 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
999 } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){
1000 // ttxt stsd contains display flags, justification, background
1001 // color, fonts, and default styles, so fake an atom to read it
1002 MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
1003 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1004 mov_read_glbl(c, pb, fake_atom);
1005 st->codec->codec_id= id;
1006 st->codec->width = sc->width;
1007 st->codec->height = sc->height;
1008 } else {
1009 /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1010 url_fskip(pb, size - (url_ftell(pb) - start_pos));
1012 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1013 a.size = size - (url_ftell(pb) - start_pos);
1014 if (a.size > 8) {
1015 if (mov_read_default(c, pb, a) < 0)
1016 return -1;
1017 } else if (a.size > 0)
1018 url_fskip(pb, a.size);
1021 if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1022 st->codec->sample_rate= sc->time_scale;
1024 /* special codec parameters handling */
1025 switch (st->codec->codec_id) {
1026 #if CONFIG_DV_DEMUXER
1027 case CODEC_ID_DVAUDIO:
1028 c->dv_fctx = avformat_alloc_context();
1029 c->dv_demux = dv_init_demux(c->dv_fctx);
1030 if (!c->dv_demux) {
1031 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1032 return -1;
1034 sc->dv_audio_container = 1;
1035 st->codec->codec_id = CODEC_ID_PCM_S16LE;
1036 break;
1037 #endif
1038 /* no ifdef since parameters are always those */
1039 case CODEC_ID_QCELP:
1040 // force sample rate for qcelp when not stored in mov
1041 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1042 st->codec->sample_rate = 8000;
1043 st->codec->frame_size= 160;
1044 st->codec->channels= 1; /* really needed */
1045 break;
1046 case CODEC_ID_AMR_NB:
1047 case CODEC_ID_AMR_WB:
1048 st->codec->frame_size= sc->samples_per_frame;
1049 st->codec->channels= 1; /* really needed */
1050 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1051 if (st->codec->codec_id == CODEC_ID_AMR_NB)
1052 st->codec->sample_rate = 8000;
1053 else if (st->codec->codec_id == CODEC_ID_AMR_WB)
1054 st->codec->sample_rate = 16000;
1055 break;
1056 case CODEC_ID_MP2:
1057 case CODEC_ID_MP3:
1058 st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1059 st->need_parsing = AVSTREAM_PARSE_FULL;
1060 break;
1061 case CODEC_ID_GSM:
1062 case CODEC_ID_ADPCM_MS:
1063 case CODEC_ID_ADPCM_IMA_WAV:
1064 st->codec->block_align = sc->bytes_per_frame;
1065 break;
1066 case CODEC_ID_ALAC:
1067 if (st->codec->extradata_size == 36) {
1068 st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1069 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1071 break;
1072 default:
1073 break;
1076 return 0;
1079 static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1081 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1082 MOVStreamContext *sc = st->priv_data;
1083 unsigned int i, entries;
1085 get_byte(pb); /* version */
1086 get_be24(pb); /* flags */
1088 entries = get_be32(pb);
1090 dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1092 if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
1093 return -1;
1094 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1095 if (!sc->stsc_data)
1096 return AVERROR(ENOMEM);
1097 sc->stsc_count = entries;
1099 for(i=0; i<entries; i++) {
1100 sc->stsc_data[i].first = get_be32(pb);
1101 sc->stsc_data[i].count = get_be32(pb);
1102 sc->stsc_data[i].id = get_be32(pb);
1104 return 0;
1107 static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1109 AVStream *st;
1110 MOVStreamContext *sc;
1111 unsigned i, entries;
1113 if (c->fc->nb_streams < 1)
1114 return 0;
1115 st = c->fc->streams[c->fc->nb_streams-1];
1116 sc = st->priv_data;
1118 get_be32(pb); // version + flags
1120 entries = get_be32(pb);
1121 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1122 return -1;
1123 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1124 if (!sc->stps_data)
1125 return AVERROR(ENOMEM);
1126 sc->stps_count = entries;
1128 for (i = 0; i < entries; i++) {
1129 sc->stps_data[i] = get_be32(pb);
1130 //dprintf(c->fc, "stps %d\n", sc->stps_data[i]);
1133 return 0;
1136 static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1138 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1139 MOVStreamContext *sc = st->priv_data;
1140 unsigned int i, entries;
1142 get_byte(pb); /* version */
1143 get_be24(pb); /* flags */
1145 entries = get_be32(pb);
1147 dprintf(c->fc, "keyframe_count = %d\n", entries);
1149 if(entries >= UINT_MAX / sizeof(int))
1150 return -1;
1151 sc->keyframes = av_malloc(entries * sizeof(int));
1152 if (!sc->keyframes)
1153 return AVERROR(ENOMEM);
1154 sc->keyframe_count = entries;
1156 for(i=0; i<entries; i++) {
1157 sc->keyframes[i] = get_be32(pb);
1158 //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1160 return 0;
1163 static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1165 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1166 MOVStreamContext *sc = st->priv_data;
1167 unsigned int i, entries, sample_size, field_size, num_bytes;
1168 GetBitContext gb;
1169 unsigned char* buf;
1171 get_byte(pb); /* version */
1172 get_be24(pb); /* flags */
1174 if (atom.type == MKTAG('s','t','s','z')) {
1175 sample_size = get_be32(pb);
1176 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1177 sc->sample_size = sample_size;
1178 field_size = 32;
1179 } else {
1180 sample_size = 0;
1181 get_be24(pb); /* reserved */
1182 field_size = get_byte(pb);
1184 entries = get_be32(pb);
1186 dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1188 sc->sample_count = entries;
1189 if (sample_size)
1190 return 0;
1192 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1193 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1194 return -1;
1197 if(entries >= UINT_MAX / sizeof(int))
1198 return -1;
1199 sc->sample_sizes = av_malloc(entries * sizeof(int));
1200 if (!sc->sample_sizes)
1201 return AVERROR(ENOMEM);
1203 num_bytes = (entries*field_size+4)>>3;
1205 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1206 if (!buf) {
1207 av_freep(&sc->sample_sizes);
1208 return AVERROR(ENOMEM);
1211 if (get_buffer(pb, buf, num_bytes) < num_bytes) {
1212 av_freep(&sc->sample_sizes);
1213 av_free(buf);
1214 return -1;
1217 init_get_bits(&gb, buf, 8*num_bytes);
1219 for(i=0; i<entries; i++)
1220 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1222 av_free(buf);
1223 return 0;
1226 static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1228 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1229 MOVStreamContext *sc = st->priv_data;
1230 unsigned int i, entries;
1231 int64_t duration=0;
1232 int64_t total_sample_count=0;
1234 get_byte(pb); /* version */
1235 get_be24(pb); /* flags */
1236 entries = get_be32(pb);
1238 dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1240 if(entries >= UINT_MAX / sizeof(*sc->stts_data))
1241 return -1;
1242 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1243 if (!sc->stts_data)
1244 return AVERROR(ENOMEM);
1245 sc->stts_count = entries;
1247 for(i=0; i<entries; i++) {
1248 int sample_duration;
1249 int sample_count;
1251 sample_count=get_be32(pb);
1252 sample_duration = get_be32(pb);
1253 sc->stts_data[i].count= sample_count;
1254 sc->stts_data[i].duration= sample_duration;
1256 dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1258 duration+=(int64_t)sample_duration*sample_count;
1259 total_sample_count+=sample_count;
1262 st->nb_frames= total_sample_count;
1263 if(duration)
1264 st->duration= duration;
1265 return 0;
1268 static int mov_read_cslg(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1270 AVStream *st;
1271 MOVStreamContext *sc;
1273 if (c->fc->nb_streams < 1)
1274 return 0;
1275 st = c->fc->streams[c->fc->nb_streams-1];
1276 sc = st->priv_data;
1278 get_be32(pb); // version + flags
1280 sc->dts_shift = get_be32(pb);
1281 dprintf(c->fc, "dts shift %d\n", sc->dts_shift);
1283 get_be32(pb); // least dts to pts delta
1284 get_be32(pb); // greatest dts to pts delta
1285 get_be32(pb); // pts start
1286 get_be32(pb); // pts end
1288 return 0;
1291 static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1293 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1294 MOVStreamContext *sc = st->priv_data;
1295 unsigned int i, entries;
1297 get_byte(pb); /* version */
1298 get_be24(pb); /* flags */
1299 entries = get_be32(pb);
1301 dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1303 if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
1304 return -1;
1305 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1306 if (!sc->ctts_data)
1307 return AVERROR(ENOMEM);
1308 sc->ctts_count = entries;
1310 for(i=0; i<entries; i++) {
1311 int count =get_be32(pb);
1312 int duration =get_be32(pb);
1314 sc->ctts_data[i].count = count;
1315 sc->ctts_data[i].duration= duration;
1317 return 0;
1320 static void mov_build_index(MOVContext *mov, AVStream *st)
1322 MOVStreamContext *sc = st->priv_data;
1323 int64_t current_offset;
1324 int64_t current_dts = 0;
1325 unsigned int stts_index = 0;
1326 unsigned int stsc_index = 0;
1327 unsigned int stss_index = 0;
1328 unsigned int stps_index = 0;
1329 unsigned int i, j;
1331 /* adjust first dts according to edit list */
1332 if (sc->time_offset) {
1333 int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
1334 current_dts = -rescaled;
1335 if (sc->ctts_data && sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1336 /* more than 16 frames delay, dts are likely wrong
1337 this happens with files created by iMovie */
1338 sc->wrong_dts = 1;
1339 st->codec->has_b_frames = 1;
1343 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1344 if (!(st->codec->codec_type == CODEC_TYPE_AUDIO &&
1345 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1346 unsigned int current_sample = 0;
1347 unsigned int stts_sample = 0;
1348 unsigned int sample_size;
1349 unsigned int distance = 0;
1350 int key_off = sc->keyframes && sc->keyframes[0] == 1;
1352 current_dts -= sc->dts_shift;
1354 st->nb_frames = sc->sample_count;
1355 for (i = 0; i < sc->chunk_count; i++) {
1356 current_offset = sc->chunk_offsets[i];
1357 if (stsc_index + 1 < sc->stsc_count &&
1358 i + 1 == sc->stsc_data[stsc_index + 1].first)
1359 stsc_index++;
1360 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1361 int keyframe = 0;
1362 if (current_sample >= sc->sample_count) {
1363 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1364 return;
1367 if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1368 keyframe = 1;
1369 if (stss_index + 1 < sc->keyframe_count)
1370 stss_index++;
1371 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1372 keyframe = 1;
1373 if (stps_index + 1 < sc->stps_count)
1374 stps_index++;
1376 if (keyframe)
1377 distance = 0;
1378 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1379 if(sc->pseudo_stream_id == -1 ||
1380 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1381 av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
1382 keyframe ? AVINDEX_KEYFRAME : 0);
1383 dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1384 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1385 current_offset, current_dts, sample_size, distance, keyframe);
1388 current_offset += sample_size;
1389 current_dts += sc->stts_data[stts_index].duration;
1390 distance++;
1391 stts_sample++;
1392 current_sample++;
1393 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1394 stts_sample = 0;
1395 stts_index++;
1399 } else {
1400 for (i = 0; i < sc->chunk_count; i++) {
1401 unsigned chunk_samples;
1403 current_offset = sc->chunk_offsets[i];
1404 if (stsc_index + 1 < sc->stsc_count &&
1405 i + 1 == sc->stsc_data[stsc_index + 1].first)
1406 stsc_index++;
1407 chunk_samples = sc->stsc_data[stsc_index].count;
1409 if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1410 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1411 return;
1414 while (chunk_samples > 0) {
1415 unsigned size, samples;
1417 if (sc->samples_per_frame >= 160) { // gsm
1418 samples = sc->samples_per_frame;
1419 size = sc->bytes_per_frame;
1420 } else {
1421 if (sc->samples_per_frame > 1) {
1422 samples = FFMIN((1024 / sc->samples_per_frame)*
1423 sc->samples_per_frame, chunk_samples);
1424 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1425 } else {
1426 samples = FFMIN(1024, chunk_samples);
1427 size = samples * sc->sample_size;
1431 av_add_index_entry(st, current_offset, current_dts, size, 0, AVINDEX_KEYFRAME);
1432 dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1433 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1434 size, samples);
1436 current_offset += size;
1437 current_dts += samples;
1438 chunk_samples -= samples;
1444 static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1446 AVStream *st;
1447 MOVStreamContext *sc;
1448 int ret;
1450 st = av_new_stream(c->fc, c->fc->nb_streams);
1451 if (!st) return AVERROR(ENOMEM);
1452 sc = av_mallocz(sizeof(MOVStreamContext));
1453 if (!sc) return AVERROR(ENOMEM);
1455 st->priv_data = sc;
1456 st->codec->codec_type = CODEC_TYPE_DATA;
1457 sc->ffindex = st->index;
1459 if ((ret = mov_read_default(c, pb, atom)) < 0)
1460 return ret;
1462 /* sanity checks */
1463 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1464 (!sc->sample_size && !sc->sample_count))) {
1465 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1466 st->index);
1467 return 0;
1470 if (!sc->time_scale)
1471 sc->time_scale = c->time_scale;
1473 av_set_pts_info(st, 64, 1, sc->time_scale);
1475 if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
1476 !st->codec->frame_size && sc->stts_count == 1) {
1477 st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
1478 st->codec->sample_rate, sc->time_scale);
1479 dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
1482 mov_build_index(c, st);
1484 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1485 if (url_fopen(&sc->pb, sc->drefs[sc->dref_id-1].path, URL_RDONLY) < 0)
1486 av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening file %s: %s\n",
1487 st->index, sc->drefs[sc->dref_id-1].path, strerror(errno));
1488 } else
1489 sc->pb = c->fc->pb;
1491 switch (st->codec->codec_id) {
1492 #if CONFIG_H261_DECODER
1493 case CODEC_ID_H261:
1494 #endif
1495 #if CONFIG_H263_DECODER
1496 case CODEC_ID_H263:
1497 #endif
1498 #if CONFIG_H264_DECODER
1499 case CODEC_ID_H264:
1500 #endif
1501 #if CONFIG_MPEG4_DECODER
1502 case CODEC_ID_MPEG4:
1503 #endif
1504 st->codec->width = 0; /* let decoder init width/height */
1505 st->codec->height= 0;
1506 break;
1509 /* Do not need those anymore. */
1510 av_freep(&sc->chunk_offsets);
1511 av_freep(&sc->stsc_data);
1512 av_freep(&sc->sample_sizes);
1513 av_freep(&sc->keyframes);
1514 av_freep(&sc->stts_data);
1515 av_freep(&sc->stps_data);
1517 return 0;
1520 static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1522 int ret;
1523 c->itunes_metadata = 1;
1524 ret = mov_read_default(c, pb, atom);
1525 c->itunes_metadata = 0;
1526 return ret;
1529 static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1531 while (atom.size > 8) {
1532 uint32_t tag = get_le32(pb);
1533 atom.size -= 4;
1534 if (tag == MKTAG('h','d','l','r')) {
1535 url_fseek(pb, -8, SEEK_CUR);
1536 atom.size += 8;
1537 return mov_read_default(c, pb, atom);
1540 return 0;
1543 static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1545 int i;
1546 int width;
1547 int height;
1548 int64_t disp_transform[2];
1549 int display_matrix[3][2];
1550 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1551 MOVStreamContext *sc = st->priv_data;
1552 int version = get_byte(pb);
1554 get_be24(pb); /* flags */
1556 MOV_TRACK_ENABLED 0x0001
1557 MOV_TRACK_IN_MOVIE 0x0002
1558 MOV_TRACK_IN_PREVIEW 0x0004
1559 MOV_TRACK_IN_POSTER 0x0008
1562 if (version == 1) {
1563 get_be64(pb);
1564 get_be64(pb);
1565 } else {
1566 get_be32(pb); /* creation time */
1567 get_be32(pb); /* modification time */
1569 st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1570 get_be32(pb); /* reserved */
1572 /* highlevel (considering edits) duration in movie timebase */
1573 (version == 1) ? get_be64(pb) : get_be32(pb);
1574 get_be32(pb); /* reserved */
1575 get_be32(pb); /* reserved */
1577 get_be16(pb); /* layer */
1578 get_be16(pb); /* alternate group */
1579 get_be16(pb); /* volume */
1580 get_be16(pb); /* reserved */
1582 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
1583 // they're kept in fixed point format through all calculations
1584 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
1585 for (i = 0; i < 3; i++) {
1586 display_matrix[i][0] = get_be32(pb); // 16.16 fixed point
1587 display_matrix[i][1] = get_be32(pb); // 16.16 fixed point
1588 get_be32(pb); // 2.30 fixed point (not used)
1591 width = get_be32(pb); // 16.16 fixed point track width
1592 height = get_be32(pb); // 16.16 fixed point track height
1593 sc->width = width >> 16;
1594 sc->height = height >> 16;
1596 //transform the display width/height according to the matrix
1597 // skip this if the display matrix is the default identity matrix
1598 // to keep the same scale, use [width height 1<<16]
1599 if (width && height &&
1600 (display_matrix[0][0] != 65536 || display_matrix[0][1] ||
1601 display_matrix[1][0] || display_matrix[1][1] != 65536 ||
1602 display_matrix[2][0] || display_matrix[2][1])) {
1603 for (i = 0; i < 2; i++)
1604 disp_transform[i] =
1605 (int64_t) width * display_matrix[0][i] +
1606 (int64_t) height * display_matrix[1][i] +
1607 ((int64_t) display_matrix[2][i] << 16);
1609 //sample aspect ratio is new width/height divided by old width/height
1610 st->sample_aspect_ratio = av_d2q(
1611 ((double) disp_transform[0] * height) /
1612 ((double) disp_transform[1] * width), INT_MAX);
1614 return 0;
1617 static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1619 MOVFragment *frag = &c->fragment;
1620 MOVTrackExt *trex = NULL;
1621 int flags, track_id, i;
1623 get_byte(pb); /* version */
1624 flags = get_be24(pb);
1626 track_id = get_be32(pb);
1627 if (!track_id)
1628 return -1;
1629 frag->track_id = track_id;
1630 for (i = 0; i < c->trex_count; i++)
1631 if (c->trex_data[i].track_id == frag->track_id) {
1632 trex = &c->trex_data[i];
1633 break;
1635 if (!trex) {
1636 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
1637 return -1;
1640 if (flags & 0x01) frag->base_data_offset = get_be64(pb);
1641 else frag->base_data_offset = frag->moof_offset;
1642 if (flags & 0x02) frag->stsd_id = get_be32(pb);
1643 else frag->stsd_id = trex->stsd_id;
1645 frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
1646 frag->size = flags & 0x10 ? get_be32(pb) : trex->size;
1647 frag->flags = flags & 0x20 ? get_be32(pb) : trex->flags;
1648 dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
1649 return 0;
1652 static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1654 MOVTrackExt *trex;
1656 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
1657 return -1;
1658 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
1659 if (!trex)
1660 return AVERROR(ENOMEM);
1661 c->trex_data = trex;
1662 trex = &c->trex_data[c->trex_count++];
1663 get_byte(pb); /* version */
1664 get_be24(pb); /* flags */
1665 trex->track_id = get_be32(pb);
1666 trex->stsd_id = get_be32(pb);
1667 trex->duration = get_be32(pb);
1668 trex->size = get_be32(pb);
1669 trex->flags = get_be32(pb);
1670 return 0;
1673 static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1675 MOVFragment *frag = &c->fragment;
1676 AVStream *st = NULL;
1677 MOVStreamContext *sc;
1678 uint64_t offset;
1679 int64_t dts;
1680 int data_offset = 0;
1681 unsigned entries, first_sample_flags = frag->flags;
1682 int flags, distance, i;
1684 for (i = 0; i < c->fc->nb_streams; i++) {
1685 if (c->fc->streams[i]->id == frag->track_id) {
1686 st = c->fc->streams[i];
1687 break;
1690 if (!st) {
1691 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
1692 return -1;
1694 sc = st->priv_data;
1695 if (sc->pseudo_stream_id+1 != frag->stsd_id)
1696 return 0;
1697 get_byte(pb); /* version */
1698 flags = get_be24(pb);
1699 entries = get_be32(pb);
1700 dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
1701 if (flags & 0x001) data_offset = get_be32(pb);
1702 if (flags & 0x004) first_sample_flags = get_be32(pb);
1703 if (flags & 0x800) {
1704 MOVStts *ctts_data;
1705 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
1706 return -1;
1707 ctts_data = av_realloc(sc->ctts_data,
1708 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
1709 if (!ctts_data)
1710 return AVERROR(ENOMEM);
1711 sc->ctts_data = ctts_data;
1713 dts = st->duration;
1714 offset = frag->base_data_offset + data_offset;
1715 distance = 0;
1716 dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
1717 for (i = 0; i < entries; i++) {
1718 unsigned sample_size = frag->size;
1719 int sample_flags = i ? frag->flags : first_sample_flags;
1720 unsigned sample_duration = frag->duration;
1721 int keyframe;
1723 if (flags & 0x100) sample_duration = get_be32(pb);
1724 if (flags & 0x200) sample_size = get_be32(pb);
1725 if (flags & 0x400) sample_flags = get_be32(pb);
1726 if (flags & 0x800) {
1727 sc->ctts_data[sc->ctts_count].count = 1;
1728 sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
1729 sc->ctts_count++;
1731 if ((keyframe = st->codec->codec_type == CODEC_TYPE_AUDIO ||
1732 (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
1733 distance = 0;
1734 av_add_index_entry(st, offset, dts, sample_size, distance,
1735 keyframe ? AVINDEX_KEYFRAME : 0);
1736 dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1737 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
1738 offset, dts, sample_size, distance, keyframe);
1739 distance++;
1740 dts += sample_duration;
1741 offset += sample_size;
1743 frag->moof_offset = offset;
1744 st->duration = dts;
1745 return 0;
1748 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1749 /* like the files created with Adobe Premiere 5.0, for samples see */
1750 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1751 static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1753 int err;
1755 if (atom.size < 8)
1756 return 0; /* continue */
1757 if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1758 url_fskip(pb, atom.size - 4);
1759 return 0;
1761 atom.type = get_le32(pb);
1762 atom.offset += 8;
1763 atom.size -= 8;
1764 if (atom.type != MKTAG('m','d','a','t')) {
1765 url_fskip(pb, atom.size);
1766 return 0;
1768 err = mov_read_mdat(c, pb, atom);
1769 return err;
1772 static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1774 #if CONFIG_ZLIB
1775 ByteIOContext ctx;
1776 uint8_t *cmov_data;
1777 uint8_t *moov_data; /* uncompressed data */
1778 long cmov_len, moov_len;
1779 int ret = -1;
1781 get_be32(pb); /* dcom atom */
1782 if (get_le32(pb) != MKTAG('d','c','o','m'))
1783 return -1;
1784 if (get_le32(pb) != MKTAG('z','l','i','b')) {
1785 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
1786 return -1;
1788 get_be32(pb); /* cmvd atom */
1789 if (get_le32(pb) != MKTAG('c','m','v','d'))
1790 return -1;
1791 moov_len = get_be32(pb); /* uncompressed size */
1792 cmov_len = atom.size - 6 * 4;
1794 cmov_data = av_malloc(cmov_len);
1795 if (!cmov_data)
1796 return AVERROR(ENOMEM);
1797 moov_data = av_malloc(moov_len);
1798 if (!moov_data) {
1799 av_free(cmov_data);
1800 return AVERROR(ENOMEM);
1802 get_buffer(pb, cmov_data, cmov_len);
1803 if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1804 goto free_and_return;
1805 if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
1806 goto free_and_return;
1807 atom.type = MKTAG('m','o','o','v');
1808 atom.offset = 0;
1809 atom.size = moov_len;
1810 #ifdef DEBUG
1811 // { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1812 #endif
1813 ret = mov_read_default(c, &ctx, atom);
1814 free_and_return:
1815 av_free(moov_data);
1816 av_free(cmov_data);
1817 return ret;
1818 #else
1819 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
1820 return -1;
1821 #endif
1824 /* edit list atom */
1825 static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1827 MOVStreamContext *sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
1828 int i, edit_count;
1830 get_byte(pb); /* version */
1831 get_be24(pb); /* flags */
1832 edit_count = get_be32(pb); /* entries */
1834 for(i=0; i<edit_count; i++){
1835 int time;
1836 int duration = get_be32(pb); /* Track duration */
1837 time = get_be32(pb); /* Media time */
1838 get_be32(pb); /* Media rate */
1839 if (i == 0 && time >= -1) {
1840 sc->time_offset = time != -1 ? time : -duration;
1844 if(edit_count > 1)
1845 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
1846 "a/v desync might occur, patch welcome\n");
1848 dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
1849 return 0;
1852 static const MOVParseTableEntry mov_default_parse_table[] = {
1853 { MKTAG('a','v','s','s'), mov_read_extradata },
1854 { MKTAG('c','o','6','4'), mov_read_stco },
1855 { MKTAG('c','s','l','g'), mov_read_cslg },
1856 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
1857 { MKTAG('d','i','n','f'), mov_read_default },
1858 { MKTAG('d','r','e','f'), mov_read_dref },
1859 { MKTAG('e','d','t','s'), mov_read_default },
1860 { MKTAG('e','l','s','t'), mov_read_elst },
1861 { MKTAG('e','n','d','a'), mov_read_enda },
1862 { MKTAG('f','i','e','l'), mov_read_extradata },
1863 { MKTAG('f','t','y','p'), mov_read_ftyp },
1864 { MKTAG('g','l','b','l'), mov_read_glbl },
1865 { MKTAG('h','d','l','r'), mov_read_hdlr },
1866 { MKTAG('i','l','s','t'), mov_read_ilst },
1867 { MKTAG('j','p','2','h'), mov_read_extradata },
1868 { MKTAG('m','d','a','t'), mov_read_mdat },
1869 { MKTAG('m','d','h','d'), mov_read_mdhd },
1870 { MKTAG('m','d','i','a'), mov_read_default },
1871 { MKTAG('m','e','t','a'), mov_read_meta },
1872 { MKTAG('m','i','n','f'), mov_read_default },
1873 { MKTAG('m','o','o','f'), mov_read_moof },
1874 { MKTAG('m','o','o','v'), mov_read_moov },
1875 { MKTAG('m','v','e','x'), mov_read_default },
1876 { MKTAG('m','v','h','d'), mov_read_mvhd },
1877 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
1878 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
1879 { MKTAG('a','v','c','C'), mov_read_glbl },
1880 { MKTAG('p','a','s','p'), mov_read_pasp },
1881 { MKTAG('s','t','b','l'), mov_read_default },
1882 { MKTAG('s','t','c','o'), mov_read_stco },
1883 { MKTAG('s','t','p','s'), mov_read_stps },
1884 { MKTAG('s','t','s','c'), mov_read_stsc },
1885 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
1886 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
1887 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
1888 { MKTAG('s','t','t','s'), mov_read_stts },
1889 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
1890 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
1891 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
1892 { MKTAG('t','r','a','k'), mov_read_trak },
1893 { MKTAG('t','r','a','f'), mov_read_default },
1894 { MKTAG('t','r','e','x'), mov_read_trex },
1895 { MKTAG('t','r','u','n'), mov_read_trun },
1896 { MKTAG('u','d','t','a'), mov_read_default },
1897 { MKTAG('w','a','v','e'), mov_read_wave },
1898 { MKTAG('e','s','d','s'), mov_read_esds },
1899 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
1900 { MKTAG('c','m','o','v'), mov_read_cmov },
1901 { 0, NULL }
1904 static int mov_probe(AVProbeData *p)
1906 unsigned int offset;
1907 uint32_t tag;
1908 int score = 0;
1910 /* check file header */
1911 offset = 0;
1912 for(;;) {
1913 /* ignore invalid offset */
1914 if ((offset + 8) > (unsigned int)p->buf_size)
1915 return score;
1916 tag = AV_RL32(p->buf + offset + 4);
1917 switch(tag) {
1918 /* check for obvious tags */
1919 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
1920 case MKTAG('m','o','o','v'):
1921 case MKTAG('m','d','a','t'):
1922 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
1923 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
1924 case MKTAG('f','t','y','p'):
1925 return AVPROBE_SCORE_MAX;
1926 /* those are more common words, so rate then a bit less */
1927 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
1928 case MKTAG('w','i','d','e'):
1929 case MKTAG('f','r','e','e'):
1930 case MKTAG('j','u','n','k'):
1931 case MKTAG('p','i','c','t'):
1932 return AVPROBE_SCORE_MAX - 5;
1933 case MKTAG(0x82,0x82,0x7f,0x7d):
1934 case MKTAG('s','k','i','p'):
1935 case MKTAG('u','u','i','d'):
1936 case MKTAG('p','r','f','l'):
1937 offset = AV_RB32(p->buf+offset) + offset;
1938 /* if we only find those cause probedata is too small at least rate them */
1939 score = AVPROBE_SCORE_MAX - 50;
1940 break;
1941 default:
1942 /* unrecognized tag */
1943 return score;
1946 return score;
1949 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1951 MOVContext *mov = s->priv_data;
1952 ByteIOContext *pb = s->pb;
1953 int err;
1954 MOVAtom atom = { 0, 0, 0 };
1956 mov->fc = s;
1957 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1958 if(!url_is_streamed(pb))
1959 atom.size = url_fsize(pb);
1960 else
1961 atom.size = INT64_MAX;
1963 /* check MOV header */
1964 if ((err = mov_read_default(mov, pb, atom)) < 0) {
1965 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
1966 return err;
1968 if (!mov->found_moov) {
1969 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
1970 return -1;
1972 dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
1974 return 0;
1977 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1979 MOVContext *mov = s->priv_data;
1980 MOVStreamContext *sc = 0;
1981 AVIndexEntry *sample = 0;
1982 int64_t best_dts = INT64_MAX;
1983 int i, ret;
1984 retry:
1985 for (i = 0; i < s->nb_streams; i++) {
1986 AVStream *st = s->streams[i];
1987 MOVStreamContext *msc = st->priv_data;
1988 if (st->discard != AVDISCARD_ALL && msc->pb && msc->current_sample < st->nb_index_entries) {
1989 AVIndexEntry *current_sample = &st->index_entries[msc->current_sample];
1990 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
1991 dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
1992 if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
1993 (!url_is_streamed(s->pb) &&
1994 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
1995 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
1996 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
1997 sample = current_sample;
1998 best_dts = dts;
1999 sc = msc;
2003 if (!sample) {
2004 mov->found_mdat = 0;
2005 if (!url_is_streamed(s->pb) ||
2006 mov_read_default(mov, s->pb, (MOVAtom){ 0, 0, INT64_MAX }) < 0 ||
2007 url_feof(s->pb))
2008 return AVERROR_EOF;
2009 dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
2010 goto retry;
2012 /* must be done just before reading, to avoid infinite loop on sample */
2013 sc->current_sample++;
2014 if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2015 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2016 sc->ffindex, sample->pos);
2017 return -1;
2019 ret = av_get_packet(sc->pb, pkt, sample->size);
2020 if (ret < 0)
2021 return ret;
2022 #if CONFIG_DV_DEMUXER
2023 if (mov->dv_demux && sc->dv_audio_container) {
2024 dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2025 av_free(pkt->data);
2026 pkt->size = 0;
2027 if (dv_get_packet(mov->dv_demux, pkt) < 0)
2028 return -1;
2030 #endif
2031 pkt->stream_index = sc->ffindex;
2032 pkt->dts = sample->timestamp;
2033 if (sc->ctts_data) {
2034 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2035 /* update ctts context */
2036 sc->ctts_sample++;
2037 if (sc->ctts_index < sc->ctts_count &&
2038 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2039 sc->ctts_index++;
2040 sc->ctts_sample = 0;
2042 if (sc->wrong_dts)
2043 pkt->dts = AV_NOPTS_VALUE;
2044 } else {
2045 AVStream *st = s->streams[sc->ffindex];
2046 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2047 st->index_entries[sc->current_sample].timestamp : st->duration;
2048 pkt->duration = next_dts - pkt->dts;
2049 pkt->pts = pkt->dts;
2051 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
2052 pkt->pos = sample->pos;
2053 dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2054 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2055 return 0;
2058 static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
2060 MOVStreamContext *sc = st->priv_data;
2061 int sample, time_sample;
2062 int i;
2064 sample = av_index_search_timestamp(st, timestamp, flags);
2065 dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2066 if (sample < 0) /* not sure what to do */
2067 return -1;
2068 sc->current_sample = sample;
2069 dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
2070 /* adjust ctts index */
2071 if (sc->ctts_data) {
2072 time_sample = 0;
2073 for (i = 0; i < sc->ctts_count; i++) {
2074 int next = time_sample + sc->ctts_data[i].count;
2075 if (next > sc->current_sample) {
2076 sc->ctts_index = i;
2077 sc->ctts_sample = sc->current_sample - time_sample;
2078 break;
2080 time_sample = next;
2083 return sample;
2086 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2088 AVStream *st;
2089 int64_t seek_timestamp, timestamp;
2090 int sample;
2091 int i;
2093 if (stream_index >= s->nb_streams)
2094 return -1;
2095 if (sample_time < 0)
2096 sample_time = 0;
2098 st = s->streams[stream_index];
2099 sample = mov_seek_stream(st, sample_time, flags);
2100 if (sample < 0)
2101 return -1;
2103 /* adjust seek timestamp to found sample timestamp */
2104 seek_timestamp = st->index_entries[sample].timestamp;
2106 for (i = 0; i < s->nb_streams; i++) {
2107 st = s->streams[i];
2108 if (stream_index == i || st->discard == AVDISCARD_ALL)
2109 continue;
2111 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2112 mov_seek_stream(st, timestamp, flags);
2114 return 0;
2117 static int mov_read_close(AVFormatContext *s)
2119 MOVContext *mov = s->priv_data;
2120 int i, j;
2122 for (i = 0; i < s->nb_streams; i++) {
2123 AVStream *st = s->streams[i];
2124 MOVStreamContext *sc = st->priv_data;
2126 av_freep(&sc->ctts_data);
2127 for (j = 0; j < sc->drefs_count; j++)
2128 av_freep(&sc->drefs[j].path);
2129 av_freep(&sc->drefs);
2130 if (sc->pb && sc->pb != s->pb)
2131 url_fclose(sc->pb);
2133 av_freep(&st->codec->palctrl);
2136 if (mov->dv_demux) {
2137 for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
2138 av_freep(&mov->dv_fctx->streams[i]->codec);
2139 av_freep(&mov->dv_fctx->streams[i]);
2141 av_freep(&mov->dv_fctx);
2142 av_freep(&mov->dv_demux);
2145 av_freep(&mov->trex_data);
2147 return 0;
2150 AVInputFormat mov_demuxer = {
2151 "mov,mp4,m4a,3gp,3g2,mj2",
2152 NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2153 sizeof(MOVContext),
2154 mov_probe,
2155 mov_read_header,
2156 mov_read_packet,
2157 mov_read_close,
2158 mov_read_seek,