3 * Copyright (c) 2001 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
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"
38 #include "libavcodec/bytestream.h"
39 #include "libavcodec/exif.h"
40 #include "libavcodec/internal.h"
42 typedef struct AVIStream {
43 int64_t frame_offset; /* current frame (video) or byte (audio) counter
44 * (used to compute the pts) */
51 int sample_size; /* size of one sample (or packet)
52 * (in the rate/scale sense) in bytes */
54 int64_t cum_len; /* temporary storage (used during seek) */
55 int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
59 int dshow_block_align; /* block align variable used to emulate bugs in
60 * the MS dshow demuxer */
62 AVFormatContext *sub_ctx;
69 typedef struct AVIContext {
81 DVDemuxContext *dv_demux;
84 #define MAX_ODML_DEPTH 1000
89 static const AVOption options[] = {
90 { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_INT, {.i64 = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
94 static const AVClass demuxer_class = {
96 .item_name = av_default_item_name,
98 .version = LIBAVUTIL_VERSION_INT,
99 .category = AV_CLASS_CATEGORY_DEMUXER,
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', ' ' },
112 static const AVMetadataConv avi_metadata_conv[] = {
117 static int avi_load_index(AVFormatContext *s);
118 static int guess_ni_flag(AVFormatContext *s);
120 #define print_tag(str, tag, size) \
121 av_log(NULL, AV_LOG_TRACE, "pos:%"PRIX64" %s: tag=%c%c%c%c size=0x%x\n", \
122 avio_tell(pb), str, tag & 0xff, \
124 (tag >> 16) & 0xff, \
125 (tag >> 24) & 0xff, \
128 static inline int get_duration(AVIStream *ast, int len)
130 if (ast->sample_size)
132 else if (ast->dshow_block_align)
133 return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
138 static int get_riff(AVFormatContext *s, AVIOContext *pb)
140 AVIContext *avi = s->priv_data;
141 char header[8] = {0};
144 /* check RIFF header */
145 avio_read(pb, header, 4);
146 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
147 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
148 avio_read(pb, header + 4, 4);
150 for (i = 0; avi_headers[i][0]; i++)
151 if (!memcmp(header, avi_headers[i], 8))
153 if (!avi_headers[i][0])
154 return AVERROR_INVALIDDATA;
156 if (header[7] == 0x19)
157 av_log(s, AV_LOG_INFO,
158 "This file has been generated by a totally broken muxer.\n");
163 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
165 AVIContext *avi = s->priv_data;
166 AVIOContext *pb = s->pb;
167 int longs_pre_entry = avio_rl16(pb);
168 int index_sub_type = avio_r8(pb);
169 int index_type = avio_r8(pb);
170 int entries_in_use = avio_rl32(pb);
171 int chunk_id = avio_rl32(pb);
172 int64_t base = avio_rl64(pb);
173 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
174 ((chunk_id >> 8 & 0xFF) - '0');
178 int64_t last_pos = -1;
179 int64_t filesize = avi->fsize;
181 av_log(s, AV_LOG_TRACE,
182 "longs_pre_entry:%d index_type:%d entries_in_use:%d "
183 "chunk_id:%X base:%16"PRIX64" frame_num:%d\n",
191 if (stream_id >= s->nb_streams || stream_id < 0)
192 return AVERROR_INVALIDDATA;
193 st = s->streams[stream_id];
197 return AVERROR_INVALIDDATA;
201 if (index_type && longs_pre_entry != 2)
202 return AVERROR_INVALIDDATA;
204 return AVERROR_INVALIDDATA;
206 if (filesize > 0 && base >= filesize) {
207 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
208 if (base >> 32 == (base & 0xFFFFFFFF) &&
209 (base & 0xFFFFFFFF) < filesize &&
210 filesize <= 0xFFFFFFFF)
213 return AVERROR_INVALIDDATA;
216 for (i = 0; i < entries_in_use; i++) {
218 int64_t pos = avio_rl32(pb) + base - 8;
219 int len = avio_rl32(pb);
223 av_log(s, AV_LOG_TRACE, "pos:%"PRId64", len:%X\n", pos, len);
226 return AVERROR_INVALIDDATA;
228 if (last_pos == pos || pos == base - 8)
229 avi->non_interleaved = 1;
230 if (last_pos != pos && len)
231 av_add_index_entry(st, pos, ast->cum_len, len, 0,
232 key ? AVINDEX_KEYFRAME : 0);
234 ast->cum_len += get_duration(ast, len);
239 offset = avio_rl64(pb);
240 avio_rl32(pb); /* size */
241 duration = avio_rl32(pb);
244 return AVERROR_INVALIDDATA;
248 if (avi->odml_depth > MAX_ODML_DEPTH) {
249 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
250 return AVERROR_INVALIDDATA;
253 if (avio_seek(pb, offset + 8, SEEK_SET) < 0)
256 read_braindead_odml_indx(s, frame_num);
258 frame_num += duration;
260 if (avio_seek(pb, pos, SEEK_SET) < 0) {
261 av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index\n");
267 avi->index_loaded = 2;
271 static void clean_index(AVFormatContext *s)
276 for (i = 0; i < s->nb_streams; i++) {
277 AVStream *st = s->streams[i];
278 AVIStream *ast = st->priv_data;
279 int n = st->nb_index_entries;
280 int max = ast->sample_size;
281 int64_t pos, size, ts;
283 if (n != 1 || ast->sample_size == 0)
289 pos = st->index_entries[0].pos;
290 size = st->index_entries[0].size;
291 ts = st->index_entries[0].timestamp;
293 for (j = 0; j < size; j += max)
294 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
299 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
302 AVIOContext *pb = s->pb;
308 if (size == UINT_MAX)
309 return AVERROR(EINVAL);
310 value = av_malloc(size + 1);
312 return AVERROR(ENOMEM);
313 if (avio_read(pb, value, size) != size)
314 return AVERROR_INVALIDDATA;
319 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
320 AV_DICT_DONT_STRDUP_VAL);
323 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
324 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
326 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
328 char month[4], time[9], buffer[64];
330 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
331 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
332 month, &day, time, &year) == 4) {
333 for (i = 0; i < 12; i++)
334 if (!av_strcasecmp(month, months[i])) {
335 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
336 year, i + 1, day, time);
337 av_dict_set(metadata, "creation_time", buffer, 0);
339 } else if (date[4] == '/' && date[7] == '/') {
340 date[4] = date[7] = '-';
341 av_dict_set(metadata, "creation_time", date, 0);
345 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
347 while (avio_tell(s->pb) < end) {
348 uint32_t tag = avio_rl32(s->pb);
349 uint32_t size = avio_rl32(s->pb);
351 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
353 uint64_t tag_end = avio_tell(s->pb) + size;
354 while (avio_tell(s->pb) < tag_end) {
355 uint16_t tag = avio_rl16(s->pb);
356 uint16_t size = avio_rl16(s->pb);
357 const char *name = NULL;
358 char buffer[64] = { 0 };
359 size = FFMIN(size, tag_end - avio_tell(s->pb));
360 size -= avio_read(s->pb, buffer,
361 FFMIN(size, sizeof(buffer) - 1));
370 name = "creation_time";
371 if (buffer[4] == ':' && buffer[7] == ':')
372 buffer[4] = buffer[7] = '-';
376 av_dict_set(&s->metadata, name, buffer, 0);
377 avio_skip(s->pb, size);
382 avio_skip(s->pb, size);
388 static int avi_extract_stream_metadata(AVStream *st)
391 uint8_t *data = st->codec->extradata;
392 int data_size = st->codec->extradata_size;
395 if (!data || data_size < 8) {
396 return AVERROR_INVALIDDATA;
399 bytestream2_init(&gb, data, data_size);
401 tag = bytestream2_get_le32(&gb);
404 case MKTAG('A', 'V', 'I', 'F'):
405 // skip 4 byte padding
406 bytestream2_skip(&gb, 4);
407 offset = bytestream2_tell(&gb);
408 bytestream2_init(&gb, data + offset, data_size - offset);
410 // decode EXIF tags from IFD, AVI is always little-endian
411 return avpriv_exif_decode_ifd(st->codec, &gb, 1, 0, &st->metadata);
413 case MKTAG('C', 'A', 'S', 'I'):
414 avpriv_request_sample(st->codec, "RIFF stream data tag type CASI (%u)", tag);
416 case MKTAG('Z', 'o', 'r', 'a'):
417 avpriv_request_sample(st->codec, "RIFF stream data tag type Zora (%u)", tag);
426 static int calculate_bitrate(AVFormatContext *s)
428 AVIContext *avi = s->priv_data;
433 for (i = 0; i<s->nb_streams; i++) {
435 AVStream *st = s->streams[i];
437 if (!st->nb_index_entries)
440 for (j = 0; j < st->nb_index_entries; j++)
441 len += st->index_entries[j].size;
442 maxpos = FFMAX(maxpos, st->index_entries[j-1].pos);
445 if (maxpos < avi->io_fsize*9/10) // index does not cover the whole file
447 if (lensum*9/10 > maxpos || lensum < maxpos*9/10) // frame sum and filesize mismatch
450 for (i = 0; i<s->nb_streams; i++) {
452 AVStream *st = s->streams[i];
456 for (j = 0; j < st->nb_index_entries; j++)
457 len += st->index_entries[j].size;
459 if (st->nb_index_entries < 2 || st->codec->bit_rate > 0)
461 duration = st->index_entries[j-1].timestamp - st->index_entries[0].timestamp;
462 bitrate = av_rescale(8*len, st->time_base.den, duration * st->time_base.num);
463 if (bitrate <= INT_MAX && bitrate > 0) {
464 st->codec->bit_rate = bitrate;
470 static int avi_read_header(AVFormatContext *s)
472 AVIContext *avi = s->priv_data;
473 AVIOContext *pb = s->pb;
474 unsigned int tag, tag1, handler;
475 int codec_type, stream_index, frame_period;
479 AVIStream *ast = NULL;
480 int avih_width = 0, avih_height = 0;
481 int amv_file_format = 0;
482 uint64_t list_end = 0;
484 AVDictionaryEntry *dict_entry;
486 avi->stream_index = -1;
488 ret = get_riff(s, pb);
492 av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
494 avi->io_fsize = avi->fsize = avio_size(pb);
495 if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
496 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
506 size = avio_rl32(pb);
508 print_tag("tag", tag, size);
511 case MKTAG('L', 'I', 'S', 'T'):
512 list_end = avio_tell(pb) + size;
513 /* Ignored, except at start of video packets. */
514 tag1 = avio_rl32(pb);
516 print_tag("list", tag1, 0);
518 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
519 avi->movi_list = avio_tell(pb) - 4;
521 avi->movi_end = avi->movi_list + size + (size & 1);
523 avi->movi_end = avi->fsize;
524 av_log(NULL, AV_LOG_TRACE, "movi end=%"PRIx64"\n", avi->movi_end);
526 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
527 ff_read_riff_info(s, size - 4);
528 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
529 avi_read_nikon(s, list_end);
532 case MKTAG('I', 'D', 'I', 'T'):
534 unsigned char date[64] = { 0 };
536 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
538 avi_metadata_creation_time(&s->metadata, date);
541 case MKTAG('d', 'm', 'l', 'h'):
543 avio_skip(pb, size + (size & 1));
545 case MKTAG('a', 'm', 'v', 'h'):
547 case MKTAG('a', 'v', 'i', 'h'):
549 /* using frame_period is bad idea */
550 frame_period = avio_rl32(pb);
551 avio_rl32(pb); /* max. bytes per second */
553 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
555 avio_skip(pb, 2 * 4);
558 avih_width = avio_rl32(pb);
559 avih_height = avio_rl32(pb);
561 avio_skip(pb, size - 10 * 4);
563 case MKTAG('s', 't', 'r', 'h'):
566 tag1 = avio_rl32(pb);
567 handler = avio_rl32(pb); /* codec tag */
569 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
570 avio_skip(pb, size - 8);
574 st = avformat_new_stream(s, NULL);
578 st->id = stream_index;
579 ast = av_mallocz(sizeof(AVIStream));
585 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
586 : MKTAG('v', 'i', 'd', 's');
588 print_tag("strh", tag1, -1);
590 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
591 tag1 == MKTAG('i', 'v', 'a', 's')) {
594 /* After some consideration -- I don't think we
595 * have to support anything but DV in type1 AVIs. */
596 if (s->nb_streams != 1)
599 if (handler != MKTAG('d', 'v', 's', 'd') &&
600 handler != MKTAG('d', 'v', 'h', 'd') &&
601 handler != MKTAG('d', 'v', 's', 'l'))
604 ast = s->streams[0]->priv_data;
605 av_freep(&s->streams[0]->codec->extradata);
606 av_freep(&s->streams[0]->codec);
607 if (s->streams[0]->info)
608 av_freep(&s->streams[0]->info->duration_error);
609 av_freep(&s->streams[0]->info);
610 av_freep(&s->streams[0]);
612 if (CONFIG_DV_DEMUXER) {
613 avi->dv_demux = avpriv_dv_init_demux(s);
618 s->streams[0]->priv_data = ast;
619 avio_skip(pb, 3 * 4);
620 ast->scale = avio_rl32(pb);
621 ast->rate = avio_rl32(pb);
622 avio_skip(pb, 4); /* start time */
624 dv_dur = avio_rl32(pb);
625 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
626 dv_dur *= AV_TIME_BASE;
627 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
629 /* else, leave duration alone; timing estimation in utils.c
630 * will make a guess based on bitrate. */
632 stream_index = s->nb_streams - 1;
633 avio_skip(pb, size - 9 * 4);
637 av_assert0(stream_index < s->nb_streams);
638 ast->handler = handler;
640 avio_rl32(pb); /* flags */
641 avio_rl16(pb); /* priority */
642 avio_rl16(pb); /* language */
643 avio_rl32(pb); /* initial frame */
644 ast->scale = avio_rl32(pb);
645 ast->rate = avio_rl32(pb);
646 if (!(ast->scale && ast->rate)) {
647 av_log(s, AV_LOG_WARNING,
648 "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
649 "(This file has been generated by broken software.)\n",
654 ast->scale = frame_period;
660 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
662 ast->cum_len = avio_rl32(pb); /* start */
663 st->nb_frames = avio_rl32(pb);
666 avio_rl32(pb); /* buffer size */
667 avio_rl32(pb); /* quality */
668 if (ast->cum_len*ast->scale/ast->rate > 3600) {
669 av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
672 ast->sample_size = avio_rl32(pb); /* sample ssize */
673 ast->cum_len *= FFMAX(1, ast->sample_size);
674 av_log(s, AV_LOG_TRACE, "%"PRIu32" %"PRIu32" %d\n",
675 ast->rate, ast->scale, ast->sample_size);
678 case MKTAG('v', 'i', 'd', 's'):
679 codec_type = AVMEDIA_TYPE_VIDEO;
681 ast->sample_size = 0;
682 st->avg_frame_rate = av_inv_q(st->time_base);
684 case MKTAG('a', 'u', 'd', 's'):
685 codec_type = AVMEDIA_TYPE_AUDIO;
687 case MKTAG('t', 'x', 't', 's'):
688 codec_type = AVMEDIA_TYPE_SUBTITLE;
690 case MKTAG('d', 'a', 't', 's'):
691 codec_type = AVMEDIA_TYPE_DATA;
694 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
697 if (ast->sample_size < 0) {
698 if (s->error_recognition & AV_EF_EXPLODE) {
699 av_log(s, AV_LOG_ERROR,
700 "Invalid sample_size %d at stream %d\n",
705 av_log(s, AV_LOG_WARNING,
706 "Invalid sample_size %d at stream %d "
710 ast->sample_size = 0;
713 if (ast->sample_size == 0) {
714 st->duration = st->nb_frames;
715 if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) {
716 av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n");
717 st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end);
720 ast->frame_offset = ast->cum_len;
721 avio_skip(pb, size - 12 * 4);
723 case MKTAG('s', 't', 'r', 'f'):
727 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
730 uint64_t cur_pos = avio_tell(pb);
732 if (cur_pos < list_end)
733 size = FFMIN(size, list_end - cur_pos);
734 st = s->streams[stream_index];
735 if (st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN) {
739 switch (codec_type) {
740 case AVMEDIA_TYPE_VIDEO:
741 if (amv_file_format) {
742 st->codec->width = avih_width;
743 st->codec->height = avih_height;
744 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
745 st->codec->codec_id = AV_CODEC_ID_AMV;
749 tag1 = ff_get_bmp_header(pb, st, &esize);
751 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
752 tag1 == MKTAG('D', 'X', 'S', 'A')) {
753 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
754 st->codec->codec_tag = tag1;
755 st->codec->codec_id = AV_CODEC_ID_XSUB;
759 if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) {
760 if (esize == size-1 && (esize&1)) {
761 st->codec->extradata_size = esize - 10 * 4;
763 st->codec->extradata_size = size - 10 * 4;
764 if (ff_get_extradata(st->codec, pb, st->codec->extradata_size) < 0)
765 return AVERROR(ENOMEM);
768 // FIXME: check if the encoder really did this correctly
769 if (st->codec->extradata_size & 1)
772 /* Extract palette from extradata if bpp <= 8.
773 * This code assumes that extradata contains only palette.
774 * This is true for all paletted codecs implemented in
776 if (st->codec->extradata_size &&
777 (st->codec->bits_per_coded_sample <= 8)) {
778 int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
779 const uint8_t *pal_src;
781 pal_size = FFMIN(pal_size, st->codec->extradata_size);
782 pal_src = st->codec->extradata +
783 st->codec->extradata_size - pal_size;
784 /* Exclude the "BottomUp" field from the palette */
785 if (pal_src - st->codec->extradata >= 9 &&
786 !memcmp(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9))
788 for (i = 0; i < pal_size / 4; i++)
789 ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i);
793 print_tag("video", tag1, 0);
795 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
796 st->codec->codec_tag = tag1;
797 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
799 /* If codec is not found yet, try with the mov tags. */
800 if (!st->codec->codec_id) {
802 av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag1);
803 st->codec->codec_id =
804 ff_codec_get_id(ff_codec_movvideo_tags, tag1);
805 if (st->codec->codec_id)
806 av_log(s, AV_LOG_WARNING,
807 "mov tag found in avi (fourcc %s)\n",
810 /* This is needed to get the pict type which is necessary
811 * for generating correct pts. */
812 st->need_parsing = AVSTREAM_PARSE_HEADERS;
814 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
815 ast->handler == MKTAG('X', 'V', 'I', 'D'))
816 st->codec->codec_tag = MKTAG('X', 'V', 'I', 'D');
818 if (st->codec->codec_tag == MKTAG('V', 'S', 'S', 'H'))
819 st->need_parsing = AVSTREAM_PARSE_FULL;
821 if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
822 st->codec->extradata_size < 1U << 30) {
823 st->codec->extradata_size += 9;
824 if ((ret = av_reallocp(&st->codec->extradata,
825 st->codec->extradata_size +
826 FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
827 st->codec->extradata_size = 0;
830 memcpy(st->codec->extradata + st->codec->extradata_size - 9,
833 st->codec->height = FFABS(st->codec->height);
835 // avio_skip(pb, size - 5 * 4);
837 case AVMEDIA_TYPE_AUDIO:
838 ret = ff_get_wav_header(s, pb, st->codec, size, 0);
841 ast->dshow_block_align = st->codec->block_align;
842 if (ast->sample_size && st->codec->block_align &&
843 ast->sample_size != st->codec->block_align) {
846 "sample size (%d) != block align (%d)\n",
848 st->codec->block_align);
849 ast->sample_size = st->codec->block_align;
852 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
855 /* Force parsing as several audio frames can be in
856 * one packet and timestamps refer to packet start. */
857 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
858 /* ADTS header is in extradata, AAC without header must be
859 * stored as exact frames. Parser not needed and it will
861 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
862 st->codec->extradata_size)
863 st->need_parsing = AVSTREAM_PARSE_NONE;
864 /* AVI files with Xan DPCM audio (wrongly) declare PCM
865 * audio in the header but have Axan as stream_code_tag. */
866 if (ast->handler == AV_RL32("Axan")) {
867 st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
868 st->codec->codec_tag = 0;
869 ast->dshow_block_align = 0;
871 if (amv_file_format) {
872 st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
873 ast->dshow_block_align = 0;
875 if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align <= 4 && ast->dshow_block_align ||
876 st->codec->codec_id == AV_CODEC_ID_MP2 && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
877 av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
878 ast->dshow_block_align = 0;
880 if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
881 st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
882 st->codec->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
883 av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
884 ast->sample_size = 0;
887 case AVMEDIA_TYPE_SUBTITLE:
888 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
889 st->request_probe= 1;
893 st->codec->codec_type = AVMEDIA_TYPE_DATA;
894 st->codec->codec_id = AV_CODEC_ID_NONE;
895 st->codec->codec_tag = 0;
901 case MKTAG('s', 't', 'r', 'd'):
902 if (stream_index >= (unsigned)s->nb_streams
903 || s->streams[stream_index]->codec->extradata_size
904 || s->streams[stream_index]->codec->codec_tag == MKTAG('H','2','6','4')) {
907 uint64_t cur_pos = avio_tell(pb);
908 if (cur_pos < list_end)
909 size = FFMIN(size, list_end - cur_pos);
910 st = s->streams[stream_index];
913 if (ff_get_extradata(st->codec, pb, size) < 0)
914 return AVERROR(ENOMEM);
917 if (st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
920 ret = avi_extract_stream_metadata(st);
922 av_log(s, AV_LOG_WARNING, "could not decoding EXIF data in stream header.\n");
926 case MKTAG('i', 'n', 'd', 'x'):
928 if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
930 read_braindead_odml_indx(s, 0) < 0 &&
931 (s->error_recognition & AV_EF_EXPLODE))
933 avio_seek(pb, i + size, SEEK_SET);
935 case MKTAG('v', 'p', 'r', 'p'):
936 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
937 AVRational active, active_aspect;
939 st = s->streams[stream_index];
946 active_aspect.den = avio_rl16(pb);
947 active_aspect.num = avio_rl16(pb);
948 active.num = avio_rl32(pb);
949 active.den = avio_rl32(pb);
950 avio_rl32(pb); // nbFieldsPerFrame
952 if (active_aspect.num && active_aspect.den &&
953 active.num && active.den) {
954 st->sample_aspect_ratio = av_div_q(active_aspect, active);
955 av_log(s, AV_LOG_TRACE, "vprp %d/%d %d/%d\n",
956 active_aspect.num, active_aspect.den,
957 active.num, active.den);
963 case MKTAG('s', 't', 'r', 'n'):
965 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
971 if (size > 1000000) {
972 av_log(s, AV_LOG_ERROR,
973 "Something went wrong during header parsing, "
974 "I will ignore it and try to continue anyway.\n");
975 if (s->error_recognition & AV_EF_EXPLODE)
977 avi->movi_list = avio_tell(pb) - 4;
978 avi->movi_end = avi->fsize;
989 /* check stream number */
990 if (stream_index != s->nb_streams - 1) {
993 return AVERROR_INVALIDDATA;
996 if (!avi->index_loaded && pb->seekable)
998 calculate_bitrate(s);
999 avi->index_loaded |= 1;
1001 if ((ret = guess_ni_flag(s)) < 0)
1004 avi->non_interleaved |= ret | (s->flags & AVFMT_FLAG_SORT_DTS);
1006 dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0);
1007 if (dict_entry && !strcmp(dict_entry->value, "PotEncoder"))
1008 for (i = 0; i < s->nb_streams; i++) {
1009 AVStream *st = s->streams[i];
1010 if ( st->codec->codec_id == AV_CODEC_ID_MPEG1VIDEO
1011 || st->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1012 st->need_parsing = AVSTREAM_PARSE_FULL;
1015 for (i = 0; i < s->nb_streams; i++) {
1016 AVStream *st = s->streams[i];
1017 if (st->nb_index_entries)
1020 // DV-in-AVI cannot be non-interleaved, if set this must be
1023 avi->non_interleaved = 0;
1024 if (i == s->nb_streams && avi->non_interleaved) {
1025 av_log(s, AV_LOG_WARNING,
1026 "Non-interleaved AVI without index, switching to interleaved\n");
1027 avi->non_interleaved = 0;
1030 if (avi->non_interleaved) {
1031 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
1035 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
1036 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
1041 static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1043 if (pkt->size >= 7 &&
1044 pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
1045 !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
1047 int score = AVPROBE_SCORE_EXTENSION, ret;
1048 AVIStream *ast = st->priv_data;
1049 AVInputFormat *sub_demuxer;
1050 AVRational time_base;
1052 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
1054 0, NULL, NULL, NULL, NULL);
1056 unsigned int desc_len = avio_rl32(pb);
1058 if (desc_len > pb->buf_end - pb->buf_ptr)
1061 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
1062 avio_skip(pb, desc_len - ret);
1064 av_dict_set(&st->metadata, "title", desc, 0);
1066 avio_rl16(pb); /* flags? */
1067 avio_rl32(pb); /* data size */
1069 size = pb->buf_end - pb->buf_ptr;
1070 pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
1074 memcpy(pd.buf, pb->buf_ptr, size);
1075 sub_demuxer = av_probe_input_format2(&pd, 1, &score);
1080 if (!(ast->sub_ctx = avformat_alloc_context()))
1083 ast->sub_ctx->pb = pb;
1085 if (ff_copy_whitelists(ast->sub_ctx, s) < 0)
1088 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
1089 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
1090 *st->codec = *ast->sub_ctx->streams[0]->codec;
1091 ast->sub_ctx->streams[0]->codec->extradata = NULL;
1092 time_base = ast->sub_ctx->streams[0]->time_base;
1093 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
1095 ast->sub_buffer = pkt->data;
1096 memset(pkt, 0, sizeof(*pkt));
1100 av_freep(&ast->sub_ctx);
1106 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
1109 AVIStream *ast, *next_ast = next_st->priv_data;
1110 int64_t ts, next_ts, ts_min = INT64_MAX;
1111 AVStream *st, *sub_st = NULL;
1114 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
1117 for (i = 0; i < s->nb_streams; i++) {
1119 ast = st->priv_data;
1120 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
1121 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
1122 if (ts <= next_ts && ts < ts_min) {
1130 ast = sub_st->priv_data;
1131 *pkt = ast->sub_pkt;
1132 pkt->stream_index = sub_st->index;
1134 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
1135 ast->sub_pkt.data = NULL;
1140 static int get_stream_idx(const unsigned *d)
1142 if (d[0] >= '0' && d[0] <= '9' &&
1143 d[1] >= '0' && d[1] <= '9') {
1144 return (d[0] - '0') * 10 + (d[1] - '0');
1146 return 100; // invalid stream ID
1152 * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
1154 static int avi_sync(AVFormatContext *s, int exit_early)
1156 AVIContext *avi = s->priv_data;
1157 AVIOContext *pb = s->pb;
1164 memset(d, -1, sizeof(d));
1165 for (i = sync = avio_tell(pb); !avio_feof(pb); i++) {
1168 for (j = 0; j < 7; j++)
1172 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
1174 n = get_stream_idx(d + 2);
1175 ff_tlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
1176 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
1177 if (i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127)
1181 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
1183 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
1184 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
1185 avio_skip(pb, size);
1190 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
1195 n = get_stream_idx(d);
1197 if (!((i - avi->last_pkt_pos) & 1) &&
1198 get_stream_idx(d + 1) < s->nb_streams)
1201 // detect ##ix chunk and skip
1202 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
1203 avio_skip(pb, size);
1207 if (avi->dv_demux && n != 0)
1211 if (n < s->nb_streams) {
1215 ast = st->priv_data;
1218 av_log(s, AV_LOG_WARNING, "Skipping foreign stream %d packet\n", n);
1222 if (s->nb_streams >= 2) {
1223 AVStream *st1 = s->streams[1];
1224 AVIStream *ast1 = st1->priv_data;
1225 // workaround for broken small-file-bug402.avi
1226 if ( d[2] == 'w' && d[3] == 'b'
1228 && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
1229 && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
1230 && ast->prefix == 'd'*256+'c'
1231 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
1236 av_log(s, AV_LOG_WARNING,
1237 "Invalid stream + prefix combination, assuming audio.\n");
1241 if (!avi->dv_demux &&
1242 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
1243 // FIXME: needs a little reordering
1244 (st->discard >= AVDISCARD_NONKEY &&
1245 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1246 || st->discard >= AVDISCARD_ALL)) {
1248 ast->frame_offset += get_duration(ast, size);
1249 avio_skip(pb, size);
1254 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1255 int k = avio_r8(pb);
1256 int last = (k + avio_r8(pb) - 1) & 0xFF;
1258 avio_rl16(pb); // flags
1260 // b + (g << 8) + (r << 16);
1261 for (; k <= last; k++)
1262 ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;
1266 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1267 d[2] < 128 && d[3] < 128) ||
1268 d[2] * 256 + d[3] == ast->prefix /* ||
1269 (d[2] == 'd' && d[3] == 'c') ||
1270 (d[2] == 'w' && d[3] == 'b') */) {
1273 if (d[2] * 256 + d[3] == ast->prefix)
1274 ast->prefix_count++;
1276 ast->prefix = d[2] * 256 + d[3];
1277 ast->prefix_count = 0;
1280 avi->stream_index = n;
1281 ast->packet_size = size + 8;
1282 ast->remaining = size;
1285 uint64_t pos = avio_tell(pb) - 8;
1286 if (!st->index_entries || !st->nb_index_entries ||
1287 st->index_entries[st->nb_index_entries - 1].pos < pos) {
1288 av_add_index_entry(st, pos, ast->frame_offset, size,
1289 0, AVINDEX_KEYFRAME);
1302 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1304 AVIContext *avi = s->priv_data;
1305 AVIOContext *pb = s->pb;
1307 #if FF_API_DESTRUCT_PACKET
1311 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1312 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1319 if (avi->non_interleaved) {
1320 int best_stream_index = 0;
1321 AVStream *best_st = NULL;
1322 AVIStream *best_ast;
1323 int64_t best_ts = INT64_MAX;
1326 for (i = 0; i < s->nb_streams; i++) {
1327 AVStream *st = s->streams[i];
1328 AVIStream *ast = st->priv_data;
1329 int64_t ts = ast->frame_offset;
1332 if (!st->nb_index_entries)
1335 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1336 if (!ast->remaining && ts > last_ts)
1339 ts = av_rescale_q(ts, st->time_base,
1340 (AVRational) { FFMAX(1, ast->sample_size),
1343 av_log(s, AV_LOG_TRACE, "%"PRId64" %d/%d %"PRId64"\n", ts,
1344 st->time_base.num, st->time_base.den, ast->frame_offset);
1348 best_stream_index = i;
1354 best_ast = best_st->priv_data;
1355 best_ts = best_ast->frame_offset;
1356 if (best_ast->remaining) {
1357 i = av_index_search_timestamp(best_st,
1360 AVSEEK_FLAG_BACKWARD);
1362 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1364 best_ast->frame_offset = best_st->index_entries[i].timestamp;
1368 int64_t pos = best_st->index_entries[i].pos;
1369 pos += best_ast->packet_size - best_ast->remaining;
1370 if (avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
1373 av_assert0(best_ast->remaining <= best_ast->packet_size);
1375 avi->stream_index = best_stream_index;
1376 if (!best_ast->remaining)
1377 best_ast->packet_size =
1378 best_ast->remaining = best_st->index_entries[i].size;
1385 if (avi->stream_index >= 0) {
1386 AVStream *st = s->streams[avi->stream_index];
1387 AVIStream *ast = st->priv_data;
1390 if (get_subtitle_pkt(s, st, pkt))
1393 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1394 if (ast->sample_size <= 1)
1396 else if (ast->sample_size < 32)
1397 // arbitrary multiplier to avoid tiny packets for raw PCM data
1398 size = 1024 * ast->sample_size;
1400 size = ast->sample_size;
1402 if (size > ast->remaining)
1403 size = ast->remaining;
1404 avi->last_pkt_pos = avio_tell(pb);
1405 err = av_get_packet(pb, pkt, size);
1410 if (ast->has_pal && pkt->size < (unsigned)INT_MAX / 2) {
1412 pal = av_packet_new_side_data(pkt,
1413 AV_PKT_DATA_PALETTE,
1416 av_log(s, AV_LOG_ERROR,
1417 "Failed to allocate data for palette\n");
1419 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1424 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1425 AVBufferRef *avbuf = pkt->buf;
1426 #if FF_API_DESTRUCT_PACKET
1427 FF_DISABLE_DEPRECATION_WARNINGS
1428 dstr = pkt->destruct;
1429 FF_ENABLE_DEPRECATION_WARNINGS
1431 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1432 pkt->data, pkt->size, pkt->pos);
1433 #if FF_API_DESTRUCT_PACKET
1434 FF_DISABLE_DEPRECATION_WARNINGS
1435 pkt->destruct = dstr;
1436 FF_ENABLE_DEPRECATION_WARNINGS
1439 pkt->flags |= AV_PKT_FLAG_KEY;
1441 av_free_packet(pkt);
1442 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1443 !st->codec->codec_tag && read_gab2_sub(s, st, pkt)) {
1444 ast->frame_offset++;
1445 avi->stream_index = -1;
1449 /* XXX: How to handle B-frames in AVI? */
1450 pkt->dts = ast->frame_offset;
1451 // pkt->dts += ast->start;
1452 if (ast->sample_size)
1453 pkt->dts /= ast->sample_size;
1454 av_log(s, AV_LOG_TRACE,
1455 "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
1456 "base:%d st:%d size:%d\n",
1465 pkt->stream_index = avi->stream_index;
1467 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->index_entries) {
1471 index = av_index_search_timestamp(st, ast->frame_offset, AVSEEK_FLAG_ANY);
1472 e = &st->index_entries[index];
1474 if (index >= 0 && e->timestamp == ast->frame_offset) {
1475 if (index == st->nb_index_entries-1) {
1478 if (st->codec->codec_id == AV_CODEC_ID_MPEG4) {
1479 const uint8_t *ptr = pkt->data, *end = ptr + FFMIN(size, 256);
1481 ptr = avpriv_find_start_code(ptr, end, &state);
1482 if (state == 0x1B6 && ptr < end) {
1483 key = !(*ptr & 0xC0);
1489 e->flags &= ~AVINDEX_KEYFRAME;
1491 if (e->flags & AVINDEX_KEYFRAME)
1492 pkt->flags |= AV_PKT_FLAG_KEY;
1495 pkt->flags |= AV_PKT_FLAG_KEY;
1497 ast->frame_offset += get_duration(ast, pkt->size);
1499 ast->remaining -= err;
1500 if (!ast->remaining) {
1501 avi->stream_index = -1;
1502 ast->packet_size = 0;
1505 if (!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos) {
1506 av_free_packet(pkt);
1511 if (!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1) {
1512 int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
1514 if (avi->dts_max - dts > 2*AV_TIME_BASE) {
1515 avi->non_interleaved= 1;
1516 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
1517 }else if (avi->dts_max < dts)
1524 if ((err = avi_sync(s, 0)) < 0)
1529 /* XXX: We make the implicit supposition that the positions are sorted
1530 * for each stream. */
1531 static int avi_read_idx1(AVFormatContext *s, int size)
1533 AVIContext *avi = s->priv_data;
1534 AVIOContext *pb = s->pb;
1535 int nb_index_entries, i;
1538 unsigned int index, tag, flags, pos, len, first_packet = 1;
1539 unsigned last_pos = -1;
1540 unsigned last_idx = -1;
1541 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1544 nb_index_entries = size / 16;
1545 if (nb_index_entries <= 0)
1546 return AVERROR_INVALIDDATA;
1548 idx1_pos = avio_tell(pb);
1549 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1550 if (avi_sync(s, 1) == 0)
1551 first_packet_pos = avio_tell(pb) - 8;
1552 avi->stream_index = -1;
1553 avio_seek(pb, idx1_pos, SEEK_SET);
1555 if (s->nb_streams == 1 && s->streams[0]->codec->codec_tag == AV_RL32("MMES")) {
1556 first_packet_pos = 0;
1557 data_offset = avi->movi_list;
1560 /* Read the entries and sort them in each stream component. */
1561 for (i = 0; i < nb_index_entries; i++) {
1565 tag = avio_rl32(pb);
1566 flags = avio_rl32(pb);
1567 pos = avio_rl32(pb);
1568 len = avio_rl32(pb);
1569 av_log(s, AV_LOG_TRACE, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1570 i, tag, flags, pos, len);
1572 index = ((tag & 0xff) - '0') * 10;
1573 index += (tag >> 8 & 0xff) - '0';
1574 if (index >= s->nb_streams)
1576 st = s->streams[index];
1577 ast = st->priv_data;
1579 if (first_packet && first_packet_pos) {
1580 data_offset = first_packet_pos - pos;
1585 av_log(s, AV_LOG_TRACE, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1587 // even if we have only a single stream, we should
1588 // switch to non-interleaved to get correct timestamps
1589 if (last_pos == pos)
1590 avi->non_interleaved = 1;
1591 if (last_idx != pos && len) {
1592 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1593 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1596 ast->cum_len += get_duration(ast, len);
1598 anykey |= flags&AVIIF_INDEX;
1601 for (index = 0; index < s->nb_streams; index++) {
1602 st = s->streams[index];
1603 if (st->nb_index_entries)
1604 st->index_entries[0].flags |= AVINDEX_KEYFRAME;
1610 /* Scan the index and consider any file with streams more than
1611 * 2 seconds or 64MB apart non-interleaved. */
1612 static int check_stream_max_drift(AVFormatContext *s)
1614 int64_t min_pos, pos;
1616 int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
1618 return AVERROR(ENOMEM);
1619 for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
1620 int64_t max_dts = INT64_MIN / 2;
1621 int64_t min_dts = INT64_MAX / 2;
1622 int64_t max_buffer = 0;
1624 min_pos = INT64_MAX;
1626 for (i = 0; i < s->nb_streams; i++) {
1627 AVStream *st = s->streams[i];
1628 AVIStream *ast = st->priv_data;
1629 int n = st->nb_index_entries;
1630 while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
1634 dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
1635 FFMAX(ast->sample_size, 1),
1636 st->time_base, AV_TIME_BASE_Q);
1637 min_dts = FFMIN(min_dts, dts);
1638 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
1641 for (i = 0; i < s->nb_streams; i++) {
1642 AVStream *st = s->streams[i];
1643 AVIStream *ast = st->priv_data;
1645 if (idx[i] && min_dts != INT64_MAX / 2) {
1647 dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
1648 FFMAX(ast->sample_size, 1),
1649 st->time_base, AV_TIME_BASE_Q);
1650 max_dts = FFMAX(max_dts, dts);
1651 max_buffer = FFMAX(max_buffer,
1652 av_rescale(dts - min_dts,
1653 st->codec->bit_rate,
1657 if (max_dts - min_dts > 2 * AV_TIME_BASE ||
1658 max_buffer > 1024 * 1024 * 8 * 8) {
1667 static int guess_ni_flag(AVFormatContext *s)
1670 int64_t last_start = 0;
1671 int64_t first_end = INT64_MAX;
1672 int64_t oldpos = avio_tell(s->pb);
1674 for (i = 0; i < s->nb_streams; i++) {
1675 AVStream *st = s->streams[i];
1676 int n = st->nb_index_entries;
1683 int64_t pos = st->index_entries[0].pos;
1684 avio_seek(s->pb, pos + 4, SEEK_SET);
1685 size = avio_rl32(s->pb);
1686 if (pos + size > st->index_entries[1].pos)
1687 last_start = INT64_MAX;
1690 if (st->index_entries[0].pos > last_start)
1691 last_start = st->index_entries[0].pos;
1692 if (st->index_entries[n - 1].pos < first_end)
1693 first_end = st->index_entries[n - 1].pos;
1695 avio_seek(s->pb, oldpos, SEEK_SET);
1697 if (last_start > first_end)
1700 return check_stream_max_drift(s);
1703 static int avi_load_index(AVFormatContext *s)
1705 AVIContext *avi = s->priv_data;
1706 AVIOContext *pb = s->pb;
1708 int64_t pos = avio_tell(pb);
1712 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1713 goto the_end; // maybe truncated file
1714 av_log(s, AV_LOG_TRACE, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1716 tag = avio_rl32(pb);
1717 size = avio_rl32(pb);
1720 next = avio_tell(pb) + size + (size & 1);
1722 av_log(s, AV_LOG_TRACE, "tag=%c%c%c%c size=0x%x\n",
1729 if (tag == MKTAG('i', 'd', 'x', '1') &&
1730 avi_read_idx1(s, size) >= 0) {
1731 avi->index_loaded=2;
1733 }else if (tag == MKTAG('L', 'I', 'S', 'T')) {
1734 uint32_t tag1 = avio_rl32(pb);
1736 if (tag1 == MKTAG('I', 'N', 'F', 'O'))
1737 ff_read_riff_info(s, size - 4);
1741 if (avio_seek(pb, next, SEEK_SET) < 0)
1742 break; // something is wrong here
1746 avio_seek(pb, pos, SEEK_SET);
1750 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1752 AVIStream *ast2 = st2->priv_data;
1753 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1754 av_free_packet(&ast2->sub_pkt);
1755 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1756 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1757 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1760 static int avi_read_seek(AVFormatContext *s, int stream_index,
1761 int64_t timestamp, int flags)
1763 AVIContext *avi = s->priv_data;
1766 int64_t pos, pos_min;
1769 /* Does not matter which stream is requested dv in avi has the
1770 * stream information in the first video stream.
1775 if (!avi->index_loaded) {
1776 /* we only load the index on demand */
1778 avi->index_loaded |= 1;
1780 av_assert0(stream_index >= 0);
1782 st = s->streams[stream_index];
1783 ast = st->priv_data;
1784 index = av_index_search_timestamp(st,
1785 timestamp * FFMAX(ast->sample_size, 1),
1788 if (st->nb_index_entries > 0)
1789 av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
1790 timestamp * FFMAX(ast->sample_size, 1),
1791 st->index_entries[0].timestamp,
1792 st->index_entries[st->nb_index_entries - 1].timestamp);
1793 return AVERROR_INVALIDDATA;
1796 /* find the position */
1797 pos = st->index_entries[index].pos;
1798 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1800 av_log(s, AV_LOG_TRACE, "XX %"PRId64" %d %"PRId64"\n",
1801 timestamp, index, st->index_entries[index].timestamp);
1803 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1804 /* One and only one real stream for DV in AVI, and it has video */
1805 /* offsets. Calling with other stream indexes should have failed */
1806 /* the av_index_search_timestamp call above. */
1808 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
1811 /* Feed the DV video stream version of the timestamp to the */
1812 /* DV demux so it can synthesize correct timestamps. */
1813 ff_dv_offset_reset(avi->dv_demux, timestamp);
1815 avi->stream_index = -1;
1820 for (i = 0; i < s->nb_streams; i++) {
1821 AVStream *st2 = s->streams[i];
1822 AVIStream *ast2 = st2->priv_data;
1825 ast2->remaining = 0;
1827 if (ast2->sub_ctx) {
1828 seek_subtitle(st, st2, timestamp);
1832 if (st2->nb_index_entries <= 0)
1835 // av_assert1(st2->codec->block_align);
1836 av_assert0(fabs(av_q2d(st2->time_base) - ast2->scale / (double)ast2->rate) < av_q2d(st2->time_base) * 0.00000001);
1837 index = av_index_search_timestamp(st2,
1838 av_rescale_q(timestamp,
1841 FFMAX(ast2->sample_size, 1),
1843 AVSEEK_FLAG_BACKWARD |
1844 (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1847 ast2->seek_pos = st2->index_entries[index].pos;
1848 pos_min = FFMIN(pos_min,ast2->seek_pos);
1850 for (i = 0; i < s->nb_streams; i++) {
1851 AVStream *st2 = s->streams[i];
1852 AVIStream *ast2 = st2->priv_data;
1854 if (ast2->sub_ctx || st2->nb_index_entries <= 0)
1857 index = av_index_search_timestamp(
1859 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1860 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1863 while (!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
1865 ast2->frame_offset = st2->index_entries[index].timestamp;
1869 if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
1870 av_log(s, AV_LOG_ERROR, "Seek failed\n");
1873 avi->stream_index = -1;
1874 avi->dts_max = INT_MIN;
1878 static int avi_read_close(AVFormatContext *s)
1881 AVIContext *avi = s->priv_data;
1883 for (i = 0; i < s->nb_streams; i++) {
1884 AVStream *st = s->streams[i];
1885 AVIStream *ast = st->priv_data;
1888 av_freep(&ast->sub_ctx->pb);
1889 avformat_close_input(&ast->sub_ctx);
1891 av_freep(&ast->sub_buffer);
1892 av_free_packet(&ast->sub_pkt);
1896 av_freep(&avi->dv_demux);
1901 static int avi_probe(AVProbeData *p)
1905 /* check file header */
1906 for (i = 0; avi_headers[i][0]; i++)
1907 if (AV_RL32(p->buf ) == AV_RL32(avi_headers[i] ) &&
1908 AV_RL32(p->buf + 8) == AV_RL32(avi_headers[i] + 4))
1909 return AVPROBE_SCORE_MAX;
1914 AVInputFormat ff_avi_demuxer = {
1916 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1917 .priv_data_size = sizeof(AVIContext),
1918 .extensions = "avi",
1919 .read_probe = avi_probe,
1920 .read_header = avi_read_header,
1921 .read_packet = avi_read_packet,
1922 .read_close = avi_read_close,
1923 .read_seek = avi_read_seek,
1924 .priv_class = &demuxer_class,