LCOV - code coverage report
Current view: top level - libavformat - avidec.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 822 1148 71.6 %
Date: 2017-12-16 01:21:47 Functions: 21 24 87.5 %

          Line data    Source code
       1             : /*
       2             :  * AVI demuxer
       3             :  * Copyright (c) 2001 Fabrice Bellard
       4             :  *
       5             :  * This file is part of FFmpeg.
       6             :  *
       7             :  * FFmpeg is free software; you can redistribute it and/or
       8             :  * modify it under the terms of the GNU Lesser General Public
       9             :  * License as published by the Free Software Foundation; either
      10             :  * version 2.1 of the License, or (at your option) any later version.
      11             :  *
      12             :  * FFmpeg is distributed in the hope that it will be useful,
      13             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      15             :  * Lesser General Public License for more details.
      16             :  *
      17             :  * You should have received a copy of the GNU Lesser General Public
      18             :  * License along with FFmpeg; if not, write to the Free Software
      19             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      20             :  */
      21             : 
      22             : #include <inttypes.h>
      23             : 
      24             : #include "libavutil/avassert.h"
      25             : #include "libavutil/avstring.h"
      26             : #include "libavutil/bswap.h"
      27             : #include "libavutil/opt.h"
      28             : #include "libavutil/dict.h"
      29             : #include "libavutil/internal.h"
      30             : #include "libavutil/intreadwrite.h"
      31             : #include "libavutil/mathematics.h"
      32             : #include "avformat.h"
      33             : #include "avi.h"
      34             : #include "dv.h"
      35             : #include "internal.h"
      36             : #include "isom.h"
      37             : #include "riff.h"
      38             : #include "libavcodec/bytestream.h"
      39             : #include "libavcodec/exif.h"
      40             : #include "libavcodec/internal.h"
      41             : 
      42             : typedef struct AVIStream {
      43             :     int64_t frame_offset;   /* current frame (video) or byte (audio) counter
      44             :                              * (used to compute the pts) */
      45             :     int remaining;
      46             :     int packet_size;
      47             : 
      48             :     uint32_t handler;
      49             :     uint32_t scale;
      50             :     uint32_t rate;
      51             :     int sample_size;        /* size of one sample (or packet)
      52             :                              * (in the rate/scale sense) in bytes */
      53             : 
      54             :     int64_t cum_len;        /* temporary storage (used during seek) */
      55             :     int prefix;             /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
      56             :     int prefix_count;
      57             :     uint32_t pal[256];
      58             :     int has_pal;
      59             :     int dshow_block_align;  /* block align variable used to emulate bugs in
      60             :                              * the MS dshow demuxer */
      61             : 
      62             :     AVFormatContext *sub_ctx;
      63             :     AVPacket sub_pkt;
      64             :     uint8_t *sub_buffer;
      65             : 
      66             :     int64_t seek_pos;
      67             : } AVIStream;
      68             : 
      69             : typedef struct AVIContext {
      70             :     const AVClass *class;
      71             :     int64_t riff_end;
      72             :     int64_t movi_end;
      73             :     int64_t fsize;
      74             :     int64_t io_fsize;
      75             :     int64_t movi_list;
      76             :     int64_t last_pkt_pos;
      77             :     int index_loaded;
      78             :     int is_odml;
      79             :     int non_interleaved;
      80             :     int stream_index;
      81             :     DVDemuxContext *dv_demux;
      82             :     int odml_depth;
      83             :     int use_odml;
      84             : #define MAX_ODML_DEPTH 1000
      85             :     int64_t dts_max;
      86             : } AVIContext;
      87             : 
      88             : 
      89             : static const AVOption options[] = {
      90             :     { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
      91             :     { NULL },
      92             : };
      93             : 
      94             : static const AVClass demuxer_class = {
      95             :     .class_name = "avi",
      96             :     .item_name  = av_default_item_name,
      97             :     .option     = options,
      98             :     .version    = LIBAVUTIL_VERSION_INT,
      99             :     .category   = AV_CLASS_CATEGORY_DEMUXER,
     100             : };
     101             : 
     102             : 
     103             : static const char avi_headers[][8] = {
     104             :     { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' '  },
     105             :     { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X'  },
     106             :     { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
     107             :     { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f'  },
     108             :     { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' '  },
     109             :     { 0 }
     110             : };
     111             : 
     112             : static const AVMetadataConv avi_metadata_conv[] = {
     113             :     { "strn", "title" },
     114             :     { 0 },
     115             : };
     116             : 
     117             : static int avi_load_index(AVFormatContext *s);
     118             : static int guess_ni_flag(AVFormatContext *s);
     119             : 
     120             : #define print_tag(str, tag, size)                                      \
     121             :     av_log(NULL, AV_LOG_TRACE, "pos:%"PRIX64" %s: tag=%s size=0x%x\n", \
     122             :            avio_tell(pb), str, av_fourcc2str(tag), size)                  \
     123             : 
     124       57007 : static inline int get_duration(AVIStream *ast, int len)
     125             : {
     126       57007 :     if (ast->sample_size)
     127        8590 :         return len;
     128       48417 :     else if (ast->dshow_block_align)
     129         212 :         return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
     130             :     else
     131       48205 :         return 1;
     132             : }
     133             : 
     134         423 : static int get_riff(AVFormatContext *s, AVIOContext *pb)
     135             : {
     136         423 :     AVIContext *avi = s->priv_data;
     137         423 :     char header[8] = {0};
     138             :     int i;
     139             : 
     140             :     /* check RIFF header */
     141         423 :     avio_read(pb, header, 4);
     142         423 :     avi->riff_end  = avio_rl32(pb); /* RIFF chunk size */
     143         423 :     avi->riff_end += avio_tell(pb); /* RIFF chunk end */
     144         423 :     avio_read(pb, header + 4, 4);
     145             : 
     146         431 :     for (i = 0; avi_headers[i][0]; i++)
     147         431 :         if (!memcmp(header, avi_headers[i], 8))
     148         423 :             break;
     149         423 :     if (!avi_headers[i][0])
     150           0 :         return AVERROR_INVALIDDATA;
     151             : 
     152         423 :     if (header[7] == 0x19)
     153           0 :         av_log(s, AV_LOG_INFO,
     154             :                "This file has been generated by a totally broken muxer.\n");
     155             : 
     156         423 :     return 0;
     157             : }
     158             : 
     159          36 : static int read_odml_index(AVFormatContext *s, int frame_num)
     160             : {
     161          36 :     AVIContext *avi     = s->priv_data;
     162          36 :     AVIOContext *pb     = s->pb;
     163          36 :     int longs_per_entry = avio_rl16(pb);
     164          36 :     int index_sub_type  = avio_r8(pb);
     165          36 :     int index_type      = avio_r8(pb);
     166          36 :     int entries_in_use  = avio_rl32(pb);
     167          36 :     int chunk_id        = avio_rl32(pb);
     168          36 :     int64_t base        = avio_rl64(pb);
     169          72 :     int stream_id       = ((chunk_id      & 0xFF) - '0') * 10 +
     170          36 :                           ((chunk_id >> 8 & 0xFF) - '0');
     171             :     AVStream *st;
     172             :     AVIStream *ast;
     173             :     int i;
     174          36 :     int64_t last_pos = -1;
     175          36 :     int64_t filesize = avi->fsize;
     176             : 
     177          36 :     av_log(s, AV_LOG_TRACE,
     178             :             "longs_per_entry:%d index_type:%d entries_in_use:%d "
     179             :             "chunk_id:%X base:%16"PRIX64" frame_num:%d\n",
     180             :             longs_per_entry,
     181             :             index_type,
     182             :             entries_in_use,
     183             :             chunk_id,
     184             :             base,
     185             :             frame_num);
     186             : 
     187          36 :     if (stream_id >= s->nb_streams || stream_id < 0)
     188           9 :         return AVERROR_INVALIDDATA;
     189          27 :     st  = s->streams[stream_id];
     190          27 :     ast = st->priv_data;
     191             : 
     192          27 :     if (index_sub_type)
     193           0 :         return AVERROR_INVALIDDATA;
     194             : 
     195          27 :     avio_rl32(pb);
     196             : 
     197          27 :     if (index_type && longs_per_entry != 2)
     198           0 :         return AVERROR_INVALIDDATA;
     199          27 :     if (index_type > 1)
     200           0 :         return AVERROR_INVALIDDATA;
     201             : 
     202          27 :     if (filesize > 0 && base >= filesize) {
     203           0 :         av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
     204           0 :         if (base >> 32 == (base & 0xFFFFFFFF) &&
     205           0 :             (base & 0xFFFFFFFF) < filesize    &&
     206             :             filesize <= 0xFFFFFFFF)
     207           0 :             base &= 0xFFFFFFFF;
     208             :         else
     209           0 :             return AVERROR_INVALIDDATA;
     210             :     }
     211             : 
     212        5720 :     for (i = 0; i < entries_in_use; i++) {
     213        5693 :         if (index_type) {
     214        5675 :             int64_t pos = avio_rl32(pb) + base - 8;
     215        5675 :             int len     = avio_rl32(pb);
     216        5675 :             int key     = len >= 0;
     217        5675 :             len &= 0x7FFFFFFF;
     218             : 
     219        5675 :             av_log(s, AV_LOG_TRACE, "pos:%"PRId64", len:%X\n", pos, len);
     220             : 
     221        5675 :             if (avio_feof(pb))
     222           0 :                 return AVERROR_INVALIDDATA;
     223             : 
     224        5675 :             if (last_pos == pos || pos == base - 8)
     225           2 :                 avi->non_interleaved = 1;
     226        5675 :             if (last_pos != pos && len)
     227        5457 :                 av_add_index_entry(st, pos, ast->cum_len, len, 0,
     228             :                                    key ? AVINDEX_KEYFRAME : 0);
     229             : 
     230        5675 :             ast->cum_len += get_duration(ast, len);
     231        5675 :             last_pos      = pos;
     232             :         } else {
     233             :             int64_t offset, pos;
     234             :             int duration;
     235          18 :             offset = avio_rl64(pb);
     236          18 :             avio_rl32(pb);       /* size */
     237          18 :             duration = avio_rl32(pb);
     238             : 
     239          18 :             if (avio_feof(pb))
     240           0 :                 return AVERROR_INVALIDDATA;
     241             : 
     242          18 :             pos = avio_tell(pb);
     243             : 
     244          18 :             if (avi->odml_depth > MAX_ODML_DEPTH) {
     245           0 :                 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
     246           0 :                 return AVERROR_INVALIDDATA;
     247             :             }
     248             : 
     249          18 :             if (avio_seek(pb, offset + 8, SEEK_SET) < 0)
     250           0 :                 return -1;
     251          18 :             avi->odml_depth++;
     252          18 :             read_odml_index(s, frame_num);
     253          18 :             avi->odml_depth--;
     254          18 :             frame_num += duration;
     255             : 
     256          18 :             if (avio_seek(pb, pos, SEEK_SET) < 0) {
     257           0 :                 av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index\n");
     258           0 :                 return -1;
     259             :             }
     260             : 
     261             :         }
     262             :     }
     263          27 :     avi->index_loaded = 2;
     264          27 :     return 0;
     265             : }
     266             : 
     267           7 : static void clean_index(AVFormatContext *s)
     268             : {
     269             :     int i;
     270             :     int64_t j;
     271             : 
     272          19 :     for (i = 0; i < s->nb_streams; i++) {
     273          12 :         AVStream *st   = s->streams[i];
     274          12 :         AVIStream *ast = st->priv_data;
     275          12 :         int n          = st->nb_index_entries;
     276          12 :         int max        = ast->sample_size;
     277             :         int64_t pos, size, ts;
     278             : 
     279          12 :         if (n != 1 || ast->sample_size == 0)
     280          10 :             continue;
     281             : 
     282          22 :         while (max < 1024)
     283          18 :             max += max;
     284             : 
     285           2 :         pos  = st->index_entries[0].pos;
     286           2 :         size = st->index_entries[0].size;
     287           2 :         ts   = st->index_entries[0].timestamp;
     288             : 
     289          15 :         for (j = 0; j < size; j += max)
     290          13 :             av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
     291             :                                AVINDEX_KEYFRAME);
     292             :     }
     293           7 : }
     294             : 
     295          17 : static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
     296             :                         uint32_t size)
     297             : {
     298          17 :     AVIOContext *pb = s->pb;
     299          17 :     char key[5]     = { 0 };
     300             :     char *value;
     301             : 
     302          17 :     size += (size & 1);
     303             : 
     304          17 :     if (size == UINT_MAX)
     305           0 :         return AVERROR(EINVAL);
     306          17 :     value = av_malloc(size + 1);
     307          17 :     if (!value)
     308           0 :         return AVERROR(ENOMEM);
     309          17 :     if (avio_read(pb, value, size) != size)
     310           0 :         return AVERROR_INVALIDDATA;
     311          17 :     value[size] = 0;
     312             : 
     313          17 :     AV_WL32(key, tag);
     314             : 
     315          17 :     return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
     316             :                        AV_DICT_DONT_STRDUP_VAL);
     317             : }
     318             : 
     319             : static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
     320             :                                     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
     321             : 
     322           1 : static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
     323             : {
     324             :     char month[4], time[9], buffer[64];
     325             :     int i, day, year;
     326             :     /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
     327           1 :     if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
     328             :                month, &day, time, &year) == 4) {
     329          13 :         for (i = 0; i < 12; i++)
     330          12 :             if (!av_strcasecmp(month, months[i])) {
     331           1 :                 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
     332             :                          year, i + 1, day, time);
     333           1 :                 av_dict_set(metadata, "creation_time", buffer, 0);
     334             :             }
     335           0 :     } else if (date[4] == '/' && date[7] == '/') {
     336           0 :         date[4] = date[7] = '-';
     337           0 :         av_dict_set(metadata, "creation_time", date, 0);
     338             :     }
     339           1 : }
     340             : 
     341           0 : static void avi_read_nikon(AVFormatContext *s, uint64_t end)
     342             : {
     343           0 :     while (avio_tell(s->pb) < end && !avio_feof(s->pb)) {
     344           0 :         uint32_t tag  = avio_rl32(s->pb);
     345           0 :         uint32_t size = avio_rl32(s->pb);
     346           0 :         switch (tag) {
     347           0 :         case MKTAG('n', 'c', 't', 'g'):  /* Nikon Tags */
     348             :         {
     349           0 :             uint64_t tag_end = avio_tell(s->pb) + size;
     350           0 :             while (avio_tell(s->pb) < tag_end && !avio_feof(s->pb)) {
     351           0 :                 uint16_t tag     = avio_rl16(s->pb);
     352           0 :                 uint16_t size    = avio_rl16(s->pb);
     353           0 :                 const char *name = NULL;
     354           0 :                 char buffer[64]  = { 0 };
     355           0 :                 size = FFMIN(size, tag_end - avio_tell(s->pb));
     356           0 :                 size -= avio_read(s->pb, buffer,
     357           0 :                                   FFMIN(size, sizeof(buffer) - 1));
     358           0 :                 switch (tag) {
     359           0 :                 case 0x03:
     360           0 :                     name = "maker";
     361           0 :                     break;
     362           0 :                 case 0x04:
     363           0 :                     name = "model";
     364           0 :                     break;
     365           0 :                 case 0x13:
     366           0 :                     name = "creation_time";
     367           0 :                     if (buffer[4] == ':' && buffer[7] == ':')
     368           0 :                         buffer[4] = buffer[7] = '-';
     369           0 :                     break;
     370             :                 }
     371           0 :                 if (name)
     372           0 :                     av_dict_set(&s->metadata, name, buffer, 0);
     373           0 :                 avio_skip(s->pb, size);
     374             :             }
     375           0 :             break;
     376             :         }
     377           0 :         default:
     378           0 :             avio_skip(s->pb, size);
     379           0 :             break;
     380             :         }
     381             :     }
     382           0 : }
     383             : 
     384           5 : static int avi_extract_stream_metadata(AVFormatContext *s, AVStream *st)
     385             : {
     386             :     GetByteContext gb;
     387           5 :     uint8_t *data = st->codecpar->extradata;
     388           5 :     int data_size = st->codecpar->extradata_size;
     389             :     int tag, offset;
     390             : 
     391           5 :     if (!data || data_size < 8) {
     392           0 :         return AVERROR_INVALIDDATA;
     393             :     }
     394             : 
     395           5 :     bytestream2_init(&gb, data, data_size);
     396             : 
     397           5 :     tag = bytestream2_get_le32(&gb);
     398             : 
     399           5 :     switch (tag) {
     400           0 :     case MKTAG('A', 'V', 'I', 'F'):
     401             :         // skip 4 byte padding
     402           0 :         bytestream2_skip(&gb, 4);
     403           0 :         offset = bytestream2_tell(&gb);
     404             : 
     405             :         // decode EXIF tags from IFD, AVI is always little-endian
     406           0 :         return avpriv_exif_decode_ifd(s, data + offset, data_size - offset,
     407             :                                       1, 0, &st->metadata);
     408             :         break;
     409           0 :     case MKTAG('C', 'A', 'S', 'I'):
     410           0 :         avpriv_request_sample(s, "RIFF stream data tag type CASI (%u)", tag);
     411           0 :         break;
     412           0 :     case MKTAG('Z', 'o', 'r', 'a'):
     413           0 :         avpriv_request_sample(s, "RIFF stream data tag type Zora (%u)", tag);
     414           0 :         break;
     415           5 :     default:
     416           5 :         break;
     417             :     }
     418             : 
     419           5 :     return 0;
     420             : }
     421             : 
     422         423 : static int calculate_bitrate(AVFormatContext *s)
     423             : {
     424         423 :     AVIContext *avi = s->priv_data;
     425             :     int i, j;
     426         423 :     int64_t lensum = 0;
     427         423 :     int64_t maxpos = 0;
     428             : 
     429         885 :     for (i = 0; i<s->nb_streams; i++) {
     430         462 :         int64_t len = 0;
     431         462 :         AVStream *st = s->streams[i];
     432             : 
     433         462 :         if (!st->nb_index_entries)
     434          53 :             continue;
     435             : 
     436       28878 :         for (j = 0; j < st->nb_index_entries; j++)
     437       28469 :             len += st->index_entries[j].size;
     438         409 :         maxpos = FFMAX(maxpos, st->index_entries[j-1].pos);
     439         409 :         lensum += len;
     440             :     }
     441         423 :     if (maxpos < avi->io_fsize*9/10) // index does not cover the whole file
     442          97 :         return 0;
     443         326 :     if (lensum*9/10 > maxpos || lensum < maxpos*9/10) // frame sum and filesize mismatch
     444          26 :         return 0;
     445             : 
     446         619 :     for (i = 0; i<s->nb_streams; i++) {
     447         319 :         int64_t len = 0;
     448         319 :         AVStream *st = s->streams[i];
     449             :         int64_t duration;
     450             :         int64_t bitrate;
     451             : 
     452       25656 :         for (j = 0; j < st->nb_index_entries; j++)
     453       25337 :             len += st->index_entries[j].size;
     454             : 
     455         319 :         if (st->nb_index_entries < 2 || st->codecpar->bit_rate > 0)
     456          22 :             continue;
     457         297 :         duration = st->index_entries[j-1].timestamp - st->index_entries[0].timestamp;
     458         297 :         bitrate = av_rescale(8*len, st->time_base.den, duration * st->time_base.num);
     459         297 :         if (bitrate <= INT_MAX && bitrate > 0) {
     460         297 :             st->codecpar->bit_rate = bitrate;
     461             :         }
     462             :     }
     463         300 :     return 1;
     464             : }
     465             : 
     466         423 : static int avi_read_header(AVFormatContext *s)
     467             : {
     468         423 :     AVIContext *avi = s->priv_data;
     469         423 :     AVIOContext *pb = s->pb;
     470             :     unsigned int tag, tag1, handler;
     471             :     int codec_type, stream_index, frame_period;
     472             :     unsigned int size;
     473             :     int i;
     474             :     AVStream *st;
     475         423 :     AVIStream *ast      = NULL;
     476         423 :     int avih_width      = 0, avih_height = 0;
     477         423 :     int amv_file_format = 0;
     478         423 :     uint64_t list_end   = 0;
     479             :     int64_t pos;
     480             :     int ret;
     481             :     AVDictionaryEntry *dict_entry;
     482             : 
     483         423 :     avi->stream_index = -1;
     484             : 
     485         423 :     ret = get_riff(s, pb);
     486         423 :     if (ret < 0)
     487           0 :         return ret;
     488             : 
     489         423 :     av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
     490             : 
     491         423 :     avi->io_fsize = avi->fsize = avio_size(pb);
     492         423 :     if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
     493          35 :         avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
     494             : 
     495             :     /* first list tag */
     496         423 :     stream_index = -1;
     497         423 :     codec_type   = -1;
     498         423 :     frame_period = 0;
     499             :     for (;;) {
     500        7929 :         if (avio_feof(pb))
     501           0 :             goto fail;
     502        4176 :         tag  = avio_rl32(pb);
     503        4176 :         size = avio_rl32(pb);
     504             : 
     505        4176 :         print_tag("tag", tag, size);
     506             : 
     507        4176 :         switch (tag) {
     508        1420 :         case MKTAG('L', 'I', 'S', 'T'):
     509        1420 :             list_end = avio_tell(pb) + size;
     510             :             /* Ignored, except at start of video packets. */
     511        1420 :             tag1 = avio_rl32(pb);
     512             : 
     513        1420 :             print_tag("list", tag1, 0);
     514             : 
     515        1420 :             if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
     516         423 :                 avi->movi_list = avio_tell(pb) - 4;
     517         423 :                 if (size)
     518         421 :                     avi->movi_end = avi->movi_list + size + (size & 1);
     519             :                 else
     520           2 :                     avi->movi_end = avi->fsize;
     521         423 :                 av_log(NULL, AV_LOG_TRACE, "movi end=%"PRIx64"\n", avi->movi_end);
     522         423 :                 goto end_of_header;
     523         997 :             } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
     524          57 :                 ff_read_riff_info(s, size - 4);
     525         940 :             else if (tag1 == MKTAG('n', 'c', 'd', 't'))
     526           0 :                 avi_read_nikon(s, list_end);
     527             : 
     528         997 :             break;
     529           1 :         case MKTAG('I', 'D', 'I', 'T'):
     530             :         {
     531           1 :             unsigned char date[64] = { 0 };
     532           1 :             size += (size & 1);
     533           1 :             size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
     534           1 :             avio_skip(pb, size);
     535           1 :             avi_metadata_creation_time(&s->metadata, date);
     536           1 :             break;
     537             :         }
     538          38 :         case MKTAG('d', 'm', 'l', 'h'):
     539          38 :             avi->is_odml = 1;
     540          38 :             avio_skip(pb, size + (size & 1));
     541          38 :             break;
     542           2 :         case MKTAG('a', 'm', 'v', 'h'):
     543           2 :             amv_file_format = 1;
     544         423 :         case MKTAG('a', 'v', 'i', 'h'):
     545             :             /* AVI header */
     546             :             /* using frame_period is bad idea */
     547         423 :             frame_period = avio_rl32(pb);
     548         423 :             avio_rl32(pb); /* max. bytes per second */
     549         423 :             avio_rl32(pb);
     550         423 :             avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
     551             : 
     552         423 :             avio_skip(pb, 2 * 4);
     553         423 :             avio_rl32(pb);
     554         423 :             avio_rl32(pb);
     555         423 :             avih_width  = avio_rl32(pb);
     556         423 :             avih_height = avio_rl32(pb);
     557             : 
     558         423 :             avio_skip(pb, size - 10 * 4);
     559         423 :             break;
     560         463 :         case MKTAG('s', 't', 'r', 'h'):
     561             :             /* stream header */
     562             : 
     563         463 :             tag1    = avio_rl32(pb);
     564         463 :             handler = avio_rl32(pb); /* codec tag */
     565             : 
     566         463 :             if (tag1 == MKTAG('p', 'a', 'd', 's')) {
     567           1 :                 avio_skip(pb, size - 8);
     568           1 :                 break;
     569             :             } else {
     570         462 :                 stream_index++;
     571         462 :                 st = avformat_new_stream(s, NULL);
     572         462 :                 if (!st)
     573           0 :                     goto fail;
     574             : 
     575         462 :                 st->id = stream_index;
     576         462 :                 ast    = av_mallocz(sizeof(AVIStream));
     577         462 :                 if (!ast)
     578           0 :                     goto fail;
     579         462 :                 st->priv_data = ast;
     580             :             }
     581         462 :             if (amv_file_format)
     582           4 :                 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
     583           4 :                                     : MKTAG('v', 'i', 'd', 's');
     584             : 
     585         462 :             print_tag("strh", tag1, -1);
     586             : 
     587         462 :             if (tag1 == MKTAG('i', 'a', 'v', 's') ||
     588             :                 tag1 == MKTAG('i', 'v', 'a', 's')) {
     589             :                 int64_t dv_dur;
     590             : 
     591             :                 /* After some consideration -- I don't think we
     592             :                  * have to support anything but DV in type1 AVIs. */
     593           0 :                 if (s->nb_streams != 1)
     594           0 :                     goto fail;
     595             : 
     596           0 :                 if (handler != MKTAG('d', 'v', 's', 'd') &&
     597           0 :                     handler != MKTAG('d', 'v', 'h', 'd') &&
     598             :                     handler != MKTAG('d', 'v', 's', 'l'))
     599           0 :                     goto fail;
     600             : 
     601           0 :                 ast = s->streams[0]->priv_data;
     602           0 :                 av_freep(&s->streams[0]->codecpar->extradata);
     603           0 :                 av_freep(&s->streams[0]->codecpar);
     604             : #if FF_API_LAVF_AVCTX
     605             : FF_DISABLE_DEPRECATION_WARNINGS
     606           0 :                 av_freep(&s->streams[0]->codec);
     607             : FF_ENABLE_DEPRECATION_WARNINGS
     608             : #endif
     609           0 :                 if (s->streams[0]->info)
     610           0 :                     av_freep(&s->streams[0]->info->duration_error);
     611           0 :                 av_freep(&s->streams[0]->info);
     612           0 :                 if (s->streams[0]->internal)
     613           0 :                     av_freep(&s->streams[0]->internal->avctx);
     614           0 :                 av_freep(&s->streams[0]->internal);
     615           0 :                 av_freep(&s->streams[0]);
     616           0 :                 s->nb_streams = 0;
     617             :                 if (CONFIG_DV_DEMUXER) {
     618           0 :                     avi->dv_demux = avpriv_dv_init_demux(s);
     619           0 :                     if (!avi->dv_demux)
     620           0 :                         goto fail;
     621             :                 } else
     622             :                     goto fail;
     623           0 :                 s->streams[0]->priv_data = ast;
     624           0 :                 avio_skip(pb, 3 * 4);
     625           0 :                 ast->scale = avio_rl32(pb);
     626           0 :                 ast->rate  = avio_rl32(pb);
     627           0 :                 avio_skip(pb, 4);  /* start time */
     628             : 
     629           0 :                 dv_dur = avio_rl32(pb);
     630           0 :                 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
     631           0 :                     dv_dur     *= AV_TIME_BASE;
     632           0 :                     s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
     633             :                 }
     634             :                 /* else, leave duration alone; timing estimation in utils.c
     635             :                  * will make a guess based on bitrate. */
     636             : 
     637           0 :                 stream_index = s->nb_streams - 1;
     638           0 :                 avio_skip(pb, size - 9 * 4);
     639           0 :                 break;
     640             :             }
     641             : 
     642         462 :             av_assert0(stream_index < s->nb_streams);
     643         462 :             ast->handler = handler;
     644             : 
     645         462 :             avio_rl32(pb); /* flags */
     646         462 :             avio_rl16(pb); /* priority */
     647         462 :             avio_rl16(pb); /* language */
     648         462 :             avio_rl32(pb); /* initial frame */
     649         462 :             ast->scale = avio_rl32(pb);
     650         462 :             ast->rate  = avio_rl32(pb);
     651         462 :             if (!(ast->scale && ast->rate)) {
     652           4 :                 av_log(s, AV_LOG_WARNING,
     653             :                        "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
     654             :                        "(This file has been generated by broken software.)\n",
     655             :                        ast->scale,
     656             :                        ast->rate);
     657           4 :                 if (frame_period) {
     658           4 :                     ast->rate  = 1000000;
     659           4 :                     ast->scale = frame_period;
     660             :                 } else {
     661           0 :                     ast->rate  = 25;
     662           0 :                     ast->scale = 1;
     663             :                 }
     664             :             }
     665         462 :             avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
     666             : 
     667         462 :             ast->cum_len  = avio_rl32(pb); /* start */
     668         462 :             st->nb_frames = avio_rl32(pb);
     669             : 
     670         462 :             st->start_time = 0;
     671         462 :             avio_rl32(pb); /* buffer size */
     672         462 :             avio_rl32(pb); /* quality */
     673         462 :             if (ast->cum_len*ast->scale/ast->rate > 3600) {
     674           0 :                 av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
     675           0 :                 ast->cum_len = 0;
     676             :             }
     677         462 :             ast->sample_size = avio_rl32(pb);
     678         462 :             ast->cum_len    *= FFMAX(1, ast->sample_size);
     679         462 :             av_log(s, AV_LOG_TRACE, "%"PRIu32" %"PRIu32" %d\n",
     680             :                     ast->rate, ast->scale, ast->sample_size);
     681             : 
     682         462 :             switch (tag1) {
     683         420 :             case MKTAG('v', 'i', 'd', 's'):
     684         420 :                 codec_type = AVMEDIA_TYPE_VIDEO;
     685             : 
     686         420 :                 ast->sample_size = 0;
     687         420 :                 st->avg_frame_rate = av_inv_q(st->time_base);
     688         420 :                 break;
     689          42 :             case MKTAG('a', 'u', 'd', 's'):
     690          42 :                 codec_type = AVMEDIA_TYPE_AUDIO;
     691          42 :                 break;
     692           0 :             case MKTAG('t', 'x', 't', 's'):
     693           0 :                 codec_type = AVMEDIA_TYPE_SUBTITLE;
     694           0 :                 break;
     695           0 :             case MKTAG('d', 'a', 't', 's'):
     696           0 :                 codec_type = AVMEDIA_TYPE_DATA;
     697           0 :                 break;
     698           0 :             default:
     699           0 :                 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
     700             :             }
     701             : 
     702         462 :             if (ast->sample_size < 0) {
     703           0 :                 if (s->error_recognition & AV_EF_EXPLODE) {
     704           0 :                     av_log(s, AV_LOG_ERROR,
     705             :                            "Invalid sample_size %d at stream %d\n",
     706             :                            ast->sample_size,
     707             :                            stream_index);
     708           0 :                     goto fail;
     709             :                 }
     710           0 :                 av_log(s, AV_LOG_WARNING,
     711             :                        "Invalid sample_size %d at stream %d "
     712             :                        "setting it to 0\n",
     713             :                        ast->sample_size,
     714             :                        stream_index);
     715           0 :                 ast->sample_size = 0;
     716             :             }
     717             : 
     718         462 :             if (ast->sample_size == 0) {
     719         429 :                 st->duration = st->nb_frames;
     720         429 :                 if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) {
     721          36 :                     av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n");
     722          36 :                     st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end);
     723             :                 }
     724             :             }
     725         462 :             ast->frame_offset = ast->cum_len;
     726         462 :             avio_skip(pb, size - 12 * 4);
     727         462 :             break;
     728         462 :         case MKTAG('s', 't', 'r', 'f'):
     729             :             /* stream header */
     730         462 :             if (!size && (codec_type == AVMEDIA_TYPE_AUDIO ||
     731             :                           codec_type == AVMEDIA_TYPE_VIDEO))
     732             :                 break;
     733         462 :             if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
     734           0 :                 avio_skip(pb, size);
     735             :             } else {
     736         462 :                 uint64_t cur_pos = avio_tell(pb);
     737             :                 unsigned esize;
     738         462 :                 if (cur_pos < list_end)
     739         458 :                     size = FFMIN(size, list_end - cur_pos);
     740         462 :                 st = s->streams[stream_index];
     741         462 :                 if (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN) {
     742           0 :                     avio_skip(pb, size);
     743           0 :                     break;
     744             :                 }
     745         462 :                 switch (codec_type) {
     746         420 :                 case AVMEDIA_TYPE_VIDEO:
     747         420 :                     if (amv_file_format) {
     748           2 :                         st->codecpar->width      = avih_width;
     749           2 :                         st->codecpar->height     = avih_height;
     750           2 :                         st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
     751           2 :                         st->codecpar->codec_id   = AV_CODEC_ID_AMV;
     752           2 :                         avio_skip(pb, size);
     753           2 :                         break;
     754             :                     }
     755         418 :                     tag1 = ff_get_bmp_header(pb, st, &esize);
     756             : 
     757         418 :                     if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
     758             :                         tag1 == MKTAG('D', 'X', 'S', 'A')) {
     759           0 :                         st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
     760           0 :                         st->codecpar->codec_tag  = tag1;
     761           0 :                         st->codecpar->codec_id   = AV_CODEC_ID_XSUB;
     762           0 :                         break;
     763             :                     }
     764             : 
     765         418 :                     if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) {
     766         145 :                         if (esize == size-1 && (esize&1)) {
     767           9 :                             st->codecpar->extradata_size = esize - 10 * 4;
     768             :                         } else
     769         136 :                             st->codecpar->extradata_size =  size - 10 * 4;
     770         145 :                         if (st->codecpar->extradata) {
     771           0 :                             av_log(s, AV_LOG_WARNING, "New extradata in strf chunk, freeing previous one.\n");
     772           0 :                             av_freep(&st->codecpar->extradata);
     773             :                         }
     774         145 :                         if (ff_get_extradata(s, st->codecpar, pb, st->codecpar->extradata_size) < 0)
     775           0 :                             return AVERROR(ENOMEM);
     776             :                     }
     777             : 
     778             :                     // FIXME: check if the encoder really did this correctly
     779         418 :                     if (st->codecpar->extradata_size & 1)
     780           9 :                         avio_r8(pb);
     781             : 
     782             :                     /* Extract palette from extradata if bpp <= 8.
     783             :                      * This code assumes that extradata contains only palette.
     784             :                      * This is true for all paletted codecs implemented in
     785             :                      * FFmpeg. */
     786         563 :                     if (st->codecpar->extradata_size &&
     787         145 :                         (st->codecpar->bits_per_coded_sample <= 8)) {
     788          11 :                         int pal_size = (1 << st->codecpar->bits_per_coded_sample) << 2;
     789             :                         const uint8_t *pal_src;
     790             : 
     791          11 :                         pal_size = FFMIN(pal_size, st->codecpar->extradata_size);
     792          22 :                         pal_src  = st->codecpar->extradata +
     793          11 :                                    st->codecpar->extradata_size - pal_size;
     794             :                         /* Exclude the "BottomUp" field from the palette */
     795          11 :                         if (pal_src - st->codecpar->extradata >= 9 &&
     796           0 :                             !memcmp(st->codecpar->extradata + st->codecpar->extradata_size - 9, "BottomUp", 9))
     797           0 :                             pal_src -= 9;
     798        1317 :                         for (i = 0; i < pal_size / 4; i++)
     799        1306 :                             ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src + 4 * i);
     800          11 :                         ast->has_pal = 1;
     801             :                     }
     802             : 
     803         418 :                     print_tag("video", tag1, 0);
     804             : 
     805         418 :                     st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
     806         418 :                     st->codecpar->codec_tag  = tag1;
     807         418 :                     st->codecpar->codec_id   = ff_codec_get_id(ff_codec_bmp_tags,
     808             :                                                             tag1);
     809             :                     /* If codec is not found yet, try with the mov tags. */
     810         418 :                     if (!st->codecpar->codec_id) {
     811           0 :                         st->codecpar->codec_id =
     812           0 :                             ff_codec_get_id(ff_codec_movvideo_tags, tag1);
     813           0 :                         if (st->codecpar->codec_id)
     814           0 :                            av_log(s, AV_LOG_WARNING,
     815             :                                   "mov tag found in avi (fourcc %s)\n",
     816           0 :                                   av_fourcc2str(tag1));
     817             :                     }
     818             :                     /* This is needed to get the pict type which is necessary
     819             :                      * for generating correct pts. */
     820         418 :                     st->need_parsing = AVSTREAM_PARSE_HEADERS;
     821             : 
     822         472 :                     if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4 &&
     823          54 :                         ast->handler == MKTAG('X', 'V', 'I', 'D'))
     824           2 :                         st->codecpar->codec_tag = MKTAG('X', 'V', 'I', 'D');
     825             : 
     826         418 :                     if (st->codecpar->codec_tag == MKTAG('V', 'S', 'S', 'H'))
     827           0 :                         st->need_parsing = AVSTREAM_PARSE_FULL;
     828         418 :                     if (st->codecpar->codec_id == AV_CODEC_ID_RV40)
     829           0 :                         st->need_parsing = AVSTREAM_PARSE_NONE;
     830             : 
     831         418 :                     if (st->codecpar->codec_tag == 0 && st->codecpar->height > 0 &&
     832           0 :                         st->codecpar->extradata_size < 1U << 30) {
     833           0 :                         st->codecpar->extradata_size += 9;
     834           0 :                         if ((ret = av_reallocp(&st->codecpar->extradata,
     835           0 :                                                st->codecpar->extradata_size +
     836             :                                                AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {
     837           0 :                             st->codecpar->extradata_size = 0;
     838           0 :                             return ret;
     839             :                         } else
     840           0 :                             memcpy(st->codecpar->extradata + st->codecpar->extradata_size - 9,
     841             :                                    "BottomUp", 9);
     842             :                     }
     843         418 :                     st->codecpar->height = FFABS(st->codecpar->height);
     844             : 
     845             : //                    avio_skip(pb, size - 5 * 4);
     846         418 :                     break;
     847          42 :                 case AVMEDIA_TYPE_AUDIO:
     848          42 :                     ret = ff_get_wav_header(s, pb, st->codecpar, size, 0);
     849          42 :                     if (ret < 0)
     850           0 :                         return ret;
     851          42 :                     ast->dshow_block_align = st->codecpar->block_align;
     852          75 :                     if (ast->sample_size && st->codecpar->block_align &&
     853          33 :                         ast->sample_size != st->codecpar->block_align) {
     854           0 :                         av_log(s,
     855             :                                AV_LOG_WARNING,
     856             :                                "sample size (%d) != block align (%d)\n",
     857             :                                ast->sample_size,
     858           0 :                                st->codecpar->block_align);
     859           0 :                         ast->sample_size = st->codecpar->block_align;
     860             :                     }
     861             :                     /* 2-aligned
     862             :                      * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
     863          42 :                     if (size & 1)
     864           0 :                         avio_skip(pb, 1);
     865             :                     /* Force parsing as several audio frames can be in
     866             :                      * one packet and timestamps refer to packet start. */
     867          42 :                     st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
     868             :                     /* ADTS header is in extradata, AAC without header must be
     869             :                      * stored as exact frames. Parser not needed and it will
     870             :                      * fail. */
     871          42 :                     if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
     872           0 :                         st->codecpar->extradata_size)
     873           0 :                         st->need_parsing = AVSTREAM_PARSE_NONE;
     874             :                     // The flac parser does not work with AVSTREAM_PARSE_TIMESTAMPS
     875          42 :                     if (st->codecpar->codec_id == AV_CODEC_ID_FLAC)
     876           0 :                         st->need_parsing = AVSTREAM_PARSE_NONE;
     877             :                     /* AVI files with Xan DPCM audio (wrongly) declare PCM
     878             :                      * audio in the header but have Axan as stream_code_tag. */
     879          42 :                     if (ast->handler == AV_RL32("Axan")) {
     880           2 :                         st->codecpar->codec_id  = AV_CODEC_ID_XAN_DPCM;
     881           2 :                         st->codecpar->codec_tag = 0;
     882           2 :                         ast->dshow_block_align = 0;
     883             :                     }
     884          42 :                     if (amv_file_format) {
     885           2 :                         st->codecpar->codec_id    = AV_CODEC_ID_ADPCM_IMA_AMV;
     886           2 :                         ast->dshow_block_align = 0;
     887             :                     }
     888          84 :                     if ((st->codecpar->codec_id == AV_CODEC_ID_AAC  ||
     889          84 :                          st->codecpar->codec_id == AV_CODEC_ID_FLAC ||
     890          45 :                          st->codecpar->codec_id == AV_CODEC_ID_MP2 ) && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
     891           0 :                         av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
     892           0 :                         ast->dshow_block_align = 0;
     893             :                     }
     894          84 :                     if (st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
     895          84 :                        st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
     896          44 :                        st->codecpar->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
     897           0 :                         av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
     898           0 :                         ast->sample_size = 0;
     899             :                     }
     900          42 :                     break;
     901           0 :                 case AVMEDIA_TYPE_SUBTITLE:
     902           0 :                     st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
     903           0 :                     st->request_probe= 1;
     904           0 :                     avio_skip(pb, size);
     905           0 :                     break;
     906           0 :                 default:
     907           0 :                     st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
     908           0 :                     st->codecpar->codec_id   = AV_CODEC_ID_NONE;
     909           0 :                     st->codecpar->codec_tag  = 0;
     910           0 :                     avio_skip(pb, size);
     911           0 :                     break;
     912             :                 }
     913             :             }
     914         462 :             break;
     915           9 :         case MKTAG('s', 't', 'r', 'd'):
     916           9 :             if (stream_index >= (unsigned)s->nb_streams
     917           9 :                 || s->streams[stream_index]->codecpar->extradata_size
     918           5 :                 || s->streams[stream_index]->codecpar->codec_tag == MKTAG('H','2','6','4')) {
     919           4 :                 avio_skip(pb, size);
     920             :             } else {
     921           5 :                 uint64_t cur_pos = avio_tell(pb);
     922           5 :                 if (cur_pos < list_end)
     923           5 :                     size = FFMIN(size, list_end - cur_pos);
     924           5 :                 st = s->streams[stream_index];
     925             : 
     926           5 :                 if (size<(1<<30)) {
     927           5 :                     if (st->codecpar->extradata) {
     928           0 :                         av_log(s, AV_LOG_WARNING, "New extradata in strd chunk, freeing previous one.\n");
     929           0 :                         av_freep(&st->codecpar->extradata);
     930             :                     }
     931           5 :                     if (ff_get_extradata(s, st->codecpar, pb, size) < 0)
     932           0 :                         return AVERROR(ENOMEM);
     933             :                 }
     934             : 
     935           5 :                 if (st->codecpar->extradata_size & 1) //FIXME check if the encoder really did this correctly
     936           0 :                     avio_r8(pb);
     937             : 
     938           5 :                 ret = avi_extract_stream_metadata(s, st);
     939           5 :                 if (ret < 0) {
     940           0 :                     av_log(s, AV_LOG_WARNING, "could not decoding EXIF data in stream header.\n");
     941             :                 }
     942             :             }
     943           9 :             break;
     944          18 :         case MKTAG('i', 'n', 'd', 'x'):
     945          18 :             pos = avio_tell(pb);
     946          36 :             if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !(s->flags & AVFMT_FLAG_IGNIDX) &&
     947          36 :                 avi->use_odml &&
     948          18 :                 read_odml_index(s, 0) < 0 &&
     949           0 :                 (s->error_recognition & AV_EF_EXPLODE))
     950           0 :                 goto fail;
     951          18 :             avio_seek(pb, pos + size, SEEK_SET);
     952          18 :             break;
     953          10 :         case MKTAG('v', 'p', 'r', 'p'):
     954          10 :             if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
     955             :                 AVRational active, active_aspect;
     956             : 
     957          10 :                 st = s->streams[stream_index];
     958          10 :                 avio_rl32(pb);
     959          10 :                 avio_rl32(pb);
     960          10 :                 avio_rl32(pb);
     961          10 :                 avio_rl32(pb);
     962          10 :                 avio_rl32(pb);
     963             : 
     964          10 :                 active_aspect.den = avio_rl16(pb);
     965          10 :                 active_aspect.num = avio_rl16(pb);
     966          10 :                 active.num        = avio_rl32(pb);
     967          10 :                 active.den        = avio_rl32(pb);
     968          10 :                 avio_rl32(pb); // nbFieldsPerFrame
     969             : 
     970          20 :                 if (active_aspect.num && active_aspect.den &&
     971          20 :                     active.num && active.den) {
     972          10 :                     st->sample_aspect_ratio = av_div_q(active_aspect, active);
     973          10 :                     av_log(s, AV_LOG_TRACE, "vprp %d/%d %d/%d\n",
     974             :                             active_aspect.num, active_aspect.den,
     975             :                             active.num, active.den);
     976             :                 }
     977          10 :                 size -= 9 * 4;
     978             :             }
     979          10 :             avio_skip(pb, size);
     980          10 :             break;
     981          17 :         case MKTAG('s', 't', 'r', 'n'):
     982          17 :             if (s->nb_streams) {
     983          17 :                 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
     984          17 :                 if (ret < 0)
     985           0 :                     return ret;
     986          17 :                 break;
     987             :             }
     988             :         default:
     989        1315 :             if (size > 1000000) {
     990           0 :                 av_log(s, AV_LOG_ERROR,
     991             :                        "Something went wrong during header parsing, "
     992             :                        "tag %s has size %u, "
     993             :                        "I will ignore it and try to continue anyway.\n",
     994           0 :                        av_fourcc2str(tag), size);
     995           0 :                 if (s->error_recognition & AV_EF_EXPLODE)
     996           0 :                     goto fail;
     997           0 :                 avi->movi_list = avio_tell(pb) - 4;
     998           0 :                 avi->movi_end  = avi->fsize;
     999           0 :                 goto end_of_header;
    1000             :             }
    1001             :         /* Do not fail for very large idx1 tags */
    1002             :         case MKTAG('i', 'd', 'x', '1'):
    1003             :             /* skip tag */
    1004        1315 :             size += (size & 1);
    1005        1315 :             avio_skip(pb, size);
    1006        1315 :             break;
    1007             :         }
    1008           0 :     }
    1009             : 
    1010         423 : end_of_header:
    1011             :     /* check stream number */
    1012         423 :     if (stream_index != s->nb_streams - 1) {
    1013             : 
    1014           0 : fail:
    1015           0 :         return AVERROR_INVALIDDATA;
    1016             :     }
    1017             : 
    1018         423 :     if (!avi->index_loaded && (pb->seekable & AVIO_SEEKABLE_NORMAL))
    1019         413 :         avi_load_index(s);
    1020         423 :     calculate_bitrate(s);
    1021         423 :     avi->index_loaded    |= 1;
    1022             : 
    1023         423 :     if ((ret = guess_ni_flag(s)) < 0)
    1024           0 :         return ret;
    1025             : 
    1026         423 :     avi->non_interleaved |= ret | (s->flags & AVFMT_FLAG_SORT_DTS);
    1027             : 
    1028         423 :     dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0);
    1029         423 :     if (dict_entry && !strcmp(dict_entry->value, "PotEncoder"))
    1030           0 :         for (i = 0; i < s->nb_streams; i++) {
    1031           0 :             AVStream *st = s->streams[i];
    1032           0 :             if (   st->codecpar->codec_id == AV_CODEC_ID_MPEG1VIDEO
    1033           0 :                 || st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO)
    1034           0 :                 st->need_parsing = AVSTREAM_PARSE_FULL;
    1035             :         }
    1036             : 
    1037         475 :     for (i = 0; i < s->nb_streams; i++) {
    1038         440 :         AVStream *st = s->streams[i];
    1039         440 :         if (st->nb_index_entries)
    1040         388 :             break;
    1041             :     }
    1042             :     // DV-in-AVI cannot be non-interleaved, if set this must be
    1043             :     // a mis-detection.
    1044         423 :     if (avi->dv_demux)
    1045           0 :         avi->non_interleaved = 0;
    1046         423 :     if (i == s->nb_streams && avi->non_interleaved) {
    1047           1 :         av_log(s, AV_LOG_WARNING,
    1048             :                "Non-interleaved AVI without index, switching to interleaved\n");
    1049           1 :         avi->non_interleaved = 0;
    1050             :     }
    1051             : 
    1052         423 :     if (avi->non_interleaved) {
    1053           7 :         av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
    1054           7 :         clean_index(s);
    1055             :     }
    1056             : 
    1057         423 :     ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
    1058         423 :     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
    1059             : 
    1060         423 :     return 0;
    1061             : }
    1062             : 
    1063           0 : static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)
    1064             : {
    1065           0 :     if (pkt->size >= 7 &&
    1066           0 :         pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
    1067           0 :         !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
    1068             :         uint8_t desc[256];
    1069           0 :         int score      = AVPROBE_SCORE_EXTENSION, ret;
    1070           0 :         AVIStream *ast = st->priv_data;
    1071             :         AVInputFormat *sub_demuxer;
    1072             :         AVRational time_base;
    1073             :         int size;
    1074           0 :         AVIOContext *pb = avio_alloc_context(pkt->data + 7,
    1075           0 :                                              pkt->size - 7,
    1076             :                                              0, NULL, NULL, NULL, NULL);
    1077             :         AVProbeData pd;
    1078           0 :         unsigned int desc_len = avio_rl32(pb);
    1079             : 
    1080           0 :         if (desc_len > pb->buf_end - pb->buf_ptr)
    1081           0 :             goto error;
    1082             : 
    1083           0 :         ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
    1084           0 :         avio_skip(pb, desc_len - ret);
    1085           0 :         if (*desc)
    1086           0 :             av_dict_set(&st->metadata, "title", desc, 0);
    1087             : 
    1088           0 :         avio_rl16(pb);   /* flags? */
    1089           0 :         avio_rl32(pb);   /* data size */
    1090             : 
    1091           0 :         size = pb->buf_end - pb->buf_ptr;
    1092           0 :         pd = (AVProbeData) { .buf      = av_mallocz(size + AVPROBE_PADDING_SIZE),
    1093             :                              .buf_size = size };
    1094           0 :         if (!pd.buf)
    1095           0 :             goto error;
    1096           0 :         memcpy(pd.buf, pb->buf_ptr, size);
    1097           0 :         sub_demuxer = av_probe_input_format2(&pd, 1, &score);
    1098           0 :         av_freep(&pd.buf);
    1099           0 :         if (!sub_demuxer)
    1100           0 :             goto error;
    1101             : 
    1102           0 :         if (strcmp(sub_demuxer->name, "srt") && strcmp(sub_demuxer->name, "ass"))
    1103           0 :             goto error;
    1104             : 
    1105           0 :         if (!(ast->sub_ctx = avformat_alloc_context()))
    1106           0 :             goto error;
    1107             : 
    1108           0 :         ast->sub_ctx->pb = pb;
    1109             : 
    1110           0 :         if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0)
    1111           0 :             goto error;
    1112             : 
    1113           0 :         if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
    1114           0 :             if (ast->sub_ctx->nb_streams != 1)
    1115           0 :                 goto error;
    1116           0 :             ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
    1117           0 :             avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
    1118           0 :             time_base = ast->sub_ctx->streams[0]->time_base;
    1119           0 :             avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
    1120             :         }
    1121           0 :         ast->sub_buffer = pkt->data;
    1122           0 :         memset(pkt, 0, sizeof(*pkt));
    1123           0 :         return 1;
    1124             : 
    1125           0 : error:
    1126           0 :         av_freep(&ast->sub_ctx);
    1127           0 :         avio_context_free(&pb);
    1128             :     }
    1129           0 :     return 0;
    1130             : }
    1131             : 
    1132       23962 : static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
    1133             :                                   AVPacket *pkt)
    1134             : {
    1135       23962 :     AVIStream *ast, *next_ast = next_st->priv_data;
    1136       23962 :     int64_t ts, next_ts, ts_min = INT64_MAX;
    1137       23962 :     AVStream *st, *sub_st = NULL;
    1138             :     int i;
    1139             : 
    1140       23962 :     next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
    1141       23962 :                            AV_TIME_BASE_Q);
    1142             : 
    1143       53496 :     for (i = 0; i < s->nb_streams; i++) {
    1144       29534 :         st  = s->streams[i];
    1145       29534 :         ast = st->priv_data;
    1146       29534 :         if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
    1147           0 :             ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
    1148           0 :             if (ts <= next_ts && ts < ts_min) {
    1149           0 :                 ts_min = ts;
    1150           0 :                 sub_st = st;
    1151             :             }
    1152             :         }
    1153             :     }
    1154             : 
    1155       23962 :     if (sub_st) {
    1156           0 :         ast               = sub_st->priv_data;
    1157           0 :         *pkt              = ast->sub_pkt;
    1158           0 :         pkt->stream_index = sub_st->index;
    1159             : 
    1160           0 :         if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
    1161           0 :             ast->sub_pkt.data = NULL;
    1162             :     }
    1163       23962 :     return sub_st;
    1164             : }
    1165             : 
    1166      477978 : static int get_stream_idx(const unsigned *d)
    1167             : {
    1168      560070 :     if (d[0] >= '0' && d[0] <= '9' &&
    1169      163826 :         d[1] >= '0' && d[1] <= '9') {
    1170       55057 :         return (d[0] - '0') * 10 + (d[1] - '0');
    1171             :     } else {
    1172      422921 :         return 100; // invalid stream ID
    1173             :     }
    1174             : }
    1175             : 
    1176             : /**
    1177             :  *
    1178             :  * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
    1179             :  */
    1180       23977 : static int avi_sync(AVFormatContext *s, int exit_early)
    1181             : {
    1182       23977 :     AVIContext *avi = s->priv_data;
    1183       23977 :     AVIOContext *pb = s->pb;
    1184             :     int n;
    1185             :     unsigned int d[8];
    1186             :     unsigned int size;
    1187             :     int64_t i, sync;
    1188             : 
    1189       28150 : start_sync:
    1190       28150 :     memset(d, -1, sizeof(d));
    1191      330253 :     for (i = sync = avio_tell(pb); !avio_feof(pb); i++) {
    1192             :         int j;
    1193             : 
    1194     2638328 :         for (j = 0; j < 7; j++)
    1195     2308537 :             d[j] = d[j + 1];
    1196      329791 :         d[7] = avio_r8(pb);
    1197             : 
    1198      329791 :         size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
    1199             : 
    1200      329791 :         n = get_stream_idx(d + 2);
    1201             :         ff_tlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
    1202             :                 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
    1203      329791 :         if (i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127)
    1204      221805 :             continue;
    1205             : 
    1206             :         // parse ix##
    1207      215971 :         if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
    1208             :             // parse JUNK
    1209      215971 :             (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
    1210      215037 :             (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1') ||
    1211      107089 :             (d[0] == 'i' && d[1] == 'n' && d[2] == 'd' && d[3] == 'x')) {
    1212         898 :             avio_skip(pb, size);
    1213         898 :             goto start_sync;
    1214             :         }
    1215             : 
    1216             :         // parse stray LIST
    1217      107088 :         if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
    1218         643 :             avio_skip(pb, 4);
    1219         643 :             goto start_sync;
    1220             :         }
    1221             : 
    1222      106445 :         n = get_stream_idx(d);
    1223             : 
    1224      147441 :         if (!((i - avi->last_pkt_pos) & 1) &&
    1225       40996 :             get_stream_idx(d + 1) < s->nb_streams)
    1226         735 :             continue;
    1227             : 
    1228             :         // detect ##ix chunk and skip
    1229      105710 :         if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
    1230           0 :             avio_skip(pb, size);
    1231           0 :             goto start_sync;
    1232             :         }
    1233             : 
    1234      105710 :         if (avi->dv_demux && n != 0)
    1235           0 :             continue;
    1236             : 
    1237             :         // parse ##dc/##wb
    1238      105710 :         if (n < s->nb_streams) {
    1239             :             AVStream *st;
    1240             :             AVIStream *ast;
    1241       26147 :             st  = s->streams[n];
    1242       26147 :             ast = st->priv_data;
    1243             : 
    1244       26147 :             if (!ast) {
    1245           0 :                 av_log(s, AV_LOG_WARNING, "Skipping foreign stream %d packet\n", n);
    1246           0 :                 continue;
    1247             :             }
    1248             : 
    1249       26147 :             if (s->nb_streams >= 2) {
    1250        7655 :                 AVStream *st1   = s->streams[1];
    1251        7655 :                 AVIStream *ast1 = st1->priv_data;
    1252             :                 // workaround for broken small-file-bug402.avi
    1253        7655 :                 if (   d[2] == 'w' && d[3] == 'b'
    1254        2836 :                    && n == 0
    1255         314 :                    && st ->codecpar->codec_type == AVMEDIA_TYPE_VIDEO
    1256           0 :                    && st1->codecpar->codec_type == AVMEDIA_TYPE_AUDIO
    1257           0 :                    && ast->prefix == 'd'*256+'c'
    1258           0 :                    && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
    1259             :                   ) {
    1260           0 :                     n   = 1;
    1261           0 :                     st  = st1;
    1262           0 :                     ast = ast1;
    1263           0 :                     av_log(s, AV_LOG_WARNING,
    1264             :                            "Invalid stream + prefix combination, assuming audio.\n");
    1265             :                 }
    1266             :             }
    1267             : 
    1268       26147 :             if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
    1269           4 :                 int k    = avio_r8(pb);
    1270           4 :                 int last = (k + avio_r8(pb) - 1) & 0xFF;
    1271             : 
    1272           4 :                 avio_rl16(pb); // flags
    1273             : 
    1274             :                 // b + (g << 8) + (r << 16);
    1275         763 :                 for (; k <= last; k++)
    1276         759 :                     ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;
    1277             : 
    1278           4 :                 ast->has_pal = 1;
    1279           4 :                 goto start_sync;
    1280       52272 :             } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
    1281       52272 :                         d[2] < 128 && d[3] < 128) ||
    1282          14 :                        d[2] * 256 + d[3] == ast->prefix /* ||
    1283             :                        (d[2] == 'd' && d[3] == 'c') ||
    1284             :                        (d[2] == 'w' && d[3] == 'b') */) {
    1285       26143 :                 if (exit_early)
    1286         382 :                     return 0;
    1287       25761 :                 if (d[2] * 256 + d[3] == ast->prefix)
    1288       25243 :                     ast->prefix_count++;
    1289             :                 else {
    1290         518 :                     ast->prefix       = d[2] * 256 + d[3];
    1291         518 :                     ast->prefix_count = 0;
    1292             :                 }
    1293             : 
    1294       51522 :                 if (!avi->dv_demux &&
    1295       29763 :                     ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
    1296             :                         // FIXME: needs a little reordering
    1297             :                         (st->discard >= AVDISCARD_NONKEY &&
    1298             :                         !(pkt->flags & AV_PKT_FLAG_KEY)) */
    1299       25488 :                     || st->discard >= AVDISCARD_ALL)) {
    1300             : 
    1301        2628 :                     ast->frame_offset += get_duration(ast, size);
    1302        2628 :                     avio_skip(pb, size);
    1303        2628 :                     goto start_sync;
    1304             :                 }
    1305             : 
    1306       23133 :                 avi->stream_index = n;
    1307       23133 :                 ast->packet_size  = size + 8;
    1308       23133 :                 ast->remaining    = size;
    1309             : 
    1310       23133 :                 if (size) {
    1311       21621 :                     uint64_t pos = avio_tell(pb) - 8;
    1312       43191 :                     if (!st->index_entries || !st->nb_index_entries ||
    1313       21570 :                         st->index_entries[st->nb_index_entries - 1].pos < pos) {
    1314        2205 :                         av_add_index_entry(st, pos, ast->frame_offset, size,
    1315             :                                            0, AVINDEX_KEYFRAME);
    1316             :                     }
    1317             :                 }
    1318       23133 :                 return 0;
    1319             :             }
    1320             :         }
    1321             :     }
    1322             : 
    1323         462 :     if (pb->error)
    1324           0 :         return pb->error;
    1325         462 :     return AVERROR_EOF;
    1326             : }
    1327             : 
    1328         766 : static int ni_prepare_read(AVFormatContext *s)
    1329             : {
    1330         766 :     AVIContext *avi = s->priv_data;
    1331         766 :     int best_stream_index = 0;
    1332         766 :     AVStream *best_st     = NULL;
    1333             :     AVIStream *best_ast;
    1334         766 :     int64_t best_ts = INT64_MAX;
    1335             :     int i;
    1336             : 
    1337        2054 :     for (i = 0; i < s->nb_streams; i++) {
    1338        1288 :         AVStream *st   = s->streams[i];
    1339        1288 :         AVIStream *ast = st->priv_data;
    1340        1288 :         int64_t ts     = ast->frame_offset;
    1341             :         int64_t last_ts;
    1342             : 
    1343        1288 :         if (!st->nb_index_entries)
    1344           0 :             continue;
    1345             : 
    1346        1288 :         last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
    1347        1288 :         if (!ast->remaining && ts > last_ts)
    1348          16 :             continue;
    1349             : 
    1350        1272 :         ts = av_rescale_q(ts, st->time_base,
    1351        1272 :                           (AVRational) { FFMAX(1, ast->sample_size),
    1352             :                                          AV_TIME_BASE });
    1353             : 
    1354        1272 :         av_log(s, AV_LOG_TRACE, "%"PRId64" %d/%d %"PRId64"\n", ts,
    1355             :                 st->time_base.num, st->time_base.den, ast->frame_offset);
    1356        1272 :         if (ts < best_ts) {
    1357         975 :             best_ts           = ts;
    1358         975 :             best_st           = st;
    1359         975 :             best_stream_index = i;
    1360             :         }
    1361             :     }
    1362         766 :     if (!best_st)
    1363           5 :         return AVERROR_EOF;
    1364             : 
    1365         761 :     best_ast = best_st->priv_data;
    1366         761 :     best_ts  = best_ast->frame_offset;
    1367         761 :     if (best_ast->remaining) {
    1368         181 :         i = av_index_search_timestamp(best_st,
    1369             :                                       best_ts,
    1370             :                                       AVSEEK_FLAG_ANY |
    1371             :                                       AVSEEK_FLAG_BACKWARD);
    1372             :     } else {
    1373         580 :         i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
    1374         580 :         if (i >= 0)
    1375         580 :             best_ast->frame_offset = best_st->index_entries[i].timestamp;
    1376             :     }
    1377             : 
    1378         761 :     if (i >= 0) {
    1379         761 :         int64_t pos = best_st->index_entries[i].pos;
    1380         761 :         pos += best_ast->packet_size - best_ast->remaining;
    1381         761 :         if (avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
    1382           0 :           return AVERROR_EOF;
    1383             : 
    1384         761 :         av_assert0(best_ast->remaining <= best_ast->packet_size);
    1385             : 
    1386         761 :         avi->stream_index = best_stream_index;
    1387         761 :         if (!best_ast->remaining)
    1388         580 :             best_ast->packet_size =
    1389         580 :             best_ast->remaining   = best_st->index_entries[i].size;
    1390             :     }
    1391             :     else
    1392           0 :         return AVERROR_EOF;
    1393             : 
    1394         761 :     return 0;
    1395             : }
    1396             : 
    1397       24428 : static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
    1398             : {
    1399       24428 :     AVIContext *avi = s->priv_data;
    1400       24428 :     AVIOContext *pb = s->pb;
    1401             :     int err;
    1402             : 
    1403       24428 :     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
    1404           0 :         int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
    1405           0 :         if (size >= 0)
    1406           0 :             return size;
    1407             :         else
    1408           0 :             goto resync;
    1409             :     }
    1410             : 
    1411       24428 :     if (avi->non_interleaved) {
    1412         766 :         err = ni_prepare_read(s);
    1413         766 :         if (err < 0)
    1414           5 :             return err;
    1415             :     }
    1416             : 
    1417       24423 : resync:
    1418       47557 :     if (avi->stream_index >= 0) {
    1419       23962 :         AVStream *st   = s->streams[avi->stream_index];
    1420       23962 :         AVIStream *ast = st->priv_data;
    1421             :         int size, err;
    1422             : 
    1423       23962 :         if (get_subtitle_pkt(s, st, pkt))
    1424           0 :             return 0;
    1425             : 
    1426             :         // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
    1427       23962 :         if (ast->sample_size <= 1)
    1428       21094 :             size = INT_MAX;
    1429        2868 :         else if (ast->sample_size < 32)
    1430             :             // arbitrary multiplier to avoid tiny packets for raw PCM data
    1431         238 :             size = 1024 * ast->sample_size;
    1432             :         else
    1433        2630 :             size = ast->sample_size;
    1434             : 
    1435       23962 :         if (size > ast->remaining)
    1436       21105 :             size = ast->remaining;
    1437       23962 :         avi->last_pkt_pos = avio_tell(pb);
    1438       23962 :         err               = av_get_packet(pb, pkt, size);
    1439       23962 :         if (err < 0)
    1440          35 :             return err;
    1441       23927 :         size = err;
    1442             : 
    1443       23927 :         if (ast->has_pal && pkt->size < (unsigned)INT_MAX / 2) {
    1444             :             uint8_t *pal;
    1445          15 :             pal = av_packet_new_side_data(pkt,
    1446             :                                           AV_PKT_DATA_PALETTE,
    1447             :                                           AVPALETTE_SIZE);
    1448          15 :             if (!pal) {
    1449           0 :                 av_log(s, AV_LOG_ERROR,
    1450             :                        "Failed to allocate data for palette\n");
    1451             :             } else {
    1452          15 :                 memcpy(pal, ast->pal, AVPALETTE_SIZE);
    1453          15 :                 ast->has_pal = 0;
    1454             :             }
    1455             :         }
    1456             : 
    1457       23927 :         if (CONFIG_DV_DEMUXER && avi->dv_demux) {
    1458           0 :             AVBufferRef *avbuf = pkt->buf;
    1459           0 :             size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
    1460             :                                             pkt->data, pkt->size, pkt->pos);
    1461           0 :             pkt->buf    = avbuf;
    1462           0 :             pkt->flags |= AV_PKT_FLAG_KEY;
    1463           0 :             if (size < 0)
    1464           0 :                 av_packet_unref(pkt);
    1465       23927 :         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
    1466           0 :                    !st->codecpar->codec_tag && read_gab2_sub(s, st, pkt)) {
    1467           0 :             ast->frame_offset++;
    1468           0 :             avi->stream_index = -1;
    1469           0 :             ast->remaining    = 0;
    1470           0 :             goto resync;
    1471             :         } else {
    1472             :             /* XXX: How to handle B-frames in AVI? */
    1473       23927 :             pkt->dts = ast->frame_offset;
    1474             : //                pkt->dts += ast->start;
    1475       23927 :             if (ast->sample_size)
    1476        3226 :                 pkt->dts /= ast->sample_size;
    1477       23927 :             pkt->stream_index = avi->stream_index;
    1478             : 
    1479       44231 :             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->index_entries) {
    1480             :                 AVIndexEntry *e;
    1481             :                 int index;
    1482             : 
    1483       20304 :                 index = av_index_search_timestamp(st, ast->frame_offset, AVSEEK_FLAG_ANY);
    1484       20304 :                 e     = &st->index_entries[index];
    1485             : 
    1486       20304 :                 if (index >= 0 && e->timestamp == ast->frame_offset) {
    1487       18791 :                     if (index == st->nb_index_entries-1) {
    1488        2137 :                         int key=1;
    1489        2137 :                         uint32_t state=-1;
    1490        2137 :                         if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
    1491          52 :                             const uint8_t *ptr = pkt->data, *end = ptr + FFMIN(size, 256);
    1492         161 :                             while (ptr < end) {
    1493         109 :                                 ptr = avpriv_find_start_code(ptr, end, &state);
    1494         109 :                                 if (state == 0x1B6 && ptr < end) {
    1495          52 :                                     key = !(*ptr & 0xC0);
    1496          52 :                                     break;
    1497             :                                 }
    1498             :                             }
    1499             :                         }
    1500        2137 :                         if (!key)
    1501          39 :                             e->flags &= ~AVINDEX_KEYFRAME;
    1502             :                     }
    1503       18791 :                     if (e->flags & AVINDEX_KEYFRAME)
    1504       11050 :                         pkt->flags |= AV_PKT_FLAG_KEY;
    1505             :                 }
    1506             :             } else {
    1507        3623 :                 pkt->flags |= AV_PKT_FLAG_KEY;
    1508             :             }
    1509       23927 :             ast->frame_offset += get_duration(ast, pkt->size);
    1510             :         }
    1511       23927 :         ast->remaining -= err;
    1512       23927 :         if (!ast->remaining) {
    1513       23681 :             avi->stream_index = -1;
    1514       23681 :             ast->packet_size  = 0;
    1515             :         }
    1516             : 
    1517       23927 :         if (!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos) {
    1518           1 :             av_packet_unref(pkt);
    1519           1 :             goto resync;
    1520             :         }
    1521       23926 :         ast->seek_pos= 0;
    1522             : 
    1523       23926 :         if (!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1) {
    1524       21403 :             int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
    1525             : 
    1526       21403 :             if (avi->dts_max - dts > 2*AV_TIME_BASE) {
    1527           0 :                 avi->non_interleaved= 1;
    1528           0 :                 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
    1529       21403 :             }else if (avi->dts_max < dts)
    1530       20761 :                 avi->dts_max = dts;
    1531             :         }
    1532             : 
    1533       23926 :         return 0;
    1534             :     }
    1535             : 
    1536       23595 :     if ((err = avi_sync(s, 0)) < 0)
    1537         462 :         return err;
    1538       23133 :     goto resync;
    1539             : }
    1540             : 
    1541             : /* XXX: We make the implicit supposition that the positions are sorted
    1542             :  * for each stream. */
    1543         382 : static int avi_read_idx1(AVFormatContext *s, int size)
    1544             : {
    1545         382 :     AVIContext *avi = s->priv_data;
    1546         382 :     AVIOContext *pb = s->pb;
    1547             :     int nb_index_entries, i;
    1548             :     AVStream *st;
    1549             :     AVIStream *ast;
    1550             :     int64_t pos;
    1551         382 :     unsigned int index, tag, flags, len, first_packet = 1;
    1552         382 :     int64_t last_pos = -1;
    1553         382 :     unsigned last_idx = -1;
    1554         382 :     int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
    1555         382 :     int anykey = 0;
    1556             : 
    1557         382 :     nb_index_entries = size / 16;
    1558         382 :     if (nb_index_entries <= 0)
    1559           0 :         return AVERROR_INVALIDDATA;
    1560             : 
    1561         382 :     idx1_pos = avio_tell(pb);
    1562         382 :     avio_seek(pb, avi->movi_list + 4, SEEK_SET);
    1563         382 :     if (avi_sync(s, 1) == 0)
    1564         382 :         first_packet_pos = avio_tell(pb) - 8;
    1565         382 :     avi->stream_index = -1;
    1566         382 :     avio_seek(pb, idx1_pos, SEEK_SET);
    1567             : 
    1568         382 :     if (s->nb_streams == 1 && s->streams[0]->codecpar->codec_tag == AV_RL32("MMES")) {
    1569           0 :         first_packet_pos = 0;
    1570           0 :         data_offset = avi->movi_list;
    1571             :     }
    1572             : 
    1573             :     /* Read the entries and sort them in each stream component. */
    1574       25451 :     for (i = 0; i < nb_index_entries; i++) {
    1575       25069 :         if (avio_feof(pb))
    1576           0 :             return -1;
    1577             : 
    1578       25069 :         tag   = avio_rl32(pb);
    1579       25069 :         flags = avio_rl32(pb);
    1580       25069 :         pos   = avio_rl32(pb);
    1581       25069 :         len   = avio_rl32(pb);
    1582       25069 :         av_log(s, AV_LOG_TRACE, "%d: tag=0x%x flags=0x%x pos=0x%"PRIx64" len=%d/",
    1583             :                 i, tag, flags, pos, len);
    1584             : 
    1585       25069 :         index  = ((tag      & 0xff) - '0') * 10;
    1586       25069 :         index +=  (tag >> 8 & 0xff) - '0';
    1587       25069 :         if (index >= s->nb_streams)
    1588         290 :             continue;
    1589       24779 :         st  = s->streams[index];
    1590       24779 :         ast = st->priv_data;
    1591             : 
    1592             :         /* Skip 'xxpc' palette change entries in the index until a logic
    1593             :          * to process these is properly implemented. */
    1594       24779 :         if ((tag >> 16 & 0xff) == 'p' && (tag >> 24 & 0xff) == 'c')
    1595           2 :             continue;
    1596             : 
    1597       24777 :         if (first_packet && first_packet_pos) {
    1598         382 :             if (avi->movi_list + 4 != pos || pos + 500 > first_packet_pos)
    1599         382 :                 data_offset  = first_packet_pos - pos;
    1600         382 :             first_packet = 0;
    1601             :         }
    1602       24777 :         pos += data_offset;
    1603             : 
    1604       24777 :         av_log(s, AV_LOG_TRACE, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
    1605             : 
    1606             :         // even if we have only a single stream, we should
    1607             :         // switch to non-interleaved to get correct timestamps
    1608       24777 :         if (last_pos == pos)
    1609           0 :             avi->non_interleaved = 1;
    1610       24777 :         if (last_idx != pos && len) {
    1611       23012 :             av_add_index_entry(st, pos, ast->cum_len, len, 0,
    1612       23012 :                                (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
    1613       23012 :             last_idx= pos;
    1614             :         }
    1615       24777 :         ast->cum_len += get_duration(ast, len);
    1616       24777 :         last_pos      = pos;
    1617       24777 :         anykey       |= flags&AVIIF_INDEX;
    1618             :     }
    1619         382 :     if (!anykey) {
    1620           2 :         for (index = 0; index < s->nb_streams; index++) {
    1621           1 :             st = s->streams[index];
    1622           1 :             if (st->nb_index_entries)
    1623           1 :                 st->index_entries[0].flags |= AVINDEX_KEYFRAME;
    1624             :         }
    1625             :     }
    1626         382 :     return 0;
    1627             : }
    1628             : 
    1629             : /* Scan the index and consider any file with streams more than
    1630             :  * 2 seconds or 64MB apart non-interleaved. */
    1631         418 : static int check_stream_max_drift(AVFormatContext *s)
    1632             : {
    1633             :     int64_t min_pos, pos;
    1634             :     int i;
    1635         418 :     int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
    1636         418 :     if (!idx)
    1637           0 :         return AVERROR(ENOMEM);
    1638       28918 :     for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
    1639       28500 :         int64_t max_dts = INT64_MIN / 2;
    1640       28500 :         int64_t min_dts = INT64_MAX / 2;
    1641       28500 :         int64_t max_buffer = 0;
    1642             : 
    1643       28500 :         min_pos = INT64_MAX;
    1644             : 
    1645       65257 :         for (i = 0; i < s->nb_streams; i++) {
    1646       36757 :             AVStream *st = s->streams[i];
    1647       36757 :             AVIStream *ast = st->priv_data;
    1648       36757 :             int n = st->nb_index_entries;
    1649      101596 :             while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
    1650       28082 :                 idx[i]++;
    1651       36757 :             if (idx[i] < n) {
    1652             :                 int64_t dts;
    1653       72136 :                 dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
    1654       36068 :                                    FFMAX(ast->sample_size, 1),
    1655       36068 :                                    st->time_base, AV_TIME_BASE_Q);
    1656       36068 :                 min_dts = FFMIN(min_dts, dts);
    1657       36068 :                 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
    1658             :             }
    1659             :         }
    1660       65257 :         for (i = 0; i < s->nb_streams; i++) {
    1661       36757 :             AVStream *st = s->streams[i];
    1662       36757 :             AVIStream *ast = st->priv_data;
    1663             : 
    1664       36757 :             if (idx[i] && min_dts != INT64_MAX / 2) {
    1665             :                 int64_t dts;
    1666       71420 :                 dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
    1667       35710 :                                    FFMAX(ast->sample_size, 1),
    1668       35710 :                                    st->time_base, AV_TIME_BASE_Q);
    1669       35710 :                 max_dts = FFMAX(max_dts, dts);
    1670       35710 :                 max_buffer = FFMAX(max_buffer,
    1671             :                                    av_rescale(dts - min_dts,
    1672             :                                               st->codecpar->bit_rate,
    1673             :                                               AV_TIME_BASE));
    1674             :             }
    1675             :         }
    1676       28500 :         if (max_dts - min_dts > 2 * AV_TIME_BASE ||
    1677             :             max_buffer > 1024 * 1024 * 8 * 8) {
    1678           0 :             av_free(idx);
    1679           0 :             return 1;
    1680             :         }
    1681             :     }
    1682         418 :     av_free(idx);
    1683         418 :     return 0;
    1684             : }
    1685             : 
    1686         423 : static int guess_ni_flag(AVFormatContext *s)
    1687             : {
    1688             :     int i;
    1689         423 :     int64_t last_start = 0;
    1690         423 :     int64_t first_end  = INT64_MAX;
    1691         423 :     int64_t oldpos     = avio_tell(s->pb);
    1692             : 
    1693         885 :     for (i = 0; i < s->nb_streams; i++) {
    1694         462 :         AVStream *st = s->streams[i];
    1695         462 :         int n        = st->nb_index_entries;
    1696             :         unsigned int size;
    1697             : 
    1698         462 :         if (n <= 0)
    1699          53 :             continue;
    1700             : 
    1701         409 :         if (n >= 2) {
    1702         373 :             int64_t pos = st->index_entries[0].pos;
    1703             :             unsigned tag[2];
    1704         373 :             avio_seek(s->pb, pos, SEEK_SET);
    1705         373 :             tag[0] = avio_r8(s->pb);
    1706         373 :             tag[1] = avio_r8(s->pb);
    1707         373 :             avio_rl16(s->pb);
    1708         373 :             size = avio_rl32(s->pb);
    1709         373 :             if (get_stream_idx(tag) == i && pos + size > st->index_entries[1].pos)
    1710           0 :                 last_start = INT64_MAX;
    1711         373 :             if (get_stream_idx(tag) == i && size == st->index_entries[0].size + 8)
    1712           0 :                 last_start = INT64_MAX;
    1713             :         }
    1714             : 
    1715         409 :         if (st->index_entries[0].pos > last_start)
    1716         400 :             last_start = st->index_entries[0].pos;
    1717         409 :         if (st->index_entries[n - 1].pos < first_end)
    1718         396 :             first_end = st->index_entries[n - 1].pos;
    1719             :     }
    1720         423 :     avio_seek(s->pb, oldpos, SEEK_SET);
    1721             : 
    1722         423 :     if (last_start > first_end)
    1723           5 :         return 1;
    1724             : 
    1725         418 :     return check_stream_max_drift(s);
    1726             : }
    1727             : 
    1728         413 : static int avi_load_index(AVFormatContext *s)
    1729             : {
    1730         413 :     AVIContext *avi = s->priv_data;
    1731         413 :     AVIOContext *pb = s->pb;
    1732             :     uint32_t tag, size;
    1733         413 :     int64_t pos = avio_tell(pb);
    1734             :     int64_t next;
    1735         413 :     int ret     = -1;
    1736             : 
    1737         413 :     if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
    1738           0 :         goto the_end; // maybe truncated file
    1739         413 :     av_log(s, AV_LOG_TRACE, "movi_end=0x%"PRIx64"\n", avi->movi_end);
    1740             :     for (;;) {
    1741        1193 :         tag  = avio_rl32(pb);
    1742         803 :         size = avio_rl32(pb);
    1743         803 :         if (avio_feof(pb))
    1744         390 :             break;
    1745         413 :         next = avio_tell(pb) + size + (size & 1);
    1746             : 
    1747         795 :         if (tag == MKTAG('i', 'd', 'x', '1') &&
    1748         382 :             avi_read_idx1(s, size) >= 0) {
    1749         382 :             avi->index_loaded=2;
    1750         382 :             ret = 0;
    1751          31 :         }else if (tag == MKTAG('L', 'I', 'S', 'T')) {
    1752           8 :             uint32_t tag1 = avio_rl32(pb);
    1753             : 
    1754           8 :             if (tag1 == MKTAG('I', 'N', 'F', 'O'))
    1755           4 :                 ff_read_riff_info(s, size - 4);
    1756          23 :         }else if (!ret)
    1757          23 :             break;
    1758             : 
    1759         390 :         if (avio_seek(pb, next, SEEK_SET) < 0)
    1760           0 :             break; // something is wrong here
    1761             :     }
    1762             : 
    1763         413 : the_end:
    1764         413 :     avio_seek(pb, pos, SEEK_SET);
    1765         413 :     return ret;
    1766             : }
    1767             : 
    1768           0 : static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
    1769             : {
    1770           0 :     AVIStream *ast2 = st2->priv_data;
    1771           0 :     int64_t ts2     = av_rescale_q(timestamp, st->time_base, st2->time_base);
    1772           0 :     av_packet_unref(&ast2->sub_pkt);
    1773           0 :     if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
    1774           0 :         avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
    1775           0 :         ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
    1776           0 : }
    1777             : 
    1778         728 : static int avi_read_seek(AVFormatContext *s, int stream_index,
    1779             :                          int64_t timestamp, int flags)
    1780             : {
    1781         728 :     AVIContext *avi = s->priv_data;
    1782             :     AVStream *st;
    1783             :     int i, index;
    1784             :     int64_t pos, pos_min;
    1785             :     AVIStream *ast;
    1786             : 
    1787             :     /* Does not matter which stream is requested dv in avi has the
    1788             :      * stream information in the first video stream.
    1789             :      */
    1790         728 :     if (avi->dv_demux)
    1791           0 :         stream_index = 0;
    1792             : 
    1793         728 :     if (!avi->index_loaded) {
    1794             :         /* we only load the index on demand */
    1795           0 :         avi_load_index(s);
    1796           0 :         avi->index_loaded |= 1;
    1797             :     }
    1798         728 :     av_assert0(stream_index >= 0);
    1799             : 
    1800         728 :     st    = s->streams[stream_index];
    1801         728 :     ast   = st->priv_data;
    1802         728 :     index = av_index_search_timestamp(st,
    1803         728 :                                       timestamp * FFMAX(ast->sample_size, 1),
    1804             :                                       flags);
    1805         728 :     if (index < 0) {
    1806         198 :         if (st->nb_index_entries > 0)
    1807         594 :             av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
    1808         198 :                    timestamp * FFMAX(ast->sample_size, 1),
    1809         198 :                    st->index_entries[0].timestamp,
    1810         198 :                    st->index_entries[st->nb_index_entries - 1].timestamp);
    1811         198 :         return AVERROR_INVALIDDATA;
    1812             :     }
    1813             : 
    1814             :     /* find the position */
    1815         530 :     pos       = st->index_entries[index].pos;
    1816         530 :     timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
    1817             : 
    1818         530 :     av_log(s, AV_LOG_TRACE, "XX %"PRId64" %d %"PRId64"\n",
    1819         530 :             timestamp, index, st->index_entries[index].timestamp);
    1820             : 
    1821         530 :     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
    1822             :         /* One and only one real stream for DV in AVI, and it has video  */
    1823             :         /* offsets. Calling with other stream indexes should have failed */
    1824             :         /* the av_index_search_timestamp call above.                     */
    1825             : 
    1826           0 :         if (avio_seek(s->pb, pos, SEEK_SET) < 0)
    1827           0 :             return -1;
    1828             : 
    1829             :         /* Feed the DV video stream version of the timestamp to the */
    1830             :         /* DV demux so it can synthesize correct timestamps.        */
    1831           0 :         ff_dv_offset_reset(avi->dv_demux, timestamp);
    1832             : 
    1833           0 :         avi->stream_index = -1;
    1834           0 :         return 0;
    1835             :     }
    1836             : 
    1837         530 :     pos_min = pos;
    1838        1077 :     for (i = 0; i < s->nb_streams; i++) {
    1839         547 :         AVStream *st2   = s->streams[i];
    1840         547 :         AVIStream *ast2 = st2->priv_data;
    1841             : 
    1842         547 :         ast2->packet_size =
    1843         547 :         ast2->remaining   = 0;
    1844             : 
    1845         547 :         if (ast2->sub_ctx) {
    1846           0 :             seek_subtitle(st, st2, timestamp);
    1847           0 :             continue;
    1848             :         }
    1849             : 
    1850         547 :         if (st2->nb_index_entries <= 0)
    1851           0 :             continue;
    1852             : 
    1853             : //        av_assert1(st2->codecpar->block_align);
    1854        1094 :         index = av_index_search_timestamp(st2,
    1855         547 :                                           av_rescale_q(timestamp,
    1856             :                                                        st->time_base,
    1857             :                                                        st2->time_base) *
    1858         547 :                                           FFMAX(ast2->sample_size, 1),
    1859         547 :                                           flags |
    1860             :                                           AVSEEK_FLAG_BACKWARD |
    1861         547 :                                           (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
    1862         547 :         if (index < 0)
    1863           0 :             index = 0;
    1864         547 :         ast2->seek_pos = st2->index_entries[index].pos;
    1865         547 :         pos_min = FFMIN(pos_min,ast2->seek_pos);
    1866             :     }
    1867        1077 :     for (i = 0; i < s->nb_streams; i++) {
    1868         547 :         AVStream *st2 = s->streams[i];
    1869         547 :         AVIStream *ast2 = st2->priv_data;
    1870             : 
    1871         547 :         if (ast2->sub_ctx || st2->nb_index_entries <= 0)
    1872           0 :             continue;
    1873             : 
    1874        1094 :         index = av_index_search_timestamp(
    1875             :                 st2,
    1876         547 :                 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
    1877         547 :                 flags | AVSEEK_FLAG_BACKWARD | (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
    1878         547 :         if (index < 0)
    1879           0 :             index = 0;
    1880        1105 :         while (!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
    1881          11 :             index--;
    1882         547 :         ast2->frame_offset = st2->index_entries[index].timestamp;
    1883             :     }
    1884             : 
    1885             :     /* do the seek */
    1886         530 :     if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
    1887           0 :         av_log(s, AV_LOG_ERROR, "Seek failed\n");
    1888           0 :         return -1;
    1889             :     }
    1890         530 :     avi->stream_index = -1;
    1891         530 :     avi->dts_max      = INT_MIN;
    1892         530 :     return 0;
    1893             : }
    1894             : 
    1895         423 : static int avi_read_close(AVFormatContext *s)
    1896             : {
    1897             :     int i;
    1898         423 :     AVIContext *avi = s->priv_data;
    1899             : 
    1900         885 :     for (i = 0; i < s->nb_streams; i++) {
    1901         462 :         AVStream *st   = s->streams[i];
    1902         462 :         AVIStream *ast = st->priv_data;
    1903         462 :         if (ast) {
    1904         462 :             if (ast->sub_ctx) {
    1905           0 :                 av_freep(&ast->sub_ctx->pb);
    1906           0 :                 avformat_close_input(&ast->sub_ctx);
    1907             :             }
    1908         462 :             av_freep(&ast->sub_buffer);
    1909         462 :             av_packet_unref(&ast->sub_pkt);
    1910             :         }
    1911             :     }
    1912             : 
    1913         423 :     av_freep(&avi->dv_demux);
    1914             : 
    1915         423 :     return 0;
    1916             : }
    1917             : 
    1918        6130 : static int avi_probe(AVProbeData *p)
    1919             : {
    1920             :     int i;
    1921             : 
    1922             :     /* check file header */
    1923       34673 :     for (i = 0; avi_headers[i][0]; i++)
    1924       31315 :         if (AV_RL32(p->buf    ) == AV_RL32(avi_headers[i]    ) &&
    1925        2349 :             AV_RL32(p->buf + 8) == AV_RL32(avi_headers[i] + 4))
    1926         423 :             return AVPROBE_SCORE_MAX;
    1927             : 
    1928        5707 :     return 0;
    1929             : }
    1930             : 
    1931             : AVInputFormat ff_avi_demuxer = {
    1932             :     .name           = "avi",
    1933             :     .long_name      = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
    1934             :     .priv_data_size = sizeof(AVIContext),
    1935             :     .extensions     = "avi",
    1936             :     .read_probe     = avi_probe,
    1937             :     .read_header    = avi_read_header,
    1938             :     .read_packet    = avi_read_packet,
    1939             :     .read_close     = avi_read_close,
    1940             :     .read_seek      = avi_read_seek,
    1941             :     .priv_class = &demuxer_class,
    1942             : };

Generated by: LCOV version 1.13