• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • File List
  • Globals

libavformat/mov.c

Go to the documentation of this file.
00001 /*
00002  * MOV demuxer
00003  * Copyright (c) 2001 Fabrice Bellard
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 #include <limits.h>
00023 
00024 //#define DEBUG
00025 
00026 #include "libavutil/intreadwrite.h"
00027 #include "libavutil/avstring.h"
00028 #include "avformat.h"
00029 #include "riff.h"
00030 #include "isom.h"
00031 #include "dv.h"
00032 #include "libavcodec/mpeg4audio.h"
00033 #include "libavcodec/mpegaudiodata.h"
00034 
00035 #if CONFIG_ZLIB
00036 #include <zlib.h>
00037 #endif
00038 
00039 /*
00040  * First version by Francois Revol revol@free.fr
00041  * Seek function by Gael Chardon gael.dev@4now.net
00042  *
00043  * Features and limitations:
00044  * - reads most of the QT files I have (at least the structure),
00045  *   Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
00046  * - the code is quite ugly... maybe I won't do it recursive next time :-)
00047  *
00048  * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
00049  * when coding this :) (it's a writer anyway)
00050  *
00051  * Reference documents:
00052  * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
00053  * Apple:
00054  *  http://developer.apple.com/documentation/QuickTime/QTFF/
00055  *  http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
00056  * QuickTime is a trademark of Apple (AFAIK :))
00057  */
00058 
00059 #include "qtpalette.h"
00060 
00061 
00062 #undef NDEBUG
00063 #include <assert.h>
00064 
00065 /* the QuickTime file format is quite convoluted...
00066  * it has lots of index tables, each indexing something in another one...
00067  * Here we just use what is needed to read the chunks
00068  */
00069 
00070 typedef struct {
00071     int first;
00072     int count;
00073     int id;
00074 } MOVStsc;
00075 
00076 typedef struct {
00077     uint32_t type;
00078     char *path;
00079 } MOVDref;
00080 
00081 typedef struct {
00082     uint32_t type;
00083     int64_t offset;
00084     int64_t size; /* total size (excluding the size and type fields) */
00085 } MOVAtom;
00086 
00087 struct MOVParseTableEntry;
00088 
00089 typedef struct {
00090     unsigned track_id;
00091     uint64_t base_data_offset;
00092     uint64_t moof_offset;
00093     unsigned stsd_id;
00094     unsigned duration;
00095     unsigned size;
00096     unsigned flags;
00097 } MOVFragment;
00098 
00099 typedef struct {
00100     unsigned track_id;
00101     unsigned stsd_id;
00102     unsigned duration;
00103     unsigned size;
00104     unsigned flags;
00105 } MOVTrackExt;
00106 
00107 typedef struct MOVStreamContext {
00108     ByteIOContext *pb;
00109     int ffindex; /* the ffmpeg stream id */
00110     int next_chunk;
00111     unsigned int chunk_count;
00112     int64_t *chunk_offsets;
00113     unsigned int stts_count;
00114     MOVStts *stts_data;
00115     unsigned int ctts_count;
00116     MOVStts *ctts_data;
00117     unsigned int stsc_count;
00118     MOVStsc *stsc_data;
00119     int ctts_index;
00120     int ctts_sample;
00121     unsigned int sample_size;
00122     unsigned int sample_count;
00123     int *sample_sizes;
00124     unsigned int keyframe_count;
00125     int *keyframes;
00126     int time_scale;
00127     int time_rate;
00128     int time_offset; 
00129     int current_sample;
00130     unsigned int bytes_per_frame;
00131     unsigned int samples_per_frame;
00132     int dv_audio_container;
00133     int pseudo_stream_id; 
00134     int16_t audio_cid; 
00135     unsigned drefs_count;
00136     MOVDref *drefs;
00137     int dref_id;
00138     int wrong_dts; 
00139     int width;  
00140     int height; 
00141 } MOVStreamContext;
00142 
00143 typedef struct MOVContext {
00144     AVFormatContext *fc;
00145     int time_scale;
00146     int64_t duration; /* duration of the longest track */
00147     int found_moov; /* when both 'moov' and 'mdat' sections has been found */
00148     int found_mdat; /* we suppose we have enough data to read the file */
00149     AVPaletteControl palette_control;
00150     DVDemuxContext *dv_demux;
00151     AVFormatContext *dv_fctx;
00152     int isom; /* 1 if file is ISO Media (mp4/3gp) */
00153     MOVFragment fragment; 
00154     MOVTrackExt *trex_data;
00155     unsigned trex_count;
00156     int itunes_metadata; 
00157 } MOVContext;
00158 
00159 
00160 /* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
00161 
00162 /* those functions parse an atom */
00163 /* return code:
00164   0: continue to parse next atom
00165  <0: error occurred, exit
00166 */
00167 /* links atom IDs to parse functions */
00168 typedef struct MOVParseTableEntry {
00169     uint32_t type;
00170     int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOVAtom atom);
00171 } MOVParseTableEntry;
00172 
00173 static const MOVParseTableEntry mov_default_parse_table[];
00174 
00175 static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00176 {
00177     int64_t total_size = 0;
00178     MOVAtom a;
00179     int i;
00180     int err = 0;
00181 
00182     a.offset = atom.offset;
00183 
00184     if (atom.size < 0)
00185         atom.size = INT64_MAX;
00186     while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
00187         a.size = atom.size;
00188         a.type=0;
00189         if(atom.size >= 8) {
00190             a.size = get_be32(pb);
00191             a.type = get_le32(pb);
00192         }
00193         total_size += 8;
00194         a.offset += 8;
00195         dprintf(c->fc, "type: %08x  %.4s  sz: %"PRIx64"  %"PRIx64"   %"PRIx64"\n",
00196                 a.type, (char*)&a.type, a.size, atom.size, total_size);
00197         if (a.size == 1) { /* 64 bit extended size */
00198             a.size = get_be64(pb) - 8;
00199             a.offset += 8;
00200             total_size += 8;
00201         }
00202         if (a.size == 0) {
00203             a.size = atom.size - total_size;
00204             if (a.size <= 8)
00205                 break;
00206         }
00207         a.size -= 8;
00208         if(a.size < 0)
00209             break;
00210         a.size = FFMIN(a.size, atom.size - total_size);
00211 
00212         for (i = 0; mov_default_parse_table[i].type != 0
00213              && mov_default_parse_table[i].type != a.type; i++)
00214             /* empty */;
00215 
00216         if (mov_default_parse_table[i].type == 0) { /* skip leaf atoms data */
00217             url_fskip(pb, a.size);
00218         } else {
00219             int64_t start_pos = url_ftell(pb);
00220             int64_t left;
00221             err = mov_default_parse_table[i].parse(c, pb, a);
00222             if (url_is_streamed(pb) && c->found_moov && c->found_mdat)
00223                 break;
00224             left = a.size - url_ftell(pb) + start_pos;
00225             if (left > 0) /* skip garbage at atom end */
00226                 url_fskip(pb, left);
00227         }
00228 
00229         a.offset += a.size;
00230         total_size += a.size;
00231     }
00232 
00233     if (!err && total_size < atom.size && atom.size < 0x7ffff)
00234         url_fskip(pb, atom.size - total_size);
00235 
00236     return err;
00237 }
00238 
00239 static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00240 {
00241     AVStream *st;
00242     MOVStreamContext *sc;
00243     int entries, i, j;
00244 
00245     if (c->fc->nb_streams < 1)
00246         return 0;
00247     st = c->fc->streams[c->fc->nb_streams-1];
00248     sc = st->priv_data;
00249 
00250     get_be32(pb); // version + flags
00251     entries = get_be32(pb);
00252     if (entries >= UINT_MAX / sizeof(*sc->drefs))
00253         return -1;
00254     sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
00255     if (!sc->drefs)
00256         return AVERROR(ENOMEM);
00257     sc->drefs_count = entries;
00258 
00259     for (i = 0; i < sc->drefs_count; i++) {
00260         MOVDref *dref = &sc->drefs[i];
00261         uint32_t size = get_be32(pb);
00262         int64_t next = url_ftell(pb) + size - 4;
00263 
00264         dref->type = get_le32(pb);
00265         get_be32(pb); // version + flags
00266         dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
00267 
00268         if (dref->type == MKTAG('a','l','i','s') && size > 150) {
00269             /* macintosh alias record */
00270             uint16_t volume_len, len;
00271             char volume[28];
00272             int16_t type;
00273 
00274             url_fskip(pb, 10);
00275 
00276             volume_len = get_byte(pb);
00277             volume_len = FFMIN(volume_len, 27);
00278             get_buffer(pb, volume, 27);
00279             volume[volume_len] = 0;
00280             av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", volume, volume_len);
00281 
00282             url_fskip(pb, 112);
00283 
00284             for (type = 0; type != -1 && url_ftell(pb) < next; ) {
00285                 type = get_be16(pb);
00286                 len = get_be16(pb);
00287                 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
00288                 if (len&1)
00289                     len += 1;
00290                 if (type == 2) { // absolute path
00291                     av_free(dref->path);
00292                     dref->path = av_mallocz(len+1);
00293                     if (!dref->path)
00294                         return AVERROR(ENOMEM);
00295                     get_buffer(pb, dref->path, len);
00296                     if (len > volume_len && !strncmp(dref->path, volume, volume_len)) {
00297                         len -= volume_len;
00298                         memmove(dref->path, dref->path+volume_len, len);
00299                         dref->path[len] = 0;
00300                     }
00301                     for (j = 0; j < len; j++)
00302                         if (dref->path[j] == ':')
00303                             dref->path[j] = '/';
00304                     av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
00305                 } else
00306                     url_fskip(pb, len);
00307             }
00308         }
00309         url_fseek(pb, next, SEEK_SET);
00310     }
00311     return 0;
00312 }
00313 
00314 static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00315 {
00316     AVStream *st = c->fc->streams[c->fc->nb_streams-1];
00317     uint32_t type;
00318     uint32_t ctype;
00319 
00320     get_byte(pb); /* version */
00321     get_be24(pb); /* flags */
00322 
00323     /* component type */
00324     ctype = get_le32(pb);
00325     type = get_le32(pb); /* component subtype */
00326 
00327     dprintf(c->fc, "ctype= %c%c%c%c (0x%08x)\n", *((char *)&ctype), ((char *)&ctype)[1],
00328             ((char *)&ctype)[2], ((char *)&ctype)[3], (int) ctype);
00329     dprintf(c->fc, "stype= %c%c%c%c\n",
00330             *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
00331     if(!ctype)
00332         c->isom = 1;
00333     if     (type == MKTAG('v','i','d','e'))
00334         st->codec->codec_type = CODEC_TYPE_VIDEO;
00335     else if(type == MKTAG('s','o','u','n'))
00336         st->codec->codec_type = CODEC_TYPE_AUDIO;
00337     else if(type == MKTAG('m','1','a',' '))
00338         st->codec->codec_id = CODEC_ID_MP2;
00339     else if(type == MKTAG('s','u','b','p')) {
00340         st->codec->codec_type = CODEC_TYPE_SUBTITLE;
00341     }
00342     get_be32(pb); /* component  manufacture */
00343     get_be32(pb); /* component flags */
00344     get_be32(pb); /* component flags mask */
00345 
00346     if(atom.size <= 24)
00347         return 0; /* nothing left to read */
00348 
00349     url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
00350     return 0;
00351 }
00352 
00353 static int mp4_read_descr_len(ByteIOContext *pb)
00354 {
00355     int len = 0;
00356     int count = 4;
00357     while (count--) {
00358         int c = get_byte(pb);
00359         len = (len << 7) | (c & 0x7f);
00360         if (!(c & 0x80))
00361             break;
00362     }
00363     return len;
00364 }
00365 
00366 static int mp4_read_descr(MOVContext *c, ByteIOContext *pb, int *tag)
00367 {
00368     int len;
00369     *tag = get_byte(pb);
00370     len = mp4_read_descr_len(pb);
00371     dprintf(c->fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
00372     return len;
00373 }
00374 
00375 #define MP4ESDescrTag                   0x03
00376 #define MP4DecConfigDescrTag            0x04
00377 #define MP4DecSpecificDescrTag          0x05
00378 
00379 static const AVCodecTag mp4_audio_types[] = {
00380     { CODEC_ID_MP3ON4, 29 }, /* old mp3on4 draft */
00381     { CODEC_ID_MP3ON4, 32 }, /* layer 1 */
00382     { CODEC_ID_MP3ON4, 33 }, /* layer 2 */
00383     { CODEC_ID_MP3ON4, 34 }, /* layer 3 */
00384     { CODEC_ID_NONE,    0 },
00385 };
00386 
00387 static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00388 {
00389     AVStream *st;
00390     int tag, len;
00391 
00392     if (c->fc->nb_streams < 1)
00393         return 0;
00394     st = c->fc->streams[c->fc->nb_streams-1];
00395 
00396     get_be32(pb); /* version + flags */
00397     len = mp4_read_descr(c, pb, &tag);
00398     if (tag == MP4ESDescrTag) {
00399         get_be16(pb); /* ID */
00400         get_byte(pb); /* priority */
00401     } else
00402         get_be16(pb); /* ID */
00403 
00404     len = mp4_read_descr(c, pb, &tag);
00405     if (tag == MP4DecConfigDescrTag) {
00406         int object_type_id = get_byte(pb);
00407         get_byte(pb); /* stream type */
00408         get_be24(pb); /* buffer size db */
00409         get_be32(pb); /* max bitrate */
00410         get_be32(pb); /* avg bitrate */
00411 
00412         st->codec->codec_id= codec_get_id(ff_mp4_obj_type, object_type_id);
00413         dprintf(c->fc, "esds object type id %d\n", object_type_id);
00414         len = mp4_read_descr(c, pb, &tag);
00415         if (tag == MP4DecSpecificDescrTag) {
00416             dprintf(c->fc, "Specific MPEG4 header len=%d\n", len);
00417             if((uint64_t)len > (1<<30))
00418                 return -1;
00419             st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
00420             if (!st->codec->extradata)
00421                 return AVERROR(ENOMEM);
00422             get_buffer(pb, st->codec->extradata, len);
00423             st->codec->extradata_size = len;
00424             if (st->codec->codec_id == CODEC_ID_AAC) {
00425                 MPEG4AudioConfig cfg;
00426                 ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
00427                                          st->codec->extradata_size);
00428                 if (cfg.chan_config > 7)
00429                     return -1;
00430                 st->codec->channels = ff_mpeg4audio_channels[cfg.chan_config];
00431                 if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
00432                     st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
00433                 else
00434                     st->codec->sample_rate = cfg.sample_rate; // ext sample rate ?
00435                 dprintf(c->fc, "mp4a config channels %d obj %d ext obj %d "
00436                         "sample rate %d ext sample rate %d\n", st->codec->channels,
00437                         cfg.object_type, cfg.ext_object_type,
00438                         cfg.sample_rate, cfg.ext_sample_rate);
00439                 if (!(st->codec->codec_id = codec_get_id(mp4_audio_types,
00440                                                          cfg.object_type)))
00441                     st->codec->codec_id = CODEC_ID_AAC;
00442             }
00443         }
00444     }
00445     return 0;
00446 }
00447 
00448 static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00449 {
00450     const int num = get_be32(pb);
00451     const int den = get_be32(pb);
00452     AVStream *st;
00453 
00454     if (c->fc->nb_streams < 1)
00455         return 0;
00456     st = c->fc->streams[c->fc->nb_streams-1];
00457 
00458     if (den != 0) {
00459         if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
00460             (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))
00461             av_log(c->fc, AV_LOG_WARNING,
00462                    "sample aspect ratio already set to %d:%d, overriding by 'pasp' atom\n",
00463                    st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
00464         st->sample_aspect_ratio.num = num;
00465         st->sample_aspect_ratio.den = den;
00466     }
00467     return 0;
00468 }
00469 
00470 /* this atom contains actual media data */
00471 static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00472 {
00473     if(atom.size == 0) /* wrong one (MP4) */
00474         return 0;
00475     c->found_mdat=1;
00476     return 0; /* now go for moov */
00477 }
00478 
00479 static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00480 {
00481     uint32_t type = get_le32(pb);
00482 
00483     if (type != MKTAG('q','t',' ',' '))
00484         c->isom = 1;
00485     av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
00486     get_be32(pb); /* minor version */
00487     url_fskip(pb, atom.size - 8);
00488     return 0;
00489 }
00490 
00491 /* this atom should contain all header atoms */
00492 static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00493 {
00494     if (mov_read_default(c, pb, atom) < 0)
00495         return -1;
00496     /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
00497     /* so we don't parse the whole file if over a network */
00498     c->found_moov=1;
00499     return 0; /* now go for mdat */
00500 }
00501 
00502 static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00503 {
00504     c->fragment.moof_offset = url_ftell(pb) - 8;
00505     dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
00506     return mov_read_default(c, pb, atom);
00507 }
00508 
00509 static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00510 {
00511     AVStream *st;
00512     MOVStreamContext *sc;
00513     int version;
00514     char language[4] = {0};
00515     unsigned lang;
00516 
00517     if (c->fc->nb_streams < 1)
00518         return 0;
00519     st = c->fc->streams[c->fc->nb_streams-1];
00520     sc = st->priv_data;
00521 
00522     version = get_byte(pb);
00523     if (version > 1)
00524         return -1; /* unsupported */
00525 
00526     get_be24(pb); /* flags */
00527     if (version == 1) {
00528         get_be64(pb);
00529         get_be64(pb);
00530     } else {
00531         get_be32(pb); /* creation time */
00532         get_be32(pb); /* modification time */
00533     }
00534 
00535     sc->time_scale = get_be32(pb);
00536     st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
00537 
00538     lang = get_be16(pb); /* language */
00539     if (ff_mov_lang_to_iso639(lang, language))
00540         av_metadata_set(&st->metadata, "language", language);
00541     get_be16(pb); /* quality */
00542 
00543     return 0;
00544 }
00545 
00546 static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00547 {
00548     int version = get_byte(pb); /* version */
00549     get_be24(pb); /* flags */
00550 
00551     if (version == 1) {
00552         get_be64(pb);
00553         get_be64(pb);
00554     } else {
00555         get_be32(pb); /* creation time */
00556         get_be32(pb); /* modification time */
00557     }
00558     c->time_scale = get_be32(pb); /* time scale */
00559 
00560     dprintf(c->fc, "time scale = %i\n", c->time_scale);
00561 
00562     c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
00563     get_be32(pb); /* preferred scale */
00564 
00565     get_be16(pb); /* preferred volume */
00566 
00567     url_fskip(pb, 10); /* reserved */
00568 
00569     url_fskip(pb, 36); /* display matrix */
00570 
00571     get_be32(pb); /* preview time */
00572     get_be32(pb); /* preview duration */
00573     get_be32(pb); /* poster time */
00574     get_be32(pb); /* selection time */
00575     get_be32(pb); /* selection duration */
00576     get_be32(pb); /* current time */
00577     get_be32(pb); /* next track ID */
00578 
00579     return 0;
00580 }
00581 
00582 static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00583 {
00584     AVStream *st;
00585 
00586     if (c->fc->nb_streams < 1)
00587         return 0;
00588     st = c->fc->streams[c->fc->nb_streams-1];
00589 
00590     if((uint64_t)atom.size > (1<<30))
00591         return -1;
00592 
00593     // currently SVQ3 decoder expect full STSD header - so let's fake it
00594     // this should be fixed and just SMI header should be passed
00595     av_free(st->codec->extradata);
00596     st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
00597     if (!st->codec->extradata)
00598         return AVERROR(ENOMEM);
00599     st->codec->extradata_size = 0x5a + atom.size;
00600     memcpy(st->codec->extradata, "SVQ3", 4); // fake
00601     get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
00602     dprintf(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
00603     return 0;
00604 }
00605 
00606 static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00607 {
00608     AVStream *st;
00609     int little_endian;
00610 
00611     if (c->fc->nb_streams < 1)
00612         return 0;
00613     st = c->fc->streams[c->fc->nb_streams-1];
00614 
00615     little_endian = get_be16(pb);
00616     dprintf(c->fc, "enda %d\n", little_endian);
00617     if (little_endian == 1) {
00618         switch (st->codec->codec_id) {
00619         case CODEC_ID_PCM_S24BE:
00620             st->codec->codec_id = CODEC_ID_PCM_S24LE;
00621             break;
00622         case CODEC_ID_PCM_S32BE:
00623             st->codec->codec_id = CODEC_ID_PCM_S32LE;
00624             break;
00625         case CODEC_ID_PCM_F32BE:
00626             st->codec->codec_id = CODEC_ID_PCM_F32LE;
00627             break;
00628         case CODEC_ID_PCM_F64BE:
00629             st->codec->codec_id = CODEC_ID_PCM_F64LE;
00630             break;
00631         default:
00632             break;
00633         }
00634     }
00635     return 0;
00636 }
00637 
00638 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
00639 static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00640 {
00641     AVStream *st;
00642     uint64_t size;
00643     uint8_t *buf;
00644 
00645     if (c->fc->nb_streams < 1) // will happen with jp2 files
00646         return 0;
00647     st= c->fc->streams[c->fc->nb_streams-1];
00648     size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
00649     if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
00650         return -1;
00651     buf= av_realloc(st->codec->extradata, size);
00652     if(!buf)
00653         return -1;
00654     st->codec->extradata= buf;
00655     buf+= st->codec->extradata_size;
00656     st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
00657     AV_WB32(       buf    , atom.size + 8);
00658     AV_WL32(       buf + 4, atom.type);
00659     get_buffer(pb, buf + 8, atom.size);
00660     return 0;
00661 }
00662 
00663 static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00664 {
00665     AVStream *st;
00666 
00667     if (c->fc->nb_streams < 1)
00668         return 0;
00669     st = c->fc->streams[c->fc->nb_streams-1];
00670 
00671     if((uint64_t)atom.size > (1<<30))
00672         return -1;
00673 
00674     if (st->codec->codec_id == CODEC_ID_QDM2) {
00675         // pass all frma atom to codec, needed at least for QDM2
00676         av_free(st->codec->extradata);
00677         st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
00678         if (!st->codec->extradata)
00679             return AVERROR(ENOMEM);
00680         st->codec->extradata_size = atom.size;
00681         get_buffer(pb, st->codec->extradata, atom.size);
00682     } else if (atom.size > 8) { /* to read frma, esds atoms */
00683         if (mov_read_default(c, pb, atom) < 0)
00684             return -1;
00685     } else
00686         url_fskip(pb, atom.size);
00687     return 0;
00688 }
00689 
00694 static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00695 {
00696     AVStream *st;
00697 
00698     if (c->fc->nb_streams < 1)
00699         return 0;
00700     st = c->fc->streams[c->fc->nb_streams-1];
00701 
00702     if((uint64_t)atom.size > (1<<30))
00703         return -1;
00704 
00705     av_free(st->codec->extradata);
00706     st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
00707     if (!st->codec->extradata)
00708         return AVERROR(ENOMEM);
00709     st->codec->extradata_size = atom.size;
00710     get_buffer(pb, st->codec->extradata, atom.size);
00711     return 0;
00712 }
00713 
00714 static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00715 {
00716     AVStream *st;
00717     MOVStreamContext *sc;
00718     unsigned int i, entries;
00719 
00720     if (c->fc->nb_streams < 1)
00721         return 0;
00722     st = c->fc->streams[c->fc->nb_streams-1];
00723     sc = st->priv_data;
00724 
00725     get_byte(pb); /* version */
00726     get_be24(pb); /* flags */
00727 
00728     entries = get_be32(pb);
00729 
00730     if(entries >= UINT_MAX/sizeof(int64_t))
00731         return -1;
00732 
00733     sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
00734     if (!sc->chunk_offsets)
00735         return AVERROR(ENOMEM);
00736     sc->chunk_count = entries;
00737 
00738     if      (atom.type == MKTAG('s','t','c','o'))
00739         for(i=0; i<entries; i++)
00740             sc->chunk_offsets[i] = get_be32(pb);
00741     else if (atom.type == MKTAG('c','o','6','4'))
00742         for(i=0; i<entries; i++)
00743             sc->chunk_offsets[i] = get_be64(pb);
00744     else
00745         return -1;
00746 
00747     return 0;
00748 }
00749 
00754 static enum CodecID mov_get_lpcm_codec_id(int bps, int flags)
00755 {
00756     if (flags & 1) { // floating point
00757         if (flags & 2) { // big endian
00758             if      (bps == 32) return CODEC_ID_PCM_F32BE;
00759             else if (bps == 64) return CODEC_ID_PCM_F64BE;
00760         } else {
00761             if      (bps == 32) return CODEC_ID_PCM_F32LE;
00762             else if (bps == 64) return CODEC_ID_PCM_F64LE;
00763         }
00764     } else {
00765         if (flags & 2) {
00766             if      (bps == 8)
00767                 // signed integer
00768                 if (flags & 4)  return CODEC_ID_PCM_S8;
00769                 else            return CODEC_ID_PCM_U8;
00770             else if (bps == 16) return CODEC_ID_PCM_S16BE;
00771             else if (bps == 24) return CODEC_ID_PCM_S24BE;
00772             else if (bps == 32) return CODEC_ID_PCM_S32BE;
00773         } else {
00774             if      (bps == 8)
00775                 if (flags & 4)  return CODEC_ID_PCM_S8;
00776                 else            return CODEC_ID_PCM_U8;
00777             else if (bps == 16) return CODEC_ID_PCM_S16LE;
00778             else if (bps == 24) return CODEC_ID_PCM_S24LE;
00779             else if (bps == 32) return CODEC_ID_PCM_S32LE;
00780         }
00781     }
00782     return CODEC_ID_NONE;
00783 }
00784 
00785 static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
00786 {
00787     AVStream *st;
00788     MOVStreamContext *sc;
00789     int j, entries, pseudo_stream_id;
00790 
00791     if (c->fc->nb_streams < 1)
00792         return 0;
00793     st = c->fc->streams[c->fc->nb_streams-1];
00794     sc = st->priv_data;
00795 
00796     get_byte(pb); /* version */
00797     get_be24(pb); /* flags */
00798 
00799     entries = get_be32(pb);
00800 
00801     for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
00802         //Parsing Sample description table
00803         enum CodecID id;
00804         int dref_id;
00805         MOVAtom a = { 0, 0, 0 };
00806         int64_t start_pos = url_ftell(pb);
00807         int size = get_be32(pb); /* size */
00808         uint32_t format = get_le32(pb); /* data format */
00809 
00810         get_be32(pb); /* reserved */
00811         get_be16(pb); /* reserved */
00812         dref_id = get_be16(pb);
00813 
00814         if (st->codec->codec_tag &&
00815             st->codec->codec_tag != format &&
00816             (c->fc->video_codec_id ? codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
00817                                    : st->codec->codec_tag != MKTAG('j','p','e','g'))
00818            ){
00819             /* Multiple fourcc, we skip JPEG. This is not correct, we should
00820              * export it as a separate AVStream but this needs a few changes
00821              * in the MOV demuxer, patch welcome. */
00822             av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
00823             url_fskip(pb, size - (url_ftell(pb) - start_pos));
00824             continue;
00825         }
00826         sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
00827         sc->dref_id= dref_id;
00828 
00829         st->codec->codec_tag = format;
00830         id = codec_get_id(codec_movaudio_tags, format);
00831         if (id<=0 && (format&0xFFFF) == 'm'+('s'<<8))
00832             id = codec_get_id(codec_wav_tags, bswap_32(format)&0xFFFF);
00833 
00834         if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
00835             st->codec->codec_type = CODEC_TYPE_AUDIO;
00836         } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
00837                    format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
00838             id = codec_get_id(codec_movvideo_tags, format);
00839             if (id <= 0)
00840                 id = codec_get_id(codec_bmp_tags, format);
00841             if (id > 0)
00842                 st->codec->codec_type = CODEC_TYPE_VIDEO;
00843             else if(st->codec->codec_type == CODEC_TYPE_DATA){
00844                 id = codec_get_id(ff_codec_movsubtitle_tags, format);
00845                 if(id > 0)
00846                     st->codec->codec_type = CODEC_TYPE_SUBTITLE;
00847             }
00848         }
00849 
00850         dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
00851                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
00852                 (format >> 24) & 0xff, st->codec->codec_type);
00853 
00854         if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
00855             uint8_t codec_name[32];
00856             unsigned int color_depth;
00857             int color_greyscale;
00858 
00859             st->codec->codec_id = id;
00860             get_be16(pb); /* version */
00861             get_be16(pb); /* revision level */
00862             get_be32(pb); /* vendor */
00863             get_be32(pb); /* temporal quality */
00864             get_be32(pb); /* spatial quality */
00865 
00866             st->codec->width = get_be16(pb); /* width */
00867             st->codec->height = get_be16(pb); /* height */
00868 
00869             get_be32(pb); /* horiz resolution */
00870             get_be32(pb); /* vert resolution */
00871             get_be32(pb); /* data size, always 0 */
00872             get_be16(pb); /* frames per samples */
00873 
00874             get_buffer(pb, codec_name, 32); /* codec name, pascal string */
00875             if (codec_name[0] <= 31) {
00876                 memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
00877                 st->codec->codec_name[codec_name[0]] = 0;
00878             }
00879 
00880             st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
00881             st->codec->color_table_id = get_be16(pb); /* colortable id */
00882             dprintf(c->fc, "depth %d, ctab id %d\n",
00883                    st->codec->bits_per_coded_sample, st->codec->color_table_id);
00884             /* figure out the palette situation */
00885             color_depth = st->codec->bits_per_coded_sample & 0x1F;
00886             color_greyscale = st->codec->bits_per_coded_sample & 0x20;
00887 
00888             /* if the depth is 2, 4, or 8 bpp, file is palettized */
00889             if ((color_depth == 2) || (color_depth == 4) ||
00890                 (color_depth == 8)) {
00891                 /* for palette traversal */
00892                 unsigned int color_start, color_count, color_end;
00893                 unsigned char r, g, b;
00894 
00895                 if (color_greyscale) {
00896                     int color_index, color_dec;
00897                     /* compute the greyscale palette */
00898                     st->codec->bits_per_coded_sample = color_depth;
00899                     color_count = 1 << color_depth;
00900                     color_index = 255;
00901                     color_dec = 256 / (color_count - 1);
00902                     for (j = 0; j < color_count; j++) {
00903                         r = g = b = color_index;
00904                         c->palette_control.palette[j] =
00905                             (r << 16) | (g << 8) | (b);
00906                         color_index -= color_dec;
00907                         if (color_index < 0)
00908                             color_index = 0;
00909                     }
00910                 } else if (st->codec->color_table_id) {
00911                     const uint8_t *color_table;
00912                     /* if flag bit 3 is set, use the default palette */
00913                     color_count = 1 << color_depth;
00914                     if (color_depth == 2)
00915                         color_table = ff_qt_default_palette_4;
00916                     else if (color_depth == 4)
00917                         color_table = ff_qt_default_palette_16;
00918                     else
00919                         color_table = ff_qt_default_palette_256;
00920 
00921                     for (j = 0; j < color_count; j++) {
00922                         r = color_table[j * 4 + 0];
00923                         g = color_table[j * 4 + 1];
00924                         b = color_table[j * 4 + 2];
00925                         c->palette_control.palette[j] =
00926                             (r << 16) | (g << 8) | (b);
00927                     }
00928                 } else {
00929                     /* load the palette from the file */
00930                     color_start = get_be32(pb);
00931                     color_count = get_be16(pb);
00932                     color_end = get_be16(pb);
00933                     if ((color_start <= 255) &&
00934                         (color_end <= 255)) {
00935                         for (j = color_start; j <= color_end; j++) {
00936                             /* each R, G, or B component is 16 bits;
00937                              * only use the top 8 bits; skip alpha bytes
00938                              * up front */
00939                             get_byte(pb);
00940                             get_byte(pb);
00941                             r = get_byte(pb);
00942                             get_byte(pb);
00943                             g = get_byte(pb);
00944                             get_byte(pb);
00945                             b = get_byte(pb);
00946                             get_byte(pb);
00947                             c->palette_control.palette[j] =
00948                                 (r << 16) | (g << 8) | (b);
00949                         }
00950                     }
00951                 }
00952                 st->codec->palctrl = &c->palette_control;
00953                 st->codec->palctrl->palette_changed = 1;
00954             } else
00955                 st->codec->palctrl = NULL;
00956         } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
00957             int bits_per_sample, flags;
00958             uint16_t version = get_be16(pb);
00959 
00960             st->codec->codec_id = id;
00961             get_be16(pb); /* revision level */
00962             get_be32(pb); /* vendor */
00963 
00964             st->codec->channels = get_be16(pb);             /* channel count */
00965             dprintf(c->fc, "audio channels %d\n", st->codec->channels);
00966             st->codec->bits_per_coded_sample = get_be16(pb);      /* sample size */
00967 
00968             sc->audio_cid = get_be16(pb);
00969             get_be16(pb); /* packet size = 0 */
00970 
00971             st->codec->sample_rate = ((get_be32(pb) >> 16));
00972 
00973             //Read QT version 1 fields. In version 0 these do not exist.
00974             dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
00975             if(!c->isom) {
00976                 if(version==1) {
00977                     sc->samples_per_frame = get_be32(pb);
00978                     get_be32(pb); /* bytes per packet */
00979                     sc->bytes_per_frame = get_be32(pb);
00980                     get_be32(pb); /* bytes per sample */
00981                 } else if(version==2) {
00982                     get_be32(pb); /* sizeof struct only */
00983                     st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
00984                     st->codec->channels = get_be32(pb);
00985                     get_be32(pb); /* always 0x7F000000 */
00986                     st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
00987                     flags = get_be32(pb); /* lcpm format specific flag */
00988                     sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
00989                     sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
00990                     if (format == MKTAG('l','p','c','m'))
00991                         st->codec->codec_id = mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
00992                 }
00993             }
00994 
00995             switch (st->codec->codec_id) {
00996             case CODEC_ID_PCM_S8:
00997             case CODEC_ID_PCM_U8:
00998                 if (st->codec->bits_per_coded_sample == 16)
00999                     st->codec->codec_id = CODEC_ID_PCM_S16BE;
01000                 break;
01001             case CODEC_ID_PCM_S16LE:
01002             case CODEC_ID_PCM_S16BE:
01003                 if (st->codec->bits_per_coded_sample == 8)
01004                     st->codec->codec_id = CODEC_ID_PCM_S8;
01005                 else if (st->codec->bits_per_coded_sample == 24)
01006                     st->codec->codec_id =
01007                         st->codec->codec_id == CODEC_ID_PCM_S16BE ?
01008                         CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
01009                 break;
01010             /* set values for old format before stsd version 1 appeared */
01011             case CODEC_ID_MACE3:
01012                 sc->samples_per_frame = 6;
01013                 sc->bytes_per_frame = 2*st->codec->channels;
01014                 break;
01015             case CODEC_ID_MACE6:
01016                 sc->samples_per_frame = 6;
01017                 sc->bytes_per_frame = 1*st->codec->channels;
01018                 break;
01019             case CODEC_ID_ADPCM_IMA_QT:
01020                 sc->samples_per_frame = 64;
01021                 sc->bytes_per_frame = 34*st->codec->channels;
01022                 break;
01023             case CODEC_ID_GSM:
01024                 sc->samples_per_frame = 160;
01025                 sc->bytes_per_frame = 33;
01026                 break;
01027             default:
01028                 break;
01029             }
01030 
01031             bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
01032             if (bits_per_sample) {
01033                 st->codec->bits_per_coded_sample = bits_per_sample;
01034                 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
01035             }
01036         } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){
01037             // ttxt stsd contains display flags, justification, background
01038             // color, fonts, and default styles, so fake an atom to read it
01039             MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
01040             mov_read_glbl(c, pb, fake_atom);
01041             st->codec->codec_id= id;
01042             st->codec->width = sc->width;
01043             st->codec->height = sc->height;
01044         } else {
01045             /* other codec type, just skip (rtp, mp4s, tmcd ...) */
01046             url_fskip(pb, size - (url_ftell(pb) - start_pos));
01047         }
01048         /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
01049         a.size = size - (url_ftell(pb) - start_pos);
01050         if (a.size > 8) {
01051             if (mov_read_default(c, pb, a) < 0)
01052                 return -1;
01053         } else if (a.size > 0)
01054             url_fskip(pb, a.size);
01055     }
01056 
01057     if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
01058         st->codec->sample_rate= sc->time_scale;
01059 
01060     /* special codec parameters handling */
01061     switch (st->codec->codec_id) {
01062 #if CONFIG_DV_DEMUXER
01063     case CODEC_ID_DVAUDIO:
01064         c->dv_fctx = avformat_alloc_context();
01065         c->dv_demux = dv_init_demux(c->dv_fctx);
01066         if (!c->dv_demux) {
01067             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
01068             return -1;
01069         }
01070         sc->dv_audio_container = 1;
01071         st->codec->codec_id = CODEC_ID_PCM_S16LE;
01072         break;
01073 #endif
01074     /* no ifdef since parameters are always those */
01075     case CODEC_ID_QCELP:
01076         st->codec->frame_size= 160;
01077         st->codec->channels= 1; /* really needed */
01078         break;
01079     case CODEC_ID_AMR_NB:
01080     case CODEC_ID_AMR_WB:
01081         st->codec->frame_size= sc->samples_per_frame;
01082         st->codec->channels= 1; /* really needed */
01083         /* force sample rate for amr, stsd in 3gp does not store sample rate */
01084         if (st->codec->codec_id == CODEC_ID_AMR_NB)
01085             st->codec->sample_rate = 8000;
01086         else if (st->codec->codec_id == CODEC_ID_AMR_WB)
01087             st->codec->sample_rate = 16000;
01088         break;
01089     case CODEC_ID_MP2:
01090     case CODEC_ID_MP3:
01091         st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
01092         st->need_parsing = AVSTREAM_PARSE_FULL;
01093         break;
01094     case CODEC_ID_GSM:
01095     case CODEC_ID_ADPCM_MS:
01096     case CODEC_ID_ADPCM_IMA_WAV:
01097         st->codec->block_align = sc->bytes_per_frame;
01098         break;
01099     case CODEC_ID_ALAC:
01100         if (st->codec->extradata_size == 36) {
01101             st->codec->frame_size = AV_RB32(st->codec->extradata+12);
01102             st->codec->channels   = AV_RB8 (st->codec->extradata+21);
01103         }
01104         break;
01105     default:
01106         break;
01107     }
01108 
01109     return 0;
01110 }
01111 
01112 static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01113 {
01114     AVStream *st;
01115     MOVStreamContext *sc;
01116     unsigned int i, entries;
01117 
01118     if (c->fc->nb_streams < 1)
01119         return 0;
01120     st = c->fc->streams[c->fc->nb_streams-1];
01121     sc = st->priv_data;
01122 
01123     get_byte(pb); /* version */
01124     get_be24(pb); /* flags */
01125 
01126     entries = get_be32(pb);
01127 
01128     dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
01129 
01130     if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
01131         return -1;
01132     sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
01133     if (!sc->stsc_data)
01134         return AVERROR(ENOMEM);
01135     sc->stsc_count = entries;
01136 
01137     for(i=0; i<entries; i++) {
01138         sc->stsc_data[i].first = get_be32(pb);
01139         sc->stsc_data[i].count = get_be32(pb);
01140         sc->stsc_data[i].id = get_be32(pb);
01141     }
01142     return 0;
01143 }
01144 
01145 static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01146 {
01147     AVStream *st;
01148     MOVStreamContext *sc;
01149     unsigned int i, entries;
01150 
01151     if (c->fc->nb_streams < 1)
01152         return 0;
01153     st = c->fc->streams[c->fc->nb_streams-1];
01154     sc = st->priv_data;
01155 
01156     get_byte(pb); /* version */
01157     get_be24(pb); /* flags */
01158 
01159     entries = get_be32(pb);
01160 
01161     dprintf(c->fc, "keyframe_count = %d\n", entries);
01162 
01163     if(entries >= UINT_MAX / sizeof(int))
01164         return -1;
01165     sc->keyframes = av_malloc(entries * sizeof(int));
01166     if (!sc->keyframes)
01167         return AVERROR(ENOMEM);
01168     sc->keyframe_count = entries;
01169 
01170     for(i=0; i<entries; i++) {
01171         sc->keyframes[i] = get_be32(pb);
01172         //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
01173     }
01174     return 0;
01175 }
01176 
01177 static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01178 {
01179     AVStream *st;
01180     MOVStreamContext *sc;
01181     unsigned int i, entries, sample_size;
01182 
01183     if (c->fc->nb_streams < 1)
01184         return 0;
01185     st = c->fc->streams[c->fc->nb_streams-1];
01186     sc = st->priv_data;
01187 
01188     get_byte(pb); /* version */
01189     get_be24(pb); /* flags */
01190 
01191     sample_size = get_be32(pb);
01192     if (!sc->sample_size) /* do not overwrite value computed in stsd */
01193         sc->sample_size = sample_size;
01194     entries = get_be32(pb);
01195 
01196     dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
01197 
01198     sc->sample_count = entries;
01199     if (sample_size)
01200         return 0;
01201 
01202     if(entries >= UINT_MAX / sizeof(int))
01203         return -1;
01204     sc->sample_sizes = av_malloc(entries * sizeof(int));
01205     if (!sc->sample_sizes)
01206         return AVERROR(ENOMEM);
01207 
01208     for(i=0; i<entries; i++)
01209         sc->sample_sizes[i] = get_be32(pb);
01210     return 0;
01211 }
01212 
01213 static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01214 {
01215     AVStream *st;
01216     MOVStreamContext *sc;
01217     unsigned int i, entries;
01218     int64_t duration=0;
01219     int64_t total_sample_count=0;
01220 
01221     if (c->fc->nb_streams < 1)
01222         return 0;
01223     st = c->fc->streams[c->fc->nb_streams-1];
01224     sc = st->priv_data;
01225 
01226     get_byte(pb); /* version */
01227     get_be24(pb); /* flags */
01228     entries = get_be32(pb);
01229 
01230     dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
01231 
01232     if(entries >= UINT_MAX / sizeof(*sc->stts_data))
01233         return -1;
01234     sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
01235     if (!sc->stts_data)
01236         return AVERROR(ENOMEM);
01237     sc->stts_count = entries;
01238 
01239     for(i=0; i<entries; i++) {
01240         int sample_duration;
01241         int sample_count;
01242 
01243         sample_count=get_be32(pb);
01244         sample_duration = get_be32(pb);
01245         sc->stts_data[i].count= sample_count;
01246         sc->stts_data[i].duration= sample_duration;
01247 
01248         sc->time_rate= av_gcd(sc->time_rate, sample_duration);
01249 
01250         dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
01251 
01252         duration+=(int64_t)sample_duration*sample_count;
01253         total_sample_count+=sample_count;
01254     }
01255 
01256     st->nb_frames= total_sample_count;
01257     if(duration)
01258         st->duration= duration;
01259     return 0;
01260 }
01261 
01262 static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01263 {
01264     AVStream *st;
01265     MOVStreamContext *sc;
01266     unsigned int i, entries;
01267 
01268     if (c->fc->nb_streams < 1)
01269         return 0;
01270     st = c->fc->streams[c->fc->nb_streams-1];
01271     sc = st->priv_data;
01272 
01273     get_byte(pb); /* version */
01274     get_be24(pb); /* flags */
01275     entries = get_be32(pb);
01276 
01277     dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
01278 
01279     if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
01280         return -1;
01281     sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
01282     if (!sc->ctts_data)
01283         return AVERROR(ENOMEM);
01284     sc->ctts_count = entries;
01285 
01286     for(i=0; i<entries; i++) {
01287         int count    =get_be32(pb);
01288         int duration =get_be32(pb);
01289 
01290         if (duration < 0) {
01291             sc->wrong_dts = 1;
01292             st->codec->has_b_frames = 1;
01293         }
01294         sc->ctts_data[i].count   = count;
01295         sc->ctts_data[i].duration= duration;
01296 
01297         sc->time_rate= av_gcd(sc->time_rate, FFABS(duration));
01298     }
01299     return 0;
01300 }
01301 
01302 static void mov_build_index(MOVContext *mov, AVStream *st)
01303 {
01304     MOVStreamContext *sc = st->priv_data;
01305     int64_t current_offset;
01306     int64_t current_dts = 0;
01307     unsigned int stts_index = 0;
01308     unsigned int stsc_index = 0;
01309     unsigned int stss_index = 0;
01310     unsigned int i, j;
01311 
01312     /* adjust first dts according to edit list */
01313     if (sc->time_offset) {
01314         assert(sc->time_offset % sc->time_rate == 0);
01315         current_dts = - (sc->time_offset / sc->time_rate);
01316     }
01317 
01318     /* only use old uncompressed audio chunk demuxing when stts specifies it */
01319     if (!(st->codec->codec_type == CODEC_TYPE_AUDIO &&
01320           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
01321         unsigned int current_sample = 0;
01322         unsigned int stts_sample = 0;
01323         unsigned int keyframe, sample_size;
01324         unsigned int distance = 0;
01325         int key_off = sc->keyframes && sc->keyframes[0] == 1;
01326 
01327         st->nb_frames = sc->sample_count;
01328         for (i = 0; i < sc->chunk_count; i++) {
01329             current_offset = sc->chunk_offsets[i];
01330             if (stsc_index + 1 < sc->stsc_count &&
01331                 i + 1 == sc->stsc_data[stsc_index + 1].first)
01332                 stsc_index++;
01333             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
01334                 if (current_sample >= sc->sample_count) {
01335                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
01336                     goto out;
01337                 }
01338                 keyframe = !sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index];
01339                 if (keyframe) {
01340                     distance = 0;
01341                     if (stss_index + 1 < sc->keyframe_count)
01342                         stss_index++;
01343                 }
01344                 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
01345                 if(sc->pseudo_stream_id == -1 ||
01346                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
01347                     av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
01348                                     keyframe ? AVINDEX_KEYFRAME : 0);
01349                     dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
01350                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
01351                             current_offset, current_dts, sample_size, distance, keyframe);
01352                 }
01353                 current_offset += sample_size;
01354                 assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
01355                 current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
01356                 distance++;
01357                 stts_sample++;
01358                 current_sample++;
01359                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
01360                     stts_sample = 0;
01361                     stts_index++;
01362                 }
01363             }
01364         }
01365     } else { /* read whole chunk */
01366         unsigned int chunk_samples, chunk_size, chunk_duration;
01367         unsigned int frames = 1;
01368         for (i = 0; i < sc->chunk_count; i++) {
01369             current_offset = sc->chunk_offsets[i];
01370             if (stsc_index + 1 < sc->stsc_count &&
01371                 i + 1 == sc->stsc_data[stsc_index + 1].first)
01372                 stsc_index++;
01373             chunk_samples = sc->stsc_data[stsc_index].count;
01374             /* get chunk size, beware of alaw/ulaw/mace */
01375             if (sc->samples_per_frame > 0 &&
01376                 (chunk_samples * sc->bytes_per_frame % sc->samples_per_frame == 0)) {
01377                 if (sc->samples_per_frame < 160)
01378                     chunk_size = chunk_samples * sc->bytes_per_frame / sc->samples_per_frame;
01379                 else {
01380                     chunk_size = sc->bytes_per_frame;
01381                     frames = chunk_samples / sc->samples_per_frame;
01382                     chunk_samples = sc->samples_per_frame;
01383                 }
01384             } else
01385                 chunk_size = chunk_samples * sc->sample_size;
01386             for (j = 0; j < frames; j++) {
01387                 av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
01388                 /* get chunk duration */
01389                 chunk_duration = 0;
01390                 while (chunk_samples > 0) {
01391                     if (chunk_samples < sc->stts_data[stts_index].count) {
01392                         chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
01393                         sc->stts_data[stts_index].count -= chunk_samples;
01394                         break;
01395                     } else {
01396                         chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
01397                         chunk_samples -= sc->stts_data[stts_index].count;
01398                         if (stts_index + 1 < sc->stts_count)
01399                             stts_index++;
01400                     }
01401                 }
01402                 current_offset += sc->bytes_per_frame;
01403                 dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
01404                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
01405                         chunk_size, chunk_duration);
01406                 assert(chunk_duration % sc->time_rate == 0);
01407                 current_dts += chunk_duration / sc->time_rate;
01408             }
01409         }
01410     }
01411  out:
01412     /* adjust sample count to avindex entries */
01413     sc->sample_count = st->nb_index_entries;
01414 }
01415 
01416 static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01417 {
01418     AVStream *st;
01419     MOVStreamContext *sc;
01420     int ret;
01421 
01422     st = av_new_stream(c->fc, c->fc->nb_streams);
01423     if (!st) return AVERROR(ENOMEM);
01424     sc = av_mallocz(sizeof(MOVStreamContext));
01425     if (!sc) return AVERROR(ENOMEM);
01426 
01427     st->priv_data = sc;
01428     st->codec->codec_type = CODEC_TYPE_DATA;
01429     sc->ffindex = st->index;
01430 
01431     if ((ret = mov_read_default(c, pb, atom)) < 0)
01432         return ret;
01433 
01434     /* sanity checks */
01435     if(sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
01436                            (!sc->sample_size && !sc->sample_count))){
01437         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
01438                st->index);
01439         sc->sample_count = 0; //ignore track
01440         return 0;
01441     }
01442     if(!sc->time_rate)
01443         sc->time_rate=1;
01444     if(!sc->time_scale)
01445         sc->time_scale= c->time_scale;
01446     av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
01447 
01448     if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
01449         !st->codec->frame_size && sc->stts_count == 1) {
01450         st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
01451                                            st->codec->sample_rate, sc->time_scale);
01452         dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
01453     }
01454 
01455     if(st->duration != AV_NOPTS_VALUE){
01456         assert(st->duration % sc->time_rate == 0);
01457         st->duration /= sc->time_rate;
01458     }
01459 
01460     mov_build_index(c, st);
01461 
01462     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
01463         if (url_fopen(&sc->pb, sc->drefs[sc->dref_id-1].path, URL_RDONLY) < 0)
01464             av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening file %s: %s\n",
01465                    st->index, sc->drefs[sc->dref_id-1].path, strerror(errno));
01466     } else
01467         sc->pb = c->fc->pb;
01468 
01469     switch (st->codec->codec_id) {
01470 #if CONFIG_H261_DECODER
01471     case CODEC_ID_H261:
01472 #endif
01473 #if CONFIG_H263_DECODER
01474     case CODEC_ID_H263:
01475 #endif
01476 #if CONFIG_MPEG4_DECODER
01477     case CODEC_ID_MPEG4:
01478 #endif
01479         st->codec->width= 0; /* let decoder init width/height */
01480         st->codec->height= 0;
01481         break;
01482     }
01483 
01484     /* Do not need those anymore. */
01485     av_freep(&sc->chunk_offsets);
01486     av_freep(&sc->stsc_data);
01487     av_freep(&sc->sample_sizes);
01488     av_freep(&sc->keyframes);
01489     av_freep(&sc->stts_data);
01490 
01491     return 0;
01492 }
01493 
01494 static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01495 {
01496     int ret;
01497     c->itunes_metadata = 1;
01498     ret = mov_read_default(c, pb, atom);
01499     c->itunes_metadata = 0;
01500     return ret;
01501 }
01502 
01503 static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01504 {
01505     url_fskip(pb, 4); // version + flags
01506     atom.size -= 4;
01507     return mov_read_default(c, pb, atom);
01508 }
01509 
01510 static int mov_read_trkn(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01511 {
01512     char track[16];
01513     get_be32(pb); // type
01514     get_be32(pb); // unknown
01515     snprintf(track, sizeof(track), "%d", get_be32(pb));
01516     av_metadata_set(&c->fc->metadata, "track", track);
01517     dprintf(c->fc, "%.4s %s\n", (char*)&atom.type, track);
01518     return 0;
01519 }
01520 
01521 static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01522 {
01523     char str[1024], key2[16], language[4] = {0};
01524     const char *key = NULL;
01525     uint16_t str_size;
01526 
01527     if (c->itunes_metadata) {
01528         int data_size = get_be32(pb);
01529         int tag = get_le32(pb);
01530         if (tag == MKTAG('d','a','t','a')) {
01531             get_be32(pb); // type
01532             get_be32(pb); // unknown
01533             str_size = data_size - 16;
01534             atom.size -= 16;
01535         } else return 0;
01536     } else {
01537         str_size = get_be16(pb); // string length
01538         ff_mov_lang_to_iso639(get_be16(pb), language);
01539         atom.size -= 4;
01540     }
01541     switch (atom.type) {
01542     case MKTAG(0xa9,'n','a','m'): key = "title";     break;
01543     case MKTAG(0xa9,'a','u','t'):
01544     case MKTAG(0xa9,'A','R','T'):
01545     case MKTAG(0xa9,'w','r','t'): key = "author";    break;
01546     case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
01547     case MKTAG(0xa9,'c','m','t'):
01548     case MKTAG(0xa9,'i','n','f'): key = "comment";   break;
01549     case MKTAG(0xa9,'a','l','b'): key = "album";     break;
01550     case MKTAG(0xa9,'d','a','y'): key = "year";      break;
01551     case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
01552     case MKTAG(0xa9,'t','o','o'):
01553     case MKTAG(0xa9,'e','n','c'): key = "muxer";     break;
01554     }
01555     if (!key)
01556         return 0;
01557     if (atom.size < 0)
01558         return -1;
01559 
01560     str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
01561     get_buffer(pb, str, str_size);
01562     str[str_size] = 0;
01563     av_metadata_set(&c->fc->metadata, key, str);
01564     if (*language && strcmp(language, "und")) {
01565         snprintf(key2, sizeof(key2), "%s-%s", key, language);
01566         av_metadata_set(&c->fc->metadata, key2, str);
01567     }
01568     dprintf(c->fc, "%.4s %s %d %lld\n", (char*)&atom.type, str, str_size, atom.size);
01569     return 0;
01570 }
01571 
01572 static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01573 {
01574     int i;
01575     int width;
01576     int height;
01577     int64_t disp_transform[2];
01578     int display_matrix[3][2];
01579     AVStream *st;
01580     MOVStreamContext *sc;
01581     int version;
01582 
01583     if (c->fc->nb_streams < 1)
01584         return 0;
01585     st = c->fc->streams[c->fc->nb_streams-1];
01586     sc = st->priv_data;
01587 
01588     version = get_byte(pb);
01589     get_be24(pb); /* flags */
01590     /*
01591     MOV_TRACK_ENABLED 0x0001
01592     MOV_TRACK_IN_MOVIE 0x0002
01593     MOV_TRACK_IN_PREVIEW 0x0004
01594     MOV_TRACK_IN_POSTER 0x0008
01595     */
01596 
01597     if (version == 1) {
01598         get_be64(pb);
01599         get_be64(pb);
01600     } else {
01601         get_be32(pb); /* creation time */
01602         get_be32(pb); /* modification time */
01603     }
01604     st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
01605     get_be32(pb); /* reserved */
01606 
01607     /* highlevel (considering edits) duration in movie timebase */
01608     (version == 1) ? get_be64(pb) : get_be32(pb);
01609     get_be32(pb); /* reserved */
01610     get_be32(pb); /* reserved */
01611 
01612     get_be16(pb); /* layer */
01613     get_be16(pb); /* alternate group */
01614     get_be16(pb); /* volume */
01615     get_be16(pb); /* reserved */
01616 
01617     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
01618     // they're kept in fixed point format through all calculations
01619     // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
01620     for (i = 0; i < 3; i++) {
01621         display_matrix[i][0] = get_be32(pb);   // 16.16 fixed point
01622         display_matrix[i][1] = get_be32(pb);   // 16.16 fixed point
01623         get_be32(pb);           // 2.30 fixed point (not used)
01624     }
01625 
01626     width = get_be32(pb);       // 16.16 fixed point track width
01627     height = get_be32(pb);      // 16.16 fixed point track height
01628     sc->width = width >> 16;
01629     sc->height = height >> 16;
01630 
01631     //transform the display width/height according to the matrix
01632     // skip this if the display matrix is the default identity matrix
01633     // to keep the same scale, use [width height 1<<16]
01634     if (width && height &&
01635         (display_matrix[0][0] != 65536 || display_matrix[0][1]           ||
01636         display_matrix[1][0]           || display_matrix[1][1] != 65536  ||
01637         display_matrix[2][0]           || display_matrix[2][1])) {
01638         for (i = 0; i < 2; i++)
01639             disp_transform[i] =
01640                 (int64_t)  width  * display_matrix[0][i] +
01641                 (int64_t)  height * display_matrix[1][i] +
01642                 ((int64_t) display_matrix[2][i] << 16);
01643 
01644         //sample aspect ratio is new width/height divided by old width/height
01645         st->sample_aspect_ratio = av_d2q(
01646             ((double) disp_transform[0] * height) /
01647             ((double) disp_transform[1] * width), INT_MAX);
01648     }
01649     return 0;
01650 }
01651 
01652 static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01653 {
01654     MOVFragment *frag = &c->fragment;
01655     MOVTrackExt *trex = NULL;
01656     int flags, track_id, i;
01657 
01658     get_byte(pb); /* version */
01659     flags = get_be24(pb);
01660 
01661     track_id = get_be32(pb);
01662     if (!track_id || track_id > c->fc->nb_streams)
01663         return -1;
01664     frag->track_id = track_id;
01665     for (i = 0; i < c->trex_count; i++)
01666         if (c->trex_data[i].track_id == frag->track_id) {
01667             trex = &c->trex_data[i];
01668             break;
01669         }
01670     if (!trex) {
01671         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
01672         return -1;
01673     }
01674 
01675     if (flags & 0x01) frag->base_data_offset = get_be64(pb);
01676     else              frag->base_data_offset = frag->moof_offset;
01677     if (flags & 0x02) frag->stsd_id          = get_be32(pb);
01678     else              frag->stsd_id          = trex->stsd_id;
01679 
01680     frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
01681     frag->size     = flags & 0x10 ? get_be32(pb) : trex->size;
01682     frag->flags    = flags & 0x20 ? get_be32(pb) : trex->flags;
01683     dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
01684     return 0;
01685 }
01686 
01687 static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01688 {
01689     MOVTrackExt *trex;
01690 
01691     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
01692         return -1;
01693     trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
01694     if (!trex)
01695         return AVERROR(ENOMEM);
01696     c->trex_data = trex;
01697     trex = &c->trex_data[c->trex_count++];
01698     get_byte(pb); /* version */
01699     get_be24(pb); /* flags */
01700     trex->track_id = get_be32(pb);
01701     trex->stsd_id  = get_be32(pb);
01702     trex->duration = get_be32(pb);
01703     trex->size     = get_be32(pb);
01704     trex->flags    = get_be32(pb);
01705     return 0;
01706 }
01707 
01708 static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01709 {
01710     MOVFragment *frag = &c->fragment;
01711     AVStream *st;
01712     MOVStreamContext *sc;
01713     uint64_t offset;
01714     int64_t dts;
01715     int data_offset = 0;
01716     unsigned entries, first_sample_flags = frag->flags;
01717     int flags, distance, i;
01718 
01719     if (!frag->track_id || frag->track_id > c->fc->nb_streams)
01720         return -1;
01721     st = c->fc->streams[frag->track_id-1];
01722     sc = st->priv_data;
01723     if (sc->pseudo_stream_id+1 != frag->stsd_id)
01724         return 0;
01725     get_byte(pb); /* version */
01726     flags = get_be24(pb);
01727     entries = get_be32(pb);
01728     dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
01729     if (flags & 0x001) data_offset        = get_be32(pb);
01730     if (flags & 0x004) first_sample_flags = get_be32(pb);
01731     if (flags & 0x800) {
01732         MOVStts *ctts_data;
01733         if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
01734             return -1;
01735         ctts_data = av_realloc(sc->ctts_data,
01736                                (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
01737         if (!ctts_data)
01738             return AVERROR(ENOMEM);
01739         sc->ctts_data = ctts_data;
01740     }
01741     dts = st->duration;
01742     offset = frag->base_data_offset + data_offset;
01743     distance = 0;
01744     dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
01745     for (i = 0; i < entries; i++) {
01746         unsigned sample_size = frag->size;
01747         int sample_flags = i ? frag->flags : first_sample_flags;
01748         unsigned sample_duration = frag->duration;
01749         int keyframe;
01750 
01751         if (flags & 0x100) sample_duration = get_be32(pb);
01752         if (flags & 0x200) sample_size     = get_be32(pb);
01753         if (flags & 0x400) sample_flags    = get_be32(pb);
01754         if (flags & 0x800) {
01755             sc->ctts_data[sc->ctts_count].count = 1;
01756             sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
01757             sc->ctts_count++;
01758         }
01759         if ((keyframe = st->codec->codec_type == CODEC_TYPE_AUDIO ||
01760              (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
01761             distance = 0;
01762         av_add_index_entry(st, offset, dts, sample_size, distance,
01763                            keyframe ? AVINDEX_KEYFRAME : 0);
01764         dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
01765                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
01766                 offset, dts, sample_size, distance, keyframe);
01767         distance++;
01768         assert(sample_duration % sc->time_rate == 0);
01769         dts += sample_duration / sc->time_rate;
01770         offset += sample_size;
01771     }
01772     frag->moof_offset = offset;
01773     sc->sample_count = st->nb_index_entries;
01774     st->duration = dts;
01775     return 0;
01776 }
01777 
01778 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
01779 /* like the files created with Adobe Premiere 5.0, for samples see */
01780 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
01781 static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01782 {
01783     int err;
01784 
01785     if (atom.size < 8)
01786         return 0; /* continue */
01787     if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
01788         url_fskip(pb, atom.size - 4);
01789         return 0;
01790     }
01791     atom.type = get_le32(pb);
01792     atom.offset += 8;
01793     atom.size -= 8;
01794     if (atom.type != MKTAG('m','d','a','t')) {
01795         url_fskip(pb, atom.size);
01796         return 0;
01797     }
01798     err = mov_read_mdat(c, pb, atom);
01799     return err;
01800 }
01801 
01802 static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01803 {
01804 #if CONFIG_ZLIB
01805     ByteIOContext ctx;
01806     uint8_t *cmov_data;
01807     uint8_t *moov_data; /* uncompressed data */
01808     long cmov_len, moov_len;
01809     int ret = -1;
01810 
01811     get_be32(pb); /* dcom atom */
01812     if (get_le32(pb) != MKTAG('d','c','o','m'))
01813         return -1;
01814     if (get_le32(pb) != MKTAG('z','l','i','b')) {
01815         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
01816         return -1;
01817     }
01818     get_be32(pb); /* cmvd atom */
01819     if (get_le32(pb) != MKTAG('c','m','v','d'))
01820         return -1;
01821     moov_len = get_be32(pb); /* uncompressed size */
01822     cmov_len = atom.size - 6 * 4;
01823 
01824     cmov_data = av_malloc(cmov_len);
01825     if (!cmov_data)
01826         return AVERROR(ENOMEM);
01827     moov_data = av_malloc(moov_len);
01828     if (!moov_data) {
01829         av_free(cmov_data);
01830         return AVERROR(ENOMEM);
01831     }
01832     get_buffer(pb, cmov_data, cmov_len);
01833     if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
01834         goto free_and_return;
01835     if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
01836         goto free_and_return;
01837     atom.type = MKTAG('m','o','o','v');
01838     atom.offset = 0;
01839     atom.size = moov_len;
01840 #ifdef DEBUG
01841 //    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
01842 #endif
01843     ret = mov_read_default(c, &ctx, atom);
01844 free_and_return:
01845     av_free(moov_data);
01846     av_free(cmov_data);
01847     return ret;
01848 #else
01849     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
01850     return -1;
01851 #endif
01852 }
01853 
01854 /* edit list atom */
01855 static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
01856 {
01857     MOVStreamContext *sc;
01858     int i, edit_count;
01859 
01860     if (c->fc->nb_streams < 1)
01861         return 0;
01862     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
01863 
01864     get_byte(pb); /* version */
01865     get_be24(pb); /* flags */
01866     edit_count = get_be32(pb); /* entries */
01867 
01868     for(i=0; i<edit_count; i++){
01869         int time;
01870         get_be32(pb); /* Track duration */
01871         time = get_be32(pb); /* Media time */
01872         get_be32(pb); /* Media rate */
01873         if (i == 0 && time != -1) {
01874             sc->time_offset = time;
01875             sc->time_rate = av_gcd(sc->time_rate, time);
01876         }
01877     }
01878 
01879     if(edit_count > 1)
01880         av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
01881                "a/v desync might occur, patch welcome\n");
01882 
01883     dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
01884     return 0;
01885 }
01886 
01887 static const MOVParseTableEntry mov_default_parse_table[] = {
01888 { MKTAG('a','v','s','s'), mov_read_extradata },
01889 { MKTAG('c','o','6','4'), mov_read_stco },
01890 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
01891 { MKTAG('d','i','n','f'), mov_read_default },
01892 { MKTAG('d','r','e','f'), mov_read_dref },
01893 { MKTAG('e','d','t','s'), mov_read_default },
01894 { MKTAG('e','l','s','t'), mov_read_elst },
01895 { MKTAG('e','n','d','a'), mov_read_enda },
01896 { MKTAG('f','i','e','l'), mov_read_extradata },
01897 { MKTAG('f','t','y','p'), mov_read_ftyp },
01898 { MKTAG('g','l','b','l'), mov_read_glbl },
01899 { MKTAG('h','d','l','r'), mov_read_hdlr },
01900 { MKTAG('i','l','s','t'), mov_read_ilst },
01901 { MKTAG('j','p','2','h'), mov_read_extradata },
01902 { MKTAG('m','d','a','t'), mov_read_mdat },
01903 { MKTAG('m','d','h','d'), mov_read_mdhd },
01904 { MKTAG('m','d','i','a'), mov_read_default },
01905 { MKTAG('m','e','t','a'), mov_read_meta },
01906 { MKTAG('m','i','n','f'), mov_read_default },
01907 { MKTAG('m','o','o','f'), mov_read_moof },
01908 { MKTAG('m','o','o','v'), mov_read_moov },
01909 { MKTAG('m','v','e','x'), mov_read_default },
01910 { MKTAG('m','v','h','d'), mov_read_mvhd },
01911 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
01912 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
01913 { MKTAG('a','v','c','C'), mov_read_glbl },
01914 { MKTAG('p','a','s','p'), mov_read_pasp },
01915 { MKTAG('s','t','b','l'), mov_read_default },
01916 { MKTAG('s','t','c','o'), mov_read_stco },
01917 { MKTAG('s','t','s','c'), mov_read_stsc },
01918 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
01919 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
01920 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
01921 { MKTAG('s','t','t','s'), mov_read_stts },
01922 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
01923 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
01924 { MKTAG('t','r','a','k'), mov_read_trak },
01925 { MKTAG('t','r','a','f'), mov_read_default },
01926 { MKTAG('t','r','e','x'), mov_read_trex },
01927 { MKTAG('t','r','k','n'), mov_read_trkn },
01928 { MKTAG('t','r','u','n'), mov_read_trun },
01929 { MKTAG('u','d','t','a'), mov_read_default },
01930 { MKTAG('w','a','v','e'), mov_read_wave },
01931 { MKTAG('e','s','d','s'), mov_read_esds },
01932 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
01933 { MKTAG('c','m','o','v'), mov_read_cmov },
01934 { MKTAG(0xa9,'n','a','m'), mov_read_udta_string },
01935 { MKTAG(0xa9,'w','r','t'), mov_read_udta_string },
01936 { MKTAG(0xa9,'c','p','y'), mov_read_udta_string },
01937 { MKTAG(0xa9,'i','n','f'), mov_read_udta_string },
01938 { MKTAG(0xa9,'i','n','f'), mov_read_udta_string },
01939 { MKTAG(0xa9,'A','R','T'), mov_read_udta_string },
01940 { MKTAG(0xa9,'a','l','b'), mov_read_udta_string },
01941 { MKTAG(0xa9,'c','m','t'), mov_read_udta_string },
01942 { MKTAG(0xa9,'a','u','t'), mov_read_udta_string },
01943 { MKTAG(0xa9,'d','a','y'), mov_read_udta_string },
01944 { MKTAG(0xa9,'g','e','n'), mov_read_udta_string },
01945 { MKTAG(0xa9,'e','n','c'), mov_read_udta_string },
01946 { MKTAG(0xa9,'t','o','o'), mov_read_udta_string },
01947 { 0, NULL }
01948 };
01949 
01950 static int mov_probe(AVProbeData *p)
01951 {
01952     unsigned int offset;
01953     uint32_t tag;
01954     int score = 0;
01955 
01956     /* check file header */
01957     offset = 0;
01958     for(;;) {
01959         /* ignore invalid offset */
01960         if ((offset + 8) > (unsigned int)p->buf_size)
01961             return score;
01962         tag = AV_RL32(p->buf + offset + 4);
01963         switch(tag) {
01964         /* check for obvious tags */
01965         case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
01966         case MKTAG('m','o','o','v'):
01967         case MKTAG('m','d','a','t'):
01968         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
01969         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
01970         case MKTAG('f','t','y','p'):
01971             return AVPROBE_SCORE_MAX;
01972         /* those are more common words, so rate then a bit less */
01973         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
01974         case MKTAG('w','i','d','e'):
01975         case MKTAG('f','r','e','e'):
01976         case MKTAG('j','u','n','k'):
01977         case MKTAG('p','i','c','t'):
01978             return AVPROBE_SCORE_MAX - 5;
01979         case MKTAG(0x82,0x82,0x7f,0x7d):
01980         case MKTAG('s','k','i','p'):
01981         case MKTAG('u','u','i','d'):
01982         case MKTAG('p','r','f','l'):
01983             offset = AV_RB32(p->buf+offset) + offset;
01984             /* if we only find those cause probedata is too small at least rate them */
01985             score = AVPROBE_SCORE_MAX - 50;
01986             break;
01987         default:
01988             /* unrecognized tag */
01989             return score;
01990         }
01991     }
01992     return score;
01993 }
01994 
01995 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
01996 {
01997     MOVContext *mov = s->priv_data;
01998     ByteIOContext *pb = s->pb;
01999     int err;
02000     MOVAtom atom = { 0, 0, 0 };
02001 
02002     mov->fc = s;
02003     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
02004     if(!url_is_streamed(pb))
02005         atom.size = url_fsize(pb);
02006     else
02007         atom.size = INT64_MAX;
02008 
02009     /* check MOV header */
02010     if ((err = mov_read_default(mov, pb, atom)) < 0) {
02011         av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
02012         return err;
02013     }
02014     if (!mov->found_moov) {
02015         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
02016         return -1;
02017     }
02018     dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
02019 
02020     return 0;
02021 }
02022 
02023 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
02024 {
02025     MOVContext *mov = s->priv_data;
02026     MOVStreamContext *sc = 0;
02027     AVIndexEntry *sample = 0;
02028     int64_t best_dts = INT64_MAX;
02029     int i, ret;
02030  retry:
02031     for (i = 0; i < s->nb_streams; i++) {
02032         AVStream *st = s->streams[i];
02033         MOVStreamContext *msc = st->priv_data;
02034         if (st->discard != AVDISCARD_ALL && msc->pb && msc->current_sample < msc->sample_count) {
02035             AVIndexEntry *current_sample = &st->index_entries[msc->current_sample];
02036             int64_t dts = av_rescale(current_sample->timestamp * (int64_t)msc->time_rate,
02037                                      AV_TIME_BASE, msc->time_scale);
02038             dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
02039             if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
02040                 (!url_is_streamed(s->pb) &&
02041                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
02042                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
02043                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
02044                 sample = current_sample;
02045                 best_dts = dts;
02046                 sc = msc;
02047             }
02048         }
02049     }
02050     if (!sample) {
02051         mov->found_mdat = 0;
02052         if (!url_is_streamed(s->pb) ||
02053             mov_read_default(mov, s->pb, (MOVAtom){ 0, 0, INT64_MAX }) < 0 ||
02054             url_feof(s->pb))
02055             return -1;
02056         dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
02057         goto retry;
02058     }
02059     /* must be done just before reading, to avoid infinite loop on sample */
02060     sc->current_sample++;
02061     if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
02062         av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
02063                sc->ffindex, sample->pos);
02064         return -1;
02065     }
02066     ret = av_get_packet(sc->pb, pkt, sample->size);
02067     if (ret < 0)
02068         return ret;
02069 #if CONFIG_DV_DEMUXER
02070     if (mov->dv_demux && sc->dv_audio_container) {
02071         dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
02072         av_free(pkt->data);
02073         pkt->size = 0;
02074         if (dv_get_packet(mov->dv_demux, pkt) < 0)
02075             return -1;
02076     }
02077 #endif
02078     pkt->stream_index = sc->ffindex;
02079     pkt->dts = sample->timestamp;
02080     if (sc->ctts_data) {
02081         assert(sc->ctts_data[sc->ctts_index].duration % sc->time_rate == 0);
02082         pkt->pts = pkt->dts + sc->ctts_data[sc->ctts_index].duration / sc->time_rate;
02083         /* update ctts context */
02084         sc->ctts_sample++;
02085         if (sc->ctts_index < sc->ctts_count &&
02086             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
02087             sc->ctts_index++;
02088             sc->ctts_sample = 0;
02089         }
02090         if (sc->wrong_dts)
02091             pkt->dts = AV_NOPTS_VALUE;
02092     } else {
02093         AVStream *st = s->streams[sc->ffindex];
02094         int64_t next_dts = (sc->current_sample < sc->sample_count) ?
02095             st->index_entries[sc->current_sample].timestamp : st->duration;
02096         pkt->duration = next_dts - pkt->dts;
02097         pkt->pts = pkt->dts;
02098     }
02099     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
02100     pkt->pos = sample->pos;
02101     dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
02102             pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
02103     return 0;
02104 }
02105 
02106 static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
02107 {
02108     MOVStreamContext *sc = st->priv_data;
02109     int sample, time_sample;
02110     int i;
02111 
02112     sample = av_index_search_timestamp(st, timestamp, flags);
02113     dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
02114     if (sample < 0) /* not sure what to do */
02115         return -1;
02116     sc->current_sample = sample;
02117     dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
02118     /* adjust ctts index */
02119     if (sc->ctts_data) {
02120         time_sample = 0;
02121         for (i = 0; i < sc->ctts_count; i++) {
02122             int next = time_sample + sc->ctts_data[i].count;
02123             if (next > sc->current_sample) {
02124                 sc->ctts_index = i;
02125                 sc->ctts_sample = sc->current_sample - time_sample;
02126                 break;
02127             }
02128             time_sample = next;
02129         }
02130     }
02131     return sample;
02132 }
02133 
02134 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
02135 {
02136     AVStream *st;
02137     int64_t seek_timestamp, timestamp;
02138     int sample;
02139     int i;
02140 
02141     if (stream_index >= s->nb_streams)
02142         return -1;
02143     if (sample_time < 0)
02144         sample_time = 0;
02145 
02146     st = s->streams[stream_index];
02147     sample = mov_seek_stream(st, sample_time, flags);
02148     if (sample < 0)
02149         return -1;
02150 
02151     /* adjust seek timestamp to found sample timestamp */
02152     seek_timestamp = st->index_entries[sample].timestamp;
02153 
02154     for (i = 0; i < s->nb_streams; i++) {
02155         st = s->streams[i];
02156         if (stream_index == i || st->discard == AVDISCARD_ALL)
02157             continue;
02158 
02159         timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
02160         mov_seek_stream(st, timestamp, flags);
02161     }
02162     return 0;
02163 }
02164 
02165 static int mov_read_close(AVFormatContext *s)
02166 {
02167     int i, j;
02168     MOVContext *mov = s->priv_data;
02169     for(i=0; i<s->nb_streams; i++) {
02170         MOVStreamContext *sc = s->streams[i]->priv_data;
02171         av_freep(&sc->ctts_data);
02172         for (j=0; j<sc->drefs_count; j++)
02173             av_freep(&sc->drefs[j].path);
02174         av_freep(&sc->drefs);
02175         if (sc->pb && sc->pb != s->pb)
02176             url_fclose(sc->pb);
02177     }
02178     if(mov->dv_demux){
02179         for(i=0; i<mov->dv_fctx->nb_streams; i++){
02180             av_freep(&mov->dv_fctx->streams[i]->codec);
02181             av_freep(&mov->dv_fctx->streams[i]);
02182         }
02183         av_freep(&mov->dv_fctx);
02184         av_freep(&mov->dv_demux);
02185     }
02186     av_freep(&mov->trex_data);
02187     return 0;
02188 }
02189 
02190 AVInputFormat mov_demuxer = {
02191     "mov,mp4,m4a,3gp,3g2,mj2",
02192     NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
02193     sizeof(MOVContext),
02194     mov_probe,
02195     mov_read_header,
02196     mov_read_packet,
02197     mov_read_close,
02198     mov_read_seek,
02199 };

Generated on Tue Nov 4 2014 12:59:23 for ffmpeg by  doxygen 1.7.1