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