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
22 #include "libavutil/avassert.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/bswap.h"
25 #include "libavutil/opt.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/internal.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/mathematics.h"
36 typedef struct AVIStream {
37 int64_t frame_offset; /* current frame (video) or byte (audio) counter
38 * (used to compute the pts) */
44 int sample_size; /* size of one sample (or packet)
45 * (in the rate/scale sense) in bytes */
47 int64_t cum_len; /* temporary storage (used during seek) */
48 int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
52 int dshow_block_align; /* block align variable used to emulate bugs in
53 * the MS dshow demuxer */
55 AVFormatContext *sub_ctx;
74 DVDemuxContext *dv_demux;
77 #define MAX_ODML_DEPTH 1000
82 static const AVOption options[] = {
83 { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_INT, {.i64 = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
87 static const AVClass demuxer_class = {
89 .item_name = av_default_item_name,
91 .version = LIBAVUTIL_VERSION_INT,
92 .category = AV_CLASS_CATEGORY_DEMUXER,
96 static const char avi_headers[][8] = {
97 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
98 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
99 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
100 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
101 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
105 static const AVMetadataConv avi_metadata_conv[] = {
110 static int avi_load_index(AVFormatContext *s);
111 static int guess_ni_flag(AVFormatContext *s);
113 #define print_tag(str, tag, size) \
114 av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
117 (tag >> 16) & 0xff, \
118 (tag >> 24) & 0xff, \
121 static inline int get_duration(AVIStream *ast, int len)
123 if (ast->sample_size)
125 else if (ast->dshow_block_align)
126 return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
131 static int get_riff(AVFormatContext *s, AVIOContext *pb)
133 AVIContext *avi = s->priv_data;
137 /* check RIFF header */
138 avio_read(pb, header, 4);
139 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
140 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
141 avio_read(pb, header + 4, 4);
143 for (i = 0; avi_headers[i][0]; i++)
144 if (!memcmp(header, avi_headers[i], 8))
146 if (!avi_headers[i][0])
147 return AVERROR_INVALIDDATA;
149 if (header[7] == 0x19)
150 av_log(s, AV_LOG_INFO,
151 "This file has been generated by a totally broken muxer.\n");
156 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
158 AVIContext *avi = s->priv_data;
159 AVIOContext *pb = s->pb;
160 int longs_pre_entry = avio_rl16(pb);
161 int index_sub_type = avio_r8(pb);
162 int index_type = avio_r8(pb);
163 int entries_in_use = avio_rl32(pb);
164 int chunk_id = avio_rl32(pb);
165 int64_t base = avio_rl64(pb);
166 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
167 ((chunk_id >> 8 & 0xFF) - '0');
171 int64_t last_pos = -1;
172 int64_t filesize = avi->fsize;
175 "longs_pre_entry:%d index_type:%d entries_in_use:%d "
176 "chunk_id:%X base:%16"PRIX64"\n",
183 if (stream_id >= s->nb_streams || stream_id < 0)
184 return AVERROR_INVALIDDATA;
185 st = s->streams[stream_id];
189 return AVERROR_INVALIDDATA;
193 if (index_type && longs_pre_entry != 2)
194 return AVERROR_INVALIDDATA;
196 return AVERROR_INVALIDDATA;
198 if (filesize > 0 && base >= filesize) {
199 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
200 if (base >> 32 == (base & 0xFFFFFFFF) &&
201 (base & 0xFFFFFFFF) < filesize &&
202 filesize <= 0xFFFFFFFF)
205 return AVERROR_INVALIDDATA;
208 for (i = 0; i < entries_in_use; i++) {
210 int64_t pos = avio_rl32(pb) + base - 8;
211 int len = avio_rl32(pb);
216 av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
219 return AVERROR_INVALIDDATA;
221 if (last_pos == pos || pos == base - 8)
222 avi->non_interleaved = 1;
223 if (last_pos != pos && (len || !ast->sample_size))
224 av_add_index_entry(st, pos, ast->cum_len, len, 0,
225 key ? AVINDEX_KEYFRAME : 0);
227 ast->cum_len += get_duration(ast, len);
232 offset = avio_rl64(pb);
233 avio_rl32(pb); /* size */
234 duration = avio_rl32(pb);
237 return AVERROR_INVALIDDATA;
241 if (avi->odml_depth > MAX_ODML_DEPTH) {
242 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
243 return AVERROR_INVALIDDATA;
246 if (avio_seek(pb, offset + 8, SEEK_SET) < 0)
249 read_braindead_odml_indx(s, frame_num);
251 frame_num += duration;
253 if (avio_seek(pb, pos, SEEK_SET) < 0) {
254 av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index\n");
260 avi->index_loaded = 2;
264 static void clean_index(AVFormatContext *s)
269 for (i = 0; i < s->nb_streams; i++) {
270 AVStream *st = s->streams[i];
271 AVIStream *ast = st->priv_data;
272 int n = st->nb_index_entries;
273 int max = ast->sample_size;
274 int64_t pos, size, ts;
276 if (n != 1 || ast->sample_size == 0)
282 pos = st->index_entries[0].pos;
283 size = st->index_entries[0].size;
284 ts = st->index_entries[0].timestamp;
286 for (j = 0; j < size; j += max)
287 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
292 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
295 AVIOContext *pb = s->pb;
301 if (size == UINT_MAX)
302 return AVERROR(EINVAL);
303 value = av_malloc(size + 1);
305 return AVERROR(ENOMEM);
306 avio_read(pb, value, size);
311 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
312 AV_DICT_DONT_STRDUP_VAL);
315 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
316 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
318 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
320 char month[4], time[9], buffer[64];
322 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
323 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
324 month, &day, time, &year) == 4) {
325 for (i = 0; i < 12; i++)
326 if (!av_strcasecmp(month, months[i])) {
327 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
328 year, i + 1, day, time);
329 av_dict_set(metadata, "creation_time", buffer, 0);
331 } else if (date[4] == '/' && date[7] == '/') {
332 date[4] = date[7] = '-';
333 av_dict_set(metadata, "creation_time", date, 0);
337 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
339 while (avio_tell(s->pb) < end) {
340 uint32_t tag = avio_rl32(s->pb);
341 uint32_t size = avio_rl32(s->pb);
343 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
345 uint64_t tag_end = avio_tell(s->pb) + size;
346 while (avio_tell(s->pb) < tag_end) {
347 uint16_t tag = avio_rl16(s->pb);
348 uint16_t size = avio_rl16(s->pb);
349 const char *name = NULL;
350 char buffer[64] = { 0 };
351 size -= avio_read(s->pb, buffer,
352 FFMIN(size, sizeof(buffer) - 1));
361 name = "creation_time";
362 if (buffer[4] == ':' && buffer[7] == ':')
363 buffer[4] = buffer[7] = '-';
367 av_dict_set(&s->metadata, name, buffer, 0);
368 avio_skip(s->pb, size);
373 avio_skip(s->pb, size);
379 static int avi_read_header(AVFormatContext *s)
381 AVIContext *avi = s->priv_data;
382 AVIOContext *pb = s->pb;
383 unsigned int tag, tag1, handler;
384 int codec_type, stream_index, frame_period;
388 AVIStream *ast = NULL;
389 int avih_width = 0, avih_height = 0;
390 int amv_file_format = 0;
391 uint64_t list_end = 0;
393 AVDictionaryEntry *dict_entry;
395 avi->stream_index = -1;
397 ret = get_riff(s, pb);
401 av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
403 avi->io_fsize = avi->fsize = avio_size(pb);
404 if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
405 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
415 size = avio_rl32(pb);
417 print_tag("tag", tag, size);
420 case MKTAG('L', 'I', 'S', 'T'):
421 list_end = avio_tell(pb) + size;
422 /* Ignored, except at start of video packets. */
423 tag1 = avio_rl32(pb);
425 print_tag("list", tag1, 0);
427 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
428 avi->movi_list = avio_tell(pb) - 4;
430 avi->movi_end = avi->movi_list + size + (size & 1);
432 avi->movi_end = avi->fsize;
433 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
435 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
436 ff_read_riff_info(s, size - 4);
437 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
438 avi_read_nikon(s, list_end);
441 case MKTAG('I', 'D', 'I', 'T'):
443 unsigned char date[64] = { 0 };
445 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
447 avi_metadata_creation_time(&s->metadata, date);
450 case MKTAG('d', 'm', 'l', 'h'):
452 avio_skip(pb, size + (size & 1));
454 case MKTAG('a', 'm', 'v', 'h'):
456 case MKTAG('a', 'v', 'i', 'h'):
458 /* using frame_period is bad idea */
459 frame_period = avio_rl32(pb);
460 avio_rl32(pb); /* max. bytes per second */
462 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
464 avio_skip(pb, 2 * 4);
467 avih_width = avio_rl32(pb);
468 avih_height = avio_rl32(pb);
470 avio_skip(pb, size - 10 * 4);
472 case MKTAG('s', 't', 'r', 'h'):
475 tag1 = avio_rl32(pb);
476 handler = avio_rl32(pb); /* codec tag */
478 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
479 avio_skip(pb, size - 8);
483 st = avformat_new_stream(s, NULL);
487 st->id = stream_index;
488 ast = av_mallocz(sizeof(AVIStream));
494 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
495 : MKTAG('v', 'i', 'd', 's');
497 print_tag("strh", tag1, -1);
499 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
500 tag1 == MKTAG('i', 'v', 'a', 's')) {
503 /* After some consideration -- I don't think we
504 * have to support anything but DV in type1 AVIs. */
505 if (s->nb_streams != 1)
508 if (handler != MKTAG('d', 'v', 's', 'd') &&
509 handler != MKTAG('d', 'v', 'h', 'd') &&
510 handler != MKTAG('d', 'v', 's', 'l'))
513 ast = s->streams[0]->priv_data;
514 av_freep(&s->streams[0]->codec->extradata);
515 av_freep(&s->streams[0]->codec);
516 if (s->streams[0]->info)
517 av_freep(&s->streams[0]->info->duration_error);
518 av_freep(&s->streams[0]->info);
519 av_freep(&s->streams[0]);
521 if (CONFIG_DV_DEMUXER) {
522 avi->dv_demux = avpriv_dv_init_demux(s);
526 s->streams[0]->priv_data = ast;
527 avio_skip(pb, 3 * 4);
528 ast->scale = avio_rl32(pb);
529 ast->rate = avio_rl32(pb);
530 avio_skip(pb, 4); /* start time */
532 dv_dur = avio_rl32(pb);
533 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
534 dv_dur *= AV_TIME_BASE;
535 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
537 /* else, leave duration alone; timing estimation in utils.c
538 * will make a guess based on bitrate. */
540 stream_index = s->nb_streams - 1;
541 avio_skip(pb, size - 9 * 4);
545 av_assert0(stream_index < s->nb_streams);
546 st->codec->stream_codec_tag = handler;
548 avio_rl32(pb); /* flags */
549 avio_rl16(pb); /* priority */
550 avio_rl16(pb); /* language */
551 avio_rl32(pb); /* initial frame */
552 ast->scale = avio_rl32(pb);
553 ast->rate = avio_rl32(pb);
554 if (!(ast->scale && ast->rate)) {
555 av_log(s, AV_LOG_WARNING,
556 "scale/rate is %u/%u which is invalid. "
557 "(This file has been generated by broken software.)\n",
562 ast->scale = frame_period;
568 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
570 ast->cum_len = avio_rl32(pb); /* start */
571 st->nb_frames = avio_rl32(pb);
574 avio_rl32(pb); /* buffer size */
575 avio_rl32(pb); /* quality */
576 if (ast->cum_len*ast->scale/ast->rate > 3600) {
577 av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
578 return AVERROR_INVALIDDATA;
580 ast->sample_size = avio_rl32(pb); /* sample ssize */
581 ast->cum_len *= FFMAX(1, ast->sample_size);
582 av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
583 ast->rate, ast->scale, ast->sample_size);
586 case MKTAG('v', 'i', 'd', 's'):
587 codec_type = AVMEDIA_TYPE_VIDEO;
589 ast->sample_size = 0;
591 case MKTAG('a', 'u', 'd', 's'):
592 codec_type = AVMEDIA_TYPE_AUDIO;
594 case MKTAG('t', 'x', 't', 's'):
595 codec_type = AVMEDIA_TYPE_SUBTITLE;
597 case MKTAG('d', 'a', 't', 's'):
598 codec_type = AVMEDIA_TYPE_DATA;
601 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
603 if (ast->sample_size == 0) {
604 st->duration = st->nb_frames;
605 if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) {
606 av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n");
607 st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end);
610 ast->frame_offset = ast->cum_len;
611 avio_skip(pb, size - 12 * 4);
613 case MKTAG('s', 't', 'r', 'f'):
617 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
620 uint64_t cur_pos = avio_tell(pb);
622 if (cur_pos < list_end)
623 size = FFMIN(size, list_end - cur_pos);
624 st = s->streams[stream_index];
625 switch (codec_type) {
626 case AVMEDIA_TYPE_VIDEO:
627 if (amv_file_format) {
628 st->codec->width = avih_width;
629 st->codec->height = avih_height;
630 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
631 st->codec->codec_id = AV_CODEC_ID_AMV;
635 tag1 = ff_get_bmp_header(pb, st, &esize);
637 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
638 tag1 == MKTAG('D', 'X', 'S', 'A')) {
639 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
640 st->codec->codec_tag = tag1;
641 st->codec->codec_id = AV_CODEC_ID_XSUB;
645 if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) {
646 if (esize == size-1 && (esize&1)) {
647 st->codec->extradata_size = esize - 10 * 4;
649 st->codec->extradata_size = size - 10 * 4;
650 st->codec->extradata = av_malloc(st->codec->extradata_size +
651 FF_INPUT_BUFFER_PADDING_SIZE);
652 if (!st->codec->extradata) {
653 st->codec->extradata_size = 0;
654 return AVERROR(ENOMEM);
657 st->codec->extradata,
658 st->codec->extradata_size);
661 // FIXME: check if the encoder really did this correctly
662 if (st->codec->extradata_size & 1)
665 /* Extract palette from extradata if bpp <= 8.
666 * This code assumes that extradata contains only palette.
667 * This is true for all paletted codecs implemented in
669 if (st->codec->extradata_size &&
670 (st->codec->bits_per_coded_sample <= 8)) {
671 int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
672 const uint8_t *pal_src;
674 pal_size = FFMIN(pal_size, st->codec->extradata_size);
675 pal_src = st->codec->extradata +
676 st->codec->extradata_size - pal_size;
677 for (i = 0; i < pal_size / 4; i++)
678 ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i);
682 print_tag("video", tag1, 0);
684 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
685 st->codec->codec_tag = tag1;
686 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
688 /* This is needed to get the pict type which is necessary
689 * for generating correct pts. */
690 st->need_parsing = AVSTREAM_PARSE_HEADERS;
692 if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
693 st->codec->extradata_size < 1U << 30) {
694 st->codec->extradata_size += 9;
695 st->codec->extradata = av_realloc_f(st->codec->extradata,
697 st->codec->extradata_size +
698 FF_INPUT_BUFFER_PADDING_SIZE);
699 if (st->codec->extradata)
700 memcpy(st->codec->extradata + st->codec->extradata_size - 9,
703 st->codec->height = FFABS(st->codec->height);
705 // avio_skip(pb, size - 5 * 4);
707 case AVMEDIA_TYPE_AUDIO:
708 ret = ff_get_wav_header(pb, st->codec, size);
711 ast->dshow_block_align = st->codec->block_align;
712 if (ast->sample_size && st->codec->block_align &&
713 ast->sample_size != st->codec->block_align) {
716 "sample size (%d) != block align (%d)\n",
718 st->codec->block_align);
719 ast->sample_size = st->codec->block_align;
722 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
725 /* Force parsing as several audio frames can be in
726 * one packet and timestamps refer to packet start. */
727 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
728 /* ADTS header is in extradata, AAC without header must be
729 * stored as exact frames. Parser not needed and it will
731 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
732 st->codec->extradata_size)
733 st->need_parsing = AVSTREAM_PARSE_NONE;
734 /* AVI files with Xan DPCM audio (wrongly) declare PCM
735 * audio in the header but have Axan as stream_code_tag. */
736 if (st->codec->stream_codec_tag == AV_RL32("Axan")) {
737 st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
738 st->codec->codec_tag = 0;
739 ast->dshow_block_align = 0;
741 if (amv_file_format) {
742 st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
743 ast->dshow_block_align = 0;
745 if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
746 av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
747 ast->dshow_block_align = 0;
749 if (st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
750 st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
751 st->codec->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
752 av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
753 ast->sample_size = 0;
756 case AVMEDIA_TYPE_SUBTITLE:
757 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
758 st->request_probe= 1;
762 st->codec->codec_type = AVMEDIA_TYPE_DATA;
763 st->codec->codec_id = AV_CODEC_ID_NONE;
764 st->codec->codec_tag = 0;
770 case MKTAG('s', 't', 'r', 'd'):
771 if (stream_index >= (unsigned)s->nb_streams
772 || s->streams[stream_index]->codec->extradata_size
773 || s->streams[stream_index]->codec->codec_tag == MKTAG('H','2','6','4')) {
776 uint64_t cur_pos = avio_tell(pb);
777 if (cur_pos < list_end)
778 size = FFMIN(size, list_end - cur_pos);
779 st = s->streams[stream_index];
782 st->codec->extradata_size= size;
783 st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
784 if (!st->codec->extradata) {
785 st->codec->extradata_size= 0;
786 return AVERROR(ENOMEM);
788 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
791 if (st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
795 case MKTAG('i', 'n', 'd', 'x'):
797 if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
799 read_braindead_odml_indx(s, 0) < 0 &&
800 (s->error_recognition & AV_EF_EXPLODE))
802 avio_seek(pb, i + size, SEEK_SET);
804 case MKTAG('v', 'p', 'r', 'p'):
805 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
806 AVRational active, active_aspect;
808 st = s->streams[stream_index];
815 active_aspect.den = avio_rl16(pb);
816 active_aspect.num = avio_rl16(pb);
817 active.num = avio_rl32(pb);
818 active.den = avio_rl32(pb);
819 avio_rl32(pb); // nbFieldsPerFrame
821 if (active_aspect.num && active_aspect.den &&
822 active.num && active.den) {
823 st->sample_aspect_ratio = av_div_q(active_aspect, active);
824 av_dlog(s, "vprp %d/%d %d/%d\n",
825 active_aspect.num, active_aspect.den,
826 active.num, active.den);
832 case MKTAG('s', 't', 'r', 'n'):
834 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
840 if (size > 1000000) {
841 av_log(s, AV_LOG_ERROR,
842 "Something went wrong during header parsing, "
843 "I will ignore it and try to continue anyway.\n");
844 if (s->error_recognition & AV_EF_EXPLODE)
846 avi->movi_list = avio_tell(pb) - 4;
847 avi->movi_end = avi->fsize;
858 /* check stream number */
859 if (stream_index != s->nb_streams - 1) {
862 return AVERROR_INVALIDDATA;
865 if (!avi->index_loaded && pb->seekable)
867 avi->index_loaded |= 1;
868 avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
870 dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0);
871 if (dict_entry && !strcmp(dict_entry->value, "PotEncoder"))
872 for (i = 0; i < s->nb_streams; i++) {
873 AVStream *st = s->streams[i];
874 if ( st->codec->codec_id == AV_CODEC_ID_MPEG1VIDEO
875 || st->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO)
876 st->need_parsing = AVSTREAM_PARSE_FULL;
879 for (i = 0; i < s->nb_streams; i++) {
880 AVStream *st = s->streams[i];
881 if (st->nb_index_entries)
884 // DV-in-AVI cannot be non-interleaved, if set this must be
887 avi->non_interleaved = 0;
888 if (i == s->nb_streams && avi->non_interleaved) {
889 av_log(s, AV_LOG_WARNING,
890 "Non-interleaved AVI without index, switching to interleaved\n");
891 avi->non_interleaved = 0;
894 if (avi->non_interleaved) {
895 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
899 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
900 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
905 static int read_gab2_sub(AVStream *st, AVPacket *pkt)
907 if (pkt->data && !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
909 int score = AVPROBE_SCORE_EXTENSION, ret;
910 AVIStream *ast = st->priv_data;
911 AVInputFormat *sub_demuxer;
912 AVRational time_base;
913 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
915 0, NULL, NULL, NULL, NULL);
917 unsigned int desc_len = avio_rl32(pb);
919 if (desc_len > pb->buf_end - pb->buf_ptr)
922 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
923 avio_skip(pb, desc_len - ret);
925 av_dict_set(&st->metadata, "title", desc, 0);
927 avio_rl16(pb); /* flags? */
928 avio_rl32(pb); /* data size */
930 pd = (AVProbeData) { .buf = pb->buf_ptr,
931 .buf_size = pb->buf_end - pb->buf_ptr };
932 if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
935 if (!(ast->sub_ctx = avformat_alloc_context()))
938 ast->sub_ctx->pb = pb;
939 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
940 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
941 *st->codec = *ast->sub_ctx->streams[0]->codec;
942 ast->sub_ctx->streams[0]->codec->extradata = NULL;
943 time_base = ast->sub_ctx->streams[0]->time_base;
944 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
946 ast->sub_buffer = pkt->data;
947 memset(pkt, 0, sizeof(*pkt));
956 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
959 AVIStream *ast, *next_ast = next_st->priv_data;
960 int64_t ts, next_ts, ts_min = INT64_MAX;
961 AVStream *st, *sub_st = NULL;
964 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
967 for (i = 0; i < s->nb_streams; i++) {
970 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
971 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
972 if (ts <= next_ts && ts < ts_min) {
980 ast = sub_st->priv_data;
982 pkt->stream_index = sub_st->index;
984 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
985 ast->sub_pkt.data = NULL;
990 static int get_stream_idx(int *d)
992 if (d[0] >= '0' && d[0] <= '9' &&
993 d[1] >= '0' && d[1] <= '9') {
994 return (d[0] - '0') * 10 + (d[1] - '0');
996 return 100; // invalid stream ID
1002 * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
1004 static int avi_sync(AVFormatContext *s, int exit_early)
1006 AVIContext *avi = s->priv_data;
1007 AVIOContext *pb = s->pb;
1014 memset(d, -1, sizeof(d));
1015 for (i = sync = avio_tell(pb); !url_feof(pb); i++) {
1018 for (j = 0; j < 7; j++)
1022 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
1024 n = get_stream_idx(d + 2);
1025 av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
1026 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
1027 if (i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127)
1031 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
1033 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
1034 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
1035 avio_skip(pb, size);
1040 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
1045 n = get_stream_idx(d);
1047 if (!((i - avi->last_pkt_pos) & 1) &&
1048 get_stream_idx(d + 1) < s->nb_streams)
1051 // detect ##ix chunk and skip
1052 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
1053 avio_skip(pb, size);
1058 if (n < s->nb_streams) {
1062 ast = st->priv_data;
1065 av_log(s, AV_LOG_WARNING, "Skiping foreign stream %d packet\n", n);
1069 if (s->nb_streams >= 2) {
1070 AVStream *st1 = s->streams[1];
1071 AVIStream *ast1 = st1->priv_data;
1072 // workaround for broken small-file-bug402.avi
1073 if ( d[2] == 'w' && d[3] == 'b'
1075 && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
1076 && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
1077 && ast->prefix == 'd'*256+'c'
1078 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
1083 av_log(s, AV_LOG_WARNING,
1084 "Invalid stream + prefix combination, assuming audio.\n");
1088 if (!avi->dv_demux &&
1089 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
1090 // FIXME: needs a little reordering
1091 (st->discard >= AVDISCARD_NONKEY &&
1092 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1093 || st->discard >= AVDISCARD_ALL)) {
1095 ast->frame_offset += get_duration(ast, size);
1096 avio_skip(pb, size);
1101 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1102 int k = avio_r8(pb);
1103 int last = (k + avio_r8(pb) - 1) & 0xFF;
1105 avio_rl16(pb); // flags
1107 // b + (g << 8) + (r << 16);
1108 for (; k <= last; k++)
1109 ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;
1113 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1114 d[2] < 128 && d[3] < 128) ||
1115 d[2] * 256 + d[3] == ast->prefix /* ||
1116 (d[2] == 'd' && d[3] == 'c') ||
1117 (d[2] == 'w' && d[3] == 'b') */) {
1120 if (d[2] * 256 + d[3] == ast->prefix)
1121 ast->prefix_count++;
1123 ast->prefix = d[2] * 256 + d[3];
1124 ast->prefix_count = 0;
1127 avi->stream_index = n;
1128 ast->packet_size = size + 8;
1129 ast->remaining = size;
1131 if (size || !ast->sample_size) {
1132 uint64_t pos = avio_tell(pb) - 8;
1133 if (!st->index_entries || !st->nb_index_entries ||
1134 st->index_entries[st->nb_index_entries - 1].pos < pos) {
1135 av_add_index_entry(st, pos, ast->frame_offset, size,
1136 0, AVINDEX_KEYFRAME);
1149 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1151 AVIContext *avi = s->priv_data;
1152 AVIOContext *pb = s->pb;
1154 #if FF_API_DESTRUCT_PACKET
1158 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1159 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1164 if (avi->non_interleaved) {
1165 int best_stream_index = 0;
1166 AVStream *best_st = NULL;
1167 AVIStream *best_ast;
1168 int64_t best_ts = INT64_MAX;
1171 for (i = 0; i < s->nb_streams; i++) {
1172 AVStream *st = s->streams[i];
1173 AVIStream *ast = st->priv_data;
1174 int64_t ts = ast->frame_offset;
1177 if (!st->nb_index_entries)
1180 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1181 if (!ast->remaining && ts > last_ts)
1184 ts = av_rescale_q(ts, st->time_base,
1185 (AVRational) { FFMAX(1, ast->sample_size),
1188 av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
1189 st->time_base.num, st->time_base.den, ast->frame_offset);
1193 best_stream_index = i;
1199 best_ast = best_st->priv_data;
1200 best_ts = best_ast->frame_offset;
1201 if (best_ast->remaining) {
1202 i = av_index_search_timestamp(best_st,
1205 AVSEEK_FLAG_BACKWARD);
1207 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1209 best_ast->frame_offset = best_st->index_entries[i].timestamp;
1213 int64_t pos = best_st->index_entries[i].pos;
1214 pos += best_ast->packet_size - best_ast->remaining;
1215 if (avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
1218 av_assert0(best_ast->remaining <= best_ast->packet_size);
1220 avi->stream_index = best_stream_index;
1221 if (!best_ast->remaining)
1222 best_ast->packet_size =
1223 best_ast->remaining = best_st->index_entries[i].size;
1230 if (avi->stream_index >= 0) {
1231 AVStream *st = s->streams[avi->stream_index];
1232 AVIStream *ast = st->priv_data;
1235 if (get_subtitle_pkt(s, st, pkt))
1238 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1239 if (ast->sample_size <= 1)
1241 else if (ast->sample_size < 32)
1242 // arbitrary multiplier to avoid tiny packets for raw PCM data
1243 size = 1024 * ast->sample_size;
1245 size = ast->sample_size;
1247 if (size > ast->remaining)
1248 size = ast->remaining;
1249 avi->last_pkt_pos = avio_tell(pb);
1250 err = av_get_packet(pb, pkt, size);
1255 if (ast->has_pal && pkt->size < (unsigned)INT_MAX / 2) {
1257 pal = av_packet_new_side_data(pkt,
1258 AV_PKT_DATA_PALETTE,
1261 av_log(s, AV_LOG_ERROR,
1262 "Failed to allocate data for palette\n");
1264 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1269 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1270 AVBufferRef *avbuf = pkt->buf;
1271 #if FF_API_DESTRUCT_PACKET
1272 FF_DISABLE_DEPRECATION_WARNINGS
1273 dstr = pkt->destruct;
1274 FF_ENABLE_DEPRECATION_WARNINGS
1276 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1277 pkt->data, pkt->size, pkt->pos);
1278 #if FF_API_DESTRUCT_PACKET
1279 FF_DISABLE_DEPRECATION_WARNINGS
1280 pkt->destruct = dstr;
1281 FF_ENABLE_DEPRECATION_WARNINGS
1284 pkt->flags |= AV_PKT_FLAG_KEY;
1286 av_free_packet(pkt);
1287 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1288 !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1289 ast->frame_offset++;
1290 avi->stream_index = -1;
1294 /* XXX: How to handle B-frames in AVI? */
1295 pkt->dts = ast->frame_offset;
1296 // pkt->dts += ast->start;
1297 if (ast->sample_size)
1298 pkt->dts /= ast->sample_size;
1300 "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
1301 "base:%d st:%d size:%d\n",
1310 pkt->stream_index = avi->stream_index;
1312 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1315 av_assert0(st->index_entries);
1317 index = av_index_search_timestamp(st, ast->frame_offset, 0);
1318 e = &st->index_entries[index];
1320 if (index >= 0 && e->timestamp == ast->frame_offset) {
1321 if (index == st->nb_index_entries-1) {
1325 for (i=0; i<FFMIN(size,256); i++) {
1326 if (st->codec->codec_id == AV_CODEC_ID_MPEG4) {
1327 if (state == 0x1B6) {
1328 key= !(pkt->data[i]&0xC0);
1333 state= (state<<8) + pkt->data[i];
1336 e->flags &= ~AVINDEX_KEYFRAME;
1338 if (e->flags & AVINDEX_KEYFRAME)
1339 pkt->flags |= AV_PKT_FLAG_KEY;
1342 pkt->flags |= AV_PKT_FLAG_KEY;
1344 ast->frame_offset += get_duration(ast, pkt->size);
1346 ast->remaining -= err;
1347 if (!ast->remaining) {
1348 avi->stream_index = -1;
1349 ast->packet_size = 0;
1352 if (!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos) {
1353 av_free_packet(pkt);
1358 if (!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1) {
1359 int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
1361 if (avi->dts_max - dts > 2*AV_TIME_BASE) {
1362 avi->non_interleaved= 1;
1363 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
1364 }else if (avi->dts_max < dts)
1371 if ((err = avi_sync(s, 0)) < 0)
1376 /* XXX: We make the implicit supposition that the positions are sorted
1377 * for each stream. */
1378 static int avi_read_idx1(AVFormatContext *s, int size)
1380 AVIContext *avi = s->priv_data;
1381 AVIOContext *pb = s->pb;
1382 int nb_index_entries, i;
1385 unsigned int index, tag, flags, pos, len, first_packet = 1;
1386 unsigned last_pos = -1;
1387 unsigned last_idx = -1;
1388 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1391 nb_index_entries = size / 16;
1392 if (nb_index_entries <= 0)
1393 return AVERROR_INVALIDDATA;
1395 idx1_pos = avio_tell(pb);
1396 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1397 if (avi_sync(s, 1) == 0)
1398 first_packet_pos = avio_tell(pb) - 8;
1399 avi->stream_index = -1;
1400 avio_seek(pb, idx1_pos, SEEK_SET);
1402 if (s->nb_streams == 1 && s->streams[0]->codec->codec_tag == AV_RL32("MMES")) {
1403 first_packet_pos = 0;
1404 data_offset = avi->movi_list;
1407 /* Read the entries and sort them in each stream component. */
1408 for (i = 0; i < nb_index_entries; i++) {
1412 tag = avio_rl32(pb);
1413 flags = avio_rl32(pb);
1414 pos = avio_rl32(pb);
1415 len = avio_rl32(pb);
1416 av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1417 i, tag, flags, pos, len);
1419 index = ((tag & 0xff) - '0') * 10;
1420 index += (tag >> 8 & 0xff) - '0';
1421 if (index >= s->nb_streams)
1423 st = s->streams[index];
1424 ast = st->priv_data;
1426 if (first_packet && first_packet_pos && len) {
1427 data_offset = first_packet_pos - pos;
1432 av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1434 // even if we have only a single stream, we should
1435 // switch to non-interleaved to get correct timestamps
1436 if (last_pos == pos)
1437 avi->non_interleaved = 1;
1438 if (last_idx != pos && len) {
1439 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1440 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1443 ast->cum_len += get_duration(ast, len);
1445 anykey |= flags&AVIIF_INDEX;
1448 for (index = 0; index < s->nb_streams; index++) {
1449 st = s->streams[index];
1450 if (st->nb_index_entries)
1451 st->index_entries[0].flags |= AVINDEX_KEYFRAME;
1457 static int guess_ni_flag(AVFormatContext *s)
1460 int64_t last_start = 0;
1461 int64_t first_end = INT64_MAX;
1462 int64_t oldpos = avio_tell(s->pb);
1464 int64_t min_pos, pos;
1466 for (i = 0; i < s->nb_streams; i++) {
1467 AVStream *st = s->streams[i];
1468 int n = st->nb_index_entries;
1475 int64_t pos = st->index_entries[0].pos;
1476 avio_seek(s->pb, pos + 4, SEEK_SET);
1477 size = avio_rl32(s->pb);
1478 if (pos + size > st->index_entries[1].pos)
1479 last_start = INT64_MAX;
1482 if (st->index_entries[0].pos > last_start)
1483 last_start = st->index_entries[0].pos;
1484 if (st->index_entries[n - 1].pos < first_end)
1485 first_end = st->index_entries[n - 1].pos;
1487 avio_seek(s->pb, oldpos, SEEK_SET);
1488 if (last_start > first_end)
1490 idx= av_mallocz(sizeof(*idx) * s->nb_streams);
1491 for (min_pos=pos=0; min_pos!=INT64_MAX; pos= min_pos+1LU) {
1492 int64_t max_dts = INT64_MIN/2, min_dts= INT64_MAX/2;
1493 min_pos = INT64_MAX;
1495 for (i=0; i<s->nb_streams; i++) {
1496 AVStream *st = s->streams[i];
1497 AVIStream *ast = st->priv_data;
1498 int n= st->nb_index_entries;
1499 while (idx[i]<n && st->index_entries[idx[i]].pos < pos)
1502 min_dts = FFMIN(min_dts, av_rescale_q(st->index_entries[idx[i]].timestamp/FFMAX(ast->sample_size, 1), st->time_base, AV_TIME_BASE_Q));
1503 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
1506 max_dts = FFMAX(max_dts, av_rescale_q(st->index_entries[idx[i]-1].timestamp/FFMAX(ast->sample_size, 1), st->time_base, AV_TIME_BASE_Q));
1508 if (max_dts - min_dts > 2*AV_TIME_BASE) {
1517 static int avi_load_index(AVFormatContext *s)
1519 AVIContext *avi = s->priv_data;
1520 AVIOContext *pb = s->pb;
1522 int64_t pos = avio_tell(pb);
1526 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1527 goto the_end; // maybe truncated file
1528 av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1530 tag = avio_rl32(pb);
1531 size = avio_rl32(pb);
1534 next = avio_tell(pb) + size + (size & 1);
1536 av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1543 if (tag == MKTAG('i', 'd', 'x', '1') &&
1544 avi_read_idx1(s, size) >= 0) {
1545 avi->index_loaded=2;
1547 }else if (tag == MKTAG('L', 'I', 'S', 'T')) {
1548 uint32_t tag1 = avio_rl32(pb);
1550 if (tag1 == MKTAG('I', 'N', 'F', 'O'))
1551 ff_read_riff_info(s, size - 4);
1555 if (avio_seek(pb, next, SEEK_SET) < 0)
1556 break; // something is wrong here
1560 avio_seek(pb, pos, SEEK_SET);
1564 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1566 AVIStream *ast2 = st2->priv_data;
1567 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1568 av_free_packet(&ast2->sub_pkt);
1569 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1570 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1571 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1574 static int avi_read_seek(AVFormatContext *s, int stream_index,
1575 int64_t timestamp, int flags)
1577 AVIContext *avi = s->priv_data;
1580 int64_t pos, pos_min;
1583 if (!avi->index_loaded) {
1584 /* we only load the index on demand */
1586 avi->index_loaded |= 1;
1588 av_assert0(stream_index >= 0);
1590 st = s->streams[stream_index];
1591 ast = st->priv_data;
1592 index = av_index_search_timestamp(st,
1593 timestamp * FFMAX(ast->sample_size, 1),
1596 if (st->nb_index_entries > 0)
1597 av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
1598 timestamp * FFMAX(ast->sample_size, 1),
1599 st->index_entries[0].timestamp,
1600 st->index_entries[st->nb_index_entries - 1].timestamp);
1601 return AVERROR_INVALIDDATA;
1604 /* find the position */
1605 pos = st->index_entries[index].pos;
1606 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1608 av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
1609 timestamp, index, st->index_entries[index].timestamp);
1611 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1612 /* One and only one real stream for DV in AVI, and it has video */
1613 /* offsets. Calling with other stream indexes should have failed */
1614 /* the av_index_search_timestamp call above. */
1615 av_assert0(stream_index == 0);
1617 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
1620 /* Feed the DV video stream version of the timestamp to the */
1621 /* DV demux so it can synthesize correct timestamps. */
1622 ff_dv_offset_reset(avi->dv_demux, timestamp);
1624 avi->stream_index = -1;
1629 for (i = 0; i < s->nb_streams; i++) {
1630 AVStream *st2 = s->streams[i];
1631 AVIStream *ast2 = st2->priv_data;
1634 ast2->remaining = 0;
1636 if (ast2->sub_ctx) {
1637 seek_subtitle(st, st2, timestamp);
1641 if (st2->nb_index_entries <= 0)
1644 // av_assert1(st2->codec->block_align);
1645 av_assert0((int64_t)st2->time_base.num * ast2->rate ==
1646 (int64_t)st2->time_base.den * ast2->scale);
1647 index = av_index_search_timestamp(st2,
1648 av_rescale_q(timestamp,
1651 FFMAX(ast2->sample_size, 1),
1653 AVSEEK_FLAG_BACKWARD |
1654 (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1657 ast2->seek_pos = st2->index_entries[index].pos;
1658 pos_min = FFMIN(pos_min,ast2->seek_pos);
1660 for (i = 0; i < s->nb_streams; i++) {
1661 AVStream *st2 = s->streams[i];
1662 AVIStream *ast2 = st2->priv_data;
1664 if (ast2->sub_ctx || st2->nb_index_entries <= 0)
1667 index = av_index_search_timestamp(
1669 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1670 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1673 while (!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
1675 ast2->frame_offset = st2->index_entries[index].timestamp;
1679 if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
1680 av_log(s, AV_LOG_ERROR, "Seek failed\n");
1683 avi->stream_index = -1;
1684 avi->dts_max = INT_MIN;
1688 static int avi_read_close(AVFormatContext *s)
1691 AVIContext *avi = s->priv_data;
1693 for (i = 0; i < s->nb_streams; i++) {
1694 AVStream *st = s->streams[i];
1695 AVIStream *ast = st->priv_data;
1698 av_freep(&ast->sub_ctx->pb);
1699 avformat_close_input(&ast->sub_ctx);
1701 av_free(ast->sub_buffer);
1702 av_free_packet(&ast->sub_pkt);
1706 av_free(avi->dv_demux);
1711 static int avi_probe(AVProbeData *p)
1715 /* check file header */
1716 for (i = 0; avi_headers[i][0]; i++)
1717 if (!memcmp(p->buf, avi_headers[i], 4) &&
1718 !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
1719 return AVPROBE_SCORE_MAX;
1724 AVInputFormat ff_avi_demuxer = {
1726 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1727 .priv_data_size = sizeof(AVIContext),
1728 .read_probe = avi_probe,
1729 .read_header = avi_read_header,
1730 .read_packet = avi_read_packet,
1731 .read_close = avi_read_close,
1732 .read_seek = avi_read_seek,
1733 .priv_class = &demuxer_class,