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