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

libavformat/mov.c

Go to the documentation of this file.
00001 /*
00002  * MOV demuxer
00003  * Copyright (c) 2001 Fabrice Bellard
00004  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
00005  *
00006  * This file is part of Libav.
00007  *
00008  * Libav is free software; you can redistribute it and/or
00009  * modify it under the terms of the GNU Lesser General Public
00010  * License as published by the Free Software Foundation; either
00011  * version 2.1 of the License, or (at your option) any later version.
00012  *
00013  * Libav is distributed in the hope that it will be useful,
00014  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016  * Lesser General Public License for more details.
00017  *
00018  * You should have received a copy of the GNU Lesser General Public
00019  * License along with Libav; if not, write to the Free Software
00020  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00021  */
00022 
00023 #include <limits.h>
00024 
00025 //#define DEBUG
00026 //#define MOV_EXPORT_ALL_METADATA
00027 
00028 #include "libavutil/intreadwrite.h"
00029 #include "libavutil/intfloat.h"
00030 #include "libavutil/mathematics.h"
00031 #include "libavutil/avstring.h"
00032 #include "libavutil/dict.h"
00033 #include "avformat.h"
00034 #include "internal.h"
00035 #include "avio_internal.h"
00036 #include "riff.h"
00037 #include "isom.h"
00038 #include "libavcodec/get_bits.h"
00039 #include "id3v1.h"
00040 #include "mov_chan.h"
00041 
00042 #if CONFIG_ZLIB
00043 #include <zlib.h>
00044 #endif
00045 
00046 /*
00047  * First version by Francois Revol revol@free.fr
00048  * Seek function by Gael Chardon gael.dev@4now.net
00049  */
00050 
00051 #include "qtpalette.h"
00052 
00053 
00054 #undef NDEBUG
00055 #include <assert.h>
00056 
00057 /* those functions parse an atom */
00058 /* links atom IDs to parse functions */
00059 typedef struct MOVParseTableEntry {
00060     uint32_t type;
00061     int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
00062 } MOVParseTableEntry;
00063 
00064 static const MOVParseTableEntry mov_default_parse_table[];
00065 
00066 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
00067                                              unsigned len, const char *key)
00068 {
00069     char buf[16];
00070 
00071     short current, total;
00072     avio_rb16(pb); // unknown
00073     current = avio_rb16(pb);
00074     total = avio_rb16(pb);
00075     if (!total)
00076         snprintf(buf, sizeof(buf), "%d", current);
00077     else
00078         snprintf(buf, sizeof(buf), "%d/%d", current, total);
00079     av_dict_set(&c->fc->metadata, key, buf, 0);
00080 
00081     return 0;
00082 }
00083 
00084 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
00085                                             unsigned len, const char *key)
00086 {
00087     char buf[16];
00088 
00089     /* bypass padding bytes */
00090     avio_r8(pb);
00091     avio_r8(pb);
00092     avio_r8(pb);
00093 
00094     snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
00095     av_dict_set(&c->fc->metadata, key, buf, 0);
00096 
00097     return 0;
00098 }
00099 
00100 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
00101                                         unsigned len, const char *key)
00102 {
00103     char buf[16];
00104 
00105     snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
00106     av_dict_set(&c->fc->metadata, key, buf, 0);
00107 
00108     return 0;
00109 }
00110 
00111 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
00112                              unsigned len, const char *key)
00113 {
00114     short genre;
00115     char buf[20];
00116 
00117     avio_r8(pb); // unknown
00118 
00119     genre = avio_r8(pb);
00120     if (genre < 1 || genre > ID3v1_GENRE_MAX)
00121         return 0;
00122     snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
00123     av_dict_set(&c->fc->metadata, key, buf, 0);
00124 
00125     return 0;
00126 }
00127 
00128 static const uint32_t mac_to_unicode[128] = {
00129     0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
00130     0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
00131     0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
00132     0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
00133     0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
00134     0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
00135     0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
00136     0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
00137     0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
00138     0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
00139     0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
00140     0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
00141     0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
00142     0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
00143     0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
00144     0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
00145 };
00146 
00147 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
00148                                char *dst, int dstlen)
00149 {
00150     char *p = dst;
00151     char *end = dst+dstlen-1;
00152     int i;
00153 
00154     for (i = 0; i < len; i++) {
00155         uint8_t t, c = avio_r8(pb);
00156         if (c < 0x80 && p < end)
00157             *p++ = c;
00158         else
00159             PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
00160     }
00161     *p = 0;
00162     return p - dst;
00163 }
00164 
00165 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00166 {
00167 #ifdef MOV_EXPORT_ALL_METADATA
00168     char tmp_key[5];
00169 #endif
00170     char str[1024], key2[16], language[4] = {0};
00171     const char *key = NULL;
00172     uint16_t str_size, langcode = 0;
00173     uint32_t data_type = 0;
00174     int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
00175 
00176     switch (atom.type) {
00177     case MKTAG(0xa9,'n','a','m'): key = "title";     break;
00178     case MKTAG(0xa9,'a','u','t'):
00179     case MKTAG(0xa9,'A','R','T'): key = "artist";    break;
00180     case MKTAG( 'a','A','R','T'): key = "album_artist";    break;
00181     case MKTAG(0xa9,'w','r','t'): key = "composer";  break;
00182     case MKTAG( 'c','p','r','t'):
00183     case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
00184     case MKTAG(0xa9,'c','m','t'):
00185     case MKTAG(0xa9,'i','n','f'): key = "comment";   break;
00186     case MKTAG(0xa9,'a','l','b'): key = "album";     break;
00187     case MKTAG(0xa9,'d','a','y'): key = "date";      break;
00188     case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
00189     case MKTAG( 'g','n','r','e'): key = "genre";
00190         parse = mov_metadata_gnre; break;
00191     case MKTAG(0xa9,'t','o','o'):
00192     case MKTAG(0xa9,'s','w','r'): key = "encoder";   break;
00193     case MKTAG(0xa9,'e','n','c'): key = "encoder";   break;
00194     case MKTAG( 'd','e','s','c'): key = "description";break;
00195     case MKTAG( 'l','d','e','s'): key = "synopsis";  break;
00196     case MKTAG( 't','v','s','h'): key = "show";      break;
00197     case MKTAG( 't','v','e','n'): key = "episode_id";break;
00198     case MKTAG( 't','v','n','n'): key = "network";   break;
00199     case MKTAG( 't','r','k','n'): key = "track";
00200         parse = mov_metadata_track_or_disc_number; break;
00201     case MKTAG( 'd','i','s','k'): key = "disc";
00202         parse = mov_metadata_track_or_disc_number; break;
00203     case MKTAG( 't','v','e','s'): key = "episode_sort";
00204         parse = mov_metadata_int8_bypass_padding; break;
00205     case MKTAG( 't','v','s','n'): key = "season_number";
00206         parse = mov_metadata_int8_bypass_padding; break;
00207     case MKTAG( 's','t','i','k'): key = "media_type";
00208         parse = mov_metadata_int8_no_padding; break;
00209     case MKTAG( 'h','d','v','d'): key = "hd_video";
00210         parse = mov_metadata_int8_no_padding; break;
00211     case MKTAG( 'p','g','a','p'): key = "gapless_playback";
00212         parse = mov_metadata_int8_no_padding; break;
00213     }
00214 
00215     if (c->itunes_metadata && atom.size > 8) {
00216         int data_size = avio_rb32(pb);
00217         int tag = avio_rl32(pb);
00218         if (tag == MKTAG('d','a','t','a')) {
00219             data_type = avio_rb32(pb); // type
00220             avio_rb32(pb); // unknown
00221             str_size = data_size - 16;
00222             atom.size -= 16;
00223         } else return 0;
00224     } else if (atom.size > 4 && key && !c->itunes_metadata) {
00225         str_size = avio_rb16(pb); // string length
00226         langcode = avio_rb16(pb);
00227         ff_mov_lang_to_iso639(langcode, language);
00228         atom.size -= 4;
00229     } else
00230         str_size = atom.size;
00231 
00232 #ifdef MOV_EXPORT_ALL_METADATA
00233     if (!key) {
00234         snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
00235         key = tmp_key;
00236     }
00237 #endif
00238 
00239     if (!key)
00240         return 0;
00241     if (atom.size < 0)
00242         return AVERROR_INVALIDDATA;
00243 
00244     str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
00245 
00246     if (parse)
00247         parse(c, pb, str_size, key);
00248     else {
00249         if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
00250             mov_read_mac_string(c, pb, str_size, str, sizeof(str));
00251         } else {
00252             avio_read(pb, str, str_size);
00253             str[str_size] = 0;
00254         }
00255         av_dict_set(&c->fc->metadata, key, str, 0);
00256         if (*language && strcmp(language, "und")) {
00257             snprintf(key2, sizeof(key2), "%s-%s", key, language);
00258             av_dict_set(&c->fc->metadata, key2, str, 0);
00259         }
00260     }
00261     av_dlog(c->fc, "lang \"%3s\" ", language);
00262     av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
00263             key, str, (char*)&atom.type, str_size, atom.size);
00264 
00265     return 0;
00266 }
00267 
00268 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00269 {
00270     int64_t start;
00271     int i, nb_chapters, str_len, version;
00272     char str[256+1];
00273 
00274     if ((atom.size -= 5) < 0)
00275         return 0;
00276 
00277     version = avio_r8(pb);
00278     avio_rb24(pb);
00279     if (version)
00280         avio_rb32(pb); // ???
00281     nb_chapters = avio_r8(pb);
00282 
00283     for (i = 0; i < nb_chapters; i++) {
00284         if (atom.size < 9)
00285             return 0;
00286 
00287         start = avio_rb64(pb);
00288         str_len = avio_r8(pb);
00289 
00290         if ((atom.size -= 9+str_len) < 0)
00291             return 0;
00292 
00293         avio_read(pb, str, str_len);
00294         str[str_len] = 0;
00295         avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
00296     }
00297     return 0;
00298 }
00299 
00300 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00301 {
00302     int64_t total_size = 0;
00303     MOVAtom a;
00304     int i;
00305 
00306     if (atom.size < 0)
00307         atom.size = INT64_MAX;
00308     while (total_size + 8 < atom.size && !pb->eof_reached) {
00309         int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
00310         a.size = atom.size;
00311         a.type=0;
00312         if (atom.size >= 8) {
00313             a.size = avio_rb32(pb);
00314             a.type = avio_rl32(pb);
00315         }
00316         av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
00317                 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
00318         total_size += 8;
00319         if (a.size == 1) { /* 64 bit extended size */
00320             a.size = avio_rb64(pb) - 8;
00321             total_size += 8;
00322         }
00323         if (a.size == 0) {
00324             a.size = atom.size - total_size;
00325             if (a.size <= 8)
00326                 break;
00327         }
00328         a.size -= 8;
00329         if (a.size < 0)
00330             break;
00331         a.size = FFMIN(a.size, atom.size - total_size);
00332 
00333         for (i = 0; mov_default_parse_table[i].type; i++)
00334             if (mov_default_parse_table[i].type == a.type) {
00335                 parse = mov_default_parse_table[i].parse;
00336                 break;
00337             }
00338 
00339         // container is user data
00340         if (!parse && (atom.type == MKTAG('u','d','t','a') ||
00341                        atom.type == MKTAG('i','l','s','t')))
00342             parse = mov_read_udta_string;
00343 
00344         if (!parse) { /* skip leaf atoms data */
00345             avio_skip(pb, a.size);
00346         } else {
00347             int64_t start_pos = avio_tell(pb);
00348             int64_t left;
00349             int err = parse(c, pb, a);
00350             if (err < 0)
00351                 return err;
00352             if (c->found_moov && c->found_mdat &&
00353                 (!pb->seekable || start_pos + a.size == avio_size(pb)))
00354                 return 0;
00355             left = a.size - avio_tell(pb) + start_pos;
00356             if (left > 0) /* skip garbage at atom end */
00357                 avio_skip(pb, left);
00358         }
00359 
00360         total_size += a.size;
00361     }
00362 
00363     if (total_size < atom.size && atom.size < 0x7ffff)
00364         avio_skip(pb, atom.size - total_size);
00365 
00366     return 0;
00367 }
00368 
00369 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00370 {
00371     AVStream *st;
00372     MOVStreamContext *sc;
00373     int entries, i, j;
00374 
00375     if (c->fc->nb_streams < 1)
00376         return 0;
00377     st = c->fc->streams[c->fc->nb_streams-1];
00378     sc = st->priv_data;
00379 
00380     avio_rb32(pb); // version + flags
00381     entries = avio_rb32(pb);
00382     if (entries >= UINT_MAX / sizeof(*sc->drefs))
00383         return AVERROR_INVALIDDATA;
00384     sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
00385     if (!sc->drefs)
00386         return AVERROR(ENOMEM);
00387     sc->drefs_count = entries;
00388 
00389     for (i = 0; i < sc->drefs_count; i++) {
00390         MOVDref *dref = &sc->drefs[i];
00391         uint32_t size = avio_rb32(pb);
00392         int64_t next = avio_tell(pb) + size - 4;
00393 
00394         if (size < 12)
00395             return AVERROR_INVALIDDATA;
00396 
00397         dref->type = avio_rl32(pb);
00398         avio_rb32(pb); // version + flags
00399         av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
00400 
00401         if (dref->type == MKTAG('a','l','i','s') && size > 150) {
00402             /* macintosh alias record */
00403             uint16_t volume_len, len;
00404             int16_t type;
00405 
00406             avio_skip(pb, 10);
00407 
00408             volume_len = avio_r8(pb);
00409             volume_len = FFMIN(volume_len, 27);
00410             avio_read(pb, dref->volume, 27);
00411             dref->volume[volume_len] = 0;
00412             av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
00413 
00414             avio_skip(pb, 12);
00415 
00416             len = avio_r8(pb);
00417             len = FFMIN(len, 63);
00418             avio_read(pb, dref->filename, 63);
00419             dref->filename[len] = 0;
00420             av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
00421 
00422             avio_skip(pb, 16);
00423 
00424             /* read next level up_from_alias/down_to_target */
00425             dref->nlvl_from = avio_rb16(pb);
00426             dref->nlvl_to   = avio_rb16(pb);
00427             av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
00428                    dref->nlvl_from, dref->nlvl_to);
00429 
00430             avio_skip(pb, 16);
00431 
00432             for (type = 0; type != -1 && avio_tell(pb) < next; ) {
00433                 type = avio_rb16(pb);
00434                 len = avio_rb16(pb);
00435                 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
00436                 if (len&1)
00437                     len += 1;
00438                 if (type == 2) { // absolute path
00439                     av_free(dref->path);
00440                     dref->path = av_mallocz(len+1);
00441                     if (!dref->path)
00442                         return AVERROR(ENOMEM);
00443                     avio_read(pb, dref->path, len);
00444                     if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
00445                         len -= volume_len;
00446                         memmove(dref->path, dref->path+volume_len, len);
00447                         dref->path[len] = 0;
00448                     }
00449                     for (j = 0; j < len; j++)
00450                         if (dref->path[j] == ':')
00451                             dref->path[j] = '/';
00452                     av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
00453                 } else if (type == 0) { // directory name
00454                     av_free(dref->dir);
00455                     dref->dir = av_malloc(len+1);
00456                     if (!dref->dir)
00457                         return AVERROR(ENOMEM);
00458                     avio_read(pb, dref->dir, len);
00459                     dref->dir[len] = 0;
00460                     for (j = 0; j < len; j++)
00461                         if (dref->dir[j] == ':')
00462                             dref->dir[j] = '/';
00463                     av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
00464                 } else
00465                     avio_skip(pb, len);
00466             }
00467         }
00468         avio_seek(pb, next, SEEK_SET);
00469     }
00470     return 0;
00471 }
00472 
00473 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00474 {
00475     AVStream *st;
00476     uint32_t type;
00477     uint32_t av_unused ctype;
00478 
00479     if (c->fc->nb_streams < 1) // meta before first trak
00480         return 0;
00481 
00482     st = c->fc->streams[c->fc->nb_streams-1];
00483 
00484     avio_r8(pb); /* version */
00485     avio_rb24(pb); /* flags */
00486 
00487     /* component type */
00488     ctype = avio_rl32(pb);
00489     type = avio_rl32(pb); /* component subtype */
00490 
00491     av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
00492     av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
00493 
00494     if     (type == MKTAG('v','i','d','e'))
00495         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
00496     else if (type == MKTAG('s','o','u','n'))
00497         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
00498     else if (type == MKTAG('m','1','a',' '))
00499         st->codec->codec_id = CODEC_ID_MP2;
00500     else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
00501         st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
00502 
00503     avio_rb32(pb); /* component  manufacture */
00504     avio_rb32(pb); /* component flags */
00505     avio_rb32(pb); /* component flags mask */
00506 
00507     return 0;
00508 }
00509 
00510 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
00511 {
00512     AVStream *st;
00513     int tag;
00514 
00515     if (fc->nb_streams < 1)
00516         return 0;
00517     st = fc->streams[fc->nb_streams-1];
00518 
00519     avio_rb32(pb); /* version + flags */
00520     ff_mp4_read_descr(fc, pb, &tag);
00521     if (tag == MP4ESDescrTag) {
00522         ff_mp4_parse_es_descr(pb, NULL);
00523     } else
00524         avio_rb16(pb); /* ID */
00525 
00526     ff_mp4_read_descr(fc, pb, &tag);
00527     if (tag == MP4DecConfigDescrTag)
00528         ff_mp4_read_dec_config_descr(fc, st, pb);
00529     return 0;
00530 }
00531 
00532 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00533 {
00534     return ff_mov_read_esds(c->fc, pb, atom);
00535 }
00536 
00537 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00538 {
00539     AVStream *st;
00540     int ac3info, acmod, lfeon, bsmod;
00541 
00542     if (c->fc->nb_streams < 1)
00543         return 0;
00544     st = c->fc->streams[c->fc->nb_streams-1];
00545 
00546     ac3info = avio_rb24(pb);
00547     bsmod = (ac3info >> 14) & 0x7;
00548     acmod = (ac3info >> 11) & 0x7;
00549     lfeon = (ac3info >> 10) & 0x1;
00550     st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
00551     st->codec->audio_service_type = bsmod;
00552     if (st->codec->channels > 1 && bsmod == 0x7)
00553         st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
00554 
00555     return 0;
00556 }
00557 
00558 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00559 {
00560     AVStream *st;
00561     uint8_t version;
00562     uint32_t flags, layout_tag, bitmap, num_descr, label_mask;
00563     int i;
00564 
00565     if (c->fc->nb_streams < 1)
00566         return 0;
00567     st = c->fc->streams[c->fc->nb_streams-1];
00568 
00569     if (atom.size < 16)
00570         return 0;
00571 
00572     version = avio_r8(pb);
00573     flags   = avio_rb24(pb);
00574 
00575     layout_tag = avio_rb32(pb);
00576     bitmap     = avio_rb32(pb);
00577     num_descr  = avio_rb32(pb);
00578 
00579     if (atom.size < 16ULL + num_descr * 20ULL)
00580         return 0;
00581 
00582     av_dlog(c->fc, "chan: size=%ld version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
00583             atom.size, version, flags, layout_tag, bitmap, num_descr);
00584 
00585     label_mask = 0;
00586     for (i = 0; i < num_descr; i++) {
00587         uint32_t label, cflags;
00588         label     = avio_rb32(pb);          // mChannelLabel
00589         cflags    = avio_rb32(pb);          // mChannelFlags
00590         avio_rl32(pb);                      // mCoordinates[0]
00591         avio_rl32(pb);                      // mCoordinates[1]
00592         avio_rl32(pb);                      // mCoordinates[2]
00593         if (layout_tag == 0) {
00594             uint32_t mask_incr = ff_mov_get_channel_label(label);
00595             if (mask_incr == 0) {
00596                 label_mask = 0;
00597                 break;
00598             }
00599             label_mask |= mask_incr;
00600         }
00601     }
00602     if (layout_tag == 0)
00603         st->codec->channel_layout = label_mask;
00604     else
00605         st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
00606 
00607     return 0;
00608 }
00609 
00610 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00611 {
00612     AVStream *st;
00613 
00614     if (c->fc->nb_streams < 1)
00615         return 0;
00616     st = c->fc->streams[c->fc->nb_streams-1];
00617 
00618     ff_get_wav_header(pb, st->codec, atom.size);
00619 
00620     return 0;
00621 }
00622 
00623 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00624 {
00625     const int num = avio_rb32(pb);
00626     const int den = avio_rb32(pb);
00627     AVStream *st;
00628 
00629     if (c->fc->nb_streams < 1)
00630         return 0;
00631     st = c->fc->streams[c->fc->nb_streams-1];
00632 
00633     if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
00634         (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
00635         av_log(c->fc, AV_LOG_WARNING,
00636                "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
00637                st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
00638                num, den);
00639     } else if (den != 0) {
00640         st->sample_aspect_ratio.num = num;
00641         st->sample_aspect_ratio.den = den;
00642     }
00643     return 0;
00644 }
00645 
00646 /* this atom contains actual media data */
00647 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00648 {
00649     if (atom.size == 0) /* wrong one (MP4) */
00650         return 0;
00651     c->found_mdat=1;
00652     return 0; /* now go for moov */
00653 }
00654 
00655 /* read major brand, minor version and compatible brands and store them as metadata */
00656 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00657 {
00658     uint32_t minor_ver;
00659     int comp_brand_size;
00660     char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
00661     char* comp_brands_str;
00662     uint8_t type[5] = {0};
00663 
00664     avio_read(pb, type, 4);
00665     if (strcmp(type, "qt  "))
00666         c->isom = 1;
00667     av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
00668     av_dict_set(&c->fc->metadata, "major_brand", type, 0);
00669     minor_ver = avio_rb32(pb); /* minor version */
00670     snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
00671     av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
00672 
00673     comp_brand_size = atom.size - 8;
00674     if (comp_brand_size < 0)
00675         return AVERROR_INVALIDDATA;
00676     comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
00677     if (!comp_brands_str)
00678         return AVERROR(ENOMEM);
00679     avio_read(pb, comp_brands_str, comp_brand_size);
00680     comp_brands_str[comp_brand_size] = 0;
00681     av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
00682     av_freep(&comp_brands_str);
00683 
00684     return 0;
00685 }
00686 
00687 /* this atom should contain all header atoms */
00688 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00689 {
00690     int ret;
00691 
00692     if ((ret = mov_read_default(c, pb, atom)) < 0)
00693         return ret;
00694     /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
00695     /* so we don't parse the whole file if over a network */
00696     c->found_moov=1;
00697     return 0; /* now go for mdat */
00698 }
00699 
00700 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00701 {
00702     c->fragment.moof_offset = avio_tell(pb) - 8;
00703     av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
00704     return mov_read_default(c, pb, atom);
00705 }
00706 
00707 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
00708 {
00709     char buffer[32];
00710     if (time) {
00711         struct tm *ptm;
00712         time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
00713         ptm = gmtime(&time);
00714         if (!ptm) return;
00715         strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
00716         av_dict_set(metadata, "creation_time", buffer, 0);
00717     }
00718 }
00719 
00720 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00721 {
00722     AVStream *st;
00723     MOVStreamContext *sc;
00724     int version;
00725     char language[4] = {0};
00726     unsigned lang;
00727     time_t creation_time;
00728 
00729     if (c->fc->nb_streams < 1)
00730         return 0;
00731     st = c->fc->streams[c->fc->nb_streams-1];
00732     sc = st->priv_data;
00733 
00734     version = avio_r8(pb);
00735     if (version > 1) {
00736         av_log_ask_for_sample(c, "unsupported version %d\n", version);
00737         return AVERROR_PATCHWELCOME;
00738     }
00739     avio_rb24(pb); /* flags */
00740     if (version == 1) {
00741         creation_time = avio_rb64(pb);
00742         avio_rb64(pb);
00743     } else {
00744         creation_time = avio_rb32(pb);
00745         avio_rb32(pb); /* modification time */
00746     }
00747     mov_metadata_creation_time(&st->metadata, creation_time);
00748 
00749     sc->time_scale = avio_rb32(pb);
00750     st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
00751 
00752     lang = avio_rb16(pb); /* language */
00753     if (ff_mov_lang_to_iso639(lang, language))
00754         av_dict_set(&st->metadata, "language", language, 0);
00755     avio_rb16(pb); /* quality */
00756 
00757     return 0;
00758 }
00759 
00760 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00761 {
00762     time_t creation_time;
00763     int version = avio_r8(pb); /* version */
00764     avio_rb24(pb); /* flags */
00765 
00766     if (version == 1) {
00767         creation_time = avio_rb64(pb);
00768         avio_rb64(pb);
00769     } else {
00770         creation_time = avio_rb32(pb);
00771         avio_rb32(pb); /* modification time */
00772     }
00773     mov_metadata_creation_time(&c->fc->metadata, creation_time);
00774     c->time_scale = avio_rb32(pb); /* time scale */
00775 
00776     av_dlog(c->fc, "time scale = %i\n", c->time_scale);
00777 
00778     c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
00779     avio_rb32(pb); /* preferred scale */
00780 
00781     avio_rb16(pb); /* preferred volume */
00782 
00783     avio_skip(pb, 10); /* reserved */
00784 
00785     avio_skip(pb, 36); /* display matrix */
00786 
00787     avio_rb32(pb); /* preview time */
00788     avio_rb32(pb); /* preview duration */
00789     avio_rb32(pb); /* poster time */
00790     avio_rb32(pb); /* selection time */
00791     avio_rb32(pb); /* selection duration */
00792     avio_rb32(pb); /* current time */
00793     avio_rb32(pb); /* next track ID */
00794 
00795     return 0;
00796 }
00797 
00798 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00799 {
00800     AVStream *st;
00801 
00802     if (c->fc->nb_streams < 1)
00803         return 0;
00804     st = c->fc->streams[c->fc->nb_streams-1];
00805 
00806     if ((uint64_t)atom.size > (1<<30))
00807         return AVERROR_INVALIDDATA;
00808 
00809     // currently SVQ3 decoder expect full STSD header - so let's fake it
00810     // this should be fixed and just SMI header should be passed
00811     av_free(st->codec->extradata);
00812     st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
00813     if (!st->codec->extradata)
00814         return AVERROR(ENOMEM);
00815     st->codec->extradata_size = 0x5a + atom.size;
00816     memcpy(st->codec->extradata, "SVQ3", 4); // fake
00817     avio_read(pb, st->codec->extradata + 0x5a, atom.size);
00818     av_dlog(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
00819     return 0;
00820 }
00821 
00822 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00823 {
00824     AVStream *st;
00825     int little_endian;
00826 
00827     if (c->fc->nb_streams < 1)
00828         return 0;
00829     st = c->fc->streams[c->fc->nb_streams-1];
00830 
00831     little_endian = avio_rb16(pb);
00832     av_dlog(c->fc, "enda %d\n", little_endian);
00833     if (little_endian == 1) {
00834         switch (st->codec->codec_id) {
00835         case CODEC_ID_PCM_S24BE:
00836             st->codec->codec_id = CODEC_ID_PCM_S24LE;
00837             break;
00838         case CODEC_ID_PCM_S32BE:
00839             st->codec->codec_id = CODEC_ID_PCM_S32LE;
00840             break;
00841         case CODEC_ID_PCM_F32BE:
00842             st->codec->codec_id = CODEC_ID_PCM_F32LE;
00843             break;
00844         case CODEC_ID_PCM_F64BE:
00845             st->codec->codec_id = CODEC_ID_PCM_F64LE;
00846             break;
00847         default:
00848             break;
00849         }
00850     }
00851     return 0;
00852 }
00853 
00854 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00855 {
00856     AVStream *st;
00857     unsigned mov_field_order;
00858     enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
00859 
00860     if (c->fc->nb_streams < 1) // will happen with jp2 files
00861         return 0;
00862     st = c->fc->streams[c->fc->nb_streams-1];
00863     if (atom.size < 2)
00864         return AVERROR_INVALIDDATA;
00865     mov_field_order = avio_rb16(pb);
00866     if ((mov_field_order & 0xFF00) == 0x0100)
00867         decoded_field_order = AV_FIELD_PROGRESSIVE;
00868     else if ((mov_field_order & 0xFF00) == 0x0200) {
00869         switch (mov_field_order & 0xFF) {
00870         case 0x01: decoded_field_order = AV_FIELD_TT;
00871                    break;
00872         case 0x06: decoded_field_order = AV_FIELD_BB;
00873                    break;
00874         case 0x09: decoded_field_order = AV_FIELD_TB;
00875                    break;
00876         case 0x0E: decoded_field_order = AV_FIELD_BT;
00877                    break;
00878         }
00879     }
00880     if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
00881         av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
00882     }
00883     st->codec->field_order = decoded_field_order;
00884 
00885     return 0;
00886 }
00887 
00888 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
00889 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00890 {
00891     AVStream *st;
00892     uint64_t size;
00893     uint8_t *buf;
00894 
00895     if (c->fc->nb_streams < 1) // will happen with jp2 files
00896         return 0;
00897     st= c->fc->streams[c->fc->nb_streams-1];
00898     size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
00899     if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
00900         return AVERROR_INVALIDDATA;
00901     buf= av_realloc(st->codec->extradata, size);
00902     if (!buf)
00903         return AVERROR(ENOMEM);
00904     st->codec->extradata= buf;
00905     buf+= st->codec->extradata_size;
00906     st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
00907     AV_WB32(       buf    , atom.size + 8);
00908     AV_WL32(       buf + 4, atom.type);
00909     avio_read(pb, buf + 8, atom.size);
00910     return 0;
00911 }
00912 
00913 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00914 {
00915     AVStream *st;
00916 
00917     if (c->fc->nb_streams < 1)
00918         return 0;
00919     st = c->fc->streams[c->fc->nb_streams-1];
00920 
00921     if ((uint64_t)atom.size > (1<<30))
00922         return AVERROR_INVALIDDATA;
00923 
00924     if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
00925         // pass all frma atom to codec, needed at least for QDMC and QDM2
00926         av_free(st->codec->extradata);
00927         st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
00928         if (!st->codec->extradata)
00929             return AVERROR(ENOMEM);
00930         st->codec->extradata_size = atom.size;
00931         avio_read(pb, st->codec->extradata, atom.size);
00932     } else if (atom.size > 8) { /* to read frma, esds atoms */
00933         int ret;
00934         if ((ret = mov_read_default(c, pb, atom)) < 0)
00935             return ret;
00936     } else
00937         avio_skip(pb, atom.size);
00938     return 0;
00939 }
00940 
00945 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00946 {
00947     AVStream *st;
00948 
00949     if (c->fc->nb_streams < 1)
00950         return 0;
00951     st = c->fc->streams[c->fc->nb_streams-1];
00952 
00953     if ((uint64_t)atom.size > (1<<30))
00954         return AVERROR_INVALIDDATA;
00955 
00956     if (atom.size >= 10) {
00957         // Broken files created by legacy versions of Libav and FFmpeg will
00958         // wrap a whole fiel atom inside of a glbl atom.
00959         unsigned size = avio_rb32(pb);
00960         unsigned type = avio_rl32(pb);
00961         avio_seek(pb, -8, SEEK_CUR);
00962         if (type == MKTAG('f','i','e','l') && size == atom.size)
00963             return mov_read_default(c, pb, atom);
00964     }
00965     av_free(st->codec->extradata);
00966     st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
00967     if (!st->codec->extradata)
00968         return AVERROR(ENOMEM);
00969     st->codec->extradata_size = atom.size;
00970     avio_read(pb, st->codec->extradata, atom.size);
00971     return 0;
00972 }
00973 
00979 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
00980 {
00981     AVStream *st;
00982 
00983     if (c->fc->nb_streams < 1)
00984         return 0;
00985     if (atom.size <= 40)
00986         return 0;
00987     st = c->fc->streams[c->fc->nb_streams-1];
00988 
00989     if ((uint64_t)atom.size > (1<<30))
00990         return AVERROR_INVALIDDATA;
00991 
00992     av_free(st->codec->extradata);
00993     st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
00994     if (!st->codec->extradata)
00995         return AVERROR(ENOMEM);
00996     st->codec->extradata_size = atom.size - 40;
00997     avio_skip(pb, 40);
00998     avio_read(pb, st->codec->extradata, atom.size - 40);
00999     return 0;
01000 }
01001 
01002 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01003 {
01004     AVStream *st;
01005     MOVStreamContext *sc;
01006     unsigned int i, entries;
01007 
01008     if (c->fc->nb_streams < 1)
01009         return 0;
01010     st = c->fc->streams[c->fc->nb_streams-1];
01011     sc = st->priv_data;
01012 
01013     avio_r8(pb); /* version */
01014     avio_rb24(pb); /* flags */
01015 
01016     entries = avio_rb32(pb);
01017 
01018     if (!entries)
01019         return 0;
01020     if (entries >= UINT_MAX/sizeof(int64_t))
01021         return AVERROR_INVALIDDATA;
01022 
01023     sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
01024     if (!sc->chunk_offsets)
01025         return AVERROR(ENOMEM);
01026     sc->chunk_count = entries;
01027 
01028     if      (atom.type == MKTAG('s','t','c','o'))
01029         for (i=0; i<entries; i++)
01030             sc->chunk_offsets[i] = avio_rb32(pb);
01031     else if (atom.type == MKTAG('c','o','6','4'))
01032         for (i=0; i<entries; i++)
01033             sc->chunk_offsets[i] = avio_rb64(pb);
01034     else
01035         return AVERROR_INVALIDDATA;
01036 
01037     return 0;
01038 }
01039 
01044 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
01045 {
01046     if (flags & 1) { // floating point
01047         if (flags & 2) { // big endian
01048             if      (bps == 32) return CODEC_ID_PCM_F32BE;
01049             else if (bps == 64) return CODEC_ID_PCM_F64BE;
01050         } else {
01051             if      (bps == 32) return CODEC_ID_PCM_F32LE;
01052             else if (bps == 64) return CODEC_ID_PCM_F64LE;
01053         }
01054     } else {
01055         if (flags & 2) {
01056             if      (bps == 8)
01057                 // signed integer
01058                 if (flags & 4)  return CODEC_ID_PCM_S8;
01059                 else            return CODEC_ID_PCM_U8;
01060             else if (bps == 16) return CODEC_ID_PCM_S16BE;
01061             else if (bps == 24) return CODEC_ID_PCM_S24BE;
01062             else if (bps == 32) return CODEC_ID_PCM_S32BE;
01063         } else {
01064             if      (bps == 8)
01065                 if (flags & 4)  return CODEC_ID_PCM_S8;
01066                 else            return CODEC_ID_PCM_U8;
01067             else if (bps == 16) return CODEC_ID_PCM_S16LE;
01068             else if (bps == 24) return CODEC_ID_PCM_S24LE;
01069             else if (bps == 32) return CODEC_ID_PCM_S32LE;
01070         }
01071     }
01072     return CODEC_ID_NONE;
01073 }
01074 
01075 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
01076 {
01077     AVStream *st;
01078     MOVStreamContext *sc;
01079     int j, pseudo_stream_id;
01080 
01081     if (c->fc->nb_streams < 1)
01082         return 0;
01083     st = c->fc->streams[c->fc->nb_streams-1];
01084     sc = st->priv_data;
01085 
01086     for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
01087         //Parsing Sample description table
01088         enum CodecID id;
01089         int dref_id = 1;
01090         MOVAtom a = { AV_RL32("stsd") };
01091         int64_t start_pos = avio_tell(pb);
01092         int size = avio_rb32(pb); /* size */
01093         uint32_t format = avio_rl32(pb); /* data format */
01094 
01095         if (size >= 16) {
01096             avio_rb32(pb); /* reserved */
01097             avio_rb16(pb); /* reserved */
01098             dref_id = avio_rb16(pb);
01099         }
01100 
01101         if (st->codec->codec_tag &&
01102             st->codec->codec_tag != format &&
01103             (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
01104                                    : st->codec->codec_tag != MKTAG('j','p','e','g'))
01105            ){
01106             /* Multiple fourcc, we skip JPEG. This is not correct, we should
01107              * export it as a separate AVStream but this needs a few changes
01108              * in the MOV demuxer, patch welcome. */
01109         multiple_stsd:
01110             av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
01111             avio_skip(pb, size - (avio_tell(pb) - start_pos));
01112             continue;
01113         }
01114         /* we cannot demux concatenated h264 streams because of different extradata */
01115         if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
01116             goto multiple_stsd;
01117         sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
01118         sc->dref_id= dref_id;
01119 
01120         st->codec->codec_tag = format;
01121         id = ff_codec_get_id(codec_movaudio_tags, format);
01122         if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
01123             id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
01124 
01125         if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
01126             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
01127         } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
01128                    format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
01129             id = ff_codec_get_id(codec_movvideo_tags, format);
01130             if (id <= 0)
01131                 id = ff_codec_get_id(ff_codec_bmp_tags, format);
01132             if (id > 0)
01133                 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
01134             else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){
01135                 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
01136                 if (id > 0)
01137                     st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
01138             }
01139         }
01140 
01141         av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
01142                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
01143                 (format >> 24) & 0xff, st->codec->codec_type);
01144 
01145         if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
01146             unsigned int color_depth, len;
01147             int color_greyscale;
01148 
01149             st->codec->codec_id = id;
01150             avio_rb16(pb); /* version */
01151             avio_rb16(pb); /* revision level */
01152             avio_rb32(pb); /* vendor */
01153             avio_rb32(pb); /* temporal quality */
01154             avio_rb32(pb); /* spatial quality */
01155 
01156             st->codec->width = avio_rb16(pb); /* width */
01157             st->codec->height = avio_rb16(pb); /* height */
01158 
01159             avio_rb32(pb); /* horiz resolution */
01160             avio_rb32(pb); /* vert resolution */
01161             avio_rb32(pb); /* data size, always 0 */
01162             avio_rb16(pb); /* frames per samples */
01163 
01164             len = avio_r8(pb); /* codec name, pascal string */
01165             if (len > 31)
01166                 len = 31;
01167             mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
01168             if (len < 31)
01169                 avio_skip(pb, 31 - len);
01170             /* codec_tag YV12 triggers an UV swap in rawdec.c */
01171             if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
01172                 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
01173 
01174             st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
01175             st->codec->color_table_id = avio_rb16(pb); /* colortable id */
01176             av_dlog(c->fc, "depth %d, ctab id %d\n",
01177                    st->codec->bits_per_coded_sample, st->codec->color_table_id);
01178             /* figure out the palette situation */
01179             color_depth = st->codec->bits_per_coded_sample & 0x1F;
01180             color_greyscale = st->codec->bits_per_coded_sample & 0x20;
01181 
01182             /* if the depth is 2, 4, or 8 bpp, file is palettized */
01183             if ((color_depth == 2) || (color_depth == 4) ||
01184                 (color_depth == 8)) {
01185                 /* for palette traversal */
01186                 unsigned int color_start, color_count, color_end;
01187                 unsigned char r, g, b;
01188 
01189                 if (color_greyscale) {
01190                     int color_index, color_dec;
01191                     /* compute the greyscale palette */
01192                     st->codec->bits_per_coded_sample = color_depth;
01193                     color_count = 1 << color_depth;
01194                     color_index = 255;
01195                     color_dec = 256 / (color_count - 1);
01196                     for (j = 0; j < color_count; j++) {
01197                         r = g = b = color_index;
01198                         sc->palette[j] =
01199                             (r << 16) | (g << 8) | (b);
01200                         color_index -= color_dec;
01201                         if (color_index < 0)
01202                             color_index = 0;
01203                     }
01204                 } else if (st->codec->color_table_id) {
01205                     const uint8_t *color_table;
01206                     /* if flag bit 3 is set, use the default palette */
01207                     color_count = 1 << color_depth;
01208                     if (color_depth == 2)
01209                         color_table = ff_qt_default_palette_4;
01210                     else if (color_depth == 4)
01211                         color_table = ff_qt_default_palette_16;
01212                     else
01213                         color_table = ff_qt_default_palette_256;
01214 
01215                     for (j = 0; j < color_count; j++) {
01216                         r = color_table[j * 3 + 0];
01217                         g = color_table[j * 3 + 1];
01218                         b = color_table[j * 3 + 2];
01219                         sc->palette[j] =
01220                             (r << 16) | (g << 8) | (b);
01221                     }
01222                 } else {
01223                     /* load the palette from the file */
01224                     color_start = avio_rb32(pb);
01225                     color_count = avio_rb16(pb);
01226                     color_end = avio_rb16(pb);
01227                     if ((color_start <= 255) &&
01228                         (color_end <= 255)) {
01229                         for (j = color_start; j <= color_end; j++) {
01230                             /* each R, G, or B component is 16 bits;
01231                              * only use the top 8 bits; skip alpha bytes
01232                              * up front */
01233                             avio_r8(pb);
01234                             avio_r8(pb);
01235                             r = avio_r8(pb);
01236                             avio_r8(pb);
01237                             g = avio_r8(pb);
01238                             avio_r8(pb);
01239                             b = avio_r8(pb);
01240                             avio_r8(pb);
01241                             sc->palette[j] =
01242                                 (r << 16) | (g << 8) | (b);
01243                         }
01244                     }
01245                 }
01246                 sc->has_palette = 1;
01247             }
01248         } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
01249             int bits_per_sample, flags;
01250             uint16_t version = avio_rb16(pb);
01251 
01252             st->codec->codec_id = id;
01253             avio_rb16(pb); /* revision level */
01254             avio_rb32(pb); /* vendor */
01255 
01256             st->codec->channels = avio_rb16(pb);             /* channel count */
01257             av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
01258             st->codec->bits_per_coded_sample = avio_rb16(pb);      /* sample size */
01259 
01260             sc->audio_cid = avio_rb16(pb);
01261             avio_rb16(pb); /* packet size = 0 */
01262 
01263             st->codec->sample_rate = ((avio_rb32(pb) >> 16));
01264 
01265             //Read QT version 1 fields. In version 0 these do not exist.
01266             av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
01267             if (!c->isom) {
01268                 if (version==1) {
01269                     sc->samples_per_frame = avio_rb32(pb);
01270                     avio_rb32(pb); /* bytes per packet */
01271                     sc->bytes_per_frame = avio_rb32(pb);
01272                     avio_rb32(pb); /* bytes per sample */
01273                 } else if (version==2) {
01274                     avio_rb32(pb); /* sizeof struct only */
01275                     st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
01276                     st->codec->channels = avio_rb32(pb);
01277                     avio_rb32(pb); /* always 0x7F000000 */
01278                     st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
01279                     flags = avio_rb32(pb); /* lpcm format specific flag */
01280                     sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
01281                     sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
01282                     if (format == MKTAG('l','p','c','m'))
01283                         st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
01284                 }
01285             }
01286 
01287             switch (st->codec->codec_id) {
01288             case CODEC_ID_PCM_S8:
01289             case CODEC_ID_PCM_U8:
01290                 if (st->codec->bits_per_coded_sample == 16)
01291                     st->codec->codec_id = CODEC_ID_PCM_S16BE;
01292                 break;
01293             case CODEC_ID_PCM_S16LE:
01294             case CODEC_ID_PCM_S16BE:
01295                 if (st->codec->bits_per_coded_sample == 8)
01296                     st->codec->codec_id = CODEC_ID_PCM_S8;
01297                 else if (st->codec->bits_per_coded_sample == 24)
01298                     st->codec->codec_id =
01299                         st->codec->codec_id == CODEC_ID_PCM_S16BE ?
01300                         CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
01301                 break;
01302             /* set values for old format before stsd version 1 appeared */
01303             case CODEC_ID_MACE3:
01304                 sc->samples_per_frame = 6;
01305                 sc->bytes_per_frame = 2*st->codec->channels;
01306                 break;
01307             case CODEC_ID_MACE6:
01308                 sc->samples_per_frame = 6;
01309                 sc->bytes_per_frame = 1*st->codec->channels;
01310                 break;
01311             case CODEC_ID_ADPCM_IMA_QT:
01312                 sc->samples_per_frame = 64;
01313                 sc->bytes_per_frame = 34*st->codec->channels;
01314                 break;
01315             case CODEC_ID_GSM:
01316                 sc->samples_per_frame = 160;
01317                 sc->bytes_per_frame = 33;
01318                 break;
01319             default:
01320                 break;
01321             }
01322 
01323             bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
01324             if (bits_per_sample) {
01325                 st->codec->bits_per_coded_sample = bits_per_sample;
01326                 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
01327             }
01328         } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
01329             // ttxt stsd contains display flags, justification, background
01330             // color, fonts, and default styles, so fake an atom to read it
01331             MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
01332             if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
01333                 mov_read_glbl(c, pb, fake_atom);
01334             st->codec->codec_id= id;
01335             st->codec->width = sc->width;
01336             st->codec->height = sc->height;
01337         } else {
01338             /* other codec type, just skip (rtp, mp4s, tmcd ...) */
01339             avio_skip(pb, size - (avio_tell(pb) - start_pos));
01340         }
01341         /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
01342         a.size = size - (avio_tell(pb) - start_pos);
01343         if (a.size > 8) {
01344             int ret;
01345             if ((ret = mov_read_default(c, pb, a)) < 0)
01346                 return ret;
01347         } else if (a.size > 0)
01348             avio_skip(pb, a.size);
01349     }
01350 
01351     if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
01352         st->codec->sample_rate= sc->time_scale;
01353 
01354     /* special codec parameters handling */
01355     switch (st->codec->codec_id) {
01356 #if CONFIG_DV_DEMUXER
01357     case CODEC_ID_DVAUDIO:
01358         c->dv_fctx = avformat_alloc_context();
01359         c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
01360         if (!c->dv_demux) {
01361             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
01362             return AVERROR(ENOMEM);
01363         }
01364         sc->dv_audio_container = 1;
01365         st->codec->codec_id = CODEC_ID_PCM_S16LE;
01366         break;
01367 #endif
01368     /* no ifdef since parameters are always those */
01369     case CODEC_ID_QCELP:
01370         // force sample rate for qcelp when not stored in mov
01371         if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
01372             st->codec->sample_rate = 8000;
01373         st->codec->frame_size= 160;
01374         st->codec->channels= 1; /* really needed */
01375         break;
01376     case CODEC_ID_AMR_NB:
01377         st->codec->channels= 1; /* really needed */
01378         /* force sample rate for amr, stsd in 3gp does not store sample rate */
01379         st->codec->sample_rate = 8000;
01380         /* force frame_size, too, samples_per_frame isn't always set properly */
01381         st->codec->frame_size  = 160;
01382         break;
01383     case CODEC_ID_AMR_WB:
01384         st->codec->channels    = 1;
01385         st->codec->sample_rate = 16000;
01386         st->codec->frame_size  = 320;
01387         break;
01388     case CODEC_ID_MP2:
01389     case CODEC_ID_MP3:
01390         st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
01391         st->need_parsing = AVSTREAM_PARSE_FULL;
01392         break;
01393     case CODEC_ID_GSM:
01394     case CODEC_ID_ADPCM_MS:
01395     case CODEC_ID_ADPCM_IMA_WAV:
01396         st->codec->frame_size = sc->samples_per_frame;
01397         st->codec->block_align = sc->bytes_per_frame;
01398         break;
01399     case CODEC_ID_ALAC:
01400         if (st->codec->extradata_size == 36) {
01401             st->codec->frame_size = AV_RB32(st->codec->extradata+12);
01402             st->codec->channels   = AV_RB8 (st->codec->extradata+21);
01403             st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
01404         }
01405         break;
01406     default:
01407         break;
01408     }
01409 
01410     return 0;
01411 }
01412 
01413 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01414 {
01415     int entries;
01416 
01417     avio_r8(pb); /* version */
01418     avio_rb24(pb); /* flags */
01419     entries = avio_rb32(pb);
01420 
01421     return ff_mov_read_stsd_entries(c, pb, entries);
01422 }
01423 
01424 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01425 {
01426     AVStream *st;
01427     MOVStreamContext *sc;
01428     unsigned int i, entries;
01429 
01430     if (c->fc->nb_streams < 1)
01431         return 0;
01432     st = c->fc->streams[c->fc->nb_streams-1];
01433     sc = st->priv_data;
01434 
01435     avio_r8(pb); /* version */
01436     avio_rb24(pb); /* flags */
01437 
01438     entries = avio_rb32(pb);
01439 
01440     av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
01441 
01442     if (!entries)
01443         return 0;
01444     if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
01445         return AVERROR_INVALIDDATA;
01446     sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
01447     if (!sc->stsc_data)
01448         return AVERROR(ENOMEM);
01449     sc->stsc_count = entries;
01450 
01451     for (i=0; i<entries; i++) {
01452         sc->stsc_data[i].first = avio_rb32(pb);
01453         sc->stsc_data[i].count = avio_rb32(pb);
01454         sc->stsc_data[i].id = avio_rb32(pb);
01455     }
01456     return 0;
01457 }
01458 
01459 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01460 {
01461     AVStream *st;
01462     MOVStreamContext *sc;
01463     unsigned i, entries;
01464 
01465     if (c->fc->nb_streams < 1)
01466         return 0;
01467     st = c->fc->streams[c->fc->nb_streams-1];
01468     sc = st->priv_data;
01469 
01470     avio_rb32(pb); // version + flags
01471 
01472     entries = avio_rb32(pb);
01473     if (entries >= UINT_MAX / sizeof(*sc->stps_data))
01474         return AVERROR_INVALIDDATA;
01475     sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
01476     if (!sc->stps_data)
01477         return AVERROR(ENOMEM);
01478     sc->stps_count = entries;
01479 
01480     for (i = 0; i < entries; i++) {
01481         sc->stps_data[i] = avio_rb32(pb);
01482         //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
01483     }
01484 
01485     return 0;
01486 }
01487 
01488 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01489 {
01490     AVStream *st;
01491     MOVStreamContext *sc;
01492     unsigned int i, entries;
01493 
01494     if (c->fc->nb_streams < 1)
01495         return 0;
01496     st = c->fc->streams[c->fc->nb_streams-1];
01497     sc = st->priv_data;
01498 
01499     avio_r8(pb); /* version */
01500     avio_rb24(pb); /* flags */
01501 
01502     entries = avio_rb32(pb);
01503 
01504     av_dlog(c->fc, "keyframe_count = %d\n", entries);
01505 
01506     if (entries >= UINT_MAX / sizeof(int))
01507         return AVERROR_INVALIDDATA;
01508     sc->keyframes = av_malloc(entries * sizeof(int));
01509     if (!sc->keyframes)
01510         return AVERROR(ENOMEM);
01511     sc->keyframe_count = entries;
01512 
01513     for (i=0; i<entries; i++) {
01514         sc->keyframes[i] = avio_rb32(pb);
01515         //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
01516     }
01517     return 0;
01518 }
01519 
01520 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01521 {
01522     AVStream *st;
01523     MOVStreamContext *sc;
01524     unsigned int i, entries, sample_size, field_size, num_bytes;
01525     GetBitContext gb;
01526     unsigned char* buf;
01527 
01528     if (c->fc->nb_streams < 1)
01529         return 0;
01530     st = c->fc->streams[c->fc->nb_streams-1];
01531     sc = st->priv_data;
01532 
01533     avio_r8(pb); /* version */
01534     avio_rb24(pb); /* flags */
01535 
01536     if (atom.type == MKTAG('s','t','s','z')) {
01537         sample_size = avio_rb32(pb);
01538         if (!sc->sample_size) /* do not overwrite value computed in stsd */
01539             sc->sample_size = sample_size;
01540         field_size = 32;
01541     } else {
01542         sample_size = 0;
01543         avio_rb24(pb); /* reserved */
01544         field_size = avio_r8(pb);
01545     }
01546     entries = avio_rb32(pb);
01547 
01548     av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
01549 
01550     sc->sample_count = entries;
01551     if (sample_size)
01552         return 0;
01553 
01554     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
01555         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
01556         return AVERROR_INVALIDDATA;
01557     }
01558 
01559     if (!entries)
01560         return 0;
01561     if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
01562         return AVERROR_INVALIDDATA;
01563     sc->sample_sizes = av_malloc(entries * sizeof(int));
01564     if (!sc->sample_sizes)
01565         return AVERROR(ENOMEM);
01566 
01567     num_bytes = (entries*field_size+4)>>3;
01568 
01569     buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
01570     if (!buf) {
01571         av_freep(&sc->sample_sizes);
01572         return AVERROR(ENOMEM);
01573     }
01574 
01575     if (avio_read(pb, buf, num_bytes) < num_bytes) {
01576         av_freep(&sc->sample_sizes);
01577         av_free(buf);
01578         return AVERROR_INVALIDDATA;
01579     }
01580 
01581     init_get_bits(&gb, buf, 8*num_bytes);
01582 
01583     for (i=0; i<entries; i++)
01584         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
01585 
01586     av_free(buf);
01587     return 0;
01588 }
01589 
01590 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01591 {
01592     AVStream *st;
01593     MOVStreamContext *sc;
01594     unsigned int i, entries;
01595     int64_t duration=0;
01596     int64_t total_sample_count=0;
01597 
01598     if (c->fc->nb_streams < 1)
01599         return 0;
01600     st = c->fc->streams[c->fc->nb_streams-1];
01601     sc = st->priv_data;
01602 
01603     avio_r8(pb); /* version */
01604     avio_rb24(pb); /* flags */
01605     entries = avio_rb32(pb);
01606 
01607     av_dlog(c->fc, "track[%i].stts.entries = %i\n",
01608             c->fc->nb_streams-1, entries);
01609 
01610     if (!entries)
01611         return 0;
01612     if (entries >= UINT_MAX / sizeof(*sc->stts_data))
01613         return AVERROR(EINVAL);
01614 
01615     sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
01616     if (!sc->stts_data)
01617         return AVERROR(ENOMEM);
01618 
01619     sc->stts_count = entries;
01620 
01621     for (i=0; i<entries; i++) {
01622         int sample_duration;
01623         int sample_count;
01624 
01625         sample_count=avio_rb32(pb);
01626         sample_duration = avio_rb32(pb);
01627         sc->stts_data[i].count= sample_count;
01628         sc->stts_data[i].duration= sample_duration;
01629 
01630         av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
01631                 sample_count, sample_duration);
01632 
01633         duration+=(int64_t)sample_duration*sample_count;
01634         total_sample_count+=sample_count;
01635     }
01636 
01637     st->nb_frames= total_sample_count;
01638     if (duration)
01639         st->duration= duration;
01640     return 0;
01641 }
01642 
01643 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01644 {
01645     AVStream *st;
01646     MOVStreamContext *sc;
01647     unsigned int i, entries;
01648 
01649     if (c->fc->nb_streams < 1)
01650         return 0;
01651     st = c->fc->streams[c->fc->nb_streams-1];
01652     sc = st->priv_data;
01653 
01654     avio_r8(pb); /* version */
01655     avio_rb24(pb); /* flags */
01656     entries = avio_rb32(pb);
01657 
01658     av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
01659 
01660     if (!entries)
01661         return 0;
01662     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
01663         return AVERROR_INVALIDDATA;
01664     sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
01665     if (!sc->ctts_data)
01666         return AVERROR(ENOMEM);
01667     sc->ctts_count = entries;
01668 
01669     for (i=0; i<entries; i++) {
01670         int count    =avio_rb32(pb);
01671         int duration =avio_rb32(pb);
01672 
01673         sc->ctts_data[i].count   = count;
01674         sc->ctts_data[i].duration= duration;
01675         if (duration < 0)
01676             sc->dts_shift = FFMAX(sc->dts_shift, -duration);
01677     }
01678 
01679     av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
01680 
01681     return 0;
01682 }
01683 
01684 static void mov_build_index(MOVContext *mov, AVStream *st)
01685 {
01686     MOVStreamContext *sc = st->priv_data;
01687     int64_t current_offset;
01688     int64_t current_dts = 0;
01689     unsigned int stts_index = 0;
01690     unsigned int stsc_index = 0;
01691     unsigned int stss_index = 0;
01692     unsigned int stps_index = 0;
01693     unsigned int i, j;
01694     uint64_t stream_size = 0;
01695 
01696     /* adjust first dts according to edit list */
01697     if (sc->time_offset && mov->time_scale > 0) {
01698         if (sc->time_offset < 0)
01699             sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
01700         current_dts = -sc->time_offset;
01701         if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
01702             sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
01703             /* more than 16 frames delay, dts are likely wrong
01704                this happens with files created by iMovie */
01705             sc->wrong_dts = 1;
01706             st->codec->has_b_frames = 1;
01707         }
01708     }
01709 
01710     /* only use old uncompressed audio chunk demuxing when stts specifies it */
01711     if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
01712           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
01713         unsigned int current_sample = 0;
01714         unsigned int stts_sample = 0;
01715         unsigned int sample_size;
01716         unsigned int distance = 0;
01717         int key_off = sc->keyframes && sc->keyframes[0] == 1;
01718 
01719         current_dts -= sc->dts_shift;
01720 
01721         if (!sc->sample_count)
01722             return;
01723         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
01724             return;
01725         st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
01726         if (!st->index_entries)
01727             return;
01728         st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
01729 
01730         for (i = 0; i < sc->chunk_count; i++) {
01731             current_offset = sc->chunk_offsets[i];
01732             while (stsc_index + 1 < sc->stsc_count &&
01733                 i + 1 == sc->stsc_data[stsc_index + 1].first)
01734                 stsc_index++;
01735             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
01736                 int keyframe = 0;
01737                 if (current_sample >= sc->sample_count) {
01738                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
01739                     return;
01740                 }
01741 
01742                 if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
01743                     keyframe = 1;
01744                     if (stss_index + 1 < sc->keyframe_count)
01745                         stss_index++;
01746                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
01747                     keyframe = 1;
01748                     if (stps_index + 1 < sc->stps_count)
01749                         stps_index++;
01750                 }
01751                 if (keyframe)
01752                     distance = 0;
01753                 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
01754                 if (sc->pseudo_stream_id == -1 ||
01755                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
01756                     AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
01757                     e->pos = current_offset;
01758                     e->timestamp = current_dts;
01759                     e->size = sample_size;
01760                     e->min_distance = distance;
01761                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
01762                     av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
01763                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
01764                             current_offset, current_dts, sample_size, distance, keyframe);
01765                 }
01766 
01767                 current_offset += sample_size;
01768                 stream_size += sample_size;
01769                 current_dts += sc->stts_data[stts_index].duration;
01770                 distance++;
01771                 stts_sample++;
01772                 current_sample++;
01773                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
01774                     stts_sample = 0;
01775                     stts_index++;
01776                 }
01777             }
01778         }
01779         if (st->duration > 0)
01780             st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
01781     } else {
01782         unsigned chunk_samples, total = 0;
01783 
01784         // compute total chunk count
01785         for (i = 0; i < sc->stsc_count; i++) {
01786             unsigned count, chunk_count;
01787 
01788             chunk_samples = sc->stsc_data[i].count;
01789             if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
01790                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
01791                 return;
01792             }
01793 
01794             if (sc->samples_per_frame >= 160) { // gsm
01795                 count = chunk_samples / sc->samples_per_frame;
01796             } else if (sc->samples_per_frame > 1) {
01797                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
01798                 count = (chunk_samples+samples-1) / samples;
01799             } else {
01800                 count = (chunk_samples+1023) / 1024;
01801             }
01802 
01803             if (i < sc->stsc_count - 1)
01804                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
01805             else
01806                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
01807             total += chunk_count * count;
01808         }
01809 
01810         av_dlog(mov->fc, "chunk count %d\n", total);
01811         if (total >= UINT_MAX / sizeof(*st->index_entries))
01812             return;
01813         st->index_entries = av_malloc(total*sizeof(*st->index_entries));
01814         if (!st->index_entries)
01815             return;
01816         st->index_entries_allocated_size = total*sizeof(*st->index_entries);
01817 
01818         // populate index
01819         for (i = 0; i < sc->chunk_count; i++) {
01820             current_offset = sc->chunk_offsets[i];
01821             if (stsc_index + 1 < sc->stsc_count &&
01822                 i + 1 == sc->stsc_data[stsc_index + 1].first)
01823                 stsc_index++;
01824             chunk_samples = sc->stsc_data[stsc_index].count;
01825 
01826             while (chunk_samples > 0) {
01827                 AVIndexEntry *e;
01828                 unsigned size, samples;
01829 
01830                 if (sc->samples_per_frame >= 160) { // gsm
01831                     samples = sc->samples_per_frame;
01832                     size = sc->bytes_per_frame;
01833                 } else {
01834                     if (sc->samples_per_frame > 1) {
01835                         samples = FFMIN((1024 / sc->samples_per_frame)*
01836                                         sc->samples_per_frame, chunk_samples);
01837                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
01838                     } else {
01839                         samples = FFMIN(1024, chunk_samples);
01840                         size = samples * sc->sample_size;
01841                     }
01842                 }
01843 
01844                 if (st->nb_index_entries >= total) {
01845                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
01846                     return;
01847                 }
01848                 e = &st->index_entries[st->nb_index_entries++];
01849                 e->pos = current_offset;
01850                 e->timestamp = current_dts;
01851                 e->size = size;
01852                 e->min_distance = 0;
01853                 e->flags = AVINDEX_KEYFRAME;
01854                 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
01855                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
01856                         size, samples);
01857 
01858                 current_offset += size;
01859                 current_dts += samples;
01860                 chunk_samples -= samples;
01861             }
01862         }
01863     }
01864 }
01865 
01866 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
01867                          AVIOInterruptCB *int_cb)
01868 {
01869     /* try relative path, we do not try the absolute because it can leak information about our
01870        system to an attacker */
01871     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
01872         char filename[1024];
01873         char *src_path;
01874         int i, l;
01875 
01876         /* find a source dir */
01877         src_path = strrchr(src, '/');
01878         if (src_path)
01879             src_path++;
01880         else
01881             src_path = src;
01882 
01883         /* find a next level down to target */
01884         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
01885             if (ref->path[l] == '/') {
01886                 if (i == ref->nlvl_to - 1)
01887                     break;
01888                 else
01889                     i++;
01890             }
01891 
01892         /* compose filename if next level down to target was found */
01893         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
01894             memcpy(filename, src, src_path - src);
01895             filename[src_path - src] = 0;
01896 
01897             for (i = 1; i < ref->nlvl_from; i++)
01898                 av_strlcat(filename, "../", 1024);
01899 
01900             av_strlcat(filename, ref->path + l + 1, 1024);
01901 
01902             if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
01903                 return 0;
01904         }
01905     }
01906 
01907     return AVERROR(ENOENT);
01908 }
01909 
01910 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01911 {
01912     AVStream *st;
01913     MOVStreamContext *sc;
01914     int ret;
01915 
01916     st = avformat_new_stream(c->fc, NULL);
01917     if (!st) return AVERROR(ENOMEM);
01918     st->id = c->fc->nb_streams;
01919     sc = av_mallocz(sizeof(MOVStreamContext));
01920     if (!sc) return AVERROR(ENOMEM);
01921 
01922     st->priv_data = sc;
01923     st->codec->codec_type = AVMEDIA_TYPE_DATA;
01924     sc->ffindex = st->index;
01925 
01926     if ((ret = mov_read_default(c, pb, atom)) < 0)
01927         return ret;
01928 
01929     /* sanity checks */
01930     if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
01931                             (!sc->sample_size && !sc->sample_count))) {
01932         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
01933                st->index);
01934         return 0;
01935     }
01936 
01937     if (sc->time_scale <= 0) {
01938         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
01939         sc->time_scale = c->time_scale;
01940         if (sc->time_scale <= 0)
01941             sc->time_scale = 1;
01942     }
01943 
01944     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
01945 
01946     if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
01947         !st->codec->frame_size && sc->stts_count == 1) {
01948         st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
01949                                            st->codec->sample_rate, sc->time_scale);
01950         av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
01951     }
01952 
01953     mov_build_index(c, st);
01954 
01955     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
01956         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
01957         if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
01958             av_log(c->fc, AV_LOG_ERROR,
01959                    "stream %d, error opening alias: path='%s', dir='%s', "
01960                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
01961                    st->index, dref->path, dref->dir, dref->filename,
01962                    dref->volume, dref->nlvl_from, dref->nlvl_to);
01963     } else
01964         sc->pb = c->fc->pb;
01965 
01966     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
01967         if (!st->sample_aspect_ratio.num &&
01968             (st->codec->width != sc->width || st->codec->height != sc->height)) {
01969             st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
01970                                              ((double)st->codec->width * sc->height), INT_MAX);
01971         }
01972 
01973         av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
01974                   sc->time_scale*st->nb_frames, st->duration, INT_MAX);
01975 
01976         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
01977             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
01978                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
01979     }
01980 
01981     switch (st->codec->codec_id) {
01982 #if CONFIG_H261_DECODER
01983     case CODEC_ID_H261:
01984 #endif
01985 #if CONFIG_H263_DECODER
01986     case CODEC_ID_H263:
01987 #endif
01988 #if CONFIG_H264_DECODER
01989     case CODEC_ID_H264:
01990 #endif
01991 #if CONFIG_MPEG4_DECODER
01992     case CODEC_ID_MPEG4:
01993 #endif
01994         st->codec->width = 0; /* let decoder init width/height */
01995         st->codec->height= 0;
01996         break;
01997     }
01998 
01999     /* Do not need those anymore. */
02000     av_freep(&sc->chunk_offsets);
02001     av_freep(&sc->stsc_data);
02002     av_freep(&sc->sample_sizes);
02003     av_freep(&sc->keyframes);
02004     av_freep(&sc->stts_data);
02005     av_freep(&sc->stps_data);
02006 
02007     return 0;
02008 }
02009 
02010 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02011 {
02012     int ret;
02013     c->itunes_metadata = 1;
02014     ret = mov_read_default(c, pb, atom);
02015     c->itunes_metadata = 0;
02016     return ret;
02017 }
02018 
02019 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02020 {
02021     while (atom.size > 8) {
02022         uint32_t tag = avio_rl32(pb);
02023         atom.size -= 4;
02024         if (tag == MKTAG('h','d','l','r')) {
02025             avio_seek(pb, -8, SEEK_CUR);
02026             atom.size += 8;
02027             return mov_read_default(c, pb, atom);
02028         }
02029     }
02030     return 0;
02031 }
02032 
02033 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02034 {
02035     int i;
02036     int width;
02037     int height;
02038     int64_t disp_transform[2];
02039     int display_matrix[3][2];
02040     AVStream *st;
02041     MOVStreamContext *sc;
02042     int version;
02043 
02044     if (c->fc->nb_streams < 1)
02045         return 0;
02046     st = c->fc->streams[c->fc->nb_streams-1];
02047     sc = st->priv_data;
02048 
02049     version = avio_r8(pb);
02050     avio_rb24(pb); /* flags */
02051     /*
02052     MOV_TRACK_ENABLED 0x0001
02053     MOV_TRACK_IN_MOVIE 0x0002
02054     MOV_TRACK_IN_PREVIEW 0x0004
02055     MOV_TRACK_IN_POSTER 0x0008
02056     */
02057 
02058     if (version == 1) {
02059         avio_rb64(pb);
02060         avio_rb64(pb);
02061     } else {
02062         avio_rb32(pb); /* creation time */
02063         avio_rb32(pb); /* modification time */
02064     }
02065     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
02066     avio_rb32(pb); /* reserved */
02067 
02068     /* highlevel (considering edits) duration in movie timebase */
02069     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
02070     avio_rb32(pb); /* reserved */
02071     avio_rb32(pb); /* reserved */
02072 
02073     avio_rb16(pb); /* layer */
02074     avio_rb16(pb); /* alternate group */
02075     avio_rb16(pb); /* volume */
02076     avio_rb16(pb); /* reserved */
02077 
02078     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
02079     // they're kept in fixed point format through all calculations
02080     // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
02081     for (i = 0; i < 3; i++) {
02082         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
02083         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
02084         avio_rb32(pb);           // 2.30 fixed point (not used)
02085     }
02086 
02087     width = avio_rb32(pb);       // 16.16 fixed point track width
02088     height = avio_rb32(pb);      // 16.16 fixed point track height
02089     sc->width = width >> 16;
02090     sc->height = height >> 16;
02091 
02092     // transform the display width/height according to the matrix
02093     // skip this if the display matrix is the default identity matrix
02094     // or if it is rotating the picture, ex iPhone 3GS
02095     // to keep the same scale, use [width height 1<<16]
02096     if (width && height &&
02097         ((display_matrix[0][0] != 65536  ||
02098           display_matrix[1][1] != 65536) &&
02099          !display_matrix[0][1] &&
02100          !display_matrix[1][0] &&
02101          !display_matrix[2][0] && !display_matrix[2][1])) {
02102         for (i = 0; i < 2; i++)
02103             disp_transform[i] =
02104                 (int64_t)  width  * display_matrix[0][i] +
02105                 (int64_t)  height * display_matrix[1][i] +
02106                 ((int64_t) display_matrix[2][i] << 16);
02107 
02108         //sample aspect ratio is new width/height divided by old width/height
02109         st->sample_aspect_ratio = av_d2q(
02110             ((double) disp_transform[0] * height) /
02111             ((double) disp_transform[1] * width), INT_MAX);
02112     }
02113     return 0;
02114 }
02115 
02116 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02117 {
02118     MOVFragment *frag = &c->fragment;
02119     MOVTrackExt *trex = NULL;
02120     int flags, track_id, i;
02121 
02122     avio_r8(pb); /* version */
02123     flags = avio_rb24(pb);
02124 
02125     track_id = avio_rb32(pb);
02126     if (!track_id)
02127         return AVERROR_INVALIDDATA;
02128     frag->track_id = track_id;
02129     for (i = 0; i < c->trex_count; i++)
02130         if (c->trex_data[i].track_id == frag->track_id) {
02131             trex = &c->trex_data[i];
02132             break;
02133         }
02134     if (!trex) {
02135         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
02136         return AVERROR_INVALIDDATA;
02137     }
02138 
02139     if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
02140     else              frag->base_data_offset = frag->moof_offset;
02141     if (flags & 0x02) frag->stsd_id          = avio_rb32(pb);
02142     else              frag->stsd_id          = trex->stsd_id;
02143 
02144     frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
02145     frag->size     = flags & 0x10 ? avio_rb32(pb) : trex->size;
02146     frag->flags    = flags & 0x20 ? avio_rb32(pb) : trex->flags;
02147     av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
02148     return 0;
02149 }
02150 
02151 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02152 {
02153     c->chapter_track = avio_rb32(pb);
02154     return 0;
02155 }
02156 
02157 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02158 {
02159     MOVTrackExt *trex;
02160 
02161     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
02162         return AVERROR_INVALIDDATA;
02163     trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
02164     if (!trex)
02165         return AVERROR(ENOMEM);
02166     c->trex_data = trex;
02167     trex = &c->trex_data[c->trex_count++];
02168     avio_r8(pb); /* version */
02169     avio_rb24(pb); /* flags */
02170     trex->track_id = avio_rb32(pb);
02171     trex->stsd_id  = avio_rb32(pb);
02172     trex->duration = avio_rb32(pb);
02173     trex->size     = avio_rb32(pb);
02174     trex->flags    = avio_rb32(pb);
02175     return 0;
02176 }
02177 
02178 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02179 {
02180     MOVFragment *frag = &c->fragment;
02181     AVStream *st = NULL;
02182     MOVStreamContext *sc;
02183     MOVStts *ctts_data;
02184     uint64_t offset;
02185     int64_t dts;
02186     int data_offset = 0;
02187     unsigned entries, first_sample_flags = frag->flags;
02188     int flags, distance, i;
02189 
02190     for (i = 0; i < c->fc->nb_streams; i++) {
02191         if (c->fc->streams[i]->id == frag->track_id) {
02192             st = c->fc->streams[i];
02193             break;
02194         }
02195     }
02196     if (!st) {
02197         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
02198         return AVERROR_INVALIDDATA;
02199     }
02200     sc = st->priv_data;
02201     if (sc->pseudo_stream_id+1 != frag->stsd_id)
02202         return 0;
02203     avio_r8(pb); /* version */
02204     flags = avio_rb24(pb);
02205     entries = avio_rb32(pb);
02206     av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
02207 
02208     /* Always assume the presence of composition time offsets.
02209      * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
02210      *  1) in the initial movie, there are no samples.
02211      *  2) in the first movie fragment, there is only one sample without composition time offset.
02212      *  3) in the subsequent movie fragments, there are samples with composition time offset. */
02213     if (!sc->ctts_count && sc->sample_count)
02214     {
02215         /* Complement ctts table if moov atom doesn't have ctts atom. */
02216         ctts_data = av_malloc(sizeof(*sc->ctts_data));
02217         if (!ctts_data)
02218             return AVERROR(ENOMEM);
02219         sc->ctts_data = ctts_data;
02220         sc->ctts_data[sc->ctts_count].count = sc->sample_count;
02221         sc->ctts_data[sc->ctts_count].duration = 0;
02222         sc->ctts_count++;
02223     }
02224     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
02225         return AVERROR_INVALIDDATA;
02226     ctts_data = av_realloc(sc->ctts_data,
02227                            (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
02228     if (!ctts_data)
02229         return AVERROR(ENOMEM);
02230     sc->ctts_data = ctts_data;
02231 
02232     if (flags & 0x001) data_offset        = avio_rb32(pb);
02233     if (flags & 0x004) first_sample_flags = avio_rb32(pb);
02234     dts = st->duration - sc->time_offset;
02235     offset = frag->base_data_offset + data_offset;
02236     distance = 0;
02237     av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
02238     for (i = 0; i < entries; i++) {
02239         unsigned sample_size = frag->size;
02240         int sample_flags = i ? frag->flags : first_sample_flags;
02241         unsigned sample_duration = frag->duration;
02242         int keyframe;
02243 
02244         if (flags & 0x100) sample_duration = avio_rb32(pb);
02245         if (flags & 0x200) sample_size     = avio_rb32(pb);
02246         if (flags & 0x400) sample_flags    = avio_rb32(pb);
02247         sc->ctts_data[sc->ctts_count].count = 1;
02248         sc->ctts_data[sc->ctts_count].duration = (flags & 0x800) ? avio_rb32(pb) : 0;
02249         sc->ctts_count++;
02250         if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
02251              (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
02252             distance = 0;
02253         av_add_index_entry(st, offset, dts, sample_size, distance,
02254                            keyframe ? AVINDEX_KEYFRAME : 0);
02255         av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
02256                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
02257                 offset, dts, sample_size, distance, keyframe);
02258         distance++;
02259         dts += sample_duration;
02260         offset += sample_size;
02261     }
02262     frag->moof_offset = offset;
02263     st->duration = dts + sc->time_offset;
02264     return 0;
02265 }
02266 
02267 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
02268 /* like the files created with Adobe Premiere 5.0, for samples see */
02269 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
02270 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02271 {
02272     int err;
02273 
02274     if (atom.size < 8)
02275         return 0; /* continue */
02276     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
02277         avio_skip(pb, atom.size - 4);
02278         return 0;
02279     }
02280     atom.type = avio_rl32(pb);
02281     atom.size -= 8;
02282     if (atom.type != MKTAG('m','d','a','t')) {
02283         avio_skip(pb, atom.size);
02284         return 0;
02285     }
02286     err = mov_read_mdat(c, pb, atom);
02287     return err;
02288 }
02289 
02290 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02291 {
02292 #if CONFIG_ZLIB
02293     AVIOContext ctx;
02294     uint8_t *cmov_data;
02295     uint8_t *moov_data; /* uncompressed data */
02296     long cmov_len, moov_len;
02297     int ret = -1;
02298 
02299     avio_rb32(pb); /* dcom atom */
02300     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
02301         return AVERROR_INVALIDDATA;
02302     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
02303         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
02304         return AVERROR_INVALIDDATA;
02305     }
02306     avio_rb32(pb); /* cmvd atom */
02307     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
02308         return AVERROR_INVALIDDATA;
02309     moov_len = avio_rb32(pb); /* uncompressed size */
02310     cmov_len = atom.size - 6 * 4;
02311 
02312     cmov_data = av_malloc(cmov_len);
02313     if (!cmov_data)
02314         return AVERROR(ENOMEM);
02315     moov_data = av_malloc(moov_len);
02316     if (!moov_data) {
02317         av_free(cmov_data);
02318         return AVERROR(ENOMEM);
02319     }
02320     avio_read(pb, cmov_data, cmov_len);
02321     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
02322         goto free_and_return;
02323     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
02324         goto free_and_return;
02325     atom.type = MKTAG('m','o','o','v');
02326     atom.size = moov_len;
02327     ret = mov_read_default(c, &ctx, atom);
02328 free_and_return:
02329     av_free(moov_data);
02330     av_free(cmov_data);
02331     return ret;
02332 #else
02333     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
02334     return AVERROR(ENOSYS);
02335 #endif
02336 }
02337 
02338 /* edit list atom */
02339 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02340 {
02341     MOVStreamContext *sc;
02342     int i, edit_count, version;
02343 
02344     if (c->fc->nb_streams < 1)
02345         return 0;
02346     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
02347 
02348     version = avio_r8(pb); /* version */
02349     avio_rb24(pb); /* flags */
02350     edit_count = avio_rb32(pb); /* entries */
02351 
02352     if ((uint64_t)edit_count*12+8 > atom.size)
02353         return AVERROR_INVALIDDATA;
02354 
02355     for (i=0; i<edit_count; i++){
02356         int64_t time;
02357         int64_t duration;
02358         if (version == 1) {
02359             duration = avio_rb64(pb);
02360             time     = avio_rb64(pb);
02361         } else {
02362             duration = avio_rb32(pb); /* segment duration */
02363             time     = (int32_t)avio_rb32(pb); /* media time */
02364         }
02365         avio_rb32(pb); /* Media rate */
02366         if (i == 0 && time >= -1) {
02367             sc->time_offset = time != -1 ? time : -duration;
02368         }
02369     }
02370 
02371     if (edit_count > 1)
02372         av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
02373                "a/v desync might occur, patch welcome\n");
02374 
02375     av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
02376     return 0;
02377 }
02378 
02379 static const MOVParseTableEntry mov_default_parse_table[] = {
02380 { MKTAG('a','v','s','s'), mov_read_extradata },
02381 { MKTAG('c','h','p','l'), mov_read_chpl },
02382 { MKTAG('c','o','6','4'), mov_read_stco },
02383 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
02384 { MKTAG('d','i','n','f'), mov_read_default },
02385 { MKTAG('d','r','e','f'), mov_read_dref },
02386 { MKTAG('e','d','t','s'), mov_read_default },
02387 { MKTAG('e','l','s','t'), mov_read_elst },
02388 { MKTAG('e','n','d','a'), mov_read_enda },
02389 { MKTAG('f','i','e','l'), mov_read_fiel },
02390 { MKTAG('f','t','y','p'), mov_read_ftyp },
02391 { MKTAG('g','l','b','l'), mov_read_glbl },
02392 { MKTAG('h','d','l','r'), mov_read_hdlr },
02393 { MKTAG('i','l','s','t'), mov_read_ilst },
02394 { MKTAG('j','p','2','h'), mov_read_extradata },
02395 { MKTAG('m','d','a','t'), mov_read_mdat },
02396 { MKTAG('m','d','h','d'), mov_read_mdhd },
02397 { MKTAG('m','d','i','a'), mov_read_default },
02398 { MKTAG('m','e','t','a'), mov_read_meta },
02399 { MKTAG('m','i','n','f'), mov_read_default },
02400 { MKTAG('m','o','o','f'), mov_read_moof },
02401 { MKTAG('m','o','o','v'), mov_read_moov },
02402 { MKTAG('m','v','e','x'), mov_read_default },
02403 { MKTAG('m','v','h','d'), mov_read_mvhd },
02404 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
02405 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
02406 { MKTAG('a','v','c','C'), mov_read_glbl },
02407 { MKTAG('p','a','s','p'), mov_read_pasp },
02408 { MKTAG('s','t','b','l'), mov_read_default },
02409 { MKTAG('s','t','c','o'), mov_read_stco },
02410 { MKTAG('s','t','p','s'), mov_read_stps },
02411 { MKTAG('s','t','r','f'), mov_read_strf },
02412 { MKTAG('s','t','s','c'), mov_read_stsc },
02413 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
02414 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
02415 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
02416 { MKTAG('s','t','t','s'), mov_read_stts },
02417 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
02418 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
02419 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
02420 { MKTAG('t','r','a','k'), mov_read_trak },
02421 { MKTAG('t','r','a','f'), mov_read_default },
02422 { MKTAG('t','r','e','f'), mov_read_default },
02423 { MKTAG('c','h','a','p'), mov_read_chap },
02424 { MKTAG('t','r','e','x'), mov_read_trex },
02425 { MKTAG('t','r','u','n'), mov_read_trun },
02426 { MKTAG('u','d','t','a'), mov_read_default },
02427 { MKTAG('w','a','v','e'), mov_read_wave },
02428 { MKTAG('e','s','d','s'), mov_read_esds },
02429 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
02430 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
02431 { MKTAG('w','f','e','x'), mov_read_wfex },
02432 { MKTAG('c','m','o','v'), mov_read_cmov },
02433 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
02434 { 0, NULL }
02435 };
02436 
02437 static int mov_probe(AVProbeData *p)
02438 {
02439     unsigned int offset;
02440     uint32_t tag;
02441     int score = 0;
02442 
02443     /* check file header */
02444     offset = 0;
02445     for (;;) {
02446         /* ignore invalid offset */
02447         if ((offset + 8) > (unsigned int)p->buf_size)
02448             return score;
02449         tag = AV_RL32(p->buf + offset + 4);
02450         switch(tag) {
02451         /* check for obvious tags */
02452         case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
02453         case MKTAG('m','o','o','v'):
02454         case MKTAG('m','d','a','t'):
02455         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
02456         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
02457         case MKTAG('f','t','y','p'):
02458             return AVPROBE_SCORE_MAX;
02459         /* those are more common words, so rate then a bit less */
02460         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
02461         case MKTAG('w','i','d','e'):
02462         case MKTAG('f','r','e','e'):
02463         case MKTAG('j','u','n','k'):
02464         case MKTAG('p','i','c','t'):
02465             return AVPROBE_SCORE_MAX - 5;
02466         case MKTAG(0x82,0x82,0x7f,0x7d):
02467         case MKTAG('s','k','i','p'):
02468         case MKTAG('u','u','i','d'):
02469         case MKTAG('p','r','f','l'):
02470             offset = AV_RB32(p->buf+offset) + offset;
02471             /* if we only find those cause probedata is too small at least rate them */
02472             score = AVPROBE_SCORE_MAX - 50;
02473             break;
02474         default:
02475             /* unrecognized tag */
02476             return score;
02477         }
02478     }
02479 }
02480 
02481 // must be done after parsing all trak because there's no order requirement
02482 static void mov_read_chapters(AVFormatContext *s)
02483 {
02484     MOVContext *mov = s->priv_data;
02485     AVStream *st = NULL;
02486     MOVStreamContext *sc;
02487     int64_t cur_pos;
02488     int i;
02489 
02490     for (i = 0; i < s->nb_streams; i++)
02491         if (s->streams[i]->id == mov->chapter_track) {
02492             st = s->streams[i];
02493             break;
02494         }
02495     if (!st) {
02496         av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
02497         return;
02498     }
02499 
02500     st->discard = AVDISCARD_ALL;
02501     sc = st->priv_data;
02502     cur_pos = avio_tell(sc->pb);
02503 
02504     for (i = 0; i < st->nb_index_entries; i++) {
02505         AVIndexEntry *sample = &st->index_entries[i];
02506         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
02507         uint8_t *title;
02508         uint16_t ch;
02509         int len, title_len;
02510 
02511         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
02512             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
02513             goto finish;
02514         }
02515 
02516         // the first two bytes are the length of the title
02517         len = avio_rb16(sc->pb);
02518         if (len > sample->size-2)
02519             continue;
02520         title_len = 2*len + 1;
02521         if (!(title = av_mallocz(title_len)))
02522             goto finish;
02523 
02524         // The samples could theoretically be in any encoding if there's an encd
02525         // atom following, but in practice are only utf-8 or utf-16, distinguished
02526         // instead by the presence of a BOM
02527         if (!len) {
02528             title[0] = 0;
02529         } else {
02530             ch = avio_rb16(sc->pb);
02531             if (ch == 0xfeff)
02532                 avio_get_str16be(sc->pb, len, title, title_len);
02533             else if (ch == 0xfffe)
02534                 avio_get_str16le(sc->pb, len, title, title_len);
02535             else {
02536                 AV_WB16(title, ch);
02537                 if (len == 1 || len == 2)
02538                     title[len] = 0;
02539                 else
02540                     avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
02541             }
02542         }
02543 
02544         avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
02545         av_freep(&title);
02546     }
02547 finish:
02548     avio_seek(sc->pb, cur_pos, SEEK_SET);
02549 }
02550 
02551 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
02552 {
02553     MOVContext *mov = s->priv_data;
02554     AVIOContext *pb = s->pb;
02555     int err;
02556     MOVAtom atom = { AV_RL32("root") };
02557 
02558     mov->fc = s;
02559     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
02560     if (pb->seekable)
02561         atom.size = avio_size(pb);
02562     else
02563         atom.size = INT64_MAX;
02564 
02565     /* check MOV header */
02566     if ((err = mov_read_default(mov, pb, atom)) < 0) {
02567         av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
02568         return err;
02569     }
02570     if (!mov->found_moov) {
02571         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
02572         return AVERROR_INVALIDDATA;
02573     }
02574     av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
02575 
02576     if (pb->seekable && mov->chapter_track > 0)
02577         mov_read_chapters(s);
02578 
02579     return 0;
02580 }
02581 
02582 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
02583 {
02584     AVIndexEntry *sample = NULL;
02585     int64_t best_dts = INT64_MAX;
02586     int i;
02587     for (i = 0; i < s->nb_streams; i++) {
02588         AVStream *avst = s->streams[i];
02589         MOVStreamContext *msc = avst->priv_data;
02590         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
02591             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
02592             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
02593             av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
02594             if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
02595                 (s->pb->seekable &&
02596                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
02597                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
02598                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
02599                 sample = current_sample;
02600                 best_dts = dts;
02601                 *st = avst;
02602             }
02603         }
02604     }
02605     return sample;
02606 }
02607 
02608 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
02609 {
02610     MOVContext *mov = s->priv_data;
02611     MOVStreamContext *sc;
02612     AVIndexEntry *sample;
02613     AVStream *st = NULL;
02614     int ret;
02615  retry:
02616     sample = mov_find_next_sample(s, &st);
02617     if (!sample) {
02618         mov->found_mdat = 0;
02619         if (s->pb->seekable||
02620             mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
02621             s->pb->eof_reached)
02622             return AVERROR_EOF;
02623         av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
02624         goto retry;
02625     }
02626     sc = st->priv_data;
02627     /* must be done just before reading, to avoid infinite loop on sample */
02628     sc->current_sample++;
02629 
02630     if (st->discard != AVDISCARD_ALL) {
02631         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
02632             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
02633                    sc->ffindex, sample->pos);
02634             return AVERROR_INVALIDDATA;
02635         }
02636         ret = av_get_packet(sc->pb, pkt, sample->size);
02637         if (ret < 0)
02638             return ret;
02639         if (sc->has_palette) {
02640             uint8_t *pal;
02641 
02642             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
02643             if (!pal) {
02644                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
02645             } else {
02646                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
02647                 sc->has_palette = 0;
02648             }
02649         }
02650 #if CONFIG_DV_DEMUXER
02651         if (mov->dv_demux && sc->dv_audio_container) {
02652             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
02653             av_free(pkt->data);
02654             pkt->size = 0;
02655             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
02656             if (ret < 0)
02657                 return ret;
02658         }
02659 #endif
02660     }
02661 
02662     pkt->stream_index = sc->ffindex;
02663     pkt->dts = sample->timestamp;
02664     if (sc->ctts_data) {
02665         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
02666         /* update ctts context */
02667         sc->ctts_sample++;
02668         if (sc->ctts_index < sc->ctts_count &&
02669             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
02670             sc->ctts_index++;
02671             sc->ctts_sample = 0;
02672         }
02673         if (sc->wrong_dts)
02674             pkt->dts = AV_NOPTS_VALUE;
02675     } else {
02676         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
02677             st->index_entries[sc->current_sample].timestamp : st->duration;
02678         pkt->duration = next_dts - pkt->dts;
02679         pkt->pts = pkt->dts;
02680     }
02681     if (st->discard == AVDISCARD_ALL)
02682         goto retry;
02683     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
02684     pkt->pos = sample->pos;
02685     av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
02686             pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
02687     return 0;
02688 }
02689 
02690 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
02691 {
02692     MOVStreamContext *sc = st->priv_data;
02693     int sample, time_sample;
02694     int i;
02695 
02696     sample = av_index_search_timestamp(st, timestamp, flags);
02697     av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
02698     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
02699         sample = 0;
02700     if (sample < 0) /* not sure what to do */
02701         return AVERROR_INVALIDDATA;
02702     sc->current_sample = sample;
02703     av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
02704     /* adjust ctts index */
02705     if (sc->ctts_data) {
02706         time_sample = 0;
02707         for (i = 0; i < sc->ctts_count; i++) {
02708             int next = time_sample + sc->ctts_data[i].count;
02709             if (next > sc->current_sample) {
02710                 sc->ctts_index = i;
02711                 sc->ctts_sample = sc->current_sample - time_sample;
02712                 break;
02713             }
02714             time_sample = next;
02715         }
02716     }
02717     return sample;
02718 }
02719 
02720 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
02721 {
02722     AVStream *st;
02723     int64_t seek_timestamp, timestamp;
02724     int sample;
02725     int i;
02726 
02727     if (stream_index >= s->nb_streams)
02728         return AVERROR_INVALIDDATA;
02729     if (sample_time < 0)
02730         sample_time = 0;
02731 
02732     st = s->streams[stream_index];
02733     sample = mov_seek_stream(s, st, sample_time, flags);
02734     if (sample < 0)
02735         return sample;
02736 
02737     /* adjust seek timestamp to found sample timestamp */
02738     seek_timestamp = st->index_entries[sample].timestamp;
02739 
02740     for (i = 0; i < s->nb_streams; i++) {
02741         st = s->streams[i];
02742         if (stream_index == i)
02743             continue;
02744 
02745         timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
02746         mov_seek_stream(s, st, timestamp, flags);
02747     }
02748     return 0;
02749 }
02750 
02751 static int mov_read_close(AVFormatContext *s)
02752 {
02753     MOVContext *mov = s->priv_data;
02754     int i, j;
02755 
02756     for (i = 0; i < s->nb_streams; i++) {
02757         AVStream *st = s->streams[i];
02758         MOVStreamContext *sc = st->priv_data;
02759 
02760         av_freep(&sc->ctts_data);
02761         for (j = 0; j < sc->drefs_count; j++) {
02762             av_freep(&sc->drefs[j].path);
02763             av_freep(&sc->drefs[j].dir);
02764         }
02765         av_freep(&sc->drefs);
02766         if (sc->pb && sc->pb != s->pb)
02767             avio_close(sc->pb);
02768     }
02769 
02770     if (mov->dv_demux) {
02771         for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
02772             av_freep(&mov->dv_fctx->streams[i]->codec);
02773             av_freep(&mov->dv_fctx->streams[i]);
02774         }
02775         av_freep(&mov->dv_fctx);
02776         av_freep(&mov->dv_demux);
02777     }
02778 
02779     av_freep(&mov->trex_data);
02780 
02781     return 0;
02782 }
02783 
02784 AVInputFormat ff_mov_demuxer = {
02785     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
02786     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
02787     .priv_data_size = sizeof(MOVContext),
02788     .read_probe     = mov_probe,
02789     .read_header    = mov_read_header,
02790     .read_packet    = mov_read_packet,
02791     .read_close     = mov_read_close,
02792     .read_seek      = mov_read_seek,
02793 };
Generated on Sat Mar 17 2012 12:57:54 for Libav by doxygen 1.7.1