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"
39 typedef struct AVIStream {
40 int64_t frame_offset; /* current frame (video) or byte (audio) counter
41 * (used to compute the pts) */
47 int sample_size; /* size of one sample (or packet)
48 * (in the rate/scale sense) in bytes */
50 int64_t cum_len; /* temporary storage (used during seek) */
51 int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
55 int dshow_block_align; /* block align variable used to emulate bugs in
56 * the MS dshow demuxer */
58 AVFormatContext *sub_ctx;
73 DVDemuxContext *dv_demux;
75 #define MAX_ODML_DEPTH 1000
78 static const char avi_headers[][8] = {
79 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
80 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
81 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
82 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
83 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
87 static const AVMetadataConv avi_metadata_conv[] = {
92 static int avi_load_index(AVFormatContext *s);
93 static int guess_ni_flag(AVFormatContext *s);
95 #define print_tag(str, tag, size) \
96 av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
100 (tag >> 24) & 0xff, \
103 static inline int get_duration(AVIStream *ast, int len)
105 if (ast->sample_size)
107 else if (ast->dshow_block_align)
108 return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
113 static int get_riff(AVFormatContext *s, AVIOContext *pb)
115 AVIContext *avi = s->priv_data;
119 /* check RIFF header */
120 avio_read(pb, header, 4);
121 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
122 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
123 avio_read(pb, header + 4, 4);
125 for (i = 0; avi_headers[i][0]; i++)
126 if (!memcmp(header, avi_headers[i], 8))
128 if (!avi_headers[i][0])
129 return AVERROR_INVALIDDATA;
131 if (header[7] == 0x19)
132 av_log(s, AV_LOG_INFO,
133 "This file has been generated by a totally broken muxer.\n");
138 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
140 AVIContext *avi = s->priv_data;
141 AVIOContext *pb = s->pb;
142 int longs_pre_entry = avio_rl16(pb);
143 int index_sub_type = avio_r8(pb);
144 int index_type = avio_r8(pb);
145 int entries_in_use = avio_rl32(pb);
146 int chunk_id = avio_rl32(pb);
147 int64_t base = avio_rl64(pb);
148 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
149 ((chunk_id >> 8 & 0xFF) - '0');
153 int64_t last_pos = -1;
154 int64_t filesize = avio_size(s->pb);
157 "longs_pre_entry:%d index_type:%d entries_in_use:%d "
158 "chunk_id:%X base:%16"PRIX64"\n",
165 if (stream_id >= s->nb_streams || stream_id < 0)
166 return AVERROR_INVALIDDATA;
167 st = s->streams[stream_id];
171 return AVERROR_INVALIDDATA;
175 if (index_type && longs_pre_entry != 2)
176 return AVERROR_INVALIDDATA;
178 return AVERROR_INVALIDDATA;
180 if (filesize > 0 && base >= filesize) {
181 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
182 if (base >> 32 == (base & 0xFFFFFFFF) &&
183 (base & 0xFFFFFFFF) < filesize &&
184 filesize <= 0xFFFFFFFF)
187 return AVERROR_INVALIDDATA;
190 for (i = 0; i < entries_in_use; i++) {
192 int64_t pos = avio_rl32(pb) + base - 8;
193 int len = avio_rl32(pb);
197 av_dlog(s, "pos:%"PRId64", len:%X\n", pos, len);
200 return AVERROR_INVALIDDATA;
202 if (last_pos == pos || pos == base - 8)
203 avi->non_interleaved = 1;
204 if (last_pos != pos && (len || !ast->sample_size))
205 av_add_index_entry(st, pos, ast->cum_len, len, 0,
206 key ? AVINDEX_KEYFRAME : 0);
208 ast->cum_len += get_duration(ast, len);
213 offset = avio_rl64(pb);
214 avio_rl32(pb); /* size */
215 duration = avio_rl32(pb);
218 return AVERROR_INVALIDDATA;
222 if (avi->odml_depth > MAX_ODML_DEPTH) {
223 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
224 return AVERROR_INVALIDDATA;
227 avio_seek(pb, offset + 8, SEEK_SET);
229 read_braindead_odml_indx(s, frame_num);
231 frame_num += duration;
233 avio_seek(pb, pos, SEEK_SET);
236 avi->index_loaded = 1;
240 static void clean_index(AVFormatContext *s)
245 for (i = 0; i < s->nb_streams; i++) {
246 AVStream *st = s->streams[i];
247 AVIStream *ast = st->priv_data;
248 int n = st->nb_index_entries;
249 int max = ast->sample_size;
250 int64_t pos, size, ts;
252 if (n != 1 || ast->sample_size == 0)
258 pos = st->index_entries[0].pos;
259 size = st->index_entries[0].size;
260 ts = st->index_entries[0].timestamp;
262 for (j = 0; j < size; j += max)
263 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
268 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
271 AVIOContext *pb = s->pb;
277 if (size == UINT_MAX)
278 return AVERROR(EINVAL);
279 value = av_malloc(size + 1);
281 return AVERROR(ENOMEM);
282 avio_read(pb, value, size);
287 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
288 AV_DICT_DONT_STRDUP_VAL);
291 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
292 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
294 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
296 char month[4], time[9], buffer[64];
298 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
299 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
300 month, &day, time, &year) == 4) {
301 for (i = 0; i < 12; i++)
302 if (!av_strcasecmp(month, months[i])) {
303 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
304 year, i + 1, day, time);
305 av_dict_set(metadata, "creation_time", buffer, 0);
307 } else if (date[4] == '/' && date[7] == '/') {
308 date[4] = date[7] = '-';
309 av_dict_set(metadata, "creation_time", date, 0);
313 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
315 while (avio_tell(s->pb) < end) {
316 uint32_t tag = avio_rl32(s->pb);
317 uint32_t size = avio_rl32(s->pb);
319 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
321 uint64_t tag_end = avio_tell(s->pb) + size;
322 while (avio_tell(s->pb) < tag_end) {
323 uint16_t tag = avio_rl16(s->pb);
324 uint16_t size = avio_rl16(s->pb);
325 const char *name = NULL;
326 char buffer[64] = { 0 };
327 size -= avio_read(s->pb, buffer,
328 FFMIN(size, sizeof(buffer) - 1));
337 name = "creation_time";
338 if (buffer[4] == ':' && buffer[7] == ':')
339 buffer[4] = buffer[7] = '-';
343 av_dict_set(&s->metadata, name, buffer, 0);
344 avio_skip(s->pb, size);
349 avio_skip(s->pb, size);
355 static int avi_read_header(AVFormatContext *s)
357 AVIContext *avi = s->priv_data;
358 AVIOContext *pb = s->pb;
359 unsigned int tag, tag1, handler;
360 int codec_type, stream_index, frame_period;
364 AVIStream *ast = NULL;
365 int avih_width = 0, avih_height = 0;
366 int amv_file_format = 0;
367 uint64_t list_end = 0;
370 avi->stream_index = -1;
372 ret = get_riff(s, pb);
376 avi->fsize = avio_size(pb);
378 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
388 size = avio_rl32(pb);
390 print_tag("tag", tag, size);
393 case MKTAG('L', 'I', 'S', 'T'):
394 list_end = avio_tell(pb) + size;
395 /* Ignored, except at start of video packets. */
396 tag1 = avio_rl32(pb);
398 print_tag("list", tag1, 0);
400 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
401 avi->movi_list = avio_tell(pb) - 4;
403 avi->movi_end = avi->movi_list + size + (size & 1);
405 avi->movi_end = avio_size(pb);
406 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
408 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
409 ff_read_riff_info(s, size - 4);
410 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
411 avi_read_nikon(s, list_end);
414 case MKTAG('I', 'D', 'I', 'T'):
416 unsigned char date[64] = { 0 };
418 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
420 avi_metadata_creation_time(&s->metadata, date);
423 case MKTAG('d', 'm', 'l', 'h'):
425 avio_skip(pb, size + (size & 1));
427 case MKTAG('a', 'm', 'v', 'h'):
429 case MKTAG('a', 'v', 'i', 'h'):
431 /* using frame_period is bad idea */
432 frame_period = avio_rl32(pb);
435 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
437 avio_skip(pb, 2 * 4);
440 avih_width = avio_rl32(pb);
441 avih_height = avio_rl32(pb);
443 avio_skip(pb, size - 10 * 4);
445 case MKTAG('s', 't', 'r', 'h'):
448 tag1 = avio_rl32(pb);
449 handler = avio_rl32(pb); /* codec tag */
451 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
452 avio_skip(pb, size - 8);
456 st = avformat_new_stream(s, NULL);
460 st->id = stream_index;
461 ast = av_mallocz(sizeof(AVIStream));
467 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
468 : MKTAG('v', 'i', 'd', 's');
470 print_tag("strh", tag1, -1);
472 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
473 tag1 == MKTAG('i', 'v', 'a', 's')) {
476 /* After some consideration -- I don't think we
477 * have to support anything but DV in type1 AVIs. */
478 if (s->nb_streams != 1)
481 if (handler != MKTAG('d', 'v', 's', 'd') &&
482 handler != MKTAG('d', 'v', 'h', 'd') &&
483 handler != MKTAG('d', 'v', 's', 'l'))
486 ast = s->streams[0]->priv_data;
487 av_freep(&s->streams[0]->codec->extradata);
488 av_freep(&s->streams[0]->codec);
489 av_freep(&s->streams[0]->info);
490 av_freep(&s->streams[0]);
492 if (CONFIG_DV_DEMUXER) {
493 avi->dv_demux = avpriv_dv_init_demux(s);
498 s->streams[0]->priv_data = ast;
499 avio_skip(pb, 3 * 4);
500 ast->scale = avio_rl32(pb);
501 ast->rate = avio_rl32(pb);
502 avio_skip(pb, 4); /* start time */
504 dv_dur = avio_rl32(pb);
505 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
506 dv_dur *= AV_TIME_BASE;
507 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
509 /* else, leave duration alone; timing estimation in utils.c
510 * will make a guess based on bitrate. */
512 stream_index = s->nb_streams - 1;
513 avio_skip(pb, size - 9 * 4);
517 assert(stream_index < s->nb_streams);
518 st->codec->stream_codec_tag = handler;
520 avio_rl32(pb); /* flags */
521 avio_rl16(pb); /* priority */
522 avio_rl16(pb); /* language */
523 avio_rl32(pb); /* initial frame */
524 ast->scale = avio_rl32(pb);
525 ast->rate = avio_rl32(pb);
526 if (!(ast->scale && ast->rate)) {
527 av_log(s, AV_LOG_WARNING,
528 "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
529 "(This file has been generated by broken software.)\n",
534 ast->scale = frame_period;
540 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
542 ast->cum_len = avio_rl32(pb); /* start */
543 st->nb_frames = avio_rl32(pb);
546 avio_rl32(pb); /* buffer size */
547 avio_rl32(pb); /* quality */
548 ast->sample_size = avio_rl32(pb); /* sample ssize */
549 ast->cum_len *= FFMAX(1, ast->sample_size);
550 av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
551 ast->rate, ast->scale, ast->sample_size);
554 case MKTAG('v', 'i', 'd', 's'):
555 codec_type = AVMEDIA_TYPE_VIDEO;
557 ast->sample_size = 0;
559 case MKTAG('a', 'u', 'd', 's'):
560 codec_type = AVMEDIA_TYPE_AUDIO;
562 case MKTAG('t', 'x', 't', 's'):
563 codec_type = AVMEDIA_TYPE_SUBTITLE;
565 case MKTAG('d', 'a', 't', 's'):
566 codec_type = AVMEDIA_TYPE_DATA;
569 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
572 if (ast->sample_size == 0)
573 st->duration = st->nb_frames;
574 ast->frame_offset = ast->cum_len;
575 avio_skip(pb, size - 12 * 4);
577 case MKTAG('s', 't', 'r', 'f'):
579 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
582 uint64_t cur_pos = avio_tell(pb);
583 if (cur_pos < list_end)
584 size = FFMIN(size, list_end - cur_pos);
585 st = s->streams[stream_index];
586 switch (codec_type) {
587 case AVMEDIA_TYPE_VIDEO:
588 if (amv_file_format) {
589 st->codec->width = avih_width;
590 st->codec->height = avih_height;
591 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
592 st->codec->codec_id = AV_CODEC_ID_AMV;
596 tag1 = ff_get_bmp_header(pb, st);
598 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
599 tag1 == MKTAG('D', 'X', 'S', 'A')) {
600 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
601 st->codec->codec_tag = tag1;
602 st->codec->codec_id = AV_CODEC_ID_XSUB;
606 if (size > 10 * 4 && size < (1 << 30)) {
607 st->codec->extradata_size = size - 10 * 4;
608 st->codec->extradata = av_malloc(st->codec->extradata_size +
609 FF_INPUT_BUFFER_PADDING_SIZE);
610 if (!st->codec->extradata) {
611 st->codec->extradata_size = 0;
612 return AVERROR(ENOMEM);
615 st->codec->extradata,
616 st->codec->extradata_size);
619 // FIXME: check if the encoder really did this correctly
620 if (st->codec->extradata_size & 1)
623 /* Extract palette from extradata if bpp <= 8.
624 * This code assumes that extradata contains only palette.
625 * This is true for all paletted codecs implemented in
627 if (st->codec->extradata_size &&
628 (st->codec->bits_per_coded_sample <= 8)) {
629 int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
630 const uint8_t *pal_src;
632 pal_size = FFMIN(pal_size, st->codec->extradata_size);
633 pal_src = st->codec->extradata +
634 st->codec->extradata_size - pal_size;
636 for (i = 0; i < pal_size / 4; i++)
637 ast->pal[i] = av_bswap32(((uint32_t *)pal_src)[i]);
639 memcpy(ast->pal, pal_src, pal_size);
644 print_tag("video", tag1, 0);
646 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
647 st->codec->codec_tag = tag1;
648 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
650 /* This is needed to get the pict type which is necessary
651 * for generating correct pts. */
652 st->need_parsing = AVSTREAM_PARSE_HEADERS;
653 // Support "Resolution 1:1" for Avid AVI Codec
654 if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
655 st->codec->extradata_size >= 31 &&
656 !memcmp(&st->codec->extradata[28], "1:1", 3))
657 st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
659 if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
660 st->codec->extradata_size < 1U << 30) {
661 st->codec->extradata_size += 9;
662 if ((ret = av_reallocp(&st->codec->extradata,
663 st->codec->extradata_size +
664 FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
665 st->codec->extradata_size = 0;
668 memcpy(st->codec->extradata + st->codec->extradata_size - 9,
671 st->codec->height = FFABS(st->codec->height);
673 // avio_skip(pb, size - 5 * 4);
675 case AVMEDIA_TYPE_AUDIO:
676 ret = ff_get_wav_header(pb, st->codec, size);
679 ast->dshow_block_align = st->codec->block_align;
680 if (ast->sample_size && st->codec->block_align &&
681 ast->sample_size != st->codec->block_align) {
684 "sample size (%d) != block align (%d)\n",
686 st->codec->block_align);
687 ast->sample_size = st->codec->block_align;
690 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
693 /* Force parsing as several audio frames can be in
694 * one packet and timestamps refer to packet start. */
695 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
696 /* ADTS header is in extradata, AAC without header must be
697 * stored as exact frames. Parser not needed and it will
699 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
700 st->codec->extradata_size)
701 st->need_parsing = AVSTREAM_PARSE_NONE;
702 /* AVI files with Xan DPCM audio (wrongly) declare PCM
703 * audio in the header but have Axan as stream_code_tag. */
704 if (st->codec->stream_codec_tag == AV_RL32("Axan")) {
705 st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
706 st->codec->codec_tag = 0;
708 if (amv_file_format) {
709 st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
710 ast->dshow_block_align = 0;
713 case AVMEDIA_TYPE_SUBTITLE:
714 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
715 st->codec->codec_id = AV_CODEC_ID_PROBE;
718 st->codec->codec_type = AVMEDIA_TYPE_DATA;
719 st->codec->codec_id = AV_CODEC_ID_NONE;
720 st->codec->codec_tag = 0;
726 case MKTAG('i', 'n', 'd', 'x'):
728 if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
729 read_braindead_odml_indx(s, 0) < 0 &&
730 (s->error_recognition & AV_EF_EXPLODE))
732 avio_seek(pb, i + size, SEEK_SET);
734 case MKTAG('v', 'p', 'r', 'p'):
735 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
736 AVRational active, active_aspect;
738 st = s->streams[stream_index];
745 active_aspect.den = avio_rl16(pb);
746 active_aspect.num = avio_rl16(pb);
747 active.num = avio_rl32(pb);
748 active.den = avio_rl32(pb);
749 avio_rl32(pb); // nbFieldsPerFrame
751 if (active_aspect.num && active_aspect.den &&
752 active.num && active.den) {
753 st->sample_aspect_ratio = av_div_q(active_aspect, active);
754 av_dlog(s, "vprp %d/%d %d/%d\n",
755 active_aspect.num, active_aspect.den,
756 active.num, active.den);
762 case MKTAG('s', 't', 'r', 'n'):
764 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
770 if (size > 1000000) {
771 av_log(s, AV_LOG_ERROR,
772 "Something went wrong during header parsing, "
773 "I will ignore it and try to continue anyway.\n");
774 if (s->error_recognition & AV_EF_EXPLODE)
776 avi->movi_list = avio_tell(pb) - 4;
777 avi->movi_end = avio_size(pb);
788 /* check stream number */
789 if (stream_index != s->nb_streams - 1) {
792 return AVERROR_INVALIDDATA;
795 if (!avi->index_loaded && pb->seekable)
797 avi->index_loaded = 1;
798 avi->non_interleaved |= guess_ni_flag(s);
799 for (i = 0; i < s->nb_streams; i++) {
800 AVStream *st = s->streams[i];
801 if (st->nb_index_entries)
804 if (i == s->nb_streams && avi->non_interleaved) {
805 av_log(s, AV_LOG_WARNING,
806 "Non-interleaved AVI without index, switching to interleaved\n");
807 avi->non_interleaved = 0;
810 if (avi->non_interleaved) {
811 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
815 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
816 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
821 static int read_gab2_sub(AVStream *st, AVPacket *pkt)
823 if (pkt->size >= 7 &&
824 !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
826 int score = AVPROBE_SCORE_EXTENSION, ret;
827 AVIStream *ast = st->priv_data;
828 AVInputFormat *sub_demuxer;
829 AVRational time_base;
830 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
832 0, NULL, NULL, NULL, NULL);
834 unsigned int desc_len = avio_rl32(pb);
836 if (desc_len > pb->buf_end - pb->buf_ptr)
839 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
840 avio_skip(pb, desc_len - ret);
842 av_dict_set(&st->metadata, "title", desc, 0);
844 avio_rl16(pb); /* flags? */
845 avio_rl32(pb); /* data size */
847 pd = (AVProbeData) { .buf = pb->buf_ptr,
848 .buf_size = pb->buf_end - pb->buf_ptr };
849 if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
852 if (!(ast->sub_ctx = avformat_alloc_context()))
855 ast->sub_ctx->pb = pb;
856 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
857 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
858 *st->codec = *ast->sub_ctx->streams[0]->codec;
859 ast->sub_ctx->streams[0]->codec->extradata = NULL;
860 time_base = ast->sub_ctx->streams[0]->time_base;
861 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
863 ast->sub_buffer = pkt->data;
864 memset(pkt, 0, sizeof(*pkt));
873 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
876 AVIStream *ast, *next_ast = next_st->priv_data;
877 int64_t ts, next_ts, ts_min = INT64_MAX;
878 AVStream *st, *sub_st = NULL;
881 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
884 for (i = 0; i < s->nb_streams; i++) {
887 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
888 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
889 if (ts <= next_ts && ts < ts_min) {
897 ast = sub_st->priv_data;
899 pkt->stream_index = sub_st->index;
901 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
902 ast->sub_pkt.data = NULL;
907 static int get_stream_idx(int *d)
909 if (d[0] >= '0' && d[0] <= '9' &&
910 d[1] >= '0' && d[1] <= '9') {
911 return (d[0] - '0') * 10 + (d[1] - '0');
913 return 100; // invalid stream ID
917 static int avi_sync(AVFormatContext *s, int exit_early)
919 AVIContext *avi = s->priv_data;
920 AVIOContext *pb = s->pb;
927 memset(d, -1, sizeof(d));
928 for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
931 for (j = 0; j < 7; j++)
935 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
937 n = get_stream_idx(d + 2);
938 av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
939 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
940 if (i + (uint64_t)size > avi->fsize || d[0] > 127)
944 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
946 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
947 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
953 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
958 n = avi->dv_demux ? 0 : get_stream_idx(d);
960 if (!((i - avi->last_pkt_pos) & 1) &&
961 get_stream_idx(d + 1) < s->nb_streams)
964 // detect ##ix chunk and skip
965 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
971 if (n < s->nb_streams) {
977 if (s->nb_streams >= 2) {
978 AVStream *st1 = s->streams[1];
979 AVIStream *ast1 = st1->priv_data;
980 // workaround for broken small-file-bug402.avi
981 if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
982 st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
983 st1->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
984 ast->prefix == 'd' * 256 + 'c' &&
985 (d[2] * 256 + d[3] == ast1->prefix ||
986 !ast1->prefix_count)) {
990 av_log(s, AV_LOG_WARNING,
991 "Invalid stream + prefix combination, assuming audio.\n");
995 if (!avi->dv_demux &&
996 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
997 // FIXME: needs a little reordering
998 (st->discard >= AVDISCARD_NONKEY &&
999 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1000 || st->discard >= AVDISCARD_ALL)) {
1002 ast->frame_offset += get_duration(ast, size);
1004 avio_skip(pb, size);
1008 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1009 int k = avio_r8(pb);
1010 int last = (k + avio_r8(pb) - 1) & 0xFF;
1012 avio_rl16(pb); // flags
1014 // b + (g << 8) + (r << 16);
1015 for (; k <= last; k++)
1016 ast->pal[k] = avio_rb32(pb) >> 8;
1020 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1021 d[2] < 128 && d[3] < 128) ||
1022 d[2] * 256 + d[3] == ast->prefix /* ||
1023 (d[2] == 'd' && d[3] == 'c') ||
1024 (d[2] == 'w' && d[3] == 'b') */) {
1027 if (d[2] * 256 + d[3] == ast->prefix)
1028 ast->prefix_count++;
1030 ast->prefix = d[2] * 256 + d[3];
1031 ast->prefix_count = 0;
1034 avi->stream_index = n;
1035 ast->packet_size = size + 8;
1036 ast->remaining = size;
1038 if (size || !ast->sample_size) {
1039 uint64_t pos = avio_tell(pb) - 8;
1040 if (!st->index_entries || !st->nb_index_entries ||
1041 st->index_entries[st->nb_index_entries - 1].pos < pos) {
1042 av_add_index_entry(st, pos, ast->frame_offset, size,
1043 0, AVINDEX_KEYFRAME);
1054 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1056 AVIContext *avi = s->priv_data;
1057 AVIOContext *pb = s->pb;
1059 #if FF_API_DESTRUCT_PACKET
1063 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1064 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1071 if (avi->non_interleaved) {
1072 int best_stream_index = 0;
1073 AVStream *best_st = NULL;
1074 AVIStream *best_ast;
1075 int64_t best_ts = INT64_MAX;
1078 for (i = 0; i < s->nb_streams; i++) {
1079 AVStream *st = s->streams[i];
1080 AVIStream *ast = st->priv_data;
1081 int64_t ts = ast->frame_offset;
1084 if (!st->nb_index_entries)
1087 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1088 if (!ast->remaining && ts > last_ts)
1091 ts = av_rescale_q(ts, st->time_base,
1092 (AVRational) { FFMAX(1, ast->sample_size),
1095 av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
1096 st->time_base.num, st->time_base.den, ast->frame_offset);
1100 best_stream_index = i;
1106 best_ast = best_st->priv_data;
1107 best_ts = av_rescale_q(best_ts,
1108 (AVRational) { FFMAX(1, best_ast->sample_size),
1110 best_st->time_base);
1111 if (best_ast->remaining) {
1112 i = av_index_search_timestamp(best_st,
1115 AVSEEK_FLAG_BACKWARD);
1117 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1119 best_ast->frame_offset = best_st->index_entries[i].timestamp;
1123 int64_t pos = best_st->index_entries[i].pos;
1124 pos += best_ast->packet_size - best_ast->remaining;
1125 avio_seek(s->pb, pos + 8, SEEK_SET);
1127 assert(best_ast->remaining <= best_ast->packet_size);
1129 avi->stream_index = best_stream_index;
1130 if (!best_ast->remaining)
1131 best_ast->packet_size =
1132 best_ast->remaining = best_st->index_entries[i].size;
1137 if (avi->stream_index >= 0) {
1138 AVStream *st = s->streams[avi->stream_index];
1139 AVIStream *ast = st->priv_data;
1142 if (get_subtitle_pkt(s, st, pkt))
1145 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1146 if (ast->sample_size <= 1)
1148 else if (ast->sample_size < 32)
1149 // arbitrary multiplier to avoid tiny packets for raw PCM data
1150 size = 1024 * ast->sample_size;
1152 size = ast->sample_size;
1154 if (size > ast->remaining)
1155 size = ast->remaining;
1156 avi->last_pkt_pos = avio_tell(pb);
1157 err = av_get_packet(pb, pkt, size);
1161 if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
1163 pal = av_packet_new_side_data(pkt,
1164 AV_PKT_DATA_PALETTE,
1167 av_log(s, AV_LOG_ERROR,
1168 "Failed to allocate data for palette\n");
1170 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1175 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1176 AVBufferRef *avbuf = pkt->buf;
1177 #if FF_API_DESTRUCT_PACKET
1178 FF_DISABLE_DEPRECATION_WARNINGS
1179 dstr = pkt->destruct;
1180 FF_ENABLE_DEPRECATION_WARNINGS
1182 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1183 pkt->data, pkt->size);
1184 #if FF_API_DESTRUCT_PACKET
1185 FF_DISABLE_DEPRECATION_WARNINGS
1186 pkt->destruct = dstr;
1187 FF_ENABLE_DEPRECATION_WARNINGS
1190 pkt->flags |= AV_PKT_FLAG_KEY;
1192 av_free_packet(pkt);
1193 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1194 !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1195 ast->frame_offset++;
1196 avi->stream_index = -1;
1200 /* XXX: How to handle B-frames in AVI? */
1201 pkt->dts = ast->frame_offset;
1202 // pkt->dts += ast->start;
1203 if (ast->sample_size)
1204 pkt->dts /= ast->sample_size;
1206 "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
1207 "base:%d st:%d size:%d\n",
1216 pkt->stream_index = avi->stream_index;
1218 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1221 assert(st->index_entries);
1223 index = av_index_search_timestamp(st, ast->frame_offset, 0);
1224 e = &st->index_entries[index];
1226 if (index >= 0 && e->timestamp == ast->frame_offset)
1227 if (e->flags & AVINDEX_KEYFRAME)
1228 pkt->flags |= AV_PKT_FLAG_KEY;
1230 pkt->flags |= AV_PKT_FLAG_KEY;
1232 ast->frame_offset += get_duration(ast, pkt->size);
1234 ast->remaining -= err;
1235 if (!ast->remaining) {
1236 avi->stream_index = -1;
1237 ast->packet_size = 0;
1243 if ((err = avi_sync(s, 0)) < 0)
1248 /* XXX: We make the implicit supposition that the positions are sorted
1249 * for each stream. */
1250 static int avi_read_idx1(AVFormatContext *s, int size)
1252 AVIContext *avi = s->priv_data;
1253 AVIOContext *pb = s->pb;
1254 int nb_index_entries, i;
1257 unsigned int index, tag, flags, pos, len, first_packet = 1;
1258 unsigned last_pos = -1;
1259 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1261 nb_index_entries = size / 16;
1262 if (nb_index_entries <= 0)
1263 return AVERROR_INVALIDDATA;
1265 idx1_pos = avio_tell(pb);
1266 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1267 if (avi_sync(s, 1) == 0)
1268 first_packet_pos = avio_tell(pb) - 8;
1269 avi->stream_index = -1;
1270 avio_seek(pb, idx1_pos, SEEK_SET);
1272 /* Read the entries and sort them in each stream component. */
1273 for (i = 0; i < nb_index_entries; i++) {
1274 tag = avio_rl32(pb);
1275 flags = avio_rl32(pb);
1276 pos = avio_rl32(pb);
1277 len = avio_rl32(pb);
1278 av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1279 i, tag, flags, pos, len);
1281 index = ((tag & 0xff) - '0') * 10;
1282 index += (tag >> 8 & 0xff) - '0';
1283 if (index >= s->nb_streams)
1285 st = s->streams[index];
1286 ast = st->priv_data;
1288 if (first_packet && first_packet_pos && len) {
1289 data_offset = first_packet_pos - pos;
1294 av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1296 if (pb->eof_reached)
1297 return AVERROR_INVALIDDATA;
1299 if (last_pos == pos)
1300 avi->non_interleaved = 1;
1301 else if (len || !ast->sample_size)
1302 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1303 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1304 ast->cum_len += get_duration(ast, len);
1310 static int guess_ni_flag(AVFormatContext *s)
1313 int64_t last_start = 0;
1314 int64_t first_end = INT64_MAX;
1315 int64_t oldpos = avio_tell(s->pb);
1317 for (i = 0; i < s->nb_streams; i++) {
1318 AVStream *st = s->streams[i];
1319 int n = st->nb_index_entries;
1326 int64_t pos = st->index_entries[0].pos;
1327 avio_seek(s->pb, pos + 4, SEEK_SET);
1328 size = avio_rl32(s->pb);
1329 if (pos + size > st->index_entries[1].pos)
1330 last_start = INT64_MAX;
1333 if (st->index_entries[0].pos > last_start)
1334 last_start = st->index_entries[0].pos;
1335 if (st->index_entries[n - 1].pos < first_end)
1336 first_end = st->index_entries[n - 1].pos;
1338 avio_seek(s->pb, oldpos, SEEK_SET);
1339 return last_start > first_end;
1342 static int avi_load_index(AVFormatContext *s)
1344 AVIContext *avi = s->priv_data;
1345 AVIOContext *pb = s->pb;
1347 int64_t pos = avio_tell(pb);
1350 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1351 goto the_end; // maybe truncated file
1352 av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1354 if (pb->eof_reached)
1356 tag = avio_rl32(pb);
1357 size = avio_rl32(pb);
1358 av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1365 if (tag == MKTAG('i', 'd', 'x', '1') &&
1366 avi_read_idx1(s, size) >= 0) {
1372 if (avio_skip(pb, size) < 0)
1373 break; // something is wrong here
1377 avio_seek(pb, pos, SEEK_SET);
1381 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1383 AVIStream *ast2 = st2->priv_data;
1384 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1385 av_free_packet(&ast2->sub_pkt);
1386 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1387 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1388 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1391 static int avi_read_seek(AVFormatContext *s, int stream_index,
1392 int64_t timestamp, int flags)
1394 AVIContext *avi = s->priv_data;
1400 /* Does not matter which stream is requested dv in avi has the
1401 * stream information in the first video stream.
1406 if (!avi->index_loaded) {
1407 /* we only load the index on demand */
1409 avi->index_loaded = 1;
1412 st = s->streams[stream_index];
1413 ast = st->priv_data;
1414 index = av_index_search_timestamp(st,
1415 timestamp * FFMAX(ast->sample_size, 1),
1418 return AVERROR_INVALIDDATA;
1420 /* find the position */
1421 pos = st->index_entries[index].pos;
1422 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1424 av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
1425 timestamp, index, st->index_entries[index].timestamp);
1427 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1428 /* One and only one real stream for DV in AVI, and it has video */
1429 /* offsets. Calling with other stream indexes should have failed */
1430 /* the av_index_search_timestamp call above. */
1432 /* Feed the DV video stream version of the timestamp to the */
1433 /* DV demux so it can synthesize correct timestamps. */
1434 ff_dv_offset_reset(avi->dv_demux, timestamp);
1436 avio_seek(s->pb, pos, SEEK_SET);
1437 avi->stream_index = -1;
1441 for (i = 0; i < s->nb_streams; i++) {
1442 AVStream *st2 = s->streams[i];
1443 AVIStream *ast2 = st2->priv_data;
1446 ast2->remaining = 0;
1448 if (ast2->sub_ctx) {
1449 seek_subtitle(st, st2, timestamp);
1453 if (st2->nb_index_entries <= 0)
1456 // assert(st2->codec->block_align);
1457 assert((int64_t)st2->time_base.num * ast2->rate ==
1458 (int64_t)st2->time_base.den * ast2->scale);
1459 index = av_index_search_timestamp(st2,
1460 av_rescale_q(timestamp,
1463 FFMAX(ast2->sample_size, 1),
1464 flags | AVSEEK_FLAG_BACKWARD);
1468 if (!avi->non_interleaved) {
1469 while (index > 0 && st2->index_entries[index].pos > pos)
1471 while (index + 1 < st2->nb_index_entries &&
1472 st2->index_entries[index].pos < pos)
1476 av_dlog(s, "%"PRId64" %d %"PRId64"\n",
1477 timestamp, index, st2->index_entries[index].timestamp);
1478 /* extract the current frame number */
1479 ast2->frame_offset = st2->index_entries[index].timestamp;
1483 avio_seek(s->pb, pos, SEEK_SET);
1484 avi->stream_index = -1;
1488 static int avi_read_close(AVFormatContext *s)
1491 AVIContext *avi = s->priv_data;
1493 for (i = 0; i < s->nb_streams; i++) {
1494 AVStream *st = s->streams[i];
1495 AVIStream *ast = st->priv_data;
1498 av_freep(&ast->sub_ctx->pb);
1499 avformat_close_input(&ast->sub_ctx);
1501 av_free(ast->sub_buffer);
1502 av_free_packet(&ast->sub_pkt);
1506 av_free(avi->dv_demux);
1511 static int avi_probe(AVProbeData *p)
1515 /* check file header */
1516 for (i = 0; avi_headers[i][0]; i++)
1517 if (!memcmp(p->buf, avi_headers[i], 4) &&
1518 !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
1519 return AVPROBE_SCORE_MAX;
1524 AVInputFormat ff_avi_demuxer = {
1526 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1527 .priv_data_size = sizeof(AVIContext),
1528 .read_probe = avi_probe,
1529 .read_header = avi_read_header,
1530 .read_packet = avi_read_packet,
1531 .read_close = avi_read_close,
1532 .read_seek = avi_read_seek,