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

libavformat/mov.c

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