Add missing #includes for avutil.h, required for the AV_VERSION* macros.
[ffmpeg-lucabe.git] / libavformat / mov.c
blob6a8c14948fc01bebf2283c5744b4e446efe9845d
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'): key = "author"; break;
110 case MKTAG(0xa9,'w','r','t'): key = "composer"; 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 = "encoder"; 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;
248 MOVStreamContext *sc;
249 int entries, i, j;
251 if (c->fc->nb_streams < 1)
252 return 0;
253 st = c->fc->streams[c->fc->nb_streams-1];
254 sc = st->priv_data;
256 get_be32(pb); // version + flags
257 entries = get_be32(pb);
258 if (entries >= UINT_MAX / sizeof(*sc->drefs))
259 return -1;
260 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
261 if (!sc->drefs)
262 return AVERROR(ENOMEM);
263 sc->drefs_count = entries;
265 for (i = 0; i < sc->drefs_count; i++) {
266 MOVDref *dref = &sc->drefs[i];
267 uint32_t size = get_be32(pb);
268 int64_t next = url_ftell(pb) + size - 4;
270 dref->type = get_le32(pb);
271 get_be32(pb); // version + flags
272 dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
274 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
275 /* macintosh alias record */
276 uint16_t volume_len, len;
277 int16_t type;
279 url_fskip(pb, 10);
281 volume_len = get_byte(pb);
282 volume_len = FFMIN(volume_len, 27);
283 get_buffer(pb, dref->volume, 27);
284 dref->volume[volume_len] = 0;
285 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
287 url_fskip(pb, 12);
289 len = get_byte(pb);
290 len = FFMIN(len, 63);
291 get_buffer(pb, dref->filename, 63);
292 dref->filename[len] = 0;
293 av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
295 url_fskip(pb, 16);
297 /* read next level up_from_alias/down_to_target */
298 dref->nlvl_from = get_be16(pb);
299 dref->nlvl_to = get_be16(pb);
300 av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
301 dref->nlvl_from, dref->nlvl_to);
303 url_fskip(pb, 16);
305 for (type = 0; type != -1 && url_ftell(pb) < next; ) {
306 type = get_be16(pb);
307 len = get_be16(pb);
308 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
309 if (len&1)
310 len += 1;
311 if (type == 2) { // absolute path
312 av_free(dref->path);
313 dref->path = av_mallocz(len+1);
314 if (!dref->path)
315 return AVERROR(ENOMEM);
316 get_buffer(pb, dref->path, len);
317 if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
318 len -= volume_len;
319 memmove(dref->path, dref->path+volume_len, len);
320 dref->path[len] = 0;
322 for (j = 0; j < len; j++)
323 if (dref->path[j] == ':')
324 dref->path[j] = '/';
325 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
326 } else if (type == 0) { // directory name
327 av_free(dref->dir);
328 dref->dir = av_malloc(len+1);
329 if (!dref->dir)
330 return AVERROR(ENOMEM);
331 get_buffer(pb, dref->dir, len);
332 dref->dir[len] = 0;
333 for (j = 0; j < len; j++)
334 if (dref->dir[j] == ':')
335 dref->dir[j] = '/';
336 av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
337 } else
338 url_fskip(pb, len);
341 url_fseek(pb, next, SEEK_SET);
343 return 0;
346 static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
348 AVStream *st;
349 uint32_t type;
350 uint32_t ctype;
352 if (c->fc->nb_streams < 1) // meta before first trak
353 return 0;
355 st = c->fc->streams[c->fc->nb_streams-1];
357 get_byte(pb); /* version */
358 get_be24(pb); /* flags */
360 /* component type */
361 ctype = get_le32(pb);
362 type = get_le32(pb); /* component subtype */
364 dprintf(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
365 dprintf(c->fc, "stype= %.4s\n", (char*)&type);
367 if (type == MKTAG('v','i','d','e'))
368 st->codec->codec_type = CODEC_TYPE_VIDEO;
369 else if(type == MKTAG('s','o','u','n'))
370 st->codec->codec_type = CODEC_TYPE_AUDIO;
371 else if(type == MKTAG('m','1','a',' '))
372 st->codec->codec_id = CODEC_ID_MP2;
373 else if(type == MKTAG('s','u','b','p'))
374 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
376 get_be32(pb); /* component manufacture */
377 get_be32(pb); /* component flags */
378 get_be32(pb); /* component flags mask */
380 if(atom.size <= 24)
381 return 0; /* nothing left to read */
383 url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
384 return 0;
387 int ff_mp4_read_descr_len(ByteIOContext *pb)
389 int len = 0;
390 int count = 4;
391 while (count--) {
392 int c = get_byte(pb);
393 len = (len << 7) | (c & 0x7f);
394 if (!(c & 0x80))
395 break;
397 return len;
400 int mp4_read_descr(AVFormatContext *fc, ByteIOContext *pb, int *tag)
402 int len;
403 *tag = get_byte(pb);
404 len = ff_mp4_read_descr_len(pb);
405 dprintf(fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
406 return len;
409 #define MP4ESDescrTag 0x03
410 #define MP4DecConfigDescrTag 0x04
411 #define MP4DecSpecificDescrTag 0x05
413 static const AVCodecTag mp4_audio_types[] = {
414 { CODEC_ID_MP3ON4, AOT_PS }, /* old mp3on4 draft */
415 { CODEC_ID_MP3ON4, AOT_L1 }, /* layer 1 */
416 { CODEC_ID_MP3ON4, AOT_L2 }, /* layer 2 */
417 { CODEC_ID_MP3ON4, AOT_L3 }, /* layer 3 */
418 { CODEC_ID_MP4ALS, AOT_ALS }, /* MPEG-4 ALS */
419 { CODEC_ID_NONE, AOT_NULL },
422 int ff_mov_read_esds(AVFormatContext *fc, ByteIOContext *pb, MOVAtom atom)
424 AVStream *st;
425 int tag, len;
427 if (fc->nb_streams < 1)
428 return 0;
429 st = fc->streams[fc->nb_streams-1];
431 get_be32(pb); /* version + flags */
432 len = mp4_read_descr(fc, pb, &tag);
433 if (tag == MP4ESDescrTag) {
434 get_be16(pb); /* ID */
435 get_byte(pb); /* priority */
436 } else
437 get_be16(pb); /* ID */
439 len = mp4_read_descr(fc, pb, &tag);
440 if (tag == MP4DecConfigDescrTag) {
441 int object_type_id = get_byte(pb);
442 get_byte(pb); /* stream type */
443 get_be24(pb); /* buffer size db */
444 get_be32(pb); /* max bitrate */
445 get_be32(pb); /* avg bitrate */
447 st->codec->codec_id= ff_codec_get_id(ff_mp4_obj_type, object_type_id);
448 dprintf(fc, "esds object type id 0x%02x\n", object_type_id);
449 len = mp4_read_descr(fc, pb, &tag);
450 if (tag == MP4DecSpecificDescrTag) {
451 dprintf(fc, "Specific MPEG4 header len=%d\n", len);
452 if((uint64_t)len > (1<<30))
453 return -1;
454 st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
455 if (!st->codec->extradata)
456 return AVERROR(ENOMEM);
457 get_buffer(pb, st->codec->extradata, len);
458 st->codec->extradata_size = len;
459 if (st->codec->codec_id == CODEC_ID_AAC) {
460 MPEG4AudioConfig cfg;
461 ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
462 st->codec->extradata_size);
463 st->codec->channels = cfg.channels;
464 if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
465 st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
466 else
467 st->codec->sample_rate = cfg.sample_rate; // ext sample rate ?
468 dprintf(fc, "mp4a config channels %d obj %d ext obj %d "
469 "sample rate %d ext sample rate %d\n", st->codec->channels,
470 cfg.object_type, cfg.ext_object_type,
471 cfg.sample_rate, cfg.ext_sample_rate);
472 if (!(st->codec->codec_id = ff_codec_get_id(mp4_audio_types,
473 cfg.object_type)))
474 st->codec->codec_id = CODEC_ID_AAC;
478 return 0;
481 static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
483 return ff_mov_read_esds(c->fc, pb, atom);
486 static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
488 const int num = get_be32(pb);
489 const int den = get_be32(pb);
490 AVStream *st;
492 if (c->fc->nb_streams < 1)
493 return 0;
494 st = c->fc->streams[c->fc->nb_streams-1];
496 if (den != 0) {
497 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
498 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))
499 av_log(c->fc, AV_LOG_WARNING,
500 "sample aspect ratio already set to %d:%d, overriding by 'pasp' atom\n",
501 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
502 st->sample_aspect_ratio.num = num;
503 st->sample_aspect_ratio.den = den;
505 return 0;
508 /* this atom contains actual media data */
509 static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
511 if(atom.size == 0) /* wrong one (MP4) */
512 return 0;
513 c->found_mdat=1;
514 return 0; /* now go for moov */
517 /* read major brand, minor version and compatible brands and store them as metadata */
518 static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
520 uint32_t minor_ver;
521 int comp_brand_size;
522 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
523 char* comp_brands_str;
524 uint8_t type[5] = {0};
526 get_buffer(pb, type, 4);
527 if (strcmp(type, "qt "))
528 c->isom = 1;
529 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
530 av_metadata_set(&c->fc->metadata, "major_brand", type);
531 minor_ver = get_be32(pb); /* minor version */
532 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
533 av_metadata_set(&c->fc->metadata, "minor_version", minor_ver_str);
535 comp_brand_size = atom.size - 8;
536 if (comp_brand_size < 0)
537 return -1;
538 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
539 if (!comp_brands_str)
540 return AVERROR(ENOMEM);
541 get_buffer(pb, comp_brands_str, comp_brand_size);
542 comp_brands_str[comp_brand_size] = 0;
543 av_metadata_set(&c->fc->metadata, "compatible_brands", comp_brands_str);
544 av_freep(&comp_brands_str);
546 return 0;
549 /* this atom should contain all header atoms */
550 static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
552 if (mov_read_default(c, pb, atom) < 0)
553 return -1;
554 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
555 /* so we don't parse the whole file if over a network */
556 c->found_moov=1;
557 return 0; /* now go for mdat */
560 static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
562 c->fragment.moof_offset = url_ftell(pb) - 8;
563 dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
564 return mov_read_default(c, pb, atom);
567 static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
569 AVStream *st;
570 MOVStreamContext *sc;
571 int version;
572 char language[4] = {0};
573 unsigned lang;
575 if (c->fc->nb_streams < 1)
576 return 0;
577 st = c->fc->streams[c->fc->nb_streams-1];
578 sc = st->priv_data;
580 version = get_byte(pb);
581 if (version > 1)
582 return -1; /* unsupported */
584 get_be24(pb); /* flags */
585 if (version == 1) {
586 get_be64(pb);
587 get_be64(pb);
588 } else {
589 get_be32(pb); /* creation time */
590 get_be32(pb); /* modification time */
593 sc->time_scale = get_be32(pb);
594 st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
596 lang = get_be16(pb); /* language */
597 if (ff_mov_lang_to_iso639(lang, language))
598 av_metadata_set(&st->metadata, "language", language);
599 get_be16(pb); /* quality */
601 return 0;
604 static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
606 int version = get_byte(pb); /* version */
607 get_be24(pb); /* flags */
609 if (version == 1) {
610 get_be64(pb);
611 get_be64(pb);
612 } else {
613 get_be32(pb); /* creation time */
614 get_be32(pb); /* modification time */
616 c->time_scale = get_be32(pb); /* time scale */
618 dprintf(c->fc, "time scale = %i\n", c->time_scale);
620 c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
621 get_be32(pb); /* preferred scale */
623 get_be16(pb); /* preferred volume */
625 url_fskip(pb, 10); /* reserved */
627 url_fskip(pb, 36); /* display matrix */
629 get_be32(pb); /* preview time */
630 get_be32(pb); /* preview duration */
631 get_be32(pb); /* poster time */
632 get_be32(pb); /* selection time */
633 get_be32(pb); /* selection duration */
634 get_be32(pb); /* current time */
635 get_be32(pb); /* next track ID */
637 return 0;
640 static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
642 AVStream *st;
644 if (c->fc->nb_streams < 1)
645 return 0;
646 st = c->fc->streams[c->fc->nb_streams-1];
648 if((uint64_t)atom.size > (1<<30))
649 return -1;
651 // currently SVQ3 decoder expect full STSD header - so let's fake it
652 // this should be fixed and just SMI header should be passed
653 av_free(st->codec->extradata);
654 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
655 if (!st->codec->extradata)
656 return AVERROR(ENOMEM);
657 st->codec->extradata_size = 0x5a + atom.size;
658 memcpy(st->codec->extradata, "SVQ3", 4); // fake
659 get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
660 dprintf(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
661 return 0;
664 static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
666 AVStream *st;
667 int little_endian;
669 if (c->fc->nb_streams < 1)
670 return 0;
671 st = c->fc->streams[c->fc->nb_streams-1];
673 little_endian = get_be16(pb);
674 dprintf(c->fc, "enda %d\n", little_endian);
675 if (little_endian == 1) {
676 switch (st->codec->codec_id) {
677 case CODEC_ID_PCM_S24BE:
678 st->codec->codec_id = CODEC_ID_PCM_S24LE;
679 break;
680 case CODEC_ID_PCM_S32BE:
681 st->codec->codec_id = CODEC_ID_PCM_S32LE;
682 break;
683 case CODEC_ID_PCM_F32BE:
684 st->codec->codec_id = CODEC_ID_PCM_F32LE;
685 break;
686 case CODEC_ID_PCM_F64BE:
687 st->codec->codec_id = CODEC_ID_PCM_F64LE;
688 break;
689 default:
690 break;
693 return 0;
696 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
697 static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
699 AVStream *st;
700 uint64_t size;
701 uint8_t *buf;
703 if (c->fc->nb_streams < 1) // will happen with jp2 files
704 return 0;
705 st= c->fc->streams[c->fc->nb_streams-1];
706 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
707 if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
708 return -1;
709 buf= av_realloc(st->codec->extradata, size);
710 if(!buf)
711 return -1;
712 st->codec->extradata= buf;
713 buf+= st->codec->extradata_size;
714 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
715 AV_WB32( buf , atom.size + 8);
716 AV_WL32( buf + 4, atom.type);
717 get_buffer(pb, buf + 8, atom.size);
718 return 0;
721 static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
723 AVStream *st;
725 if (c->fc->nb_streams < 1)
726 return 0;
727 st = c->fc->streams[c->fc->nb_streams-1];
729 if((uint64_t)atom.size > (1<<30))
730 return -1;
732 if (st->codec->codec_id == CODEC_ID_QDM2) {
733 // pass all frma atom to codec, needed at least for QDM2
734 av_free(st->codec->extradata);
735 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
736 if (!st->codec->extradata)
737 return AVERROR(ENOMEM);
738 st->codec->extradata_size = atom.size;
739 get_buffer(pb, st->codec->extradata, atom.size);
740 } else if (atom.size > 8) { /* to read frma, esds atoms */
741 if (mov_read_default(c, pb, atom) < 0)
742 return -1;
743 } else
744 url_fskip(pb, atom.size);
745 return 0;
749 * This function reads atom content and puts data in extradata without tag
750 * nor size unlike mov_read_extradata.
752 static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
754 AVStream *st;
756 if (c->fc->nb_streams < 1)
757 return 0;
758 st = c->fc->streams[c->fc->nb_streams-1];
760 if((uint64_t)atom.size > (1<<30))
761 return -1;
763 av_free(st->codec->extradata);
764 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
765 if (!st->codec->extradata)
766 return AVERROR(ENOMEM);
767 st->codec->extradata_size = atom.size;
768 get_buffer(pb, st->codec->extradata, atom.size);
769 return 0;
772 static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
774 AVStream *st;
775 MOVStreamContext *sc;
776 unsigned int i, entries;
778 if (c->fc->nb_streams < 1)
779 return 0;
780 st = c->fc->streams[c->fc->nb_streams-1];
781 sc = st->priv_data;
783 get_byte(pb); /* version */
784 get_be24(pb); /* flags */
786 entries = get_be32(pb);
788 if(entries >= UINT_MAX/sizeof(int64_t))
789 return -1;
791 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
792 if (!sc->chunk_offsets)
793 return AVERROR(ENOMEM);
794 sc->chunk_count = entries;
796 if (atom.type == MKTAG('s','t','c','o'))
797 for(i=0; i<entries; i++)
798 sc->chunk_offsets[i] = get_be32(pb);
799 else if (atom.type == MKTAG('c','o','6','4'))
800 for(i=0; i<entries; i++)
801 sc->chunk_offsets[i] = get_be64(pb);
802 else
803 return -1;
805 return 0;
809 * Compute codec id for 'lpcm' tag.
810 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
812 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
814 if (flags & 1) { // floating point
815 if (flags & 2) { // big endian
816 if (bps == 32) return CODEC_ID_PCM_F32BE;
817 else if (bps == 64) return CODEC_ID_PCM_F64BE;
818 } else {
819 if (bps == 32) return CODEC_ID_PCM_F32LE;
820 else if (bps == 64) return CODEC_ID_PCM_F64LE;
822 } else {
823 if (flags & 2) {
824 if (bps == 8)
825 // signed integer
826 if (flags & 4) return CODEC_ID_PCM_S8;
827 else return CODEC_ID_PCM_U8;
828 else if (bps == 16) return CODEC_ID_PCM_S16BE;
829 else if (bps == 24) return CODEC_ID_PCM_S24BE;
830 else if (bps == 32) return CODEC_ID_PCM_S32BE;
831 } else {
832 if (bps == 8)
833 if (flags & 4) return CODEC_ID_PCM_S8;
834 else return CODEC_ID_PCM_U8;
835 else if (bps == 16) return CODEC_ID_PCM_S16LE;
836 else if (bps == 24) return CODEC_ID_PCM_S24LE;
837 else if (bps == 32) return CODEC_ID_PCM_S32LE;
840 return CODEC_ID_NONE;
843 static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
845 AVStream *st;
846 MOVStreamContext *sc;
847 int j, entries, pseudo_stream_id;
849 if (c->fc->nb_streams < 1)
850 return 0;
851 st = c->fc->streams[c->fc->nb_streams-1];
852 sc = st->priv_data;
854 get_byte(pb); /* version */
855 get_be24(pb); /* flags */
857 entries = get_be32(pb);
859 for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
860 //Parsing Sample description table
861 enum CodecID id;
862 int dref_id = 1;
863 MOVAtom a = { 0, 0, 0 };
864 int64_t start_pos = url_ftell(pb);
865 int size = get_be32(pb); /* size */
866 uint32_t format = get_le32(pb); /* data format */
868 if (size >= 16) {
869 get_be32(pb); /* reserved */
870 get_be16(pb); /* reserved */
871 dref_id = get_be16(pb);
874 if (st->codec->codec_tag &&
875 st->codec->codec_tag != format &&
876 (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
877 : st->codec->codec_tag != MKTAG('j','p','e','g'))
879 /* Multiple fourcc, we skip JPEG. This is not correct, we should
880 * export it as a separate AVStream but this needs a few changes
881 * in the MOV demuxer, patch welcome. */
882 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
883 url_fskip(pb, size - (url_ftell(pb) - start_pos));
884 continue;
886 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
887 sc->dref_id= dref_id;
889 st->codec->codec_tag = format;
890 id = ff_codec_get_id(codec_movaudio_tags, format);
891 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
892 id = ff_codec_get_id(ff_codec_wav_tags, bswap_32(format)&0xFFFF);
894 if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
895 st->codec->codec_type = CODEC_TYPE_AUDIO;
896 } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
897 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
898 id = ff_codec_get_id(codec_movvideo_tags, format);
899 if (id <= 0)
900 id = ff_codec_get_id(ff_codec_bmp_tags, format);
901 if (id > 0)
902 st->codec->codec_type = CODEC_TYPE_VIDEO;
903 else if(st->codec->codec_type == CODEC_TYPE_DATA){
904 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
905 if(id > 0)
906 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
910 dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
911 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
912 (format >> 24) & 0xff, st->codec->codec_type);
914 if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
915 uint8_t codec_name[32];
916 unsigned int color_depth;
917 int color_greyscale;
919 st->codec->codec_id = id;
920 get_be16(pb); /* version */
921 get_be16(pb); /* revision level */
922 get_be32(pb); /* vendor */
923 get_be32(pb); /* temporal quality */
924 get_be32(pb); /* spatial quality */
926 st->codec->width = get_be16(pb); /* width */
927 st->codec->height = get_be16(pb); /* height */
929 get_be32(pb); /* horiz resolution */
930 get_be32(pb); /* vert resolution */
931 get_be32(pb); /* data size, always 0 */
932 get_be16(pb); /* frames per samples */
934 get_buffer(pb, codec_name, 32); /* codec name, pascal string */
935 if (codec_name[0] <= 31) {
936 int i;
937 int pos = 0;
938 for (i = 0; i < codec_name[0] && pos < sizeof(st->codec->codec_name) - 3; i++) {
939 uint8_t tmp;
940 PUT_UTF8(codec_name[i+1], tmp, st->codec->codec_name[pos++] = tmp;)
942 st->codec->codec_name[pos] = 0;
945 st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
946 st->codec->color_table_id = get_be16(pb); /* colortable id */
947 dprintf(c->fc, "depth %d, ctab id %d\n",
948 st->codec->bits_per_coded_sample, st->codec->color_table_id);
949 /* figure out the palette situation */
950 color_depth = st->codec->bits_per_coded_sample & 0x1F;
951 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
953 /* if the depth is 2, 4, or 8 bpp, file is palettized */
954 if ((color_depth == 2) || (color_depth == 4) ||
955 (color_depth == 8)) {
956 /* for palette traversal */
957 unsigned int color_start, color_count, color_end;
958 unsigned char r, g, b;
960 st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
961 if (color_greyscale) {
962 int color_index, color_dec;
963 /* compute the greyscale palette */
964 st->codec->bits_per_coded_sample = color_depth;
965 color_count = 1 << color_depth;
966 color_index = 255;
967 color_dec = 256 / (color_count - 1);
968 for (j = 0; j < color_count; j++) {
969 r = g = b = color_index;
970 st->codec->palctrl->palette[j] =
971 (r << 16) | (g << 8) | (b);
972 color_index -= color_dec;
973 if (color_index < 0)
974 color_index = 0;
976 } else if (st->codec->color_table_id) {
977 const uint8_t *color_table;
978 /* if flag bit 3 is set, use the default palette */
979 color_count = 1 << color_depth;
980 if (color_depth == 2)
981 color_table = ff_qt_default_palette_4;
982 else if (color_depth == 4)
983 color_table = ff_qt_default_palette_16;
984 else
985 color_table = ff_qt_default_palette_256;
987 for (j = 0; j < color_count; j++) {
988 r = color_table[j * 3 + 0];
989 g = color_table[j * 3 + 1];
990 b = color_table[j * 3 + 2];
991 st->codec->palctrl->palette[j] =
992 (r << 16) | (g << 8) | (b);
994 } else {
995 /* load the palette from the file */
996 color_start = get_be32(pb);
997 color_count = get_be16(pb);
998 color_end = get_be16(pb);
999 if ((color_start <= 255) &&
1000 (color_end <= 255)) {
1001 for (j = color_start; j <= color_end; j++) {
1002 /* each R, G, or B component is 16 bits;
1003 * only use the top 8 bits; skip alpha bytes
1004 * up front */
1005 get_byte(pb);
1006 get_byte(pb);
1007 r = get_byte(pb);
1008 get_byte(pb);
1009 g = get_byte(pb);
1010 get_byte(pb);
1011 b = get_byte(pb);
1012 get_byte(pb);
1013 st->codec->palctrl->palette[j] =
1014 (r << 16) | (g << 8) | (b);
1018 st->codec->palctrl->palette_changed = 1;
1020 } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
1021 int bits_per_sample, flags;
1022 uint16_t version = get_be16(pb);
1024 st->codec->codec_id = id;
1025 get_be16(pb); /* revision level */
1026 get_be32(pb); /* vendor */
1028 st->codec->channels = get_be16(pb); /* channel count */
1029 dprintf(c->fc, "audio channels %d\n", st->codec->channels);
1030 st->codec->bits_per_coded_sample = get_be16(pb); /* sample size */
1032 sc->audio_cid = get_be16(pb);
1033 get_be16(pb); /* packet size = 0 */
1035 st->codec->sample_rate = ((get_be32(pb) >> 16));
1037 //Read QT version 1 fields. In version 0 these do not exist.
1038 dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
1039 if(!c->isom) {
1040 if(version==1) {
1041 sc->samples_per_frame = get_be32(pb);
1042 get_be32(pb); /* bytes per packet */
1043 sc->bytes_per_frame = get_be32(pb);
1044 get_be32(pb); /* bytes per sample */
1045 } else if(version==2) {
1046 get_be32(pb); /* sizeof struct only */
1047 st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
1048 st->codec->channels = get_be32(pb);
1049 get_be32(pb); /* always 0x7F000000 */
1050 st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
1051 flags = get_be32(pb); /* lcpm format specific flag */
1052 sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
1053 sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
1054 if (format == MKTAG('l','p','c','m'))
1055 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1059 switch (st->codec->codec_id) {
1060 case CODEC_ID_PCM_S8:
1061 case CODEC_ID_PCM_U8:
1062 if (st->codec->bits_per_coded_sample == 16)
1063 st->codec->codec_id = CODEC_ID_PCM_S16BE;
1064 break;
1065 case CODEC_ID_PCM_S16LE:
1066 case CODEC_ID_PCM_S16BE:
1067 if (st->codec->bits_per_coded_sample == 8)
1068 st->codec->codec_id = CODEC_ID_PCM_S8;
1069 else if (st->codec->bits_per_coded_sample == 24)
1070 st->codec->codec_id =
1071 st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1072 CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1073 break;
1074 /* set values for old format before stsd version 1 appeared */
1075 case CODEC_ID_MACE3:
1076 sc->samples_per_frame = 6;
1077 sc->bytes_per_frame = 2*st->codec->channels;
1078 break;
1079 case CODEC_ID_MACE6:
1080 sc->samples_per_frame = 6;
1081 sc->bytes_per_frame = 1*st->codec->channels;
1082 break;
1083 case CODEC_ID_ADPCM_IMA_QT:
1084 sc->samples_per_frame = 64;
1085 sc->bytes_per_frame = 34*st->codec->channels;
1086 break;
1087 case CODEC_ID_GSM:
1088 sc->samples_per_frame = 160;
1089 sc->bytes_per_frame = 33;
1090 break;
1091 default:
1092 break;
1095 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1096 if (bits_per_sample) {
1097 st->codec->bits_per_coded_sample = bits_per_sample;
1098 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1100 } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){
1101 // ttxt stsd contains display flags, justification, background
1102 // color, fonts, and default styles, so fake an atom to read it
1103 MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
1104 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1105 mov_read_glbl(c, pb, fake_atom);
1106 st->codec->codec_id= id;
1107 st->codec->width = sc->width;
1108 st->codec->height = sc->height;
1109 } else {
1110 /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1111 url_fskip(pb, size - (url_ftell(pb) - start_pos));
1113 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1114 a.size = size - (url_ftell(pb) - start_pos);
1115 if (a.size > 8) {
1116 if (mov_read_default(c, pb, a) < 0)
1117 return -1;
1118 } else if (a.size > 0)
1119 url_fskip(pb, a.size);
1122 if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1123 st->codec->sample_rate= sc->time_scale;
1125 /* special codec parameters handling */
1126 switch (st->codec->codec_id) {
1127 #if CONFIG_DV_DEMUXER
1128 case CODEC_ID_DVAUDIO:
1129 c->dv_fctx = avformat_alloc_context();
1130 c->dv_demux = dv_init_demux(c->dv_fctx);
1131 if (!c->dv_demux) {
1132 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1133 return -1;
1135 sc->dv_audio_container = 1;
1136 st->codec->codec_id = CODEC_ID_PCM_S16LE;
1137 break;
1138 #endif
1139 /* no ifdef since parameters are always those */
1140 case CODEC_ID_QCELP:
1141 // force sample rate for qcelp when not stored in mov
1142 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1143 st->codec->sample_rate = 8000;
1144 st->codec->frame_size= 160;
1145 st->codec->channels= 1; /* really needed */
1146 break;
1147 case CODEC_ID_AMR_NB:
1148 case CODEC_ID_AMR_WB:
1149 st->codec->frame_size= sc->samples_per_frame;
1150 st->codec->channels= 1; /* really needed */
1151 /* force sample rate for amr, stsd in 3gp does not store sample rate */
1152 if (st->codec->codec_id == CODEC_ID_AMR_NB)
1153 st->codec->sample_rate = 8000;
1154 else if (st->codec->codec_id == CODEC_ID_AMR_WB)
1155 st->codec->sample_rate = 16000;
1156 break;
1157 case CODEC_ID_MP2:
1158 case CODEC_ID_MP3:
1159 st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1160 st->need_parsing = AVSTREAM_PARSE_FULL;
1161 break;
1162 case CODEC_ID_GSM:
1163 case CODEC_ID_ADPCM_MS:
1164 case CODEC_ID_ADPCM_IMA_WAV:
1165 st->codec->block_align = sc->bytes_per_frame;
1166 break;
1167 case CODEC_ID_ALAC:
1168 if (st->codec->extradata_size == 36) {
1169 st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1170 st->codec->channels = AV_RB8 (st->codec->extradata+21);
1172 break;
1173 default:
1174 break;
1177 return 0;
1180 static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1182 AVStream *st;
1183 MOVStreamContext *sc;
1184 unsigned int i, entries;
1186 if (c->fc->nb_streams < 1)
1187 return 0;
1188 st = c->fc->streams[c->fc->nb_streams-1];
1189 sc = st->priv_data;
1191 get_byte(pb); /* version */
1192 get_be24(pb); /* flags */
1194 entries = get_be32(pb);
1196 dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1198 if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
1199 return -1;
1200 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1201 if (!sc->stsc_data)
1202 return AVERROR(ENOMEM);
1203 sc->stsc_count = entries;
1205 for(i=0; i<entries; i++) {
1206 sc->stsc_data[i].first = get_be32(pb);
1207 sc->stsc_data[i].count = get_be32(pb);
1208 sc->stsc_data[i].id = get_be32(pb);
1210 return 0;
1213 static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1215 AVStream *st;
1216 MOVStreamContext *sc;
1217 unsigned i, entries;
1219 if (c->fc->nb_streams < 1)
1220 return 0;
1221 st = c->fc->streams[c->fc->nb_streams-1];
1222 sc = st->priv_data;
1224 get_be32(pb); // version + flags
1226 entries = get_be32(pb);
1227 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1228 return -1;
1229 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1230 if (!sc->stps_data)
1231 return AVERROR(ENOMEM);
1232 sc->stps_count = entries;
1234 for (i = 0; i < entries; i++) {
1235 sc->stps_data[i] = get_be32(pb);
1236 //dprintf(c->fc, "stps %d\n", sc->stps_data[i]);
1239 return 0;
1242 static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1244 AVStream *st;
1245 MOVStreamContext *sc;
1246 unsigned int i, entries;
1248 if (c->fc->nb_streams < 1)
1249 return 0;
1250 st = c->fc->streams[c->fc->nb_streams-1];
1251 sc = st->priv_data;
1253 get_byte(pb); /* version */
1254 get_be24(pb); /* flags */
1256 entries = get_be32(pb);
1258 dprintf(c->fc, "keyframe_count = %d\n", entries);
1260 if(entries >= UINT_MAX / sizeof(int))
1261 return -1;
1262 sc->keyframes = av_malloc(entries * sizeof(int));
1263 if (!sc->keyframes)
1264 return AVERROR(ENOMEM);
1265 sc->keyframe_count = entries;
1267 for(i=0; i<entries; i++) {
1268 sc->keyframes[i] = get_be32(pb);
1269 //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1271 return 0;
1274 static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1276 AVStream *st;
1277 MOVStreamContext *sc;
1278 unsigned int i, entries, sample_size, field_size, num_bytes;
1279 GetBitContext gb;
1280 unsigned char* buf;
1282 if (c->fc->nb_streams < 1)
1283 return 0;
1284 st = c->fc->streams[c->fc->nb_streams-1];
1285 sc = st->priv_data;
1287 get_byte(pb); /* version */
1288 get_be24(pb); /* flags */
1290 if (atom.type == MKTAG('s','t','s','z')) {
1291 sample_size = get_be32(pb);
1292 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1293 sc->sample_size = sample_size;
1294 field_size = 32;
1295 } else {
1296 sample_size = 0;
1297 get_be24(pb); /* reserved */
1298 field_size = get_byte(pb);
1300 entries = get_be32(pb);
1302 dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1304 sc->sample_count = entries;
1305 if (sample_size)
1306 return 0;
1308 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1309 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1310 return -1;
1313 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1314 return -1;
1315 sc->sample_sizes = av_malloc(entries * sizeof(int));
1316 if (!sc->sample_sizes)
1317 return AVERROR(ENOMEM);
1319 num_bytes = (entries*field_size+4)>>3;
1321 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1322 if (!buf) {
1323 av_freep(&sc->sample_sizes);
1324 return AVERROR(ENOMEM);
1327 if (get_buffer(pb, buf, num_bytes) < num_bytes) {
1328 av_freep(&sc->sample_sizes);
1329 av_free(buf);
1330 return -1;
1333 init_get_bits(&gb, buf, 8*num_bytes);
1335 for(i=0; i<entries; i++)
1336 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1338 av_free(buf);
1339 return 0;
1342 static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1344 AVStream *st;
1345 MOVStreamContext *sc;
1346 unsigned int i, entries;
1347 int64_t duration=0;
1348 int64_t total_sample_count=0;
1350 if (c->fc->nb_streams < 1)
1351 return 0;
1352 st = c->fc->streams[c->fc->nb_streams-1];
1353 sc = st->priv_data;
1355 get_byte(pb); /* version */
1356 get_be24(pb); /* flags */
1357 entries = get_be32(pb);
1359 dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1361 if(entries >= UINT_MAX / sizeof(*sc->stts_data))
1362 return -1;
1363 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1364 if (!sc->stts_data)
1365 return AVERROR(ENOMEM);
1366 sc->stts_count = entries;
1368 for(i=0; i<entries; i++) {
1369 int sample_duration;
1370 int sample_count;
1372 sample_count=get_be32(pb);
1373 sample_duration = get_be32(pb);
1374 sc->stts_data[i].count= sample_count;
1375 sc->stts_data[i].duration= sample_duration;
1377 dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1379 duration+=(int64_t)sample_duration*sample_count;
1380 total_sample_count+=sample_count;
1383 st->nb_frames= total_sample_count;
1384 if(duration)
1385 st->duration= duration;
1386 return 0;
1389 static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1391 AVStream *st;
1392 MOVStreamContext *sc;
1393 unsigned int i, entries;
1395 if (c->fc->nb_streams < 1)
1396 return 0;
1397 st = c->fc->streams[c->fc->nb_streams-1];
1398 sc = st->priv_data;
1400 get_byte(pb); /* version */
1401 get_be24(pb); /* flags */
1402 entries = get_be32(pb);
1404 dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1406 if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
1407 return -1;
1408 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1409 if (!sc->ctts_data)
1410 return AVERROR(ENOMEM);
1411 sc->ctts_count = entries;
1413 for(i=0; i<entries; i++) {
1414 int count =get_be32(pb);
1415 int duration =get_be32(pb);
1417 sc->ctts_data[i].count = count;
1418 sc->ctts_data[i].duration= duration;
1419 if (duration < 0)
1420 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1423 dprintf(c->fc, "dts shift %d\n", sc->dts_shift);
1425 return 0;
1428 static void mov_build_index(MOVContext *mov, AVStream *st)
1430 MOVStreamContext *sc = st->priv_data;
1431 int64_t current_offset;
1432 int64_t current_dts = 0;
1433 unsigned int stts_index = 0;
1434 unsigned int stsc_index = 0;
1435 unsigned int stss_index = 0;
1436 unsigned int stps_index = 0;
1437 unsigned int i, j;
1438 uint64_t stream_size = 0;
1440 /* adjust first dts according to edit list */
1441 if (sc->time_offset) {
1442 int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
1443 current_dts = -rescaled;
1444 if (sc->ctts_data && sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1445 /* more than 16 frames delay, dts are likely wrong
1446 this happens with files created by iMovie */
1447 sc->wrong_dts = 1;
1448 st->codec->has_b_frames = 1;
1452 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1453 if (!(st->codec->codec_type == CODEC_TYPE_AUDIO &&
1454 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1455 unsigned int current_sample = 0;
1456 unsigned int stts_sample = 0;
1457 unsigned int sample_size;
1458 unsigned int distance = 0;
1459 int key_off = sc->keyframes && sc->keyframes[0] == 1;
1461 current_dts -= sc->dts_shift;
1463 for (i = 0; i < sc->chunk_count; i++) {
1464 current_offset = sc->chunk_offsets[i];
1465 if (stsc_index + 1 < sc->stsc_count &&
1466 i + 1 == sc->stsc_data[stsc_index + 1].first)
1467 stsc_index++;
1468 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1469 int keyframe = 0;
1470 if (current_sample >= sc->sample_count) {
1471 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1472 return;
1475 if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1476 keyframe = 1;
1477 if (stss_index + 1 < sc->keyframe_count)
1478 stss_index++;
1479 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1480 keyframe = 1;
1481 if (stps_index + 1 < sc->stps_count)
1482 stps_index++;
1484 if (keyframe)
1485 distance = 0;
1486 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1487 if(sc->pseudo_stream_id == -1 ||
1488 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1489 av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
1490 keyframe ? AVINDEX_KEYFRAME : 0);
1491 dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1492 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1493 current_offset, current_dts, sample_size, distance, keyframe);
1496 current_offset += sample_size;
1497 stream_size += sample_size;
1498 current_dts += sc->stts_data[stts_index].duration;
1499 distance++;
1500 stts_sample++;
1501 current_sample++;
1502 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1503 stts_sample = 0;
1504 stts_index++;
1508 if (st->duration > 0)
1509 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1510 } else {
1511 for (i = 0; i < sc->chunk_count; i++) {
1512 unsigned chunk_samples;
1514 current_offset = sc->chunk_offsets[i];
1515 if (stsc_index + 1 < sc->stsc_count &&
1516 i + 1 == sc->stsc_data[stsc_index + 1].first)
1517 stsc_index++;
1518 chunk_samples = sc->stsc_data[stsc_index].count;
1520 if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1521 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1522 return;
1525 while (chunk_samples > 0) {
1526 unsigned size, samples;
1528 if (sc->samples_per_frame >= 160) { // gsm
1529 samples = sc->samples_per_frame;
1530 size = sc->bytes_per_frame;
1531 } else {
1532 if (sc->samples_per_frame > 1) {
1533 samples = FFMIN((1024 / sc->samples_per_frame)*
1534 sc->samples_per_frame, chunk_samples);
1535 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1536 } else {
1537 samples = FFMIN(1024, chunk_samples);
1538 size = samples * sc->sample_size;
1542 av_add_index_entry(st, current_offset, current_dts, size, 0, AVINDEX_KEYFRAME);
1543 dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1544 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1545 size, samples);
1547 current_offset += size;
1548 current_dts += samples;
1549 chunk_samples -= samples;
1555 static int mov_open_dref(ByteIOContext **pb, char *src, MOVDref *ref)
1557 /* try absolute path */
1558 if (!url_fopen(pb, ref->path, URL_RDONLY))
1559 return 0;
1561 /* try relative path */
1562 if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1563 char filename[1024];
1564 char *src_path;
1565 int i, l;
1567 /* find a source dir */
1568 src_path = strrchr(src, '/');
1569 if (src_path)
1570 src_path++;
1571 else
1572 src_path = src;
1574 /* find a next level down to target */
1575 for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1576 if (ref->path[l] == '/') {
1577 if (i == ref->nlvl_to - 1)
1578 break;
1579 else
1580 i++;
1583 /* compose filename if next level down to target was found */
1584 if (i == ref->nlvl_to - 1) {
1585 memcpy(filename, src, src_path - src);
1586 filename[src_path - src] = 0;
1588 for (i = 1; i < ref->nlvl_from; i++)
1589 av_strlcat(filename, "../", 1024);
1591 av_strlcat(filename, ref->path + l + 1, 1024);
1593 if (!url_fopen(pb, filename, URL_RDONLY))
1594 return 0;
1598 return AVERROR(ENOENT);
1601 static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1603 AVStream *st;
1604 MOVStreamContext *sc;
1605 int ret;
1607 st = av_new_stream(c->fc, c->fc->nb_streams);
1608 if (!st) return AVERROR(ENOMEM);
1609 sc = av_mallocz(sizeof(MOVStreamContext));
1610 if (!sc) return AVERROR(ENOMEM);
1612 st->priv_data = sc;
1613 st->codec->codec_type = CODEC_TYPE_DATA;
1614 sc->ffindex = st->index;
1616 if ((ret = mov_read_default(c, pb, atom)) < 0)
1617 return ret;
1619 /* sanity checks */
1620 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1621 (!sc->sample_size && !sc->sample_count))) {
1622 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1623 st->index);
1624 return 0;
1627 if (!sc->time_scale) {
1628 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
1629 sc->time_scale = c->time_scale;
1630 if (!sc->time_scale)
1631 sc->time_scale = 1;
1634 av_set_pts_info(st, 64, 1, sc->time_scale);
1636 if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
1637 !st->codec->frame_size && sc->stts_count == 1) {
1638 st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
1639 st->codec->sample_rate, sc->time_scale);
1640 dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
1643 mov_build_index(c, st);
1645 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1646 MOVDref *dref = &sc->drefs[sc->dref_id - 1];
1647 if (mov_open_dref(&sc->pb, c->fc->filename, dref) < 0)
1648 av_log(c->fc, AV_LOG_ERROR,
1649 "stream %d, error opening alias: path='%s', dir='%s', "
1650 "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
1651 st->index, dref->path, dref->dir, dref->filename,
1652 dref->volume, dref->nlvl_from, dref->nlvl_to);
1653 } else
1654 sc->pb = c->fc->pb;
1656 switch (st->codec->codec_id) {
1657 #if CONFIG_H261_DECODER
1658 case CODEC_ID_H261:
1659 #endif
1660 #if CONFIG_H263_DECODER
1661 case CODEC_ID_H263:
1662 #endif
1663 #if CONFIG_H264_DECODER
1664 case CODEC_ID_H264:
1665 #endif
1666 #if CONFIG_MPEG4_DECODER
1667 case CODEC_ID_MPEG4:
1668 #endif
1669 st->codec->width = 0; /* let decoder init width/height */
1670 st->codec->height= 0;
1671 break;
1674 /* Do not need those anymore. */
1675 av_freep(&sc->chunk_offsets);
1676 av_freep(&sc->stsc_data);
1677 av_freep(&sc->sample_sizes);
1678 av_freep(&sc->keyframes);
1679 av_freep(&sc->stts_data);
1680 av_freep(&sc->stps_data);
1682 return 0;
1685 static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1687 int ret;
1688 c->itunes_metadata = 1;
1689 ret = mov_read_default(c, pb, atom);
1690 c->itunes_metadata = 0;
1691 return ret;
1694 static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1696 while (atom.size > 8) {
1697 uint32_t tag = get_le32(pb);
1698 atom.size -= 4;
1699 if (tag == MKTAG('h','d','l','r')) {
1700 url_fseek(pb, -8, SEEK_CUR);
1701 atom.size += 8;
1702 return mov_read_default(c, pb, atom);
1705 return 0;
1708 static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1710 int i;
1711 int width;
1712 int height;
1713 int64_t disp_transform[2];
1714 int display_matrix[3][2];
1715 AVStream *st;
1716 MOVStreamContext *sc;
1717 int version;
1719 if (c->fc->nb_streams < 1)
1720 return 0;
1721 st = c->fc->streams[c->fc->nb_streams-1];
1722 sc = st->priv_data;
1724 version = get_byte(pb);
1725 get_be24(pb); /* flags */
1727 MOV_TRACK_ENABLED 0x0001
1728 MOV_TRACK_IN_MOVIE 0x0002
1729 MOV_TRACK_IN_PREVIEW 0x0004
1730 MOV_TRACK_IN_POSTER 0x0008
1733 if (version == 1) {
1734 get_be64(pb);
1735 get_be64(pb);
1736 } else {
1737 get_be32(pb); /* creation time */
1738 get_be32(pb); /* modification time */
1740 st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1741 get_be32(pb); /* reserved */
1743 /* highlevel (considering edits) duration in movie timebase */
1744 (version == 1) ? get_be64(pb) : get_be32(pb);
1745 get_be32(pb); /* reserved */
1746 get_be32(pb); /* reserved */
1748 get_be16(pb); /* layer */
1749 get_be16(pb); /* alternate group */
1750 get_be16(pb); /* volume */
1751 get_be16(pb); /* reserved */
1753 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
1754 // they're kept in fixed point format through all calculations
1755 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
1756 for (i = 0; i < 3; i++) {
1757 display_matrix[i][0] = get_be32(pb); // 16.16 fixed point
1758 display_matrix[i][1] = get_be32(pb); // 16.16 fixed point
1759 get_be32(pb); // 2.30 fixed point (not used)
1762 width = get_be32(pb); // 16.16 fixed point track width
1763 height = get_be32(pb); // 16.16 fixed point track height
1764 sc->width = width >> 16;
1765 sc->height = height >> 16;
1767 // transform the display width/height according to the matrix
1768 // skip this if the display matrix is the default identity matrix
1769 // or if it is rotating the picture, ex iPhone 3GS
1770 // to keep the same scale, use [width height 1<<16]
1771 if (width && height &&
1772 ((display_matrix[0][0] != 65536 ||
1773 display_matrix[1][1] != 65536) &&
1774 !display_matrix[0][1] &&
1775 !display_matrix[1][0] &&
1776 !display_matrix[2][0] && !display_matrix[2][1])) {
1777 for (i = 0; i < 2; i++)
1778 disp_transform[i] =
1779 (int64_t) width * display_matrix[0][i] +
1780 (int64_t) height * display_matrix[1][i] +
1781 ((int64_t) display_matrix[2][i] << 16);
1783 //sample aspect ratio is new width/height divided by old width/height
1784 st->sample_aspect_ratio = av_d2q(
1785 ((double) disp_transform[0] * height) /
1786 ((double) disp_transform[1] * width), INT_MAX);
1788 return 0;
1791 static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1793 MOVFragment *frag = &c->fragment;
1794 MOVTrackExt *trex = NULL;
1795 int flags, track_id, i;
1797 get_byte(pb); /* version */
1798 flags = get_be24(pb);
1800 track_id = get_be32(pb);
1801 if (!track_id)
1802 return -1;
1803 frag->track_id = track_id;
1804 for (i = 0; i < c->trex_count; i++)
1805 if (c->trex_data[i].track_id == frag->track_id) {
1806 trex = &c->trex_data[i];
1807 break;
1809 if (!trex) {
1810 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
1811 return -1;
1814 if (flags & 0x01) frag->base_data_offset = get_be64(pb);
1815 else frag->base_data_offset = frag->moof_offset;
1816 if (flags & 0x02) frag->stsd_id = get_be32(pb);
1817 else frag->stsd_id = trex->stsd_id;
1819 frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
1820 frag->size = flags & 0x10 ? get_be32(pb) : trex->size;
1821 frag->flags = flags & 0x20 ? get_be32(pb) : trex->flags;
1822 dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
1823 return 0;
1826 static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1828 MOVTrackExt *trex;
1830 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
1831 return -1;
1832 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
1833 if (!trex)
1834 return AVERROR(ENOMEM);
1835 c->trex_data = trex;
1836 trex = &c->trex_data[c->trex_count++];
1837 get_byte(pb); /* version */
1838 get_be24(pb); /* flags */
1839 trex->track_id = get_be32(pb);
1840 trex->stsd_id = get_be32(pb);
1841 trex->duration = get_be32(pb);
1842 trex->size = get_be32(pb);
1843 trex->flags = get_be32(pb);
1844 return 0;
1847 static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1849 MOVFragment *frag = &c->fragment;
1850 AVStream *st = NULL;
1851 MOVStreamContext *sc;
1852 uint64_t offset;
1853 int64_t dts;
1854 int data_offset = 0;
1855 unsigned entries, first_sample_flags = frag->flags;
1856 int flags, distance, i;
1858 for (i = 0; i < c->fc->nb_streams; i++) {
1859 if (c->fc->streams[i]->id == frag->track_id) {
1860 st = c->fc->streams[i];
1861 break;
1864 if (!st) {
1865 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
1866 return -1;
1868 sc = st->priv_data;
1869 if (sc->pseudo_stream_id+1 != frag->stsd_id)
1870 return 0;
1871 get_byte(pb); /* version */
1872 flags = get_be24(pb);
1873 entries = get_be32(pb);
1874 dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
1875 if (flags & 0x001) data_offset = get_be32(pb);
1876 if (flags & 0x004) first_sample_flags = get_be32(pb);
1877 if (flags & 0x800) {
1878 MOVStts *ctts_data;
1879 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
1880 return -1;
1881 ctts_data = av_realloc(sc->ctts_data,
1882 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
1883 if (!ctts_data)
1884 return AVERROR(ENOMEM);
1885 sc->ctts_data = ctts_data;
1887 dts = st->duration;
1888 offset = frag->base_data_offset + data_offset;
1889 distance = 0;
1890 dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
1891 for (i = 0; i < entries; i++) {
1892 unsigned sample_size = frag->size;
1893 int sample_flags = i ? frag->flags : first_sample_flags;
1894 unsigned sample_duration = frag->duration;
1895 int keyframe;
1897 if (flags & 0x100) sample_duration = get_be32(pb);
1898 if (flags & 0x200) sample_size = get_be32(pb);
1899 if (flags & 0x400) sample_flags = get_be32(pb);
1900 if (flags & 0x800) {
1901 sc->ctts_data[sc->ctts_count].count = 1;
1902 sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
1903 sc->ctts_count++;
1905 if ((keyframe = st->codec->codec_type == CODEC_TYPE_AUDIO ||
1906 (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
1907 distance = 0;
1908 av_add_index_entry(st, offset, dts, sample_size, distance,
1909 keyframe ? AVINDEX_KEYFRAME : 0);
1910 dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1911 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
1912 offset, dts, sample_size, distance, keyframe);
1913 distance++;
1914 dts += sample_duration;
1915 offset += sample_size;
1917 frag->moof_offset = offset;
1918 st->duration = dts;
1919 return 0;
1922 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1923 /* like the files created with Adobe Premiere 5.0, for samples see */
1924 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1925 static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1927 int err;
1929 if (atom.size < 8)
1930 return 0; /* continue */
1931 if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1932 url_fskip(pb, atom.size - 4);
1933 return 0;
1935 atom.type = get_le32(pb);
1936 atom.offset += 8;
1937 atom.size -= 8;
1938 if (atom.type != MKTAG('m','d','a','t')) {
1939 url_fskip(pb, atom.size);
1940 return 0;
1942 err = mov_read_mdat(c, pb, atom);
1943 return err;
1946 static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1948 #if CONFIG_ZLIB
1949 ByteIOContext ctx;
1950 uint8_t *cmov_data;
1951 uint8_t *moov_data; /* uncompressed data */
1952 long cmov_len, moov_len;
1953 int ret = -1;
1955 get_be32(pb); /* dcom atom */
1956 if (get_le32(pb) != MKTAG('d','c','o','m'))
1957 return -1;
1958 if (get_le32(pb) != MKTAG('z','l','i','b')) {
1959 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
1960 return -1;
1962 get_be32(pb); /* cmvd atom */
1963 if (get_le32(pb) != MKTAG('c','m','v','d'))
1964 return -1;
1965 moov_len = get_be32(pb); /* uncompressed size */
1966 cmov_len = atom.size - 6 * 4;
1968 cmov_data = av_malloc(cmov_len);
1969 if (!cmov_data)
1970 return AVERROR(ENOMEM);
1971 moov_data = av_malloc(moov_len);
1972 if (!moov_data) {
1973 av_free(cmov_data);
1974 return AVERROR(ENOMEM);
1976 get_buffer(pb, cmov_data, cmov_len);
1977 if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1978 goto free_and_return;
1979 if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
1980 goto free_and_return;
1981 atom.type = MKTAG('m','o','o','v');
1982 atom.offset = 0;
1983 atom.size = moov_len;
1984 #ifdef DEBUG
1985 // { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1986 #endif
1987 ret = mov_read_default(c, &ctx, atom);
1988 free_and_return:
1989 av_free(moov_data);
1990 av_free(cmov_data);
1991 return ret;
1992 #else
1993 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
1994 return -1;
1995 #endif
1998 /* edit list atom */
1999 static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
2001 MOVStreamContext *sc;
2002 int i, edit_count;
2004 if (c->fc->nb_streams < 1)
2005 return 0;
2006 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2008 get_byte(pb); /* version */
2009 get_be24(pb); /* flags */
2010 edit_count = get_be32(pb); /* entries */
2012 if((uint64_t)edit_count*12+8 > atom.size)
2013 return -1;
2015 for(i=0; i<edit_count; i++){
2016 int time;
2017 int duration = get_be32(pb); /* Track duration */
2018 time = get_be32(pb); /* Media time */
2019 get_be32(pb); /* Media rate */
2020 if (i == 0 && time >= -1) {
2021 sc->time_offset = time != -1 ? time : -duration;
2025 if(edit_count > 1)
2026 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2027 "a/v desync might occur, patch welcome\n");
2029 dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2030 return 0;
2033 static const MOVParseTableEntry mov_default_parse_table[] = {
2034 { MKTAG('a','v','s','s'), mov_read_extradata },
2035 { MKTAG('c','o','6','4'), mov_read_stco },
2036 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2037 { MKTAG('d','i','n','f'), mov_read_default },
2038 { MKTAG('d','r','e','f'), mov_read_dref },
2039 { MKTAG('e','d','t','s'), mov_read_default },
2040 { MKTAG('e','l','s','t'), mov_read_elst },
2041 { MKTAG('e','n','d','a'), mov_read_enda },
2042 { MKTAG('f','i','e','l'), mov_read_extradata },
2043 { MKTAG('f','t','y','p'), mov_read_ftyp },
2044 { MKTAG('g','l','b','l'), mov_read_glbl },
2045 { MKTAG('h','d','l','r'), mov_read_hdlr },
2046 { MKTAG('i','l','s','t'), mov_read_ilst },
2047 { MKTAG('j','p','2','h'), mov_read_extradata },
2048 { MKTAG('m','d','a','t'), mov_read_mdat },
2049 { MKTAG('m','d','h','d'), mov_read_mdhd },
2050 { MKTAG('m','d','i','a'), mov_read_default },
2051 { MKTAG('m','e','t','a'), mov_read_meta },
2052 { MKTAG('m','i','n','f'), mov_read_default },
2053 { MKTAG('m','o','o','f'), mov_read_moof },
2054 { MKTAG('m','o','o','v'), mov_read_moov },
2055 { MKTAG('m','v','e','x'), mov_read_default },
2056 { MKTAG('m','v','h','d'), mov_read_mvhd },
2057 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2058 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2059 { MKTAG('a','v','c','C'), mov_read_glbl },
2060 { MKTAG('p','a','s','p'), mov_read_pasp },
2061 { MKTAG('s','t','b','l'), mov_read_default },
2062 { MKTAG('s','t','c','o'), mov_read_stco },
2063 { MKTAG('s','t','p','s'), mov_read_stps },
2064 { MKTAG('s','t','s','c'), mov_read_stsc },
2065 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2066 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2067 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2068 { MKTAG('s','t','t','s'), mov_read_stts },
2069 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2070 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2071 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2072 { MKTAG('t','r','a','k'), mov_read_trak },
2073 { MKTAG('t','r','a','f'), mov_read_default },
2074 { MKTAG('t','r','e','x'), mov_read_trex },
2075 { MKTAG('t','r','u','n'), mov_read_trun },
2076 { MKTAG('u','d','t','a'), mov_read_default },
2077 { MKTAG('w','a','v','e'), mov_read_wave },
2078 { MKTAG('e','s','d','s'), mov_read_esds },
2079 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2080 { MKTAG('c','m','o','v'), mov_read_cmov },
2081 { 0, NULL }
2084 static int mov_probe(AVProbeData *p)
2086 unsigned int offset;
2087 uint32_t tag;
2088 int score = 0;
2090 /* check file header */
2091 offset = 0;
2092 for(;;) {
2093 /* ignore invalid offset */
2094 if ((offset + 8) > (unsigned int)p->buf_size)
2095 return score;
2096 tag = AV_RL32(p->buf + offset + 4);
2097 switch(tag) {
2098 /* check for obvious tags */
2099 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2100 case MKTAG('m','o','o','v'):
2101 case MKTAG('m','d','a','t'):
2102 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2103 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2104 case MKTAG('f','t','y','p'):
2105 return AVPROBE_SCORE_MAX;
2106 /* those are more common words, so rate then a bit less */
2107 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2108 case MKTAG('w','i','d','e'):
2109 case MKTAG('f','r','e','e'):
2110 case MKTAG('j','u','n','k'):
2111 case MKTAG('p','i','c','t'):
2112 return AVPROBE_SCORE_MAX - 5;
2113 case MKTAG(0x82,0x82,0x7f,0x7d):
2114 case MKTAG('s','k','i','p'):
2115 case MKTAG('u','u','i','d'):
2116 case MKTAG('p','r','f','l'):
2117 offset = AV_RB32(p->buf+offset) + offset;
2118 /* if we only find those cause probedata is too small at least rate them */
2119 score = AVPROBE_SCORE_MAX - 50;
2120 break;
2121 default:
2122 /* unrecognized tag */
2123 return score;
2126 return score;
2129 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
2131 MOVContext *mov = s->priv_data;
2132 ByteIOContext *pb = s->pb;
2133 int err;
2134 MOVAtom atom = { 0, 0, 0 };
2136 mov->fc = s;
2137 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2138 if(!url_is_streamed(pb))
2139 atom.size = url_fsize(pb);
2140 else
2141 atom.size = INT64_MAX;
2143 /* check MOV header */
2144 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2145 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2146 return err;
2148 if (!mov->found_moov) {
2149 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2150 return -1;
2152 dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
2154 return 0;
2157 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2159 AVIndexEntry *sample = NULL;
2160 int64_t best_dts = INT64_MAX;
2161 int i;
2162 for (i = 0; i < s->nb_streams; i++) {
2163 AVStream *avst = s->streams[i];
2164 MOVStreamContext *msc = avst->priv_data;
2165 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2166 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2167 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2168 dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2169 if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
2170 (!url_is_streamed(s->pb) &&
2171 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2172 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2173 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2174 sample = current_sample;
2175 best_dts = dts;
2176 *st = avst;
2180 return sample;
2183 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2185 MOVContext *mov = s->priv_data;
2186 MOVStreamContext *sc;
2187 AVIndexEntry *sample;
2188 AVStream *st = NULL;
2189 int ret;
2190 retry:
2191 sample = mov_find_next_sample(s, &st);
2192 if (!sample) {
2193 mov->found_mdat = 0;
2194 if (!url_is_streamed(s->pb) ||
2195 mov_read_default(mov, s->pb, (MOVAtom){ 0, 0, INT64_MAX }) < 0 ||
2196 url_feof(s->pb))
2197 return AVERROR_EOF;
2198 dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
2199 goto retry;
2201 sc = st->priv_data;
2202 /* must be done just before reading, to avoid infinite loop on sample */
2203 sc->current_sample++;
2205 if (st->discard != AVDISCARD_ALL) {
2206 if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2207 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2208 sc->ffindex, sample->pos);
2209 return -1;
2211 ret = av_get_packet(sc->pb, pkt, sample->size);
2212 if (ret < 0)
2213 return ret;
2214 #if CONFIG_DV_DEMUXER
2215 if (mov->dv_demux && sc->dv_audio_container) {
2216 dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2217 av_free(pkt->data);
2218 pkt->size = 0;
2219 ret = dv_get_packet(mov->dv_demux, pkt);
2220 if (ret < 0)
2221 return ret;
2223 #endif
2226 pkt->stream_index = sc->ffindex;
2227 pkt->dts = sample->timestamp;
2228 if (sc->ctts_data) {
2229 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2230 /* update ctts context */
2231 sc->ctts_sample++;
2232 if (sc->ctts_index < sc->ctts_count &&
2233 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2234 sc->ctts_index++;
2235 sc->ctts_sample = 0;
2237 if (sc->wrong_dts)
2238 pkt->dts = AV_NOPTS_VALUE;
2239 } else {
2240 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2241 st->index_entries[sc->current_sample].timestamp : st->duration;
2242 pkt->duration = next_dts - pkt->dts;
2243 pkt->pts = pkt->dts;
2245 if (st->discard == AVDISCARD_ALL)
2246 goto retry;
2247 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
2248 pkt->pos = sample->pos;
2249 dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2250 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2251 return 0;
2254 static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
2256 MOVStreamContext *sc = st->priv_data;
2257 int sample, time_sample;
2258 int i;
2260 sample = av_index_search_timestamp(st, timestamp, flags);
2261 dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2262 if (sample < 0) /* not sure what to do */
2263 return -1;
2264 sc->current_sample = sample;
2265 dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
2266 /* adjust ctts index */
2267 if (sc->ctts_data) {
2268 time_sample = 0;
2269 for (i = 0; i < sc->ctts_count; i++) {
2270 int next = time_sample + sc->ctts_data[i].count;
2271 if (next > sc->current_sample) {
2272 sc->ctts_index = i;
2273 sc->ctts_sample = sc->current_sample - time_sample;
2274 break;
2276 time_sample = next;
2279 return sample;
2282 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2284 AVStream *st;
2285 int64_t seek_timestamp, timestamp;
2286 int sample;
2287 int i;
2289 if (stream_index >= s->nb_streams)
2290 return -1;
2291 if (sample_time < 0)
2292 sample_time = 0;
2294 st = s->streams[stream_index];
2295 sample = mov_seek_stream(st, sample_time, flags);
2296 if (sample < 0)
2297 return -1;
2299 /* adjust seek timestamp to found sample timestamp */
2300 seek_timestamp = st->index_entries[sample].timestamp;
2302 for (i = 0; i < s->nb_streams; i++) {
2303 st = s->streams[i];
2304 if (stream_index == i)
2305 continue;
2307 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2308 mov_seek_stream(st, timestamp, flags);
2310 return 0;
2313 static int mov_read_close(AVFormatContext *s)
2315 MOVContext *mov = s->priv_data;
2316 int i, j;
2318 for (i = 0; i < s->nb_streams; i++) {
2319 AVStream *st = s->streams[i];
2320 MOVStreamContext *sc = st->priv_data;
2322 av_freep(&sc->ctts_data);
2323 for (j = 0; j < sc->drefs_count; j++) {
2324 av_freep(&sc->drefs[j].path);
2325 av_freep(&sc->drefs[j].dir);
2327 av_freep(&sc->drefs);
2328 if (sc->pb && sc->pb != s->pb)
2329 url_fclose(sc->pb);
2331 av_freep(&st->codec->palctrl);
2334 if (mov->dv_demux) {
2335 for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
2336 av_freep(&mov->dv_fctx->streams[i]->codec);
2337 av_freep(&mov->dv_fctx->streams[i]);
2339 av_freep(&mov->dv_fctx);
2340 av_freep(&mov->dv_demux);
2343 av_freep(&mov->trex_data);
2345 return 0;
2348 AVInputFormat mov_demuxer = {
2349 "mov,mp4,m4a,3gp,3g2,mj2",
2350 NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2351 sizeof(MOVContext),
2352 mov_probe,
2353 mov_read_header,
2354 mov_read_packet,
2355 mov_read_close,
2356 mov_read_seek,