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) */
49 int sample_size; /* size of one sample (or packet)
50 * (in the rate/scale sense) in bytes */
52 int64_t cum_len; /* temporary storage (used during seek) */
53 int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
57 int dshow_block_align; /* block align variable used to emulate bugs in
58 * the MS dshow demuxer */
60 AVFormatContext *sub_ctx;
67 typedef struct AVIContext {
79 DVDemuxContext *dv_demux;
82 #define MAX_ODML_DEPTH 1000
87 static const AVOption options[] = {
88 { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_INT, {.i64 = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
92 static const AVClass demuxer_class = {
94 .item_name = av_default_item_name,
96 .version = LIBAVUTIL_VERSION_INT,
97 .category = AV_CLASS_CATEGORY_DEMUXER,
101 static const char avi_headers[][8] = {
102 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
103 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
104 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
105 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
106 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
110 static const AVMetadataConv avi_metadata_conv[] = {
115 static int avi_load_index(AVFormatContext *s);
116 static int guess_ni_flag(AVFormatContext *s);
118 #define print_tag(str, tag, size) \
119 av_dlog(NULL, "pos:%"PRIX64" %s: tag=%c%c%c%c size=0x%x\n", \
120 avio_tell(pb), str, tag & 0xff, \
122 (tag >> 16) & 0xff, \
123 (tag >> 24) & 0xff, \
126 static inline int get_duration(AVIStream *ast, int len)
128 if (ast->sample_size)
130 else if (ast->dshow_block_align > 1)
131 return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
136 static int get_riff(AVFormatContext *s, AVIOContext *pb)
138 AVIContext *avi = s->priv_data;
142 /* check RIFF header */
143 avio_read(pb, header, 4);
144 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
145 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
146 avio_read(pb, header + 4, 4);
148 for (i = 0; avi_headers[i][0]; i++)
149 if (!memcmp(header, avi_headers[i], 8))
151 if (!avi_headers[i][0])
152 return AVERROR_INVALIDDATA;
154 if (header[7] == 0x19)
155 av_log(s, AV_LOG_INFO,
156 "This file has been generated by a totally broken muxer.\n");
161 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
163 AVIContext *avi = s->priv_data;
164 AVIOContext *pb = s->pb;
165 int longs_pre_entry = avio_rl16(pb);
166 int index_sub_type = avio_r8(pb);
167 int index_type = avio_r8(pb);
168 int entries_in_use = avio_rl32(pb);
169 int chunk_id = avio_rl32(pb);
170 int64_t base = avio_rl64(pb);
171 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
172 ((chunk_id >> 8 & 0xFF) - '0');
176 int64_t last_pos = -1;
177 int64_t filesize = avi->fsize;
180 "longs_pre_entry:%d index_type:%d entries_in_use:%d "
181 "chunk_id:%X base:%16"PRIX64"\n",
188 if (stream_id >= s->nb_streams || stream_id < 0)
189 return AVERROR_INVALIDDATA;
190 st = s->streams[stream_id];
194 return AVERROR_INVALIDDATA;
198 if (index_type && longs_pre_entry != 2)
199 return AVERROR_INVALIDDATA;
201 return AVERROR_INVALIDDATA;
203 if (filesize > 0 && base >= filesize) {
204 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
205 if (base >> 32 == (base & 0xFFFFFFFF) &&
206 (base & 0xFFFFFFFF) < filesize &&
207 filesize <= 0xFFFFFFFF)
210 return AVERROR_INVALIDDATA;
213 for (i = 0; i < entries_in_use; i++) {
215 int64_t pos = avio_rl32(pb) + base - 8;
216 int len = avio_rl32(pb);
221 av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
224 return AVERROR_INVALIDDATA;
226 if (last_pos == pos || pos == base - 8)
227 avi->non_interleaved = 1;
228 if (last_pos != pos && len)
229 av_add_index_entry(st, pos, ast->cum_len, len, 0,
230 key ? AVINDEX_KEYFRAME : 0);
232 ast->cum_len += get_duration(ast, len);
237 offset = avio_rl64(pb);
238 avio_rl32(pb); /* size */
239 duration = avio_rl32(pb);
242 return AVERROR_INVALIDDATA;
246 if (avi->odml_depth > MAX_ODML_DEPTH) {
247 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
248 return AVERROR_INVALIDDATA;
251 if (avio_seek(pb, offset + 8, SEEK_SET) < 0)
254 read_braindead_odml_indx(s, frame_num);
256 frame_num += duration;
258 if (avio_seek(pb, pos, SEEK_SET) < 0) {
259 av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index\n");
265 avi->index_loaded = 2;
269 static void clean_index(AVFormatContext *s)
274 for (i = 0; i < s->nb_streams; i++) {
275 AVStream *st = s->streams[i];
276 AVIStream *ast = st->priv_data;
277 int n = st->nb_index_entries;
278 int max = ast->sample_size;
279 int64_t pos, size, ts;
281 if (n != 1 || ast->sample_size == 0)
287 pos = st->index_entries[0].pos;
288 size = st->index_entries[0].size;
289 ts = st->index_entries[0].timestamp;
291 for (j = 0; j < size; j += max)
292 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
297 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
300 AVIOContext *pb = s->pb;
306 if (size == UINT_MAX)
307 return AVERROR(EINVAL);
308 value = av_malloc(size + 1);
310 return AVERROR(ENOMEM);
311 avio_read(pb, value, size);
316 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
317 AV_DICT_DONT_STRDUP_VAL);
320 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
321 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
323 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
325 char month[4], time[9], buffer[64];
327 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
328 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
329 month, &day, time, &year) == 4) {
330 for (i = 0; i < 12; i++)
331 if (!av_strcasecmp(month, months[i])) {
332 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
333 year, i + 1, day, time);
334 av_dict_set(metadata, "creation_time", buffer, 0);
336 } else if (date[4] == '/' && date[7] == '/') {
337 date[4] = date[7] = '-';
338 av_dict_set(metadata, "creation_time", date, 0);
342 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
344 while (avio_tell(s->pb) < end) {
345 uint32_t tag = avio_rl32(s->pb);
346 uint32_t size = avio_rl32(s->pb);
348 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
350 uint64_t tag_end = avio_tell(s->pb) + size;
351 while (avio_tell(s->pb) < tag_end) {
352 uint16_t tag = avio_rl16(s->pb);
353 uint16_t size = avio_rl16(s->pb);
354 const char *name = NULL;
355 char buffer[64] = { 0 };
356 size = FFMIN(size, tag_end - avio_tell(s->pb));
357 size -= avio_read(s->pb, buffer,
358 FFMIN(size, sizeof(buffer) - 1));
367 name = "creation_time";
368 if (buffer[4] == ':' && buffer[7] == ':')
369 buffer[4] = buffer[7] = '-';
373 av_dict_set(&s->metadata, name, buffer, 0);
374 avio_skip(s->pb, size);
379 avio_skip(s->pb, size);
385 static int avi_extract_stream_metadata(AVStream *st)
388 uint8_t *data = st->codec->extradata;
389 int data_size = st->codec->extradata_size;
392 if (!data || data_size < 8) {
393 return AVERROR_INVALIDDATA;
396 bytestream2_init(&gb, data, data_size);
398 tag = bytestream2_get_le32(&gb);
401 case MKTAG('A', 'V', 'I', 'F'):
402 // skip 4 byte padding
403 bytestream2_skip(&gb, 4);
404 offset = bytestream2_tell(&gb);
405 bytestream2_init(&gb, data + offset, data_size - offset);
407 // decode EXIF tags from IFD, AVI is always little-endian
408 return avpriv_exif_decode_ifd(st->codec, &gb, 1, 0, &st->metadata);
410 case MKTAG('C', 'A', 'S', 'I'):
411 avpriv_request_sample(st->codec, "RIFF stream data tag type CASI (%u)", tag);
413 case MKTAG('Z', 'o', 'r', 'a'):
414 avpriv_request_sample(st->codec, "RIFF stream data tag type Zora (%u)", tag);
423 static int calculate_bitrate(AVFormatContext *s)
425 AVIContext *avi = s->priv_data;
430 for (i = 0; i<s->nb_streams; i++) {
432 AVStream *st = s->streams[i];
434 if (!st->nb_index_entries)
437 for (j = 0; j < st->nb_index_entries; j++)
438 len += st->index_entries[j].size;
439 maxpos = FFMAX(maxpos, st->index_entries[j-1].pos);
442 if (maxpos < avi->io_fsize*9/10) // index does not cover the whole file
444 if (lensum*9/10 > maxpos || lensum < maxpos*9/10) // frame sum and filesize mismatch
447 for (i = 0; i<s->nb_streams; i++) {
449 AVStream *st = s->streams[i];
452 for (j = 0; j < st->nb_index_entries; j++)
453 len += st->index_entries[j].size;
455 if (st->nb_index_entries < 2 || st->codec->bit_rate > 0)
457 duration = st->index_entries[j-1].timestamp - st->index_entries[0].timestamp;
458 st->codec->bit_rate = av_rescale(8*len, st->time_base.den, duration * st->time_base.num);
463 static int avi_read_header(AVFormatContext *s)
465 AVIContext *avi = s->priv_data;
466 AVIOContext *pb = s->pb;
467 unsigned int tag, tag1, handler;
468 int codec_type, stream_index, frame_period;
472 AVIStream *ast = NULL;
473 int avih_width = 0, avih_height = 0;
474 int amv_file_format = 0;
475 uint64_t list_end = 0;
477 AVDictionaryEntry *dict_entry;
479 avi->stream_index = -1;
481 ret = get_riff(s, pb);
485 av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
487 avi->io_fsize = avi->fsize = avio_size(pb);
488 if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
489 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
499 size = avio_rl32(pb);
501 print_tag("tag", tag, size);
504 case MKTAG('L', 'I', 'S', 'T'):
505 list_end = avio_tell(pb) + size;
506 /* Ignored, except at start of video packets. */
507 tag1 = avio_rl32(pb);
509 print_tag("list", tag1, 0);
511 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
512 avi->movi_list = avio_tell(pb) - 4;
514 avi->movi_end = avi->movi_list + size + (size & 1);
516 avi->movi_end = avi->fsize;
517 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
519 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
520 ff_read_riff_info(s, size - 4);
521 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
522 avi_read_nikon(s, list_end);
525 case MKTAG('I', 'D', 'I', 'T'):
527 unsigned char date[64] = { 0 };
529 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
531 avi_metadata_creation_time(&s->metadata, date);
534 case MKTAG('d', 'm', 'l', 'h'):
536 avio_skip(pb, size + (size & 1));
538 case MKTAG('a', 'm', 'v', 'h'):
540 case MKTAG('a', 'v', 'i', 'h'):
542 /* using frame_period is bad idea */
543 frame_period = avio_rl32(pb);
544 avio_rl32(pb); /* max. bytes per second */
546 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
548 avio_skip(pb, 2 * 4);
551 avih_width = avio_rl32(pb);
552 avih_height = avio_rl32(pb);
554 avio_skip(pb, size - 10 * 4);
556 case MKTAG('s', 't', 'r', 'h'):
559 tag1 = avio_rl32(pb);
560 handler = avio_rl32(pb); /* codec tag */
562 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
563 avio_skip(pb, size - 8);
567 st = avformat_new_stream(s, NULL);
571 st->id = stream_index;
572 ast = av_mallocz(sizeof(AVIStream));
578 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
579 : MKTAG('v', 'i', 'd', 's');
581 print_tag("strh", tag1, -1);
583 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
584 tag1 == MKTAG('i', 'v', 'a', 's')) {
587 /* After some consideration -- I don't think we
588 * have to support anything but DV in type1 AVIs. */
589 if (s->nb_streams != 1)
592 if (handler != MKTAG('d', 'v', 's', 'd') &&
593 handler != MKTAG('d', 'v', 'h', 'd') &&
594 handler != MKTAG('d', 'v', 's', 'l'))
597 ast = s->streams[0]->priv_data;
598 av_freep(&s->streams[0]->codec->extradata);
599 av_freep(&s->streams[0]->codec);
600 if (s->streams[0]->info)
601 av_freep(&s->streams[0]->info->duration_error);
602 av_freep(&s->streams[0]->info);
603 av_freep(&s->streams[0]);
605 if (CONFIG_DV_DEMUXER) {
606 avi->dv_demux = avpriv_dv_init_demux(s);
611 s->streams[0]->priv_data = ast;
612 avio_skip(pb, 3 * 4);
613 ast->scale = avio_rl32(pb);
614 ast->rate = avio_rl32(pb);
615 avio_skip(pb, 4); /* start time */
617 dv_dur = avio_rl32(pb);
618 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
619 dv_dur *= AV_TIME_BASE;
620 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
622 /* else, leave duration alone; timing estimation in utils.c
623 * will make a guess based on bitrate. */
625 stream_index = s->nb_streams - 1;
626 avio_skip(pb, size - 9 * 4);
630 av_assert0(stream_index < s->nb_streams);
631 ast->handler = handler;
633 avio_rl32(pb); /* flags */
634 avio_rl16(pb); /* priority */
635 avio_rl16(pb); /* language */
636 avio_rl32(pb); /* initial frame */
637 ast->scale = avio_rl32(pb);
638 ast->rate = avio_rl32(pb);
639 if (!(ast->scale && ast->rate)) {
640 av_log(s, AV_LOG_WARNING,
641 "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
642 "(This file has been generated by broken software.)\n",
647 ast->scale = frame_period;
653 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
655 ast->cum_len = avio_rl32(pb); /* start */
656 st->nb_frames = avio_rl32(pb);
659 avio_rl32(pb); /* buffer size */
660 avio_rl32(pb); /* quality */
661 if (ast->cum_len*ast->scale/ast->rate > 3600) {
662 av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
665 ast->sample_size = avio_rl32(pb); /* sample ssize */
666 ast->cum_len *= FFMAX(1, ast->sample_size);
667 av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
668 ast->rate, ast->scale, ast->sample_size);
671 case MKTAG('v', 'i', 'd', 's'):
672 codec_type = AVMEDIA_TYPE_VIDEO;
674 ast->sample_size = 0;
675 st->avg_frame_rate = av_inv_q(st->time_base);
677 case MKTAG('a', 'u', 'd', 's'):
678 codec_type = AVMEDIA_TYPE_AUDIO;
680 case MKTAG('t', 'x', 't', 's'):
681 codec_type = AVMEDIA_TYPE_SUBTITLE;
683 case MKTAG('d', 'a', 't', 's'):
684 codec_type = AVMEDIA_TYPE_DATA;
687 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
689 if (ast->sample_size == 0) {
690 st->duration = st->nb_frames;
691 if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) {
692 av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n");
693 st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end);
696 ast->frame_offset = ast->cum_len;
697 avio_skip(pb, size - 12 * 4);
699 case MKTAG('s', 't', 'r', 'f'):
703 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
706 uint64_t cur_pos = avio_tell(pb);
708 if (cur_pos < list_end)
709 size = FFMIN(size, list_end - cur_pos);
710 st = s->streams[stream_index];
711 if (st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN) {
715 switch (codec_type) {
716 case AVMEDIA_TYPE_VIDEO:
717 if (amv_file_format) {
718 st->codec->width = avih_width;
719 st->codec->height = avih_height;
720 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
721 st->codec->codec_id = AV_CODEC_ID_AMV;
725 tag1 = ff_get_bmp_header(pb, st, &esize);
727 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
728 tag1 == MKTAG('D', 'X', 'S', 'A')) {
729 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
730 st->codec->codec_tag = tag1;
731 st->codec->codec_id = AV_CODEC_ID_XSUB;
735 if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) {
736 if (esize == size-1 && (esize&1)) {
737 st->codec->extradata_size = esize - 10 * 4;
739 st->codec->extradata_size = size - 10 * 4;
740 if (ff_get_extradata(st->codec, pb, st->codec->extradata_size) < 0)
741 return AVERROR(ENOMEM);
744 // FIXME: check if the encoder really did this correctly
745 if (st->codec->extradata_size & 1)
748 /* Extract palette from extradata if bpp <= 8.
749 * This code assumes that extradata contains only palette.
750 * This is true for all paletted codecs implemented in
752 if (st->codec->extradata_size &&
753 (st->codec->bits_per_coded_sample <= 8)) {
754 int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
755 const uint8_t *pal_src;
757 pal_size = FFMIN(pal_size, st->codec->extradata_size);
758 pal_src = st->codec->extradata +
759 st->codec->extradata_size - pal_size;
760 /* Exclude the "BottomUp" field from the palette */
761 if (pal_src - st->codec->extradata >= 9 &&
762 !memcmp(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9))
764 for (i = 0; i < pal_size / 4; i++)
765 ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i);
769 print_tag("video", tag1, 0);
771 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
772 st->codec->codec_tag = tag1;
773 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
775 /* This is needed to get the pict type which is necessary
776 * for generating correct pts. */
777 st->need_parsing = AVSTREAM_PARSE_HEADERS;
779 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
780 ast->handler == MKTAG('X', 'V', 'I', 'D'))
781 st->codec->codec_tag = MKTAG('X', 'V', 'I', 'D');
783 if (st->codec->codec_tag == MKTAG('V', 'S', 'S', 'H'))
784 st->need_parsing = AVSTREAM_PARSE_FULL;
786 if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
787 st->codec->extradata_size < 1U << 30) {
788 st->codec->extradata_size += 9;
789 if ((ret = av_reallocp(&st->codec->extradata,
790 st->codec->extradata_size +
791 FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
792 st->codec->extradata_size = 0;
795 memcpy(st->codec->extradata + st->codec->extradata_size - 9,
798 st->codec->height = FFABS(st->codec->height);
800 // avio_skip(pb, size - 5 * 4);
802 case AVMEDIA_TYPE_AUDIO:
803 ret = ff_get_wav_header(pb, st->codec, size, 0);
806 ast->dshow_block_align = st->codec->block_align;
807 if (ast->sample_size && st->codec->block_align &&
808 ast->sample_size != st->codec->block_align) {
811 "sample size (%d) != block align (%d)\n",
813 st->codec->block_align);
814 ast->sample_size = st->codec->block_align;
817 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
820 /* Force parsing as several audio frames can be in
821 * one packet and timestamps refer to packet start. */
822 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
823 /* ADTS header is in extradata, AAC without header must be
824 * stored as exact frames. Parser not needed and it will
826 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
827 st->codec->extradata_size)
828 st->need_parsing = AVSTREAM_PARSE_NONE;
829 /* AVI files with Xan DPCM audio (wrongly) declare PCM
830 * audio in the header but have Axan as stream_code_tag. */
831 if (ast->handler == AV_RL32("Axan")) {
832 st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
833 st->codec->codec_tag = 0;
834 ast->dshow_block_align = 0;
836 if (amv_file_format) {
837 st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
838 ast->dshow_block_align = 0;
840 if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
841 av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
842 ast->dshow_block_align = 0;
844 if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
845 st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
846 st->codec->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
847 av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
848 ast->sample_size = 0;
851 case AVMEDIA_TYPE_SUBTITLE:
852 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
853 st->request_probe= 1;
857 st->codec->codec_type = AVMEDIA_TYPE_DATA;
858 st->codec->codec_id = AV_CODEC_ID_NONE;
859 st->codec->codec_tag = 0;
865 case MKTAG('s', 't', 'r', 'd'):
866 if (stream_index >= (unsigned)s->nb_streams
867 || s->streams[stream_index]->codec->extradata_size
868 || s->streams[stream_index]->codec->codec_tag == MKTAG('H','2','6','4')) {
871 uint64_t cur_pos = avio_tell(pb);
872 if (cur_pos < list_end)
873 size = FFMIN(size, list_end - cur_pos);
874 st = s->streams[stream_index];
877 if (ff_get_extradata(st->codec, pb, size) < 0)
878 return AVERROR(ENOMEM);
881 if (st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
884 ret = avi_extract_stream_metadata(st);
886 av_log(s, AV_LOG_WARNING, "could not decoding EXIF data in stream header.\n");
890 case MKTAG('i', 'n', 'd', 'x'):
892 if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
894 read_braindead_odml_indx(s, 0) < 0 &&
895 (s->error_recognition & AV_EF_EXPLODE))
897 avio_seek(pb, i + size, SEEK_SET);
899 case MKTAG('v', 'p', 'r', 'p'):
900 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
901 AVRational active, active_aspect;
903 st = s->streams[stream_index];
910 active_aspect.den = avio_rl16(pb);
911 active_aspect.num = avio_rl16(pb);
912 active.num = avio_rl32(pb);
913 active.den = avio_rl32(pb);
914 avio_rl32(pb); // nbFieldsPerFrame
916 if (active_aspect.num && active_aspect.den &&
917 active.num && active.den) {
918 st->sample_aspect_ratio = av_div_q(active_aspect, active);
919 av_dlog(s, "vprp %d/%d %d/%d\n",
920 active_aspect.num, active_aspect.den,
921 active.num, active.den);
927 case MKTAG('s', 't', 'r', 'n'):
929 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
935 if (size > 1000000) {
936 av_log(s, AV_LOG_ERROR,
937 "Something went wrong during header parsing, "
938 "I will ignore it and try to continue anyway.\n");
939 if (s->error_recognition & AV_EF_EXPLODE)
941 avi->movi_list = avio_tell(pb) - 4;
942 avi->movi_end = avi->fsize;
953 /* check stream number */
954 if (stream_index != s->nb_streams - 1) {
957 return AVERROR_INVALIDDATA;
960 if (!avi->index_loaded && pb->seekable)
962 calculate_bitrate(s);
963 avi->index_loaded |= 1;
965 if ((ret = guess_ni_flag(s)) < 0)
968 avi->non_interleaved |= ret | (s->flags & AVFMT_FLAG_SORT_DTS);
970 dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0);
971 if (dict_entry && !strcmp(dict_entry->value, "PotEncoder"))
972 for (i = 0; i < s->nb_streams; i++) {
973 AVStream *st = s->streams[i];
974 if ( st->codec->codec_id == AV_CODEC_ID_MPEG1VIDEO
975 || st->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO)
976 st->need_parsing = AVSTREAM_PARSE_FULL;
979 for (i = 0; i < s->nb_streams; i++) {
980 AVStream *st = s->streams[i];
981 if (st->nb_index_entries)
984 // DV-in-AVI cannot be non-interleaved, if set this must be
987 avi->non_interleaved = 0;
988 if (i == s->nb_streams && avi->non_interleaved) {
989 av_log(s, AV_LOG_WARNING,
990 "Non-interleaved AVI without index, switching to interleaved\n");
991 avi->non_interleaved = 0;
994 if (avi->non_interleaved) {
995 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
999 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
1000 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
1005 static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1007 if (pkt->size >= 7 &&
1008 pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
1009 !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
1011 int score = AVPROBE_SCORE_EXTENSION, ret;
1012 AVIStream *ast = st->priv_data;
1013 AVInputFormat *sub_demuxer;
1014 AVRational time_base;
1016 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
1018 0, NULL, NULL, NULL, NULL);
1020 unsigned int desc_len = avio_rl32(pb);
1022 if (desc_len > pb->buf_end - pb->buf_ptr)
1025 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
1026 avio_skip(pb, desc_len - ret);
1028 av_dict_set(&st->metadata, "title", desc, 0);
1030 avio_rl16(pb); /* flags? */
1031 avio_rl32(pb); /* data size */
1033 size = pb->buf_end - pb->buf_ptr;
1034 pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
1038 memcpy(pd.buf, pb->buf_ptr, size);
1039 sub_demuxer = av_probe_input_format2(&pd, 1, &score);
1044 if (!(ast->sub_ctx = avformat_alloc_context()))
1047 ast->sub_ctx->pb = pb;
1049 if (ff_copy_whitelists(ast->sub_ctx, s) < 0)
1052 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
1053 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
1054 *st->codec = *ast->sub_ctx->streams[0]->codec;
1055 ast->sub_ctx->streams[0]->codec->extradata = NULL;
1056 time_base = ast->sub_ctx->streams[0]->time_base;
1057 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
1059 ast->sub_buffer = pkt->data;
1060 memset(pkt, 0, sizeof(*pkt));
1064 av_freep(&ast->sub_ctx);
1070 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
1073 AVIStream *ast, *next_ast = next_st->priv_data;
1074 int64_t ts, next_ts, ts_min = INT64_MAX;
1075 AVStream *st, *sub_st = NULL;
1078 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
1081 for (i = 0; i < s->nb_streams; i++) {
1083 ast = st->priv_data;
1084 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
1085 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
1086 if (ts <= next_ts && ts < ts_min) {
1094 ast = sub_st->priv_data;
1095 *pkt = ast->sub_pkt;
1096 pkt->stream_index = sub_st->index;
1098 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
1099 ast->sub_pkt.data = NULL;
1104 static int get_stream_idx(const unsigned *d)
1106 if (d[0] >= '0' && d[0] <= '9' &&
1107 d[1] >= '0' && d[1] <= '9') {
1108 return (d[0] - '0') * 10 + (d[1] - '0');
1110 return 100; // invalid stream ID
1116 * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
1118 static int avi_sync(AVFormatContext *s, int exit_early)
1120 AVIContext *avi = s->priv_data;
1121 AVIOContext *pb = s->pb;
1128 memset(d, -1, sizeof(d));
1129 for (i = sync = avio_tell(pb); !avio_feof(pb); i++) {
1132 for (j = 0; j < 7; j++)
1136 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
1138 n = get_stream_idx(d + 2);
1139 av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
1140 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
1141 if (i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127)
1145 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
1147 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
1148 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
1149 avio_skip(pb, size);
1154 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
1159 n = get_stream_idx(d);
1161 if (!((i - avi->last_pkt_pos) & 1) &&
1162 get_stream_idx(d + 1) < s->nb_streams)
1165 // detect ##ix chunk and skip
1166 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
1167 avio_skip(pb, size);
1171 if (avi->dv_demux && n != 0)
1175 if (n < s->nb_streams) {
1179 ast = st->priv_data;
1182 av_log(s, AV_LOG_WARNING, "Skipping foreign stream %d packet\n", n);
1186 if (s->nb_streams >= 2) {
1187 AVStream *st1 = s->streams[1];
1188 AVIStream *ast1 = st1->priv_data;
1189 // workaround for broken small-file-bug402.avi
1190 if ( d[2] == 'w' && d[3] == 'b'
1192 && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
1193 && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
1194 && ast->prefix == 'd'*256+'c'
1195 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
1200 av_log(s, AV_LOG_WARNING,
1201 "Invalid stream + prefix combination, assuming audio.\n");
1205 if (!avi->dv_demux &&
1206 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
1207 // FIXME: needs a little reordering
1208 (st->discard >= AVDISCARD_NONKEY &&
1209 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1210 || st->discard >= AVDISCARD_ALL)) {
1212 ast->frame_offset += get_duration(ast, size);
1213 avio_skip(pb, size);
1218 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1219 int k = avio_r8(pb);
1220 int last = (k + avio_r8(pb) - 1) & 0xFF;
1222 avio_rl16(pb); // flags
1224 // b + (g << 8) + (r << 16);
1225 for (; k <= last; k++)
1226 ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;
1230 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1231 d[2] < 128 && d[3] < 128) ||
1232 d[2] * 256 + d[3] == ast->prefix /* ||
1233 (d[2] == 'd' && d[3] == 'c') ||
1234 (d[2] == 'w' && d[3] == 'b') */) {
1237 if (d[2] * 256 + d[3] == ast->prefix)
1238 ast->prefix_count++;
1240 ast->prefix = d[2] * 256 + d[3];
1241 ast->prefix_count = 0;
1244 avi->stream_index = n;
1245 ast->packet_size = size + 8;
1246 ast->remaining = size;
1249 uint64_t pos = avio_tell(pb) - 8;
1250 if (!st->index_entries || !st->nb_index_entries ||
1251 st->index_entries[st->nb_index_entries - 1].pos < pos) {
1252 av_add_index_entry(st, pos, ast->frame_offset, size,
1253 0, AVINDEX_KEYFRAME);
1266 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1268 AVIContext *avi = s->priv_data;
1269 AVIOContext *pb = s->pb;
1271 #if FF_API_DESTRUCT_PACKET
1275 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1276 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1283 if (avi->non_interleaved) {
1284 int best_stream_index = 0;
1285 AVStream *best_st = NULL;
1286 AVIStream *best_ast;
1287 int64_t best_ts = INT64_MAX;
1290 for (i = 0; i < s->nb_streams; i++) {
1291 AVStream *st = s->streams[i];
1292 AVIStream *ast = st->priv_data;
1293 int64_t ts = ast->frame_offset;
1296 if (!st->nb_index_entries)
1299 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1300 if (!ast->remaining && ts > last_ts)
1303 ts = av_rescale_q(ts, st->time_base,
1304 (AVRational) { FFMAX(1, ast->sample_size),
1307 av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
1308 st->time_base.num, st->time_base.den, ast->frame_offset);
1312 best_stream_index = i;
1318 best_ast = best_st->priv_data;
1319 best_ts = best_ast->frame_offset;
1320 if (best_ast->remaining) {
1321 i = av_index_search_timestamp(best_st,
1324 AVSEEK_FLAG_BACKWARD);
1326 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1328 best_ast->frame_offset = best_st->index_entries[i].timestamp;
1332 int64_t pos = best_st->index_entries[i].pos;
1333 pos += best_ast->packet_size - best_ast->remaining;
1334 if (avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
1337 av_assert0(best_ast->remaining <= best_ast->packet_size);
1339 avi->stream_index = best_stream_index;
1340 if (!best_ast->remaining)
1341 best_ast->packet_size =
1342 best_ast->remaining = best_st->index_entries[i].size;
1349 if (avi->stream_index >= 0) {
1350 AVStream *st = s->streams[avi->stream_index];
1351 AVIStream *ast = st->priv_data;
1354 if (get_subtitle_pkt(s, st, pkt))
1357 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1358 if (ast->sample_size <= 1)
1360 else if (ast->sample_size < 32)
1361 // arbitrary multiplier to avoid tiny packets for raw PCM data
1362 size = 1024 * ast->sample_size;
1364 size = ast->sample_size;
1366 if (size > ast->remaining)
1367 size = ast->remaining;
1368 avi->last_pkt_pos = avio_tell(pb);
1369 err = av_get_packet(pb, pkt, size);
1374 if (ast->has_pal && pkt->size < (unsigned)INT_MAX / 2) {
1376 pal = av_packet_new_side_data(pkt,
1377 AV_PKT_DATA_PALETTE,
1380 av_log(s, AV_LOG_ERROR,
1381 "Failed to allocate data for palette\n");
1383 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1388 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1389 AVBufferRef *avbuf = pkt->buf;
1390 #if FF_API_DESTRUCT_PACKET
1391 FF_DISABLE_DEPRECATION_WARNINGS
1392 dstr = pkt->destruct;
1393 FF_ENABLE_DEPRECATION_WARNINGS
1395 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1396 pkt->data, pkt->size, pkt->pos);
1397 #if FF_API_DESTRUCT_PACKET
1398 FF_DISABLE_DEPRECATION_WARNINGS
1399 pkt->destruct = dstr;
1400 FF_ENABLE_DEPRECATION_WARNINGS
1403 pkt->flags |= AV_PKT_FLAG_KEY;
1405 av_free_packet(pkt);
1406 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1407 !st->codec->codec_tag && read_gab2_sub(s, st, pkt)) {
1408 ast->frame_offset++;
1409 avi->stream_index = -1;
1413 /* XXX: How to handle B-frames in AVI? */
1414 pkt->dts = ast->frame_offset;
1415 // pkt->dts += ast->start;
1416 if (ast->sample_size)
1417 pkt->dts /= ast->sample_size;
1419 "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
1420 "base:%d st:%d size:%d\n",
1429 pkt->stream_index = avi->stream_index;
1431 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->index_entries) {
1435 index = av_index_search_timestamp(st, ast->frame_offset, AVSEEK_FLAG_ANY);
1436 e = &st->index_entries[index];
1438 if (index >= 0 && e->timestamp == ast->frame_offset) {
1439 if (index == st->nb_index_entries-1) {
1443 for (i=0; i<FFMIN(size,256); i++) {
1444 if (st->codec->codec_id == AV_CODEC_ID_MPEG4) {
1445 if (state == 0x1B6) {
1446 key= !(pkt->data[i]&0xC0);
1451 state= (state<<8) + pkt->data[i];
1454 e->flags &= ~AVINDEX_KEYFRAME;
1456 if (e->flags & AVINDEX_KEYFRAME)
1457 pkt->flags |= AV_PKT_FLAG_KEY;
1460 pkt->flags |= AV_PKT_FLAG_KEY;
1462 ast->frame_offset += get_duration(ast, pkt->size);
1464 ast->remaining -= err;
1465 if (!ast->remaining) {
1466 avi->stream_index = -1;
1467 ast->packet_size = 0;
1470 if (!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos) {
1471 av_free_packet(pkt);
1476 if (!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1) {
1477 int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
1479 if (avi->dts_max - dts > 2*AV_TIME_BASE) {
1480 avi->non_interleaved= 1;
1481 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
1482 }else if (avi->dts_max < dts)
1489 if ((err = avi_sync(s, 0)) < 0)
1494 /* XXX: We make the implicit supposition that the positions are sorted
1495 * for each stream. */
1496 static int avi_read_idx1(AVFormatContext *s, int size)
1498 AVIContext *avi = s->priv_data;
1499 AVIOContext *pb = s->pb;
1500 int nb_index_entries, i;
1503 unsigned int index, tag, flags, pos, len, first_packet = 1;
1504 unsigned last_pos = -1;
1505 unsigned last_idx = -1;
1506 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1509 nb_index_entries = size / 16;
1510 if (nb_index_entries <= 0)
1511 return AVERROR_INVALIDDATA;
1513 idx1_pos = avio_tell(pb);
1514 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1515 if (avi_sync(s, 1) == 0)
1516 first_packet_pos = avio_tell(pb) - 8;
1517 avi->stream_index = -1;
1518 avio_seek(pb, idx1_pos, SEEK_SET);
1520 if (s->nb_streams == 1 && s->streams[0]->codec->codec_tag == AV_RL32("MMES")) {
1521 first_packet_pos = 0;
1522 data_offset = avi->movi_list;
1525 /* Read the entries and sort them in each stream component. */
1526 for (i = 0; i < nb_index_entries; i++) {
1530 tag = avio_rl32(pb);
1531 flags = avio_rl32(pb);
1532 pos = avio_rl32(pb);
1533 len = avio_rl32(pb);
1534 av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1535 i, tag, flags, pos, len);
1537 index = ((tag & 0xff) - '0') * 10;
1538 index += (tag >> 8 & 0xff) - '0';
1539 if (index >= s->nb_streams)
1541 st = s->streams[index];
1542 ast = st->priv_data;
1544 if (first_packet && first_packet_pos) {
1545 data_offset = first_packet_pos - pos;
1550 av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1552 // even if we have only a single stream, we should
1553 // switch to non-interleaved to get correct timestamps
1554 if (last_pos == pos)
1555 avi->non_interleaved = 1;
1556 if (last_idx != pos && len) {
1557 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1558 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1561 ast->cum_len += get_duration(ast, len);
1563 anykey |= flags&AVIIF_INDEX;
1566 for (index = 0; index < s->nb_streams; index++) {
1567 st = s->streams[index];
1568 if (st->nb_index_entries)
1569 st->index_entries[0].flags |= AVINDEX_KEYFRAME;
1575 /* Scan the index and consider any file with streams more than
1576 * 2 seconds or 64MB apart non-interleaved. */
1577 static int check_stream_max_drift(AVFormatContext *s)
1579 int64_t min_pos, pos;
1581 int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
1583 return AVERROR(ENOMEM);
1584 for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
1585 int64_t max_dts = INT64_MIN / 2;
1586 int64_t min_dts = INT64_MAX / 2;
1587 int64_t max_buffer = 0;
1589 min_pos = INT64_MAX;
1591 for (i = 0; i < s->nb_streams; i++) {
1592 AVStream *st = s->streams[i];
1593 AVIStream *ast = st->priv_data;
1594 int n = st->nb_index_entries;
1595 while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
1599 dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
1600 FFMAX(ast->sample_size, 1),
1601 st->time_base, AV_TIME_BASE_Q);
1602 min_dts = FFMIN(min_dts, dts);
1603 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
1606 for (i = 0; i < s->nb_streams; i++) {
1607 AVStream *st = s->streams[i];
1608 AVIStream *ast = st->priv_data;
1610 if (idx[i] && min_dts != INT64_MAX / 2) {
1612 dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
1613 FFMAX(ast->sample_size, 1),
1614 st->time_base, AV_TIME_BASE_Q);
1615 max_dts = FFMAX(max_dts, dts);
1616 max_buffer = FFMAX(max_buffer,
1617 av_rescale(dts - min_dts,
1618 st->codec->bit_rate,
1622 if (max_dts - min_dts > 2 * AV_TIME_BASE ||
1623 max_buffer > 1024 * 1024 * 8 * 8) {
1632 static int guess_ni_flag(AVFormatContext *s)
1635 int64_t last_start = 0;
1636 int64_t first_end = INT64_MAX;
1637 int64_t oldpos = avio_tell(s->pb);
1639 for (i = 0; i < s->nb_streams; i++) {
1640 AVStream *st = s->streams[i];
1641 int n = st->nb_index_entries;
1648 int64_t pos = st->index_entries[0].pos;
1649 avio_seek(s->pb, pos + 4, SEEK_SET);
1650 size = avio_rl32(s->pb);
1651 if (pos + size > st->index_entries[1].pos)
1652 last_start = INT64_MAX;
1655 if (st->index_entries[0].pos > last_start)
1656 last_start = st->index_entries[0].pos;
1657 if (st->index_entries[n - 1].pos < first_end)
1658 first_end = st->index_entries[n - 1].pos;
1660 avio_seek(s->pb, oldpos, SEEK_SET);
1662 if (last_start > first_end)
1665 return check_stream_max_drift(s);
1668 static int avi_load_index(AVFormatContext *s)
1670 AVIContext *avi = s->priv_data;
1671 AVIOContext *pb = s->pb;
1673 int64_t pos = avio_tell(pb);
1677 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1678 goto the_end; // maybe truncated file
1679 av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1681 tag = avio_rl32(pb);
1682 size = avio_rl32(pb);
1685 next = avio_tell(pb) + size + (size & 1);
1687 av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1694 if (tag == MKTAG('i', 'd', 'x', '1') &&
1695 avi_read_idx1(s, size) >= 0) {
1696 avi->index_loaded=2;
1698 }else if (tag == MKTAG('L', 'I', 'S', 'T')) {
1699 uint32_t tag1 = avio_rl32(pb);
1701 if (tag1 == MKTAG('I', 'N', 'F', 'O'))
1702 ff_read_riff_info(s, size - 4);
1706 if (avio_seek(pb, next, SEEK_SET) < 0)
1707 break; // something is wrong here
1711 avio_seek(pb, pos, SEEK_SET);
1715 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1717 AVIStream *ast2 = st2->priv_data;
1718 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1719 av_free_packet(&ast2->sub_pkt);
1720 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1721 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1722 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1725 static int avi_read_seek(AVFormatContext *s, int stream_index,
1726 int64_t timestamp, int flags)
1728 AVIContext *avi = s->priv_data;
1731 int64_t pos, pos_min;
1734 /* Does not matter which stream is requested dv in avi has the
1735 * stream information in the first video stream.
1740 if (!avi->index_loaded) {
1741 /* we only load the index on demand */
1743 avi->index_loaded |= 1;
1745 av_assert0(stream_index >= 0);
1747 st = s->streams[stream_index];
1748 ast = st->priv_data;
1749 index = av_index_search_timestamp(st,
1750 timestamp * FFMAX(ast->sample_size, 1),
1753 if (st->nb_index_entries > 0)
1754 av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
1755 timestamp * FFMAX(ast->sample_size, 1),
1756 st->index_entries[0].timestamp,
1757 st->index_entries[st->nb_index_entries - 1].timestamp);
1758 return AVERROR_INVALIDDATA;
1761 /* find the position */
1762 pos = st->index_entries[index].pos;
1763 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1765 av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
1766 timestamp, index, st->index_entries[index].timestamp);
1768 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1769 /* One and only one real stream for DV in AVI, and it has video */
1770 /* offsets. Calling with other stream indexes should have failed */
1771 /* the av_index_search_timestamp call above. */
1773 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
1776 /* Feed the DV video stream version of the timestamp to the */
1777 /* DV demux so it can synthesize correct timestamps. */
1778 ff_dv_offset_reset(avi->dv_demux, timestamp);
1780 avi->stream_index = -1;
1785 for (i = 0; i < s->nb_streams; i++) {
1786 AVStream *st2 = s->streams[i];
1787 AVIStream *ast2 = st2->priv_data;
1790 ast2->remaining = 0;
1792 if (ast2->sub_ctx) {
1793 seek_subtitle(st, st2, timestamp);
1797 if (st2->nb_index_entries <= 0)
1800 // av_assert1(st2->codec->block_align);
1801 av_assert0(fabs(av_q2d(st2->time_base) - ast2->scale / (double)ast2->rate) < av_q2d(st2->time_base) * 0.00000001);
1802 index = av_index_search_timestamp(st2,
1803 av_rescale_q(timestamp,
1806 FFMAX(ast2->sample_size, 1),
1808 AVSEEK_FLAG_BACKWARD |
1809 (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1812 ast2->seek_pos = st2->index_entries[index].pos;
1813 pos_min = FFMIN(pos_min,ast2->seek_pos);
1815 for (i = 0; i < s->nb_streams; i++) {
1816 AVStream *st2 = s->streams[i];
1817 AVIStream *ast2 = st2->priv_data;
1819 if (ast2->sub_ctx || st2->nb_index_entries <= 0)
1822 index = av_index_search_timestamp(
1824 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1825 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1828 while (!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
1830 ast2->frame_offset = st2->index_entries[index].timestamp;
1834 if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
1835 av_log(s, AV_LOG_ERROR, "Seek failed\n");
1838 avi->stream_index = -1;
1839 avi->dts_max = INT_MIN;
1843 static int avi_read_close(AVFormatContext *s)
1846 AVIContext *avi = s->priv_data;
1848 for (i = 0; i < s->nb_streams; i++) {
1849 AVStream *st = s->streams[i];
1850 AVIStream *ast = st->priv_data;
1853 av_freep(&ast->sub_ctx->pb);
1854 avformat_close_input(&ast->sub_ctx);
1856 av_freep(&ast->sub_buffer);
1857 av_free_packet(&ast->sub_pkt);
1861 av_freep(&avi->dv_demux);
1866 static int avi_probe(AVProbeData *p)
1870 /* check file header */
1871 for (i = 0; avi_headers[i][0]; i++)
1872 if (AV_RL32(p->buf ) == AV_RL32(avi_headers[i] ) &&
1873 AV_RL32(p->buf + 8) == AV_RL32(avi_headers[i] + 4))
1874 return AVPROBE_SCORE_MAX;
1879 AVInputFormat ff_avi_demuxer = {
1881 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1882 .priv_data_size = sizeof(AVIContext),
1883 .extensions = "avi",
1884 .read_probe = avi_probe,
1885 .read_header = avi_read_header,
1886 .read_packet = avi_read_packet,
1887 .read_close = avi_read_close,
1888 .read_seek = avi_read_seek,
1889 .priv_class = &demuxer_class,