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)
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 does not 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;
674 st->avg_frame_rate = av_inv_q(st->time_base);
676 case MKTAG('a', 'u', 'd', 's'):
677 codec_type = AVMEDIA_TYPE_AUDIO;
679 case MKTAG('t', 'x', 't', 's'):
680 codec_type = AVMEDIA_TYPE_SUBTITLE;
682 case MKTAG('d', 'a', 't', 's'):
683 codec_type = AVMEDIA_TYPE_DATA;
686 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
688 if (ast->sample_size == 0) {
689 st->duration = st->nb_frames;
690 if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) {
691 av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n");
692 st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end);
695 ast->frame_offset = ast->cum_len;
696 avio_skip(pb, size - 12 * 4);
698 case MKTAG('s', 't', 'r', 'f'):
702 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
705 uint64_t cur_pos = avio_tell(pb);
707 if (cur_pos < list_end)
708 size = FFMIN(size, list_end - cur_pos);
709 st = s->streams[stream_index];
710 if (st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN) {
714 switch (codec_type) {
715 case AVMEDIA_TYPE_VIDEO:
716 if (amv_file_format) {
717 st->codec->width = avih_width;
718 st->codec->height = avih_height;
719 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
720 st->codec->codec_id = AV_CODEC_ID_AMV;
724 tag1 = ff_get_bmp_header(pb, st, &esize);
726 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
727 tag1 == MKTAG('D', 'X', 'S', 'A')) {
728 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
729 st->codec->codec_tag = tag1;
730 st->codec->codec_id = AV_CODEC_ID_XSUB;
734 if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) {
735 if (esize == size-1 && (esize&1)) {
736 st->codec->extradata_size = esize - 10 * 4;
738 st->codec->extradata_size = size - 10 * 4;
739 if (ff_get_extradata(st->codec, pb, st->codec->extradata_size) < 0)
740 return AVERROR(ENOMEM);
743 // FIXME: check if the encoder really did this correctly
744 if (st->codec->extradata_size & 1)
747 /* Extract palette from extradata if bpp <= 8.
748 * This code assumes that extradata contains only palette.
749 * This is true for all paletted codecs implemented in
751 if (st->codec->extradata_size &&
752 (st->codec->bits_per_coded_sample <= 8)) {
753 int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
754 const uint8_t *pal_src;
756 pal_size = FFMIN(pal_size, st->codec->extradata_size);
757 pal_src = st->codec->extradata +
758 st->codec->extradata_size - pal_size;
759 for (i = 0; i < pal_size / 4; i++)
760 ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i);
764 print_tag("video", tag1, 0);
766 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
767 st->codec->codec_tag = tag1;
768 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
770 /* This is needed to get the pict type which is necessary
771 * for generating correct pts. */
772 st->need_parsing = AVSTREAM_PARSE_HEADERS;
773 if (st->codec->codec_tag == MKTAG('V', 'S', 'S', 'H'))
774 st->need_parsing = AVSTREAM_PARSE_FULL;
776 if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
777 st->codec->extradata_size < 1U << 30) {
778 st->codec->extradata_size += 9;
779 if ((ret = av_reallocp(&st->codec->extradata,
780 st->codec->extradata_size +
781 FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
782 st->codec->extradata_size = 0;
785 memcpy(st->codec->extradata + st->codec->extradata_size - 9,
788 st->codec->height = FFABS(st->codec->height);
790 // avio_skip(pb, size - 5 * 4);
792 case AVMEDIA_TYPE_AUDIO:
793 ret = ff_get_wav_header(pb, st->codec, size);
796 ast->dshow_block_align = st->codec->block_align;
797 if (ast->sample_size && st->codec->block_align &&
798 ast->sample_size != st->codec->block_align) {
801 "sample size (%d) != block align (%d)\n",
803 st->codec->block_align);
804 ast->sample_size = st->codec->block_align;
807 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
810 /* Force parsing as several audio frames can be in
811 * one packet and timestamps refer to packet start. */
812 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
813 /* ADTS header is in extradata, AAC without header must be
814 * stored as exact frames. Parser not needed and it will
816 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
817 st->codec->extradata_size)
818 st->need_parsing = AVSTREAM_PARSE_NONE;
819 /* AVI files with Xan DPCM audio (wrongly) declare PCM
820 * audio in the header but have Axan as stream_code_tag. */
821 if (st->codec->stream_codec_tag == AV_RL32("Axan")) {
822 st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
823 st->codec->codec_tag = 0;
824 ast->dshow_block_align = 0;
826 if (amv_file_format) {
827 st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
828 ast->dshow_block_align = 0;
830 if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
831 av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
832 ast->dshow_block_align = 0;
834 if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
835 st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
836 st->codec->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
837 av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
838 ast->sample_size = 0;
841 case AVMEDIA_TYPE_SUBTITLE:
842 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
843 st->request_probe= 1;
847 st->codec->codec_type = AVMEDIA_TYPE_DATA;
848 st->codec->codec_id = AV_CODEC_ID_NONE;
849 st->codec->codec_tag = 0;
855 case MKTAG('s', 't', 'r', 'd'):
856 if (stream_index >= (unsigned)s->nb_streams
857 || s->streams[stream_index]->codec->extradata_size
858 || s->streams[stream_index]->codec->codec_tag == MKTAG('H','2','6','4')) {
861 uint64_t cur_pos = avio_tell(pb);
862 if (cur_pos < list_end)
863 size = FFMIN(size, list_end - cur_pos);
864 st = s->streams[stream_index];
867 if (ff_get_extradata(st->codec, pb, size) < 0)
868 return AVERROR(ENOMEM);
871 if (st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
874 ret = avi_extract_stream_metadata(st);
876 av_log(s, AV_LOG_WARNING, "could not decoding EXIF data in stream header.\n");
880 case MKTAG('i', 'n', 'd', 'x'):
882 if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
884 read_braindead_odml_indx(s, 0) < 0 &&
885 (s->error_recognition & AV_EF_EXPLODE))
887 avio_seek(pb, i + size, SEEK_SET);
889 case MKTAG('v', 'p', 'r', 'p'):
890 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
891 AVRational active, active_aspect;
893 st = s->streams[stream_index];
900 active_aspect.den = avio_rl16(pb);
901 active_aspect.num = avio_rl16(pb);
902 active.num = avio_rl32(pb);
903 active.den = avio_rl32(pb);
904 avio_rl32(pb); // nbFieldsPerFrame
906 if (active_aspect.num && active_aspect.den &&
907 active.num && active.den) {
908 st->sample_aspect_ratio = av_div_q(active_aspect, active);
909 av_dlog(s, "vprp %d/%d %d/%d\n",
910 active_aspect.num, active_aspect.den,
911 active.num, active.den);
917 case MKTAG('s', 't', 'r', 'n'):
919 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
925 if (size > 1000000) {
926 av_log(s, AV_LOG_ERROR,
927 "Something went wrong during header parsing, "
928 "I will ignore it and try to continue anyway.\n");
929 if (s->error_recognition & AV_EF_EXPLODE)
931 avi->movi_list = avio_tell(pb) - 4;
932 avi->movi_end = avi->fsize;
943 /* check stream number */
944 if (stream_index != s->nb_streams - 1) {
947 return AVERROR_INVALIDDATA;
950 if (!avi->index_loaded && pb->seekable)
952 calculate_bitrate(s);
953 avi->index_loaded |= 1;
955 if ((ret = guess_ni_flag(s)) < 0)
958 avi->non_interleaved |= ret | (s->flags & AVFMT_FLAG_SORT_DTS);
960 dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0);
961 if (dict_entry && !strcmp(dict_entry->value, "PotEncoder"))
962 for (i = 0; i < s->nb_streams; i++) {
963 AVStream *st = s->streams[i];
964 if ( st->codec->codec_id == AV_CODEC_ID_MPEG1VIDEO
965 || st->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO)
966 st->need_parsing = AVSTREAM_PARSE_FULL;
969 for (i = 0; i < s->nb_streams; i++) {
970 AVStream *st = s->streams[i];
971 if (st->nb_index_entries)
974 // DV-in-AVI cannot be non-interleaved, if set this must be
977 avi->non_interleaved = 0;
978 if (i == s->nb_streams && avi->non_interleaved) {
979 av_log(s, AV_LOG_WARNING,
980 "Non-interleaved AVI without index, switching to interleaved\n");
981 avi->non_interleaved = 0;
984 if (avi->non_interleaved) {
985 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
989 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
990 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
995 static int read_gab2_sub(AVStream *st, AVPacket *pkt)
997 if (pkt->size >= 7 &&
998 pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
999 !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
1001 int score = AVPROBE_SCORE_EXTENSION, ret;
1002 AVIStream *ast = st->priv_data;
1003 AVInputFormat *sub_demuxer;
1004 AVRational time_base;
1006 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
1008 0, NULL, NULL, NULL, NULL);
1010 unsigned int desc_len = avio_rl32(pb);
1012 if (desc_len > pb->buf_end - pb->buf_ptr)
1015 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
1016 avio_skip(pb, desc_len - ret);
1018 av_dict_set(&st->metadata, "title", desc, 0);
1020 avio_rl16(pb); /* flags? */
1021 avio_rl32(pb); /* data size */
1023 size = pb->buf_end - pb->buf_ptr;
1024 pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
1028 memcpy(pd.buf, pb->buf_ptr, size);
1029 sub_demuxer = av_probe_input_format2(&pd, 1, &score);
1034 if (!(ast->sub_ctx = avformat_alloc_context()))
1037 ast->sub_ctx->pb = pb;
1038 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
1039 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
1040 *st->codec = *ast->sub_ctx->streams[0]->codec;
1041 ast->sub_ctx->streams[0]->codec->extradata = NULL;
1042 time_base = ast->sub_ctx->streams[0]->time_base;
1043 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
1045 ast->sub_buffer = pkt->data;
1046 memset(pkt, 0, sizeof(*pkt));
1055 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
1058 AVIStream *ast, *next_ast = next_st->priv_data;
1059 int64_t ts, next_ts, ts_min = INT64_MAX;
1060 AVStream *st, *sub_st = NULL;
1063 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
1066 for (i = 0; i < s->nb_streams; i++) {
1068 ast = st->priv_data;
1069 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
1070 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
1071 if (ts <= next_ts && ts < ts_min) {
1079 ast = sub_st->priv_data;
1080 *pkt = ast->sub_pkt;
1081 pkt->stream_index = sub_st->index;
1083 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
1084 ast->sub_pkt.data = NULL;
1089 static int get_stream_idx(unsigned *d)
1091 if (d[0] >= '0' && d[0] <= '9' &&
1092 d[1] >= '0' && d[1] <= '9') {
1093 return (d[0] - '0') * 10 + (d[1] - '0');
1095 return 100; // invalid stream ID
1101 * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
1103 static int avi_sync(AVFormatContext *s, int exit_early)
1105 AVIContext *avi = s->priv_data;
1106 AVIOContext *pb = s->pb;
1113 memset(d, -1, sizeof(d));
1114 for (i = sync = avio_tell(pb); !url_feof(pb); i++) {
1117 for (j = 0; j < 7; j++)
1121 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
1123 n = get_stream_idx(d + 2);
1124 av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
1125 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
1126 if (i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127)
1130 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
1132 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
1133 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
1134 avio_skip(pb, size);
1139 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
1144 n = avi->dv_demux ? 0 : get_stream_idx(d);
1146 if (!((i - avi->last_pkt_pos) & 1) &&
1147 get_stream_idx(d + 1) < s->nb_streams)
1150 // detect ##ix chunk and skip
1151 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
1152 avio_skip(pb, size);
1157 if (n < s->nb_streams) {
1161 ast = st->priv_data;
1164 av_log(s, AV_LOG_WARNING, "Skipping foreign stream %d packet\n", n);
1168 if (s->nb_streams >= 2) {
1169 AVStream *st1 = s->streams[1];
1170 AVIStream *ast1 = st1->priv_data;
1171 // workaround for broken small-file-bug402.avi
1172 if ( d[2] == 'w' && d[3] == 'b'
1174 && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
1175 && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
1176 && ast->prefix == 'd'*256+'c'
1177 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
1182 av_log(s, AV_LOG_WARNING,
1183 "Invalid stream + prefix combination, assuming audio.\n");
1187 if (!avi->dv_demux &&
1188 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
1189 // FIXME: needs a little reordering
1190 (st->discard >= AVDISCARD_NONKEY &&
1191 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1192 || st->discard >= AVDISCARD_ALL)) {
1194 ast->frame_offset += get_duration(ast, size);
1195 avio_skip(pb, size);
1200 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1201 int k = avio_r8(pb);
1202 int last = (k + avio_r8(pb) - 1) & 0xFF;
1204 avio_rl16(pb); // flags
1206 // b + (g << 8) + (r << 16);
1207 for (; k <= last; k++)
1208 ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;
1212 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1213 d[2] < 128 && d[3] < 128) ||
1214 d[2] * 256 + d[3] == ast->prefix /* ||
1215 (d[2] == 'd' && d[3] == 'c') ||
1216 (d[2] == 'w' && d[3] == 'b') */) {
1219 if (d[2] * 256 + d[3] == ast->prefix)
1220 ast->prefix_count++;
1222 ast->prefix = d[2] * 256 + d[3];
1223 ast->prefix_count = 0;
1226 avi->stream_index = n;
1227 ast->packet_size = size + 8;
1228 ast->remaining = size;
1231 uint64_t pos = avio_tell(pb) - 8;
1232 if (!st->index_entries || !st->nb_index_entries ||
1233 st->index_entries[st->nb_index_entries - 1].pos < pos) {
1234 av_add_index_entry(st, pos, ast->frame_offset, size,
1235 0, AVINDEX_KEYFRAME);
1248 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1250 AVIContext *avi = s->priv_data;
1251 AVIOContext *pb = s->pb;
1253 #if FF_API_DESTRUCT_PACKET
1257 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1258 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1265 if (avi->non_interleaved) {
1266 int best_stream_index = 0;
1267 AVStream *best_st = NULL;
1268 AVIStream *best_ast;
1269 int64_t best_ts = INT64_MAX;
1272 for (i = 0; i < s->nb_streams; i++) {
1273 AVStream *st = s->streams[i];
1274 AVIStream *ast = st->priv_data;
1275 int64_t ts = ast->frame_offset;
1278 if (!st->nb_index_entries)
1281 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1282 if (!ast->remaining && ts > last_ts)
1285 ts = av_rescale_q(ts, st->time_base,
1286 (AVRational) { FFMAX(1, ast->sample_size),
1289 av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
1290 st->time_base.num, st->time_base.den, ast->frame_offset);
1294 best_stream_index = i;
1300 best_ast = best_st->priv_data;
1301 best_ts = best_ast->frame_offset;
1302 if (best_ast->remaining) {
1303 i = av_index_search_timestamp(best_st,
1306 AVSEEK_FLAG_BACKWARD);
1308 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1310 best_ast->frame_offset = best_st->index_entries[i].timestamp;
1314 int64_t pos = best_st->index_entries[i].pos;
1315 pos += best_ast->packet_size - best_ast->remaining;
1316 if (avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
1319 av_assert0(best_ast->remaining <= best_ast->packet_size);
1321 avi->stream_index = best_stream_index;
1322 if (!best_ast->remaining)
1323 best_ast->packet_size =
1324 best_ast->remaining = best_st->index_entries[i].size;
1331 if (avi->stream_index >= 0) {
1332 AVStream *st = s->streams[avi->stream_index];
1333 AVIStream *ast = st->priv_data;
1336 if (get_subtitle_pkt(s, st, pkt))
1339 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1340 if (ast->sample_size <= 1)
1342 else if (ast->sample_size < 32)
1343 // arbitrary multiplier to avoid tiny packets for raw PCM data
1344 size = 1024 * ast->sample_size;
1346 size = ast->sample_size;
1348 if (size > ast->remaining)
1349 size = ast->remaining;
1350 avi->last_pkt_pos = avio_tell(pb);
1351 err = av_get_packet(pb, pkt, size);
1356 if (ast->has_pal && pkt->size < (unsigned)INT_MAX / 2) {
1358 pal = av_packet_new_side_data(pkt,
1359 AV_PKT_DATA_PALETTE,
1362 av_log(s, AV_LOG_ERROR,
1363 "Failed to allocate data for palette\n");
1365 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1370 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1371 AVBufferRef *avbuf = pkt->buf;
1372 #if FF_API_DESTRUCT_PACKET
1373 FF_DISABLE_DEPRECATION_WARNINGS
1374 dstr = pkt->destruct;
1375 FF_ENABLE_DEPRECATION_WARNINGS
1377 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1378 pkt->data, pkt->size, pkt->pos);
1379 #if FF_API_DESTRUCT_PACKET
1380 FF_DISABLE_DEPRECATION_WARNINGS
1381 pkt->destruct = dstr;
1382 FF_ENABLE_DEPRECATION_WARNINGS
1385 pkt->flags |= AV_PKT_FLAG_KEY;
1387 av_free_packet(pkt);
1388 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1389 !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1390 ast->frame_offset++;
1391 avi->stream_index = -1;
1395 /* XXX: How to handle B-frames in AVI? */
1396 pkt->dts = ast->frame_offset;
1397 // pkt->dts += ast->start;
1398 if (ast->sample_size)
1399 pkt->dts /= ast->sample_size;
1401 "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
1402 "base:%d st:%d size:%d\n",
1411 pkt->stream_index = avi->stream_index;
1413 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->index_entries) {
1417 index = av_index_search_timestamp(st, ast->frame_offset, AVSEEK_FLAG_ANY);
1418 e = &st->index_entries[index];
1420 if (index >= 0 && e->timestamp == ast->frame_offset) {
1421 if (index == st->nb_index_entries-1) {
1425 for (i=0; i<FFMIN(size,256); i++) {
1426 if (st->codec->codec_id == AV_CODEC_ID_MPEG4) {
1427 if (state == 0x1B6) {
1428 key= !(pkt->data[i]&0xC0);
1433 state= (state<<8) + pkt->data[i];
1436 e->flags &= ~AVINDEX_KEYFRAME;
1438 if (e->flags & AVINDEX_KEYFRAME)
1439 pkt->flags |= AV_PKT_FLAG_KEY;
1442 pkt->flags |= AV_PKT_FLAG_KEY;
1444 ast->frame_offset += get_duration(ast, pkt->size);
1446 ast->remaining -= err;
1447 if (!ast->remaining) {
1448 avi->stream_index = -1;
1449 ast->packet_size = 0;
1452 if (!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos) {
1453 av_free_packet(pkt);
1458 if (!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1) {
1459 int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
1461 if (avi->dts_max - dts > 2*AV_TIME_BASE) {
1462 avi->non_interleaved= 1;
1463 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
1464 }else if (avi->dts_max < dts)
1471 if ((err = avi_sync(s, 0)) < 0)
1476 /* XXX: We make the implicit supposition that the positions are sorted
1477 * for each stream. */
1478 static int avi_read_idx1(AVFormatContext *s, int size)
1480 AVIContext *avi = s->priv_data;
1481 AVIOContext *pb = s->pb;
1482 int nb_index_entries, i;
1485 unsigned int index, tag, flags, pos, len, first_packet = 1;
1486 unsigned last_pos = -1;
1487 unsigned last_idx = -1;
1488 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1491 nb_index_entries = size / 16;
1492 if (nb_index_entries <= 0)
1493 return AVERROR_INVALIDDATA;
1495 idx1_pos = avio_tell(pb);
1496 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1497 if (avi_sync(s, 1) == 0)
1498 first_packet_pos = avio_tell(pb) - 8;
1499 avi->stream_index = -1;
1500 avio_seek(pb, idx1_pos, SEEK_SET);
1502 if (s->nb_streams == 1 && s->streams[0]->codec->codec_tag == AV_RL32("MMES")) {
1503 first_packet_pos = 0;
1504 data_offset = avi->movi_list;
1507 /* Read the entries and sort them in each stream component. */
1508 for (i = 0; i < nb_index_entries; i++) {
1512 tag = avio_rl32(pb);
1513 flags = avio_rl32(pb);
1514 pos = avio_rl32(pb);
1515 len = avio_rl32(pb);
1516 av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1517 i, tag, flags, pos, len);
1519 index = ((tag & 0xff) - '0') * 10;
1520 index += (tag >> 8 & 0xff) - '0';
1521 if (index >= s->nb_streams)
1523 st = s->streams[index];
1524 ast = st->priv_data;
1526 if (first_packet && first_packet_pos) {
1527 data_offset = first_packet_pos - pos;
1532 av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1534 // even if we have only a single stream, we should
1535 // switch to non-interleaved to get correct timestamps
1536 if (last_pos == pos)
1537 avi->non_interleaved = 1;
1538 if (last_idx != pos && len) {
1539 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1540 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1543 ast->cum_len += get_duration(ast, len);
1545 anykey |= flags&AVIIF_INDEX;
1548 for (index = 0; index < s->nb_streams; index++) {
1549 st = s->streams[index];
1550 if (st->nb_index_entries)
1551 st->index_entries[0].flags |= AVINDEX_KEYFRAME;
1557 /* Scan the index and consider any file with streams more than
1558 * 2 seconds or 64MB apart non-interleaved. */
1559 static int check_stream_max_drift(AVFormatContext *s)
1561 int64_t min_pos, pos;
1563 int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
1565 return AVERROR(ENOMEM);
1566 for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
1567 int64_t max_dts = INT64_MIN / 2;
1568 int64_t min_dts = INT64_MAX / 2;
1569 int64_t max_buffer = 0;
1571 min_pos = INT64_MAX;
1573 for (i = 0; i < s->nb_streams; i++) {
1574 AVStream *st = s->streams[i];
1575 AVIStream *ast = st->priv_data;
1576 int n = st->nb_index_entries;
1577 while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
1581 dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
1582 FFMAX(ast->sample_size, 1),
1583 st->time_base, AV_TIME_BASE_Q);
1584 min_dts = FFMIN(min_dts, dts);
1585 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
1588 for (i = 0; i < s->nb_streams; i++) {
1589 AVStream *st = s->streams[i];
1590 AVIStream *ast = st->priv_data;
1592 if (idx[i] && min_dts != INT64_MAX / 2) {
1594 dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
1595 FFMAX(ast->sample_size, 1),
1596 st->time_base, AV_TIME_BASE_Q);
1597 max_dts = FFMAX(max_dts, dts);
1598 max_buffer = FFMAX(max_buffer,
1599 av_rescale(dts - min_dts,
1600 st->codec->bit_rate,
1604 if (max_dts - min_dts > 2 * AV_TIME_BASE ||
1605 max_buffer > 1024 * 1024 * 8 * 8) {
1614 static int guess_ni_flag(AVFormatContext *s)
1617 int64_t last_start = 0;
1618 int64_t first_end = INT64_MAX;
1619 int64_t oldpos = avio_tell(s->pb);
1621 for (i = 0; i < s->nb_streams; i++) {
1622 AVStream *st = s->streams[i];
1623 int n = st->nb_index_entries;
1630 int64_t pos = st->index_entries[0].pos;
1631 avio_seek(s->pb, pos + 4, SEEK_SET);
1632 size = avio_rl32(s->pb);
1633 if (pos + size > st->index_entries[1].pos)
1634 last_start = INT64_MAX;
1637 if (st->index_entries[0].pos > last_start)
1638 last_start = st->index_entries[0].pos;
1639 if (st->index_entries[n - 1].pos < first_end)
1640 first_end = st->index_entries[n - 1].pos;
1642 avio_seek(s->pb, oldpos, SEEK_SET);
1644 if (last_start > first_end)
1647 return check_stream_max_drift(s);
1650 static int avi_load_index(AVFormatContext *s)
1652 AVIContext *avi = s->priv_data;
1653 AVIOContext *pb = s->pb;
1655 int64_t pos = avio_tell(pb);
1659 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1660 goto the_end; // maybe truncated file
1661 av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1663 tag = avio_rl32(pb);
1664 size = avio_rl32(pb);
1667 next = avio_tell(pb) + size + (size & 1);
1669 av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1676 if (tag == MKTAG('i', 'd', 'x', '1') &&
1677 avi_read_idx1(s, size) >= 0) {
1678 avi->index_loaded=2;
1680 }else if (tag == MKTAG('L', 'I', 'S', 'T')) {
1681 uint32_t tag1 = avio_rl32(pb);
1683 if (tag1 == MKTAG('I', 'N', 'F', 'O'))
1684 ff_read_riff_info(s, size - 4);
1688 if (avio_seek(pb, next, SEEK_SET) < 0)
1689 break; // something is wrong here
1693 avio_seek(pb, pos, SEEK_SET);
1697 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1699 AVIStream *ast2 = st2->priv_data;
1700 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1701 av_free_packet(&ast2->sub_pkt);
1702 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1703 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1704 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1707 static int avi_read_seek(AVFormatContext *s, int stream_index,
1708 int64_t timestamp, int flags)
1710 AVIContext *avi = s->priv_data;
1713 int64_t pos, pos_min;
1716 /* Does not matter which stream is requested dv in avi has the
1717 * stream information in the first video stream.
1722 if (!avi->index_loaded) {
1723 /* we only load the index on demand */
1725 avi->index_loaded |= 1;
1727 av_assert0(stream_index >= 0);
1729 st = s->streams[stream_index];
1730 ast = st->priv_data;
1731 index = av_index_search_timestamp(st,
1732 timestamp * FFMAX(ast->sample_size, 1),
1735 if (st->nb_index_entries > 0)
1736 av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
1737 timestamp * FFMAX(ast->sample_size, 1),
1738 st->index_entries[0].timestamp,
1739 st->index_entries[st->nb_index_entries - 1].timestamp);
1740 return AVERROR_INVALIDDATA;
1743 /* find the position */
1744 pos = st->index_entries[index].pos;
1745 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1747 av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
1748 timestamp, index, st->index_entries[index].timestamp);
1750 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1751 /* One and only one real stream for DV in AVI, and it has video */
1752 /* offsets. Calling with other stream indexes should have failed */
1753 /* the av_index_search_timestamp call above. */
1755 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
1758 /* Feed the DV video stream version of the timestamp to the */
1759 /* DV demux so it can synthesize correct timestamps. */
1760 ff_dv_offset_reset(avi->dv_demux, timestamp);
1762 avi->stream_index = -1;
1767 for (i = 0; i < s->nb_streams; i++) {
1768 AVStream *st2 = s->streams[i];
1769 AVIStream *ast2 = st2->priv_data;
1772 ast2->remaining = 0;
1774 if (ast2->sub_ctx) {
1775 seek_subtitle(st, st2, timestamp);
1779 if (st2->nb_index_entries <= 0)
1782 // av_assert1(st2->codec->block_align);
1783 av_assert0(fabs(av_q2d(st2->time_base) - ast2->scale / (double)ast2->rate) < av_q2d(st2->time_base) * 0.00000001);
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,