3 * Copyright (c) 2001 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 #include "libavutil/avstring.h"
25 #include "libavutil/bswap.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/internal.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/mathematics.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;
65 typedef struct AVIContext {
75 DVDemuxContext *dv_demux;
77 #define MAX_ODML_DEPTH 1000
80 static const char avi_headers[][8] = {
81 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
82 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
83 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
84 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
85 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
89 static const AVMetadataConv avi_metadata_conv[] = {
94 static int avi_load_index(AVFormatContext *s);
95 static int guess_ni_flag(AVFormatContext *s);
97 #define print_tag(str, tag, size) \
98 av_log(NULL, AV_LOG_TRACE, "%s: tag=%c%c%c%c size=0x%x\n", \
101 (tag >> 16) & 0xff, \
102 (tag >> 24) & 0xff, \
105 static inline int get_duration(AVIStream *ast, int len)
107 if (ast->sample_size)
109 else if (ast->dshow_block_align)
110 return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
115 static int get_riff(AVFormatContext *s, AVIOContext *pb)
117 AVIContext *avi = s->priv_data;
121 /* check RIFF header */
122 avio_read(pb, header, 4);
123 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
124 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
125 avio_read(pb, header + 4, 4);
127 for (i = 0; avi_headers[i][0]; i++)
128 if (!memcmp(header, avi_headers[i], 8))
130 if (!avi_headers[i][0])
131 return AVERROR_INVALIDDATA;
133 if (header[7] == 0x19)
134 av_log(s, AV_LOG_INFO,
135 "This file has been generated by a totally broken muxer.\n");
140 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
142 AVIContext *avi = s->priv_data;
143 AVIOContext *pb = s->pb;
144 int longs_pre_entry = avio_rl16(pb);
145 int index_sub_type = avio_r8(pb);
146 int index_type = avio_r8(pb);
147 int entries_in_use = avio_rl32(pb);
148 int chunk_id = avio_rl32(pb);
149 int64_t base = avio_rl64(pb);
150 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
151 ((chunk_id >> 8 & 0xFF) - '0');
155 int64_t last_pos = -1;
156 int64_t filesize = avi->fsize;
158 av_log(s, AV_LOG_TRACE,
159 "longs_pre_entry:%d index_type:%d entries_in_use:%d "
160 "chunk_id:%X base:%16"PRIX64"\n",
167 if (stream_id >= s->nb_streams || stream_id < 0)
168 return AVERROR_INVALIDDATA;
169 st = s->streams[stream_id];
173 return AVERROR_INVALIDDATA;
177 if (index_type && longs_pre_entry != 2)
178 return AVERROR_INVALIDDATA;
180 return AVERROR_INVALIDDATA;
182 if (filesize > 0 && base >= filesize) {
183 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
184 if (base >> 32 == (base & 0xFFFFFFFF) &&
185 (base & 0xFFFFFFFF) < filesize &&
186 filesize <= 0xFFFFFFFF)
189 return AVERROR_INVALIDDATA;
192 for (i = 0; i < entries_in_use; i++) {
194 int64_t pos = avio_rl32(pb) + base - 8;
195 int len = avio_rl32(pb);
199 av_log(s, AV_LOG_TRACE, "pos:%"PRId64", len:%X\n", pos, len);
202 return AVERROR_INVALIDDATA;
204 if (last_pos == pos || pos == base - 8)
205 avi->non_interleaved = 1;
206 if (last_pos != pos && (len || !ast->sample_size))
207 av_add_index_entry(st, pos, ast->cum_len, len, 0,
208 key ? AVINDEX_KEYFRAME : 0);
210 ast->cum_len += get_duration(ast, len);
215 offset = avio_rl64(pb);
216 avio_rl32(pb); /* size */
217 duration = avio_rl32(pb);
220 return AVERROR_INVALIDDATA;
224 if (avi->odml_depth > MAX_ODML_DEPTH) {
225 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
226 return AVERROR_INVALIDDATA;
229 avio_seek(pb, offset + 8, SEEK_SET);
231 read_braindead_odml_indx(s, frame_num);
233 frame_num += duration;
235 avio_seek(pb, pos, SEEK_SET);
238 avi->index_loaded = 1;
242 static void clean_index(AVFormatContext *s)
247 for (i = 0; i < s->nb_streams; i++) {
248 AVStream *st = s->streams[i];
249 AVIStream *ast = st->priv_data;
250 int n = st->nb_index_entries;
251 int max = ast->sample_size;
252 int64_t pos, size, ts;
254 if (n != 1 || ast->sample_size == 0)
260 pos = st->index_entries[0].pos;
261 size = st->index_entries[0].size;
262 ts = st->index_entries[0].timestamp;
264 for (j = 0; j < size; j += max)
265 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
270 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
273 AVIOContext *pb = s->pb;
279 if (size == UINT_MAX)
280 return AVERROR(EINVAL);
281 value = av_malloc(size + 1);
283 return AVERROR(ENOMEM);
284 avio_read(pb, value, size);
289 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
290 AV_DICT_DONT_STRDUP_VAL);
293 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
294 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
296 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
298 char month[4], time[9], buffer[64];
300 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
301 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
302 month, &day, time, &year) == 4) {
303 for (i = 0; i < 12; i++)
304 if (!av_strcasecmp(month, months[i])) {
305 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
306 year, i + 1, day, time);
307 av_dict_set(metadata, "creation_time", buffer, 0);
309 } else if (date[4] == '/' && date[7] == '/') {
310 date[4] = date[7] = '-';
311 av_dict_set(metadata, "creation_time", date, 0);
315 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
317 while (avio_tell(s->pb) < end) {
318 uint32_t tag = avio_rl32(s->pb);
319 uint32_t size = avio_rl32(s->pb);
321 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
323 uint64_t tag_end = avio_tell(s->pb) + size;
324 while (avio_tell(s->pb) < tag_end) {
325 uint16_t tag = avio_rl16(s->pb);
326 uint16_t size = avio_rl16(s->pb);
327 const char *name = NULL;
328 char buffer[64] = { 0 };
329 size -= avio_read(s->pb, buffer,
330 FFMIN(size, sizeof(buffer) - 1));
339 name = "creation_time";
340 if (buffer[4] == ':' && buffer[7] == ':')
341 buffer[4] = buffer[7] = '-';
345 av_dict_set(&s->metadata, name, buffer, 0);
346 avio_skip(s->pb, size);
351 avio_skip(s->pb, size);
357 static int avi_read_header(AVFormatContext *s)
359 AVIContext *avi = s->priv_data;
360 AVIOContext *pb = s->pb;
361 unsigned int tag, tag1, handler;
362 int codec_type, stream_index, frame_period;
366 AVIStream *ast = NULL;
367 int avih_width = 0, avih_height = 0;
368 int amv_file_format = 0;
369 uint64_t list_end = 0;
373 avi->stream_index = -1;
375 ret = get_riff(s, pb);
379 avi->fsize = avio_size(pb);
380 if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
381 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
391 size = avio_rl32(pb);
393 print_tag("tag", tag, size);
396 case MKTAG('L', 'I', 'S', 'T'):
397 list_end = avio_tell(pb) + size;
398 /* Ignored, except at start of video packets. */
399 tag1 = avio_rl32(pb);
401 print_tag("list", tag1, 0);
403 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
404 avi->movi_list = avio_tell(pb) - 4;
406 avi->movi_end = avi->movi_list + size + (size & 1);
408 avi->movi_end = avi->fsize;
409 av_log(NULL, AV_LOG_TRACE, "movi end=%"PRIx64"\n", avi->movi_end);
411 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
412 ff_read_riff_info(s, size - 4);
413 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
414 avi_read_nikon(s, list_end);
417 case MKTAG('I', 'D', 'I', 'T'):
419 unsigned char date[64] = { 0 };
421 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
423 avi_metadata_creation_time(&s->metadata, date);
426 case MKTAG('d', 'm', 'l', 'h'):
428 avio_skip(pb, size + (size & 1));
430 case MKTAG('a', 'm', 'v', 'h'):
432 case MKTAG('a', 'v', 'i', 'h'):
434 /* using frame_period is bad idea */
435 frame_period = avio_rl32(pb);
438 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
440 avio_skip(pb, 2 * 4);
443 avih_width = avio_rl32(pb);
444 avih_height = avio_rl32(pb);
446 avio_skip(pb, size - 10 * 4);
448 case MKTAG('s', 't', 'r', 'h'):
451 tag1 = avio_rl32(pb);
452 handler = avio_rl32(pb); /* codec tag */
454 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
455 avio_skip(pb, size - 8);
459 st = avformat_new_stream(s, NULL);
463 st->id = stream_index;
464 ast = av_mallocz(sizeof(AVIStream));
470 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
471 : MKTAG('v', 'i', 'd', 's');
473 print_tag("strh", tag1, -1);
475 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
476 tag1 == MKTAG('i', 'v', 'a', 's')) {
479 /* After some consideration -- I don't think we
480 * have to support anything but DV in type1 AVIs. */
481 if (s->nb_streams != 1)
484 if (handler != MKTAG('d', 'v', 's', 'd') &&
485 handler != MKTAG('d', 'v', 'h', 'd') &&
486 handler != MKTAG('d', 'v', 's', 'l'))
489 ast = s->streams[0]->priv_data;
490 av_freep(&s->streams[0]->codecpar->extradata);
491 av_freep(&s->streams[0]->codecpar);
492 av_freep(&s->streams[0]->info);
493 av_freep(&s->streams[0]);
495 if (CONFIG_DV_DEMUXER) {
496 avi->dv_demux = avpriv_dv_init_demux(s);
501 s->streams[0]->priv_data = ast;
502 avio_skip(pb, 3 * 4);
503 ast->scale = avio_rl32(pb);
504 ast->rate = avio_rl32(pb);
505 avio_skip(pb, 4); /* start time */
507 dv_dur = avio_rl32(pb);
508 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
509 dv_dur *= AV_TIME_BASE;
510 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
512 /* else, leave duration alone; timing estimation in utils.c
513 * will make a guess based on bitrate. */
515 stream_index = s->nb_streams - 1;
516 avio_skip(pb, size - 9 * 4);
520 assert(stream_index < s->nb_streams);
521 ast->handler = handler;
523 avio_rl32(pb); /* flags */
524 avio_rl16(pb); /* priority */
525 avio_rl16(pb); /* language */
526 avio_rl32(pb); /* initial frame */
527 ast->scale = avio_rl32(pb);
528 ast->rate = avio_rl32(pb);
529 if (!(ast->scale && ast->rate)) {
530 av_log(s, AV_LOG_WARNING,
531 "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
532 "(This file has been generated by broken software.)\n",
537 ast->scale = frame_period;
543 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
545 ast->cum_len = avio_rl32(pb); /* start */
546 st->nb_frames = avio_rl32(pb);
549 avio_rl32(pb); /* buffer size */
550 avio_rl32(pb); /* quality */
551 ast->sample_size = avio_rl32(pb); /* sample size */
552 ast->cum_len *= FFMAX(1, ast->sample_size);
553 av_log(s, AV_LOG_TRACE, "%"PRIu32" %"PRIu32" %d\n",
554 ast->rate, ast->scale, ast->sample_size);
557 case MKTAG('v', 'i', 'd', 's'):
558 codec_type = AVMEDIA_TYPE_VIDEO;
560 ast->sample_size = 0;
562 case MKTAG('a', 'u', 'd', 's'):
563 codec_type = AVMEDIA_TYPE_AUDIO;
565 case MKTAG('t', 'x', 't', 's'):
566 codec_type = AVMEDIA_TYPE_SUBTITLE;
568 case MKTAG('d', 'a', 't', 's'):
569 codec_type = AVMEDIA_TYPE_DATA;
572 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
576 if (ast->sample_size < 0) {
577 if (s->error_recognition & AV_EF_EXPLODE) {
578 av_log(s, AV_LOG_ERROR,
579 "Invalid sample_size %d at stream %d\n",
584 av_log(s, AV_LOG_WARNING,
585 "Invalid sample_size %d at stream %d "
589 ast->sample_size = 0;
592 if (ast->sample_size == 0)
593 st->duration = st->nb_frames;
594 ast->frame_offset = ast->cum_len;
595 avio_skip(pb, size - 12 * 4);
597 case MKTAG('s', 't', 'r', 'f'):
599 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
602 uint64_t cur_pos = avio_tell(pb);
603 if (cur_pos < list_end)
604 size = FFMIN(size, list_end - cur_pos);
605 st = s->streams[stream_index];
606 switch (codec_type) {
607 case AVMEDIA_TYPE_VIDEO:
608 if (amv_file_format) {
609 st->codecpar->width = avih_width;
610 st->codecpar->height = avih_height;
611 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
612 st->codecpar->codec_id = AV_CODEC_ID_AMV;
616 tag1 = ff_get_bmp_header(pb, st, NULL);
618 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
619 tag1 == MKTAG('D', 'X', 'S', 'A')) {
620 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
621 st->codecpar->codec_tag = tag1;
622 st->codecpar->codec_id = AV_CODEC_ID_XSUB;
626 if (size > 10 * 4 && size < (1 << 30)) {
627 st->codecpar->extradata_size = size - 10 * 4;
628 st->codecpar->extradata = av_malloc(st->codecpar->extradata_size +
629 AV_INPUT_BUFFER_PADDING_SIZE);
630 if (!st->codecpar->extradata) {
631 st->codecpar->extradata_size = 0;
632 return AVERROR(ENOMEM);
635 st->codecpar->extradata,
636 st->codecpar->extradata_size);
639 // FIXME: check if the encoder really did this correctly
640 if (st->codecpar->extradata_size & 1)
643 /* Extract palette from extradata if bpp <= 8.
644 * This code assumes that extradata contains only palette.
645 * This is true for all paletted codecs implemented in
647 if (st->codecpar->extradata_size &&
648 (st->codecpar->bits_per_coded_sample <= 8)) {
649 int pal_size = (1 << st->codecpar->bits_per_coded_sample) << 2;
650 const uint8_t *pal_src;
652 pal_size = FFMIN(pal_size, st->codecpar->extradata_size);
653 pal_src = st->codecpar->extradata +
654 st->codecpar->extradata_size - pal_size;
655 for (i = 0; i < pal_size / 4; i++)
656 ast->pal[i] = (0xFFu << 24) | AV_RL32(pal_src + 4 * i);
660 print_tag("video", tag1, 0);
662 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
663 st->codecpar->codec_tag = tag1;
664 st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
666 /* If codec is not found yet, try with the mov tags. */
667 if (!st->codecpar->codec_id) {
669 av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag1);
670 st->codecpar->codec_id =
671 ff_codec_get_id(ff_codec_movvideo_tags, tag1);
672 if (st->codecpar->codec_id)
673 av_log(s, AV_LOG_WARNING,
674 "mov tag found in avi (fourcc %s)\n",
677 /* This is needed to get the pict type which is necessary
678 * for generating correct pts. */
679 st->need_parsing = AVSTREAM_PARSE_HEADERS;
681 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4 &&
682 ast->handler == MKTAG('X', 'V', 'I', 'D'))
683 st->codecpar->codec_tag = MKTAG('X', 'V', 'I', 'D');
685 // Support "Resolution 1:1" for Avid AVI Codec
686 if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
687 st->codecpar->extradata_size >= 31 &&
688 !memcmp(&st->codecpar->extradata[28], "1:1", 3))
689 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
691 if (st->codecpar->codec_tag == 0 && st->codecpar->height > 0 &&
692 st->codecpar->extradata_size < 1U << 30) {
693 st->codecpar->extradata_size += 9;
694 if ((ret = av_reallocp(&st->codecpar->extradata,
695 st->codecpar->extradata_size +
696 AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {
697 st->codecpar->extradata_size = 0;
700 memcpy(st->codecpar->extradata + st->codecpar->extradata_size - 9,
703 st->codecpar->height = FFABS(st->codecpar->height);
705 // avio_skip(pb, size - 5 * 4);
707 case AVMEDIA_TYPE_AUDIO:
708 ret = ff_get_wav_header(s, pb, st->codecpar, size);
711 ast->dshow_block_align = st->codecpar->block_align;
712 if (ast->sample_size && st->codecpar->block_align &&
713 ast->sample_size != st->codecpar->block_align) {
716 "sample size (%d) != block align (%d)\n",
718 st->codecpar->block_align);
719 ast->sample_size = st->codecpar->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->codecpar->codec_id == AV_CODEC_ID_AAC &&
732 st->codecpar->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 (ast->handler == AV_RL32("Axan")) {
737 st->codecpar->codec_id = AV_CODEC_ID_XAN_DPCM;
738 st->codecpar->codec_tag = 0;
740 if (amv_file_format) {
741 st->codecpar->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
742 ast->dshow_block_align = 0;
745 case AVMEDIA_TYPE_SUBTITLE:
746 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
747 st->codecpar->codec_id = AV_CODEC_ID_PROBE;
750 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
751 st->codecpar->codec_id = AV_CODEC_ID_NONE;
752 st->codecpar->codec_tag = 0;
758 case MKTAG('i', 'n', 'd', 'x'):
760 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) &&
761 !(s->flags & AVFMT_FLAG_IGNIDX) &&
762 read_braindead_odml_indx(s, 0) < 0 &&
763 (s->error_recognition & AV_EF_EXPLODE))
765 avio_seek(pb, pos + size, SEEK_SET);
767 case MKTAG('v', 'p', 'r', 'p'):
768 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
769 AVRational active, active_aspect;
771 st = s->streams[stream_index];
778 active_aspect.den = avio_rl16(pb);
779 active_aspect.num = avio_rl16(pb);
780 active.num = avio_rl32(pb);
781 active.den = avio_rl32(pb);
782 avio_rl32(pb); // nbFieldsPerFrame
784 if (active_aspect.num && active_aspect.den &&
785 active.num && active.den) {
786 st->sample_aspect_ratio = av_div_q(active_aspect, active);
787 av_log(s, AV_LOG_TRACE, "vprp %d/%d %d/%d\n",
788 active_aspect.num, active_aspect.den,
789 active.num, active.den);
795 case MKTAG('s', 't', 'r', 'n'):
797 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
803 if (size > 1000000) {
804 av_log(s, AV_LOG_ERROR,
805 "Something went wrong during header parsing, "
806 "I will ignore it and try to continue anyway.\n");
807 if (s->error_recognition & AV_EF_EXPLODE)
809 avi->movi_list = avio_tell(pb) - 4;
810 avi->movi_end = avi->fsize;
821 /* check stream number */
822 if (stream_index != s->nb_streams - 1) {
825 return AVERROR_INVALIDDATA;
828 if (!avi->index_loaded && (pb->seekable & AVIO_SEEKABLE_NORMAL))
830 avi->index_loaded = 1;
832 if ((ret = guess_ni_flag(s)) < 0)
835 avi->non_interleaved |= ret;
836 for (i = 0; i < s->nb_streams; i++) {
837 AVStream *st = s->streams[i];
838 if (st->nb_index_entries)
841 if (i == s->nb_streams && avi->non_interleaved) {
842 av_log(s, AV_LOG_WARNING,
843 "Non-interleaved AVI without index, switching to interleaved\n");
844 avi->non_interleaved = 0;
847 if (avi->non_interleaved) {
848 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
852 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
853 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
858 static int read_gab2_sub(AVStream *st, AVPacket *pkt)
860 if (pkt->size >= 7 &&
861 !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
863 int score = AVPROBE_SCORE_EXTENSION, ret;
864 AVIStream *ast = st->priv_data;
865 AVInputFormat *sub_demuxer;
866 AVRational time_base;
867 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
869 0, NULL, NULL, NULL, NULL);
871 unsigned int desc_len = avio_rl32(pb);
873 if (desc_len > pb->buf_end - pb->buf_ptr)
876 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
877 avio_skip(pb, desc_len - ret);
879 av_dict_set(&st->metadata, "title", desc, 0);
881 avio_rl16(pb); /* flags? */
882 avio_rl32(pb); /* data size */
884 pd = (AVProbeData) { .buf = pb->buf_ptr,
885 .buf_size = pb->buf_end - pb->buf_ptr };
886 if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
889 if (!(ast->sub_ctx = avformat_alloc_context()))
892 ast->sub_ctx->pb = pb;
893 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
894 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
895 avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
896 time_base = ast->sub_ctx->streams[0]->time_base;
897 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
899 ast->sub_buffer = pkt->data;
900 memset(pkt, 0, sizeof(*pkt));
904 avio_context_free(&pb);
909 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
912 AVIStream *ast, *next_ast = next_st->priv_data;
913 int64_t ts, next_ts, ts_min = INT64_MAX;
914 AVStream *st, *sub_st = NULL;
917 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
920 for (i = 0; i < s->nb_streams; i++) {
923 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
924 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
925 if (ts <= next_ts && ts < ts_min) {
933 ast = sub_st->priv_data;
935 pkt->stream_index = sub_st->index;
937 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
938 ast->sub_pkt.data = NULL;
943 static int get_stream_idx(int *d)
945 if (d[0] >= '0' && d[0] <= '9' &&
946 d[1] >= '0' && d[1] <= '9') {
947 return (d[0] - '0') * 10 + (d[1] - '0');
949 return 100; // invalid stream ID
953 static int avi_sync(AVFormatContext *s, int exit_early)
955 AVIContext *avi = s->priv_data;
956 AVIOContext *pb = s->pb;
963 memset(d, -1, sizeof(d));
964 for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
967 for (j = 0; j < 7; j++)
971 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
973 n = get_stream_idx(d + 2);
974 av_log(s, AV_LOG_TRACE, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
975 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
976 if (i + (uint64_t)size > avi->fsize || d[0] > 127)
980 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
982 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
983 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
989 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
994 n = get_stream_idx(d);
996 if (!((i - avi->last_pkt_pos) & 1) &&
997 get_stream_idx(d + 1) < s->nb_streams)
1000 // detect ##ix chunk and skip
1001 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
1002 avio_skip(pb, size);
1006 if (avi->dv_demux && n != 0)
1010 if (n < s->nb_streams) {
1014 ast = st->priv_data;
1016 if (s->nb_streams >= 2) {
1017 AVStream *st1 = s->streams[1];
1018 AVIStream *ast1 = st1->priv_data;
1019 // workaround for broken small-file-bug402.avi
1020 if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
1021 st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1022 st1->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1023 ast->prefix == 'd' * 256 + 'c' &&
1024 (d[2] * 256 + d[3] == ast1->prefix ||
1025 !ast1->prefix_count)) {
1029 av_log(s, AV_LOG_WARNING,
1030 "Invalid stream + prefix combination, assuming audio.\n");
1034 if (!avi->dv_demux &&
1035 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
1036 // FIXME: needs a little reordering
1037 (st->discard >= AVDISCARD_NONKEY &&
1038 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1039 || st->discard >= AVDISCARD_ALL)) {
1041 ast->frame_offset += get_duration(ast, size);
1043 avio_skip(pb, size);
1047 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1048 int k = avio_r8(pb);
1049 int last = (k + avio_r8(pb) - 1) & 0xFF;
1051 avio_rl16(pb); // flags
1053 // b + (g << 8) + (r << 16);
1054 for (; k <= last; k++)
1055 ast->pal[k] = avio_rb32(pb) >> 8;
1059 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1060 d[2] < 128 && d[3] < 128) ||
1061 d[2] * 256 + d[3] == ast->prefix /* ||
1062 (d[2] == 'd' && d[3] == 'c') ||
1063 (d[2] == 'w' && d[3] == 'b') */) {
1066 if (d[2] * 256 + d[3] == ast->prefix)
1067 ast->prefix_count++;
1069 ast->prefix = d[2] * 256 + d[3];
1070 ast->prefix_count = 0;
1073 avi->stream_index = n;
1074 ast->packet_size = size + 8;
1075 ast->remaining = size;
1077 if (size || !ast->sample_size) {
1078 uint64_t pos = avio_tell(pb) - 8;
1079 if (!st->index_entries || !st->nb_index_entries ||
1080 st->index_entries[st->nb_index_entries - 1].pos < pos) {
1081 av_add_index_entry(st, pos, ast->frame_offset, size,
1082 0, AVINDEX_KEYFRAME);
1093 static int ni_prepare_read(AVFormatContext *s)
1095 AVIContext *avi = s->priv_data;
1096 int best_stream_index = 0;
1097 AVStream *best_st = NULL;
1098 AVIStream *best_ast;
1099 int64_t best_ts = INT64_MAX;
1102 for (i = 0; i < s->nb_streams; i++) {
1103 AVStream *st = s->streams[i];
1104 AVIStream *ast = st->priv_data;
1105 int64_t ts = ast->frame_offset;
1108 if (!st->nb_index_entries)
1111 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1112 if (!ast->remaining && ts > last_ts)
1115 ts = av_rescale_q(ts, st->time_base,
1116 (AVRational) { FFMAX(1, ast->sample_size),
1119 av_log(s, AV_LOG_TRACE, "%"PRId64" %d/%d %"PRId64"\n", ts,
1120 st->time_base.num, st->time_base.den, ast->frame_offset);
1124 best_stream_index = i;
1130 best_ast = best_st->priv_data;
1131 best_ts = av_rescale_q(best_ts,
1132 (AVRational) { FFMAX(1, best_ast->sample_size),
1134 best_st->time_base);
1135 if (best_ast->remaining) {
1136 i = av_index_search_timestamp(best_st,
1139 AVSEEK_FLAG_BACKWARD);
1141 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1143 best_ast->frame_offset = best_st->index_entries[i].timestamp;
1147 int64_t pos = best_st->index_entries[i].pos;
1148 pos += best_ast->packet_size - best_ast->remaining;
1149 avio_seek(s->pb, pos + 8, SEEK_SET);
1151 assert(best_ast->remaining <= best_ast->packet_size);
1153 avi->stream_index = best_stream_index;
1154 if (!best_ast->remaining)
1155 best_ast->packet_size =
1156 best_ast->remaining = best_st->index_entries[i].size;
1162 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1164 AVIContext *avi = s->priv_data;
1165 AVIOContext *pb = s->pb;
1168 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1169 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1176 if (avi->non_interleaved) {
1177 err = ni_prepare_read(s);
1183 if (avi->stream_index >= 0) {
1184 AVStream *st = s->streams[avi->stream_index];
1185 AVIStream *ast = st->priv_data;
1188 if (get_subtitle_pkt(s, st, pkt))
1191 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1192 if (ast->sample_size <= 1)
1194 else if (ast->sample_size < 32)
1195 // arbitrary multiplier to avoid tiny packets for raw PCM data
1196 size = 1024 * ast->sample_size;
1198 size = ast->sample_size;
1200 if (size > ast->remaining)
1201 size = ast->remaining;
1202 avi->last_pkt_pos = avio_tell(pb);
1203 err = av_get_packet(pb, pkt, size);
1207 if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
1209 pal = av_packet_new_side_data(pkt,
1210 AV_PKT_DATA_PALETTE,
1213 av_log(s, AV_LOG_ERROR,
1214 "Failed to allocate data for palette\n");
1216 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1221 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1222 AVBufferRef *avbuf = pkt->buf;
1223 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1224 pkt->data, pkt->size);
1226 pkt->flags |= AV_PKT_FLAG_KEY;
1228 av_packet_unref(pkt);
1229 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1230 !st->codecpar->codec_tag && read_gab2_sub(st, pkt)) {
1231 ast->frame_offset++;
1232 avi->stream_index = -1;
1236 /* XXX: How to handle B-frames in AVI? */
1237 pkt->dts = ast->frame_offset;
1238 // pkt->dts += ast->start;
1239 if (ast->sample_size)
1240 pkt->dts /= ast->sample_size;
1241 pkt->stream_index = avi->stream_index;
1243 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1246 assert(st->index_entries);
1248 index = av_index_search_timestamp(st, ast->frame_offset, 0);
1249 e = &st->index_entries[index];
1251 if (index >= 0 && e->timestamp == ast->frame_offset)
1252 if (e->flags & AVINDEX_KEYFRAME)
1253 pkt->flags |= AV_PKT_FLAG_KEY;
1255 pkt->flags |= AV_PKT_FLAG_KEY;
1257 ast->frame_offset += get_duration(ast, pkt->size);
1259 ast->remaining -= err;
1260 if (!ast->remaining) {
1261 avi->stream_index = -1;
1262 ast->packet_size = 0;
1268 if ((err = avi_sync(s, 0)) < 0)
1273 /* XXX: We make the implicit supposition that the positions are sorted
1274 * for each stream. */
1275 static int avi_read_idx1(AVFormatContext *s, int size)
1277 AVIContext *avi = s->priv_data;
1278 AVIOContext *pb = s->pb;
1279 int nb_index_entries, i;
1282 unsigned int index, tag, flags, pos, len, first_packet = 1;
1283 unsigned last_pos = -1;
1284 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1286 nb_index_entries = size / 16;
1287 if (nb_index_entries <= 0)
1288 return AVERROR_INVALIDDATA;
1290 idx1_pos = avio_tell(pb);
1291 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1292 if (avi_sync(s, 1) == 0)
1293 first_packet_pos = avio_tell(pb) - 8;
1294 avi->stream_index = -1;
1295 avio_seek(pb, idx1_pos, SEEK_SET);
1297 /* Read the entries and sort them in each stream component. */
1298 for (i = 0; i < nb_index_entries; i++) {
1299 tag = avio_rl32(pb);
1300 flags = avio_rl32(pb);
1301 pos = avio_rl32(pb);
1302 len = avio_rl32(pb);
1303 av_log(s, AV_LOG_TRACE, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1304 i, tag, flags, pos, len);
1306 index = ((tag & 0xff) - '0') * 10;
1307 index += (tag >> 8 & 0xff) - '0';
1308 if (index >= s->nb_streams)
1310 st = s->streams[index];
1311 ast = st->priv_data;
1313 if (first_packet && first_packet_pos && len) {
1314 data_offset = first_packet_pos - pos;
1319 av_log(s, AV_LOG_TRACE, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1321 if (pb->eof_reached)
1322 return AVERROR_INVALIDDATA;
1324 if (last_pos == pos)
1325 avi->non_interleaved = 1;
1326 else if (len || !ast->sample_size)
1327 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1328 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1329 ast->cum_len += get_duration(ast, len);
1335 /* Scan the index and consider any file with streams more than
1336 * 2 seconds or 64MB apart non-interleaved. */
1337 static int check_stream_max_drift(AVFormatContext *s)
1339 int64_t min_pos, pos;
1341 int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
1343 return AVERROR(ENOMEM);
1345 for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
1346 int64_t max_dts = INT64_MIN / 2;
1347 int64_t min_dts = INT64_MAX / 2;
1348 int64_t max_buffer = 0;
1350 min_pos = INT64_MAX;
1352 for (i = 0; i < s->nb_streams; i++) {
1353 AVStream *st = s->streams[i];
1354 AVIStream *ast = st->priv_data;
1355 int n = st->nb_index_entries;
1356 while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
1360 dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
1361 FFMAX(ast->sample_size, 1),
1362 st->time_base, AV_TIME_BASE_Q);
1363 min_dts = FFMIN(min_dts, dts);
1364 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
1367 for (i = 0; i < s->nb_streams; i++) {
1368 AVStream *st = s->streams[i];
1369 AVIStream *ast = st->priv_data;
1371 if (idx[i] && min_dts != INT64_MAX / 2) {
1373 dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
1374 FFMAX(ast->sample_size, 1),
1375 st->time_base, AV_TIME_BASE_Q);
1376 max_dts = FFMAX(max_dts, dts);
1377 max_buffer = FFMAX(max_buffer,
1378 av_rescale(dts - min_dts,
1379 st->codecpar->bit_rate,
1383 if (max_dts - min_dts > 2 * AV_TIME_BASE ||
1384 max_buffer > 1024 * 1024 * 8 * 8) {
1393 static int guess_ni_flag(AVFormatContext *s)
1396 int64_t last_start = 0;
1397 int64_t first_end = INT64_MAX;
1398 int64_t oldpos = avio_tell(s->pb);
1400 for (i = 0; i < s->nb_streams; i++) {
1401 AVStream *st = s->streams[i];
1402 int n = st->nb_index_entries;
1409 int64_t pos = st->index_entries[0].pos;
1410 avio_seek(s->pb, pos + 4, SEEK_SET);
1411 size = avio_rl32(s->pb);
1412 if (pos + size > st->index_entries[1].pos)
1413 last_start = INT64_MAX;
1416 if (st->index_entries[0].pos > last_start)
1417 last_start = st->index_entries[0].pos;
1418 if (st->index_entries[n - 1].pos < first_end)
1419 first_end = st->index_entries[n - 1].pos;
1421 avio_seek(s->pb, oldpos, SEEK_SET);
1423 if (last_start > first_end)
1426 return check_stream_max_drift(s);
1429 static int avi_load_index(AVFormatContext *s)
1431 AVIContext *avi = s->priv_data;
1432 AVIOContext *pb = s->pb;
1434 int64_t pos = avio_tell(pb);
1437 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1438 goto the_end; // maybe truncated file
1439 av_log(s, AV_LOG_TRACE, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1441 if (pb->eof_reached)
1443 tag = avio_rl32(pb);
1444 size = avio_rl32(pb);
1446 if (tag == MKTAG('i', 'd', 'x', '1') &&
1447 avi_read_idx1(s, size) >= 0) {
1453 if (avio_skip(pb, size) < 0)
1454 break; // something is wrong here
1458 avio_seek(pb, pos, SEEK_SET);
1462 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1464 AVIStream *ast2 = st2->priv_data;
1465 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1466 av_packet_unref(&ast2->sub_pkt);
1467 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1468 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1469 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1472 static int avi_read_seek(AVFormatContext *s, int stream_index,
1473 int64_t timestamp, int flags)
1475 AVIContext *avi = s->priv_data;
1481 /* Does not matter which stream is requested dv in avi has the
1482 * stream information in the first video stream.
1487 if (!avi->index_loaded) {
1488 /* we only load the index on demand */
1490 avi->index_loaded = 1;
1493 st = s->streams[stream_index];
1494 ast = st->priv_data;
1495 index = av_index_search_timestamp(st,
1496 timestamp * FFMAX(ast->sample_size, 1),
1499 return AVERROR_INVALIDDATA;
1501 /* find the position */
1502 pos = st->index_entries[index].pos;
1503 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1505 av_log(s, AV_LOG_TRACE, "XX %"PRId64" %d %"PRId64"\n",
1506 timestamp, index, st->index_entries[index].timestamp);
1508 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1509 /* One and only one real stream for DV in AVI, and it has video */
1510 /* offsets. Calling with other stream indexes should have failed */
1511 /* the av_index_search_timestamp call above. */
1513 /* Feed the DV video stream version of the timestamp to the */
1514 /* DV demux so it can synthesize correct timestamps. */
1515 ff_dv_offset_reset(avi->dv_demux, timestamp);
1517 avio_seek(s->pb, pos, SEEK_SET);
1518 avi->stream_index = -1;
1522 for (i = 0; i < s->nb_streams; i++) {
1523 AVStream *st2 = s->streams[i];
1524 AVIStream *ast2 = st2->priv_data;
1527 ast2->remaining = 0;
1529 if (ast2->sub_ctx) {
1530 seek_subtitle(st, st2, timestamp);
1534 if (st2->nb_index_entries <= 0)
1537 // assert(st2->codecpar->block_align);
1538 assert((int64_t)st2->time_base.num * ast2->rate ==
1539 (int64_t)st2->time_base.den * ast2->scale);
1540 index = av_index_search_timestamp(st2,
1541 av_rescale_q(timestamp,
1544 FFMAX(ast2->sample_size, 1),
1545 flags | AVSEEK_FLAG_BACKWARD);
1549 if (!avi->non_interleaved) {
1550 while (index > 0 && st2->index_entries[index].pos > pos)
1552 while (index + 1 < st2->nb_index_entries &&
1553 st2->index_entries[index].pos < pos)
1557 av_log(s, AV_LOG_TRACE, "%"PRId64" %d %"PRId64"\n",
1558 timestamp, index, st2->index_entries[index].timestamp);
1559 /* extract the current frame number */
1560 ast2->frame_offset = st2->index_entries[index].timestamp;
1564 avio_seek(s->pb, pos, SEEK_SET);
1565 avi->stream_index = -1;
1569 static int avi_read_close(AVFormatContext *s)
1572 AVIContext *avi = s->priv_data;
1574 for (i = 0; i < s->nb_streams; i++) {
1575 AVStream *st = s->streams[i];
1576 AVIStream *ast = st->priv_data;
1579 avio_context_free(&ast->sub_ctx->pb);
1580 avformat_close_input(&ast->sub_ctx);
1582 av_free(ast->sub_buffer);
1583 av_packet_unref(&ast->sub_pkt);
1587 av_free(avi->dv_demux);
1592 static int avi_probe(AVProbeData *p)
1596 /* check file header */
1597 for (i = 0; avi_headers[i][0]; i++)
1598 if (!memcmp(p->buf, avi_headers[i], 4) &&
1599 !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
1600 return AVPROBE_SCORE_MAX;
1605 AVInputFormat ff_avi_demuxer = {
1607 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1608 .priv_data_size = sizeof(AVIContext),
1609 .extensions = "avi",
1610 .read_probe = avi_probe,
1611 .read_header = avi_read_header,
1612 .read_packet = avi_read_packet,
1613 .read_close = avi_read_close,
1614 .read_seek = avi_read_seek,