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 < 0x400 || langcode == 0x7fff))) { // 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     av_freep(&sc->keyframes);
01527     sc->keyframes = av_malloc(entries * sizeof(int));
01528     if (!sc->keyframes)
01529         return AVERROR(ENOMEM);
01530     sc->keyframe_count = entries;
01531 
01532     for (i=0; i<entries; i++) {
01533         sc->keyframes[i] = avio_rb32(pb);
01534         //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
01535     }
01536     return 0;
01537 }
01538 
01539 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01540 {
01541     AVStream *st;
01542     MOVStreamContext *sc;
01543     unsigned int i, entries, sample_size, field_size, num_bytes;
01544     GetBitContext gb;
01545     unsigned char* buf;
01546 
01547     if (c->fc->nb_streams < 1)
01548         return 0;
01549     st = c->fc->streams[c->fc->nb_streams-1];
01550     sc = st->priv_data;
01551 
01552     avio_r8(pb); /* version */
01553     avio_rb24(pb); /* flags */
01554 
01555     if (atom.type == MKTAG('s','t','s','z')) {
01556         sample_size = avio_rb32(pb);
01557         if (!sc->sample_size) /* do not overwrite value computed in stsd */
01558             sc->sample_size = sample_size;
01559         field_size = 32;
01560     } else {
01561         sample_size = 0;
01562         avio_rb24(pb); /* reserved */
01563         field_size = avio_r8(pb);
01564     }
01565     entries = avio_rb32(pb);
01566 
01567     av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
01568 
01569     sc->sample_count = entries;
01570     if (sample_size)
01571         return 0;
01572 
01573     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
01574         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
01575         return AVERROR_INVALIDDATA;
01576     }
01577 
01578     if (!entries)
01579         return 0;
01580     if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
01581         return AVERROR_INVALIDDATA;
01582     sc->sample_sizes = av_malloc(entries * sizeof(int));
01583     if (!sc->sample_sizes)
01584         return AVERROR(ENOMEM);
01585 
01586     num_bytes = (entries*field_size+4)>>3;
01587 
01588     buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
01589     if (!buf) {
01590         av_freep(&sc->sample_sizes);
01591         return AVERROR(ENOMEM);
01592     }
01593 
01594     if (avio_read(pb, buf, num_bytes) < num_bytes) {
01595         av_freep(&sc->sample_sizes);
01596         av_free(buf);
01597         return AVERROR_INVALIDDATA;
01598     }
01599 
01600     init_get_bits(&gb, buf, 8*num_bytes);
01601 
01602     for (i=0; i<entries; i++)
01603         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
01604 
01605     av_free(buf);
01606     return 0;
01607 }
01608 
01609 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01610 {
01611     AVStream *st;
01612     MOVStreamContext *sc;
01613     unsigned int i, entries;
01614     int64_t duration=0;
01615     int64_t total_sample_count=0;
01616 
01617     if (c->fc->nb_streams < 1)
01618         return 0;
01619     st = c->fc->streams[c->fc->nb_streams-1];
01620     sc = st->priv_data;
01621 
01622     avio_r8(pb); /* version */
01623     avio_rb24(pb); /* flags */
01624     entries = avio_rb32(pb);
01625 
01626     av_dlog(c->fc, "track[%i].stts.entries = %i\n",
01627             c->fc->nb_streams-1, entries);
01628 
01629     if (!entries)
01630         return 0;
01631     if (entries >= UINT_MAX / sizeof(*sc->stts_data))
01632         return AVERROR(EINVAL);
01633 
01634     av_free(sc->stts_data);
01635     sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
01636     if (!sc->stts_data)
01637         return AVERROR(ENOMEM);
01638 
01639     sc->stts_count = entries;
01640 
01641     for (i=0; i<entries; i++) {
01642         int sample_duration;
01643         int sample_count;
01644 
01645         sample_count=avio_rb32(pb);
01646         sample_duration = avio_rb32(pb);
01647         if (sample_count < 0) {
01648             av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
01649             return AVERROR_INVALIDDATA;
01650         }
01651         sc->stts_data[i].count= sample_count;
01652         sc->stts_data[i].duration= sample_duration;
01653 
01654         av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
01655                 sample_count, sample_duration);
01656 
01657         duration+=(int64_t)sample_duration*sample_count;
01658         total_sample_count+=sample_count;
01659     }
01660 
01661     st->nb_frames= total_sample_count;
01662     if (duration)
01663         st->duration= duration;
01664     return 0;
01665 }
01666 
01667 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01668 {
01669     AVStream *st;
01670     MOVStreamContext *sc;
01671     unsigned int i, entries;
01672 
01673     if (c->fc->nb_streams < 1)
01674         return 0;
01675     st = c->fc->streams[c->fc->nb_streams-1];
01676     sc = st->priv_data;
01677 
01678     avio_r8(pb); /* version */
01679     avio_rb24(pb); /* flags */
01680     entries = avio_rb32(pb);
01681 
01682     av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
01683 
01684     if (!entries)
01685         return 0;
01686     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
01687         return AVERROR_INVALIDDATA;
01688     sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
01689     if (!sc->ctts_data)
01690         return AVERROR(ENOMEM);
01691     sc->ctts_count = entries;
01692 
01693     for (i=0; i<entries; i++) {
01694         int count    =avio_rb32(pb);
01695         int duration =avio_rb32(pb);
01696 
01697         sc->ctts_data[i].count   = count;
01698         sc->ctts_data[i].duration= duration;
01699         if (duration < 0)
01700             sc->dts_shift = FFMAX(sc->dts_shift, -duration);
01701     }
01702 
01703     av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
01704 
01705     return 0;
01706 }
01707 
01708 static void mov_build_index(MOVContext *mov, AVStream *st)
01709 {
01710     MOVStreamContext *sc = st->priv_data;
01711     int64_t current_offset;
01712     int64_t current_dts = 0;
01713     unsigned int stts_index = 0;
01714     unsigned int stsc_index = 0;
01715     unsigned int stss_index = 0;
01716     unsigned int stps_index = 0;
01717     unsigned int i, j;
01718     uint64_t stream_size = 0;
01719     AVIndexEntry *mem;
01720 
01721     /* adjust first dts according to edit list */
01722     if (sc->time_offset && mov->time_scale > 0) {
01723         if (sc->time_offset < 0)
01724             sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
01725         current_dts = -sc->time_offset;
01726         if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
01727             sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
01728             /* more than 16 frames delay, dts are likely wrong
01729                this happens with files created by iMovie */
01730             sc->wrong_dts = 1;
01731             st->codec->has_b_frames = 1;
01732         }
01733     }
01734 
01735     /* only use old uncompressed audio chunk demuxing when stts specifies it */
01736     if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
01737           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
01738         unsigned int current_sample = 0;
01739         unsigned int stts_sample = 0;
01740         unsigned int sample_size;
01741         unsigned int distance = 0;
01742         int key_off = sc->keyframes && sc->keyframes[0] == 1;
01743 
01744         current_dts -= sc->dts_shift;
01745 
01746         if (!sc->sample_count)
01747             return;
01748         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
01749             return;
01750         mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
01751         if (!mem)
01752             return;
01753         st->index_entries = mem;
01754         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
01755 
01756         for (i = 0; i < sc->chunk_count; i++) {
01757             current_offset = sc->chunk_offsets[i];
01758             while (stsc_index + 1 < sc->stsc_count &&
01759                 i + 1 == sc->stsc_data[stsc_index + 1].first)
01760                 stsc_index++;
01761             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
01762                 int keyframe = 0;
01763                 if (current_sample >= sc->sample_count) {
01764                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
01765                     return;
01766                 }
01767 
01768                 if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
01769                     keyframe = 1;
01770                     if (stss_index + 1 < sc->keyframe_count)
01771                         stss_index++;
01772                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
01773                     keyframe = 1;
01774                     if (stps_index + 1 < sc->stps_count)
01775                         stps_index++;
01776                 }
01777                 if (keyframe)
01778                     distance = 0;
01779                 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
01780                 if (sc->pseudo_stream_id == -1 ||
01781                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
01782                     AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
01783                     e->pos = current_offset;
01784                     e->timestamp = current_dts;
01785                     e->size = sample_size;
01786                     e->min_distance = distance;
01787                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
01788                     av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
01789                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
01790                             current_offset, current_dts, sample_size, distance, keyframe);
01791                 }
01792 
01793                 current_offset += sample_size;
01794                 stream_size += sample_size;
01795                 current_dts += sc->stts_data[stts_index].duration;
01796                 distance++;
01797                 stts_sample++;
01798                 current_sample++;
01799                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
01800                     stts_sample = 0;
01801                     stts_index++;
01802                 }
01803             }
01804         }
01805         if (st->duration > 0)
01806             st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
01807     } else {
01808         unsigned chunk_samples, total = 0;
01809 
01810         // compute total chunk count
01811         for (i = 0; i < sc->stsc_count; i++) {
01812             unsigned count, chunk_count;
01813 
01814             chunk_samples = sc->stsc_data[i].count;
01815             if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
01816                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
01817                 return;
01818             }
01819 
01820             if (sc->samples_per_frame >= 160) { // gsm
01821                 count = chunk_samples / sc->samples_per_frame;
01822             } else if (sc->samples_per_frame > 1) {
01823                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
01824                 count = (chunk_samples+samples-1) / samples;
01825             } else {
01826                 count = (chunk_samples+1023) / 1024;
01827             }
01828 
01829             if (i < sc->stsc_count - 1)
01830                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
01831             else
01832                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
01833             total += chunk_count * count;
01834         }
01835 
01836         av_dlog(mov->fc, "chunk count %d\n", total);
01837         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
01838             return;
01839         mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
01840         if (!mem)
01841             return;
01842         st->index_entries = mem;
01843         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
01844 
01845         // populate index
01846         for (i = 0; i < sc->chunk_count; i++) {
01847             current_offset = sc->chunk_offsets[i];
01848             if (stsc_index + 1 < sc->stsc_count &&
01849                 i + 1 == sc->stsc_data[stsc_index + 1].first)
01850                 stsc_index++;
01851             chunk_samples = sc->stsc_data[stsc_index].count;
01852 
01853             while (chunk_samples > 0) {
01854                 AVIndexEntry *e;
01855                 unsigned size, samples;
01856 
01857                 if (sc->samples_per_frame >= 160) { // gsm
01858                     samples = sc->samples_per_frame;
01859                     size = sc->bytes_per_frame;
01860                 } else {
01861                     if (sc->samples_per_frame > 1) {
01862                         samples = FFMIN((1024 / sc->samples_per_frame)*
01863                                         sc->samples_per_frame, chunk_samples);
01864                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
01865                     } else {
01866                         samples = FFMIN(1024, chunk_samples);
01867                         size = samples * sc->sample_size;
01868                     }
01869                 }
01870 
01871                 if (st->nb_index_entries >= total) {
01872                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
01873                     return;
01874                 }
01875                 e = &st->index_entries[st->nb_index_entries++];
01876                 e->pos = current_offset;
01877                 e->timestamp = current_dts;
01878                 e->size = size;
01879                 e->min_distance = 0;
01880                 e->flags = AVINDEX_KEYFRAME;
01881                 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
01882                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
01883                         size, samples);
01884 
01885                 current_offset += size;
01886                 current_dts += samples;
01887                 chunk_samples -= samples;
01888             }
01889         }
01890     }
01891 }
01892 
01893 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
01894                          AVIOInterruptCB *int_cb)
01895 {
01896     /* try relative path, we do not try the absolute because it can leak information about our
01897        system to an attacker */
01898     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
01899         char filename[1024];
01900         char *src_path;
01901         int i, l;
01902 
01903         /* find a source dir */
01904         src_path = strrchr(src, '/');
01905         if (src_path)
01906             src_path++;
01907         else
01908             src_path = src;
01909 
01910         /* find a next level down to target */
01911         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
01912             if (ref->path[l] == '/') {
01913                 if (i == ref->nlvl_to - 1)
01914                     break;
01915                 else
01916                     i++;
01917             }
01918 
01919         /* compose filename if next level down to target was found */
01920         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
01921             memcpy(filename, src, src_path - src);
01922             filename[src_path - src] = 0;
01923 
01924             for (i = 1; i < ref->nlvl_from; i++)
01925                 av_strlcat(filename, "../", 1024);
01926 
01927             av_strlcat(filename, ref->path + l + 1, 1024);
01928 
01929             if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
01930                 return 0;
01931         }
01932     }
01933 
01934     return AVERROR(ENOENT);
01935 }
01936 
01937 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
01938 {
01939     AVStream *st;
01940     MOVStreamContext *sc;
01941     int ret;
01942 
01943     st = avformat_new_stream(c->fc, NULL);
01944     if (!st) return AVERROR(ENOMEM);
01945     st->id = c->fc->nb_streams;
01946     sc = av_mallocz(sizeof(MOVStreamContext));
01947     if (!sc) return AVERROR(ENOMEM);
01948 
01949     st->priv_data = sc;
01950     st->codec->codec_type = AVMEDIA_TYPE_DATA;
01951     sc->ffindex = st->index;
01952 
01953     if ((ret = mov_read_default(c, pb, atom)) < 0)
01954         return ret;
01955 
01956     /* sanity checks */
01957     if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
01958                             (!sc->sample_size && !sc->sample_count))) {
01959         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
01960                st->index);
01961         return 0;
01962     }
01963 
01964     if (sc->time_scale <= 0) {
01965         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
01966         sc->time_scale = c->time_scale;
01967         if (sc->time_scale <= 0)
01968             sc->time_scale = 1;
01969     }
01970 
01971     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
01972 
01973     if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
01974         !st->codec->frame_size && sc->stts_count == 1) {
01975         st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
01976                                            st->codec->sample_rate, sc->time_scale);
01977         av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
01978     }
01979 
01980     mov_build_index(c, st);
01981 
01982     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
01983         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
01984         if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
01985             av_log(c->fc, AV_LOG_ERROR,
01986                    "stream %d, error opening alias: path='%s', dir='%s', "
01987                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
01988                    st->index, dref->path, dref->dir, dref->filename,
01989                    dref->volume, dref->nlvl_from, dref->nlvl_to);
01990     } else
01991         sc->pb = c->fc->pb;
01992 
01993     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
01994         if (!st->sample_aspect_ratio.num &&
01995             (st->codec->width != sc->width || st->codec->height != sc->height)) {
01996             st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
01997                                              ((double)st->codec->width * sc->height), INT_MAX);
01998         }
01999 
02000         av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
02001                   sc->time_scale*st->nb_frames, st->duration, INT_MAX);
02002 
02003         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
02004             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
02005                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
02006     }
02007 
02008     switch (st->codec->codec_id) {
02009 #if CONFIG_H261_DECODER
02010     case CODEC_ID_H261:
02011 #endif
02012 #if CONFIG_H263_DECODER
02013     case CODEC_ID_H263:
02014 #endif
02015 #if CONFIG_MPEG4_DECODER
02016     case CODEC_ID_MPEG4:
02017 #endif
02018         st->codec->width = 0; /* let decoder init width/height */
02019         st->codec->height= 0;
02020         break;
02021     }
02022 
02023     /* Do not need those anymore. */
02024     av_freep(&sc->chunk_offsets);
02025     av_freep(&sc->stsc_data);
02026     av_freep(&sc->sample_sizes);
02027     av_freep(&sc->keyframes);
02028     av_freep(&sc->stts_data);
02029     av_freep(&sc->stps_data);
02030 
02031     return 0;
02032 }
02033 
02034 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02035 {
02036     int ret;
02037     c->itunes_metadata = 1;
02038     ret = mov_read_default(c, pb, atom);
02039     c->itunes_metadata = 0;
02040     return ret;
02041 }
02042 
02043 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02044 {
02045     while (atom.size > 8) {
02046         uint32_t tag = avio_rl32(pb);
02047         atom.size -= 4;
02048         if (tag == MKTAG('h','d','l','r')) {
02049             avio_seek(pb, -8, SEEK_CUR);
02050             atom.size += 8;
02051             return mov_read_default(c, pb, atom);
02052         }
02053     }
02054     return 0;
02055 }
02056 
02057 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02058 {
02059     int i;
02060     int width;
02061     int height;
02062     int64_t disp_transform[2];
02063     int display_matrix[3][2];
02064     AVStream *st;
02065     MOVStreamContext *sc;
02066     int version;
02067 
02068     if (c->fc->nb_streams < 1)
02069         return 0;
02070     st = c->fc->streams[c->fc->nb_streams-1];
02071     sc = st->priv_data;
02072 
02073     version = avio_r8(pb);
02074     avio_rb24(pb); /* flags */
02075     /*
02076     MOV_TRACK_ENABLED 0x0001
02077     MOV_TRACK_IN_MOVIE 0x0002
02078     MOV_TRACK_IN_PREVIEW 0x0004
02079     MOV_TRACK_IN_POSTER 0x0008
02080     */
02081 
02082     if (version == 1) {
02083         avio_rb64(pb);
02084         avio_rb64(pb);
02085     } else {
02086         avio_rb32(pb); /* creation time */
02087         avio_rb32(pb); /* modification time */
02088     }
02089     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
02090     avio_rb32(pb); /* reserved */
02091 
02092     /* highlevel (considering edits) duration in movie timebase */
02093     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
02094     avio_rb32(pb); /* reserved */
02095     avio_rb32(pb); /* reserved */
02096 
02097     avio_rb16(pb); /* layer */
02098     avio_rb16(pb); /* alternate group */
02099     avio_rb16(pb); /* volume */
02100     avio_rb16(pb); /* reserved */
02101 
02102     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
02103     // they're kept in fixed point format through all calculations
02104     // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
02105     for (i = 0; i < 3; i++) {
02106         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
02107         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
02108         avio_rb32(pb);           // 2.30 fixed point (not used)
02109     }
02110 
02111     width = avio_rb32(pb);       // 16.16 fixed point track width
02112     height = avio_rb32(pb);      // 16.16 fixed point track height
02113     sc->width = width >> 16;
02114     sc->height = height >> 16;
02115 
02116     // transform the display width/height according to the matrix
02117     // skip this if the display matrix is the default identity matrix
02118     // or if it is rotating the picture, ex iPhone 3GS
02119     // to keep the same scale, use [width height 1<<16]
02120     if (width && height &&
02121         ((display_matrix[0][0] != 65536  ||
02122           display_matrix[1][1] != 65536) &&
02123          !display_matrix[0][1] &&
02124          !display_matrix[1][0] &&
02125          !display_matrix[2][0] && !display_matrix[2][1])) {
02126         for (i = 0; i < 2; i++)
02127             disp_transform[i] =
02128                 (int64_t)  width  * display_matrix[0][i] +
02129                 (int64_t)  height * display_matrix[1][i] +
02130                 ((int64_t) display_matrix[2][i] << 16);
02131 
02132         //sample aspect ratio is new width/height divided by old width/height
02133         st->sample_aspect_ratio = av_d2q(
02134             ((double) disp_transform[0] * height) /
02135             ((double) disp_transform[1] * width), INT_MAX);
02136     }
02137     return 0;
02138 }
02139 
02140 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02141 {
02142     MOVFragment *frag = &c->fragment;
02143     MOVTrackExt *trex = NULL;
02144     int flags, track_id, i;
02145 
02146     avio_r8(pb); /* version */
02147     flags = avio_rb24(pb);
02148 
02149     track_id = avio_rb32(pb);
02150     if (!track_id)
02151         return AVERROR_INVALIDDATA;
02152     frag->track_id = track_id;
02153     for (i = 0; i < c->trex_count; i++)
02154         if (c->trex_data[i].track_id == frag->track_id) {
02155             trex = &c->trex_data[i];
02156             break;
02157         }
02158     if (!trex) {
02159         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
02160         return AVERROR_INVALIDDATA;
02161     }
02162 
02163     if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
02164     else              frag->base_data_offset = frag->moof_offset;
02165     if (flags & 0x02) frag->stsd_id          = avio_rb32(pb);
02166     else              frag->stsd_id          = trex->stsd_id;
02167 
02168     frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
02169     frag->size     = flags & 0x10 ? avio_rb32(pb) : trex->size;
02170     frag->flags    = flags & 0x20 ? avio_rb32(pb) : trex->flags;
02171     av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
02172     return 0;
02173 }
02174 
02175 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02176 {
02177     c->chapter_track = avio_rb32(pb);
02178     return 0;
02179 }
02180 
02181 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02182 {
02183     MOVTrackExt *trex;
02184 
02185     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
02186         return AVERROR_INVALIDDATA;
02187     trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
02188     if (!trex)
02189         return AVERROR(ENOMEM);
02190     c->trex_data = trex;
02191     trex = &c->trex_data[c->trex_count++];
02192     avio_r8(pb); /* version */
02193     avio_rb24(pb); /* flags */
02194     trex->track_id = avio_rb32(pb);
02195     trex->stsd_id  = avio_rb32(pb);
02196     trex->duration = avio_rb32(pb);
02197     trex->size     = avio_rb32(pb);
02198     trex->flags    = avio_rb32(pb);
02199     return 0;
02200 }
02201 
02202 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02203 {
02204     MOVFragment *frag = &c->fragment;
02205     AVStream *st = NULL;
02206     MOVStreamContext *sc;
02207     MOVStts *ctts_data;
02208     uint64_t offset;
02209     int64_t dts;
02210     int data_offset = 0;
02211     unsigned entries, first_sample_flags = frag->flags;
02212     int flags, distance, i;
02213 
02214     for (i = 0; i < c->fc->nb_streams; i++) {
02215         if (c->fc->streams[i]->id == frag->track_id) {
02216             st = c->fc->streams[i];
02217             break;
02218         }
02219     }
02220     if (!st) {
02221         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
02222         return AVERROR_INVALIDDATA;
02223     }
02224     sc = st->priv_data;
02225     if (sc->pseudo_stream_id+1 != frag->stsd_id)
02226         return 0;
02227     avio_r8(pb); /* version */
02228     flags = avio_rb24(pb);
02229     entries = avio_rb32(pb);
02230     av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
02231 
02232     /* Always assume the presence of composition time offsets.
02233      * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
02234      *  1) in the initial movie, there are no samples.
02235      *  2) in the first movie fragment, there is only one sample without composition time offset.
02236      *  3) in the subsequent movie fragments, there are samples with composition time offset. */
02237     if (!sc->ctts_count && sc->sample_count)
02238     {
02239         /* Complement ctts table if moov atom doesn't have ctts atom. */
02240         ctts_data = av_malloc(sizeof(*sc->ctts_data));
02241         if (!ctts_data)
02242             return AVERROR(ENOMEM);
02243         sc->ctts_data = ctts_data;
02244         sc->ctts_data[sc->ctts_count].count = sc->sample_count;
02245         sc->ctts_data[sc->ctts_count].duration = 0;
02246         sc->ctts_count++;
02247     }
02248     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
02249         return AVERROR_INVALIDDATA;
02250     ctts_data = av_realloc(sc->ctts_data,
02251                            (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
02252     if (!ctts_data)
02253         return AVERROR(ENOMEM);
02254     sc->ctts_data = ctts_data;
02255 
02256     if (flags & 0x001) data_offset        = avio_rb32(pb);
02257     if (flags & 0x004) first_sample_flags = avio_rb32(pb);
02258     dts = st->duration - sc->time_offset;
02259     offset = frag->base_data_offset + data_offset;
02260     distance = 0;
02261     av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
02262     for (i = 0; i < entries; i++) {
02263         unsigned sample_size = frag->size;
02264         int sample_flags = i ? frag->flags : first_sample_flags;
02265         unsigned sample_duration = frag->duration;
02266         int keyframe;
02267 
02268         if (flags & 0x100) sample_duration = avio_rb32(pb);
02269         if (flags & 0x200) sample_size     = avio_rb32(pb);
02270         if (flags & 0x400) sample_flags    = avio_rb32(pb);
02271         sc->ctts_data[sc->ctts_count].count = 1;
02272         sc->ctts_data[sc->ctts_count].duration = (flags & 0x800) ? avio_rb32(pb) : 0;
02273         sc->ctts_count++;
02274         if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
02275              (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
02276             distance = 0;
02277         av_add_index_entry(st, offset, dts, sample_size, distance,
02278                            keyframe ? AVINDEX_KEYFRAME : 0);
02279         av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
02280                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
02281                 offset, dts, sample_size, distance, keyframe);
02282         distance++;
02283         dts += sample_duration;
02284         offset += sample_size;
02285     }
02286     frag->moof_offset = offset;
02287     st->duration = dts + sc->time_offset;
02288     return 0;
02289 }
02290 
02291 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
02292 /* like the files created with Adobe Premiere 5.0, for samples see */
02293 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
02294 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02295 {
02296     int err;
02297 
02298     if (atom.size < 8)
02299         return 0; /* continue */
02300     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
02301         avio_skip(pb, atom.size - 4);
02302         return 0;
02303     }
02304     atom.type = avio_rl32(pb);
02305     atom.size -= 8;
02306     if (atom.type != MKTAG('m','d','a','t')) {
02307         avio_skip(pb, atom.size);
02308         return 0;
02309     }
02310     err = mov_read_mdat(c, pb, atom);
02311     return err;
02312 }
02313 
02314 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02315 {
02316 #if CONFIG_ZLIB
02317     AVIOContext ctx;
02318     uint8_t *cmov_data;
02319     uint8_t *moov_data; /* uncompressed data */
02320     long cmov_len, moov_len;
02321     int ret = -1;
02322 
02323     avio_rb32(pb); /* dcom atom */
02324     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
02325         return AVERROR_INVALIDDATA;
02326     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
02327         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
02328         return AVERROR_INVALIDDATA;
02329     }
02330     avio_rb32(pb); /* cmvd atom */
02331     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
02332         return AVERROR_INVALIDDATA;
02333     moov_len = avio_rb32(pb); /* uncompressed size */
02334     cmov_len = atom.size - 6 * 4;
02335 
02336     cmov_data = av_malloc(cmov_len);
02337     if (!cmov_data)
02338         return AVERROR(ENOMEM);
02339     moov_data = av_malloc(moov_len);
02340     if (!moov_data) {
02341         av_free(cmov_data);
02342         return AVERROR(ENOMEM);
02343     }
02344     avio_read(pb, cmov_data, cmov_len);
02345     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
02346         goto free_and_return;
02347     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
02348         goto free_and_return;
02349     atom.type = MKTAG('m','o','o','v');
02350     atom.size = moov_len;
02351     ret = mov_read_default(c, &ctx, atom);
02352 free_and_return:
02353     av_free(moov_data);
02354     av_free(cmov_data);
02355     return ret;
02356 #else
02357     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
02358     return AVERROR(ENOSYS);
02359 #endif
02360 }
02361 
02362 /* edit list atom */
02363 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
02364 {
02365     MOVStreamContext *sc;
02366     int i, edit_count, version;
02367 
02368     if (c->fc->nb_streams < 1)
02369         return 0;
02370     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
02371 
02372     version = avio_r8(pb); /* version */
02373     avio_rb24(pb); /* flags */
02374     edit_count = avio_rb32(pb); /* entries */
02375 
02376     if ((uint64_t)edit_count*12+8 > atom.size)
02377         return AVERROR_INVALIDDATA;
02378 
02379     for (i=0; i<edit_count; i++){
02380         int64_t time;
02381         int64_t duration;
02382         if (version == 1) {
02383             duration = avio_rb64(pb);
02384             time     = avio_rb64(pb);
02385         } else {
02386             duration = avio_rb32(pb); /* segment duration */
02387             time     = (int32_t)avio_rb32(pb); /* media time */
02388         }
02389         avio_rb32(pb); /* Media rate */
02390         if (i == 0 && time >= -1) {
02391             sc->time_offset = time != -1 ? time : -duration;
02392         }
02393     }
02394 
02395     if (edit_count > 1)
02396         av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
02397                "a/v desync might occur, patch welcome\n");
02398 
02399     av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
02400     return 0;
02401 }
02402 
02403 static const MOVParseTableEntry mov_default_parse_table[] = {
02404 { MKTAG('a','v','s','s'), mov_read_extradata },
02405 { MKTAG('c','h','p','l'), mov_read_chpl },
02406 { MKTAG('c','o','6','4'), mov_read_stco },
02407 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
02408 { MKTAG('d','i','n','f'), mov_read_default },
02409 { MKTAG('d','r','e','f'), mov_read_dref },
02410 { MKTAG('e','d','t','s'), mov_read_default },
02411 { MKTAG('e','l','s','t'), mov_read_elst },
02412 { MKTAG('e','n','d','a'), mov_read_enda },
02413 { MKTAG('f','i','e','l'), mov_read_fiel },
02414 { MKTAG('f','t','y','p'), mov_read_ftyp },
02415 { MKTAG('g','l','b','l'), mov_read_glbl },
02416 { MKTAG('h','d','l','r'), mov_read_hdlr },
02417 { MKTAG('i','l','s','t'), mov_read_ilst },
02418 { MKTAG('j','p','2','h'), mov_read_extradata },
02419 { MKTAG('m','d','a','t'), mov_read_mdat },
02420 { MKTAG('m','d','h','d'), mov_read_mdhd },
02421 { MKTAG('m','d','i','a'), mov_read_default },
02422 { MKTAG('m','e','t','a'), mov_read_meta },
02423 { MKTAG('m','i','n','f'), mov_read_default },
02424 { MKTAG('m','o','o','f'), mov_read_moof },
02425 { MKTAG('m','o','o','v'), mov_read_moov },
02426 { MKTAG('m','v','e','x'), mov_read_default },
02427 { MKTAG('m','v','h','d'), mov_read_mvhd },
02428 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
02429 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
02430 { MKTAG('a','v','c','C'), mov_read_glbl },
02431 { MKTAG('p','a','s','p'), mov_read_pasp },
02432 { MKTAG('s','t','b','l'), mov_read_default },
02433 { MKTAG('s','t','c','o'), mov_read_stco },
02434 { MKTAG('s','t','p','s'), mov_read_stps },
02435 { MKTAG('s','t','r','f'), mov_read_strf },
02436 { MKTAG('s','t','s','c'), mov_read_stsc },
02437 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
02438 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
02439 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
02440 { MKTAG('s','t','t','s'), mov_read_stts },
02441 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
02442 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
02443 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
02444 { MKTAG('t','r','a','k'), mov_read_trak },
02445 { MKTAG('t','r','a','f'), mov_read_default },
02446 { MKTAG('t','r','e','f'), mov_read_default },
02447 { MKTAG('c','h','a','p'), mov_read_chap },
02448 { MKTAG('t','r','e','x'), mov_read_trex },
02449 { MKTAG('t','r','u','n'), mov_read_trun },
02450 { MKTAG('u','d','t','a'), mov_read_default },
02451 { MKTAG('w','a','v','e'), mov_read_wave },
02452 { MKTAG('e','s','d','s'), mov_read_esds },
02453 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
02454 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
02455 { MKTAG('w','f','e','x'), mov_read_wfex },
02456 { MKTAG('c','m','o','v'), mov_read_cmov },
02457 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
02458 { 0, NULL }
02459 };
02460 
02461 static int mov_probe(AVProbeData *p)
02462 {
02463     unsigned int offset;
02464     uint32_t tag;
02465     int score = 0;
02466 
02467     /* check file header */
02468     offset = 0;
02469     for (;;) {
02470         /* ignore invalid offset */
02471         if ((offset + 8) > (unsigned int)p->buf_size)
02472             return score;
02473         tag = AV_RL32(p->buf + offset + 4);
02474         switch(tag) {
02475         /* check for obvious tags */
02476         case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
02477         case MKTAG('m','o','o','v'):
02478         case MKTAG('m','d','a','t'):
02479         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
02480         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
02481         case MKTAG('f','t','y','p'):
02482             return AVPROBE_SCORE_MAX;
02483         /* those are more common words, so rate then a bit less */
02484         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
02485         case MKTAG('w','i','d','e'):
02486         case MKTAG('f','r','e','e'):
02487         case MKTAG('j','u','n','k'):
02488         case MKTAG('p','i','c','t'):
02489             return AVPROBE_SCORE_MAX - 5;
02490         case MKTAG(0x82,0x82,0x7f,0x7d):
02491         case MKTAG('s','k','i','p'):
02492         case MKTAG('u','u','i','d'):
02493         case MKTAG('p','r','f','l'):
02494             offset = AV_RB32(p->buf+offset) + offset;
02495             /* if we only find those cause probedata is too small at least rate them */
02496             score = AVPROBE_SCORE_MAX - 50;
02497             break;
02498         default:
02499             /* unrecognized tag */
02500             return score;
02501         }
02502     }
02503 }
02504 
02505 // must be done after parsing all trak because there's no order requirement
02506 static void mov_read_chapters(AVFormatContext *s)
02507 {
02508     MOVContext *mov = s->priv_data;
02509     AVStream *st = NULL;
02510     MOVStreamContext *sc;
02511     int64_t cur_pos;
02512     int i;
02513 
02514     for (i = 0; i < s->nb_streams; i++)
02515         if (s->streams[i]->id == mov->chapter_track) {
02516             st = s->streams[i];
02517             break;
02518         }
02519     if (!st) {
02520         av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
02521         return;
02522     }
02523 
02524     st->discard = AVDISCARD_ALL;
02525     sc = st->priv_data;
02526     cur_pos = avio_tell(sc->pb);
02527 
02528     for (i = 0; i < st->nb_index_entries; i++) {
02529         AVIndexEntry *sample = &st->index_entries[i];
02530         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
02531         uint8_t *title;
02532         uint16_t ch;
02533         int len, title_len;
02534 
02535         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
02536             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
02537             goto finish;
02538         }
02539 
02540         // the first two bytes are the length of the title
02541         len = avio_rb16(sc->pb);
02542         if (len > sample->size-2)
02543             continue;
02544         title_len = 2*len + 1;
02545         if (!(title = av_mallocz(title_len)))
02546             goto finish;
02547 
02548         // The samples could theoretically be in any encoding if there's an encd
02549         // atom following, but in practice are only utf-8 or utf-16, distinguished
02550         // instead by the presence of a BOM
02551         if (!len) {
02552             title[0] = 0;
02553         } else {
02554             ch = avio_rb16(sc->pb);
02555             if (ch == 0xfeff)
02556                 avio_get_str16be(sc->pb, len, title, title_len);
02557             else if (ch == 0xfffe)
02558                 avio_get_str16le(sc->pb, len, title, title_len);
02559             else {
02560                 AV_WB16(title, ch);
02561                 if (len == 1 || len == 2)
02562                     title[len] = 0;
02563                 else
02564                     avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
02565             }
02566         }
02567 
02568         avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
02569         av_freep(&title);
02570     }
02571 finish:
02572     avio_seek(sc->pb, cur_pos, SEEK_SET);
02573 }
02574 
02575 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
02576 {
02577     MOVContext *mov = s->priv_data;
02578     AVIOContext *pb = s->pb;
02579     int err;
02580     MOVAtom atom = { AV_RL32("root") };
02581 
02582     mov->fc = s;
02583     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
02584     if (pb->seekable)
02585         atom.size = avio_size(pb);
02586     else
02587         atom.size = INT64_MAX;
02588 
02589     /* check MOV header */
02590     if ((err = mov_read_default(mov, pb, atom)) < 0) {
02591         av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
02592         return err;
02593     }
02594     if (!mov->found_moov) {
02595         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
02596         return AVERROR_INVALIDDATA;
02597     }
02598     av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
02599 
02600     if (pb->seekable && mov->chapter_track > 0)
02601         mov_read_chapters(s);
02602 
02603     return 0;
02604 }
02605 
02606 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
02607 {
02608     AVIndexEntry *sample = NULL;
02609     int64_t best_dts = INT64_MAX;
02610     int i;
02611     for (i = 0; i < s->nb_streams; i++) {
02612         AVStream *avst = s->streams[i];
02613         MOVStreamContext *msc = avst->priv_data;
02614         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
02615             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
02616             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
02617             av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
02618             if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
02619                 (s->pb->seekable &&
02620                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
02621                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
02622                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
02623                 sample = current_sample;
02624                 best_dts = dts;
02625                 *st = avst;
02626             }
02627         }
02628     }
02629     return sample;
02630 }
02631 
02632 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
02633 {
02634     MOVContext *mov = s->priv_data;
02635     MOVStreamContext *sc;
02636     AVIndexEntry *sample;
02637     AVStream *st = NULL;
02638     int ret;
02639  retry:
02640     sample = mov_find_next_sample(s, &st);
02641     if (!sample) {
02642         mov->found_mdat = 0;
02643         if (s->pb->seekable||
02644             mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
02645             s->pb->eof_reached)
02646             return AVERROR_EOF;
02647         av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
02648         goto retry;
02649     }
02650     sc = st->priv_data;
02651     /* must be done just before reading, to avoid infinite loop on sample */
02652     sc->current_sample++;
02653 
02654     if (st->discard != AVDISCARD_ALL) {
02655         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
02656             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
02657                    sc->ffindex, sample->pos);
02658             return AVERROR_INVALIDDATA;
02659         }
02660         ret = av_get_packet(sc->pb, pkt, sample->size);
02661         if (ret < 0)
02662             return ret;
02663         if (sc->has_palette) {
02664             uint8_t *pal;
02665 
02666             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
02667             if (!pal) {
02668                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
02669             } else {
02670                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
02671                 sc->has_palette = 0;
02672             }
02673         }
02674 #if CONFIG_DV_DEMUXER
02675         if (mov->dv_demux && sc->dv_audio_container) {
02676             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
02677             av_free(pkt->data);
02678             pkt->size = 0;
02679             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
02680             if (ret < 0)
02681                 return ret;
02682         }
02683 #endif
02684     }
02685 
02686     pkt->stream_index = sc->ffindex;
02687     pkt->dts = sample->timestamp;
02688     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
02689         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
02690         /* update ctts context */
02691         sc->ctts_sample++;
02692         if (sc->ctts_index < sc->ctts_count &&
02693             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
02694             sc->ctts_index++;
02695             sc->ctts_sample = 0;
02696         }
02697         if (sc->wrong_dts)
02698             pkt->dts = AV_NOPTS_VALUE;
02699     } else {
02700         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
02701             st->index_entries[sc->current_sample].timestamp : st->duration;
02702         pkt->duration = next_dts - pkt->dts;
02703         pkt->pts = pkt->dts;
02704     }
02705     if (st->discard == AVDISCARD_ALL)
02706         goto retry;
02707     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
02708     pkt->pos = sample->pos;
02709     av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
02710             pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
02711     return 0;
02712 }
02713 
02714 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
02715 {
02716     MOVStreamContext *sc = st->priv_data;
02717     int sample, time_sample;
02718     int i;
02719 
02720     sample = av_index_search_timestamp(st, timestamp, flags);
02721     av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
02722     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
02723         sample = 0;
02724     if (sample < 0) /* not sure what to do */
02725         return AVERROR_INVALIDDATA;
02726     sc->current_sample = sample;
02727     av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
02728     /* adjust ctts index */
02729     if (sc->ctts_data) {
02730         time_sample = 0;
02731         for (i = 0; i < sc->ctts_count; i++) {
02732             int next = time_sample + sc->ctts_data[i].count;
02733             if (next > sc->current_sample) {
02734                 sc->ctts_index = i;
02735                 sc->ctts_sample = sc->current_sample - time_sample;
02736                 break;
02737             }
02738             time_sample = next;
02739         }
02740     }
02741     return sample;
02742 }
02743 
02744 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
02745 {
02746     AVStream *st;
02747     int64_t seek_timestamp, timestamp;
02748     int sample;
02749     int i;
02750 
02751     if (stream_index >= s->nb_streams)
02752         return AVERROR_INVALIDDATA;
02753     if (sample_time < 0)
02754         sample_time = 0;
02755 
02756     st = s->streams[stream_index];
02757     sample = mov_seek_stream(s, st, sample_time, flags);
02758     if (sample < 0)
02759         return sample;
02760 
02761     /* adjust seek timestamp to found sample timestamp */
02762     seek_timestamp = st->index_entries[sample].timestamp;
02763 
02764     for (i = 0; i < s->nb_streams; i++) {
02765         st = s->streams[i];
02766         if (stream_index == i)
02767             continue;
02768 
02769         timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
02770         mov_seek_stream(s, st, timestamp, flags);
02771     }
02772     return 0;
02773 }
02774 
02775 static int mov_read_close(AVFormatContext *s)
02776 {
02777     MOVContext *mov = s->priv_data;
02778     int i, j;
02779 
02780     for (i = 0; i < s->nb_streams; i++) {
02781         AVStream *st = s->streams[i];
02782         MOVStreamContext *sc = st->priv_data;
02783 
02784         av_freep(&sc->ctts_data);
02785         for (j = 0; j < sc->drefs_count; j++) {
02786             av_freep(&sc->drefs[j].path);
02787             av_freep(&sc->drefs[j].dir);
02788         }
02789         av_freep(&sc->drefs);
02790         if (sc->pb && sc->pb != s->pb)
02791             avio_close(sc->pb);
02792     }
02793 
02794     if (mov->dv_demux) {
02795         for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
02796             av_freep(&mov->dv_fctx->streams[i]->codec);
02797             av_freep(&mov->dv_fctx->streams[i]);
02798         }
02799         av_freep(&mov->dv_fctx);
02800         av_freep(&mov->dv_demux);
02801     }
02802 
02803     av_freep(&mov->trex_data);
02804 
02805     return 0;
02806 }
02807 
02808 AVInputFormat ff_mov_demuxer = {
02809     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
02810     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
02811     .priv_data_size = sizeof(MOVContext),
02812     .read_probe     = mov_probe,
02813     .read_header    = mov_read_header,
02814     .read_packet    = mov_read_packet,
02815     .read_close     = mov_read_close,
02816     .read_seek      = mov_read_seek,
02817 };