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