]> git.sesse.net Git - ffmpeg/blob - libavformat/mov.c
TIFF decoder
[ffmpeg] / libavformat / mov.c
1 /*
2  * MOV decoder.
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 "avformat.h"
27 #include "riff.h"
28 #include "isom.h"
29 #include "dv.h"
30
31 #ifdef CONFIG_ZLIB
32 #include <zlib.h>
33 #endif
34
35 /*
36  * First version by Francois Revol revol@free.fr
37  * Seek function by Gael Chardon gael.dev@4now.net
38  *
39  * Features and limitations:
40  * - reads most of the QT files I have (at least the structure),
41  *   the exceptions are .mov with zlib compressed headers ('cmov' section). It shouldn't be hard to implement.
42  *   FIXED, Francois Revol, 07/17/2002
43  * - ffmpeg has nearly none of the usual QuickTime codecs,
44  *   although I succesfully dumped raw and mp3 audio tracks off .mov files.
45  *   Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
46  * - .mp4 parsing is still hazardous, although the format really is QuickTime with some minor changes
47  *   (to make .mov parser crash maybe ?), despite what they say in the MPEG FAQ at
48  *   http://mpeg.telecomitalialab.com/faq.htm
49  * - the code is quite ugly... maybe I won't do it recursive next time :-)
50  * - seek is not supported with files that contain edit list
51  *
52  * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
53  * when coding this :) (it's a writer anyway)
54  *
55  * Reference documents:
56  * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
57  * Apple:
58  *  http://developer.apple.com/documentation/QuickTime/QTFF/
59  *  http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
60  * QuickTime is a trademark of Apple (AFAIK :))
61  */
62
63 #include "qtpalette.h"
64
65
66 #undef NDEBUG
67 #include <assert.h>
68
69 static const CodecTag mov_video_tags[] = {
70 /*  { CODEC_ID_, MKTAG('c', 'v', 'i', 'd') }, *//* Cinepak */
71 /*  { CODEC_ID_H263, MKTAG('r', 'a', 'w', ' ') }, *//* Uncompressed RGB */
72 /*  { CODEC_ID_H263, MKTAG('Y', 'u', 'v', '2') }, *//* Uncompressed YUV422 */
73 /*    { CODEC_ID_RAWVIDEO, MKTAG('A', 'V', 'U', 'I') }, *//* YUV with alpha-channel (AVID Uncompressed) */
74 /* Graphics */
75 /* Animation */
76 /* Apple video */
77 /* Kodak Photo CD */
78     { CODEC_ID_MJPEG, MKTAG('j', 'p', 'e', 'g') }, /* PhotoJPEG */
79     { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'e', 'g') }, /* MPEG */
80     { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'a') }, /* Motion-JPEG (format A) */
81     { CODEC_ID_MJPEGB, MKTAG('m', 'j', 'p', 'b') }, /* Motion-JPEG (format B) */
82     { CODEC_ID_MJPEG, MKTAG('A', 'V', 'D', 'J') }, /* MJPEG with alpha-channel (AVID JFIF meridien compressed) */
83 /*    { CODEC_ID_MJPEG, MKTAG('A', 'V', 'R', 'n') }, *//* MJPEG with alpha-channel (AVID ABVB/Truevision NuVista) */
84 /*    { CODEC_ID_GIF, MKTAG('g', 'i', 'f', ' ') }, *//* embedded gif files as frames (usually one "click to play movie" frame) */
85 /* Sorenson video */
86     { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') }, /* Sorenson Video v1 */
87     { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', '1') }, /* Sorenson Video v1 */
88     { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', 'i') }, /* Sorenson Video v1 (from QT specs)*/
89     { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') }, /* Sorenson Video v3 */
90     { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
91     { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', 'X') }, /* OpenDiVX *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
92     { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') },
93     { CODEC_ID_MPEG4, MKTAG('3', 'I', 'V', '2') }, /* experimental: 3IVX files before ivx D4 4.5.1 */
94 /*    { CODEC_ID_, MKTAG('I', 'V', '5', '0') }, *//* Indeo 5.0 */
95     { CODEC_ID_H263, MKTAG('h', '2', '6', '3') }, /* H263 */
96     { CODEC_ID_H263, MKTAG('s', '2', '6', '3') }, /* H263 ?? works */
97     { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
98     { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
99     { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') }, /* On2 VP3 */
100     { CODEC_ID_RPZA, MKTAG('r', 'p', 'z', 'a') }, /* Apple Video (RPZA) */
101     { CODEC_ID_CINEPAK, MKTAG('c', 'v', 'i', 'd') }, /* Cinepak */
102     { CODEC_ID_8BPS, MKTAG('8', 'B', 'P', 'S') }, /* Planar RGB (8BPS) */
103     { CODEC_ID_SMC, MKTAG('s', 'm', 'c', ' ') }, /* Apple Graphics (SMC) */
104     { CODEC_ID_QTRLE, MKTAG('r', 'l', 'e', ' ') }, /* Apple Animation (RLE) */
105     { CODEC_ID_QDRAW, MKTAG('q', 'd', 'r', 'w') }, /* QuickDraw */
106     { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') }, /* AVC-1/H.264 */
107     { CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '2') }, /* MPEG2 produced by Sony HD camera */
108     { CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '3') }, /* HDV produced by FCP */
109     { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '5', 'n') }, /* MPEG2 IMX NTSC 525/60 50mb/s produced by FCP */
110     { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '5', 'p') }, /* MPEG2 IMX PAL 625/50 50mb/s produced by FCP */
111     { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '3', 'n') }, /* MPEG2 IMX NTSC 525/60 30mb/s produced by FCP */
112     { CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '3', 'p') }, /* MPEG2 IMX PAL 625/50 30mb/s produced by FCP */
113     { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'p', 'p') }, /* DVCPRO PAL produced by FCP */
114     //{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '5') }, /* DVCPRO HD 50i produced by FCP */
115     //{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '6') }, /* DVCPRO HD 60i produced by FCP */
116     { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'p') }, /* DVCPRO50 PAL produced by FCP */
117     { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'n') }, /* DVCPRO50 NTSC produced by FCP */
118     { CODEC_ID_DVVIDEO, MKTAG('A', 'V', 'd', 'v') }, /* AVID DV */
119     //{ CODEC_ID_JPEG2000, MKTAG('m', 'j', 'p', '2') }, /* JPEG 2000 produced by FCP */
120     { CODEC_ID_TARGA, MKTAG('t', 'g', 'a', ' ') }, /* Truevision Targa */
121     { CODEC_ID_TIFF, MKTAG('t', 'i', 'f', 'f') }, /* TIFF embedded in MOV */
122     { CODEC_ID_RAWVIDEO, MKTAG('2', 'v', 'u', 'y') }, /* UNCOMPRESSED 8BIT 4:2:2 */
123     { CODEC_ID_NONE, 0 },
124 };
125
126 static const CodecTag mov_audio_tags[] = {
127     { CODEC_ID_PCM_S32BE, MKTAG('i', 'n', '3', '2') },
128     { CODEC_ID_PCM_S24BE, MKTAG('i', 'n', '2', '4') },
129     { CODEC_ID_PCM_S16BE, MKTAG('N', 'O', 'N', 'E') }, /* uncompressed */
130     { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') }, /* 16 bits */
131     { CODEC_ID_PCM_U8, MKTAG('r', 'a', 'w', ' ') }, /* 8 bits unsigned */
132     { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') }, /*  */
133     { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') }, /*  */
134     { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') }, /*  */
135     { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') }, /* IMA-4 ADPCM */
136     { CODEC_ID_ADPCM_MS, MKTAG('m', 's', 0x00, 0x02) }, /* MS ADPCM */
137     { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') }, /* Macintosh Audio Compression and Expansion 3:1 */
138     { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') }, /* Macintosh Audio Compression and Expansion 6:1 */
139
140     { CODEC_ID_MP3, MKTAG('.', 'm', 'p', '3') }, /* MPEG layer 3 */ /* sample files at http://www.3ivx.com/showcase.html use this tag */
141     { CODEC_ID_MP2, 0x6D730055 }, /* MPEG layer 3 */
142     { CODEC_ID_MP2, 0x5500736D }, /* MPEG layer 3 *//* XXX: check endianness */
143 /*    { CODEC_ID_OGG_VORBIS, MKTAG('O', 'g', 'g', 'S') }, *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
144 /* MP4 tags */
145     { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') }, /* MPEG-4 AAC */
146     /* The standard for mpeg4 audio is still not normalised AFAIK anyway */
147     { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') }, /* AMR-NB 3gp */
148     { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') }, /* AMR-WB 3gp */
149     { CODEC_ID_AC3, MKTAG('m', 's', 0x20, 0x00) }, /* Dolby AC-3 */
150     { CODEC_ID_ALAC,MKTAG('a', 'l', 'a', 'c') }, /* Apple Lossless */
151     { CODEC_ID_QDM2,MKTAG('Q', 'D', 'M', '2') }, /* QDM2 */
152     { CODEC_ID_DVAUDIO, MKTAG('v', 'd', 'v', 'a') },
153     { CODEC_ID_DVAUDIO, MKTAG('d', 'v', 'c', 'a') },
154     { CODEC_ID_PCM_S16LE, MKTAG('l', 'p', 'c', 'm') },
155     { CODEC_ID_NONE, 0 },
156 };
157
158 /* the QuickTime file format is quite convoluted...
159  * it has lots of index tables, each indexing something in another one...
160  * Here we just use what is needed to read the chunks
161  */
162
163 typedef struct MOV_sample_to_chunk_tbl {
164     long first;
165     long count;
166     long id;
167 } MOV_sample_to_chunk_tbl;
168
169 typedef struct {
170     uint32_t type;
171     int64_t offset;
172     int64_t size; /* total size (excluding the size and type fields) */
173 } MOV_atom_t;
174
175 typedef struct {
176     int seed;
177     int flags;
178     int size;
179     void* clrs;
180 } MOV_ctab_t;
181
182 typedef struct MOV_mdat_atom_s {
183     offset_t offset;
184     int64_t size;
185 } MOV_mdat_atom_t;
186
187 typedef struct {
188     uint8_t  version;
189     uint32_t flags; // 24bit
190
191     /* 0x03 ESDescrTag */
192     uint16_t es_id;
193 #define MP4ODescrTag                    0x01
194 #define MP4IODescrTag                   0x02
195 #define MP4ESDescrTag                   0x03
196 #define MP4DecConfigDescrTag            0x04
197 #define MP4DecSpecificDescrTag          0x05
198 #define MP4SLConfigDescrTag             0x06
199 #define MP4ContentIdDescrTag            0x07
200 #define MP4SupplContentIdDescrTag       0x08
201 #define MP4IPIPtrDescrTag               0x09
202 #define MP4IPMPPtrDescrTag              0x0A
203 #define MP4IPMPDescrTag                 0x0B
204 #define MP4RegistrationDescrTag         0x0D
205 #define MP4ESIDIncDescrTag              0x0E
206 #define MP4ESIDRefDescrTag              0x0F
207 #define MP4FileIODescrTag               0x10
208 #define MP4FileODescrTag                0x11
209 #define MP4ExtProfileLevelDescrTag      0x13
210 #define MP4ExtDescrTagsStart            0x80
211 #define MP4ExtDescrTagsEnd              0xFE
212     uint8_t  stream_priority;
213
214     /* 0x04 DecConfigDescrTag */
215     uint8_t  object_type_id;
216     uint8_t  stream_type;
217     /* XXX: really streamType is
218      * only 6bit, followed by:
219      * 1bit  upStream
220      * 1bit  reserved
221      */
222     uint32_t buffer_size_db; // 24
223     uint32_t max_bitrate;
224     uint32_t avg_bitrate;
225
226     /* 0x05 DecSpecificDescrTag */
227     uint8_t  decoder_cfg_len;
228     uint8_t *decoder_cfg;
229
230     /* 0x06 SLConfigDescrTag */
231     uint8_t  sl_config_len;
232     uint8_t *sl_config;
233 } MOV_esds_t;
234
235 struct MOVParseTableEntry;
236
237 typedef struct MOVStreamContext {
238     int ffindex; /* the ffmpeg stream id */
239     long next_chunk;
240     long chunk_count;
241     int64_t *chunk_offsets;
242     int stts_count;
243     Time2Sample *stts_data;
244     int ctts_count;
245     Time2Sample *ctts_data;
246     int edit_count;             /* number of 'edit' (elst atom) */
247     long sample_to_chunk_sz;
248     MOV_sample_to_chunk_tbl *sample_to_chunk;
249     int sample_to_ctime_index;
250     int sample_to_ctime_sample;
251     long sample_size;
252     long sample_count;
253     long *sample_sizes;
254     long keyframe_count;
255     long *keyframes;
256     int time_scale;
257     int time_rate;
258     long current_sample;
259     MOV_esds_t esds;
260     AVRational sample_size_v1;
261     int dv_audio_container;
262 } MOVStreamContext;
263
264 typedef struct MOVContext {
265     int mp4; /* set to 1 as soon as we are sure that the file is an .mp4 file (even some header parsing depends on this) */
266     AVFormatContext *fc;
267     int time_scale;
268     int64_t duration; /* duration of the longest track */
269     int found_moov; /* when both 'moov' and 'mdat' sections has been found */
270     int found_mdat; /* we suppose we have enough data to read the file */
271     int64_t mdat_size;
272     int64_t mdat_offset;
273     int total_streams;
274     /* some streams listed here aren't presented to the ffmpeg API, since they aren't either video nor audio
275      * but we need the info to be able to skip data from those streams in the 'mdat' section
276      */
277     MOVStreamContext *streams[MAX_STREAMS];
278
279     int ctab_size;
280     MOV_ctab_t **ctab;           /* color tables */
281     const struct MOVParseTableEntry *parse_table; /* could be eventually used to change the table */
282     /* NOTE: for recursion save to/ restore from local variable! */
283
284     AVPaletteControl palette_control;
285     MOV_mdat_atom_t *mdat_list;
286     int mdat_count;
287     DVDemuxContext *dv_demux;
288     AVFormatContext *dv_fctx;
289 } MOVContext;
290
291
292 /* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
293
294 /* those functions parse an atom */
295 /* return code:
296  1: found what I wanted, exit
297  0: continue to parse next atom
298  -1: error occured, exit
299  */
300 typedef int (*mov_parse_function)(MOVContext *ctx, ByteIOContext *pb, MOV_atom_t atom);
301
302 /* links atom IDs to parse functions */
303 typedef struct MOVParseTableEntry {
304     uint32_t type;
305     mov_parse_function func;
306 } MOVParseTableEntry;
307
308 static int mov_read_leaf(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
309 {
310     if (atom.size>1)
311         url_fskip(pb, atom.size);
312 /*        url_seek(pb, atom_offset+atom.size, SEEK_SET); */
313     return 0;
314 }
315
316 static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
317 {
318     int64_t total_size = 0;
319     MOV_atom_t a;
320     int i;
321     int err = 0;
322
323     a.offset = atom.offset;
324
325     if (atom.size < 0)
326         atom.size = 0x7fffffffffffffffLL;
327     while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
328         a.size = atom.size;
329         a.type=0L;
330         if(atom.size >= 8) {
331             a.size = get_be32(pb);
332             a.type = get_le32(pb);
333         }
334         total_size += 8;
335         a.offset += 8;
336         dprintf("type: %08x  %.4s  sz: %"PRIx64"  %"PRIx64"   %"PRIx64"\n", a.type, (char*)&a.type, a.size, atom.size, total_size);
337         if (a.size == 1) { /* 64 bit extended size */
338             a.size = get_be64(pb) - 8;
339             a.offset += 8;
340             total_size += 8;
341         }
342         if (a.size == 0) {
343             a.size = atom.size - total_size;
344             if (a.size <= 8)
345                 break;
346         }
347         for (i = 0; c->parse_table[i].type != 0L
348              && c->parse_table[i].type != a.type; i++)
349             /* empty */;
350
351         a.size -= 8;
352
353         if(a.size < 0)
354             break;
355
356         if (c->parse_table[i].type == 0) { /* skip leaf atoms data */
357             url_fskip(pb, a.size);
358         } else {
359             offset_t start_pos = url_ftell(pb);
360             int64_t left;
361             err = (c->parse_table[i].func)(c, pb, a);
362             left = a.size - url_ftell(pb) + start_pos;
363             if (left > 0) /* skip garbage at atom end */
364                 url_fskip(pb, left);
365         }
366
367         a.offset += a.size;
368         total_size += a.size;
369     }
370
371     if (!err && total_size < atom.size && atom.size < 0x7ffff) {
372         url_fskip(pb, atom.size - total_size);
373     }
374
375     return err;
376 }
377
378 static int mov_read_ctab(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
379 {
380 #if 1
381     url_fskip(pb, atom.size); // for now
382 #else
383     VERY VERY BROKEN, NEVER execute this, needs rewrite
384     unsigned int len;
385     MOV_ctab_t *t;
386     c->ctab = av_realloc(c->ctab, ++c->ctab_size);
387     t = c->ctab[c->ctab_size];
388     t->seed = get_be32(pb);
389     t->flags = get_be16(pb);
390     t->size = get_be16(pb) + 1;
391     len = 2 * t->size * 4;
392     if (len > 0) {
393         t->clrs = av_malloc(len); // 16bit A R G B
394         if (t->clrs)
395             get_buffer(pb, t->clrs, len);
396     }
397 #endif
398
399     return 0;
400 }
401
402 static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
403 {
404     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
405     int len = 0;
406     uint32_t type;
407     uint32_t ctype;
408
409     get_byte(pb); /* version */
410     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
411
412     /* component type */
413     ctype = get_le32(pb);
414     type = get_le32(pb); /* component subtype */
415
416     dprintf("ctype= %c%c%c%c (0x%08lx)\n", *((char *)&ctype), ((char *)&ctype)[1], ((char *)&ctype)[2], ((char *)&ctype)[3], (long) ctype);
417     dprintf("stype= %c%c%c%c\n", *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
418     if(ctype == MKTAG('m', 'h', 'l', 'r')) /* MOV */
419         c->mp4 = 0;
420     else if(ctype == 0)
421         c->mp4 = 1;
422     if(type == MKTAG('v', 'i', 'd', 'e'))
423         st->codec->codec_type = CODEC_TYPE_VIDEO;
424     else if(type == MKTAG('s', 'o', 'u', 'n'))
425         st->codec->codec_type = CODEC_TYPE_AUDIO;
426     get_be32(pb); /* component  manufacture */
427     get_be32(pb); /* component flags */
428     get_be32(pb); /* component flags mask */
429
430     if(atom.size <= 24)
431         return 0; /* nothing left to read */
432     /* XXX: MP4 uses a C string, not a pascal one */
433     /* component name */
434
435     if(c->mp4) {
436         /* .mp4: C string */
437         while(get_byte(pb) && (++len < (atom.size - 24)));
438     } else {
439         /* .mov: PASCAL string */
440         len = get_byte(pb);
441         url_fskip(pb, len);
442     }
443
444     url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
445     return 0;
446 }
447
448 static int mov_mp4_read_descr_len(ByteIOContext *pb)
449 {
450     int len = 0;
451     int count = 4;
452     while (count--) {
453         int c = get_byte(pb);
454         len = (len << 7) | (c & 0x7f);
455         if (!(c & 0x80))
456             break;
457     }
458     return len;
459 }
460
461 static int mov_mp4_read_descr(ByteIOContext *pb, int *tag)
462 {
463     int len;
464     *tag = get_byte(pb);
465     len = mov_mp4_read_descr_len(pb);
466     dprintf("MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
467     return len;
468 }
469
470 static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
471 {
472     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
473     MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
474     int tag, len;
475
476     /* Well, broken but suffisant for some MP4 streams */
477     get_be32(pb); /* version + flags */
478     len = mov_mp4_read_descr(pb, &tag);
479     if (tag == MP4ESDescrTag) {
480         get_be16(pb); /* ID */
481         get_byte(pb); /* priority */
482     } else
483         get_be16(pb); /* ID */
484
485     len = mov_mp4_read_descr(pb, &tag);
486     if (tag == MP4DecConfigDescrTag) {
487         sc->esds.object_type_id = get_byte(pb);
488         sc->esds.stream_type = get_byte(pb);
489         sc->esds.buffer_size_db = get_be24(pb);
490         sc->esds.max_bitrate = get_be32(pb);
491         sc->esds.avg_bitrate = get_be32(pb);
492
493         st->codec->codec_id= codec_get_id(ff_mov_obj_type, sc->esds.object_type_id);
494         dprintf("esds object type id %d\n", sc->esds.object_type_id);
495         len = mov_mp4_read_descr(pb, &tag);
496         if (tag == MP4DecSpecificDescrTag) {
497             dprintf("Specific MPEG4 header len=%d\n", len);
498             st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
499             if (st->codec->extradata) {
500                 get_buffer(pb, st->codec->extradata, len);
501                 st->codec->extradata_size = len;
502                 /* from mplayer */
503                 if ((*st->codec->extradata >> 3) == 29) {
504                     st->codec->codec_id = CODEC_ID_MP3ON4;
505                 }
506             }
507         }
508     }
509     return 0;
510 }
511
512 /* this atom contains actual media data */
513 static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
514 {
515     if(atom.size == 0) /* wrong one (MP4) */
516         return 0;
517     c->mdat_list = av_realloc(c->mdat_list, (c->mdat_count + 1) * sizeof(*c->mdat_list));
518     c->mdat_list[c->mdat_count].offset = atom.offset;
519     c->mdat_list[c->mdat_count].size = atom.size;
520     c->mdat_count++;
521     c->found_mdat=1;
522     c->mdat_offset = atom.offset;
523     c->mdat_size = atom.size;
524     if(c->found_moov)
525         return 1; /* found both, just go */
526     url_fskip(pb, atom.size);
527     return 0; /* now go for moov */
528 }
529
530 static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
531 {
532     uint32_t type = get_le32(pb);
533
534     /* from mplayer */
535     switch (type) {
536     case MKTAG('i', 's', 'o', 'm'):
537     case MKTAG('m', 'p', '4', '1'):
538     case MKTAG('m', 'p', '4', '2'):
539     case MKTAG('3', 'g', 'p', '1'):
540     case MKTAG('3', 'g', 'p', '2'):
541     case MKTAG('3', 'g', '2', 'a'):
542     case MKTAG('3', 'g', 'p', '3'):
543     case MKTAG('3', 'g', 'p', '4'):
544     case MKTAG('3', 'g', 'p', '5'):
545     case MKTAG('m', 'm', 'p', '4'): /* Mobile MP4 */
546     case MKTAG('M', '4', 'A', ' '): /* Apple iTunes AAC-LC Audio */
547     case MKTAG('M', '4', 'P', ' '): /* Apple iTunes AAC-LC Protected Audio */
548     case MKTAG('m', 'j', 'p', '2'): /* Motion Jpeg 2000 */
549         c->mp4 = 1;
550     case MKTAG('q', 't', ' ', ' '):
551     default:
552         av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
553     }
554     get_be32(pb); /* minor version */
555     url_fskip(pb, atom.size - 8);
556     return 0;
557 }
558
559 /* this atom should contain all header atoms */
560 static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
561 {
562     int err;
563
564     err = mov_read_default(c, pb, atom);
565     /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
566     /* so we don't parse the whole file if over a network */
567     c->found_moov=1;
568     if(c->found_mdat)
569         return 1; /* found both, just go */
570     return 0; /* now go for mdat */
571 }
572
573
574 static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
575 {
576     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
577     MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
578     int version = get_byte(pb);
579     int lang;
580
581     if (version > 1)
582         return 1; /* unsupported */
583
584     get_byte(pb); get_byte(pb);
585     get_byte(pb); /* flags */
586
587     if (version == 1) {
588         get_be64(pb);
589         get_be64(pb);
590     } else {
591         get_be32(pb); /* creation time */
592         get_be32(pb); /* modification time */
593     }
594
595     sc->time_scale = get_be32(pb);
596     st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
597
598     lang = get_be16(pb); /* language */
599     ff_mov_lang_to_iso639(lang, st->language);
600     get_be16(pb); /* quality */
601
602     return 0;
603 }
604
605 static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
606 {
607     int version = get_byte(pb); /* version */
608     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
609
610     if (version == 1) {
611         get_be64(pb);
612         get_be64(pb);
613     } else {
614         get_be32(pb); /* creation time */
615         get_be32(pb); /* modification time */
616     }
617     c->time_scale = get_be32(pb); /* time scale */
618 #ifdef DEBUG
619     av_log(NULL, AV_LOG_DEBUG, "time scale = %i\n", c->time_scale);
620 #endif
621     c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
622     get_be32(pb); /* preferred scale */
623
624     get_be16(pb); /* preferred volume */
625
626     url_fskip(pb, 10); /* reserved */
627
628     url_fskip(pb, 36); /* display matrix */
629
630     get_be32(pb); /* preview time */
631     get_be32(pb); /* preview duration */
632     get_be32(pb); /* poster time */
633     get_be32(pb); /* selection time */
634     get_be32(pb); /* selection duration */
635     get_be32(pb); /* current time */
636     get_be32(pb); /* next track ID */
637
638     return 0;
639 }
640
641 static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
642 {
643     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
644
645     if((uint64_t)atom.size > (1<<30))
646         return -1;
647
648     // currently SVQ3 decoder expect full STSD header - so let's fake it
649     // this should be fixed and just SMI header should be passed
650     av_free(st->codec->extradata);
651     st->codec->extradata_size = 0x5a + atom.size;
652     st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
653
654     if (st->codec->extradata) {
655         strcpy(st->codec->extradata, "SVQ3"); // fake
656         get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
657         dprintf("Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
658     } else
659         url_fskip(pb, atom.size);
660
661     return 0;
662 }
663
664 static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
665 {
666     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
667     int little_endian = get_be16(pb);
668
669     if (little_endian) {
670         switch (st->codec->codec_id) {
671         case CODEC_ID_PCM_S24BE:
672             st->codec->codec_id = CODEC_ID_PCM_S24LE;
673             break;
674         case CODEC_ID_PCM_S32BE:
675             st->codec->codec_id = CODEC_ID_PCM_S32LE;
676             break;
677         default:
678             break;
679         }
680     }
681     return 0;
682 }
683
684 static int mov_read_alac(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
685 {
686     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
687
688     // currently ALAC decoder expect full atom header - so let's fake it
689     // this should be fixed and just ALAC header should be passed
690
691     av_free(st->codec->extradata);
692     st->codec->extradata_size = 36;
693     st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
694
695     if (st->codec->extradata) {
696         strcpy(st->codec->extradata + 4, "alac"); // fake
697         get_buffer(pb, st->codec->extradata + 8, 36 - 8);
698         dprintf("Reading alac %d  %s\n", st->codec->extradata_size, st->codec->extradata);
699     } else
700         url_fskip(pb, atom.size);
701     return 0;
702 }
703
704 static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
705 {
706     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
707
708     if((uint64_t)atom.size > (1<<30))
709         return -1;
710
711     if (st->codec->codec_id == CODEC_ID_QDM2) {
712         // pass all frma atom to codec, needed at least for QDM2
713         av_free(st->codec->extradata);
714         st->codec->extradata_size = atom.size;
715         st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
716
717         if (st->codec->extradata) {
718             get_buffer(pb, st->codec->extradata, atom.size);
719         } else
720             url_fskip(pb, atom.size);
721     } else if (atom.size > 8) { /* to read frma, esds atoms */
722         mov_read_default(c, pb, atom);
723     } else
724         url_fskip(pb, atom.size);
725     return 0;
726 }
727
728 static int mov_read_jp2h(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
729 {
730     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
731
732     if((uint64_t)atom.size > (1<<30))
733         return -1;
734
735     av_free(st->codec->extradata);
736
737     st->codec->extradata_size = atom.size + 8;
738     st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
739
740     /* pass all jp2h atom to codec */
741     if (st->codec->extradata) {
742         strcpy(st->codec->extradata + 4, "jp2h");
743         get_buffer(pb, st->codec->extradata + 8, atom.size);
744     } else
745         url_fskip(pb, atom.size);
746     return 0;
747 }
748
749 static int mov_read_avcC(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
750 {
751     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
752
753     if((uint64_t)atom.size > (1<<30))
754         return -1;
755
756     av_free(st->codec->extradata);
757
758     st->codec->extradata_size = atom.size;
759     st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
760
761     if (st->codec->extradata) {
762         get_buffer(pb, st->codec->extradata, atom.size);
763     } else
764         url_fskip(pb, atom.size);
765
766     return 0;
767 }
768
769 static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
770 {
771     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
772     MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
773     unsigned int i, entries;
774
775     get_byte(pb); /* version */
776     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
777
778     entries = get_be32(pb);
779
780     if(entries >= UINT_MAX/sizeof(int64_t))
781         return -1;
782
783     sc->chunk_count = entries;
784     sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
785     if (!sc->chunk_offsets)
786         return -1;
787     if (atom.type == MKTAG('s', 't', 'c', 'o')) {
788         for(i=0; i<entries; i++) {
789             sc->chunk_offsets[i] = get_be32(pb);
790         }
791     } else if (atom.type == MKTAG('c', 'o', '6', '4')) {
792         for(i=0; i<entries; i++) {
793             sc->chunk_offsets[i] = get_be64(pb);
794         }
795     } else
796         return -1;
797
798     return 0;
799 }
800
801 static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
802 {
803     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
804     MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
805     int entries, frames_per_sample;
806     uint32_t format;
807     uint8_t codec_name[32];
808
809     /* for palette traversal */
810     int color_depth;
811     int color_start;
812     int color_count;
813     int color_end;
814     int color_index;
815     int color_dec;
816     int color_greyscale;
817     unsigned char *color_table;
818     int j;
819     unsigned char r, g, b;
820
821     get_byte(pb); /* version */
822     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
823
824     entries = get_be32(pb);
825
826     while(entries--) { //Parsing Sample description table
827         enum CodecID id;
828         MOV_atom_t a = { 0, 0, 0 };
829         offset_t start_pos = url_ftell(pb);
830         int size = get_be32(pb); /* size */
831         format = get_le32(pb); /* data format */
832
833         get_be32(pb); /* reserved */
834         get_be16(pb); /* reserved */
835         get_be16(pb); /* index */
836
837         if (st->codec->codec_tag) {
838             /* multiple fourcc, just skip for now */
839             url_fskip(pb, size - (url_ftell(pb) - start_pos));
840             continue;
841         }
842
843         st->codec->codec_tag = format;
844         id = codec_get_id(mov_audio_tags, format);
845         if (id > 0) {
846             st->codec->codec_type = CODEC_TYPE_AUDIO;
847         } else if (format && format != MKTAG('m', 'p', '4', 's')) { /* skip old asf mpeg4 tag */
848             id = codec_get_id(mov_video_tags, format);
849             if (id <= 0)
850                 id = codec_get_id(codec_bmp_tags, format);
851             if (id > 0)
852                 st->codec->codec_type = CODEC_TYPE_VIDEO;
853         }
854
855         dprintf("size=%d 4CC= %c%c%c%c codec_type=%d\n",
856                 size,
857                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff, (format >> 24) & 0xff,
858                 st->codec->codec_type);
859
860         if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
861             st->codec->codec_id = id;
862             get_be16(pb); /* version */
863             get_be16(pb); /* revision level */
864             get_be32(pb); /* vendor */
865             get_be32(pb); /* temporal quality */
866             get_be32(pb); /* spacial quality */
867
868             st->codec->width = get_be16(pb); /* width */
869             st->codec->height = get_be16(pb); /* height */
870
871             get_be32(pb); /* horiz resolution */
872             get_be32(pb); /* vert resolution */
873             get_be32(pb); /* data size, always 0 */
874             frames_per_sample = get_be16(pb); /* frames per samples */
875 #ifdef DEBUG
876             av_log(NULL, AV_LOG_DEBUG, "frames/samples = %d\n", frames_per_sample);
877 #endif
878             get_buffer(pb, codec_name, 32); /* codec name, pascal string (FIXME: true for mp4?) */
879             if (codec_name[0] <= 31) {
880                 memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
881                 st->codec->codec_name[codec_name[0]] = 0;
882             }
883
884             st->codec->bits_per_sample = get_be16(pb); /* depth */
885             st->codec->color_table_id = get_be16(pb); /* colortable id */
886
887             /* figure out the palette situation */
888             color_depth = st->codec->bits_per_sample & 0x1F;
889             color_greyscale = st->codec->bits_per_sample & 0x20;
890
891             /* if the depth is 2, 4, or 8 bpp, file is palettized */
892             if ((color_depth == 2) || (color_depth == 4) ||
893                 (color_depth == 8)) {
894
895                 if (color_greyscale) {
896
897                     /* compute the greyscale palette */
898                     color_count = 1 << color_depth;
899                     color_index = 255;
900                     color_dec = 256 / (color_count - 1);
901                     for (j = 0; j < color_count; j++) {
902                         r = g = b = color_index;
903                         c->palette_control.palette[j] =
904                             (r << 16) | (g << 8) | (b);
905                         color_index -= color_dec;
906                         if (color_index < 0)
907                             color_index = 0;
908                     }
909
910                 } else if (st->codec->color_table_id & 0x08) {
911
912                     /* if flag bit 3 is set, use the default palette */
913                     color_count = 1 << color_depth;
914                     if (color_depth == 2)
915                         color_table = ff_qt_default_palette_4;
916                     else if (color_depth == 4)
917                         color_table = ff_qt_default_palette_16;
918                     else
919                         color_table = ff_qt_default_palette_256;
920
921                     for (j = 0; j < color_count; j++) {
922                         r = color_table[j * 4 + 0];
923                         g = color_table[j * 4 + 1];
924                         b = color_table[j * 4 + 2];
925                         c->palette_control.palette[j] =
926                             (r << 16) | (g << 8) | (b);
927                     }
928
929                 } else {
930
931                     /* load the palette from the file */
932                     color_start = get_be32(pb);
933                     color_count = get_be16(pb);
934                     color_end = get_be16(pb);
935                     for (j = color_start; j <= color_end; j++) {
936                         /* each R, G, or B component is 16 bits;
937                          * only use the top 8 bits; skip alpha bytes
938                          * up front */
939                         get_byte(pb);
940                         get_byte(pb);
941                         r = get_byte(pb);
942                         get_byte(pb);
943                         g = get_byte(pb);
944                         get_byte(pb);
945                         b = get_byte(pb);
946                         get_byte(pb);
947                         c->palette_control.palette[j] =
948                             (r << 16) | (g << 8) | (b);
949                     }
950                 }
951
952                 st->codec->palctrl = &c->palette_control;
953                 st->codec->palctrl->palette_changed = 1;
954             } else
955                 st->codec->palctrl = NULL;
956         } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
957             int bits_per_sample;
958             uint16_t version = get_be16(pb);
959
960             st->codec->codec_id = id;
961             get_be16(pb); /* revision level */
962             get_be32(pb); /* vendor */
963
964             st->codec->channels = get_be16(pb);             /* channel count */
965             dprintf("audio channels %d\n", st->codec->channels);
966             st->codec->bits_per_sample = get_be16(pb);      /* sample size */
967             /* do we need to force to 16 for AMR ? */
968
969             /* handle specific s8 codec */
970             get_be16(pb); /* compression id = 0*/
971             get_be16(pb); /* packet size = 0 */
972
973             st->codec->sample_rate = ((get_be32(pb) >> 16));
974
975             switch (st->codec->codec_id) {
976             case CODEC_ID_PCM_S8:
977             case CODEC_ID_PCM_U8:
978                 if (st->codec->bits_per_sample == 16)
979                     st->codec->codec_id = CODEC_ID_PCM_S16BE;
980                 break;
981             case CODEC_ID_PCM_S16LE:
982             case CODEC_ID_PCM_S16BE:
983                 if (st->codec->bits_per_sample == 8)
984                     st->codec->codec_id = CODEC_ID_PCM_S8;
985                 else if (st->codec->bits_per_sample == 24)
986                     st->codec->codec_id = CODEC_ID_PCM_S24BE;
987                 break;
988             default:
989                 break;
990             }
991
992             //Read QT version 1 fields. In version 0 theese dont exist
993             dprintf("version =%d mp4=%d\n",version,c->mp4);
994             if(version==1) {
995                 sc->sample_size_v1.den = get_be32(pb); /* samples per packet */
996                 get_be32(pb); /* bytes per packet */
997                 sc->sample_size_v1.num = get_be32(pb); /* bytes per frame */
998                 get_be32(pb); /* bytes per sample */
999             } else if(version==2) {
1000                 get_be32(pb); /* sizeof struct only */
1001                 st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
1002                 st->codec->channels = get_be32(pb);
1003                 get_be32(pb); /* always 0x7F000000 */
1004                 get_be32(pb); /* bits per channel if sound is uncompressed */
1005                 get_be32(pb); /* lcpm format specific flag */
1006                 get_be32(pb); /* bytes per audio packet if constant */
1007                 get_be32(pb); /* lpcm frames per audio packet if constant */
1008             }
1009
1010             bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1011             if (bits_per_sample) {
1012                 st->codec->bits_per_sample = bits_per_sample;
1013                 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1014             }
1015         } else {
1016             /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1017             url_fskip(pb, size - (url_ftell(pb) - start_pos));
1018         }
1019         /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1020         a.size = size - (url_ftell(pb) - start_pos);
1021         if (a.size > 8)
1022             mov_read_default(c, pb, a);
1023         else if (a.size > 0)
1024             url_fskip(pb, a.size);
1025     }
1026
1027     if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1) {
1028         st->codec->sample_rate= sc->time_scale;
1029     }
1030
1031     /* special codec parameters handling */
1032     switch (st->codec->codec_id) {
1033 #ifdef CONFIG_H261_DECODER
1034     case CODEC_ID_H261:
1035 #endif
1036 #ifdef CONFIG_H263_DECODER
1037     case CODEC_ID_H263:
1038 #endif
1039 #ifdef CONFIG_MPEG4_DECODER
1040     case CODEC_ID_MPEG4:
1041 #endif
1042         st->codec->width= 0; /* let decoder init width/height */
1043         st->codec->height= 0;
1044         break;
1045 #ifdef CONFIG_FAAD
1046     case CODEC_ID_AAC:
1047 #endif
1048 #ifdef CONFIG_VORBIS_DECODER
1049     case CODEC_ID_VORBIS:
1050 #endif
1051     case CODEC_ID_MP3ON4:
1052         st->codec->sample_rate= 0; /* let decoder init parameters properly */
1053         break;
1054 #ifdef CONFIG_DV_DEMUXER
1055     case CODEC_ID_DVAUDIO:
1056         c->dv_fctx = av_alloc_format_context();
1057         c->dv_demux = dv_init_demux(c->dv_fctx);
1058         if (!c->dv_demux) {
1059             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1060             return -1;
1061         }
1062         sc->dv_audio_container = 1;
1063         st->codec->codec_id = CODEC_ID_PCM_S16LE;
1064         break;
1065 #endif
1066     /* no ifdef since parameters are always those */
1067     case CODEC_ID_AMR_WB:
1068         st->codec->sample_rate= 16000;
1069         st->codec->channels= 1; /* really needed */
1070         break;
1071     case CODEC_ID_AMR_NB:
1072         st->codec->sample_rate= 8000;
1073         st->codec->channels= 1; /* really needed */
1074         break;
1075     case CODEC_ID_MP2:
1076         st->need_parsing = 1;
1077         break;
1078     default:
1079         break;
1080     }
1081
1082     return 0;
1083 }
1084
1085 static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1086 {
1087     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1088     MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1089     unsigned int i, entries;
1090
1091     get_byte(pb); /* version */
1092     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1093
1094     entries = get_be32(pb);
1095
1096     if(entries >= UINT_MAX / sizeof(MOV_sample_to_chunk_tbl))
1097         return -1;
1098
1099 #ifdef DEBUG
1100 av_log(NULL, AV_LOG_DEBUG, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1101 #endif
1102     sc->sample_to_chunk_sz = entries;
1103     sc->sample_to_chunk = av_malloc(entries * sizeof(MOV_sample_to_chunk_tbl));
1104     if (!sc->sample_to_chunk)
1105         return -1;
1106     for(i=0; i<entries; i++) {
1107         sc->sample_to_chunk[i].first = get_be32(pb);
1108         sc->sample_to_chunk[i].count = get_be32(pb);
1109         sc->sample_to_chunk[i].id = get_be32(pb);
1110     }
1111     return 0;
1112 }
1113
1114 static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1115 {
1116     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1117     MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1118     unsigned int i, entries;
1119
1120     get_byte(pb); /* version */
1121     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1122
1123     entries = get_be32(pb);
1124
1125     if(entries >= UINT_MAX / sizeof(long))
1126         return -1;
1127
1128     sc->keyframe_count = entries;
1129 #ifdef DEBUG
1130     av_log(NULL, AV_LOG_DEBUG, "keyframe_count = %ld\n", sc->keyframe_count);
1131 #endif
1132     sc->keyframes = av_malloc(entries * sizeof(long));
1133     if (!sc->keyframes)
1134         return -1;
1135     for(i=0; i<entries; i++) {
1136         sc->keyframes[i] = get_be32(pb);
1137 #ifdef DEBUG
1138 /*        av_log(NULL, AV_LOG_DEBUG, "keyframes[]=%ld\n", sc->keyframes[i]); */
1139 #endif
1140     }
1141     return 0;
1142 }
1143
1144 static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1145 {
1146     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1147     MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1148     unsigned int i, entries, sample_size;
1149
1150     get_byte(pb); /* version */
1151     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1152
1153     sample_size = get_be32(pb);
1154     if (!sc->sample_size) /* do not overwrite value computed in stsd */
1155         sc->sample_size = sample_size;
1156     entries = get_be32(pb);
1157     if(entries >= UINT_MAX / sizeof(long))
1158         return -1;
1159
1160     sc->sample_count = entries;
1161     if (sample_size)
1162         return 0;
1163
1164 #ifdef DEBUG
1165     av_log(NULL, AV_LOG_DEBUG, "sample_size = %ld sample_count = %ld\n", sc->sample_size, sc->sample_count);
1166 #endif
1167     sc->sample_sizes = av_malloc(entries * sizeof(long));
1168     if (!sc->sample_sizes)
1169         return -1;
1170     for(i=0; i<entries; i++) {
1171         sc->sample_sizes[i] = get_be32(pb);
1172 #ifdef DEBUG
1173         av_log(NULL, AV_LOG_DEBUG, "sample_sizes[]=%ld\n", sc->sample_sizes[i]);
1174 #endif
1175     }
1176     return 0;
1177 }
1178
1179 static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1180 {
1181     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1182     MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1183     unsigned int i, entries;
1184     int64_t duration=0;
1185     int64_t total_sample_count=0;
1186
1187     get_byte(pb); /* version */
1188     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1189     entries = get_be32(pb);
1190     if(entries >= UINT_MAX / sizeof(Time2Sample))
1191         return -1;
1192
1193     sc->stts_count = entries;
1194     sc->stts_data = av_malloc(entries * sizeof(Time2Sample));
1195
1196 #ifdef DEBUG
1197 av_log(NULL, AV_LOG_DEBUG, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1198 #endif
1199
1200     sc->time_rate=0;
1201
1202     for(i=0; i<entries; i++) {
1203         int sample_duration;
1204         int sample_count;
1205
1206         sample_count=get_be32(pb);
1207         sample_duration = get_be32(pb);
1208         sc->stts_data[i].count= sample_count;
1209         sc->stts_data[i].duration= sample_duration;
1210
1211         sc->time_rate= ff_gcd(sc->time_rate, sample_duration);
1212
1213         dprintf("sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1214
1215         duration+=(int64_t)sample_duration*sample_count;
1216         total_sample_count+=sample_count;
1217     }
1218
1219     st->nb_frames= total_sample_count;
1220     if(duration)
1221         st->duration= duration;
1222     return 0;
1223 }
1224
1225 static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1226 {
1227     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1228     MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1229     unsigned int i, entries;
1230
1231     get_byte(pb); /* version */
1232     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1233     entries = get_be32(pb);
1234     if(entries >= UINT_MAX / sizeof(Time2Sample))
1235         return -1;
1236
1237     sc->ctts_count = entries;
1238     sc->ctts_data = av_malloc(entries * sizeof(Time2Sample));
1239
1240     dprintf("track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1241
1242     for(i=0; i<entries; i++) {
1243         int count    =get_be32(pb);
1244         int duration =get_be32(pb);
1245
1246         if (duration < 0) {
1247             av_log(c->fc, AV_LOG_ERROR, "negative ctts, ignoring\n");
1248             sc->ctts_count = 0;
1249             url_fskip(pb, 8 * (entries - i - 1));
1250             break;
1251         }
1252         sc->ctts_data[i].count   = count;
1253         sc->ctts_data[i].duration= duration;
1254
1255         sc->time_rate= ff_gcd(sc->time_rate, duration);
1256     }
1257     return 0;
1258 }
1259
1260 static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1261 {
1262     AVStream *st;
1263     MOVStreamContext *sc;
1264
1265     st = av_new_stream(c->fc, c->fc->nb_streams);
1266     if (!st) return -2;
1267     sc = av_mallocz(sizeof(MOVStreamContext));
1268     if (!sc) {
1269         av_free(st);
1270         return -1;
1271     }
1272
1273     st->priv_data = sc;
1274     st->codec->codec_type = CODEC_TYPE_DATA;
1275     st->start_time = 0; /* XXX: check */
1276     c->streams[c->fc->nb_streams-1] = sc;
1277
1278     return mov_read_default(c, pb, atom);
1279 }
1280
1281 static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1282 {
1283     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1284     int version = get_byte(pb);
1285
1286     get_byte(pb); get_byte(pb);
1287     get_byte(pb); /* flags */
1288     /*
1289     MOV_TRACK_ENABLED 0x0001
1290     MOV_TRACK_IN_MOVIE 0x0002
1291     MOV_TRACK_IN_PREVIEW 0x0004
1292     MOV_TRACK_IN_POSTER 0x0008
1293     */
1294
1295     if (version == 1) {
1296         get_be64(pb);
1297         get_be64(pb);
1298     } else {
1299         get_be32(pb); /* creation time */
1300         get_be32(pb); /* modification time */
1301     }
1302     st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1303     get_be32(pb); /* reserved */
1304     st->start_time = 0; /* check */
1305     (version == 1) ? get_be64(pb) : get_be32(pb); /* highlevel (considering edits) duration in movie timebase */
1306     get_be32(pb); /* reserved */
1307     get_be32(pb); /* reserved */
1308
1309     get_be16(pb); /* layer */
1310     get_be16(pb); /* alternate group */
1311     get_be16(pb); /* volume */
1312     get_be16(pb); /* reserved */
1313
1314     url_fskip(pb, 36); /* display matrix */
1315
1316     /* those are fixed-point */
1317     get_be32(pb); /* track width */
1318     get_be32(pb); /* track height */
1319
1320     return 0;
1321 }
1322
1323 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1324 /* like the files created with Adobe Premiere 5.0, for samples see */
1325 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1326 static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1327 {
1328     int err;
1329
1330     if (atom.size < 8)
1331         return 0; /* continue */
1332     if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1333         url_fskip(pb, atom.size - 4);
1334         return 0;
1335     }
1336     atom.type = get_le32(pb);
1337     atom.offset += 8;
1338     atom.size -= 8;
1339     if (atom.type != MKTAG('m', 'd', 'a', 't')) {
1340         url_fskip(pb, atom.size);
1341         return 0;
1342     }
1343     err = mov_read_mdat(c, pb, atom);
1344     return err;
1345 }
1346
1347
1348 #ifdef CONFIG_ZLIB
1349 static int null_read_packet(void *opaque, uint8_t *buf, int buf_size)
1350 {
1351     return -1;
1352 }
1353
1354 static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1355 {
1356     ByteIOContext ctx;
1357     uint8_t *cmov_data;
1358     uint8_t *moov_data; /* uncompressed data */
1359     long cmov_len, moov_len;
1360     int ret;
1361
1362     get_be32(pb); /* dcom atom */
1363     if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
1364         return -1;
1365     if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
1366         av_log(NULL, AV_LOG_ERROR, "unknown compression for cmov atom !");
1367         return -1;
1368     }
1369     get_be32(pb); /* cmvd atom */
1370     if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
1371         return -1;
1372     moov_len = get_be32(pb); /* uncompressed size */
1373     cmov_len = atom.size - 6 * 4;
1374
1375     cmov_data = av_malloc(cmov_len);
1376     if (!cmov_data)
1377         return -1;
1378     moov_data = av_malloc(moov_len);
1379     if (!moov_data) {
1380         av_free(cmov_data);
1381         return -1;
1382     }
1383     get_buffer(pb, cmov_data, cmov_len);
1384     if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1385         return -1;
1386     if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, null_read_packet, NULL, NULL) != 0)
1387         return -1;
1388     ctx.buf_end = ctx.buffer + moov_len;
1389     atom.type = MKTAG( 'm', 'o', 'o', 'v' );
1390     atom.offset = 0;
1391     atom.size = moov_len;
1392 #ifdef DEBUG
1393 //    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1394 #endif
1395     ret = mov_read_default(c, &ctx, atom);
1396     av_free(moov_data);
1397     av_free(cmov_data);
1398
1399     return ret;
1400 }
1401 #endif
1402
1403 /* edit list atom */
1404 static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1405 {
1406     int i, edit_count;
1407
1408     get_byte(pb); /* version */
1409     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1410     edit_count= c->streams[c->fc->nb_streams-1]->edit_count = get_be32(pb);     /* entries */
1411
1412     for(i=0; i<edit_count; i++){
1413         get_be32(pb); /* Track duration */
1414         get_be32(pb); /* Media time */
1415         get_be32(pb); /* Media rate */
1416     }
1417     dprintf("track[%i].edit_count = %i\n", c->fc->nb_streams-1, c->streams[c->fc->nb_streams-1]->edit_count);
1418     return 0;
1419 }
1420
1421 static const MOVParseTableEntry mov_default_parse_table[] = {
1422 /* mp4 atoms */
1423 { MKTAG( 'c', 'o', '6', '4' ), mov_read_stco },
1424 { MKTAG( 'c', 'p', 'r', 't' ), mov_read_default },
1425 { MKTAG( 'c', 'r', 'h', 'd' ), mov_read_default },
1426 { MKTAG( 'c', 't', 't', 's' ), mov_read_ctts }, /* composition time to sample */
1427 { MKTAG( 'd', 'i', 'n', 'f' ), mov_read_default }, /* data information */
1428 { MKTAG( 'd', 'p', 'n', 'd' ), mov_read_leaf },
1429 { MKTAG( 'd', 'r', 'e', 'f' ), mov_read_leaf },
1430 { MKTAG( 'e', 'd', 't', 's' ), mov_read_default },
1431 { MKTAG( 'e', 'l', 's', 't' ), mov_read_elst },
1432 { MKTAG( 'e', 'n', 'd', 'a' ), mov_read_enda },
1433 { MKTAG( 'f', 'r', 'e', 'e' ), mov_read_leaf },
1434 { MKTAG( 'f', 't', 'y', 'p' ), mov_read_ftyp },
1435 { MKTAG( 'h', 'd', 'l', 'r' ), mov_read_hdlr },
1436 { MKTAG( 'h', 'i', 'n', 't' ), mov_read_leaf },
1437 { MKTAG( 'h', 'm', 'h', 'd' ), mov_read_leaf },
1438 { MKTAG( 'i', 'o', 'd', 's' ), mov_read_leaf },
1439 { MKTAG( 'j', 'p', '2', 'h' ), mov_read_jp2h },
1440 { MKTAG( 'm', 'd', 'a', 't' ), mov_read_mdat },
1441 { MKTAG( 'm', 'd', 'h', 'd' ), mov_read_mdhd },
1442 { MKTAG( 'm', 'd', 'i', 'a' ), mov_read_default },
1443 { MKTAG( 'm', 'i', 'n', 'f' ), mov_read_default },
1444 { MKTAG( 'm', 'o', 'o', 'v' ), mov_read_moov },
1445 { MKTAG( 'm', 'p', '4', 'a' ), mov_read_default },
1446 { MKTAG( 'm', 'p', '4', 's' ), mov_read_default },
1447 { MKTAG( 'm', 'p', '4', 'v' ), mov_read_default },
1448 { MKTAG( 'm', 'p', 'o', 'd' ), mov_read_leaf },
1449 { MKTAG( 'm', 'v', 'h', 'd' ), mov_read_mvhd },
1450 { MKTAG( 'n', 'm', 'h', 'd' ), mov_read_leaf },
1451 { MKTAG( 'o', 'd', 'h', 'd' ), mov_read_default },
1452 { MKTAG( 's', 'd', 'h', 'd' ), mov_read_default },
1453 { MKTAG( 's', 'k', 'i', 'p' ), mov_read_leaf },
1454 { MKTAG( 's', 'm', 'h', 'd' ), mov_read_leaf }, /* sound media info header */
1455 { MKTAG( 'S', 'M', 'I', ' ' ), mov_read_smi }, /* Sorenson extension ??? */
1456 { MKTAG( 'a', 'l', 'a', 'c' ), mov_read_alac }, /* alac specific atom */
1457 { MKTAG( 'a', 'v', 'c', 'C' ), mov_read_avcC },
1458 { MKTAG( 's', 't', 'b', 'l' ), mov_read_default },
1459 { MKTAG( 's', 't', 'c', 'o' ), mov_read_stco },
1460 { MKTAG( 's', 't', 'd', 'p' ), mov_read_default },
1461 { MKTAG( 's', 't', 's', 'c' ), mov_read_stsc },
1462 { MKTAG( 's', 't', 's', 'd' ), mov_read_stsd }, /* sample description */
1463 { MKTAG( 's', 't', 's', 'h' ), mov_read_default },
1464 { MKTAG( 's', 't', 's', 's' ), mov_read_stss }, /* sync sample */
1465 { MKTAG( 's', 't', 's', 'z' ), mov_read_stsz }, /* sample size */
1466 { MKTAG( 's', 't', 't', 's' ), mov_read_stts },
1467 { MKTAG( 't', 'k', 'h', 'd' ), mov_read_tkhd }, /* track header */
1468 { MKTAG( 't', 'r', 'a', 'k' ), mov_read_trak },
1469 { MKTAG( 't', 'r', 'e', 'f' ), mov_read_default }, /* not really */
1470 { MKTAG( 'u', 'd', 't', 'a' ), mov_read_leaf },
1471 { MKTAG( 'u', 'r', 'l', ' ' ), mov_read_leaf },
1472 { MKTAG( 'u', 'r', 'n', ' ' ), mov_read_leaf },
1473 { MKTAG( 'u', 'u', 'i', 'd' ), mov_read_leaf },
1474 { MKTAG( 'v', 'm', 'h', 'd' ), mov_read_leaf }, /* video media info header */
1475 { MKTAG( 'w', 'a', 'v', 'e' ), mov_read_wave },
1476 /* extra mp4 */
1477 { MKTAG( 'M', 'D', 'E', 'S' ), mov_read_leaf },
1478 /* QT atoms */
1479 { MKTAG( 'c', 'h', 'a', 'p' ), mov_read_leaf },
1480 { MKTAG( 'c', 'l', 'i', 'p' ), mov_read_default },
1481 { MKTAG( 'c', 'r', 'g', 'n' ), mov_read_leaf },
1482 { MKTAG( 'c', 't', 'a', 'b' ), mov_read_ctab },
1483 { MKTAG( 'e', 's', 'd', 's' ), mov_read_esds },
1484 { MKTAG( 'k', 'm', 'a', 't' ), mov_read_leaf },
1485 { MKTAG( 'm', 'a', 't', 't' ), mov_read_default },
1486 { MKTAG( 'r', 'd', 'r', 'f' ), mov_read_leaf },
1487 { MKTAG( 'r', 'm', 'd', 'a' ), mov_read_default },
1488 { MKTAG( 'r', 'm', 'd', 'r' ), mov_read_leaf },
1489 { MKTAG( 'r', 'm', 'r', 'a' ), mov_read_default },
1490 { MKTAG( 's', 'c', 'p', 't' ), mov_read_leaf },
1491 { MKTAG( 's', 's', 'r', 'c' ), mov_read_leaf },
1492 { MKTAG( 's', 'y', 'n', 'c' ), mov_read_leaf },
1493 { MKTAG( 't', 'c', 'm', 'd' ), mov_read_leaf },
1494 { MKTAG( 'w', 'i', 'd', 'e' ), mov_read_wide }, /* place holder */
1495 //{ MKTAG( 'r', 'm', 'q', 'u' ), mov_read_leaf },
1496 #ifdef CONFIG_ZLIB
1497 { MKTAG( 'c', 'm', 'o', 'v' ), mov_read_cmov },
1498 #else
1499 { MKTAG( 'c', 'm', 'o', 'v' ), mov_read_leaf },
1500 #endif
1501 { 0L, mov_read_leaf }
1502 };
1503
1504 static void mov_free_stream_context(MOVStreamContext *sc)
1505 {
1506     if(sc) {
1507         av_freep(&sc->ctts_data);
1508         av_freep(&sc);
1509     }
1510 }
1511
1512 /* XXX: is it sufficient ? */
1513 static int mov_probe(AVProbeData *p)
1514 {
1515     unsigned int offset;
1516     uint32_t tag;
1517     int score = 0;
1518
1519     /* check file header */
1520     if (p->buf_size <= 12)
1521         return 0;
1522     offset = 0;
1523     for(;;) {
1524         /* ignore invalid offset */
1525         if ((offset + 8) > (unsigned int)p->buf_size)
1526             return score;
1527         tag = LE_32(p->buf + offset + 4);
1528         switch(tag) {
1529         /* check for obvious tags */
1530         case MKTAG( 'j', 'P', ' ', ' ' ): /* jpeg 2000 signature */
1531         case MKTAG( 'm', 'o', 'o', 'v' ):
1532         case MKTAG( 'm', 'd', 'a', 't' ):
1533         case MKTAG( 'p', 'n', 'o', 't' ): /* detect movs with preview pics like ew.mov and april.mov */
1534         case MKTAG( 'u', 'd', 't', 'a' ): /* Packet Video PVAuthor adds this and a lot of more junk */
1535             return AVPROBE_SCORE_MAX;
1536         /* those are more common words, so rate then a bit less */
1537         case MKTAG( 'w', 'i', 'd', 'e' ):
1538         case MKTAG( 'f', 'r', 'e', 'e' ):
1539         case MKTAG( 'j', 'u', 'n', 'k' ):
1540         case MKTAG( 'p', 'i', 'c', 't' ):
1541             return AVPROBE_SCORE_MAX - 5;
1542         case MKTAG( 'f', 't', 'y', 'p' ):
1543         case MKTAG( 's', 'k', 'i', 'p' ):
1544         case MKTAG( 'u', 'u', 'i', 'd' ):
1545             offset = BE_32(p->buf+offset) + offset;
1546             /* if we only find those cause probedata is too small at least rate them */
1547             score = AVPROBE_SCORE_MAX - 50;
1548             break;
1549         default:
1550             /* unrecognized tag */
1551             return score;
1552         }
1553     }
1554     return score;
1555 }
1556
1557 static void mov_build_index(MOVContext *mov, AVStream *st)
1558 {
1559     MOVStreamContext *sc = st->priv_data;
1560     offset_t current_offset;
1561     int64_t current_dts = 0;
1562     int stts_index = 0;
1563     int stsc_index = 0;
1564     int stss_index = 0;
1565     int i, j, k;
1566
1567     if (sc->sample_sizes || st->codec->codec_type == CODEC_TYPE_VIDEO || sc->dv_audio_container) {
1568         int keyframe, sample_size;
1569         int current_sample = 0;
1570         int stts_sample = 0;
1571         int distance = 0;
1572
1573         st->nb_frames = sc->sample_count;
1574         for (i = 0; i < sc->chunk_count; i++) {
1575             current_offset = sc->chunk_offsets[i];
1576             if (stsc_index + 1 < sc->sample_to_chunk_sz && i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1577                 stsc_index++;
1578             for (j = 0; j < sc->sample_to_chunk[stsc_index].count; j++) {
1579                 keyframe = !sc->keyframe_count || current_sample + 1 == sc->keyframes[stss_index];
1580                 if (keyframe) {
1581                     distance = 0;
1582                     if (stss_index + 1 < sc->keyframe_count)
1583                         stss_index++;
1584                 }
1585                 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1586                 dprintf("AVIndex stream %d, sample %d, offset %llx, dts %lld, size %d, distance %d, keyframe %d\n",
1587                         st->index, current_sample, current_offset, current_dts, sample_size, distance, keyframe);
1588                 av_add_index_entry(st, current_offset, current_dts, sample_size, distance, keyframe ? AVINDEX_KEYFRAME : 0);
1589                 current_offset += sample_size;
1590                 assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
1591                 current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
1592                 distance++;
1593                 stts_sample++;
1594                 if (current_sample + 1 < sc->sample_count)
1595                     current_sample++;
1596                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1597                     stts_sample = 0;
1598                     stts_index++;
1599                 }
1600             }
1601         }
1602     } else { /* read whole chunk */
1603         int chunk_samples, chunk_size, chunk_duration;
1604
1605         for (i = 0; i < sc->chunk_count; i++) {
1606             current_offset = sc->chunk_offsets[i];
1607             if (stsc_index + 1 < sc->sample_to_chunk_sz && i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1608                 stsc_index++;
1609             chunk_samples = sc->sample_to_chunk[stsc_index].count;
1610             /* get chunk size */
1611             if (sc->sample_size > 1 || st->codec->codec_id == CODEC_ID_PCM_U8 || st->codec->codec_id == CODEC_ID_PCM_S8)
1612                 chunk_size = chunk_samples * sc->sample_size;
1613             else if (sc->sample_size_v1.den > 0 && (chunk_samples * sc->sample_size_v1.num % sc->sample_size_v1.den == 0))
1614                 chunk_size = chunk_samples * sc->sample_size_v1.num / sc->sample_size_v1.den;
1615             else { /* workaround to find nearest next chunk offset */
1616                 chunk_size = INT_MAX;
1617                 for (j = 0; j < mov->total_streams; j++) {
1618                     MOVStreamContext *msc = mov->streams[j];
1619
1620                     for (k = msc->next_chunk; k < msc->chunk_count; k++) {
1621                         if (msc->chunk_offsets[k] > current_offset && msc->chunk_offsets[k] - current_offset < chunk_size) {
1622                             chunk_size = msc->chunk_offsets[k] - current_offset;
1623                             msc->next_chunk = k;
1624                             break;
1625                         }
1626                     }
1627                 }
1628                 /* check for last chunk */
1629                 if (chunk_size == INT_MAX)
1630                     for (j = 0; j < mov->mdat_count; j++) {
1631                         dprintf("mdat %d, offset %llx, size %lld, current offset %llx\n",
1632                                 j, mov->mdat_list[j].offset, mov->mdat_list[j].size, current_offset);
1633                         if (mov->mdat_list[j].offset <= current_offset && mov->mdat_list[j].offset + mov->mdat_list[j].size > current_offset)
1634                             chunk_size = mov->mdat_list[j].offset + mov->mdat_list[j].size - current_offset;
1635                     }
1636                 assert(chunk_size != INT_MAX);
1637                 for (j = 0; j < mov->total_streams; j++) {
1638                     mov->streams[j]->next_chunk = 0;
1639                 }
1640             }
1641             av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
1642             /* get chunk duration */
1643             chunk_duration = 0;
1644             while (chunk_samples > 0) {
1645                 if (chunk_samples < sc->stts_data[stts_index].count) {
1646                     chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1647                     sc->stts_data[stts_index].count -= chunk_samples;
1648                     break;
1649                 } else {
1650                     chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1651                     chunk_samples -= sc->stts_data[stts_index].count;
1652                     if (stts_index + 1 < sc->stts_count) {
1653                         stts_index++;
1654                     }
1655                 }
1656             }
1657             dprintf("AVIndex stream %d, chunk %d, offset %llx, dts %lld, size %d, duration %d\n",
1658                     st->index, i, current_offset, current_dts, chunk_size, chunk_duration);
1659             assert(chunk_duration % sc->time_rate == 0);
1660             current_dts += chunk_duration / sc->time_rate;
1661         }
1662     }
1663     /* adjust sample count to avindex entries */
1664     sc->sample_count = st->nb_index_entries;
1665 }
1666
1667 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1668 {
1669     MOVContext *mov = (MOVContext *) s->priv_data;
1670     ByteIOContext *pb = &s->pb;
1671     int i, err;
1672     MOV_atom_t atom = { 0, 0, 0 };
1673
1674     mov->fc = s;
1675     mov->parse_table = mov_default_parse_table;
1676
1677     if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1678         atom.size = url_fsize(pb);
1679     else
1680         atom.size = 0x7FFFFFFFFFFFFFFFLL;
1681
1682     /* check MOV header */
1683     err = mov_read_default(mov, pb, atom);
1684     if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
1685         av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%"PRId64"\n",
1686                 err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1687         return -1;
1688     }
1689     dprintf("on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1690
1691     /* some cleanup : make sure we are on the mdat atom */
1692     if(!url_is_streamed(pb) && (url_ftell(pb) != mov->mdat_offset))
1693         url_fseek(pb, mov->mdat_offset, SEEK_SET);
1694
1695     mov->total_streams = s->nb_streams;
1696
1697     for(i=0; i<mov->total_streams; i++) {
1698         MOVStreamContext *sc = mov->streams[i];
1699
1700         if(!sc->time_rate)
1701             sc->time_rate=1;
1702         if(!sc->time_scale)
1703             sc->time_scale= mov->time_scale;
1704         av_set_pts_info(s->streams[i], 64, sc->time_rate, sc->time_scale);
1705
1706         if(s->streams[i]->duration != AV_NOPTS_VALUE){
1707             assert(s->streams[i]->duration % sc->time_rate == 0);
1708             s->streams[i]->duration /= sc->time_rate;
1709         }
1710         sc->ffindex = i;
1711         mov_build_index(mov, s->streams[i]);
1712     }
1713
1714     for(i=0; i<mov->total_streams; i++) {
1715         /* dont need those anymore */
1716         av_freep(&mov->streams[i]->chunk_offsets);
1717         av_freep(&mov->streams[i]->sample_to_chunk);
1718         av_freep(&mov->streams[i]->sample_sizes);
1719         av_freep(&mov->streams[i]->keyframes);
1720         av_freep(&mov->streams[i]->stts_data);
1721     }
1722     av_freep(&mov->mdat_list);
1723     return 0;
1724 }
1725
1726 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1727 {
1728     MOVContext *mov = s->priv_data;
1729     MOVStreamContext *sc = 0;
1730     AVIndexEntry *sample = 0;
1731     int64_t best_dts = INT64_MAX;
1732     int i;
1733
1734     for (i = 0; i < mov->total_streams; i++) {
1735         MOVStreamContext *msc = mov->streams[i];
1736
1737         if (s->streams[i]->discard != AVDISCARD_ALL && msc->current_sample < msc->sample_count) {
1738             AVIndexEntry *current_sample = &s->streams[i]->index_entries[msc->current_sample];
1739             int64_t dts = av_rescale(current_sample->timestamp * (int64_t)msc->time_rate, AV_TIME_BASE, msc->time_scale);
1740
1741             dprintf("stream %d, sample %ld, dts %lld\n", i, msc->current_sample, dts);
1742             if (dts < best_dts) {
1743                 sample = current_sample;
1744                 best_dts = dts;
1745                 sc = msc;
1746             }
1747         }
1748     }
1749     if (!sample)
1750         return -1;
1751     /* must be done just before reading, to avoid infinite loop on sample */
1752     sc->current_sample++;
1753     if (sample->pos >= url_fsize(&s->pb)) {
1754         av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%llx: partial file\n", sc->ffindex, sample->pos);
1755         return -1;
1756     }
1757 #ifdef CONFIG_DV_DEMUXER
1758     if (sc->dv_audio_container) {
1759         dv_get_packet(mov->dv_demux, pkt);
1760         dprintf("dv audio pkt size %d\n", pkt->size);
1761     } else {
1762 #endif
1763         url_fseek(&s->pb, sample->pos, SEEK_SET);
1764         av_get_packet(&s->pb, pkt, sample->size);
1765 #ifdef CONFIG_DV_DEMUXER
1766         if (mov->dv_demux) {
1767             void *pkt_destruct_func = pkt->destruct;
1768             dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
1769             pkt->destruct = pkt_destruct_func;
1770         }
1771     }
1772 #endif
1773     pkt->stream_index = sc->ffindex;
1774     pkt->dts = sample->timestamp;
1775     if (sc->ctts_data) {
1776         assert(sc->ctts_data[sc->sample_to_ctime_index].duration % sc->time_rate == 0);
1777         pkt->pts = pkt->dts + sc->ctts_data[sc->sample_to_ctime_index].duration / sc->time_rate;
1778         /* update ctts context */
1779         sc->sample_to_ctime_sample++;
1780         if (sc->sample_to_ctime_index < sc->ctts_count && sc->ctts_data[sc->sample_to_ctime_index].count == sc->sample_to_ctime_sample) {
1781             sc->sample_to_ctime_index++;
1782             sc->sample_to_ctime_sample = 0;
1783         }
1784     } else {
1785         pkt->pts = pkt->dts;
1786     }
1787     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
1788     pkt->pos = sample->pos;
1789     dprintf("stream %d, pts %lld, dts %lld, pos 0x%llx, duration %d\n", pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
1790     return 0;
1791 }
1792
1793 static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
1794 {
1795     MOVStreamContext *sc = st->priv_data;
1796     int sample, time_sample;
1797     int i;
1798
1799     sample = av_index_search_timestamp(st, timestamp, flags);
1800     dprintf("stream %d, timestamp %lld, sample %d\n", st->index, timestamp, sample);
1801     if (sample < 0) /* not sure what to do */
1802         return -1;
1803     sc->current_sample = sample;
1804     dprintf("stream %d, found sample %ld\n", st->index, sc->current_sample);
1805     /* adjust ctts index */
1806     if (sc->ctts_data) {
1807         time_sample = 0;
1808         for (i = 0; i < sc->ctts_count; i++) {
1809             time_sample += sc->ctts_data[i].count;
1810             if (time_sample >= sc->current_sample) {
1811                 sc->sample_to_ctime_index = i;
1812                 sc->sample_to_ctime_sample = time_sample - sc->current_sample;
1813                 break;
1814             }
1815         }
1816     }
1817     return sample;
1818 }
1819
1820 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1821 {
1822     AVStream *st;
1823     int64_t seek_timestamp, timestamp;
1824     int sample;
1825     int i;
1826
1827     if (stream_index >= s->nb_streams)
1828         return -1;
1829
1830     st = s->streams[stream_index];
1831     sample = mov_seek_stream(st, sample_time, flags);
1832     if (sample < 0)
1833         return -1;
1834
1835     /* adjust seek timestamp to found sample timestamp */
1836     seek_timestamp = st->index_entries[sample].timestamp;
1837
1838     for (i = 0; i < s->nb_streams; i++) {
1839         st = s->streams[i];
1840         if (stream_index == i || st->discard == AVDISCARD_ALL)
1841             continue;
1842
1843         timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
1844         mov_seek_stream(st, timestamp, flags);
1845     }
1846     return 0;
1847 }
1848
1849 static int mov_read_close(AVFormatContext *s)
1850 {
1851     int i;
1852     MOVContext *mov = (MOVContext *) s->priv_data;
1853     for(i=0; i<mov->total_streams; i++)
1854         mov_free_stream_context(mov->streams[i]);
1855     /* free color tabs */
1856     for(i=0; i<mov->ctab_size; i++)
1857         av_freep(&mov->ctab[i]);
1858     if(mov->dv_demux){
1859         for(i=0; i<mov->dv_fctx->nb_streams; i++){
1860             av_freep(&mov->dv_fctx->streams[i]->codec);
1861             av_freep(&mov->dv_fctx->streams[i]);
1862         }
1863         av_freep(&mov->dv_fctx);
1864         av_freep(&mov->dv_demux);
1865     }
1866     av_freep(&mov->ctab);
1867     return 0;
1868 }
1869
1870 AVInputFormat mov_demuxer = {
1871     "mov,mp4,m4a,3gp,3g2,mj2",
1872     "QuickTime/MPEG4/Motion JPEG 2000 format",
1873     sizeof(MOVContext),
1874     mov_probe,
1875     mov_read_header,
1876     mov_read_packet,
1877     mov_read_close,
1878     mov_read_seek,
1879 };