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