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
22 #include "libavutil/avstring.h"
23 #include "libavutil/bswap.h"
24 #include "libavutil/dict.h"
25 #include "libavutil/intreadwrite.h"
26 #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;
70 DVDemuxContext *dv_demux;
72 #define MAX_ODML_DEPTH 1000
75 static const char avi_headers[][8] = {
76 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
77 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
78 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
79 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
80 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
84 static const AVMetadataConv avi_metadata_conv[] = {
89 static int avi_load_index(AVFormatContext *s);
90 static int guess_ni_flag(AVFormatContext *s);
92 #define print_tag(str, tag, size) \
93 av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
100 static inline int get_duration(AVIStream *ast, int len)
102 if (ast->sample_size)
104 else if (ast->dshow_block_align)
105 return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
110 static int get_riff(AVFormatContext *s, AVIOContext *pb)
112 AVIContext *avi = s->priv_data;
116 /* check RIFF header */
117 avio_read(pb, header, 4);
118 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
119 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
120 avio_read(pb, header + 4, 4);
122 for (i = 0; avi_headers[i][0]; i++)
123 if (!memcmp(header, avi_headers[i], 8))
125 if (!avi_headers[i][0])
126 return AVERROR_INVALIDDATA;
128 if (header[7] == 0x19)
129 av_log(s, AV_LOG_INFO,
130 "This file has been generated by a totally broken muxer.\n");
135 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
137 AVIContext *avi = s->priv_data;
138 AVIOContext *pb = s->pb;
139 int longs_pre_entry = avio_rl16(pb);
140 int index_sub_type = avio_r8(pb);
141 int index_type = avio_r8(pb);
142 int entries_in_use = avio_rl32(pb);
143 int chunk_id = avio_rl32(pb);
144 int64_t base = avio_rl64(pb);
145 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
146 ((chunk_id >> 8 & 0xFF) - '0');
150 int64_t last_pos = -1;
151 int64_t filesize = avio_size(s->pb);
154 "longs_pre_entry:%d index_type:%d entries_in_use:%d "
155 "chunk_id:%X base:%16"PRIX64"\n",
162 if (stream_id >= s->nb_streams || stream_id < 0)
163 return AVERROR_INVALIDDATA;
164 st = s->streams[stream_id];
168 return AVERROR_INVALIDDATA;
172 if (index_type && longs_pre_entry != 2)
173 return AVERROR_INVALIDDATA;
175 return AVERROR_INVALIDDATA;
177 if (filesize > 0 && base >= filesize) {
178 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
179 if (base >> 32 == (base & 0xFFFFFFFF) &&
180 (base & 0xFFFFFFFF) < filesize &&
181 filesize <= 0xFFFFFFFF)
184 return AVERROR_INVALIDDATA;
187 for (i = 0; i < entries_in_use; i++) {
189 int64_t pos = avio_rl32(pb) + base - 8;
190 int len = avio_rl32(pb);
194 av_dlog(s, "pos:%"PRId64", len:%X\n", pos, len);
197 return AVERROR_INVALIDDATA;
199 if (last_pos == pos || pos == base - 8)
200 avi->non_interleaved = 1;
201 if (last_pos != pos && (len || !ast->sample_size))
202 av_add_index_entry(st, pos, ast->cum_len, len, 0,
203 key ? AVINDEX_KEYFRAME : 0);
205 ast->cum_len += get_duration(ast, len);
210 offset = avio_rl64(pb);
211 avio_rl32(pb); /* size */
212 duration = avio_rl32(pb);
215 return AVERROR_INVALIDDATA;
219 if (avi->odml_depth > MAX_ODML_DEPTH) {
220 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
221 return AVERROR_INVALIDDATA;
224 avio_seek(pb, offset + 8, SEEK_SET);
226 read_braindead_odml_indx(s, frame_num);
228 frame_num += duration;
230 avio_seek(pb, pos, SEEK_SET);
233 avi->index_loaded = 1;
237 static void clean_index(AVFormatContext *s)
242 for (i = 0; i < s->nb_streams; i++) {
243 AVStream *st = s->streams[i];
244 AVIStream *ast = st->priv_data;
245 int n = st->nb_index_entries;
246 int max = ast->sample_size;
247 int64_t pos, size, ts;
249 if (n != 1 || ast->sample_size == 0)
255 pos = st->index_entries[0].pos;
256 size = st->index_entries[0].size;
257 ts = st->index_entries[0].timestamp;
259 for (j = 0; j < size; j += max)
260 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
265 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
268 AVIOContext *pb = s->pb;
274 if (size == UINT_MAX)
275 return AVERROR(EINVAL);
276 value = av_malloc(size + 1);
278 return AVERROR(ENOMEM);
279 avio_read(pb, value, size);
284 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
285 AV_DICT_DONT_STRDUP_VAL);
288 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
289 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
291 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
293 char month[4], time[9], buffer[64];
295 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
296 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
297 month, &day, time, &year) == 4) {
298 for (i = 0; i < 12; i++)
299 if (!av_strcasecmp(month, months[i])) {
300 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
301 year, i + 1, day, time);
302 av_dict_set(metadata, "creation_time", buffer, 0);
304 } else if (date[4] == '/' && date[7] == '/') {
305 date[4] = date[7] = '-';
306 av_dict_set(metadata, "creation_time", date, 0);
310 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
312 while (avio_tell(s->pb) < end) {
313 uint32_t tag = avio_rl32(s->pb);
314 uint32_t size = avio_rl32(s->pb);
316 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
318 uint64_t tag_end = avio_tell(s->pb) + size;
319 while (avio_tell(s->pb) < tag_end) {
320 uint16_t tag = avio_rl16(s->pb);
321 uint16_t size = avio_rl16(s->pb);
322 const char *name = NULL;
323 char buffer[64] = { 0 };
324 size -= avio_read(s->pb, buffer,
325 FFMIN(size, sizeof(buffer) - 1));
334 name = "creation_time";
335 if (buffer[4] == ':' && buffer[7] == ':')
336 buffer[4] = buffer[7] = '-';
340 av_dict_set(&s->metadata, name, buffer, 0);
341 avio_skip(s->pb, size);
346 avio_skip(s->pb, size);
352 static int avi_read_header(AVFormatContext *s)
354 AVIContext *avi = s->priv_data;
355 AVIOContext *pb = s->pb;
356 unsigned int tag, tag1, handler;
357 int codec_type, stream_index, frame_period;
361 AVIStream *ast = NULL;
362 int avih_width = 0, avih_height = 0;
363 int amv_file_format = 0;
364 uint64_t list_end = 0;
367 avi->stream_index = -1;
369 ret = get_riff(s, pb);
373 avi->fsize = avio_size(pb);
375 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
385 size = avio_rl32(pb);
387 print_tag("tag", tag, size);
390 case MKTAG('L', 'I', 'S', 'T'):
391 list_end = avio_tell(pb) + size;
392 /* Ignored, except at start of video packets. */
393 tag1 = avio_rl32(pb);
395 print_tag("list", tag1, 0);
397 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
398 avi->movi_list = avio_tell(pb) - 4;
400 avi->movi_end = avi->movi_list + size + (size & 1);
402 avi->movi_end = avio_size(pb);
403 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
405 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
406 ff_read_riff_info(s, size - 4);
407 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
408 avi_read_nikon(s, list_end);
411 case MKTAG('I', 'D', 'I', 'T'):
413 unsigned char date[64] = { 0 };
415 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
417 avi_metadata_creation_time(&s->metadata, date);
420 case MKTAG('d', 'm', 'l', 'h'):
422 avio_skip(pb, size + (size & 1));
424 case MKTAG('a', 'm', 'v', 'h'):
426 case MKTAG('a', 'v', 'i', 'h'):
428 /* using frame_period is bad idea */
429 frame_period = avio_rl32(pb);
432 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
434 avio_skip(pb, 2 * 4);
437 avih_width = avio_rl32(pb);
438 avih_height = avio_rl32(pb);
440 avio_skip(pb, size - 10 * 4);
442 case MKTAG('s', 't', 'r', 'h'):
445 tag1 = avio_rl32(pb);
446 handler = avio_rl32(pb); /* codec tag */
448 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
449 avio_skip(pb, size - 8);
453 st = avformat_new_stream(s, NULL);
457 st->id = stream_index;
458 ast = av_mallocz(sizeof(AVIStream));
464 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
465 : MKTAG('v', 'i', 'd', 's');
467 print_tag("strh", tag1, -1);
469 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
470 tag1 == MKTAG('i', 'v', 'a', 's')) {
473 /* After some consideration -- I don't think we
474 * have to support anything but DV in type1 AVIs. */
475 if (s->nb_streams != 1)
478 if (handler != MKTAG('d', 'v', 's', 'd') &&
479 handler != MKTAG('d', 'v', 'h', 'd') &&
480 handler != MKTAG('d', 'v', 's', 'l'))
483 ast = s->streams[0]->priv_data;
484 av_freep(&s->streams[0]->codec->extradata);
485 av_freep(&s->streams[0]->codec);
486 av_freep(&s->streams[0]);
488 if (CONFIG_DV_DEMUXER) {
489 avi->dv_demux = avpriv_dv_init_demux(s);
493 s->streams[0]->priv_data = ast;
494 avio_skip(pb, 3 * 4);
495 ast->scale = avio_rl32(pb);
496 ast->rate = avio_rl32(pb);
497 avio_skip(pb, 4); /* start time */
499 dv_dur = avio_rl32(pb);
500 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
501 dv_dur *= AV_TIME_BASE;
502 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
504 /* else, leave duration alone; timing estimation in utils.c
505 * will make a guess based on bitrate. */
507 stream_index = s->nb_streams - 1;
508 avio_skip(pb, size - 9 * 4);
512 assert(stream_index < s->nb_streams);
513 st->codec->stream_codec_tag = handler;
515 avio_rl32(pb); /* flags */
516 avio_rl16(pb); /* priority */
517 avio_rl16(pb); /* language */
518 avio_rl32(pb); /* initial frame */
519 ast->scale = avio_rl32(pb);
520 ast->rate = avio_rl32(pb);
521 if (!(ast->scale && ast->rate)) {
522 av_log(s, AV_LOG_WARNING,
523 "scale/rate is %u/%u which is invalid. "
524 "(This file has been generated by broken software.)\n",
529 ast->scale = frame_period;
535 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
537 ast->cum_len = avio_rl32(pb); /* start */
538 st->nb_frames = avio_rl32(pb);
541 avio_rl32(pb); /* buffer size */
542 avio_rl32(pb); /* quality */
543 ast->sample_size = avio_rl32(pb); /* sample ssize */
544 ast->cum_len *= FFMAX(1, ast->sample_size);
545 av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
546 ast->rate, ast->scale, ast->sample_size);
549 case MKTAG('v', 'i', 'd', 's'):
550 codec_type = AVMEDIA_TYPE_VIDEO;
552 ast->sample_size = 0;
554 case MKTAG('a', 'u', 'd', 's'):
555 codec_type = AVMEDIA_TYPE_AUDIO;
557 case MKTAG('t', 'x', 't', 's'):
558 codec_type = AVMEDIA_TYPE_SUBTITLE;
560 case MKTAG('d', 'a', 't', 's'):
561 codec_type = AVMEDIA_TYPE_DATA;
564 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
567 if (ast->sample_size == 0)
568 st->duration = st->nb_frames;
569 ast->frame_offset = ast->cum_len;
570 avio_skip(pb, size - 12 * 4);
572 case MKTAG('s', 't', 'r', 'f'):
574 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
577 uint64_t cur_pos = avio_tell(pb);
578 if (cur_pos < list_end)
579 size = FFMIN(size, list_end - cur_pos);
580 st = s->streams[stream_index];
581 switch (codec_type) {
582 case AVMEDIA_TYPE_VIDEO:
583 if (amv_file_format) {
584 st->codec->width = avih_width;
585 st->codec->height = avih_height;
586 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
587 st->codec->codec_id = AV_CODEC_ID_AMV;
591 tag1 = ff_get_bmp_header(pb, st);
593 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
594 tag1 == MKTAG('D', 'X', 'S', 'A')) {
595 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
596 st->codec->codec_tag = tag1;
597 st->codec->codec_id = AV_CODEC_ID_XSUB;
601 if (size > 10 * 4 && size < (1 << 30)) {
602 st->codec->extradata_size = size - 10 * 4;
603 st->codec->extradata = av_malloc(st->codec->extradata_size +
604 FF_INPUT_BUFFER_PADDING_SIZE);
605 if (!st->codec->extradata) {
606 st->codec->extradata_size = 0;
607 return AVERROR(ENOMEM);
610 st->codec->extradata,
611 st->codec->extradata_size);
614 // FIXME: check if the encoder really did this correctly
615 if (st->codec->extradata_size & 1)
618 /* Extract palette from extradata if bpp <= 8.
619 * This code assumes that extradata contains only palette.
620 * This is true for all paletted codecs implemented in
622 if (st->codec->extradata_size &&
623 (st->codec->bits_per_coded_sample <= 8)) {
624 int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
625 const uint8_t *pal_src;
627 pal_size = FFMIN(pal_size, st->codec->extradata_size);
628 pal_src = st->codec->extradata +
629 st->codec->extradata_size - pal_size;
631 for (i = 0; i < pal_size / 4; i++)
632 ast->pal[i] = av_bswap32(((uint32_t *)pal_src)[i]);
634 memcpy(ast->pal, pal_src, pal_size);
639 print_tag("video", tag1, 0);
641 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
642 st->codec->codec_tag = tag1;
643 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
645 /* This is needed to get the pict type which is necessary
646 * for generating correct pts. */
647 st->need_parsing = AVSTREAM_PARSE_HEADERS;
648 // Support "Resolution 1:1" for Avid AVI Codec
649 if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
650 st->codec->extradata_size >= 31 &&
651 !memcmp(&st->codec->extradata[28], "1:1", 3))
652 st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
654 if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
655 st->codec->extradata_size < 1U << 30) {
656 st->codec->extradata_size += 9;
657 st->codec->extradata = av_realloc(st->codec->extradata,
658 st->codec->extradata_size +
659 FF_INPUT_BUFFER_PADDING_SIZE);
660 if (st->codec->extradata)
661 memcpy(st->codec->extradata + st->codec->extradata_size - 9,
664 st->codec->height = FFABS(st->codec->height);
666 // avio_skip(pb, size - 5 * 4);
668 case AVMEDIA_TYPE_AUDIO:
669 ret = ff_get_wav_header(pb, st->codec, size);
672 ast->dshow_block_align = st->codec->block_align;
673 if (ast->sample_size && st->codec->block_align &&
674 ast->sample_size != st->codec->block_align) {
677 "sample size (%d) != block align (%d)\n",
679 st->codec->block_align);
680 ast->sample_size = st->codec->block_align;
683 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
686 /* Force parsing as several audio frames can be in
687 * one packet and timestamps refer to packet start. */
688 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
689 /* ADTS header is in extradata, AAC without header must be
690 * stored as exact frames. Parser not needed and it will
692 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
693 st->codec->extradata_size)
694 st->need_parsing = AVSTREAM_PARSE_NONE;
695 /* AVI files with Xan DPCM audio (wrongly) declare PCM
696 * audio in the header but have Axan as stream_code_tag. */
697 if (st->codec->stream_codec_tag == AV_RL32("Axan")) {
698 st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
699 st->codec->codec_tag = 0;
701 if (amv_file_format) {
702 st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
703 ast->dshow_block_align = 0;
706 case AVMEDIA_TYPE_SUBTITLE:
707 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
708 st->codec->codec_id = AV_CODEC_ID_PROBE;
711 st->codec->codec_type = AVMEDIA_TYPE_DATA;
712 st->codec->codec_id = AV_CODEC_ID_NONE;
713 st->codec->codec_tag = 0;
719 case MKTAG('i', 'n', 'd', 'x'):
721 if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
722 read_braindead_odml_indx(s, 0) < 0 &&
723 (s->error_recognition & AV_EF_EXPLODE))
725 avio_seek(pb, i + size, SEEK_SET);
727 case MKTAG('v', 'p', 'r', 'p'):
728 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
729 AVRational active, active_aspect;
731 st = s->streams[stream_index];
738 active_aspect.den = avio_rl16(pb);
739 active_aspect.num = avio_rl16(pb);
740 active.num = avio_rl32(pb);
741 active.den = avio_rl32(pb);
742 avio_rl32(pb); // nbFieldsPerFrame
744 if (active_aspect.num && active_aspect.den &&
745 active.num && active.den) {
746 st->sample_aspect_ratio = av_div_q(active_aspect, active);
747 av_dlog(s, "vprp %d/%d %d/%d\n",
748 active_aspect.num, active_aspect.den,
749 active.num, active.den);
755 case MKTAG('s', 't', 'r', 'n'):
757 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
763 if (size > 1000000) {
764 av_log(s, AV_LOG_ERROR,
765 "Something went wrong during header parsing, "
766 "I will ignore it and try to continue anyway.\n");
767 if (s->error_recognition & AV_EF_EXPLODE)
769 avi->movi_list = avio_tell(pb) - 4;
770 avi->movi_end = avio_size(pb);
781 /* check stream number */
782 if (stream_index != s->nb_streams - 1) {
785 return AVERROR_INVALIDDATA;
788 if (!avi->index_loaded && pb->seekable)
790 avi->index_loaded = 1;
791 avi->non_interleaved |= guess_ni_flag(s);
792 for (i = 0; i < s->nb_streams; i++) {
793 AVStream *st = s->streams[i];
794 if (st->nb_index_entries)
797 if (i == s->nb_streams && avi->non_interleaved) {
798 av_log(s, AV_LOG_WARNING,
799 "Non-interleaved AVI without index, switching to interleaved\n");
800 avi->non_interleaved = 0;
803 if (avi->non_interleaved) {
804 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
808 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
809 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
814 static int read_gab2_sub(AVStream *st, AVPacket *pkt)
816 if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
818 int score = AVPROBE_SCORE_EXTENSION, ret;
819 AVIStream *ast = st->priv_data;
820 AVInputFormat *sub_demuxer;
821 AVRational time_base;
822 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
824 0, NULL, NULL, NULL, NULL);
826 unsigned int desc_len = avio_rl32(pb);
828 if (desc_len > pb->buf_end - pb->buf_ptr)
831 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
832 avio_skip(pb, desc_len - ret);
834 av_dict_set(&st->metadata, "title", desc, 0);
836 avio_rl16(pb); /* flags? */
837 avio_rl32(pb); /* data size */
839 pd = (AVProbeData) { .buf = pb->buf_ptr,
840 .buf_size = pb->buf_end - pb->buf_ptr };
841 if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
844 if (!(ast->sub_ctx = avformat_alloc_context()))
847 ast->sub_ctx->pb = pb;
848 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
849 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
850 *st->codec = *ast->sub_ctx->streams[0]->codec;
851 ast->sub_ctx->streams[0]->codec->extradata = NULL;
852 time_base = ast->sub_ctx->streams[0]->time_base;
853 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
855 ast->sub_buffer = pkt->data;
856 memset(pkt, 0, sizeof(*pkt));
865 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
868 AVIStream *ast, *next_ast = next_st->priv_data;
869 int64_t ts, next_ts, ts_min = INT64_MAX;
870 AVStream *st, *sub_st = NULL;
873 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
876 for (i = 0; i < s->nb_streams; i++) {
879 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
880 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
881 if (ts <= next_ts && ts < ts_min) {
889 ast = sub_st->priv_data;
891 pkt->stream_index = sub_st->index;
893 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
894 ast->sub_pkt.data = NULL;
899 static int get_stream_idx(int *d)
901 if (d[0] >= '0' && d[0] <= '9' &&
902 d[1] >= '0' && d[1] <= '9') {
903 return (d[0] - '0') * 10 + (d[1] - '0');
905 return 100; // invalid stream ID
909 static int avi_sync(AVFormatContext *s, int exit_early)
911 AVIContext *avi = s->priv_data;
912 AVIOContext *pb = s->pb;
919 memset(d, -1, sizeof(d));
920 for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
923 for (j = 0; j < 7; j++)
927 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
929 n = get_stream_idx(d + 2);
930 av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
931 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
932 if (i + (uint64_t)size > avi->fsize || d[0] > 127)
936 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
938 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
939 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
945 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
950 n = get_stream_idx(d);
952 if (!((i - avi->last_pkt_pos) & 1) &&
953 get_stream_idx(d + 1) < s->nb_streams)
956 // detect ##ix chunk and skip
957 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
963 if (n < s->nb_streams) {
969 if (s->nb_streams >= 2) {
970 AVStream *st1 = s->streams[1];
971 AVIStream *ast1 = st1->priv_data;
972 // workaround for broken small-file-bug402.avi
973 if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
974 st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
975 st1->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
976 ast->prefix == 'd' * 256 + 'c' &&
977 (d[2] * 256 + d[3] == ast1->prefix ||
978 !ast1->prefix_count)) {
982 av_log(s, AV_LOG_WARNING,
983 "Invalid stream + prefix combination, assuming audio.\n");
987 if (!avi->dv_demux &&
988 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
989 // FIXME: needs a little reordering
990 (st->discard >= AVDISCARD_NONKEY &&
991 !(pkt->flags & AV_PKT_FLAG_KEY)) */
992 || st->discard >= AVDISCARD_ALL)) {
994 ast->frame_offset += get_duration(ast, size);
1000 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1001 int k = avio_r8(pb);
1002 int last = (k + avio_r8(pb) - 1) & 0xFF;
1004 avio_rl16(pb); // flags
1006 // b + (g << 8) + (r << 16);
1007 for (; k <= last; k++)
1008 ast->pal[k] = avio_rb32(pb) >> 8;
1012 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1013 d[2] < 128 && d[3] < 128) ||
1014 d[2] * 256 + d[3] == ast->prefix /* ||
1015 (d[2] == 'd' && d[3] == 'c') ||
1016 (d[2] == 'w' && d[3] == 'b') */) {
1019 if (d[2] * 256 + d[3] == ast->prefix)
1020 ast->prefix_count++;
1022 ast->prefix = d[2] * 256 + d[3];
1023 ast->prefix_count = 0;
1026 avi->stream_index = n;
1027 ast->packet_size = size + 8;
1028 ast->remaining = size;
1030 if (size || !ast->sample_size) {
1031 uint64_t pos = avio_tell(pb) - 8;
1032 if (!st->index_entries || !st->nb_index_entries ||
1033 st->index_entries[st->nb_index_entries - 1].pos < pos) {
1034 av_add_index_entry(st, pos, ast->frame_offset, size,
1035 0, AVINDEX_KEYFRAME);
1046 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1048 AVIContext *avi = s->priv_data;
1049 AVIOContext *pb = s->pb;
1051 #if FF_API_DESTRUCT_PACKET
1055 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1056 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1061 if (avi->non_interleaved) {
1062 int best_stream_index = 0;
1063 AVStream *best_st = NULL;
1064 AVIStream *best_ast;
1065 int64_t best_ts = INT64_MAX;
1068 for (i = 0; i < s->nb_streams; i++) {
1069 AVStream *st = s->streams[i];
1070 AVIStream *ast = st->priv_data;
1071 int64_t ts = ast->frame_offset;
1074 if (!st->nb_index_entries)
1077 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1078 if (!ast->remaining && ts > last_ts)
1081 ts = av_rescale_q(ts, st->time_base,
1082 (AVRational) { FFMAX(1, ast->sample_size),
1085 av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
1086 st->time_base.num, st->time_base.den, ast->frame_offset);
1090 best_stream_index = i;
1096 best_ast = best_st->priv_data;
1097 best_ts = av_rescale_q(best_ts,
1098 (AVRational) { FFMAX(1, best_ast->sample_size),
1100 best_st->time_base);
1101 if (best_ast->remaining) {
1102 i = av_index_search_timestamp(best_st,
1105 AVSEEK_FLAG_BACKWARD);
1107 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1109 best_ast->frame_offset = best_st->index_entries[i].timestamp;
1113 int64_t pos = best_st->index_entries[i].pos;
1114 pos += best_ast->packet_size - best_ast->remaining;
1115 avio_seek(s->pb, pos + 8, SEEK_SET);
1117 assert(best_ast->remaining <= best_ast->packet_size);
1119 avi->stream_index = best_stream_index;
1120 if (!best_ast->remaining)
1121 best_ast->packet_size =
1122 best_ast->remaining = best_st->index_entries[i].size;
1127 if (avi->stream_index >= 0) {
1128 AVStream *st = s->streams[avi->stream_index];
1129 AVIStream *ast = st->priv_data;
1132 if (get_subtitle_pkt(s, st, pkt))
1135 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1136 if (ast->sample_size <= 1)
1138 else if (ast->sample_size < 32)
1139 // arbitrary multiplier to avoid tiny packets for raw PCM data
1140 size = 1024 * ast->sample_size;
1142 size = ast->sample_size;
1144 if (size > ast->remaining)
1145 size = ast->remaining;
1146 avi->last_pkt_pos = avio_tell(pb);
1147 err = av_get_packet(pb, pkt, size);
1151 if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
1153 pal = av_packet_new_side_data(pkt,
1154 AV_PKT_DATA_PALETTE,
1157 av_log(s, AV_LOG_ERROR,
1158 "Failed to allocate data for palette\n");
1160 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1165 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1166 AVBufferRef *avbuf = pkt->buf;
1167 #if FF_API_DESTRUCT_PACKET
1168 dstr = pkt->destruct;
1170 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1171 pkt->data, pkt->size);
1172 #if FF_API_DESTRUCT_PACKET
1173 pkt->destruct = dstr;
1176 pkt->flags |= AV_PKT_FLAG_KEY;
1178 av_free_packet(pkt);
1179 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1180 !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1181 ast->frame_offset++;
1182 avi->stream_index = -1;
1186 /* XXX: How to handle B-frames in AVI? */
1187 pkt->dts = ast->frame_offset;
1188 // pkt->dts += ast->start;
1189 if (ast->sample_size)
1190 pkt->dts /= ast->sample_size;
1192 "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
1193 "base:%d st:%d size:%d\n",
1202 pkt->stream_index = avi->stream_index;
1204 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1207 assert(st->index_entries);
1209 index = av_index_search_timestamp(st, ast->frame_offset, 0);
1210 e = &st->index_entries[index];
1212 if (index >= 0 && e->timestamp == ast->frame_offset)
1213 if (e->flags & AVINDEX_KEYFRAME)
1214 pkt->flags |= AV_PKT_FLAG_KEY;
1216 pkt->flags |= AV_PKT_FLAG_KEY;
1218 ast->frame_offset += get_duration(ast, pkt->size);
1220 ast->remaining -= err;
1221 if (!ast->remaining) {
1222 avi->stream_index = -1;
1223 ast->packet_size = 0;
1229 if ((err = avi_sync(s, 0)) < 0)
1234 /* XXX: We make the implicit supposition that the positions are sorted
1235 * for each stream. */
1236 static int avi_read_idx1(AVFormatContext *s, int size)
1238 AVIContext *avi = s->priv_data;
1239 AVIOContext *pb = s->pb;
1240 int nb_index_entries, i;
1243 unsigned int index, tag, flags, pos, len, first_packet = 1;
1244 unsigned last_pos = -1;
1245 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1247 nb_index_entries = size / 16;
1248 if (nb_index_entries <= 0)
1249 return AVERROR_INVALIDDATA;
1251 idx1_pos = avio_tell(pb);
1252 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1253 if (avi_sync(s, 1) == 0)
1254 first_packet_pos = avio_tell(pb) - 8;
1255 avi->stream_index = -1;
1256 avio_seek(pb, idx1_pos, SEEK_SET);
1258 /* Read the entries and sort them in each stream component. */
1259 for (i = 0; i < nb_index_entries; i++) {
1260 tag = avio_rl32(pb);
1261 flags = avio_rl32(pb);
1262 pos = avio_rl32(pb);
1263 len = avio_rl32(pb);
1264 av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1265 i, tag, flags, pos, len);
1267 index = ((tag & 0xff) - '0') * 10;
1268 index += (tag >> 8 & 0xff) - '0';
1269 if (index >= s->nb_streams)
1271 st = s->streams[index];
1272 ast = st->priv_data;
1274 if (first_packet && first_packet_pos && len) {
1275 data_offset = first_packet_pos - pos;
1280 av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1282 if (pb->eof_reached)
1283 return AVERROR_INVALIDDATA;
1285 if (last_pos == pos)
1286 avi->non_interleaved = 1;
1287 else if (len || !ast->sample_size)
1288 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1289 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1290 ast->cum_len += get_duration(ast, len);
1296 static int guess_ni_flag(AVFormatContext *s)
1299 int64_t last_start = 0;
1300 int64_t first_end = INT64_MAX;
1301 int64_t oldpos = avio_tell(s->pb);
1303 for (i = 0; i < s->nb_streams; i++) {
1304 AVStream *st = s->streams[i];
1305 int n = st->nb_index_entries;
1312 int64_t pos = st->index_entries[0].pos;
1313 avio_seek(s->pb, pos + 4, SEEK_SET);
1314 size = avio_rl32(s->pb);
1315 if (pos + size > st->index_entries[1].pos)
1316 last_start = INT64_MAX;
1319 if (st->index_entries[0].pos > last_start)
1320 last_start = st->index_entries[0].pos;
1321 if (st->index_entries[n - 1].pos < first_end)
1322 first_end = st->index_entries[n - 1].pos;
1324 avio_seek(s->pb, oldpos, SEEK_SET);
1325 return last_start > first_end;
1328 static int avi_load_index(AVFormatContext *s)
1330 AVIContext *avi = s->priv_data;
1331 AVIOContext *pb = s->pb;
1333 int64_t pos = avio_tell(pb);
1336 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1337 goto the_end; // maybe truncated file
1338 av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1340 if (pb->eof_reached)
1342 tag = avio_rl32(pb);
1343 size = avio_rl32(pb);
1344 av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1351 if (tag == MKTAG('i', 'd', 'x', '1') &&
1352 avi_read_idx1(s, size) >= 0) {
1358 if (avio_skip(pb, size) < 0)
1359 break; // something is wrong here
1363 avio_seek(pb, pos, SEEK_SET);
1367 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1369 AVIStream *ast2 = st2->priv_data;
1370 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1371 av_free_packet(&ast2->sub_pkt);
1372 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1373 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1374 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1377 static int avi_read_seek(AVFormatContext *s, int stream_index,
1378 int64_t timestamp, int flags)
1380 AVIContext *avi = s->priv_data;
1386 if (!avi->index_loaded) {
1387 /* we only load the index on demand */
1389 avi->index_loaded = 1;
1391 assert(stream_index >= 0);
1393 st = s->streams[stream_index];
1394 ast = st->priv_data;
1395 index = av_index_search_timestamp(st,
1396 timestamp * FFMAX(ast->sample_size, 1),
1399 return AVERROR_INVALIDDATA;
1401 /* find the position */
1402 pos = st->index_entries[index].pos;
1403 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1405 av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
1406 timestamp, index, st->index_entries[index].timestamp);
1408 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1409 /* One and only one real stream for DV in AVI, and it has video */
1410 /* offsets. Calling with other stream indexes should have failed */
1411 /* the av_index_search_timestamp call above. */
1412 assert(stream_index == 0);
1414 /* Feed the DV video stream version of the timestamp to the */
1415 /* DV demux so it can synthesize correct timestamps. */
1416 ff_dv_offset_reset(avi->dv_demux, timestamp);
1418 avio_seek(s->pb, pos, SEEK_SET);
1419 avi->stream_index = -1;
1423 for (i = 0; i < s->nb_streams; i++) {
1424 AVStream *st2 = s->streams[i];
1425 AVIStream *ast2 = st2->priv_data;
1428 ast2->remaining = 0;
1430 if (ast2->sub_ctx) {
1431 seek_subtitle(st, st2, timestamp);
1435 if (st2->nb_index_entries <= 0)
1438 // assert(st2->codec->block_align);
1439 assert((int64_t)st2->time_base.num * ast2->rate ==
1440 (int64_t)st2->time_base.den * ast2->scale);
1441 index = av_index_search_timestamp(st2,
1442 av_rescale_q(timestamp,
1445 FFMAX(ast2->sample_size, 1),
1446 flags | AVSEEK_FLAG_BACKWARD);
1450 if (!avi->non_interleaved) {
1451 while (index > 0 && st2->index_entries[index].pos > pos)
1453 while (index + 1 < st2->nb_index_entries &&
1454 st2->index_entries[index].pos < pos)
1458 av_dlog(s, "%"PRId64" %d %"PRId64"\n",
1459 timestamp, index, st2->index_entries[index].timestamp);
1460 /* extract the current frame number */
1461 ast2->frame_offset = st2->index_entries[index].timestamp;
1465 avio_seek(s->pb, pos, SEEK_SET);
1466 avi->stream_index = -1;
1470 static int avi_read_close(AVFormatContext *s)
1473 AVIContext *avi = s->priv_data;
1475 for (i = 0; i < s->nb_streams; i++) {
1476 AVStream *st = s->streams[i];
1477 AVIStream *ast = st->priv_data;
1480 av_freep(&ast->sub_ctx->pb);
1481 avformat_close_input(&ast->sub_ctx);
1483 av_free(ast->sub_buffer);
1484 av_free_packet(&ast->sub_pkt);
1488 av_free(avi->dv_demux);
1493 static int avi_probe(AVProbeData *p)
1497 /* check file header */
1498 for (i = 0; avi_headers[i][0]; i++)
1499 if (!memcmp(p->buf, avi_headers[i], 4) &&
1500 !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
1501 return AVPROBE_SCORE_MAX;
1506 AVInputFormat ff_avi_demuxer = {
1508 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1509 .priv_data_size = sizeof(AVIContext),
1510 .read_probe = avi_probe,
1511 .read_header = avi_read_header,
1512 .read_packet = avi_read_packet,
1513 .read_close = avi_read_close,
1514 .read_seek = avi_read_seek,