]> git.sesse.net Git - ffmpeg/blob - libavformat/mov.c
44c71f24bd41840616be6425c7b5bca88bfb482d
[ffmpeg] / 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 "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  *   Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
42  * - the code is quite ugly... maybe I won't do it recursive next time :-)
43  *
44  * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
45  * when coding this :) (it's a writer anyway)
46  *
47  * Reference documents:
48  * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
49  * Apple:
50  *  http://developer.apple.com/documentation/QuickTime/QTFF/
51  *  http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
52  * QuickTime is a trademark of Apple (AFAIK :))
53  */
54
55 #include "qtpalette.h"
56
57
58 #undef NDEBUG
59 #include <assert.h>
60
61 /* the QuickTime file format is quite convoluted...
62  * it has lots of index tables, each indexing something in another one...
63  * Here we just use what is needed to read the chunks
64  */
65
66 typedef struct {
67     int first;
68     int count;
69     int id;
70 } MOV_stsc_t;
71
72 typedef struct {
73     uint32_t type;
74     int64_t offset;
75     int64_t size; /* total size (excluding the size and type fields) */
76 } MOV_atom_t;
77
78 typedef struct {
79     offset_t offset;
80     int64_t size;
81 } MOV_mdat_t;
82
83 struct MOVParseTableEntry;
84
85 typedef struct MOVStreamContext {
86     int ffindex; /* the ffmpeg stream id */
87     int next_chunk;
88     unsigned int chunk_count;
89     int64_t *chunk_offsets;
90     unsigned int stts_count;
91     MOV_stts_t *stts_data;
92     unsigned int ctts_count;
93     MOV_stts_t *ctts_data;
94     unsigned int edit_count; /* number of 'edit' (elst atom) */
95     unsigned int sample_to_chunk_sz;
96     MOV_stsc_t *sample_to_chunk;
97     int sample_to_ctime_index;
98     int sample_to_ctime_sample;
99     unsigned int sample_size;
100     unsigned int sample_count;
101     int *sample_sizes;
102     unsigned int keyframe_count;
103     int *keyframes;
104     int time_scale;
105     int time_rate;
106     int current_sample;
107     unsigned int bytes_per_frame;
108     unsigned int samples_per_frame;
109     int dv_audio_container;
110     int pseudo_stream_id;
111     int16_t audio_cid; ///< stsd audio compression id
112 } MOVStreamContext;
113
114 typedef struct MOVContext {
115     AVFormatContext *fc;
116     int time_scale;
117     int64_t duration; /* duration of the longest track */
118     int found_moov; /* when both 'moov' and 'mdat' sections has been found */
119     int found_mdat; /* we suppose we have enough data to read the file */
120     AVPaletteControl palette_control;
121     MOV_mdat_t *mdat_list;
122     int mdat_count;
123     DVDemuxContext *dv_demux;
124     AVFormatContext *dv_fctx;
125     int isom; /* 1 if file is ISO Media (mp4/3gp) */
126 } MOVContext;
127
128
129 /* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
130
131 /* those functions parse an atom */
132 /* return code:
133  1: found what I wanted, exit
134  0: continue to parse next atom
135  -1: error occured, exit
136  */
137 /* links atom IDs to parse functions */
138 typedef struct MOVParseTableEntry {
139     uint32_t type;
140     int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOV_atom_t atom);
141 } MOVParseTableEntry;
142
143 static const MOVParseTableEntry mov_default_parse_table[];
144
145 static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
146 {
147     int64_t total_size = 0;
148     MOV_atom_t a;
149     int i;
150     int err = 0;
151
152     a.offset = atom.offset;
153
154     if (atom.size < 0)
155         atom.size = INT64_MAX;
156     while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
157         a.size = atom.size;
158         a.type=0;
159         if(atom.size >= 8) {
160             a.size = get_be32(pb);
161             a.type = get_le32(pb);
162         }
163         total_size += 8;
164         a.offset += 8;
165         dprintf(c->fc, "type: %08x  %.4s  sz: %"PRIx64"  %"PRIx64"   %"PRIx64"\n",
166                 a.type, (char*)&a.type, a.size, atom.size, total_size);
167         if (a.size == 1) { /* 64 bit extended size */
168             a.size = get_be64(pb) - 8;
169             a.offset += 8;
170             total_size += 8;
171         }
172         if (a.size == 0) {
173             a.size = atom.size - total_size;
174             if (a.size <= 8)
175                 break;
176         }
177         a.size -= 8;
178         if(a.size < 0)
179             break;
180         a.size = FFMIN(a.size, atom.size - total_size);
181
182         for (i = 0; mov_default_parse_table[i].type != 0
183              && mov_default_parse_table[i].type != a.type; i++)
184             /* empty */;
185
186         if (mov_default_parse_table[i].type == 0) { /* skip leaf atoms data */
187             url_fskip(pb, a.size);
188         } else {
189             offset_t start_pos = url_ftell(pb);
190             int64_t left;
191             err = mov_default_parse_table[i].parse(c, pb, a);
192             if (c->found_moov && c->found_mdat)
193                 break;
194             left = a.size - url_ftell(pb) + start_pos;
195             if (left > 0) /* skip garbage at atom end */
196                 url_fskip(pb, left);
197         }
198
199         a.offset += a.size;
200         total_size += a.size;
201     }
202
203     if (!err && total_size < atom.size && atom.size < 0x7ffff) {
204         url_fskip(pb, atom.size - total_size);
205     }
206
207     return err;
208 }
209
210 static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
211 {
212     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
213     uint32_t type;
214     uint32_t ctype;
215
216     get_byte(pb); /* version */
217     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
218
219     /* component type */
220     ctype = get_le32(pb);
221     type = get_le32(pb); /* component subtype */
222
223     dprintf(c->fc, "ctype= %c%c%c%c (0x%08x)\n", *((char *)&ctype), ((char *)&ctype)[1],
224             ((char *)&ctype)[2], ((char *)&ctype)[3], (int) ctype);
225     dprintf(c->fc, "stype= %c%c%c%c\n",
226             *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
227     if(!ctype)
228         c->isom = 1;
229     if(type == MKTAG('v', 'i', 'd', 'e'))
230         st->codec->codec_type = CODEC_TYPE_VIDEO;
231     else if(type == MKTAG('s', 'o', 'u', 'n'))
232         st->codec->codec_type = CODEC_TYPE_AUDIO;
233     else if(type == MKTAG('m', '1', 'a', ' '))
234         st->codec->codec_id = CODEC_ID_MP2;
235     else if(type == MKTAG('s', 'u', 'b', 'p')) {
236         st->codec->codec_type = CODEC_TYPE_SUBTITLE;
237     }
238     get_be32(pb); /* component  manufacture */
239     get_be32(pb); /* component flags */
240     get_be32(pb); /* component flags mask */
241
242     if(atom.size <= 24)
243         return 0; /* nothing left to read */
244
245     url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
246     return 0;
247 }
248
249 static int mp4_read_descr_len(ByteIOContext *pb)
250 {
251     int len = 0;
252     int count = 4;
253     while (count--) {
254         int c = get_byte(pb);
255         len = (len << 7) | (c & 0x7f);
256         if (!(c & 0x80))
257             break;
258     }
259     return len;
260 }
261
262 static int mp4_read_descr(MOVContext *c, ByteIOContext *pb, int *tag)
263 {
264     int len;
265     *tag = get_byte(pb);
266     len = mp4_read_descr_len(pb);
267     dprintf(c->fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
268     return len;
269 }
270
271 #define MP4ESDescrTag                   0x03
272 #define MP4DecConfigDescrTag            0x04
273 #define MP4DecSpecificDescrTag          0x05
274
275 static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
276 {
277     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
278     int tag, len;
279
280     get_be32(pb); /* version + flags */
281     len = mp4_read_descr(c, pb, &tag);
282     if (tag == MP4ESDescrTag) {
283         get_be16(pb); /* ID */
284         get_byte(pb); /* priority */
285     } else
286         get_be16(pb); /* ID */
287
288     len = mp4_read_descr(c, pb, &tag);
289     if (tag == MP4DecConfigDescrTag) {
290         int object_type_id = get_byte(pb);
291         get_byte(pb); /* stream type */
292         get_be24(pb); /* buffer size db */
293         get_be32(pb); /* max bitrate */
294         get_be32(pb); /* avg bitrate */
295
296         st->codec->codec_id= codec_get_id(ff_mp4_obj_type, object_type_id);
297         dprintf(c->fc, "esds object type id %d\n", object_type_id);
298         len = mp4_read_descr(c, pb, &tag);
299         if (tag == MP4DecSpecificDescrTag) {
300             dprintf(c->fc, "Specific MPEG4 header len=%d\n", len);
301             st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
302             if (st->codec->extradata) {
303                 get_buffer(pb, st->codec->extradata, len);
304                 st->codec->extradata_size = len;
305                 /* from mplayer */
306                 if ((*st->codec->extradata >> 3) == 29) {
307                     st->codec->codec_id = CODEC_ID_MP3ON4;
308                 }
309             }
310         }
311     }
312     return 0;
313 }
314
315 /* this atom contains actual media data */
316 static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
317 {
318     if(atom.size == 0) /* wrong one (MP4) */
319         return 0;
320     c->mdat_list = av_realloc(c->mdat_list, (c->mdat_count + 1) * sizeof(*c->mdat_list));
321     c->mdat_list[c->mdat_count].offset = atom.offset;
322     c->mdat_list[c->mdat_count].size = atom.size;
323     c->mdat_count++;
324     c->found_mdat=1;
325     if(c->found_moov)
326         return 1; /* found both, just go */
327     url_fskip(pb, atom.size);
328     return 0; /* now go for moov */
329 }
330
331 static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
332 {
333     uint32_t type = get_le32(pb);
334
335     if (type != MKTAG('q','t',' ',' '))
336         c->isom = 1;
337     av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
338     get_be32(pb); /* minor version */
339     url_fskip(pb, atom.size - 8);
340     return 0;
341 }
342
343 /* this atom should contain all header atoms */
344 static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
345 {
346     if (mov_read_default(c, pb, atom) < 0)
347         return -1;
348     /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
349     /* so we don't parse the whole file if over a network */
350     c->found_moov=1;
351     if(c->found_mdat)
352         return 1; /* found both, just go */
353     return 0; /* now go for mdat */
354 }
355
356
357 static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
358 {
359     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
360     MOVStreamContext *sc = st->priv_data;
361     int version = get_byte(pb);
362     int lang;
363
364     if (version > 1)
365         return 1; /* unsupported */
366
367     get_byte(pb); get_byte(pb);
368     get_byte(pb); /* flags */
369
370     if (version == 1) {
371         get_be64(pb);
372         get_be64(pb);
373     } else {
374         get_be32(pb); /* creation time */
375         get_be32(pb); /* modification time */
376     }
377
378     sc->time_scale = get_be32(pb);
379     st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
380
381     lang = get_be16(pb); /* language */
382     ff_mov_lang_to_iso639(lang, st->language);
383     get_be16(pb); /* quality */
384
385     return 0;
386 }
387
388 static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
389 {
390     int version = get_byte(pb); /* version */
391     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
392
393     if (version == 1) {
394         get_be64(pb);
395         get_be64(pb);
396     } else {
397         get_be32(pb); /* creation time */
398         get_be32(pb); /* modification time */
399     }
400     c->time_scale = get_be32(pb); /* time scale */
401
402     dprintf(c->fc, "time scale = %i\n", c->time_scale);
403
404     c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
405     get_be32(pb); /* preferred scale */
406
407     get_be16(pb); /* preferred volume */
408
409     url_fskip(pb, 10); /* reserved */
410
411     url_fskip(pb, 36); /* display matrix */
412
413     get_be32(pb); /* preview time */
414     get_be32(pb); /* preview duration */
415     get_be32(pb); /* poster time */
416     get_be32(pb); /* selection time */
417     get_be32(pb); /* selection duration */
418     get_be32(pb); /* current time */
419     get_be32(pb); /* next track ID */
420
421     return 0;
422 }
423
424 static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
425 {
426     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
427
428     if((uint64_t)atom.size > (1<<30))
429         return -1;
430
431     // currently SVQ3 decoder expect full STSD header - so let's fake it
432     // this should be fixed and just SMI header should be passed
433     av_free(st->codec->extradata);
434     st->codec->extradata_size = 0x5a + atom.size;
435     st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
436
437     if (st->codec->extradata) {
438         memcpy(st->codec->extradata, "SVQ3", 4); // fake
439         get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
440         dprintf(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
441     } else
442         url_fskip(pb, atom.size);
443
444     return 0;
445 }
446
447 static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
448 {
449     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
450     int little_endian = get_be16(pb);
451
452     if (little_endian) {
453         switch (st->codec->codec_id) {
454         case CODEC_ID_PCM_S24BE:
455             st->codec->codec_id = CODEC_ID_PCM_S24LE;
456             break;
457         case CODEC_ID_PCM_S32BE:
458             st->codec->codec_id = CODEC_ID_PCM_S32LE;
459             break;
460         default:
461             break;
462         }
463     }
464     return 0;
465 }
466
467 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
468 static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
469 {
470     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
471     uint64_t size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
472     uint8_t *buf;
473     if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
474         return -1;
475     buf= av_realloc(st->codec->extradata, size);
476     if(!buf)
477         return -1;
478     st->codec->extradata= buf;
479     buf+= st->codec->extradata_size;
480     st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
481     AV_WB32(       buf    , atom.size + 8);
482     AV_WL32(       buf + 4, atom.type);
483     get_buffer(pb, buf + 8, atom.size);
484     return 0;
485 }
486
487 static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
488 {
489     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
490
491     if((uint64_t)atom.size > (1<<30))
492         return -1;
493
494     if (st->codec->codec_id == CODEC_ID_QDM2) {
495         // pass all frma atom to codec, needed at least for QDM2
496         av_free(st->codec->extradata);
497         st->codec->extradata_size = atom.size;
498         st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
499
500         if (st->codec->extradata) {
501             get_buffer(pb, st->codec->extradata, atom.size);
502         } else
503             url_fskip(pb, atom.size);
504     } else if (atom.size > 8) { /* to read frma, esds atoms */
505         if (mov_read_default(c, pb, atom) < 0)
506             return -1;
507     } else
508         url_fskip(pb, atom.size);
509     return 0;
510 }
511
512 /**
513  * This function reads atom content and puts data in extradata without tag
514  * nor size unlike mov_read_extradata.
515  */
516 static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
517 {
518     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
519
520     if((uint64_t)atom.size > (1<<30))
521         return -1;
522
523     av_free(st->codec->extradata);
524
525     st->codec->extradata_size = atom.size;
526     st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
527
528     if (st->codec->extradata) {
529         get_buffer(pb, st->codec->extradata, atom.size);
530     } else
531         url_fskip(pb, atom.size);
532
533     return 0;
534 }
535
536 static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
537 {
538     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
539     MOVStreamContext *sc = st->priv_data;
540     unsigned int i, entries;
541
542     get_byte(pb); /* version */
543     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
544
545     entries = get_be32(pb);
546
547     if(entries >= UINT_MAX/sizeof(int64_t))
548         return -1;
549
550     sc->chunk_count = entries;
551     sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
552     if (!sc->chunk_offsets)
553         return -1;
554     if (atom.type == MKTAG('s', 't', 'c', 'o')) {
555         for(i=0; i<entries; i++) {
556             sc->chunk_offsets[i] = get_be32(pb);
557         }
558     } else if (atom.type == MKTAG('c', 'o', '6', '4')) {
559         for(i=0; i<entries; i++) {
560             sc->chunk_offsets[i] = get_be64(pb);
561         }
562     } else
563         return -1;
564
565     return 0;
566 }
567
568 static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
569 {
570     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
571     MOVStreamContext *sc = st->priv_data;
572     int entries, frames_per_sample;
573     uint32_t format;
574     uint8_t codec_name[32];
575
576     /* for palette traversal */
577     unsigned int color_depth;
578     unsigned int color_start;
579     unsigned int color_count;
580     unsigned int color_end;
581     int color_index;
582     int color_dec;
583     int color_greyscale;
584     const uint8_t *color_table;
585     int j, pseudo_stream_id;
586     unsigned char r, g, b;
587
588     get_byte(pb); /* version */
589     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
590
591     entries = get_be32(pb);
592
593     for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) { //Parsing Sample description table
594         enum CodecID id;
595         MOV_atom_t a = { 0, 0, 0 };
596         offset_t start_pos = url_ftell(pb);
597         int size = get_be32(pb); /* size */
598         format = get_le32(pb); /* data format */
599
600         get_be32(pb); /* reserved */
601         get_be16(pb); /* reserved */
602         get_be16(pb); /* index */
603
604         if (st->codec->codec_tag &&
605             (c->fc->video_codec_id ? codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
606                                    : st->codec->codec_tag != MKTAG('j', 'p', 'e', 'g'))
607            ){
608             /* multiple fourcc, we skip jpeg, this isnt correct, we should export it as
609                seperate AVStream but this needs a few changes in the mov demuxer, patch
610                welcome */
611             url_fskip(pb, size - (url_ftell(pb) - start_pos));
612             continue;
613         }
614         sc->pseudo_stream_id= pseudo_stream_id;
615
616         st->codec->codec_tag = format;
617         id = codec_get_id(codec_movaudio_tags, format);
618         if (id<=0 && (format&0xFFFF) == 'm' + ('s'<<8))
619             id = codec_get_id(codec_wav_tags, bswap_32(format)&0xFFFF);
620
621         if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
622             st->codec->codec_type = CODEC_TYPE_AUDIO;
623         } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
624                    format && format != MKTAG('m', 'p', '4', 's')) { /* skip old asf mpeg4 tag */
625             id = codec_get_id(codec_movvideo_tags, format);
626             if (id <= 0)
627                 id = codec_get_id(codec_bmp_tags, format);
628             if (id > 0)
629                 st->codec->codec_type = CODEC_TYPE_VIDEO;
630             else if(st->codec->codec_type == CODEC_TYPE_DATA){
631                 id = codec_get_id(ff_codec_movsubtitle_tags, format);
632                 if(id > 0)
633                     st->codec->codec_type = CODEC_TYPE_SUBTITLE;
634             }
635         }
636
637         dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
638                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
639                 (format >> 24) & 0xff, st->codec->codec_type);
640
641         if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
642             st->codec->codec_id = id;
643             get_be16(pb); /* version */
644             get_be16(pb); /* revision level */
645             get_be32(pb); /* vendor */
646             get_be32(pb); /* temporal quality */
647             get_be32(pb); /* spatial quality */
648
649             st->codec->width = get_be16(pb); /* width */
650             st->codec->height = get_be16(pb); /* height */
651
652             get_be32(pb); /* horiz resolution */
653             get_be32(pb); /* vert resolution */
654             get_be32(pb); /* data size, always 0 */
655             frames_per_sample = get_be16(pb); /* frames per samples */
656
657             dprintf(c->fc, "frames/samples = %d\n", frames_per_sample);
658
659             get_buffer(pb, codec_name, 32); /* codec name, pascal string (FIXME: true for mp4?) */
660             if (codec_name[0] <= 31) {
661                 memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
662                 st->codec->codec_name[codec_name[0]] = 0;
663             }
664
665             st->codec->bits_per_sample = get_be16(pb); /* depth */
666             st->codec->color_table_id = get_be16(pb); /* colortable id */
667
668             /* figure out the palette situation */
669             color_depth = st->codec->bits_per_sample & 0x1F;
670             color_greyscale = st->codec->bits_per_sample & 0x20;
671
672             /* if the depth is 2, 4, or 8 bpp, file is palettized */
673             if ((color_depth == 2) || (color_depth == 4) ||
674                 (color_depth == 8)) {
675                 if (color_greyscale) {
676                     /* compute the greyscale palette */
677                     color_count = 1 << color_depth;
678                     color_index = 255;
679                     color_dec = 256 / (color_count - 1);
680                     for (j = 0; j < color_count; j++) {
681                         r = g = b = color_index;
682                         c->palette_control.palette[j] =
683                             (r << 16) | (g << 8) | (b);
684                         color_index -= color_dec;
685                         if (color_index < 0)
686                             color_index = 0;
687                     }
688                 } else if (st->codec->color_table_id & 0x08) {
689                     /* if flag bit 3 is set, use the default palette */
690                     color_count = 1 << color_depth;
691                     if (color_depth == 2)
692                         color_table = ff_qt_default_palette_4;
693                     else if (color_depth == 4)
694                         color_table = ff_qt_default_palette_16;
695                     else
696                         color_table = ff_qt_default_palette_256;
697
698                     for (j = 0; j < color_count; j++) {
699                         r = color_table[j * 4 + 0];
700                         g = color_table[j * 4 + 1];
701                         b = color_table[j * 4 + 2];
702                         c->palette_control.palette[j] =
703                             (r << 16) | (g << 8) | (b);
704                     }
705                 } else {
706                     /* load the palette from the file */
707                     color_start = get_be32(pb);
708                     color_count = get_be16(pb);
709                     color_end = get_be16(pb);
710                     if ((color_start <= 255) &&
711                         (color_end <= 255)) {
712                         for (j = color_start; j <= color_end; j++) {
713                             /* each R, G, or B component is 16 bits;
714                              * only use the top 8 bits; skip alpha bytes
715                              * up front */
716                             get_byte(pb);
717                             get_byte(pb);
718                             r = get_byte(pb);
719                             get_byte(pb);
720                             g = get_byte(pb);
721                             get_byte(pb);
722                             b = get_byte(pb);
723                             get_byte(pb);
724                             c->palette_control.palette[j] =
725                                 (r << 16) | (g << 8) | (b);
726                         }
727                     }
728                 }
729                 st->codec->palctrl = &c->palette_control;
730                 st->codec->palctrl->palette_changed = 1;
731             } else
732                 st->codec->palctrl = NULL;
733         } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
734             int bits_per_sample;
735             uint16_t version = get_be16(pb);
736
737             st->codec->codec_id = id;
738             get_be16(pb); /* revision level */
739             get_be32(pb); /* vendor */
740
741             st->codec->channels = get_be16(pb);             /* channel count */
742             dprintf(c->fc, "audio channels %d\n", st->codec->channels);
743             st->codec->bits_per_sample = get_be16(pb);      /* sample size */
744
745             sc->audio_cid = get_be16(pb);
746             get_be16(pb); /* packet size = 0 */
747
748             st->codec->sample_rate = ((get_be32(pb) >> 16));
749
750             switch (st->codec->codec_id) {
751             case CODEC_ID_PCM_S8:
752             case CODEC_ID_PCM_U8:
753                 if (st->codec->bits_per_sample == 16)
754                     st->codec->codec_id = CODEC_ID_PCM_S16BE;
755                 break;
756             case CODEC_ID_PCM_S16LE:
757             case CODEC_ID_PCM_S16BE:
758                 if (st->codec->bits_per_sample == 8)
759                     st->codec->codec_id = CODEC_ID_PCM_S8;
760                 else if (st->codec->bits_per_sample == 24)
761                     st->codec->codec_id = CODEC_ID_PCM_S24BE;
762                 break;
763             /* set values for old format before stsd version 1 appeared */
764             case CODEC_ID_MACE3:
765                 sc->samples_per_frame = 6;
766                 sc->bytes_per_frame = 2*st->codec->channels;
767                 break;
768             case CODEC_ID_MACE6:
769                 sc->samples_per_frame = 6;
770                 sc->bytes_per_frame = 1*st->codec->channels;
771                 break;
772             case CODEC_ID_ADPCM_IMA_QT:
773                 sc->samples_per_frame = 64;
774                 sc->bytes_per_frame = 34*st->codec->channels;
775                 break;
776             default:
777                 break;
778             }
779
780             //Read QT version 1 fields. In version 0 these do not exist.
781             dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
782             if(!c->isom) {
783                 if(version==1) {
784                     sc->samples_per_frame = get_be32(pb);
785                     get_be32(pb); /* bytes per packet */
786                     sc->bytes_per_frame = get_be32(pb);
787                     get_be32(pb); /* bytes per sample */
788                 } else if(version==2) {
789                     get_be32(pb); /* sizeof struct only */
790                     st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
791                     st->codec->channels = get_be32(pb);
792                     get_be32(pb); /* always 0x7F000000 */
793                     get_be32(pb); /* bits per channel if sound is uncompressed */
794                     get_be32(pb); /* lcpm format specific flag */
795                     get_be32(pb); /* bytes per audio packet if constant */
796                     get_be32(pb); /* lpcm frames per audio packet if constant */
797                 }
798             }
799
800             bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
801             if (bits_per_sample) {
802                 st->codec->bits_per_sample = bits_per_sample;
803                 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
804             }
805         } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){
806             st->codec->codec_id= id;
807         } else {
808             /* other codec type, just skip (rtp, mp4s, tmcd ...) */
809             url_fskip(pb, size - (url_ftell(pb) - start_pos));
810         }
811         /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
812         a.size = size - (url_ftell(pb) - start_pos);
813         if (a.size > 8) {
814             if (mov_read_default(c, pb, a) < 0)
815                 return -1;
816         } else if (a.size > 0)
817             url_fskip(pb, a.size);
818     }
819
820     if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1) {
821         st->codec->sample_rate= sc->time_scale;
822     }
823
824     /* special codec parameters handling */
825     switch (st->codec->codec_id) {
826 #ifdef CONFIG_H261_DECODER
827     case CODEC_ID_H261:
828 #endif
829 #ifdef CONFIG_H263_DECODER
830     case CODEC_ID_H263:
831 #endif
832 #ifdef CONFIG_MPEG4_DECODER
833     case CODEC_ID_MPEG4:
834 #endif
835         st->codec->width= 0; /* let decoder init width/height */
836         st->codec->height= 0;
837         break;
838 #ifdef CONFIG_LIBFAAD
839     case CODEC_ID_AAC:
840 #endif
841 #ifdef CONFIG_VORBIS_DECODER
842     case CODEC_ID_VORBIS:
843 #endif
844     case CODEC_ID_MP3ON4:
845         st->codec->sample_rate= 0; /* let decoder init parameters properly */
846         break;
847 #ifdef CONFIG_DV_DEMUXER
848     case CODEC_ID_DVAUDIO:
849         c->dv_fctx = av_alloc_format_context();
850         c->dv_demux = dv_init_demux(c->dv_fctx);
851         if (!c->dv_demux) {
852             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
853             return -1;
854         }
855         sc->dv_audio_container = 1;
856         st->codec->codec_id = CODEC_ID_PCM_S16LE;
857         break;
858 #endif
859     /* no ifdef since parameters are always those */
860     case CODEC_ID_AMR_WB:
861         st->codec->sample_rate= 16000;
862         st->codec->channels= 1; /* really needed */
863         break;
864     case CODEC_ID_AMR_NB:
865         st->codec->sample_rate= 8000;
866         st->codec->channels= 1; /* really needed */
867         break;
868     case CODEC_ID_MP2:
869     case CODEC_ID_MP3:
870         st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
871         st->need_parsing = AVSTREAM_PARSE_FULL;
872         break;
873     case CODEC_ID_ADPCM_MS:
874     case CODEC_ID_ADPCM_IMA_WAV:
875         st->codec->block_align = sc->bytes_per_frame;
876         break;
877     default:
878         break;
879     }
880
881     return 0;
882 }
883
884 static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
885 {
886     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
887     MOVStreamContext *sc = st->priv_data;
888     unsigned int i, entries;
889
890     get_byte(pb); /* version */
891     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
892
893     entries = get_be32(pb);
894
895     if(entries >= UINT_MAX / sizeof(MOV_stsc_t))
896         return -1;
897
898     dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
899
900     sc->sample_to_chunk_sz = entries;
901     sc->sample_to_chunk = av_malloc(entries * sizeof(MOV_stsc_t));
902     if (!sc->sample_to_chunk)
903         return -1;
904     for(i=0; i<entries; i++) {
905         sc->sample_to_chunk[i].first = get_be32(pb);
906         sc->sample_to_chunk[i].count = get_be32(pb);
907         sc->sample_to_chunk[i].id = get_be32(pb);
908     }
909     return 0;
910 }
911
912 static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
913 {
914     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
915     MOVStreamContext *sc = st->priv_data;
916     unsigned int i, entries;
917
918     get_byte(pb); /* version */
919     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
920
921     entries = get_be32(pb);
922
923     if(entries >= UINT_MAX / sizeof(int))
924         return -1;
925
926     sc->keyframe_count = entries;
927
928     dprintf(c->fc, "keyframe_count = %d\n", sc->keyframe_count);
929
930     sc->keyframes = av_malloc(entries * sizeof(int));
931     if (!sc->keyframes)
932         return -1;
933     for(i=0; i<entries; i++) {
934         sc->keyframes[i] = get_be32(pb);
935         //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
936     }
937     return 0;
938 }
939
940 static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
941 {
942     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
943     MOVStreamContext *sc = st->priv_data;
944     unsigned int i, entries, sample_size;
945
946     get_byte(pb); /* version */
947     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
948
949     sample_size = get_be32(pb);
950     if (!sc->sample_size) /* do not overwrite value computed in stsd */
951         sc->sample_size = sample_size;
952     entries = get_be32(pb);
953     if(entries >= UINT_MAX / sizeof(int))
954         return -1;
955
956     sc->sample_count = entries;
957     if (sample_size)
958         return 0;
959
960     dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, sc->sample_count);
961
962     sc->sample_sizes = av_malloc(entries * sizeof(int));
963     if (!sc->sample_sizes)
964         return -1;
965     for(i=0; i<entries; i++) {
966         sc->sample_sizes[i] = get_be32(pb);
967         dprintf(c->fc, "sample_sizes[]=%d\n", sc->sample_sizes[i]);
968     }
969     return 0;
970 }
971
972 static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
973 {
974     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
975     MOVStreamContext *sc = st->priv_data;
976     unsigned int i, entries;
977     int64_t duration=0;
978     int64_t total_sample_count=0;
979
980     get_byte(pb); /* version */
981     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
982     entries = get_be32(pb);
983     if(entries >= UINT_MAX / sizeof(MOV_stts_t))
984         return -1;
985
986     sc->stts_count = entries;
987     sc->stts_data = av_malloc(entries * sizeof(MOV_stts_t));
988     if (!sc->stts_data)
989         return -1;
990     dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
991
992     sc->time_rate=0;
993
994     for(i=0; i<entries; i++) {
995         int sample_duration;
996         int sample_count;
997
998         sample_count=get_be32(pb);
999         sample_duration = get_be32(pb);
1000         sc->stts_data[i].count= sample_count;
1001         sc->stts_data[i].duration= sample_duration;
1002
1003         sc->time_rate= ff_gcd(sc->time_rate, sample_duration);
1004
1005         dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1006
1007         duration+=(int64_t)sample_duration*sample_count;
1008         total_sample_count+=sample_count;
1009     }
1010
1011     st->nb_frames= total_sample_count;
1012     if(duration)
1013         st->duration= duration;
1014     return 0;
1015 }
1016
1017 static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1018 {
1019     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1020     MOVStreamContext *sc = st->priv_data;
1021     unsigned int i, entries;
1022
1023     get_byte(pb); /* version */
1024     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1025     entries = get_be32(pb);
1026     if(entries >= UINT_MAX / sizeof(MOV_stts_t))
1027         return -1;
1028
1029     sc->ctts_count = entries;
1030     sc->ctts_data = av_malloc(entries * sizeof(MOV_stts_t));
1031     if (!sc->ctts_data)
1032         return -1;
1033     dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1034
1035     for(i=0; i<entries; i++) {
1036         int count    =get_be32(pb);
1037         int duration =get_be32(pb);
1038
1039         if (duration < 0) {
1040             av_log(c->fc, AV_LOG_ERROR, "negative ctts, ignoring\n");
1041             sc->ctts_count = 0;
1042             url_fskip(pb, 8 * (entries - i - 1));
1043             break;
1044         }
1045         sc->ctts_data[i].count   = count;
1046         sc->ctts_data[i].duration= duration;
1047
1048         sc->time_rate= ff_gcd(sc->time_rate, duration);
1049     }
1050     return 0;
1051 }
1052
1053 static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1054 {
1055     AVStream *st;
1056     MOVStreamContext *sc;
1057
1058     st = av_new_stream(c->fc, c->fc->nb_streams);
1059     if (!st) return -2;
1060     sc = av_mallocz(sizeof(MOVStreamContext));
1061     if (!sc) {
1062         av_free(st);
1063         return -1;
1064     }
1065
1066     st->priv_data = sc;
1067     st->codec->codec_type = CODEC_TYPE_DATA;
1068     st->start_time = 0; /* XXX: check */
1069
1070     return mov_read_default(c, pb, atom);
1071 }
1072
1073 static void mov_parse_udta_string(ByteIOContext *pb, char *str, int size)
1074 {
1075     uint16_t str_size = get_be16(pb); /* string length */;
1076
1077     get_be16(pb); /* skip language */
1078     get_buffer(pb, str, FFMIN(size, str_size));
1079 }
1080
1081 static int mov_read_udta(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1082 {
1083     uint64_t end = url_ftell(pb) + atom.size;
1084
1085     while (url_ftell(pb) + 8 < end) {
1086         uint32_t tag_size = get_be32(pb);
1087         uint32_t tag      = get_le32(pb);
1088         uint64_t next     = url_ftell(pb) + tag_size - 8;
1089
1090         if (next > end) // stop if tag_size is wrong
1091             break;
1092
1093         switch (tag) {
1094         case MKTAG(0xa9,'n','a','m'):
1095             mov_parse_udta_string(pb, c->fc->title,     sizeof(c->fc->title));
1096             break;
1097         case MKTAG(0xa9,'w','r','t'):
1098             mov_parse_udta_string(pb, c->fc->author,    sizeof(c->fc->author));
1099             break;
1100         case MKTAG(0xa9,'c','p','y'):
1101             mov_parse_udta_string(pb, c->fc->copyright, sizeof(c->fc->copyright));
1102             break;
1103         case MKTAG(0xa9,'i','n','f'):
1104             mov_parse_udta_string(pb, c->fc->comment,   sizeof(c->fc->comment));
1105             break;
1106         default:
1107             break;
1108         }
1109
1110         url_fseek(pb, next, SEEK_SET);
1111     }
1112
1113     return 0;
1114 }
1115
1116 static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1117 {
1118     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1119     int version = get_byte(pb);
1120
1121     get_byte(pb); get_byte(pb);
1122     get_byte(pb); /* flags */
1123     /*
1124     MOV_TRACK_ENABLED 0x0001
1125     MOV_TRACK_IN_MOVIE 0x0002
1126     MOV_TRACK_IN_PREVIEW 0x0004
1127     MOV_TRACK_IN_POSTER 0x0008
1128     */
1129
1130     if (version == 1) {
1131         get_be64(pb);
1132         get_be64(pb);
1133     } else {
1134         get_be32(pb); /* creation time */
1135         get_be32(pb); /* modification time */
1136     }
1137     st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1138     get_be32(pb); /* reserved */
1139     st->start_time = 0; /* check */
1140     (version == 1) ? get_be64(pb) : get_be32(pb); /* highlevel (considering edits) duration in movie timebase */
1141     get_be32(pb); /* reserved */
1142     get_be32(pb); /* reserved */
1143
1144     get_be16(pb); /* layer */
1145     get_be16(pb); /* alternate group */
1146     get_be16(pb); /* volume */
1147     get_be16(pb); /* reserved */
1148
1149     url_fskip(pb, 36); /* display matrix */
1150
1151     /* those are fixed-point */
1152     get_be32(pb); /* track width */
1153     get_be32(pb); /* track height */
1154
1155     return 0;
1156 }
1157
1158 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1159 /* like the files created with Adobe Premiere 5.0, for samples see */
1160 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1161 static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1162 {
1163     int err;
1164
1165     if (atom.size < 8)
1166         return 0; /* continue */
1167     if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1168         url_fskip(pb, atom.size - 4);
1169         return 0;
1170     }
1171     atom.type = get_le32(pb);
1172     atom.offset += 8;
1173     atom.size -= 8;
1174     if (atom.type != MKTAG('m', 'd', 'a', 't')) {
1175         url_fskip(pb, atom.size);
1176         return 0;
1177     }
1178     err = mov_read_mdat(c, pb, atom);
1179     return err;
1180 }
1181
1182 static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1183 {
1184 #ifdef CONFIG_ZLIB
1185     ByteIOContext ctx;
1186     uint8_t *cmov_data;
1187     uint8_t *moov_data; /* uncompressed data */
1188     long cmov_len, moov_len;
1189     int ret;
1190
1191     get_be32(pb); /* dcom atom */
1192     if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
1193         return -1;
1194     if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
1195         av_log(NULL, AV_LOG_ERROR, "unknown compression for cmov atom !");
1196         return -1;
1197     }
1198     get_be32(pb); /* cmvd atom */
1199     if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
1200         return -1;
1201     moov_len = get_be32(pb); /* uncompressed size */
1202     cmov_len = atom.size - 6 * 4;
1203
1204     cmov_data = av_malloc(cmov_len);
1205     if (!cmov_data)
1206         return -1;
1207     moov_data = av_malloc(moov_len);
1208     if (!moov_data) {
1209         av_free(cmov_data);
1210         return -1;
1211     }
1212     get_buffer(pb, cmov_data, cmov_len);
1213     if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1214         return -1;
1215     if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
1216         return -1;
1217     atom.type = MKTAG( 'm', 'o', 'o', 'v' );
1218     atom.offset = 0;
1219     atom.size = moov_len;
1220 #ifdef DEBUG
1221 //    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1222 #endif
1223     ret = mov_read_default(c, &ctx, atom);
1224     av_free(moov_data);
1225     av_free(cmov_data);
1226     return ret;
1227 #else
1228     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
1229     return -1;
1230 #endif
1231 }
1232
1233 /* edit list atom */
1234 static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1235 {
1236     MOVStreamContext *sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
1237     int i, edit_count;
1238
1239     get_byte(pb); /* version */
1240     get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1241     edit_count= sc->edit_count = get_be32(pb);     /* entries */
1242
1243     for(i=0; i<edit_count; i++){
1244         get_be32(pb); /* Track duration */
1245         get_be32(pb); /* Media time */
1246         get_be32(pb); /* Media rate */
1247     }
1248     dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, sc->edit_count);
1249     return 0;
1250 }
1251
1252 static const MOVParseTableEntry mov_default_parse_table[] = {
1253 /* mp4 atoms */
1254 { MKTAG( 'c', 'o', '6', '4' ), mov_read_stco },
1255 { MKTAG( 'c', 't', 't', 's' ), mov_read_ctts }, /* composition time to sample */
1256 { MKTAG( 'e', 'd', 't', 's' ), mov_read_default },
1257 { MKTAG( 'e', 'l', 's', 't' ), mov_read_elst },
1258 { MKTAG( 'e', 'n', 'd', 'a' ), mov_read_enda },
1259 { MKTAG( 'f', 'i', 'e', 'l' ), mov_read_extradata },
1260 { MKTAG( 'f', 't', 'y', 'p' ), mov_read_ftyp },
1261 { MKTAG( 'g', 'l', 'b', 'l' ), mov_read_glbl },
1262 { MKTAG( 'h', 'd', 'l', 'r' ), mov_read_hdlr },
1263 { MKTAG( 'j', 'p', '2', 'h' ), mov_read_extradata },
1264 { MKTAG( 'm', 'd', 'a', 't' ), mov_read_mdat },
1265 { MKTAG( 'm', 'd', 'h', 'd' ), mov_read_mdhd },
1266 { MKTAG( 'm', 'd', 'i', 'a' ), mov_read_default },
1267 { MKTAG( 'm', 'i', 'n', 'f' ), mov_read_default },
1268 { MKTAG( 'm', 'o', 'o', 'v' ), mov_read_moov },
1269 { MKTAG( 'm', 'v', 'h', 'd' ), mov_read_mvhd },
1270 { MKTAG( 'S', 'M', 'I', ' ' ), mov_read_smi }, /* Sorenson extension ??? */
1271 { MKTAG( 'a', 'l', 'a', 'c' ), mov_read_extradata }, /* alac specific atom */
1272 { MKTAG( 'a', 'v', 'c', 'C' ), mov_read_glbl },
1273 { MKTAG( 's', 't', 'b', 'l' ), mov_read_default },
1274 { MKTAG( 's', 't', 'c', 'o' ), mov_read_stco },
1275 { MKTAG( 's', 't', 's', 'c' ), mov_read_stsc },
1276 { MKTAG( 's', 't', 's', 'd' ), mov_read_stsd }, /* sample description */
1277 { MKTAG( 's', 't', 's', 's' ), mov_read_stss }, /* sync sample */
1278 { MKTAG( 's', 't', 's', 'z' ), mov_read_stsz }, /* sample size */
1279 { MKTAG( 's', 't', 't', 's' ), mov_read_stts },
1280 { MKTAG( 't', 'k', 'h', 'd' ), mov_read_tkhd }, /* track header */
1281 { MKTAG( 't', 'r', 'a', 'k' ), mov_read_trak },
1282 { MKTAG( 'u', 'd', 't', 'a' ), mov_read_udta },
1283 { MKTAG( 'w', 'a', 'v', 'e' ), mov_read_wave },
1284 { MKTAG( 'e', 's', 'd', 's' ), mov_read_esds },
1285 { MKTAG( 'w', 'i', 'd', 'e' ), mov_read_wide }, /* place holder */
1286 { MKTAG( 'c', 'm', 'o', 'v' ), mov_read_cmov },
1287 { 0, NULL }
1288 };
1289
1290 /* XXX: is it sufficient ? */
1291 static int mov_probe(AVProbeData *p)
1292 {
1293     unsigned int offset;
1294     uint32_t tag;
1295     int score = 0;
1296
1297     /* check file header */
1298     offset = 0;
1299     for(;;) {
1300         /* ignore invalid offset */
1301         if ((offset + 8) > (unsigned int)p->buf_size)
1302             return score;
1303         tag = AV_RL32(p->buf + offset + 4);
1304         switch(tag) {
1305         /* check for obvious tags */
1306         case MKTAG( 'j', 'P', ' ', ' ' ): /* jpeg 2000 signature */
1307         case MKTAG( 'm', 'o', 'o', 'v' ):
1308         case MKTAG( 'm', 'd', 'a', 't' ):
1309         case MKTAG( 'p', 'n', 'o', 't' ): /* detect movs with preview pics like ew.mov and april.mov */
1310         case MKTAG( 'u', 'd', 't', 'a' ): /* Packet Video PVAuthor adds this and a lot of more junk */
1311             return AVPROBE_SCORE_MAX;
1312         /* those are more common words, so rate then a bit less */
1313         case MKTAG( 'e', 'd', 'i', 'w' ): /* xdcam files have reverted first tags */
1314         case MKTAG( 'w', 'i', 'd', 'e' ):
1315         case MKTAG( 'f', 'r', 'e', 'e' ):
1316         case MKTAG( 'j', 'u', 'n', 'k' ):
1317         case MKTAG( 'p', 'i', 'c', 't' ):
1318             return AVPROBE_SCORE_MAX - 5;
1319         case MKTAG( 'f', 't', 'y', 'p' ):
1320         case MKTAG( 's', 'k', 'i', 'p' ):
1321         case MKTAG( 'u', 'u', 'i', 'd' ):
1322             offset = AV_RB32(p->buf+offset) + offset;
1323             /* if we only find those cause probedata is too small at least rate them */
1324             score = AVPROBE_SCORE_MAX - 50;
1325             break;
1326         default:
1327             /* unrecognized tag */
1328             return score;
1329         }
1330     }
1331     return score;
1332 }
1333
1334 static void mov_build_index(MOVContext *mov, AVStream *st)
1335 {
1336     MOVStreamContext *sc = st->priv_data;
1337     offset_t current_offset;
1338     int64_t current_dts = 0;
1339     unsigned int stts_index = 0;
1340     unsigned int stsc_index = 0;
1341     unsigned int stss_index = 0;
1342     unsigned int i, j;
1343
1344     if (sc->sample_sizes || st->codec->codec_type == CODEC_TYPE_VIDEO ||
1345         sc->audio_cid == -2) {
1346         unsigned int current_sample = 0;
1347         unsigned int stts_sample = 0;
1348         unsigned int keyframe, sample_size;
1349         unsigned int distance = 0;
1350
1351         st->nb_frames = sc->sample_count;
1352         for (i = 0; i < sc->chunk_count; i++) {
1353             current_offset = sc->chunk_offsets[i];
1354             if (stsc_index + 1 < sc->sample_to_chunk_sz &&
1355                 i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1356                 stsc_index++;
1357             for (j = 0; j < sc->sample_to_chunk[stsc_index].count; j++) {
1358                 if (current_sample >= sc->sample_count) {
1359                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1360                     goto out;
1361                 }
1362                 keyframe = !sc->keyframe_count || current_sample + 1 == sc->keyframes[stss_index];
1363                 if (keyframe) {
1364                     distance = 0;
1365                     if (stss_index + 1 < sc->keyframe_count)
1366                         stss_index++;
1367                 }
1368                 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1369                 dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1370                         "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1371                         current_offset, current_dts, sample_size, distance, keyframe);
1372                 if(sc->sample_to_chunk[stsc_index].id - 1 == sc->pseudo_stream_id)
1373                     av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
1374                                     keyframe ? AVINDEX_KEYFRAME : 0);
1375                 current_offset += sample_size;
1376                 assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
1377                 current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
1378                 distance++;
1379                 stts_sample++;
1380                 current_sample++;
1381                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1382                     stts_sample = 0;
1383                     stts_index++;
1384                 }
1385             }
1386         }
1387     } else { /* read whole chunk */
1388         unsigned int chunk_samples, chunk_size, chunk_duration;
1389         unsigned int frames = 1;
1390         for (i = 0; i < sc->chunk_count; i++) {
1391             current_offset = sc->chunk_offsets[i];
1392             if (stsc_index + 1 < sc->sample_to_chunk_sz &&
1393                 i + 1 == sc->sample_to_chunk[stsc_index + 1].first)
1394                 stsc_index++;
1395             chunk_samples = sc->sample_to_chunk[stsc_index].count;
1396             /* get chunk size */
1397             if (sc->sample_size > 1 ||
1398                 st->codec->codec_id == CODEC_ID_PCM_U8 || st->codec->codec_id == CODEC_ID_PCM_S8)
1399                 chunk_size = chunk_samples * sc->sample_size;
1400             else if (sc->samples_per_frame > 0 &&
1401                      (chunk_samples * sc->bytes_per_frame % sc->samples_per_frame == 0)) {
1402                 if (sc->samples_per_frame < 1024)
1403                     chunk_size = chunk_samples * sc->bytes_per_frame / sc->samples_per_frame;
1404                 else {
1405                     chunk_size = sc->bytes_per_frame;
1406                     frames = chunk_samples / sc->samples_per_frame;
1407                     chunk_samples = sc->samples_per_frame;
1408                 }
1409             } else {
1410                 av_log(mov->fc, AV_LOG_ERROR, "could not determine chunk size, report problem\n");
1411                 goto out;
1412             }
1413             for (j = 0; j < frames; j++) {
1414             av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
1415             /* get chunk duration */
1416             chunk_duration = 0;
1417             while (chunk_samples > 0) {
1418                 if (chunk_samples < sc->stts_data[stts_index].count) {
1419                     chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1420                     sc->stts_data[stts_index].count -= chunk_samples;
1421                     break;
1422                 } else {
1423                     chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
1424                     chunk_samples -= sc->stts_data[stts_index].count;
1425                     if (stts_index + 1 < sc->stts_count)
1426                         stts_index++;
1427                 }
1428             }
1429             current_offset += sc->bytes_per_frame;
1430             dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", size %d, "
1431                     "duration %d\n", st->index, i, current_offset, current_dts, chunk_size, chunk_duration);
1432             assert(chunk_duration % sc->time_rate == 0);
1433             current_dts += chunk_duration / sc->time_rate;
1434             }
1435         }
1436     }
1437  out:
1438     /* adjust sample count to avindex entries */
1439     sc->sample_count = st->nb_index_entries;
1440 }
1441
1442 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1443 {
1444     MOVContext *mov = s->priv_data;
1445     ByteIOContext *pb = s->pb;
1446     int i, err;
1447     MOV_atom_t atom = { 0, 0, 0 };
1448
1449     mov->fc = s;
1450
1451     if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1452         atom.size = url_fsize(pb);
1453     else
1454         atom.size = INT64_MAX;
1455
1456     /* check MOV header */
1457     err = mov_read_default(mov, pb, atom);
1458     if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
1459         av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%"PRId64"\n",
1460                 err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1461         return -1;
1462     }
1463     dprintf(mov->fc, "on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1464
1465     for(i=0; i<s->nb_streams; i++) {
1466         AVStream *st = s->streams[i];
1467         MOVStreamContext *sc = st->priv_data;
1468         /* sanity checks */
1469         if(!sc->stts_count || !sc->chunk_count || !sc->sample_to_chunk_sz ||
1470            (!sc->sample_size && !sc->sample_count)){
1471             av_log(s, AV_LOG_ERROR, "missing mandatory atoms, broken header\n");
1472             sc->sample_count = 0; //ignore track
1473             continue;
1474         }
1475         if(!sc->time_rate)
1476             sc->time_rate=1;
1477         if(!sc->time_scale)
1478             sc->time_scale= mov->time_scale;
1479         av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
1480
1481         if (st->codec->codec_type == CODEC_TYPE_AUDIO && sc->stts_count == 1)
1482             st->codec->frame_size = sc->stts_data[0].duration;
1483
1484         if(st->duration != AV_NOPTS_VALUE){
1485             assert(st->duration % sc->time_rate == 0);
1486             st->duration /= sc->time_rate;
1487         }
1488         sc->ffindex = i;
1489         mov_build_index(mov, st);
1490     }
1491
1492     for(i=0; i<s->nb_streams; i++) {
1493         MOVStreamContext *sc = s->streams[i]->priv_data;
1494         /* Do not need those anymore. */
1495         av_freep(&sc->chunk_offsets);
1496         av_freep(&sc->sample_to_chunk);
1497         av_freep(&sc->sample_sizes);
1498         av_freep(&sc->keyframes);
1499         av_freep(&sc->stts_data);
1500     }
1501     av_freep(&mov->mdat_list);
1502     return 0;
1503 }
1504
1505 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1506 {
1507     MOVContext *mov = s->priv_data;
1508     MOVStreamContext *sc = 0;
1509     AVIndexEntry *sample = 0;
1510     int64_t best_dts = INT64_MAX;
1511     int i;
1512
1513     for (i = 0; i < s->nb_streams; i++) {
1514         AVStream *st = s->streams[i];
1515         MOVStreamContext *msc = st->priv_data;
1516         if (st->discard != AVDISCARD_ALL && msc->current_sample < msc->sample_count) {
1517             AVIndexEntry *current_sample = &st->index_entries[msc->current_sample];
1518             int64_t dts = av_rescale(current_sample->timestamp * (int64_t)msc->time_rate,
1519                                      AV_TIME_BASE, msc->time_scale);
1520             dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
1521             if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
1522                 (!url_is_streamed(s->pb) &&
1523                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
1524                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))) {
1525                 sample = current_sample;
1526                 best_dts = dts;
1527                 sc = msc;
1528             }
1529         }
1530     }
1531     if (!sample)
1532         return -1;
1533     /* must be done just before reading, to avoid infinite loop on sample */
1534     sc->current_sample++;
1535     if (url_fseek(s->pb, sample->pos, SEEK_SET) != sample->pos) {
1536         av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
1537                sc->ffindex, sample->pos);
1538         return -1;
1539     }
1540     av_get_packet(s->pb, pkt, sample->size);
1541 #ifdef CONFIG_DV_DEMUXER
1542     if (mov->dv_demux && sc->dv_audio_container) {
1543         dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
1544         av_free(pkt->data);
1545         pkt->size = 0;
1546         if (dv_get_packet(mov->dv_demux, pkt) < 0)
1547             return -1;
1548     }
1549 #endif
1550     pkt->stream_index = sc->ffindex;
1551     pkt->dts = sample->timestamp;
1552     if (sc->ctts_data) {
1553         assert(sc->ctts_data[sc->sample_to_ctime_index].duration % sc->time_rate == 0);
1554         pkt->pts = pkt->dts + sc->ctts_data[sc->sample_to_ctime_index].duration / sc->time_rate;
1555         /* update ctts context */
1556         sc->sample_to_ctime_sample++;
1557         if (sc->sample_to_ctime_index < sc->ctts_count &&
1558             sc->ctts_data[sc->sample_to_ctime_index].count == sc->sample_to_ctime_sample) {
1559             sc->sample_to_ctime_index++;
1560             sc->sample_to_ctime_sample = 0;
1561         }
1562     } else {
1563         pkt->pts = pkt->dts;
1564     }
1565     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
1566     pkt->pos = sample->pos;
1567     dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
1568             pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
1569     return 0;
1570 }
1571
1572 static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
1573 {
1574     MOVStreamContext *sc = st->priv_data;
1575     int sample, time_sample;
1576     int i;
1577
1578     sample = av_index_search_timestamp(st, timestamp, flags);
1579     dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
1580     if (sample < 0) /* not sure what to do */
1581         return -1;
1582     sc->current_sample = sample;
1583     dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
1584     /* adjust ctts index */
1585     if (sc->ctts_data) {
1586         time_sample = 0;
1587         for (i = 0; i < sc->ctts_count; i++) {
1588             int next = time_sample + sc->ctts_data[i].count;
1589             if (next > sc->current_sample) {
1590                 sc->sample_to_ctime_index = i;
1591                 sc->sample_to_ctime_sample = sc->current_sample - time_sample;
1592                 break;
1593             }
1594             time_sample = next;
1595         }
1596     }
1597     return sample;
1598 }
1599
1600 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
1601 {
1602     AVStream *st;
1603     int64_t seek_timestamp, timestamp;
1604     int sample;
1605     int i;
1606
1607     if (stream_index >= s->nb_streams)
1608         return -1;
1609
1610     st = s->streams[stream_index];
1611     sample = mov_seek_stream(st, sample_time, flags);
1612     if (sample < 0)
1613         return -1;
1614
1615     /* adjust seek timestamp to found sample timestamp */
1616     seek_timestamp = st->index_entries[sample].timestamp;
1617
1618     for (i = 0; i < s->nb_streams; i++) {
1619         st = s->streams[i];
1620         if (stream_index == i || st->discard == AVDISCARD_ALL)
1621             continue;
1622
1623         timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
1624         mov_seek_stream(st, timestamp, flags);
1625     }
1626     return 0;
1627 }
1628
1629 static int mov_read_close(AVFormatContext *s)
1630 {
1631     int i;
1632     MOVContext *mov = s->priv_data;
1633     for(i=0; i<s->nb_streams; i++) {
1634         MOVStreamContext *sc = s->streams[i]->priv_data;
1635         av_freep(&sc->ctts_data);
1636     }
1637     if(mov->dv_demux){
1638         for(i=0; i<mov->dv_fctx->nb_streams; i++){
1639             av_freep(&mov->dv_fctx->streams[i]->codec);
1640             av_freep(&mov->dv_fctx->streams[i]);
1641         }
1642         av_freep(&mov->dv_fctx);
1643         av_freep(&mov->dv_demux);
1644     }
1645     return 0;
1646 }
1647
1648 AVInputFormat mov_demuxer = {
1649     "mov,mp4,m4a,3gp,3g2,mj2",
1650     "QuickTime/MPEG4/Motion JPEG 2000 format",
1651     sizeof(MOVContext),
1652     mov_probe,
1653     mov_read_header,
1654     mov_read_packet,
1655     mov_read_close,
1656     mov_read_seek,
1657 };