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