libavformat/avidec.c
Go to the documentation of this file.
00001 /*
00002  * AVI demuxer
00003  * Copyright (c) 2001 Fabrice Bellard
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 #include "libavutil/intreadwrite.h"
00023 #include "libavutil/mathematics.h"
00024 #include "libavutil/bswap.h"
00025 #include "libavutil/opt.h"
00026 #include "libavutil/dict.h"
00027 #include "libavutil/avstring.h"
00028 #include "avformat.h"
00029 #include "internal.h"
00030 #include "avi.h"
00031 #include "dv.h"
00032 #include "riff.h"
00033 
00034 #undef NDEBUG
00035 #include <assert.h>
00036 
00037 typedef struct AVIStream {
00038     int64_t frame_offset; /* current frame (video) or byte (audio) counter
00039                          (used to compute the pts) */
00040     int remaining;
00041     int packet_size;
00042 
00043     int scale;
00044     int rate;
00045     int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
00046 
00047     int64_t cum_len; /* temporary storage (used during seek) */
00048 
00049     int prefix;                       
00050     int prefix_count;
00051     uint32_t pal[256];
00052     int has_pal;
00053     int dshow_block_align;            
00054 
00055     AVFormatContext *sub_ctx;
00056     AVPacket sub_pkt;
00057     uint8_t *sub_buffer;
00058 
00059     int64_t seek_pos;
00060 } AVIStream;
00061 
00062 typedef struct {
00063     const AVClass *class;
00064     int64_t  riff_end;
00065     int64_t  movi_end;
00066     int64_t  fsize;
00067     int64_t movi_list;
00068     int64_t last_pkt_pos;
00069     int index_loaded;
00070     int is_odml;
00071     int non_interleaved;
00072     int stream_index;
00073     DVDemuxContext* dv_demux;
00074     int odml_depth;
00075     int use_odml;
00076 #define MAX_ODML_DEPTH 1000
00077     int64_t dts_max;
00078 } AVIContext;
00079 
00080 
00081 static const AVOption options[] = {
00082     { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_INT, {.dbl = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
00083     { NULL },
00084 };
00085 
00086 static const AVClass demuxer_class = {
00087     "AVI demuxer",
00088     av_default_item_name,
00089     options,
00090     LIBAVUTIL_VERSION_INT,
00091 };
00092 
00093 
00094 static const char avi_headers[][8] = {
00095     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', ' ' },
00096     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 'X' },
00097     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 0x19},
00098     { 'O', 'N', '2', ' ',    'O', 'N', '2', 'f' },
00099     { 'R', 'I', 'F', 'F',    'A', 'M', 'V', ' ' },
00100     { 0 }
00101 };
00102 
00103 static const AVMetadataConv avi_metadata_conv[] = {
00104     { "strn", "title" },
00105     { 0 },
00106 };
00107 
00108 static int avi_load_index(AVFormatContext *s);
00109 static int guess_ni_flag(AVFormatContext *s);
00110 
00111 #define print_tag(str, tag, size)                       \
00112     av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n",       \
00113            str, tag & 0xff,                             \
00114            (tag >> 8) & 0xff,                           \
00115            (tag >> 16) & 0xff,                          \
00116            (tag >> 24) & 0xff,                          \
00117            size)
00118 
00119 static inline int get_duration(AVIStream *ast, int len){
00120     if(ast->sample_size){
00121         return len;
00122     }else if (ast->dshow_block_align){
00123         return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
00124     }else
00125         return 1;
00126 }
00127 
00128 static int get_riff(AVFormatContext *s, AVIOContext *pb)
00129 {
00130     AVIContext *avi = s->priv_data;
00131     char header[8];
00132     int i;
00133 
00134     /* check RIFF header */
00135     avio_read(pb, header, 4);
00136     avi->riff_end = avio_rl32(pb);  /* RIFF chunk size */
00137     avi->riff_end += avio_tell(pb); /* RIFF chunk end */
00138     avio_read(pb, header+4, 4);
00139 
00140     for(i=0; avi_headers[i][0]; i++)
00141         if(!memcmp(header, avi_headers[i], 8))
00142             break;
00143     if(!avi_headers[i][0])
00144         return -1;
00145 
00146     if(header[7] == 0x19)
00147         av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
00148 
00149     return 0;
00150 }
00151 
00152 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
00153     AVIContext *avi = s->priv_data;
00154     AVIOContext *pb = s->pb;
00155     int longs_pre_entry= avio_rl16(pb);
00156     int index_sub_type = avio_r8(pb);
00157     int index_type     = avio_r8(pb);
00158     int entries_in_use = avio_rl32(pb);
00159     int chunk_id       = avio_rl32(pb);
00160     int64_t base       = avio_rl64(pb);
00161     int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
00162     AVStream *st;
00163     AVIStream *ast;
00164     int i;
00165     int64_t last_pos= -1;
00166     int64_t filesize= avi->fsize;
00167 
00168     av_dlog(s, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
00169             longs_pre_entry,index_type, entries_in_use, chunk_id, base);
00170 
00171     if(stream_id >= s->nb_streams || stream_id < 0)
00172         return -1;
00173     st= s->streams[stream_id];
00174     ast = st->priv_data;
00175 
00176     if(index_sub_type)
00177         return -1;
00178 
00179     avio_rl32(pb);
00180 
00181     if(index_type && longs_pre_entry != 2)
00182         return -1;
00183     if(index_type>1)
00184         return -1;
00185 
00186     if(filesize > 0 && base >= filesize){
00187         av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
00188         if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
00189             base &= 0xFFFFFFFF;
00190         else
00191             return -1;
00192     }
00193 
00194     for(i=0; i<entries_in_use; i++){
00195         if(index_type){
00196             int64_t pos= avio_rl32(pb) + base - 8;
00197             int len    = avio_rl32(pb);
00198             int key= len >= 0;
00199             len &= 0x7FFFFFFF;
00200 
00201 #ifdef DEBUG_SEEK
00202             av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
00203 #endif
00204             if(url_feof(pb))
00205                 return -1;
00206 
00207             if(last_pos == pos || pos == base - 8)
00208                 avi->non_interleaved= 1;
00209             if(last_pos != pos && (len || !ast->sample_size))
00210                 av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
00211 
00212             ast->cum_len += get_duration(ast, len);
00213             last_pos= pos;
00214         }else{
00215             int64_t offset, pos;
00216             int duration;
00217             offset = avio_rl64(pb);
00218             avio_rl32(pb);       /* size */
00219             duration = avio_rl32(pb);
00220 
00221             if(url_feof(pb))
00222                 return -1;
00223 
00224             pos = avio_tell(pb);
00225 
00226             if(avi->odml_depth > MAX_ODML_DEPTH){
00227                 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
00228                 return -1;
00229             }
00230 
00231             if(avio_seek(pb, offset+8, SEEK_SET) < 0)
00232                 return -1;
00233             avi->odml_depth++;
00234             read_braindead_odml_indx(s, frame_num);
00235             avi->odml_depth--;
00236             frame_num += duration;
00237 
00238             if(avio_seek(pb, pos, SEEK_SET) < 0) {
00239                 av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index");
00240                 return -1;
00241             }
00242 
00243         }
00244     }
00245     avi->index_loaded=2;
00246     return 0;
00247 }
00248 
00249 static void clean_index(AVFormatContext *s){
00250     int i;
00251     int64_t j;
00252 
00253     for(i=0; i<s->nb_streams; i++){
00254         AVStream *st = s->streams[i];
00255         AVIStream *ast = st->priv_data;
00256         int n= st->nb_index_entries;
00257         int max= ast->sample_size;
00258         int64_t pos, size, ts;
00259 
00260         if(n != 1 || ast->sample_size==0)
00261             continue;
00262 
00263         while(max < 1024) max+=max;
00264 
00265         pos= st->index_entries[0].pos;
00266         size= st->index_entries[0].size;
00267         ts= st->index_entries[0].timestamp;
00268 
00269         for(j=0; j<size; j+=max){
00270             av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
00271         }
00272     }
00273 }
00274 
00275 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
00276 {
00277     AVIOContext *pb = s->pb;
00278     char key[5] = {0}, *value;
00279 
00280     size += (size & 1);
00281 
00282     if (size == UINT_MAX)
00283         return -1;
00284     value = av_malloc(size+1);
00285     if (!value)
00286         return -1;
00287     avio_read(pb, value, size);
00288     value[size]=0;
00289 
00290     AV_WL32(key, tag);
00291 
00292     return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
00293                             AV_DICT_DONT_STRDUP_VAL);
00294 }
00295 
00296 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
00297                                     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
00298 
00299 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
00300 {
00301     char month[4], time[9], buffer[64];
00302     int i, day, year;
00303     /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
00304     if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
00305                month, &day, time, &year) == 4) {
00306         for (i=0; i<12; i++)
00307             if (!av_strcasecmp(month, months[i])) {
00308                 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
00309                          year, i+1, day, time);
00310                 av_dict_set(metadata, "creation_time", buffer, 0);
00311             }
00312     } else if (date[4] == '/' && date[7] == '/') {
00313         date[4] = date[7] = '-';
00314         av_dict_set(metadata, "creation_time", date, 0);
00315     }
00316 }
00317 
00318 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
00319 {
00320     while (avio_tell(s->pb) < end) {
00321         uint32_t tag  = avio_rl32(s->pb);
00322         uint32_t size = avio_rl32(s->pb);
00323         switch (tag) {
00324         case MKTAG('n', 'c', 't', 'g'): {  /* Nikon Tags */
00325             uint64_t tag_end = avio_tell(s->pb) + size;
00326             while (avio_tell(s->pb) < tag_end) {
00327                 uint16_t tag  = avio_rl16(s->pb);
00328                 uint16_t size = avio_rl16(s->pb);
00329                 const char *name = NULL;
00330                 char buffer[64] = {0};
00331                 size -= avio_read(s->pb, buffer,
00332                                    FFMIN(size, sizeof(buffer)-1));
00333                 switch (tag) {
00334                 case 0x03:  name = "maker";  break;
00335                 case 0x04:  name = "model";  break;
00336                 case 0x13:  name = "creation_time";
00337                     if (buffer[4] == ':' && buffer[7] == ':')
00338                         buffer[4] = buffer[7] = '-';
00339                     break;
00340                 }
00341                 if (name)
00342                     av_dict_set(&s->metadata, name, buffer, 0);
00343                 avio_skip(s->pb, size);
00344             }
00345             break;
00346         }
00347         default:
00348             avio_skip(s->pb, size);
00349             break;
00350         }
00351     }
00352 }
00353 
00354 static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
00355 {
00356     AVIContext *avi = s->priv_data;
00357     AVIOContext *pb = s->pb;
00358     unsigned int tag, tag1, handler;
00359     int codec_type, stream_index, frame_period;
00360     unsigned int size;
00361     int i;
00362     AVStream *st;
00363     AVIStream *ast = NULL;
00364     int avih_width=0, avih_height=0;
00365     int amv_file_format=0;
00366     uint64_t list_end = 0;
00367     int ret;
00368 
00369     avi->stream_index= -1;
00370 
00371     if (get_riff(s, pb) < 0)
00372         return -1;
00373 
00374     av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
00375 
00376     avi->fsize = avio_size(pb);
00377     if(avi->fsize<=0 || avi->fsize < avi->riff_end)
00378         avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
00379 
00380     /* first list tag */
00381     stream_index = -1;
00382     codec_type = -1;
00383     frame_period = 0;
00384     for(;;) {
00385         if (url_feof(pb))
00386             goto fail;
00387         tag = avio_rl32(pb);
00388         size = avio_rl32(pb);
00389 
00390         print_tag("tag", tag, size);
00391 
00392         switch(tag) {
00393         case MKTAG('L', 'I', 'S', 'T'):
00394             list_end = avio_tell(pb) + size;
00395             /* Ignored, except at start of video packets. */
00396             tag1 = avio_rl32(pb);
00397 
00398             print_tag("list", tag1, 0);
00399 
00400             if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
00401                 avi->movi_list = avio_tell(pb) - 4;
00402                 if(size) avi->movi_end = avi->movi_list + size + (size & 1);
00403                 else     avi->movi_end = avi->fsize;
00404                 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
00405                 goto end_of_header;
00406             }
00407             else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
00408                 ff_read_riff_info(s, size - 4);
00409             else if (tag1 == MKTAG('n', 'c', 'd', 't'))
00410                 avi_read_nikon(s, list_end);
00411 
00412             break;
00413         case MKTAG('I', 'D', 'I', 'T'): {
00414             unsigned char date[64] = {0};
00415             size += (size & 1);
00416             size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
00417             avio_skip(pb, size);
00418             avi_metadata_creation_time(&s->metadata, date);
00419             break;
00420         }
00421         case MKTAG('d', 'm', 'l', 'h'):
00422             avi->is_odml = 1;
00423             avio_skip(pb, size + (size & 1));
00424             break;
00425         case MKTAG('a', 'm', 'v', 'h'):
00426             amv_file_format=1;
00427         case MKTAG('a', 'v', 'i', 'h'):
00428             /* AVI header */
00429             /* using frame_period is bad idea */
00430             frame_period = avio_rl32(pb);
00431             avio_rl32(pb); /* max. bytes per second */
00432             avio_rl32(pb);
00433             avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
00434 
00435             avio_skip(pb, 2 * 4);
00436             avio_rl32(pb);
00437             avio_rl32(pb);
00438             avih_width=avio_rl32(pb);
00439             avih_height=avio_rl32(pb);
00440 
00441             avio_skip(pb, size - 10 * 4);
00442             break;
00443         case MKTAG('s', 't', 'r', 'h'):
00444             /* stream header */
00445 
00446             tag1 = avio_rl32(pb);
00447             handler = avio_rl32(pb); /* codec tag */
00448 
00449             if(tag1 == MKTAG('p', 'a', 'd', 's')){
00450                 avio_skip(pb, size - 8);
00451                 break;
00452             }else{
00453                 stream_index++;
00454                 st = avformat_new_stream(s, NULL);
00455                 if (!st)
00456                     goto fail;
00457 
00458                 st->id = stream_index;
00459                 ast = av_mallocz(sizeof(AVIStream));
00460                 if (!ast)
00461                     goto fail;
00462                 st->priv_data = ast;
00463             }
00464             if(amv_file_format)
00465                 tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
00466 
00467             print_tag("strh", tag1, -1);
00468 
00469             if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
00470                 int64_t dv_dur;
00471 
00472                 /*
00473                  * After some consideration -- I don't think we
00474                  * have to support anything but DV in type1 AVIs.
00475                  */
00476                 if (s->nb_streams != 1)
00477                     goto fail;
00478 
00479                 if (handler != MKTAG('d', 'v', 's', 'd') &&
00480                     handler != MKTAG('d', 'v', 'h', 'd') &&
00481                     handler != MKTAG('d', 'v', 's', 'l'))
00482                    goto fail;
00483 
00484                 ast = s->streams[0]->priv_data;
00485                 av_freep(&s->streams[0]->codec->extradata);
00486                 av_freep(&s->streams[0]->codec);
00487                 av_freep(&s->streams[0]);
00488                 s->nb_streams = 0;
00489                 if (CONFIG_DV_DEMUXER) {
00490                     avi->dv_demux = avpriv_dv_init_demux(s);
00491                     if (!avi->dv_demux)
00492                         goto fail;
00493                 }
00494                 s->streams[0]->priv_data = ast;
00495                 avio_skip(pb, 3 * 4);
00496                 ast->scale = avio_rl32(pb);
00497                 ast->rate = avio_rl32(pb);
00498                 avio_skip(pb, 4);  /* start time */
00499 
00500                 dv_dur = avio_rl32(pb);
00501                 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
00502                     dv_dur *= AV_TIME_BASE;
00503                     s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
00504                 }
00505                 /*
00506                  * else, leave duration alone; timing estimation in utils.c
00507                  *      will make a guess based on bitrate.
00508                  */
00509 
00510                 stream_index = s->nb_streams - 1;
00511                 avio_skip(pb, size - 9*4);
00512                 break;
00513             }
00514 
00515             assert(stream_index < s->nb_streams);
00516             st->codec->stream_codec_tag= handler;
00517 
00518             avio_rl32(pb); /* flags */
00519             avio_rl16(pb); /* priority */
00520             avio_rl16(pb); /* language */
00521             avio_rl32(pb); /* initial frame */
00522             ast->scale = avio_rl32(pb);
00523             ast->rate = avio_rl32(pb);
00524             if(!(ast->scale && ast->rate)){
00525                 av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
00526                 if(frame_period){
00527                     ast->rate = 1000000;
00528                     ast->scale = frame_period;
00529                 }else{
00530                     ast->rate = 25;
00531                     ast->scale = 1;
00532                 }
00533             }
00534             avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
00535 
00536             ast->cum_len=avio_rl32(pb); /* start */
00537             st->nb_frames = avio_rl32(pb);
00538 
00539             st->start_time = 0;
00540             avio_rl32(pb); /* buffer size */
00541             avio_rl32(pb); /* quality */
00542             if (ast->cum_len*ast->scale/ast->rate > 3600) {
00543                 av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
00544                 return AVERROR_INVALIDDATA;
00545             }
00546             ast->sample_size = avio_rl32(pb); /* sample ssize */
00547             ast->cum_len *= FFMAX(1, ast->sample_size);
00548 //            av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
00549 
00550             switch(tag1) {
00551             case MKTAG('v', 'i', 'd', 's'):
00552                 codec_type = AVMEDIA_TYPE_VIDEO;
00553 
00554                 ast->sample_size = 0;
00555                 break;
00556             case MKTAG('a', 'u', 'd', 's'):
00557                 codec_type = AVMEDIA_TYPE_AUDIO;
00558                 break;
00559             case MKTAG('t', 'x', 't', 's'):
00560                 codec_type = AVMEDIA_TYPE_SUBTITLE;
00561                 break;
00562             case MKTAG('d', 'a', 't', 's'):
00563                 codec_type = AVMEDIA_TYPE_DATA;
00564                 break;
00565             default:
00566                 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
00567             }
00568             if(ast->sample_size == 0)
00569                 st->duration = st->nb_frames;
00570             ast->frame_offset= ast->cum_len;
00571             avio_skip(pb, size - 12 * 4);
00572             break;
00573         case MKTAG('s', 't', 'r', 'f'):
00574             /* stream header */
00575             if (!size)
00576                 break;
00577             if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
00578                 avio_skip(pb, size);
00579             } else {
00580                 uint64_t cur_pos = avio_tell(pb);
00581                 if (cur_pos < list_end)
00582                     size = FFMIN(size, list_end - cur_pos);
00583                 st = s->streams[stream_index];
00584                 switch(codec_type) {
00585                 case AVMEDIA_TYPE_VIDEO:
00586                     if(amv_file_format){
00587                         st->codec->width=avih_width;
00588                         st->codec->height=avih_height;
00589                         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
00590                         st->codec->codec_id = CODEC_ID_AMV;
00591                         avio_skip(pb, size);
00592                         break;
00593                     }
00594                     tag1 = ff_get_bmp_header(pb, st);
00595 
00596                     if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
00597                         st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
00598                         st->codec->codec_tag = tag1;
00599                         st->codec->codec_id = CODEC_ID_XSUB;
00600                         break;
00601                     }
00602 
00603                     if(size > 10*4 && size<(1<<30) && size < avi->fsize){
00604                         st->codec->extradata_size= size - 10*4;
00605                         st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
00606                         if (!st->codec->extradata) {
00607                             st->codec->extradata_size= 0;
00608                             return AVERROR(ENOMEM);
00609                         }
00610                         avio_read(pb, st->codec->extradata, st->codec->extradata_size);
00611                     }
00612 
00613                     if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
00614                         avio_r8(pb);
00615 
00616                     /* Extract palette from extradata if bpp <= 8. */
00617                     /* This code assumes that extradata contains only palette. */
00618                     /* This is true for all paletted codecs implemented in FFmpeg. */
00619                     if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
00620                         int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
00621                         const uint8_t *pal_src;
00622 
00623                         pal_size = FFMIN(pal_size, st->codec->extradata_size);
00624                         pal_src = st->codec->extradata + st->codec->extradata_size - pal_size;
00625                         for (i = 0; i < pal_size/4; i++)
00626                             ast->pal[i] = 0xFF<<24 | AV_RL32(pal_src+4*i);
00627                         ast->has_pal = 1;
00628                     }
00629 
00630                     print_tag("video", tag1, 0);
00631 
00632                     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
00633                     st->codec->codec_tag = tag1;
00634                     st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
00635                     st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
00636                     // Support "Resolution 1:1" for Avid AVI Codec
00637                     if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
00638                        st->codec->extradata_size >= 31 &&
00639                        !memcmp(&st->codec->extradata[28], "1:1", 3))
00640                         st->codec->codec_id = CODEC_ID_RAWVIDEO;
00641 
00642                     if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
00643                         st->codec->extradata_size+= 9;
00644                         st->codec->extradata= av_realloc_f(st->codec->extradata, 1, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
00645                         if(st->codec->extradata)
00646                             memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
00647                     }
00648                     st->codec->height= FFABS(st->codec->height);
00649 
00650 //                    avio_skip(pb, size - 5 * 4);
00651                     break;
00652                 case AVMEDIA_TYPE_AUDIO:
00653                     ret = ff_get_wav_header(pb, st->codec, size);
00654                     if (ret < 0)
00655                         return ret;
00656                     ast->dshow_block_align= st->codec->block_align;
00657                     if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
00658                         av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
00659                         ast->sample_size= st->codec->block_align;
00660                     }
00661                     if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
00662                         avio_skip(pb, 1);
00663                     /* Force parsing as several audio frames can be in
00664                      * one packet and timestamps refer to packet start. */
00665                     st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
00666                     /* ADTS header is in extradata, AAC without header must be
00667                      * stored as exact frames. Parser not needed and it will
00668                      * fail. */
00669                     if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
00670                         st->need_parsing = AVSTREAM_PARSE_NONE;
00671                     /* AVI files with Xan DPCM audio (wrongly) declare PCM
00672                      * audio in the header but have Axan as stream_code_tag. */
00673                     if (st->codec->stream_codec_tag == AV_RL32("Axan")){
00674                         st->codec->codec_id  = CODEC_ID_XAN_DPCM;
00675                         st->codec->codec_tag = 0;
00676                         ast->dshow_block_align = 0;
00677                     }
00678                     if (amv_file_format){
00679                         st->codec->codec_id  = CODEC_ID_ADPCM_IMA_AMV;
00680                         ast->dshow_block_align = 0;
00681                     }
00682                     break;
00683                 case AVMEDIA_TYPE_SUBTITLE:
00684                     st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
00685                     st->request_probe= 1;
00686                     break;
00687                 default:
00688                     st->codec->codec_type = AVMEDIA_TYPE_DATA;
00689                     st->codec->codec_id= CODEC_ID_NONE;
00690                     st->codec->codec_tag= 0;
00691                     avio_skip(pb, size);
00692                     break;
00693                 }
00694             }
00695             break;
00696         case MKTAG('s', 't', 'r', 'd'):
00697             if (stream_index >= (unsigned)s->nb_streams || s->streams[stream_index]->codec->extradata_size) {
00698                 avio_skip(pb, size);
00699             } else {
00700                 uint64_t cur_pos = avio_tell(pb);
00701                 if (cur_pos < list_end)
00702                     size = FFMIN(size, list_end - cur_pos);
00703                 st = s->streams[stream_index];
00704 
00705                 if(size<(1<<30)){
00706                     st->codec->extradata_size= size;
00707                     st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
00708                     if (!st->codec->extradata) {
00709                         st->codec->extradata_size= 0;
00710                         return AVERROR(ENOMEM);
00711                     }
00712                     avio_read(pb, st->codec->extradata, st->codec->extradata_size);
00713                 }
00714 
00715                 if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
00716                     avio_r8(pb);
00717             }
00718             break;
00719         case MKTAG('i', 'n', 'd', 'x'):
00720             i= avio_tell(pb);
00721             if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) && avi->use_odml &&
00722                read_braindead_odml_indx(s, 0) < 0 && s->error_recognition >= FF_ER_EXPLODE)
00723                 goto fail;
00724             avio_seek(pb, i+size, SEEK_SET);
00725             break;
00726         case MKTAG('v', 'p', 'r', 'p'):
00727             if(stream_index < (unsigned)s->nb_streams && size > 9*4){
00728                 AVRational active, active_aspect;
00729 
00730                 st = s->streams[stream_index];
00731                 avio_rl32(pb);
00732                 avio_rl32(pb);
00733                 avio_rl32(pb);
00734                 avio_rl32(pb);
00735                 avio_rl32(pb);
00736 
00737                 active_aspect.den= avio_rl16(pb);
00738                 active_aspect.num= avio_rl16(pb);
00739                 active.num       = avio_rl32(pb);
00740                 active.den       = avio_rl32(pb);
00741                 avio_rl32(pb); //nbFieldsPerFrame
00742 
00743                 if(active_aspect.num && active_aspect.den && active.num && active.den){
00744                     st->sample_aspect_ratio= av_div_q(active_aspect, active);
00745 //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
00746                 }
00747                 size -= 9*4;
00748             }
00749             avio_skip(pb, size);
00750             break;
00751         case MKTAG('s', 't', 'r', 'n'):
00752             if(s->nb_streams){
00753                 avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
00754                 break;
00755             }
00756         default:
00757             if(size > 1000000){
00758                 av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
00759                                         "I will ignore it and try to continue anyway.\n");
00760                 if (s->error_recognition & AV_EF_EXPLODE)
00761                     goto fail;
00762                 avi->movi_list = avio_tell(pb) - 4;
00763                 avi->movi_end  = avi->fsize;
00764                 goto end_of_header;
00765             }
00766             /* skip tag */
00767             size += (size & 1);
00768             avio_skip(pb, size);
00769             break;
00770         }
00771     }
00772  end_of_header:
00773     /* check stream number */
00774     if (stream_index != s->nb_streams - 1) {
00775     fail:
00776         return -1;
00777     }
00778 
00779     if(!avi->index_loaded && pb->seekable)
00780         avi_load_index(s);
00781     avi->index_loaded |= 1;
00782     avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
00783     for(i=0; i<s->nb_streams; i++){
00784         AVStream *st = s->streams[i];
00785         if(st->nb_index_entries)
00786             break;
00787     }
00788     // DV-in-AVI cannot be non-interleaved, if set this must be
00789     // a mis-detection.
00790     if(avi->dv_demux)
00791         avi->non_interleaved=0;
00792     if(i==s->nb_streams && avi->non_interleaved) {
00793         av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
00794         avi->non_interleaved=0;
00795     }
00796 
00797     if(avi->non_interleaved) {
00798         av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
00799         clean_index(s);
00800     }
00801 
00802     ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
00803     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
00804 
00805     return 0;
00806 }
00807 
00808 static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
00809     if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
00810         uint8_t desc[256];
00811         int score = AVPROBE_SCORE_MAX / 2, ret;
00812         AVIStream *ast = st->priv_data;
00813         AVInputFormat *sub_demuxer;
00814         AVRational time_base;
00815         AVIOContext *pb = avio_alloc_context( pkt->data + 7,
00816                                               pkt->size - 7,
00817                                               0, NULL, NULL, NULL, NULL);
00818         AVProbeData pd;
00819         unsigned int desc_len = avio_rl32(pb);
00820 
00821         if (desc_len > pb->buf_end - pb->buf_ptr)
00822             goto error;
00823 
00824         ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
00825         avio_skip(pb, desc_len - ret);
00826         if (*desc)
00827             av_dict_set(&st->metadata, "title", desc, 0);
00828 
00829         avio_rl16(pb);   /* flags? */
00830         avio_rl32(pb);   /* data size */
00831 
00832         pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
00833         if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
00834             goto error;
00835 
00836         if (!(ast->sub_ctx = avformat_alloc_context()))
00837             goto error;
00838 
00839         ast->sub_ctx->pb      = pb;
00840         if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
00841             av_read_packet(ast->sub_ctx, &ast->sub_pkt);
00842             *st->codec = *ast->sub_ctx->streams[0]->codec;
00843             ast->sub_ctx->streams[0]->codec->extradata = NULL;
00844             time_base = ast->sub_ctx->streams[0]->time_base;
00845             avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
00846         }
00847         ast->sub_buffer = pkt->data;
00848         memset(pkt, 0, sizeof(*pkt));
00849         return 1;
00850 error:
00851         av_freep(&pb);
00852     }
00853     return 0;
00854 }
00855 
00856 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
00857                                   AVPacket *pkt)
00858 {
00859     AVIStream *ast, *next_ast = next_st->priv_data;
00860     int64_t ts, next_ts, ts_min = INT64_MAX;
00861     AVStream *st, *sub_st = NULL;
00862     int i;
00863 
00864     next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
00865                            AV_TIME_BASE_Q);
00866 
00867     for (i=0; i<s->nb_streams; i++) {
00868         st  = s->streams[i];
00869         ast = st->priv_data;
00870         if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
00871             ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
00872             if (ts <= next_ts && ts < ts_min) {
00873                 ts_min = ts;
00874                 sub_st = st;
00875             }
00876         }
00877     }
00878 
00879     if (sub_st) {
00880         ast = sub_st->priv_data;
00881         *pkt = ast->sub_pkt;
00882         pkt->stream_index = sub_st->index;
00883         if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
00884             ast->sub_pkt.data = NULL;
00885     }
00886     return sub_st;
00887 }
00888 
00889 static int get_stream_idx(int *d){
00890     if(    d[0] >= '0' && d[0] <= '9'
00891         && d[1] >= '0' && d[1] <= '9'){
00892         return (d[0] - '0') * 10 + (d[1] - '0');
00893     }else{
00894         return 100; //invalid stream ID
00895     }
00896 }
00897 
00898 static int avi_sync(AVFormatContext *s, int exit_early)
00899 {
00900     AVIContext *avi = s->priv_data;
00901     AVIOContext *pb = s->pb;
00902     int n;
00903     unsigned int d[8];
00904     unsigned int size;
00905     int64_t i, sync;
00906 
00907 start_sync:
00908     memset(d, -1, sizeof(d));
00909     for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
00910         int j;
00911 
00912         for(j=0; j<7; j++)
00913             d[j]= d[j+1];
00914         d[7]= avio_r8(pb);
00915 
00916         size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
00917 
00918         n= get_stream_idx(d+2);
00919 //av_log(s, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
00920         if(i + (uint64_t)size > avi->fsize || d[0] > 127)
00921             continue;
00922 
00923         //parse ix##
00924         if(  (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
00925         //parse JUNK
00926            ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
00927            ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
00928             avio_skip(pb, size);
00929 //av_log(s, AV_LOG_DEBUG, "SKIP\n");
00930             goto start_sync;
00931         }
00932 
00933         //parse stray LIST
00934         if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
00935             avio_skip(pb, 4);
00936             goto start_sync;
00937         }
00938 
00939         n= get_stream_idx(d);
00940 
00941         if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
00942             continue;
00943 
00944         //detect ##ix chunk and skip
00945         if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
00946             avio_skip(pb, size);
00947             goto start_sync;
00948         }
00949 
00950         //parse ##dc/##wb
00951         if(n < s->nb_streams){
00952             AVStream *st;
00953             AVIStream *ast;
00954             st = s->streams[n];
00955             ast = st->priv_data;
00956 
00957             if(s->nb_streams>=2){
00958                 AVStream *st1  = s->streams[1];
00959                 AVIStream *ast1= st1->priv_data;
00960                 //workaround for broken small-file-bug402.avi
00961                 if(   d[2] == 'w' && d[3] == 'b'
00962                    && n==0
00963                    && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
00964                    && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
00965                    && ast->prefix == 'd'*256+'c'
00966                    && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
00967                   ){
00968                     n=1;
00969                     st = st1;
00970                     ast = ast1;
00971                     av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
00972                 }
00973             }
00974 
00975 
00976             if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
00977                /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
00978                || st->discard >= AVDISCARD_ALL){
00979                 if (!exit_early) {
00980                     ast->frame_offset += get_duration(ast, size);
00981                 }
00982                 avio_skip(pb, size);
00983                 goto start_sync;
00984             }
00985 
00986             if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
00987                 int k = avio_r8(pb);
00988                 int last = (k + avio_r8(pb) - 1) & 0xFF;
00989 
00990                 avio_rl16(pb); //flags
00991 
00992                 for (; k <= last; k++)
00993                     ast->pal[k] = 0xFF<<24 | avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
00994                 ast->has_pal= 1;
00995                 goto start_sync;
00996             } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
00997                          d[2]*256+d[3] == ast->prefix /*||
00998                          (d[2] == 'd' && d[3] == 'c') ||
00999                          (d[2] == 'w' && d[3] == 'b')*/) {
01000 
01001                 if (exit_early)
01002                     return 0;
01003 //av_log(s, AV_LOG_DEBUG, "OK\n");
01004                 if(d[2]*256+d[3] == ast->prefix)
01005                     ast->prefix_count++;
01006                 else{
01007                     ast->prefix= d[2]*256+d[3];
01008                     ast->prefix_count= 0;
01009                 }
01010 
01011                 avi->stream_index= n;
01012                 ast->packet_size= size + 8;
01013                 ast->remaining= size;
01014 
01015                 if(size || !ast->sample_size){
01016                     uint64_t pos= avio_tell(pb) - 8;
01017                     if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
01018                         av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
01019                     }
01020                 }
01021                 return 0;
01022             }
01023         }
01024     }
01025 
01026     if(pb->error)
01027         return pb->error;
01028     return AVERROR_EOF;
01029 }
01030 
01031 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
01032 {
01033     AVIContext *avi = s->priv_data;
01034     AVIOContext *pb = s->pb;
01035     int err;
01036     void* dstr;
01037 
01038     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
01039         int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
01040         if (size >= 0)
01041             return size;
01042     }
01043 
01044     if(avi->non_interleaved){
01045         int best_stream_index = 0;
01046         AVStream *best_st= NULL;
01047         AVIStream *best_ast;
01048         int64_t best_ts= INT64_MAX;
01049         int i;
01050 
01051         for(i=0; i<s->nb_streams; i++){
01052             AVStream *st = s->streams[i];
01053             AVIStream *ast = st->priv_data;
01054             int64_t ts= ast->frame_offset;
01055             int64_t last_ts;
01056 
01057             if(!st->nb_index_entries)
01058                 continue;
01059 
01060             last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
01061             if(!ast->remaining && ts > last_ts)
01062                 continue;
01063 
01064             ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
01065 
01066 //            av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
01067             if(ts < best_ts){
01068                 best_ts= ts;
01069                 best_st= st;
01070                 best_stream_index= i;
01071             }
01072         }
01073         if(!best_st)
01074             return AVERROR_EOF;
01075 
01076         best_ast = best_st->priv_data;
01077         best_ts = best_ast->frame_offset;
01078         if(best_ast->remaining)
01079             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
01080         else{
01081             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
01082             if(i>=0)
01083                 best_ast->frame_offset= best_st->index_entries[i].timestamp;
01084         }
01085 
01086 //        av_log(s, AV_LOG_DEBUG, "%d\n", i);
01087         if(i>=0){
01088             int64_t pos= best_st->index_entries[i].pos;
01089             pos += best_ast->packet_size - best_ast->remaining;
01090             if(avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
01091               return AVERROR_EOF;
01092 //        av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
01093 
01094             assert(best_ast->remaining <= best_ast->packet_size);
01095 
01096             avi->stream_index= best_stream_index;
01097             if(!best_ast->remaining)
01098                 best_ast->packet_size=
01099                 best_ast->remaining= best_st->index_entries[i].size;
01100         }
01101         else
01102           return AVERROR_EOF;
01103     }
01104 
01105 resync:
01106     if(avi->stream_index >= 0){
01107         AVStream *st= s->streams[ avi->stream_index ];
01108         AVIStream *ast= st->priv_data;
01109         int size, err;
01110 
01111         if(get_subtitle_pkt(s, st, pkt))
01112             return 0;
01113 
01114         if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
01115             size= INT_MAX;
01116         else if(ast->sample_size < 32)
01117             // arbitrary multiplier to avoid tiny packets for raw PCM data
01118             size= 1024*ast->sample_size;
01119         else
01120             size= ast->sample_size;
01121 
01122         if(size > ast->remaining)
01123             size= ast->remaining;
01124         avi->last_pkt_pos= avio_tell(pb);
01125         err= av_get_packet(pb, pkt, size);
01126         if(err<0)
01127             return err;
01128 
01129         if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
01130             uint8_t *pal;
01131             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
01132             if(!pal){
01133                 av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
01134             }else{
01135                 memcpy(pal, ast->pal, AVPALETTE_SIZE);
01136                 ast->has_pal = 0;
01137             }
01138         }
01139 
01140         if (CONFIG_DV_DEMUXER && avi->dv_demux) {
01141             dstr = pkt->destruct;
01142             size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
01143                                     pkt->data, pkt->size, pkt->pos);
01144             pkt->destruct = dstr;
01145             pkt->flags |= AV_PKT_FLAG_KEY;
01146             if (size < 0)
01147                 av_free_packet(pkt);
01148         } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
01149                    && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
01150             ast->frame_offset++;
01151             avi->stream_index = -1;
01152             ast->remaining = 0;
01153             goto resync;
01154         } else {
01155             /* XXX: How to handle B-frames in AVI? */
01156             pkt->dts = ast->frame_offset;
01157 //                pkt->dts += ast->start;
01158             if(ast->sample_size)
01159                 pkt->dts /= ast->sample_size;
01160 //av_log(s, AV_LOG_DEBUG, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
01161             pkt->stream_index = avi->stream_index;
01162 
01163             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
01164                 AVIndexEntry *e;
01165                 int index;
01166                 assert(st->index_entries);
01167 
01168                 index= av_index_search_timestamp(st, ast->frame_offset, 0);
01169                 e= &st->index_entries[index];
01170 
01171                 if(index >= 0 && e->timestamp == ast->frame_offset){
01172                     if (index == st->nb_index_entries-1){
01173                         int key=1;
01174                         int i;
01175                         uint32_t state=-1;
01176                         for(i=0; i<FFMIN(size,256); i++){
01177                             if(st->codec->codec_id == CODEC_ID_MPEG4){
01178                                 if(state == 0x1B6){
01179                                     key= !(pkt->data[i]&0xC0);
01180                                     break;
01181                                 }
01182                             }else
01183                                 break;
01184                             state= (state<<8) + pkt->data[i];
01185                         }
01186                         if(!key)
01187                             e->flags &= ~AVINDEX_KEYFRAME;
01188                     }
01189                     if (e->flags & AVINDEX_KEYFRAME)
01190                         pkt->flags |= AV_PKT_FLAG_KEY;
01191                 }
01192             } else {
01193                 pkt->flags |= AV_PKT_FLAG_KEY;
01194             }
01195             ast->frame_offset += get_duration(ast, pkt->size);
01196         }
01197         ast->remaining -= size;
01198         if(!ast->remaining){
01199             avi->stream_index= -1;
01200             ast->packet_size= 0;
01201         }
01202 
01203         if(!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos){
01204             av_free_packet(pkt);
01205             goto resync;
01206         }
01207         ast->seek_pos= 0;
01208 
01209         if(!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1){
01210             int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
01211 
01212             if(avi->dts_max - dts > 2*AV_TIME_BASE){
01213                 avi->non_interleaved= 1;
01214                 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
01215             }else if(avi->dts_max < dts)
01216                 avi->dts_max = dts;
01217         }
01218 
01219         return size;
01220     }
01221 
01222     if ((err = avi_sync(s, 0)) < 0)
01223         return err;
01224     goto resync;
01225 }
01226 
01227 /* XXX: We make the implicit supposition that the positions are sorted
01228    for each stream. */
01229 static int avi_read_idx1(AVFormatContext *s, int size)
01230 {
01231     AVIContext *avi = s->priv_data;
01232     AVIOContext *pb = s->pb;
01233     int nb_index_entries, i;
01234     AVStream *st;
01235     AVIStream *ast;
01236     unsigned int index, tag, flags, pos, len, first_packet = 1;
01237     unsigned last_pos= -1;
01238     int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
01239 
01240     nb_index_entries = size / 16;
01241     if (nb_index_entries <= 0)
01242         return -1;
01243 
01244     idx1_pos = avio_tell(pb);
01245     avio_seek(pb, avi->movi_list+4, SEEK_SET);
01246     if (avi_sync(s, 1) == 0) {
01247         first_packet_pos = avio_tell(pb) - 8;
01248     }
01249     avi->stream_index = -1;
01250     avio_seek(pb, idx1_pos, SEEK_SET);
01251 
01252     /* Read the entries and sort them in each stream component. */
01253     for(i = 0; i < nb_index_entries; i++) {
01254         if(url_feof(pb))
01255             return -1;
01256 
01257         tag = avio_rl32(pb);
01258         flags = avio_rl32(pb);
01259         pos = avio_rl32(pb);
01260         len = avio_rl32(pb);
01261         av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
01262                 i, tag, flags, pos, len);
01263 
01264         index = ((tag & 0xff) - '0') * 10;
01265         index += ((tag >> 8) & 0xff) - '0';
01266         if (index >= s->nb_streams)
01267             continue;
01268         st = s->streams[index];
01269         ast = st->priv_data;
01270 
01271         if(first_packet && first_packet_pos && len) {
01272             data_offset = first_packet_pos - pos;
01273             first_packet = 0;
01274         }
01275         pos += data_offset;
01276 
01277         av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
01278 
01279 
01280         if(last_pos == pos)
01281             avi->non_interleaved= 1;
01282         else if(len || !ast->sample_size)
01283             av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
01284         ast->cum_len += get_duration(ast, len);
01285         last_pos= pos;
01286     }
01287     return 0;
01288 }
01289 
01290 static int guess_ni_flag(AVFormatContext *s){
01291     int i;
01292     int64_t last_start=0;
01293     int64_t first_end= INT64_MAX;
01294     int64_t oldpos= avio_tell(s->pb);
01295 
01296     for(i=0; i<s->nb_streams; i++){
01297         AVStream *st = s->streams[i];
01298         int n= st->nb_index_entries;
01299         unsigned int size;
01300 
01301         if(n <= 0)
01302             continue;
01303 
01304         if(n >= 2){
01305             int64_t pos= st->index_entries[0].pos;
01306             avio_seek(s->pb, pos + 4, SEEK_SET);
01307             size= avio_rl32(s->pb);
01308             if(pos + size > st->index_entries[1].pos)
01309                 last_start= INT64_MAX;
01310         }
01311 
01312         if(st->index_entries[0].pos > last_start)
01313             last_start= st->index_entries[0].pos;
01314         if(st->index_entries[n-1].pos < first_end)
01315             first_end= st->index_entries[n-1].pos;
01316     }
01317     avio_seek(s->pb, oldpos, SEEK_SET);
01318     return last_start > first_end;
01319 }
01320 
01321 static int avi_load_index(AVFormatContext *s)
01322 {
01323     AVIContext *avi = s->priv_data;
01324     AVIOContext *pb = s->pb;
01325     uint32_t tag, size;
01326     int64_t pos= avio_tell(pb);
01327     int ret = -1;
01328 
01329     if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
01330         goto the_end; // maybe truncated file
01331     av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
01332     for(;;) {
01333         if (url_feof(pb))
01334             break;
01335         tag = avio_rl32(pb);
01336         size = avio_rl32(pb);
01337         av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
01338                  tag        & 0xff,
01339                 (tag >>  8) & 0xff,
01340                 (tag >> 16) & 0xff,
01341                 (tag >> 24) & 0xff,
01342                 size);
01343 
01344         if (tag == MKTAG('i', 'd', 'x', '1') &&
01345             avi_read_idx1(s, size) >= 0) {
01346             avi->index_loaded=2;
01347             ret = 0;
01348             break;
01349         }
01350 
01351         size += (size & 1);
01352         if (avio_skip(pb, size) < 0)
01353             break; // something is wrong here
01354     }
01355  the_end:
01356     avio_seek(pb, pos, SEEK_SET);
01357     return ret;
01358 }
01359 
01360 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
01361 {
01362     AVIStream *ast2 = st2->priv_data;
01363     int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
01364     av_free_packet(&ast2->sub_pkt);
01365     if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
01366         avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
01367         av_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
01368 }
01369 
01370 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
01371 {
01372     AVIContext *avi = s->priv_data;
01373     AVStream *st;
01374     int i, index;
01375     int64_t pos, pos_min;
01376     AVIStream *ast;
01377 
01378     if (!avi->index_loaded) {
01379         /* we only load the index on demand */
01380         avi_load_index(s);
01381         avi->index_loaded |= 1;
01382     }
01383     assert(stream_index>= 0);
01384 
01385     st = s->streams[stream_index];
01386     ast= st->priv_data;
01387     index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
01388     if(index<0)
01389         return -1;
01390 
01391     /* find the position */
01392     pos = st->index_entries[index].pos;
01393     timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
01394 
01395 //    av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
01396 
01397     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
01398         /* One and only one real stream for DV in AVI, and it has video  */
01399         /* offsets. Calling with other stream indexes should have failed */
01400         /* the av_index_search_timestamp call above.                     */
01401         assert(stream_index == 0);
01402 
01403         if(avio_seek(s->pb, pos, SEEK_SET) < 0)
01404             return -1;
01405 
01406         /* Feed the DV video stream version of the timestamp to the */
01407         /* DV demux so it can synthesize correct timestamps.        */
01408         dv_offset_reset(avi->dv_demux, timestamp);
01409 
01410         avi->stream_index= -1;
01411         return 0;
01412     }
01413 
01414     pos_min= pos;
01415     for(i = 0; i < s->nb_streams; i++) {
01416         AVStream *st2 = s->streams[i];
01417         AVIStream *ast2 = st2->priv_data;
01418 
01419         ast2->packet_size=
01420         ast2->remaining= 0;
01421 
01422         if (ast2->sub_ctx) {
01423             seek_subtitle(st, st2, timestamp);
01424             continue;
01425         }
01426 
01427         if (st2->nb_index_entries <= 0)
01428             continue;
01429 
01430 //        assert(st2->codec->block_align);
01431         assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
01432         index = av_index_search_timestamp(
01433                 st2,
01434                 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
01435                 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
01436         if(index<0)
01437             index=0;
01438         ast2->seek_pos= st2->index_entries[index].pos;
01439         pos_min= FFMIN(pos_min,ast2->seek_pos);
01440     }
01441     for(i = 0; i < s->nb_streams; i++) {
01442         AVStream *st2 = s->streams[i];
01443         AVIStream *ast2 = st2->priv_data;
01444 
01445         if (ast2->sub_ctx || st2->nb_index_entries <= 0)
01446             continue;
01447 
01448         index = av_index_search_timestamp(
01449                 st2,
01450                 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
01451                 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
01452         if(index<0)
01453             index=0;
01454         while(!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
01455             index--;
01456         ast2->frame_offset = st2->index_entries[index].timestamp;
01457     }
01458 
01459     /* do the seek */
01460     if (avio_seek(s->pb, pos_min, SEEK_SET) < 0)
01461         return -1;
01462     avi->stream_index= -1;
01463     avi->dts_max= INT_MIN;
01464     return 0;
01465 }
01466 
01467 static int avi_read_close(AVFormatContext *s)
01468 {
01469     int i;
01470     AVIContext *avi = s->priv_data;
01471 
01472     for(i=0;i<s->nb_streams;i++) {
01473         AVStream *st = s->streams[i];
01474         AVIStream *ast = st->priv_data;
01475         if (ast) {
01476             if (ast->sub_ctx) {
01477                 av_freep(&ast->sub_ctx->pb);
01478                 avformat_close_input(&ast->sub_ctx);
01479             }
01480             av_free(ast->sub_buffer);
01481             av_free_packet(&ast->sub_pkt);
01482         }
01483     }
01484 
01485     av_free(avi->dv_demux);
01486 
01487     return 0;
01488 }
01489 
01490 static int avi_probe(AVProbeData *p)
01491 {
01492     int i;
01493 
01494     /* check file header */
01495     for(i=0; avi_headers[i][0]; i++)
01496         if(!memcmp(p->buf  , avi_headers[i]  , 4) &&
01497            !memcmp(p->buf+8, avi_headers[i]+4, 4))
01498             return AVPROBE_SCORE_MAX;
01499 
01500     return 0;
01501 }
01502 
01503 AVInputFormat ff_avi_demuxer = {
01504     .name           = "avi",
01505     .long_name      = NULL_IF_CONFIG_SMALL("AVI format"),
01506     .priv_data_size = sizeof(AVIContext),
01507     .read_probe     = avi_probe,
01508     .read_header    = avi_read_header,
01509     .read_packet    = avi_read_packet,
01510     .read_close     = avi_read_close,
01511     .read_seek      = avi_read_seek,
01512     .priv_class = &demuxer_class,
01513 };