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"
37 #include "libavcodec/bytestream.h"
38 #include "libavcodec/exif.h"
40 typedef struct AVIStream {
41 int64_t frame_offset; /* current frame (video) or byte (audio) counter
42 * (used to compute the pts) */
48 int sample_size; /* size of one sample (or packet)
49 * (in the rate/scale sense) in bytes */
51 int64_t cum_len; /* temporary storage (used during seek) */
52 int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
56 int dshow_block_align; /* block align variable used to emulate bugs in
57 * the MS dshow demuxer */
59 AVFormatContext *sub_ctx;
78 DVDemuxContext *dv_demux;
81 #define MAX_ODML_DEPTH 1000
86 static const AVOption options[] = {
87 { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_INT, {.i64 = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
91 static const AVClass demuxer_class = {
93 .item_name = av_default_item_name,
95 .version = LIBAVUTIL_VERSION_INT,
96 .category = AV_CLASS_CATEGORY_DEMUXER,
100 static const char avi_headers[][8] = {
101 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
102 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
103 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
104 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
105 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
109 static const AVMetadataConv avi_metadata_conv[] = {
114 static int avi_load_index(AVFormatContext *s);
115 static int guess_ni_flag(AVFormatContext *s);
117 #define print_tag(str, tag, size) \
118 av_dlog(NULL, "pos:%"PRIX64" %s: tag=%c%c%c%c size=0x%x\n", \
119 avio_tell(pb), str, tag & 0xff, \
121 (tag >> 16) & 0xff, \
122 (tag >> 24) & 0xff, \
125 static inline int get_duration(AVIStream *ast, int len)
127 if (ast->sample_size)
129 else if (ast->dshow_block_align)
130 return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
135 static int get_riff(AVFormatContext *s, AVIOContext *pb)
137 AVIContext *avi = s->priv_data;
141 /* check RIFF header */
142 avio_read(pb, header, 4);
143 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
144 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
145 avio_read(pb, header + 4, 4);
147 for (i = 0; avi_headers[i][0]; i++)
148 if (!memcmp(header, avi_headers[i], 8))
150 if (!avi_headers[i][0])
151 return AVERROR_INVALIDDATA;
153 if (header[7] == 0x19)
154 av_log(s, AV_LOG_INFO,
155 "This file has been generated by a totally broken muxer.\n");
160 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
162 AVIContext *avi = s->priv_data;
163 AVIOContext *pb = s->pb;
164 int longs_pre_entry = avio_rl16(pb);
165 int index_sub_type = avio_r8(pb);
166 int index_type = avio_r8(pb);
167 int entries_in_use = avio_rl32(pb);
168 int chunk_id = avio_rl32(pb);
169 int64_t base = avio_rl64(pb);
170 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
171 ((chunk_id >> 8 & 0xFF) - '0');
175 int64_t last_pos = -1;
176 int64_t filesize = avi->fsize;
179 "longs_pre_entry:%d index_type:%d entries_in_use:%d "
180 "chunk_id:%X base:%16"PRIX64"\n",
187 if (stream_id >= s->nb_streams || stream_id < 0)
188 return AVERROR_INVALIDDATA;
189 st = s->streams[stream_id];
193 return AVERROR_INVALIDDATA;
197 if (index_type && longs_pre_entry != 2)
198 return AVERROR_INVALIDDATA;
200 return AVERROR_INVALIDDATA;
202 if (filesize > 0 && base >= filesize) {
203 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
204 if (base >> 32 == (base & 0xFFFFFFFF) &&
205 (base & 0xFFFFFFFF) < filesize &&
206 filesize <= 0xFFFFFFFF)
209 return AVERROR_INVALIDDATA;
212 for (i = 0; i < entries_in_use; i++) {
214 int64_t pos = avio_rl32(pb) + base - 8;
215 int len = avio_rl32(pb);
220 av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
223 return AVERROR_INVALIDDATA;
225 if (last_pos == pos || pos == base - 8)
226 avi->non_interleaved = 1;
227 if (last_pos != pos && (len || !ast->sample_size))
228 av_add_index_entry(st, pos, ast->cum_len, len, 0,
229 key ? AVINDEX_KEYFRAME : 0);
231 ast->cum_len += get_duration(ast, len);
236 offset = avio_rl64(pb);
237 avio_rl32(pb); /* size */
238 duration = avio_rl32(pb);
241 return AVERROR_INVALIDDATA;
245 if (avi->odml_depth > MAX_ODML_DEPTH) {
246 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
247 return AVERROR_INVALIDDATA;
250 if (avio_seek(pb, offset + 8, SEEK_SET) < 0)
253 read_braindead_odml_indx(s, frame_num);
255 frame_num += duration;
257 if (avio_seek(pb, pos, SEEK_SET) < 0) {
258 av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index\n");
264 avi->index_loaded = 2;
268 static void clean_index(AVFormatContext *s)
273 for (i = 0; i < s->nb_streams; i++) {
274 AVStream *st = s->streams[i];
275 AVIStream *ast = st->priv_data;
276 int n = st->nb_index_entries;
277 int max = ast->sample_size;
278 int64_t pos, size, ts;
280 if (n != 1 || ast->sample_size == 0)
286 pos = st->index_entries[0].pos;
287 size = st->index_entries[0].size;
288 ts = st->index_entries[0].timestamp;
290 for (j = 0; j < size; j += max)
291 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
296 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
299 AVIOContext *pb = s->pb;
305 if (size == UINT_MAX)
306 return AVERROR(EINVAL);
307 value = av_malloc(size + 1);
309 return AVERROR(ENOMEM);
310 avio_read(pb, value, size);
315 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
316 AV_DICT_DONT_STRDUP_VAL);
319 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
320 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
322 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
324 char month[4], time[9], buffer[64];
326 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
327 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
328 month, &day, time, &year) == 4) {
329 for (i = 0; i < 12; i++)
330 if (!av_strcasecmp(month, months[i])) {
331 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
332 year, i + 1, day, time);
333 av_dict_set(metadata, "creation_time", buffer, 0);
335 } else if (date[4] == '/' && date[7] == '/') {
336 date[4] = date[7] = '-';
337 av_dict_set(metadata, "creation_time", date, 0);
341 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
343 while (avio_tell(s->pb) < end) {
344 uint32_t tag = avio_rl32(s->pb);
345 uint32_t size = avio_rl32(s->pb);
347 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
349 uint64_t tag_end = avio_tell(s->pb) + size;
350 while (avio_tell(s->pb) < tag_end) {
351 uint16_t tag = avio_rl16(s->pb);
352 uint16_t size = avio_rl16(s->pb);
353 const char *name = NULL;
354 char buffer[64] = { 0 };
355 size = FFMIN(size, tag_end - avio_tell(s->pb));
356 size -= avio_read(s->pb, buffer,
357 FFMIN(size, sizeof(buffer) - 1));
366 name = "creation_time";
367 if (buffer[4] == ':' && buffer[7] == ':')
368 buffer[4] = buffer[7] = '-';
372 av_dict_set(&s->metadata, name, buffer, 0);
373 avio_skip(s->pb, size);
378 avio_skip(s->pb, size);
384 static int avi_extract_stream_metadata(AVStream *st)
387 uint8_t *data = st->codec->extradata;
388 int data_size = st->codec->extradata_size;
391 if (!data || data_size < 8) {
392 return AVERROR_INVALIDDATA;
395 bytestream2_init(&gb, data, data_size);
397 tag = bytestream2_get_le32(&gb);
400 case MKTAG('A', 'V', 'I', 'F'):
401 // skip 4 byte padding
402 bytestream2_skip(&gb, 4);
403 offset = bytestream2_tell(&gb);
404 bytestream2_init(&gb, data + offset, data_size - offset);
406 // decode EXIF tags from IFD, AVI is always little-endian
407 return avpriv_exif_decode_ifd(st->codec, &gb, 1, 0, &st->metadata);
409 case MKTAG('C', 'A', 'S', 'I'):
410 avpriv_request_sample(st->codec, "RIFF stream data tag type CASI (%u)", tag);
412 case MKTAG('Z', 'o', 'r', 'a'):
413 avpriv_request_sample(st->codec, "RIFF stream data tag type Zora (%u)", tag);
422 static int calculate_bitrate(AVFormatContext *s)
424 AVIContext *avi = s->priv_data;
429 for (i = 0; i<s->nb_streams; i++) {
431 AVStream *st = s->streams[i];
433 if (!st->nb_index_entries)
436 for (j = 0; j < st->nb_index_entries; j++)
437 len += st->index_entries[j].size;
438 maxpos = FFMAX(maxpos, st->index_entries[j-1].pos);
441 if (maxpos < avi->io_fsize*9/10) // index doesnt cover the whole file
443 if (lensum*9/10 > maxpos || lensum < maxpos*9/10) // frame sum and filesize mismatch
446 for (i = 0; i<s->nb_streams; i++) {
448 AVStream *st = s->streams[i];
451 for (j = 0; j < st->nb_index_entries; j++)
452 len += st->index_entries[j].size;
454 if (st->nb_index_entries < 2 || st->codec->bit_rate > 0)
456 duration = st->index_entries[j-1].timestamp - st->index_entries[0].timestamp;
457 st->codec->bit_rate = av_rescale(8*len, st->time_base.den, duration * st->time_base.num);
462 static int avi_read_header(AVFormatContext *s)
464 AVIContext *avi = s->priv_data;
465 AVIOContext *pb = s->pb;
466 unsigned int tag, tag1, handler;
467 int codec_type, stream_index, frame_period;
471 AVIStream *ast = NULL;
472 int avih_width = 0, avih_height = 0;
473 int amv_file_format = 0;
474 uint64_t list_end = 0;
476 AVDictionaryEntry *dict_entry;
478 avi->stream_index = -1;
480 ret = get_riff(s, pb);
484 av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
486 avi->io_fsize = avi->fsize = avio_size(pb);
487 if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
488 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
498 size = avio_rl32(pb);
500 print_tag("tag", tag, size);
503 case MKTAG('L', 'I', 'S', 'T'):
504 list_end = avio_tell(pb) + size;
505 /* Ignored, except at start of video packets. */
506 tag1 = avio_rl32(pb);
508 print_tag("list", tag1, 0);
510 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
511 avi->movi_list = avio_tell(pb) - 4;
513 avi->movi_end = avi->movi_list + size + (size & 1);
515 avi->movi_end = avi->fsize;
516 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
518 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
519 ff_read_riff_info(s, size - 4);
520 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
521 avi_read_nikon(s, list_end);
524 case MKTAG('I', 'D', 'I', 'T'):
526 unsigned char date[64] = { 0 };
528 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
530 avi_metadata_creation_time(&s->metadata, date);
533 case MKTAG('d', 'm', 'l', 'h'):
535 avio_skip(pb, size + (size & 1));
537 case MKTAG('a', 'm', 'v', 'h'):
539 case MKTAG('a', 'v', 'i', 'h'):
541 /* using frame_period is bad idea */
542 frame_period = avio_rl32(pb);
543 avio_rl32(pb); /* max. bytes per second */
545 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
547 avio_skip(pb, 2 * 4);
550 avih_width = avio_rl32(pb);
551 avih_height = avio_rl32(pb);
553 avio_skip(pb, size - 10 * 4);
555 case MKTAG('s', 't', 'r', 'h'):
558 tag1 = avio_rl32(pb);
559 handler = avio_rl32(pb); /* codec tag */
561 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
562 avio_skip(pb, size - 8);
566 st = avformat_new_stream(s, NULL);
570 st->id = stream_index;
571 ast = av_mallocz(sizeof(AVIStream));
577 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
578 : MKTAG('v', 'i', 'd', 's');
580 print_tag("strh", tag1, -1);
582 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
583 tag1 == MKTAG('i', 'v', 'a', 's')) {
586 /* After some consideration -- I don't think we
587 * have to support anything but DV in type1 AVIs. */
588 if (s->nb_streams != 1)
591 if (handler != MKTAG('d', 'v', 's', 'd') &&
592 handler != MKTAG('d', 'v', 'h', 'd') &&
593 handler != MKTAG('d', 'v', 's', 'l'))
596 ast = s->streams[0]->priv_data;
597 av_freep(&s->streams[0]->codec->extradata);
598 av_freep(&s->streams[0]->codec);
599 if (s->streams[0]->info)
600 av_freep(&s->streams[0]->info->duration_error);
601 av_freep(&s->streams[0]->info);
602 av_freep(&s->streams[0]);
604 if (CONFIG_DV_DEMUXER) {
605 avi->dv_demux = avpriv_dv_init_demux(s);
610 s->streams[0]->priv_data = ast;
611 avio_skip(pb, 3 * 4);
612 ast->scale = avio_rl32(pb);
613 ast->rate = avio_rl32(pb);
614 avio_skip(pb, 4); /* start time */
616 dv_dur = avio_rl32(pb);
617 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
618 dv_dur *= AV_TIME_BASE;
619 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
621 /* else, leave duration alone; timing estimation in utils.c
622 * will make a guess based on bitrate. */
624 stream_index = s->nb_streams - 1;
625 avio_skip(pb, size - 9 * 4);
629 av_assert0(stream_index < s->nb_streams);
630 st->codec->stream_codec_tag = handler;
632 avio_rl32(pb); /* flags */
633 avio_rl16(pb); /* priority */
634 avio_rl16(pb); /* language */
635 avio_rl32(pb); /* initial frame */
636 ast->scale = avio_rl32(pb);
637 ast->rate = avio_rl32(pb);
638 if (!(ast->scale && ast->rate)) {
639 av_log(s, AV_LOG_WARNING,
640 "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
641 "(This file has been generated by broken software.)\n",
646 ast->scale = frame_period;
652 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
654 ast->cum_len = avio_rl32(pb); /* start */
655 st->nb_frames = avio_rl32(pb);
658 avio_rl32(pb); /* buffer size */
659 avio_rl32(pb); /* quality */
660 if (ast->cum_len*ast->scale/ast->rate > 3600) {
661 av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
662 return AVERROR_INVALIDDATA;
664 ast->sample_size = avio_rl32(pb); /* sample ssize */
665 ast->cum_len *= FFMAX(1, ast->sample_size);
666 av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
667 ast->rate, ast->scale, ast->sample_size);
670 case MKTAG('v', 'i', 'd', 's'):
671 codec_type = AVMEDIA_TYPE_VIDEO;
673 ast->sample_size = 0;
675 case MKTAG('a', 'u', 'd', 's'):
676 codec_type = AVMEDIA_TYPE_AUDIO;
678 case MKTAG('t', 'x', 't', 's'):
679 codec_type = AVMEDIA_TYPE_SUBTITLE;
681 case MKTAG('d', 'a', 't', 's'):
682 codec_type = AVMEDIA_TYPE_DATA;
685 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
687 if (ast->sample_size == 0) {
688 st->duration = st->nb_frames;
689 if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) {
690 av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n");
691 st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end);
694 ast->frame_offset = ast->cum_len;
695 avio_skip(pb, size - 12 * 4);
697 case MKTAG('s', 't', 'r', 'f'):
701 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
704 uint64_t cur_pos = avio_tell(pb);
706 if (cur_pos < list_end)
707 size = FFMIN(size, list_end - cur_pos);
708 st = s->streams[stream_index];
709 if (st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN) {
713 switch (codec_type) {
714 case AVMEDIA_TYPE_VIDEO:
715 if (amv_file_format) {
716 st->codec->width = avih_width;
717 st->codec->height = avih_height;
718 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
719 st->codec->codec_id = AV_CODEC_ID_AMV;
723 tag1 = ff_get_bmp_header(pb, st, &esize);
725 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
726 tag1 == MKTAG('D', 'X', 'S', 'A')) {
727 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
728 st->codec->codec_tag = tag1;
729 st->codec->codec_id = AV_CODEC_ID_XSUB;
733 if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) {
734 if (esize == size-1 && (esize&1)) {
735 st->codec->extradata_size = esize - 10 * 4;
737 st->codec->extradata_size = size - 10 * 4;
738 if (ff_get_extradata(st->codec, pb, st->codec->extradata_size) < 0)
739 return AVERROR(ENOMEM);
742 // FIXME: check if the encoder really did this correctly
743 if (st->codec->extradata_size & 1)
746 /* Extract palette from extradata if bpp <= 8.
747 * This code assumes that extradata contains only palette.
748 * This is true for all paletted codecs implemented in
750 if (st->codec->extradata_size &&
751 (st->codec->bits_per_coded_sample <= 8)) {
752 int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
753 const uint8_t *pal_src;
755 pal_size = FFMIN(pal_size, st->codec->extradata_size);
756 pal_src = st->codec->extradata +
757 st->codec->extradata_size - pal_size;
758 for (i = 0; i < pal_size / 4; i++)
759 ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i);
763 print_tag("video", tag1, 0);
765 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
766 st->codec->codec_tag = tag1;
767 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
769 /* This is needed to get the pict type which is necessary
770 * for generating correct pts. */
771 st->need_parsing = AVSTREAM_PARSE_HEADERS;
772 if (st->codec->codec_tag == MKTAG('V', 'S', 'S', 'H'))
773 st->need_parsing = AVSTREAM_PARSE_FULL;
775 if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
776 st->codec->extradata_size < 1U << 30) {
777 st->codec->extradata_size += 9;
778 if ((ret = av_reallocp(&st->codec->extradata,
779 st->codec->extradata_size +
780 FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
781 st->codec->extradata_size = 0;
784 memcpy(st->codec->extradata + st->codec->extradata_size - 9,
787 st->codec->height = FFABS(st->codec->height);
789 // avio_skip(pb, size - 5 * 4);
791 case AVMEDIA_TYPE_AUDIO:
792 ret = ff_get_wav_header(pb, st->codec, size);
795 ast->dshow_block_align = st->codec->block_align;
796 if (ast->sample_size && st->codec->block_align &&
797 ast->sample_size != st->codec->block_align) {
800 "sample size (%d) != block align (%d)\n",
802 st->codec->block_align);
803 ast->sample_size = st->codec->block_align;
806 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
809 /* Force parsing as several audio frames can be in
810 * one packet and timestamps refer to packet start. */
811 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
812 /* ADTS header is in extradata, AAC without header must be
813 * stored as exact frames. Parser not needed and it will
815 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
816 st->codec->extradata_size)
817 st->need_parsing = AVSTREAM_PARSE_NONE;
818 /* AVI files with Xan DPCM audio (wrongly) declare PCM
819 * audio in the header but have Axan as stream_code_tag. */
820 if (st->codec->stream_codec_tag == AV_RL32("Axan")) {
821 st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
822 st->codec->codec_tag = 0;
823 ast->dshow_block_align = 0;
825 if (amv_file_format) {
826 st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
827 ast->dshow_block_align = 0;
829 if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
830 av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
831 ast->dshow_block_align = 0;
833 if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
834 st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
835 st->codec->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
836 av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
837 ast->sample_size = 0;
840 case AVMEDIA_TYPE_SUBTITLE:
841 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
842 st->request_probe= 1;
846 st->codec->codec_type = AVMEDIA_TYPE_DATA;
847 st->codec->codec_id = AV_CODEC_ID_NONE;
848 st->codec->codec_tag = 0;
854 case MKTAG('s', 't', 'r', 'd'):
855 if (stream_index >= (unsigned)s->nb_streams
856 || s->streams[stream_index]->codec->extradata_size
857 || s->streams[stream_index]->codec->codec_tag == MKTAG('H','2','6','4')) {
860 uint64_t cur_pos = avio_tell(pb);
861 if (cur_pos < list_end)
862 size = FFMIN(size, list_end - cur_pos);
863 st = s->streams[stream_index];
866 if (ff_get_extradata(st->codec, pb, size) < 0)
867 return AVERROR(ENOMEM);
870 if (st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
873 ret = avi_extract_stream_metadata(st);
875 av_log(s, AV_LOG_WARNING, "could not decoding EXIF data in stream header.\n");
879 case MKTAG('i', 'n', 'd', 'x'):
881 if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
883 read_braindead_odml_indx(s, 0) < 0 &&
884 (s->error_recognition & AV_EF_EXPLODE))
886 avio_seek(pb, i + size, SEEK_SET);
888 case MKTAG('v', 'p', 'r', 'p'):
889 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
890 AVRational active, active_aspect;
892 st = s->streams[stream_index];
899 active_aspect.den = avio_rl16(pb);
900 active_aspect.num = avio_rl16(pb);
901 active.num = avio_rl32(pb);
902 active.den = avio_rl32(pb);
903 avio_rl32(pb); // nbFieldsPerFrame
905 if (active_aspect.num && active_aspect.den &&
906 active.num && active.den) {
907 st->sample_aspect_ratio = av_div_q(active_aspect, active);
908 av_dlog(s, "vprp %d/%d %d/%d\n",
909 active_aspect.num, active_aspect.den,
910 active.num, active.den);
916 case MKTAG('s', 't', 'r', 'n'):
918 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
924 if (size > 1000000) {
925 av_log(s, AV_LOG_ERROR,
926 "Something went wrong during header parsing, "
927 "I will ignore it and try to continue anyway.\n");
928 if (s->error_recognition & AV_EF_EXPLODE)
930 avi->movi_list = avio_tell(pb) - 4;
931 avi->movi_end = avi->fsize;
942 /* check stream number */
943 if (stream_index != s->nb_streams - 1) {
946 return AVERROR_INVALIDDATA;
949 if (!avi->index_loaded && pb->seekable)
951 calculate_bitrate(s);
952 avi->index_loaded |= 1;
954 if ((ret = guess_ni_flag(s)) < 0)
957 avi->non_interleaved |= ret | (s->flags & AVFMT_FLAG_SORT_DTS);
959 dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0);
960 if (dict_entry && !strcmp(dict_entry->value, "PotEncoder"))
961 for (i = 0; i < s->nb_streams; i++) {
962 AVStream *st = s->streams[i];
963 if ( st->codec->codec_id == AV_CODEC_ID_MPEG1VIDEO
964 || st->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO)
965 st->need_parsing = AVSTREAM_PARSE_FULL;
968 for (i = 0; i < s->nb_streams; i++) {
969 AVStream *st = s->streams[i];
970 if (st->nb_index_entries)
973 // DV-in-AVI cannot be non-interleaved, if set this must be
976 avi->non_interleaved = 0;
977 if (i == s->nb_streams && avi->non_interleaved) {
978 av_log(s, AV_LOG_WARNING,
979 "Non-interleaved AVI without index, switching to interleaved\n");
980 avi->non_interleaved = 0;
983 if (avi->non_interleaved) {
984 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
988 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
989 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
994 static int read_gab2_sub(AVStream *st, AVPacket *pkt)
996 if (pkt->size >= 7 &&
997 pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
998 !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
1000 int score = AVPROBE_SCORE_EXTENSION, ret;
1001 AVIStream *ast = st->priv_data;
1002 AVInputFormat *sub_demuxer;
1003 AVRational time_base;
1005 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
1007 0, NULL, NULL, NULL, NULL);
1009 unsigned int desc_len = avio_rl32(pb);
1011 if (desc_len > pb->buf_end - pb->buf_ptr)
1014 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
1015 avio_skip(pb, desc_len - ret);
1017 av_dict_set(&st->metadata, "title", desc, 0);
1019 avio_rl16(pb); /* flags? */
1020 avio_rl32(pb); /* data size */
1022 size = pb->buf_end - pb->buf_ptr;
1023 pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
1027 memcpy(pd.buf, pb->buf_ptr, size);
1028 sub_demuxer = av_probe_input_format2(&pd, 1, &score);
1033 if (!(ast->sub_ctx = avformat_alloc_context()))
1036 ast->sub_ctx->pb = pb;
1037 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
1038 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
1039 *st->codec = *ast->sub_ctx->streams[0]->codec;
1040 ast->sub_ctx->streams[0]->codec->extradata = NULL;
1041 time_base = ast->sub_ctx->streams[0]->time_base;
1042 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
1044 ast->sub_buffer = pkt->data;
1045 memset(pkt, 0, sizeof(*pkt));
1054 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
1057 AVIStream *ast, *next_ast = next_st->priv_data;
1058 int64_t ts, next_ts, ts_min = INT64_MAX;
1059 AVStream *st, *sub_st = NULL;
1062 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
1065 for (i = 0; i < s->nb_streams; i++) {
1067 ast = st->priv_data;
1068 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
1069 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
1070 if (ts <= next_ts && ts < ts_min) {
1078 ast = sub_st->priv_data;
1079 *pkt = ast->sub_pkt;
1080 pkt->stream_index = sub_st->index;
1082 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
1083 ast->sub_pkt.data = NULL;
1088 static int get_stream_idx(unsigned *d)
1090 if (d[0] >= '0' && d[0] <= '9' &&
1091 d[1] >= '0' && d[1] <= '9') {
1092 return (d[0] - '0') * 10 + (d[1] - '0');
1094 return 100; // invalid stream ID
1100 * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
1102 static int avi_sync(AVFormatContext *s, int exit_early)
1104 AVIContext *avi = s->priv_data;
1105 AVIOContext *pb = s->pb;
1112 memset(d, -1, sizeof(d));
1113 for (i = sync = avio_tell(pb); !url_feof(pb); i++) {
1116 for (j = 0; j < 7; j++)
1120 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
1122 n = get_stream_idx(d + 2);
1123 av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
1124 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
1125 if (i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127)
1129 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
1131 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
1132 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
1133 avio_skip(pb, size);
1138 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
1143 n = avi->dv_demux ? 0 : get_stream_idx(d);
1145 if (!((i - avi->last_pkt_pos) & 1) &&
1146 get_stream_idx(d + 1) < s->nb_streams)
1149 // detect ##ix chunk and skip
1150 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
1151 avio_skip(pb, size);
1156 if (n < s->nb_streams) {
1160 ast = st->priv_data;
1163 av_log(s, AV_LOG_WARNING, "Skiping foreign stream %d packet\n", n);
1167 if (s->nb_streams >= 2) {
1168 AVStream *st1 = s->streams[1];
1169 AVIStream *ast1 = st1->priv_data;
1170 // workaround for broken small-file-bug402.avi
1171 if ( d[2] == 'w' && d[3] == 'b'
1173 && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
1174 && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
1175 && ast->prefix == 'd'*256+'c'
1176 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
1181 av_log(s, AV_LOG_WARNING,
1182 "Invalid stream + prefix combination, assuming audio.\n");
1186 if (!avi->dv_demux &&
1187 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
1188 // FIXME: needs a little reordering
1189 (st->discard >= AVDISCARD_NONKEY &&
1190 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1191 || st->discard >= AVDISCARD_ALL)) {
1193 ast->frame_offset += get_duration(ast, size);
1194 avio_skip(pb, size);
1199 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1200 int k = avio_r8(pb);
1201 int last = (k + avio_r8(pb) - 1) & 0xFF;
1203 avio_rl16(pb); // flags
1205 // b + (g << 8) + (r << 16);
1206 for (; k <= last; k++)
1207 ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;
1211 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1212 d[2] < 128 && d[3] < 128) ||
1213 d[2] * 256 + d[3] == ast->prefix /* ||
1214 (d[2] == 'd' && d[3] == 'c') ||
1215 (d[2] == 'w' && d[3] == 'b') */) {
1218 if (d[2] * 256 + d[3] == ast->prefix)
1219 ast->prefix_count++;
1221 ast->prefix = d[2] * 256 + d[3];
1222 ast->prefix_count = 0;
1225 avi->stream_index = n;
1226 ast->packet_size = size + 8;
1227 ast->remaining = size;
1229 if (size || !ast->sample_size) {
1230 uint64_t pos = avio_tell(pb) - 8;
1231 if (!st->index_entries || !st->nb_index_entries ||
1232 st->index_entries[st->nb_index_entries - 1].pos < pos) {
1233 av_add_index_entry(st, pos, ast->frame_offset, size,
1234 0, AVINDEX_KEYFRAME);
1247 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1249 AVIContext *avi = s->priv_data;
1250 AVIOContext *pb = s->pb;
1252 #if FF_API_DESTRUCT_PACKET
1256 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1257 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1264 if (avi->non_interleaved) {
1265 int best_stream_index = 0;
1266 AVStream *best_st = NULL;
1267 AVIStream *best_ast;
1268 int64_t best_ts = INT64_MAX;
1271 for (i = 0; i < s->nb_streams; i++) {
1272 AVStream *st = s->streams[i];
1273 AVIStream *ast = st->priv_data;
1274 int64_t ts = ast->frame_offset;
1277 if (!st->nb_index_entries)
1280 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1281 if (!ast->remaining && ts > last_ts)
1284 ts = av_rescale_q(ts, st->time_base,
1285 (AVRational) { FFMAX(1, ast->sample_size),
1288 av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
1289 st->time_base.num, st->time_base.den, ast->frame_offset);
1293 best_stream_index = i;
1299 best_ast = best_st->priv_data;
1300 best_ts = best_ast->frame_offset;
1301 if (best_ast->remaining) {
1302 i = av_index_search_timestamp(best_st,
1305 AVSEEK_FLAG_BACKWARD);
1307 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1309 best_ast->frame_offset = best_st->index_entries[i].timestamp;
1313 int64_t pos = best_st->index_entries[i].pos;
1314 pos += best_ast->packet_size - best_ast->remaining;
1315 if (avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
1318 av_assert0(best_ast->remaining <= best_ast->packet_size);
1320 avi->stream_index = best_stream_index;
1321 if (!best_ast->remaining)
1322 best_ast->packet_size =
1323 best_ast->remaining = best_st->index_entries[i].size;
1330 if (avi->stream_index >= 0) {
1331 AVStream *st = s->streams[avi->stream_index];
1332 AVIStream *ast = st->priv_data;
1335 if (get_subtitle_pkt(s, st, pkt))
1338 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1339 if (ast->sample_size <= 1)
1341 else if (ast->sample_size < 32)
1342 // arbitrary multiplier to avoid tiny packets for raw PCM data
1343 size = 1024 * ast->sample_size;
1345 size = ast->sample_size;
1347 if (size > ast->remaining)
1348 size = ast->remaining;
1349 avi->last_pkt_pos = avio_tell(pb);
1350 err = av_get_packet(pb, pkt, size);
1355 if (ast->has_pal && pkt->size < (unsigned)INT_MAX / 2) {
1357 pal = av_packet_new_side_data(pkt,
1358 AV_PKT_DATA_PALETTE,
1361 av_log(s, AV_LOG_ERROR,
1362 "Failed to allocate data for palette\n");
1364 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1369 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1370 AVBufferRef *avbuf = pkt->buf;
1371 #if FF_API_DESTRUCT_PACKET
1372 FF_DISABLE_DEPRECATION_WARNINGS
1373 dstr = pkt->destruct;
1374 FF_ENABLE_DEPRECATION_WARNINGS
1376 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1377 pkt->data, pkt->size, pkt->pos);
1378 #if FF_API_DESTRUCT_PACKET
1379 FF_DISABLE_DEPRECATION_WARNINGS
1380 pkt->destruct = dstr;
1381 FF_ENABLE_DEPRECATION_WARNINGS
1384 pkt->flags |= AV_PKT_FLAG_KEY;
1386 av_free_packet(pkt);
1387 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1388 !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1389 ast->frame_offset++;
1390 avi->stream_index = -1;
1394 /* XXX: How to handle B-frames in AVI? */
1395 pkt->dts = ast->frame_offset;
1396 // pkt->dts += ast->start;
1397 if (ast->sample_size)
1398 pkt->dts /= ast->sample_size;
1400 "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
1401 "base:%d st:%d size:%d\n",
1410 pkt->stream_index = avi->stream_index;
1412 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->index_entries) {
1416 index = av_index_search_timestamp(st, ast->frame_offset, 0);
1417 e = &st->index_entries[index];
1419 if (index >= 0 && e->timestamp == ast->frame_offset) {
1420 if (index == st->nb_index_entries-1) {
1424 for (i=0; i<FFMIN(size,256); i++) {
1425 if (st->codec->codec_id == AV_CODEC_ID_MPEG4) {
1426 if (state == 0x1B6) {
1427 key= !(pkt->data[i]&0xC0);
1432 state= (state<<8) + pkt->data[i];
1435 e->flags &= ~AVINDEX_KEYFRAME;
1437 if (e->flags & AVINDEX_KEYFRAME)
1438 pkt->flags |= AV_PKT_FLAG_KEY;
1441 pkt->flags |= AV_PKT_FLAG_KEY;
1443 ast->frame_offset += get_duration(ast, pkt->size);
1445 ast->remaining -= err;
1446 if (!ast->remaining) {
1447 avi->stream_index = -1;
1448 ast->packet_size = 0;
1451 if (!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos) {
1452 av_free_packet(pkt);
1457 if (!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1) {
1458 int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
1460 if (avi->dts_max - dts > 2*AV_TIME_BASE) {
1461 avi->non_interleaved= 1;
1462 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
1463 }else if (avi->dts_max < dts)
1470 if ((err = avi_sync(s, 0)) < 0)
1475 /* XXX: We make the implicit supposition that the positions are sorted
1476 * for each stream. */
1477 static int avi_read_idx1(AVFormatContext *s, int size)
1479 AVIContext *avi = s->priv_data;
1480 AVIOContext *pb = s->pb;
1481 int nb_index_entries, i;
1484 unsigned int index, tag, flags, pos, len, first_packet = 1;
1485 unsigned last_pos = -1;
1486 unsigned last_idx = -1;
1487 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1490 nb_index_entries = size / 16;
1491 if (nb_index_entries <= 0)
1492 return AVERROR_INVALIDDATA;
1494 idx1_pos = avio_tell(pb);
1495 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1496 if (avi_sync(s, 1) == 0)
1497 first_packet_pos = avio_tell(pb) - 8;
1498 avi->stream_index = -1;
1499 avio_seek(pb, idx1_pos, SEEK_SET);
1501 if (s->nb_streams == 1 && s->streams[0]->codec->codec_tag == AV_RL32("MMES")) {
1502 first_packet_pos = 0;
1503 data_offset = avi->movi_list;
1506 /* Read the entries and sort them in each stream component. */
1507 for (i = 0; i < nb_index_entries; i++) {
1511 tag = avio_rl32(pb);
1512 flags = avio_rl32(pb);
1513 pos = avio_rl32(pb);
1514 len = avio_rl32(pb);
1515 av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1516 i, tag, flags, pos, len);
1518 index = ((tag & 0xff) - '0') * 10;
1519 index += (tag >> 8 & 0xff) - '0';
1520 if (index >= s->nb_streams)
1522 st = s->streams[index];
1523 ast = st->priv_data;
1525 if (first_packet && first_packet_pos) {
1526 data_offset = first_packet_pos - pos;
1531 av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1533 // even if we have only a single stream, we should
1534 // switch to non-interleaved to get correct timestamps
1535 if (last_pos == pos)
1536 avi->non_interleaved = 1;
1537 if (last_idx != pos && len) {
1538 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1539 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1542 ast->cum_len += get_duration(ast, len);
1544 anykey |= flags&AVIIF_INDEX;
1547 for (index = 0; index < s->nb_streams; index++) {
1548 st = s->streams[index];
1549 if (st->nb_index_entries)
1550 st->index_entries[0].flags |= AVINDEX_KEYFRAME;
1556 /* Scan the index and consider any file with streams more than
1557 * 2 seconds or 64MB apart non-interleaved. */
1558 static int check_stream_max_drift(AVFormatContext *s)
1560 int64_t min_pos, pos;
1562 int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
1564 return AVERROR(ENOMEM);
1565 for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
1566 int64_t max_dts = INT64_MIN / 2;
1567 int64_t min_dts = INT64_MAX / 2;
1568 int64_t max_buffer = 0;
1570 min_pos = INT64_MAX;
1572 for (i = 0; i < s->nb_streams; i++) {
1573 AVStream *st = s->streams[i];
1574 AVIStream *ast = st->priv_data;
1575 int n = st->nb_index_entries;
1576 while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
1580 dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
1581 FFMAX(ast->sample_size, 1),
1582 st->time_base, AV_TIME_BASE_Q);
1583 min_dts = FFMIN(min_dts, dts);
1584 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
1587 for (i = 0; i < s->nb_streams; i++) {
1588 AVStream *st = s->streams[i];
1589 AVIStream *ast = st->priv_data;
1591 if (idx[i] && min_dts != INT64_MAX / 2) {
1593 dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
1594 FFMAX(ast->sample_size, 1),
1595 st->time_base, AV_TIME_BASE_Q);
1596 max_dts = FFMAX(max_dts, dts);
1597 max_buffer = FFMAX(max_buffer,
1598 av_rescale(dts - min_dts,
1599 st->codec->bit_rate,
1603 if (max_dts - min_dts > 2 * AV_TIME_BASE ||
1604 max_buffer > 1024 * 1024 * 8 * 8) {
1613 static int guess_ni_flag(AVFormatContext *s)
1616 int64_t last_start = 0;
1617 int64_t first_end = INT64_MAX;
1618 int64_t oldpos = avio_tell(s->pb);
1620 for (i = 0; i < s->nb_streams; i++) {
1621 AVStream *st = s->streams[i];
1622 int n = st->nb_index_entries;
1629 int64_t pos = st->index_entries[0].pos;
1630 avio_seek(s->pb, pos + 4, SEEK_SET);
1631 size = avio_rl32(s->pb);
1632 if (pos + size > st->index_entries[1].pos)
1633 last_start = INT64_MAX;
1636 if (st->index_entries[0].pos > last_start)
1637 last_start = st->index_entries[0].pos;
1638 if (st->index_entries[n - 1].pos < first_end)
1639 first_end = st->index_entries[n - 1].pos;
1641 avio_seek(s->pb, oldpos, SEEK_SET);
1643 if (last_start > first_end)
1646 return check_stream_max_drift(s);
1649 static int avi_load_index(AVFormatContext *s)
1651 AVIContext *avi = s->priv_data;
1652 AVIOContext *pb = s->pb;
1654 int64_t pos = avio_tell(pb);
1658 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1659 goto the_end; // maybe truncated file
1660 av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1662 tag = avio_rl32(pb);
1663 size = avio_rl32(pb);
1666 next = avio_tell(pb) + size + (size & 1);
1668 av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1675 if (tag == MKTAG('i', 'd', 'x', '1') &&
1676 avi_read_idx1(s, size) >= 0) {
1677 avi->index_loaded=2;
1679 }else if (tag == MKTAG('L', 'I', 'S', 'T')) {
1680 uint32_t tag1 = avio_rl32(pb);
1682 if (tag1 == MKTAG('I', 'N', 'F', 'O'))
1683 ff_read_riff_info(s, size - 4);
1687 if (avio_seek(pb, next, SEEK_SET) < 0)
1688 break; // something is wrong here
1692 avio_seek(pb, pos, SEEK_SET);
1696 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1698 AVIStream *ast2 = st2->priv_data;
1699 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1700 av_free_packet(&ast2->sub_pkt);
1701 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1702 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1703 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1706 static int avi_read_seek(AVFormatContext *s, int stream_index,
1707 int64_t timestamp, int flags)
1709 AVIContext *avi = s->priv_data;
1712 int64_t pos, pos_min;
1715 /* Does not matter which stream is requested dv in avi has the
1716 * stream information in the first video stream.
1721 if (!avi->index_loaded) {
1722 /* we only load the index on demand */
1724 avi->index_loaded |= 1;
1726 av_assert0(stream_index >= 0);
1728 st = s->streams[stream_index];
1729 ast = st->priv_data;
1730 index = av_index_search_timestamp(st,
1731 timestamp * FFMAX(ast->sample_size, 1),
1734 if (st->nb_index_entries > 0)
1735 av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
1736 timestamp * FFMAX(ast->sample_size, 1),
1737 st->index_entries[0].timestamp,
1738 st->index_entries[st->nb_index_entries - 1].timestamp);
1739 return AVERROR_INVALIDDATA;
1742 /* find the position */
1743 pos = st->index_entries[index].pos;
1744 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1746 av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
1747 timestamp, index, st->index_entries[index].timestamp);
1749 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1750 /* One and only one real stream for DV in AVI, and it has video */
1751 /* offsets. Calling with other stream indexes should have failed */
1752 /* the av_index_search_timestamp call above. */
1754 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
1757 /* Feed the DV video stream version of the timestamp to the */
1758 /* DV demux so it can synthesize correct timestamps. */
1759 ff_dv_offset_reset(avi->dv_demux, timestamp);
1761 avi->stream_index = -1;
1766 for (i = 0; i < s->nb_streams; i++) {
1767 AVStream *st2 = s->streams[i];
1768 AVIStream *ast2 = st2->priv_data;
1771 ast2->remaining = 0;
1773 if (ast2->sub_ctx) {
1774 seek_subtitle(st, st2, timestamp);
1778 if (st2->nb_index_entries <= 0)
1781 // av_assert1(st2->codec->block_align);
1782 av_assert0((int64_t)st2->time_base.num * ast2->rate ==
1783 (int64_t)st2->time_base.den * ast2->scale);
1784 index = av_index_search_timestamp(st2,
1785 av_rescale_q(timestamp,
1788 FFMAX(ast2->sample_size, 1),
1790 AVSEEK_FLAG_BACKWARD |
1791 (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1794 ast2->seek_pos = st2->index_entries[index].pos;
1795 pos_min = FFMIN(pos_min,ast2->seek_pos);
1797 for (i = 0; i < s->nb_streams; i++) {
1798 AVStream *st2 = s->streams[i];
1799 AVIStream *ast2 = st2->priv_data;
1801 if (ast2->sub_ctx || st2->nb_index_entries <= 0)
1804 index = av_index_search_timestamp(
1806 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1807 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1810 while (!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
1812 ast2->frame_offset = st2->index_entries[index].timestamp;
1816 if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
1817 av_log(s, AV_LOG_ERROR, "Seek failed\n");
1820 avi->stream_index = -1;
1821 avi->dts_max = INT_MIN;
1825 static int avi_read_close(AVFormatContext *s)
1828 AVIContext *avi = s->priv_data;
1830 for (i = 0; i < s->nb_streams; i++) {
1831 AVStream *st = s->streams[i];
1832 AVIStream *ast = st->priv_data;
1835 av_freep(&ast->sub_ctx->pb);
1836 avformat_close_input(&ast->sub_ctx);
1838 av_free(ast->sub_buffer);
1839 av_free_packet(&ast->sub_pkt);
1843 av_free(avi->dv_demux);
1848 static int avi_probe(AVProbeData *p)
1852 /* check file header */
1853 for (i = 0; avi_headers[i][0]; i++)
1854 if (!memcmp(p->buf, avi_headers[i], 4) &&
1855 !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
1856 return AVPROBE_SCORE_MAX;
1861 AVInputFormat ff_avi_demuxer = {
1863 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1864 .priv_data_size = sizeof(AVIContext),
1865 .extensions = "avi",
1866 .read_probe = avi_probe,
1867 .read_header = avi_read_header,
1868 .read_packet = avi_read_packet,
1869 .read_close = avi_read_close,
1870 .read_seek = avi_read_seek,
1871 .priv_class = &demuxer_class,