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