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/opt.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/internal.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/mathematics.h"
37 #include "libavcodec/bytestream.h"
38 #include "libavcodec/exif.h"
39 #include "libavcodec/internal.h"
41 typedef struct AVIStream {
42 int64_t frame_offset; /* current frame (video) or byte (audio) counter
43 * (used to compute the pts) */
50 int sample_size; /* size of one sample (or packet)
51 * (in the rate/scale sense) in bytes */
53 int64_t cum_len; /* temporary storage (used during seek) */
54 int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
58 int dshow_block_align; /* block align variable used to emulate bugs in
59 * the MS dshow demuxer */
61 AVFormatContext *sub_ctx;
63 AVBufferRef *sub_buffer;
68 typedef struct AVIContext {
80 DVDemuxContext *dv_demux;
83 #define MAX_ODML_DEPTH 1000
88 static const AVOption options[] = {
89 { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
93 static const AVClass demuxer_class = {
95 .item_name = av_default_item_name,
97 .version = LIBAVUTIL_VERSION_INT,
98 .category = AV_CLASS_CATEGORY_DEMUXER,
102 static const char avi_headers[][8] = {
103 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
104 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
105 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
106 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
107 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
111 static const AVMetadataConv avi_metadata_conv[] = {
113 { "isbj", "subject" },
115 { "iart", "artist" },
116 { "icop", "copyright" },
117 { "icmt", "comment" },
119 { "iprd", "product" },
120 { "isft", "software" },
125 static int avi_read_close(AVFormatContext *s);
126 static int avi_load_index(AVFormatContext *s);
127 static int guess_ni_flag(AVFormatContext *s);
129 #define print_tag(s, str, tag, size) \
130 av_log(s, AV_LOG_TRACE, "pos:%"PRIX64" %s: tag=%s size=0x%x\n", \
131 avio_tell(pb), str, av_fourcc2str(tag), size) \
133 static inline int get_duration(AVIStream *ast, int len)
135 if (ast->sample_size)
137 else if (ast->dshow_block_align)
138 return (len + (int64_t)ast->dshow_block_align - 1) / ast->dshow_block_align;
143 static int get_riff(AVFormatContext *s, AVIOContext *pb)
145 AVIContext *avi = s->priv_data;
146 char header[8] = {0};
149 /* check RIFF header */
150 avio_read(pb, header, 4);
151 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
152 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
153 avio_read(pb, header + 4, 4);
155 for (i = 0; avi_headers[i][0]; i++)
156 if (!memcmp(header, avi_headers[i], 8))
158 if (!avi_headers[i][0])
159 return AVERROR_INVALIDDATA;
161 if (header[7] == 0x19)
162 av_log(s, AV_LOG_INFO,
163 "This file has been generated by a totally broken muxer.\n");
168 static int read_odml_index(AVFormatContext *s, int frame_num)
170 AVIContext *avi = s->priv_data;
171 AVIOContext *pb = s->pb;
172 int longs_per_entry = avio_rl16(pb);
173 int index_sub_type = avio_r8(pb);
174 int index_type = avio_r8(pb);
175 int entries_in_use = avio_rl32(pb);
176 int chunk_id = avio_rl32(pb);
177 int64_t base = avio_rl64(pb);
178 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
179 ((chunk_id >> 8 & 0xFF) - '0');
183 int64_t last_pos = -1;
184 int64_t filesize = avi->fsize;
186 av_log(s, AV_LOG_TRACE,
187 "longs_per_entry:%d index_type:%d entries_in_use:%d "
188 "chunk_id:%X base:%16"PRIX64" frame_num:%d\n",
196 if (stream_id >= s->nb_streams || stream_id < 0)
197 return AVERROR_INVALIDDATA;
198 st = s->streams[stream_id];
202 return AVERROR_INVALIDDATA;
206 if (index_type && longs_per_entry != 2)
207 return AVERROR_INVALIDDATA;
209 return AVERROR_INVALIDDATA;
211 if (filesize > 0 && base >= filesize) {
212 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
213 if (base >> 32 == (base & 0xFFFFFFFF) &&
214 (base & 0xFFFFFFFF) < filesize &&
215 filesize <= 0xFFFFFFFF)
218 return AVERROR_INVALIDDATA;
221 for (i = 0; i < entries_in_use; i++) {
223 int64_t pos = avio_rl32(pb) + base - 8;
224 int len = avio_rl32(pb);
228 av_log(s, AV_LOG_TRACE, "pos:%"PRId64", len:%X\n", pos, len);
231 return AVERROR_INVALIDDATA;
233 if (last_pos == pos || pos == base - 8)
234 avi->non_interleaved = 1;
235 if (last_pos != pos && len)
236 av_add_index_entry(st, pos, ast->cum_len, len, 0,
237 key ? AVINDEX_KEYFRAME : 0);
239 ast->cum_len += get_duration(ast, len);
244 offset = avio_rl64(pb);
245 avio_rl32(pb); /* size */
246 duration = avio_rl32(pb);
249 return AVERROR_INVALIDDATA;
253 if (avi->odml_depth > MAX_ODML_DEPTH) {
254 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
255 return AVERROR_INVALIDDATA;
258 if (avio_seek(pb, offset + 8, SEEK_SET) < 0)
261 read_odml_index(s, frame_num);
263 frame_num += duration;
265 if (avio_seek(pb, pos, SEEK_SET) < 0) {
266 av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index\n");
272 avi->index_loaded = 2;
276 static void clean_index(AVFormatContext *s)
281 for (i = 0; i < s->nb_streams; i++) {
282 AVStream *st = s->streams[i];
283 AVIStream *ast = st->priv_data;
284 int n = st->internal->nb_index_entries;
285 int max = ast->sample_size;
286 int64_t pos, size, ts;
288 if (n != 1 || ast->sample_size == 0)
294 pos = st->internal->index_entries[0].pos;
295 size = st->internal->index_entries[0].size;
296 ts = st->internal->index_entries[0].timestamp;
298 for (j = 0; j < size; j += max)
299 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
304 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
307 AVIOContext *pb = s->pb;
313 if (size == UINT_MAX)
314 return AVERROR(EINVAL);
315 value = av_malloc(size + 1);
317 return AVERROR(ENOMEM);
318 if (avio_read(pb, value, size) != size) {
320 return AVERROR_INVALIDDATA;
326 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
327 AV_DICT_DONT_STRDUP_VAL);
330 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
331 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
333 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
335 char month[4], time[9], buffer[64];
337 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
338 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
339 month, &day, time, &year) == 4) {
340 for (i = 0; i < 12; i++)
341 if (!av_strcasecmp(month, months[i])) {
342 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
343 year, i + 1, day, time);
344 av_dict_set(metadata, "creation_time", buffer, 0);
346 } else if (date[4] == '/' && date[7] == '/') {
347 date[4] = date[7] = '-';
348 av_dict_set(metadata, "creation_time", date, 0);
352 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
354 while (avio_tell(s->pb) < end && !avio_feof(s->pb)) {
355 uint32_t tag = avio_rl32(s->pb);
356 uint32_t size = avio_rl32(s->pb);
358 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
360 uint64_t tag_end = avio_tell(s->pb) + size;
361 while (avio_tell(s->pb) < tag_end && !avio_feof(s->pb)) {
362 uint16_t tag = avio_rl16(s->pb);
363 uint16_t size = avio_rl16(s->pb);
364 const char *name = NULL;
365 char buffer[64] = { 0 };
366 size = FFMIN(size, tag_end - avio_tell(s->pb));
367 size -= avio_read(s->pb, buffer,
368 FFMIN(size, sizeof(buffer) - 1));
377 name = "creation_time";
378 if (buffer[4] == ':' && buffer[7] == ':')
379 buffer[4] = buffer[7] = '-';
383 av_dict_set(&s->metadata, name, buffer, 0);
384 avio_skip(s->pb, size);
389 avio_skip(s->pb, size);
395 static int avi_extract_stream_metadata(AVFormatContext *s, AVStream *st)
398 uint8_t *data = st->codecpar->extradata;
399 int data_size = st->codecpar->extradata_size;
402 if (!data || data_size < 8) {
403 return AVERROR_INVALIDDATA;
406 bytestream2_init(&gb, data, data_size);
408 tag = bytestream2_get_le32(&gb);
411 case MKTAG('A', 'V', 'I', 'F'):
412 // skip 4 byte padding
413 bytestream2_skip(&gb, 4);
414 offset = bytestream2_tell(&gb);
416 // decode EXIF tags from IFD, AVI is always little-endian
417 return avpriv_exif_decode_ifd(s, data + offset, data_size - offset,
418 1, 0, &st->metadata);
420 case MKTAG('C', 'A', 'S', 'I'):
421 avpriv_request_sample(s, "RIFF stream data tag type CASI (%u)", tag);
423 case MKTAG('Z', 'o', 'r', 'a'):
424 avpriv_request_sample(s, "RIFF stream data tag type Zora (%u)", tag);
433 static int calculate_bitrate(AVFormatContext *s)
435 AVIContext *avi = s->priv_data;
440 for (i = 0; i<s->nb_streams; i++) {
442 AVStream *st = s->streams[i];
444 if (!st->internal->nb_index_entries)
447 for (j = 0; j < st->internal->nb_index_entries; j++)
448 len += st->internal->index_entries[j].size;
449 maxpos = FFMAX(maxpos, st->internal->index_entries[j-1].pos);
452 if (maxpos < av_rescale(avi->io_fsize, 9, 10)) // index does not cover the whole file
454 if (lensum*9/10 > maxpos || lensum < maxpos*9/10) // frame sum and filesize mismatch
457 for (i = 0; i<s->nb_streams; i++) {
459 AVStream *st = s->streams[i];
463 for (j = 0; j < st->internal->nb_index_entries; j++)
464 len += st->internal->index_entries[j].size;
466 if (st->internal->nb_index_entries < 2 || st->codecpar->bit_rate > 0)
468 duration = st->internal->index_entries[j-1].timestamp - st->internal->index_entries[0].timestamp;
469 bitrate = av_rescale(8*len, st->time_base.den, duration * st->time_base.num);
471 st->codecpar->bit_rate = bitrate;
477 #define RETURN_ERROR(code) do { ret = (code); goto fail; } while (0)
478 static int avi_read_header(AVFormatContext *s)
480 AVIContext *avi = s->priv_data;
481 AVIOContext *pb = s->pb;
482 unsigned int tag, tag1, handler;
483 int codec_type, stream_index, frame_period;
487 AVIStream *ast = NULL;
488 int avih_width = 0, avih_height = 0;
489 int amv_file_format = 0;
490 uint64_t list_end = 0;
493 AVDictionaryEntry *dict_entry;
495 avi->stream_index = -1;
497 ret = get_riff(s, pb);
501 av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
503 avi->io_fsize = avi->fsize = avio_size(pb);
504 if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
505 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
513 RETURN_ERROR(AVERROR_INVALIDDATA);
515 size = avio_rl32(pb);
517 print_tag(s, "tag", tag, size);
520 case MKTAG('L', 'I', 'S', 'T'):
521 list_end = avio_tell(pb) + size;
522 /* Ignored, except at start of video packets. */
523 tag1 = avio_rl32(pb);
525 print_tag(s, "list", tag1, 0);
527 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
528 avi->movi_list = avio_tell(pb) - 4;
530 avi->movi_end = avi->movi_list + size + (size & 1);
532 avi->movi_end = avi->fsize;
533 av_log(s, AV_LOG_TRACE, "movi end=%"PRIx64"\n", avi->movi_end);
535 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
536 ff_read_riff_info(s, size - 4);
537 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
538 avi_read_nikon(s, list_end);
541 case MKTAG('I', 'D', 'I', 'T'):
543 unsigned char date[64] = { 0 };
545 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
547 avi_metadata_creation_time(&s->metadata, date);
550 case MKTAG('d', 'm', 'l', 'h'):
552 avio_skip(pb, size + (size & 1));
554 case MKTAG('a', 'm', 'v', 'h'):
556 case MKTAG('a', 'v', 'i', 'h'):
558 /* using frame_period is bad idea */
559 frame_period = avio_rl32(pb);
560 avio_rl32(pb); /* max. bytes per second */
562 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
564 avio_skip(pb, 2 * 4);
567 avih_width = avio_rl32(pb);
568 avih_height = avio_rl32(pb);
570 avio_skip(pb, size - 10 * 4);
572 case MKTAG('s', 't', 'r', 'h'):
575 tag1 = avio_rl32(pb);
576 handler = avio_rl32(pb); /* codec tag */
578 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
579 avio_skip(pb, size - 8);
583 st = avformat_new_stream(s, NULL);
585 RETURN_ERROR(AVERROR(ENOMEM));
587 st->id = stream_index;
588 ast = av_mallocz(sizeof(AVIStream));
590 RETURN_ERROR(AVERROR(ENOMEM));
594 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
595 : MKTAG('v', 'i', 'd', 's');
597 print_tag(s, "strh", tag1, -1);
599 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
600 tag1 == MKTAG('i', 'v', 'a', 's')) {
603 /* After some consideration -- I don't think we
604 * have to support anything but DV in type1 AVIs. */
605 if (s->nb_streams != 1)
606 RETURN_ERROR(AVERROR_INVALIDDATA);
608 if (handler != MKTAG('d', 'v', 's', 'd') &&
609 handler != MKTAG('d', 'v', 'h', 'd') &&
610 handler != MKTAG('d', 'v', 's', 'l'))
611 return AVERROR_INVALIDDATA;
613 if (!CONFIG_DV_DEMUXER)
614 return AVERROR_DEMUXER_NOT_FOUND;
616 ast = s->streams[0]->priv_data;
617 st->priv_data = NULL;
618 ff_free_stream(s, st);
620 avi->dv_demux = avpriv_dv_init_demux(s);
621 if (!avi->dv_demux) {
623 return AVERROR(ENOMEM);
626 s->streams[0]->priv_data = ast;
627 avio_skip(pb, 3 * 4);
628 ast->scale = avio_rl32(pb);
629 ast->rate = avio_rl32(pb);
630 avio_skip(pb, 4); /* start time */
632 dv_dur = avio_rl32(pb);
633 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
634 dv_dur *= AV_TIME_BASE;
635 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
637 /* else, leave duration alone; timing estimation in utils.c
638 * will make a guess based on bitrate. */
640 stream_index = s->nb_streams - 1;
641 avio_skip(pb, size - 9 * 4);
645 av_assert0(stream_index < s->nb_streams);
646 ast->handler = handler;
648 avio_rl32(pb); /* flags */
649 avio_rl16(pb); /* priority */
650 avio_rl16(pb); /* language */
651 avio_rl32(pb); /* initial frame */
652 ast->scale = avio_rl32(pb);
653 ast->rate = avio_rl32(pb);
654 if (!(ast->scale && ast->rate)) {
655 av_log(s, AV_LOG_WARNING,
656 "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
657 "(This file has been generated by broken software.)\n",
662 ast->scale = frame_period;
668 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
670 ast->cum_len = avio_rl32(pb); /* start */
671 st->nb_frames = avio_rl32(pb);
674 avio_rl32(pb); /* buffer size */
675 avio_rl32(pb); /* quality */
676 if (ast->cum_len > 3600LL * ast->rate / ast->scale) {
677 av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
680 ast->sample_size = avio_rl32(pb);
681 ast->cum_len *= FFMAX(1, ast->sample_size);
682 av_log(s, AV_LOG_TRACE, "%"PRIu32" %"PRIu32" %d\n",
683 ast->rate, ast->scale, ast->sample_size);
686 case MKTAG('v', 'i', 'd', 's'):
687 codec_type = AVMEDIA_TYPE_VIDEO;
689 ast->sample_size = 0;
690 st->avg_frame_rate = av_inv_q(st->time_base);
692 case MKTAG('a', 'u', 'd', 's'):
693 codec_type = AVMEDIA_TYPE_AUDIO;
695 case MKTAG('t', 'x', 't', 's'):
696 codec_type = AVMEDIA_TYPE_SUBTITLE;
698 case MKTAG('d', 'a', 't', 's'):
699 codec_type = AVMEDIA_TYPE_DATA;
702 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
705 if (ast->sample_size < 0) {
706 if (s->error_recognition & AV_EF_EXPLODE) {
707 av_log(s, AV_LOG_ERROR,
708 "Invalid sample_size %d at stream %d\n",
711 RETURN_ERROR(AVERROR_INVALIDDATA);
713 av_log(s, AV_LOG_WARNING,
714 "Invalid sample_size %d at stream %d "
718 ast->sample_size = 0;
721 if (ast->sample_size == 0) {
722 st->duration = st->nb_frames;
723 if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) {
724 av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n");
725 st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end);
728 ast->frame_offset = ast->cum_len;
729 avio_skip(pb, size - 12 * 4);
731 case MKTAG('s', 't', 'r', 'f'):
733 if (!size && (codec_type == AVMEDIA_TYPE_AUDIO ||
734 codec_type == AVMEDIA_TYPE_VIDEO))
736 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
739 uint64_t cur_pos = avio_tell(pb);
741 if (cur_pos < list_end)
742 size = FFMIN(size, list_end - cur_pos);
743 st = s->streams[stream_index];
744 if (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN) {
748 switch (codec_type) {
749 case AVMEDIA_TYPE_VIDEO:
750 if (amv_file_format) {
751 st->codecpar->width = avih_width;
752 st->codecpar->height = avih_height;
753 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
754 st->codecpar->codec_id = AV_CODEC_ID_AMV;
758 tag1 = ff_get_bmp_header(pb, st, &esize);
760 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
761 tag1 == MKTAG('D', 'X', 'S', 'A')) {
762 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
763 st->codecpar->codec_tag = tag1;
764 st->codecpar->codec_id = AV_CODEC_ID_XSUB;
768 if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) {
769 if (esize == size-1 && (esize&1)) {
770 st->codecpar->extradata_size = esize - 10 * 4;
772 st->codecpar->extradata_size = size - 10 * 4;
773 if (st->codecpar->extradata) {
774 av_log(s, AV_LOG_WARNING, "New extradata in strf chunk, freeing previous one.\n");
776 ret = ff_get_extradata(s, st->codecpar, pb,
777 st->codecpar->extradata_size);
782 // FIXME: check if the encoder really did this correctly
783 if (st->codecpar->extradata_size & 1)
786 /* Extract palette from extradata if bpp <= 8.
787 * This code assumes that extradata contains only palette.
788 * This is true for all paletted codecs implemented in
790 if (st->codecpar->extradata_size &&
791 (st->codecpar->bits_per_coded_sample <= 8)) {
792 int pal_size = (1 << st->codecpar->bits_per_coded_sample) << 2;
793 const uint8_t *pal_src;
795 pal_size = FFMIN(pal_size, st->codecpar->extradata_size);
796 pal_src = st->codecpar->extradata +
797 st->codecpar->extradata_size - pal_size;
798 /* Exclude the "BottomUp" field from the palette */
799 if (pal_src - st->codecpar->extradata >= 9 &&
800 !memcmp(st->codecpar->extradata + st->codecpar->extradata_size - 9, "BottomUp", 9))
802 for (i = 0; i < pal_size / 4; i++)
803 ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src + 4 * i);
807 print_tag(s, "video", tag1, 0);
809 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
810 st->codecpar->codec_tag = tag1;
811 st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
813 /* If codec is not found yet, try with the mov tags. */
814 if (!st->codecpar->codec_id) {
815 st->codecpar->codec_id =
816 ff_codec_get_id(ff_codec_movvideo_tags, tag1);
817 if (st->codecpar->codec_id)
818 av_log(s, AV_LOG_WARNING,
819 "mov tag found in avi (fourcc %s)\n",
820 av_fourcc2str(tag1));
822 if (!st->codecpar->codec_id)
823 st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags_unofficial, tag1);
825 /* This is needed to get the pict type which is necessary
826 * for generating correct pts. */
827 st->need_parsing = AVSTREAM_PARSE_HEADERS;
829 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4 &&
830 ast->handler == MKTAG('X', 'V', 'I', 'D'))
831 st->codecpar->codec_tag = MKTAG('X', 'V', 'I', 'D');
833 if (st->codecpar->codec_tag == MKTAG('V', 'S', 'S', 'H'))
834 st->need_parsing = AVSTREAM_PARSE_FULL;
835 if (st->codecpar->codec_id == AV_CODEC_ID_RV40)
836 st->need_parsing = AVSTREAM_PARSE_NONE;
837 if (st->codecpar->codec_id == AV_CODEC_ID_HEVC &&
838 st->codecpar->codec_tag == MKTAG('H', '2', '6', '5'))
839 st->need_parsing = AVSTREAM_PARSE_FULL;
841 if (st->codecpar->codec_id == AV_CODEC_ID_AVRN &&
842 st->codecpar->codec_tag == MKTAG('A', 'V', 'R', 'n') &&
843 (st->codecpar->extradata_size < 31 ||
844 memcmp(&st->codecpar->extradata[28], "1:1", 3)))
845 st->codecpar->codec_id = AV_CODEC_ID_MJPEG;
847 if (st->codecpar->codec_tag == 0 && st->codecpar->height > 0 &&
848 st->codecpar->extradata_size < 1U << 30) {
849 st->codecpar->extradata_size += 9;
850 if ((ret = av_reallocp(&st->codecpar->extradata,
851 st->codecpar->extradata_size +
852 AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {
853 st->codecpar->extradata_size = 0;
856 memcpy(st->codecpar->extradata + st->codecpar->extradata_size - 9,
859 st->codecpar->height = FFABS(st->codecpar->height);
861 // avio_skip(pb, size - 5 * 4);
863 case AVMEDIA_TYPE_AUDIO:
864 ret = ff_get_wav_header(s, pb, st->codecpar, size, 0);
867 ast->dshow_block_align = st->codecpar->block_align;
868 if (ast->sample_size && st->codecpar->block_align &&
869 ast->sample_size != st->codecpar->block_align) {
872 "sample size (%d) != block align (%d)\n",
874 st->codecpar->block_align);
875 ast->sample_size = st->codecpar->block_align;
878 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
881 /* Force parsing as several audio frames can be in
882 * one packet and timestamps refer to packet start. */
883 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
884 /* ADTS header is in extradata, AAC without header must be
885 * stored as exact frames. Parser not needed and it will
887 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
888 st->codecpar->extradata_size)
889 st->need_parsing = AVSTREAM_PARSE_NONE;
890 // The flac parser does not work with AVSTREAM_PARSE_TIMESTAMPS
891 if (st->codecpar->codec_id == AV_CODEC_ID_FLAC)
892 st->need_parsing = AVSTREAM_PARSE_NONE;
893 /* AVI files with Xan DPCM audio (wrongly) declare PCM
894 * audio in the header but have Axan as stream_code_tag. */
895 if (ast->handler == AV_RL32("Axan")) {
896 st->codecpar->codec_id = AV_CODEC_ID_XAN_DPCM;
897 st->codecpar->codec_tag = 0;
898 ast->dshow_block_align = 0;
900 if (amv_file_format) {
901 st->codecpar->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
902 ast->dshow_block_align = 0;
904 if ((st->codecpar->codec_id == AV_CODEC_ID_AAC ||
905 st->codecpar->codec_id == AV_CODEC_ID_FLAC ||
906 st->codecpar->codec_id == AV_CODEC_ID_MP2 ) && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
907 av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
908 ast->dshow_block_align = 0;
910 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
911 st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
912 st->codecpar->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
913 av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
914 ast->sample_size = 0;
917 case AVMEDIA_TYPE_SUBTITLE:
918 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
919 st->internal->request_probe= 1;
923 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
924 st->codecpar->codec_id = AV_CODEC_ID_NONE;
925 st->codecpar->codec_tag = 0;
931 case MKTAG('s', 't', 'r', 'd'):
932 if (stream_index >= (unsigned)s->nb_streams
933 || s->streams[stream_index]->codecpar->extradata_size
934 || s->streams[stream_index]->codecpar->codec_tag == MKTAG('H','2','6','4')) {
937 uint64_t cur_pos = avio_tell(pb);
938 if (cur_pos < list_end)
939 size = FFMIN(size, list_end - cur_pos);
940 st = s->streams[stream_index];
943 if (st->codecpar->extradata) {
944 av_log(s, AV_LOG_WARNING, "New extradata in strd chunk, freeing previous one.\n");
946 if ((ret = ff_get_extradata(s, st->codecpar, pb, size)) < 0)
950 if (st->codecpar->extradata_size & 1) //FIXME check if the encoder really did this correctly
953 ret = avi_extract_stream_metadata(s, st);
955 av_log(s, AV_LOG_WARNING, "could not decoding EXIF data in stream header.\n");
959 case MKTAG('i', 'n', 'd', 'x'):
961 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !(s->flags & AVFMT_FLAG_IGNIDX) &&
963 read_odml_index(s, 0) < 0 &&
964 (s->error_recognition & AV_EF_EXPLODE))
965 RETURN_ERROR(AVERROR_INVALIDDATA);
966 avio_seek(pb, pos + size, SEEK_SET);
968 case MKTAG('v', 'p', 'r', 'p'):
969 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
970 AVRational active, active_aspect;
972 st = s->streams[stream_index];
979 active_aspect.den = avio_rl16(pb);
980 active_aspect.num = avio_rl16(pb);
981 active.num = avio_rl32(pb);
982 active.den = avio_rl32(pb);
983 avio_rl32(pb); // nbFieldsPerFrame
985 if (active_aspect.num && active_aspect.den &&
986 active.num && active.den) {
987 st->sample_aspect_ratio = av_div_q(active_aspect, active);
988 av_log(s, AV_LOG_TRACE, "vprp %d/%d %d/%d\n",
989 active_aspect.num, active_aspect.den,
990 active.num, active.den);
996 case MKTAG('s', 't', 'r', 'n'):
997 case MKTAG('i', 's', 'b', 'j'):
998 case MKTAG('i', 'n', 'a', 'm'):
999 case MKTAG('i', 'a', 'r', 't'):
1000 case MKTAG('i', 'c', 'o', 'p'):
1001 case MKTAG('i', 'c', 'm', 't'):
1002 case MKTAG('i', 'g', 'n', 'r'):
1003 case MKTAG('i', 'p', 'o', 'd'):
1004 case MKTAG('i', 's', 'o', 'f'):
1005 if (s->nb_streams) {
1006 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
1012 if (size > 1000000) {
1013 av_log(s, AV_LOG_ERROR,
1014 "Something went wrong during header parsing, "
1015 "tag %s has size %u, "
1016 "I will ignore it and try to continue anyway.\n",
1017 av_fourcc2str(tag), size);
1018 if (s->error_recognition & AV_EF_EXPLODE)
1019 RETURN_ERROR(AVERROR_INVALIDDATA);
1020 avi->movi_list = avio_tell(pb) - 4;
1021 avi->movi_end = avi->fsize;
1024 /* Do not fail for very large idx1 tags */
1025 case MKTAG('i', 'd', 'x', '1'):
1028 avio_skip(pb, size);
1034 /* check stream number */
1035 if (stream_index != s->nb_streams - 1) {
1036 RETURN_ERROR(AVERROR_INVALIDDATA);
1039 if (!avi->index_loaded && (pb->seekable & AVIO_SEEKABLE_NORMAL))
1041 calculate_bitrate(s);
1042 avi->index_loaded |= 1;
1044 if ((ret = guess_ni_flag(s)) < 0)
1047 avi->non_interleaved |= ret | (s->flags & AVFMT_FLAG_SORT_DTS);
1049 dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0);
1050 if (dict_entry && !strcmp(dict_entry->value, "PotEncoder"))
1051 for (i = 0; i < s->nb_streams; i++) {
1052 AVStream *st = s->streams[i];
1053 if ( st->codecpar->codec_id == AV_CODEC_ID_MPEG1VIDEO
1054 || st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1055 st->need_parsing = AVSTREAM_PARSE_FULL;
1058 for (i = 0; i < s->nb_streams; i++) {
1059 AVStream *st = s->streams[i];
1060 if (st->internal->nb_index_entries)
1063 // DV-in-AVI cannot be non-interleaved, if set this must be
1066 avi->non_interleaved = 0;
1067 if (i == s->nb_streams && avi->non_interleaved) {
1068 av_log(s, AV_LOG_WARNING,
1069 "Non-interleaved AVI without index, switching to interleaved\n");
1070 avi->non_interleaved = 0;
1073 if (avi->non_interleaved) {
1074 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
1078 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
1079 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
1087 static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1089 if (pkt->size >= 7 &&
1090 pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
1091 !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
1093 int score = AVPROBE_SCORE_EXTENSION, ret;
1094 AVIStream *ast = st->priv_data;
1095 ff_const59 AVInputFormat *sub_demuxer;
1096 AVRational time_base;
1099 unsigned int desc_len;
1100 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
1102 0, NULL, NULL, NULL, NULL);
1106 desc_len = avio_rl32(pb);
1108 if (desc_len > pb->buf_end - pb->buf_ptr)
1111 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
1112 avio_skip(pb, desc_len - ret);
1114 av_dict_set(&st->metadata, "title", desc, 0);
1116 avio_rl16(pb); /* flags? */
1117 avio_rl32(pb); /* data size */
1119 size = pb->buf_end - pb->buf_ptr;
1120 pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
1124 memcpy(pd.buf, pb->buf_ptr, size);
1125 sub_demuxer = av_probe_input_format2(&pd, 1, &score);
1130 if (strcmp(sub_demuxer->name, "srt") && strcmp(sub_demuxer->name, "ass"))
1133 if (!(ast->sub_ctx = avformat_alloc_context()))
1136 ast->sub_ctx->pb = pb;
1138 if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0)
1141 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
1142 if (ast->sub_ctx->nb_streams != 1)
1144 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
1145 avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
1146 time_base = ast->sub_ctx->streams[0]->time_base;
1147 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
1149 ast->sub_buffer = pkt->buf;
1151 av_packet_unref(pkt);
1155 av_freep(&ast->sub_ctx);
1156 avio_context_free(&pb);
1161 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
1164 AVIStream *ast, *next_ast = next_st->priv_data;
1165 int64_t ts, next_ts, ts_min = INT64_MAX;
1166 AVStream *st, *sub_st = NULL;
1169 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
1172 for (i = 0; i < s->nb_streams; i++) {
1174 ast = st->priv_data;
1175 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
1176 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
1177 if (ts <= next_ts && ts < ts_min) {
1185 ast = sub_st->priv_data;
1186 *pkt = ast->sub_pkt;
1187 pkt->stream_index = sub_st->index;
1189 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
1190 ast->sub_pkt.data = NULL;
1195 static int get_stream_idx(const unsigned *d)
1197 if (d[0] >= '0' && d[0] <= '9' &&
1198 d[1] >= '0' && d[1] <= '9') {
1199 return (d[0] - '0') * 10 + (d[1] - '0');
1201 return 100; // invalid stream ID
1207 * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
1209 static int avi_sync(AVFormatContext *s, int exit_early)
1211 AVIContext *avi = s->priv_data;
1212 AVIOContext *pb = s->pb;
1219 memset(d, -1, sizeof(d));
1220 for (i = sync = avio_tell(pb); !avio_feof(pb); i++) {
1223 for (j = 0; j < 7; j++)
1227 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
1229 n = get_stream_idx(d + 2);
1230 ff_tlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
1231 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
1232 if (i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127)
1236 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
1238 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
1239 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1') ||
1240 (d[0] == 'i' && d[1] == 'n' && d[2] == 'd' && d[3] == 'x')) {
1241 avio_skip(pb, size);
1246 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
1251 n = get_stream_idx(d);
1253 if (!((i - avi->last_pkt_pos) & 1) &&
1254 get_stream_idx(d + 1) < s->nb_streams)
1257 // detect ##ix chunk and skip
1258 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
1259 avio_skip(pb, size);
1263 if (d[2] == 'w' && d[3] == 'c' && n < s->nb_streams) {
1264 avio_skip(pb, 16 * 3 + 8);
1268 if (avi->dv_demux && n != 0)
1272 if (n < s->nb_streams) {
1276 ast = st->priv_data;
1279 av_log(s, AV_LOG_WARNING, "Skipping foreign stream %d packet\n", n);
1283 if (s->nb_streams >= 2) {
1284 AVStream *st1 = s->streams[1];
1285 AVIStream *ast1 = st1->priv_data;
1286 // workaround for broken small-file-bug402.avi
1287 if ( d[2] == 'w' && d[3] == 'b'
1289 && st ->codecpar->codec_type == AVMEDIA_TYPE_VIDEO
1290 && st1->codecpar->codec_type == AVMEDIA_TYPE_AUDIO
1291 && ast->prefix == 'd'*256+'c'
1292 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
1297 av_log(s, AV_LOG_WARNING,
1298 "Invalid stream + prefix combination, assuming audio.\n");
1302 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1303 int k = avio_r8(pb);
1304 int last = (k + avio_r8(pb) - 1) & 0xFF;
1306 avio_rl16(pb); // flags
1308 // b + (g << 8) + (r << 16);
1309 for (; k <= last; k++)
1310 ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;
1314 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1315 d[2] < 128 && d[3] < 128) ||
1316 d[2] * 256 + d[3] == ast->prefix /* ||
1317 (d[2] == 'd' && d[3] == 'c') ||
1318 (d[2] == 'w' && d[3] == 'b') */) {
1321 if (d[2] * 256 + d[3] == ast->prefix)
1322 ast->prefix_count++;
1324 ast->prefix = d[2] * 256 + d[3];
1325 ast->prefix_count = 0;
1328 if (!avi->dv_demux &&
1329 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
1330 // FIXME: needs a little reordering
1331 (st->discard >= AVDISCARD_NONKEY &&
1332 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1333 || st->discard >= AVDISCARD_ALL)) {
1335 ast->frame_offset += get_duration(ast, size);
1336 avio_skip(pb, size);
1340 avi->stream_index = n;
1341 ast->packet_size = size + 8;
1342 ast->remaining = size;
1345 uint64_t pos = avio_tell(pb) - 8;
1346 if (!st->internal->index_entries || !st->internal->nb_index_entries ||
1347 st->internal->index_entries[st->internal->nb_index_entries - 1].pos < pos) {
1348 av_add_index_entry(st, pos, ast->frame_offset, size,
1349 0, AVINDEX_KEYFRAME);
1362 static int ni_prepare_read(AVFormatContext *s)
1364 AVIContext *avi = s->priv_data;
1365 int best_stream_index = 0;
1366 AVStream *best_st = NULL;
1367 AVIStream *best_ast;
1368 int64_t best_ts = INT64_MAX;
1371 for (i = 0; i < s->nb_streams; i++) {
1372 AVStream *st = s->streams[i];
1373 AVIStream *ast = st->priv_data;
1374 int64_t ts = ast->frame_offset;
1377 if (!st->internal->nb_index_entries)
1380 last_ts = st->internal->index_entries[st->internal->nb_index_entries - 1].timestamp;
1381 if (!ast->remaining && ts > last_ts)
1384 ts = av_rescale_q(ts, st->time_base,
1385 (AVRational) { FFMAX(1, ast->sample_size),
1388 av_log(s, AV_LOG_TRACE, "%"PRId64" %d/%d %"PRId64"\n", ts,
1389 st->time_base.num, st->time_base.den, ast->frame_offset);
1393 best_stream_index = i;
1399 best_ast = best_st->priv_data;
1400 best_ts = best_ast->frame_offset;
1401 if (best_ast->remaining) {
1402 i = av_index_search_timestamp(best_st,
1405 AVSEEK_FLAG_BACKWARD);
1407 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1409 best_ast->frame_offset = best_st->internal->index_entries[i].timestamp;
1413 int64_t pos = best_st->internal->index_entries[i].pos;
1414 pos += best_ast->packet_size - best_ast->remaining;
1415 if (avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
1418 av_assert0(best_ast->remaining <= best_ast->packet_size);
1420 avi->stream_index = best_stream_index;
1421 if (!best_ast->remaining)
1422 best_ast->packet_size =
1423 best_ast->remaining = best_st->internal->index_entries[i].size;
1431 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1433 AVIContext *avi = s->priv_data;
1434 AVIOContext *pb = s->pb;
1437 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1438 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1445 if (avi->non_interleaved) {
1446 err = ni_prepare_read(s);
1452 if (avi->stream_index >= 0) {
1453 AVStream *st = s->streams[avi->stream_index];
1454 AVIStream *ast = st->priv_data;
1455 int dv_demux = CONFIG_DV_DEMUXER && avi->dv_demux;
1458 if (get_subtitle_pkt(s, st, pkt))
1461 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1462 if (ast->sample_size <= 1)
1464 else if (ast->sample_size < 32)
1465 // arbitrary multiplier to avoid tiny packets for raw PCM data
1466 size = 1024 * ast->sample_size;
1468 size = ast->sample_size;
1470 if (size > ast->remaining)
1471 size = ast->remaining;
1472 avi->last_pkt_pos = avio_tell(pb);
1473 err = av_get_packet(pb, pkt, size);
1478 if (ast->has_pal && pkt->size < (unsigned)INT_MAX / 2 && !dv_demux) {
1480 pal = av_packet_new_side_data(pkt,
1481 AV_PKT_DATA_PALETTE,
1484 av_log(s, AV_LOG_ERROR,
1485 "Failed to allocate data for palette\n");
1487 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1492 if (CONFIG_DV_DEMUXER && dv_demux) {
1493 AVBufferRef *avbuf = pkt->buf;
1494 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1495 pkt->data, pkt->size, pkt->pos);
1497 pkt->flags |= AV_PKT_FLAG_KEY;
1499 av_packet_unref(pkt);
1500 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1501 !st->codecpar->codec_tag && read_gab2_sub(s, st, pkt)) {
1502 ast->frame_offset++;
1503 avi->stream_index = -1;
1507 /* XXX: How to handle B-frames in AVI? */
1508 pkt->dts = ast->frame_offset;
1509 // pkt->dts += ast->start;
1510 if (ast->sample_size)
1511 pkt->dts /= ast->sample_size;
1512 pkt->stream_index = avi->stream_index;
1514 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->internal->index_entries) {
1518 index = av_index_search_timestamp(st, ast->frame_offset, AVSEEK_FLAG_ANY);
1519 e = &st->internal->index_entries[index];
1521 if (index >= 0 && e->timestamp == ast->frame_offset) {
1522 if (index == st->internal->nb_index_entries-1) {
1525 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1526 const uint8_t *ptr = pkt->data, *end = ptr + FFMIN(size, 256);
1528 ptr = avpriv_find_start_code(ptr, end, &state);
1529 if (state == 0x1B6 && ptr < end) {
1530 key = !(*ptr & 0xC0);
1536 e->flags &= ~AVINDEX_KEYFRAME;
1538 if (e->flags & AVINDEX_KEYFRAME)
1539 pkt->flags |= AV_PKT_FLAG_KEY;
1542 pkt->flags |= AV_PKT_FLAG_KEY;
1544 ast->frame_offset += get_duration(ast, pkt->size);
1546 ast->remaining -= err;
1547 if (!ast->remaining) {
1548 avi->stream_index = -1;
1549 ast->packet_size = 0;
1552 if (!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos) {
1553 av_packet_unref(pkt);
1558 if (!avi->non_interleaved && st->internal->nb_index_entries>1 && avi->index_loaded>1) {
1559 int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
1561 if (avi->dts_max < dts) {
1563 } else if (avi->dts_max - (uint64_t)dts > 2*AV_TIME_BASE) {
1564 avi->non_interleaved= 1;
1565 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
1572 if ((err = avi_sync(s, 0)) < 0)
1577 /* XXX: We make the implicit supposition that the positions are sorted
1578 * for each stream. */
1579 static int avi_read_idx1(AVFormatContext *s, int size)
1581 AVIContext *avi = s->priv_data;
1582 AVIOContext *pb = s->pb;
1583 int nb_index_entries, i;
1587 unsigned int index, tag, flags, len, first_packet = 1;
1588 int64_t last_pos = -1;
1589 unsigned last_idx = -1;
1590 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1593 nb_index_entries = size / 16;
1594 if (nb_index_entries <= 0)
1595 return AVERROR_INVALIDDATA;
1597 idx1_pos = avio_tell(pb);
1598 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1599 if (avi_sync(s, 1) == 0)
1600 first_packet_pos = avio_tell(pb) - 8;
1601 avi->stream_index = -1;
1602 avio_seek(pb, idx1_pos, SEEK_SET);
1604 if (s->nb_streams == 1 && s->streams[0]->codecpar->codec_tag == AV_RL32("MMES")) {
1605 first_packet_pos = 0;
1606 data_offset = avi->movi_list;
1609 /* Read the entries and sort them in each stream component. */
1610 for (i = 0; i < nb_index_entries; i++) {
1614 tag = avio_rl32(pb);
1615 flags = avio_rl32(pb);
1616 pos = avio_rl32(pb);
1617 len = avio_rl32(pb);
1618 av_log(s, AV_LOG_TRACE, "%d: tag=0x%x flags=0x%x pos=0x%"PRIx64" len=%d/",
1619 i, tag, flags, pos, len);
1621 index = ((tag & 0xff) - '0') * 10;
1622 index += (tag >> 8 & 0xff) - '0';
1623 if (index >= s->nb_streams)
1625 st = s->streams[index];
1626 ast = st->priv_data;
1628 /* Skip 'xxpc' palette change entries in the index until a logic
1629 * to process these is properly implemented. */
1630 if ((tag >> 16 & 0xff) == 'p' && (tag >> 24 & 0xff) == 'c')
1633 if (first_packet && first_packet_pos) {
1634 if (avi->movi_list + 4 != pos || pos + 500 > first_packet_pos)
1635 data_offset = first_packet_pos - pos;
1640 av_log(s, AV_LOG_TRACE, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1642 // even if we have only a single stream, we should
1643 // switch to non-interleaved to get correct timestamps
1644 if (last_pos == pos)
1645 avi->non_interleaved = 1;
1646 if (last_idx != pos && len) {
1647 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1648 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1651 ast->cum_len += get_duration(ast, len);
1653 anykey |= flags&AVIIF_INDEX;
1656 for (index = 0; index < s->nb_streams; index++) {
1657 st = s->streams[index];
1658 if (st->internal->nb_index_entries)
1659 st->internal->index_entries[0].flags |= AVINDEX_KEYFRAME;
1665 /* Scan the index and consider any file with streams more than
1666 * 2 seconds or 64MB apart non-interleaved. */
1667 static int check_stream_max_drift(AVFormatContext *s)
1669 int64_t min_pos, pos;
1671 int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
1673 return AVERROR(ENOMEM);
1674 for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
1675 int64_t max_dts = INT64_MIN / 2;
1676 int64_t min_dts = INT64_MAX / 2;
1677 int64_t max_buffer = 0;
1679 min_pos = INT64_MAX;
1681 for (i = 0; i < s->nb_streams; i++) {
1682 AVStream *st = s->streams[i];
1683 AVIStream *ast = st->priv_data;
1684 int n = st->internal->nb_index_entries;
1685 while (idx[i] < n && st->internal->index_entries[idx[i]].pos < pos)
1689 dts = av_rescale_q(st->internal->index_entries[idx[i]].timestamp /
1690 FFMAX(ast->sample_size, 1),
1691 st->time_base, AV_TIME_BASE_Q);
1692 min_dts = FFMIN(min_dts, dts);
1693 min_pos = FFMIN(min_pos, st->internal->index_entries[idx[i]].pos);
1696 for (i = 0; i < s->nb_streams; i++) {
1697 AVStream *st = s->streams[i];
1698 AVIStream *ast = st->priv_data;
1700 if (idx[i] && min_dts != INT64_MAX / 2) {
1701 int64_t dts, delta_dts;
1702 dts = av_rescale_q(st->internal->index_entries[idx[i] - 1].timestamp /
1703 FFMAX(ast->sample_size, 1),
1704 st->time_base, AV_TIME_BASE_Q);
1705 delta_dts = av_sat_sub64(dts, min_dts);
1706 max_dts = FFMAX(max_dts, dts);
1707 max_buffer = FFMAX(max_buffer,
1708 av_rescale(delta_dts,
1709 st->codecpar->bit_rate,
1713 if (av_sat_sub64(max_dts, min_dts) > 2 * AV_TIME_BASE ||
1714 max_buffer > 1024 * 1024 * 8 * 8) {
1723 static int guess_ni_flag(AVFormatContext *s)
1726 int64_t last_start = 0;
1727 int64_t first_end = INT64_MAX;
1728 int64_t oldpos = avio_tell(s->pb);
1730 for (i = 0; i < s->nb_streams; i++) {
1731 AVStream *st = s->streams[i];
1732 int n = st->internal->nb_index_entries;
1739 int64_t pos = st->internal->index_entries[0].pos;
1741 avio_seek(s->pb, pos, SEEK_SET);
1742 tag[0] = avio_r8(s->pb);
1743 tag[1] = avio_r8(s->pb);
1745 size = avio_rl32(s->pb);
1746 if (get_stream_idx(tag) == i && pos + size > st->internal->index_entries[1].pos)
1747 last_start = INT64_MAX;
1748 if (get_stream_idx(tag) == i && size == st->internal->index_entries[0].size + 8)
1749 last_start = INT64_MAX;
1752 if (st->internal->index_entries[0].pos > last_start)
1753 last_start = st->internal->index_entries[0].pos;
1754 if (st->internal->index_entries[n - 1].pos < first_end)
1755 first_end = st->internal->index_entries[n - 1].pos;
1757 avio_seek(s->pb, oldpos, SEEK_SET);
1759 if (last_start > first_end)
1762 return check_stream_max_drift(s);
1765 static int avi_load_index(AVFormatContext *s)
1767 AVIContext *avi = s->priv_data;
1768 AVIOContext *pb = s->pb;
1770 int64_t pos = avio_tell(pb);
1774 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1775 goto the_end; // maybe truncated file
1776 av_log(s, AV_LOG_TRACE, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1778 tag = avio_rl32(pb);
1779 size = avio_rl32(pb);
1782 next = avio_tell(pb) + size + (size & 1);
1784 if (tag == MKTAG('i', 'd', 'x', '1') &&
1785 avi_read_idx1(s, size) >= 0) {
1786 avi->index_loaded=2;
1788 }else if (tag == MKTAG('L', 'I', 'S', 'T')) {
1789 uint32_t tag1 = avio_rl32(pb);
1791 if (tag1 == MKTAG('I', 'N', 'F', 'O'))
1792 ff_read_riff_info(s, size - 4);
1796 if (avio_seek(pb, next, SEEK_SET) < 0)
1797 break; // something is wrong here
1801 avio_seek(pb, pos, SEEK_SET);
1805 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1807 AVIStream *ast2 = st2->priv_data;
1808 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1809 av_packet_unref(&ast2->sub_pkt);
1810 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1811 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1812 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1815 static int avi_read_seek(AVFormatContext *s, int stream_index,
1816 int64_t timestamp, int flags)
1818 AVIContext *avi = s->priv_data;
1821 int64_t pos, pos_min;
1824 /* Does not matter which stream is requested dv in avi has the
1825 * stream information in the first video stream.
1830 if (!avi->index_loaded) {
1831 /* we only load the index on demand */
1833 avi->index_loaded |= 1;
1835 av_assert0(stream_index >= 0);
1837 st = s->streams[stream_index];
1838 ast = st->priv_data;
1839 index = av_index_search_timestamp(st,
1840 timestamp * FFMAX(ast->sample_size, 1),
1843 if (st->internal->nb_index_entries > 0)
1844 av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
1845 timestamp * FFMAX(ast->sample_size, 1),
1846 st->internal->index_entries[0].timestamp,
1847 st->internal->index_entries[st->internal->nb_index_entries - 1].timestamp);
1848 return AVERROR_INVALIDDATA;
1851 /* find the position */
1852 pos = st->internal->index_entries[index].pos;
1853 timestamp = st->internal->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1855 av_log(s, AV_LOG_TRACE, "XX %"PRId64" %d %"PRId64"\n",
1856 timestamp, index, st->internal->index_entries[index].timestamp);
1858 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1859 /* One and only one real stream for DV in AVI, and it has video */
1860 /* offsets. Calling with other stream indexes should have failed */
1861 /* the av_index_search_timestamp call above. */
1863 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
1866 /* Feed the DV video stream version of the timestamp to the */
1867 /* DV demux so it can synthesize correct timestamps. */
1868 ff_dv_offset_reset(avi->dv_demux, timestamp);
1870 avi->stream_index = -1;
1875 for (i = 0; i < s->nb_streams; i++) {
1876 AVStream *st2 = s->streams[i];
1877 AVIStream *ast2 = st2->priv_data;
1880 ast2->remaining = 0;
1882 if (ast2->sub_ctx) {
1883 seek_subtitle(st, st2, timestamp);
1887 if (st2->internal->nb_index_entries <= 0)
1890 // av_assert1(st2->codecpar->block_align);
1891 index = av_index_search_timestamp(st2,
1892 av_rescale_q(timestamp,
1895 FFMAX(ast2->sample_size, 1),
1897 AVSEEK_FLAG_BACKWARD |
1898 (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1901 ast2->seek_pos = st2->internal->index_entries[index].pos;
1902 pos_min = FFMIN(pos_min,ast2->seek_pos);
1904 for (i = 0; i < s->nb_streams; i++) {
1905 AVStream *st2 = s->streams[i];
1906 AVIStream *ast2 = st2->priv_data;
1908 if (ast2->sub_ctx || st2->internal->nb_index_entries <= 0)
1911 index = av_index_search_timestamp(
1913 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1914 flags | AVSEEK_FLAG_BACKWARD | (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1917 while (!avi->non_interleaved && index>0 && st2->internal->index_entries[index-1].pos >= pos_min)
1919 ast2->frame_offset = st2->internal->index_entries[index].timestamp;
1923 if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
1924 av_log(s, AV_LOG_ERROR, "Seek failed\n");
1927 avi->stream_index = -1;
1928 avi->dts_max = INT_MIN;
1932 static int avi_read_close(AVFormatContext *s)
1935 AVIContext *avi = s->priv_data;
1937 for (i = 0; i < s->nb_streams; i++) {
1938 AVStream *st = s->streams[i];
1939 AVIStream *ast = st->priv_data;
1942 av_freep(&ast->sub_ctx->pb);
1943 avformat_close_input(&ast->sub_ctx);
1945 av_buffer_unref(&ast->sub_buffer);
1946 av_packet_unref(&ast->sub_pkt);
1950 av_freep(&avi->dv_demux);
1955 static int avi_probe(const AVProbeData *p)
1959 /* check file header */
1960 for (i = 0; avi_headers[i][0]; i++)
1961 if (AV_RL32(p->buf ) == AV_RL32(avi_headers[i] ) &&
1962 AV_RL32(p->buf + 8) == AV_RL32(avi_headers[i] + 4))
1963 return AVPROBE_SCORE_MAX;
1968 AVInputFormat ff_avi_demuxer = {
1970 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1971 .priv_data_size = sizeof(AVIContext),
1972 .extensions = "avi",
1973 .read_probe = avi_probe,
1974 .read_header = avi_read_header,
1975 .read_packet = avi_read_packet,
1976 .read_close = avi_read_close,
1977 .read_seek = avi_read_seek,
1978 .priv_class = &demuxer_class,