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/internal.h"
26 #include "libavutil/intreadwrite.h"
27 #include "libavutil/mathematics.h"
37 typedef struct AVIStream {
38 int64_t frame_offset; /* current frame (video) or byte (audio) counter
39 * (used to compute the pts) */
45 int sample_size; /* size of one sample (or packet)
46 * (in the rate/scale sense) in bytes */
48 int64_t cum_len; /* temporary storage (used during seek) */
49 int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
53 int dshow_block_align; /* block align variable used to emulate bugs in
54 * the MS dshow demuxer */
56 AVFormatContext *sub_ctx;
71 DVDemuxContext *dv_demux;
73 #define MAX_ODML_DEPTH 1000
76 static const char avi_headers[][8] = {
77 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
78 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
79 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
80 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
81 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
85 static const AVMetadataConv avi_metadata_conv[] = {
90 static int avi_load_index(AVFormatContext *s);
91 static int guess_ni_flag(AVFormatContext *s);
93 #define print_tag(str, tag, size) \
94 av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
101 static inline int get_duration(AVIStream *ast, int len)
103 if (ast->sample_size)
105 else if (ast->dshow_block_align)
106 return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
111 static int get_riff(AVFormatContext *s, AVIOContext *pb)
113 AVIContext *avi = s->priv_data;
117 /* check RIFF header */
118 avio_read(pb, header, 4);
119 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
120 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
121 avio_read(pb, header + 4, 4);
123 for (i = 0; avi_headers[i][0]; i++)
124 if (!memcmp(header, avi_headers[i], 8))
126 if (!avi_headers[i][0])
127 return AVERROR_INVALIDDATA;
129 if (header[7] == 0x19)
130 av_log(s, AV_LOG_INFO,
131 "This file has been generated by a totally broken muxer.\n");
136 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
138 AVIContext *avi = s->priv_data;
139 AVIOContext *pb = s->pb;
140 int longs_pre_entry = avio_rl16(pb);
141 int index_sub_type = avio_r8(pb);
142 int index_type = avio_r8(pb);
143 int entries_in_use = avio_rl32(pb);
144 int chunk_id = avio_rl32(pb);
145 int64_t base = avio_rl64(pb);
146 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
147 ((chunk_id >> 8 & 0xFF) - '0');
151 int64_t last_pos = -1;
152 int64_t filesize = avio_size(s->pb);
155 "longs_pre_entry:%d index_type:%d entries_in_use:%d "
156 "chunk_id:%X base:%16"PRIX64"\n",
163 if (stream_id >= s->nb_streams || stream_id < 0)
164 return AVERROR_INVALIDDATA;
165 st = s->streams[stream_id];
169 return AVERROR_INVALIDDATA;
173 if (index_type && longs_pre_entry != 2)
174 return AVERROR_INVALIDDATA;
176 return AVERROR_INVALIDDATA;
178 if (filesize > 0 && base >= filesize) {
179 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
180 if (base >> 32 == (base & 0xFFFFFFFF) &&
181 (base & 0xFFFFFFFF) < filesize &&
182 filesize <= 0xFFFFFFFF)
185 return AVERROR_INVALIDDATA;
188 for (i = 0; i < entries_in_use; i++) {
190 int64_t pos = avio_rl32(pb) + base - 8;
191 int len = avio_rl32(pb);
195 av_dlog(s, "pos:%"PRId64", len:%X\n", pos, len);
198 return AVERROR_INVALIDDATA;
200 if (last_pos == pos || pos == base - 8)
201 avi->non_interleaved = 1;
202 if (last_pos != pos && (len || !ast->sample_size))
203 av_add_index_entry(st, pos, ast->cum_len, len, 0,
204 key ? AVINDEX_KEYFRAME : 0);
206 ast->cum_len += get_duration(ast, len);
211 offset = avio_rl64(pb);
212 avio_rl32(pb); /* size */
213 duration = avio_rl32(pb);
216 return AVERROR_INVALIDDATA;
220 if (avi->odml_depth > MAX_ODML_DEPTH) {
221 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
222 return AVERROR_INVALIDDATA;
225 avio_seek(pb, offset + 8, SEEK_SET);
227 read_braindead_odml_indx(s, frame_num);
229 frame_num += duration;
231 avio_seek(pb, pos, SEEK_SET);
234 avi->index_loaded = 1;
238 static void clean_index(AVFormatContext *s)
243 for (i = 0; i < s->nb_streams; i++) {
244 AVStream *st = s->streams[i];
245 AVIStream *ast = st->priv_data;
246 int n = st->nb_index_entries;
247 int max = ast->sample_size;
248 int64_t pos, size, ts;
250 if (n != 1 || ast->sample_size == 0)
256 pos = st->index_entries[0].pos;
257 size = st->index_entries[0].size;
258 ts = st->index_entries[0].timestamp;
260 for (j = 0; j < size; j += max)
261 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
266 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
269 AVIOContext *pb = s->pb;
275 if (size == UINT_MAX)
276 return AVERROR(EINVAL);
277 value = av_malloc(size + 1);
279 return AVERROR(ENOMEM);
280 avio_read(pb, value, size);
285 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
286 AV_DICT_DONT_STRDUP_VAL);
289 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
290 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
292 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
294 char month[4], time[9], buffer[64];
296 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
297 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
298 month, &day, time, &year) == 4) {
299 for (i = 0; i < 12; i++)
300 if (!av_strcasecmp(month, months[i])) {
301 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
302 year, i + 1, day, time);
303 av_dict_set(metadata, "creation_time", buffer, 0);
305 } else if (date[4] == '/' && date[7] == '/') {
306 date[4] = date[7] = '-';
307 av_dict_set(metadata, "creation_time", date, 0);
311 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
313 while (avio_tell(s->pb) < end) {
314 uint32_t tag = avio_rl32(s->pb);
315 uint32_t size = avio_rl32(s->pb);
317 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
319 uint64_t tag_end = avio_tell(s->pb) + size;
320 while (avio_tell(s->pb) < tag_end) {
321 uint16_t tag = avio_rl16(s->pb);
322 uint16_t size = avio_rl16(s->pb);
323 const char *name = NULL;
324 char buffer[64] = { 0 };
325 size -= avio_read(s->pb, buffer,
326 FFMIN(size, sizeof(buffer) - 1));
335 name = "creation_time";
336 if (buffer[4] == ':' && buffer[7] == ':')
337 buffer[4] = buffer[7] = '-';
341 av_dict_set(&s->metadata, name, buffer, 0);
342 avio_skip(s->pb, size);
347 avio_skip(s->pb, size);
353 static int avi_read_header(AVFormatContext *s)
355 AVIContext *avi = s->priv_data;
356 AVIOContext *pb = s->pb;
357 unsigned int tag, tag1, handler;
358 int codec_type, stream_index, frame_period;
362 AVIStream *ast = NULL;
363 int avih_width = 0, avih_height = 0;
364 int amv_file_format = 0;
365 uint64_t list_end = 0;
368 avi->stream_index = -1;
370 ret = get_riff(s, pb);
374 avi->fsize = avio_size(pb);
376 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
386 size = avio_rl32(pb);
388 print_tag("tag", tag, size);
391 case MKTAG('L', 'I', 'S', 'T'):
392 list_end = avio_tell(pb) + size;
393 /* Ignored, except at start of video packets. */
394 tag1 = avio_rl32(pb);
396 print_tag("list", tag1, 0);
398 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
399 avi->movi_list = avio_tell(pb) - 4;
401 avi->movi_end = avi->movi_list + size + (size & 1);
403 avi->movi_end = avio_size(pb);
404 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
406 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
407 ff_read_riff_info(s, size - 4);
408 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
409 avi_read_nikon(s, list_end);
412 case MKTAG('I', 'D', 'I', 'T'):
414 unsigned char date[64] = { 0 };
416 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
418 avi_metadata_creation_time(&s->metadata, date);
421 case MKTAG('d', 'm', 'l', 'h'):
423 avio_skip(pb, size + (size & 1));
425 case MKTAG('a', 'm', 'v', 'h'):
427 case MKTAG('a', 'v', 'i', 'h'):
429 /* using frame_period is bad idea */
430 frame_period = avio_rl32(pb);
433 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
435 avio_skip(pb, 2 * 4);
438 avih_width = avio_rl32(pb);
439 avih_height = avio_rl32(pb);
441 avio_skip(pb, size - 10 * 4);
443 case MKTAG('s', 't', 'r', 'h'):
446 tag1 = avio_rl32(pb);
447 handler = avio_rl32(pb); /* codec tag */
449 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
450 avio_skip(pb, size - 8);
454 st = avformat_new_stream(s, NULL);
458 st->id = stream_index;
459 ast = av_mallocz(sizeof(AVIStream));
465 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
466 : MKTAG('v', 'i', 'd', 's');
468 print_tag("strh", tag1, -1);
470 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
471 tag1 == MKTAG('i', 'v', 'a', 's')) {
474 /* After some consideration -- I don't think we
475 * have to support anything but DV in type1 AVIs. */
476 if (s->nb_streams != 1)
479 if (handler != MKTAG('d', 'v', 's', 'd') &&
480 handler != MKTAG('d', 'v', 'h', 'd') &&
481 handler != MKTAG('d', 'v', 's', 'l'))
484 ast = s->streams[0]->priv_data;
485 av_freep(&s->streams[0]->codec->extradata);
486 av_freep(&s->streams[0]->codec);
487 av_freep(&s->streams[0]);
489 if (CONFIG_DV_DEMUXER) {
490 avi->dv_demux = avpriv_dv_init_demux(s);
494 s->streams[0]->priv_data = ast;
495 avio_skip(pb, 3 * 4);
496 ast->scale = avio_rl32(pb);
497 ast->rate = avio_rl32(pb);
498 avio_skip(pb, 4); /* start time */
500 dv_dur = avio_rl32(pb);
501 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
502 dv_dur *= AV_TIME_BASE;
503 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
505 /* else, leave duration alone; timing estimation in utils.c
506 * will make a guess based on bitrate. */
508 stream_index = s->nb_streams - 1;
509 avio_skip(pb, size - 9 * 4);
513 assert(stream_index < s->nb_streams);
514 st->codec->stream_codec_tag = handler;
516 avio_rl32(pb); /* flags */
517 avio_rl16(pb); /* priority */
518 avio_rl16(pb); /* language */
519 avio_rl32(pb); /* initial frame */
520 ast->scale = avio_rl32(pb);
521 ast->rate = avio_rl32(pb);
522 if (!(ast->scale && ast->rate)) {
523 av_log(s, AV_LOG_WARNING,
524 "scale/rate is %u/%u which is invalid. "
525 "(This file has been generated by broken software.)\n",
530 ast->scale = frame_period;
536 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
538 ast->cum_len = avio_rl32(pb); /* start */
539 st->nb_frames = avio_rl32(pb);
542 avio_rl32(pb); /* buffer size */
543 avio_rl32(pb); /* quality */
544 ast->sample_size = avio_rl32(pb); /* sample ssize */
545 ast->cum_len *= FFMAX(1, ast->sample_size);
546 av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
547 ast->rate, ast->scale, ast->sample_size);
550 case MKTAG('v', 'i', 'd', 's'):
551 codec_type = AVMEDIA_TYPE_VIDEO;
553 ast->sample_size = 0;
555 case MKTAG('a', 'u', 'd', 's'):
556 codec_type = AVMEDIA_TYPE_AUDIO;
558 case MKTAG('t', 'x', 't', 's'):
559 codec_type = AVMEDIA_TYPE_SUBTITLE;
561 case MKTAG('d', 'a', 't', 's'):
562 codec_type = AVMEDIA_TYPE_DATA;
565 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
568 if (ast->sample_size == 0)
569 st->duration = st->nb_frames;
570 ast->frame_offset = ast->cum_len;
571 avio_skip(pb, size - 12 * 4);
573 case MKTAG('s', 't', 'r', 'f'):
575 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
578 uint64_t cur_pos = avio_tell(pb);
579 if (cur_pos < list_end)
580 size = FFMIN(size, list_end - cur_pos);
581 st = s->streams[stream_index];
582 switch (codec_type) {
583 case AVMEDIA_TYPE_VIDEO:
584 if (amv_file_format) {
585 st->codec->width = avih_width;
586 st->codec->height = avih_height;
587 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
588 st->codec->codec_id = AV_CODEC_ID_AMV;
592 tag1 = ff_get_bmp_header(pb, st);
594 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
595 tag1 == MKTAG('D', 'X', 'S', 'A')) {
596 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
597 st->codec->codec_tag = tag1;
598 st->codec->codec_id = AV_CODEC_ID_XSUB;
602 if (size > 10 * 4 && size < (1 << 30)) {
603 st->codec->extradata_size = size - 10 * 4;
604 st->codec->extradata = av_malloc(st->codec->extradata_size +
605 FF_INPUT_BUFFER_PADDING_SIZE);
606 if (!st->codec->extradata) {
607 st->codec->extradata_size = 0;
608 return AVERROR(ENOMEM);
611 st->codec->extradata,
612 st->codec->extradata_size);
615 // FIXME: check if the encoder really did this correctly
616 if (st->codec->extradata_size & 1)
619 /* Extract palette from extradata if bpp <= 8.
620 * This code assumes that extradata contains only palette.
621 * This is true for all paletted codecs implemented in
623 if (st->codec->extradata_size &&
624 (st->codec->bits_per_coded_sample <= 8)) {
625 int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
626 const uint8_t *pal_src;
628 pal_size = FFMIN(pal_size, st->codec->extradata_size);
629 pal_src = st->codec->extradata +
630 st->codec->extradata_size - pal_size;
632 for (i = 0; i < pal_size / 4; i++)
633 ast->pal[i] = av_bswap32(((uint32_t *)pal_src)[i]);
635 memcpy(ast->pal, pal_src, pal_size);
640 print_tag("video", tag1, 0);
642 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
643 st->codec->codec_tag = tag1;
644 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
646 /* This is needed to get the pict type which is necessary
647 * for generating correct pts. */
648 st->need_parsing = AVSTREAM_PARSE_HEADERS;
649 // Support "Resolution 1:1" for Avid AVI Codec
650 if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
651 st->codec->extradata_size >= 31 &&
652 !memcmp(&st->codec->extradata[28], "1:1", 3))
653 st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
655 if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
656 st->codec->extradata_size < 1U << 30) {
657 st->codec->extradata_size += 9;
658 if ((ret = av_reallocp(&st->codec->extradata,
659 st->codec->extradata_size +
660 FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
661 st->codec->extradata_size = 0;
664 memcpy(st->codec->extradata + st->codec->extradata_size - 9,
667 st->codec->height = FFABS(st->codec->height);
669 // avio_skip(pb, size - 5 * 4);
671 case AVMEDIA_TYPE_AUDIO:
672 ret = ff_get_wav_header(pb, st->codec, size);
675 ast->dshow_block_align = st->codec->block_align;
676 if (ast->sample_size && st->codec->block_align &&
677 ast->sample_size != st->codec->block_align) {
680 "sample size (%d) != block align (%d)\n",
682 st->codec->block_align);
683 ast->sample_size = st->codec->block_align;
686 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
689 /* Force parsing as several audio frames can be in
690 * one packet and timestamps refer to packet start. */
691 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
692 /* ADTS header is in extradata, AAC without header must be
693 * stored as exact frames. Parser not needed and it will
695 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
696 st->codec->extradata_size)
697 st->need_parsing = AVSTREAM_PARSE_NONE;
698 /* AVI files with Xan DPCM audio (wrongly) declare PCM
699 * audio in the header but have Axan as stream_code_tag. */
700 if (st->codec->stream_codec_tag == AV_RL32("Axan")) {
701 st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
702 st->codec->codec_tag = 0;
704 if (amv_file_format) {
705 st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
706 ast->dshow_block_align = 0;
709 case AVMEDIA_TYPE_SUBTITLE:
710 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
711 st->codec->codec_id = AV_CODEC_ID_PROBE;
714 st->codec->codec_type = AVMEDIA_TYPE_DATA;
715 st->codec->codec_id = AV_CODEC_ID_NONE;
716 st->codec->codec_tag = 0;
722 case MKTAG('i', 'n', 'd', 'x'):
724 if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
725 read_braindead_odml_indx(s, 0) < 0 &&
726 (s->error_recognition & AV_EF_EXPLODE))
728 avio_seek(pb, i + size, SEEK_SET);
730 case MKTAG('v', 'p', 'r', 'p'):
731 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
732 AVRational active, active_aspect;
734 st = s->streams[stream_index];
741 active_aspect.den = avio_rl16(pb);
742 active_aspect.num = avio_rl16(pb);
743 active.num = avio_rl32(pb);
744 active.den = avio_rl32(pb);
745 avio_rl32(pb); // nbFieldsPerFrame
747 if (active_aspect.num && active_aspect.den &&
748 active.num && active.den) {
749 st->sample_aspect_ratio = av_div_q(active_aspect, active);
750 av_dlog(s, "vprp %d/%d %d/%d\n",
751 active_aspect.num, active_aspect.den,
752 active.num, active.den);
758 case MKTAG('s', 't', 'r', 'n'):
760 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
766 if (size > 1000000) {
767 av_log(s, AV_LOG_ERROR,
768 "Something went wrong during header parsing, "
769 "I will ignore it and try to continue anyway.\n");
770 if (s->error_recognition & AV_EF_EXPLODE)
772 avi->movi_list = avio_tell(pb) - 4;
773 avi->movi_end = avio_size(pb);
784 /* check stream number */
785 if (stream_index != s->nb_streams - 1) {
788 return AVERROR_INVALIDDATA;
791 if (!avi->index_loaded && pb->seekable)
793 avi->index_loaded = 1;
794 avi->non_interleaved |= guess_ni_flag(s);
795 for (i = 0; i < s->nb_streams; i++) {
796 AVStream *st = s->streams[i];
797 if (st->nb_index_entries)
800 if (i == s->nb_streams && avi->non_interleaved) {
801 av_log(s, AV_LOG_WARNING,
802 "Non-interleaved AVI without index, switching to interleaved\n");
803 avi->non_interleaved = 0;
806 if (avi->non_interleaved) {
807 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
811 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
812 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
817 static int read_gab2_sub(AVStream *st, AVPacket *pkt)
819 if (pkt->size >= 7 &&
820 !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
822 int score = AVPROBE_SCORE_EXTENSION, ret;
823 AVIStream *ast = st->priv_data;
824 AVInputFormat *sub_demuxer;
825 AVRational time_base;
826 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
828 0, NULL, NULL, NULL, NULL);
830 unsigned int desc_len = avio_rl32(pb);
832 if (desc_len > pb->buf_end - pb->buf_ptr)
835 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
836 avio_skip(pb, desc_len - ret);
838 av_dict_set(&st->metadata, "title", desc, 0);
840 avio_rl16(pb); /* flags? */
841 avio_rl32(pb); /* data size */
843 pd = (AVProbeData) { .buf = pb->buf_ptr,
844 .buf_size = pb->buf_end - pb->buf_ptr };
845 if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
848 if (!(ast->sub_ctx = avformat_alloc_context()))
851 ast->sub_ctx->pb = pb;
852 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
853 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
854 *st->codec = *ast->sub_ctx->streams[0]->codec;
855 ast->sub_ctx->streams[0]->codec->extradata = NULL;
856 time_base = ast->sub_ctx->streams[0]->time_base;
857 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
859 ast->sub_buffer = pkt->data;
860 memset(pkt, 0, sizeof(*pkt));
869 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
872 AVIStream *ast, *next_ast = next_st->priv_data;
873 int64_t ts, next_ts, ts_min = INT64_MAX;
874 AVStream *st, *sub_st = NULL;
877 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
880 for (i = 0; i < s->nb_streams; i++) {
883 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
884 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
885 if (ts <= next_ts && ts < ts_min) {
893 ast = sub_st->priv_data;
895 pkt->stream_index = sub_st->index;
897 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
898 ast->sub_pkt.data = NULL;
903 static int get_stream_idx(int *d)
905 if (d[0] >= '0' && d[0] <= '9' &&
906 d[1] >= '0' && d[1] <= '9') {
907 return (d[0] - '0') * 10 + (d[1] - '0');
909 return 100; // invalid stream ID
913 static int avi_sync(AVFormatContext *s, int exit_early)
915 AVIContext *avi = s->priv_data;
916 AVIOContext *pb = s->pb;
923 memset(d, -1, sizeof(d));
924 for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
927 for (j = 0; j < 7; j++)
931 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
933 n = get_stream_idx(d + 2);
934 av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
935 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
936 if (i + (uint64_t)size > avi->fsize || d[0] > 127)
940 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
942 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
943 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
949 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
954 n = get_stream_idx(d);
956 if (!((i - avi->last_pkt_pos) & 1) &&
957 get_stream_idx(d + 1) < s->nb_streams)
960 // detect ##ix chunk and skip
961 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
967 if (n < s->nb_streams) {
973 if (s->nb_streams >= 2) {
974 AVStream *st1 = s->streams[1];
975 AVIStream *ast1 = st1->priv_data;
976 // workaround for broken small-file-bug402.avi
977 if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
978 st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
979 st1->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
980 ast->prefix == 'd' * 256 + 'c' &&
981 (d[2] * 256 + d[3] == ast1->prefix ||
982 !ast1->prefix_count)) {
986 av_log(s, AV_LOG_WARNING,
987 "Invalid stream + prefix combination, assuming audio.\n");
991 if (!avi->dv_demux &&
992 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
993 // FIXME: needs a little reordering
994 (st->discard >= AVDISCARD_NONKEY &&
995 !(pkt->flags & AV_PKT_FLAG_KEY)) */
996 || st->discard >= AVDISCARD_ALL)) {
998 ast->frame_offset += get_duration(ast, size);
1000 avio_skip(pb, size);
1004 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1005 int k = avio_r8(pb);
1006 int last = (k + avio_r8(pb) - 1) & 0xFF;
1008 avio_rl16(pb); // flags
1010 // b + (g << 8) + (r << 16);
1011 for (; k <= last; k++)
1012 ast->pal[k] = avio_rb32(pb) >> 8;
1016 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1017 d[2] < 128 && d[3] < 128) ||
1018 d[2] * 256 + d[3] == ast->prefix /* ||
1019 (d[2] == 'd' && d[3] == 'c') ||
1020 (d[2] == 'w' && d[3] == 'b') */) {
1023 if (d[2] * 256 + d[3] == ast->prefix)
1024 ast->prefix_count++;
1026 ast->prefix = d[2] * 256 + d[3];
1027 ast->prefix_count = 0;
1030 avi->stream_index = n;
1031 ast->packet_size = size + 8;
1032 ast->remaining = size;
1034 if (size || !ast->sample_size) {
1035 uint64_t pos = avio_tell(pb) - 8;
1036 if (!st->index_entries || !st->nb_index_entries ||
1037 st->index_entries[st->nb_index_entries - 1].pos < pos) {
1038 av_add_index_entry(st, pos, ast->frame_offset, size,
1039 0, AVINDEX_KEYFRAME);
1050 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1052 AVIContext *avi = s->priv_data;
1053 AVIOContext *pb = s->pb;
1055 #if FF_API_DESTRUCT_PACKET
1059 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1060 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1065 if (avi->non_interleaved) {
1066 int best_stream_index = 0;
1067 AVStream *best_st = NULL;
1068 AVIStream *best_ast;
1069 int64_t best_ts = INT64_MAX;
1072 for (i = 0; i < s->nb_streams; i++) {
1073 AVStream *st = s->streams[i];
1074 AVIStream *ast = st->priv_data;
1075 int64_t ts = ast->frame_offset;
1078 if (!st->nb_index_entries)
1081 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1082 if (!ast->remaining && ts > last_ts)
1085 ts = av_rescale_q(ts, st->time_base,
1086 (AVRational) { FFMAX(1, ast->sample_size),
1089 av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
1090 st->time_base.num, st->time_base.den, ast->frame_offset);
1094 best_stream_index = i;
1100 best_ast = best_st->priv_data;
1101 best_ts = av_rescale_q(best_ts,
1102 (AVRational) { FFMAX(1, best_ast->sample_size),
1104 best_st->time_base);
1105 if (best_ast->remaining) {
1106 i = av_index_search_timestamp(best_st,
1109 AVSEEK_FLAG_BACKWARD);
1111 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1113 best_ast->frame_offset = best_st->index_entries[i].timestamp;
1117 int64_t pos = best_st->index_entries[i].pos;
1118 pos += best_ast->packet_size - best_ast->remaining;
1119 avio_seek(s->pb, pos + 8, SEEK_SET);
1121 assert(best_ast->remaining <= best_ast->packet_size);
1123 avi->stream_index = best_stream_index;
1124 if (!best_ast->remaining)
1125 best_ast->packet_size =
1126 best_ast->remaining = best_st->index_entries[i].size;
1131 if (avi->stream_index >= 0) {
1132 AVStream *st = s->streams[avi->stream_index];
1133 AVIStream *ast = st->priv_data;
1136 if (get_subtitle_pkt(s, st, pkt))
1139 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1140 if (ast->sample_size <= 1)
1142 else if (ast->sample_size < 32)
1143 // arbitrary multiplier to avoid tiny packets for raw PCM data
1144 size = 1024 * ast->sample_size;
1146 size = ast->sample_size;
1148 if (size > ast->remaining)
1149 size = ast->remaining;
1150 avi->last_pkt_pos = avio_tell(pb);
1151 err = av_get_packet(pb, pkt, size);
1155 if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
1157 pal = av_packet_new_side_data(pkt,
1158 AV_PKT_DATA_PALETTE,
1161 av_log(s, AV_LOG_ERROR,
1162 "Failed to allocate data for palette\n");
1164 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1169 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1170 AVBufferRef *avbuf = pkt->buf;
1171 #if FF_API_DESTRUCT_PACKET
1172 FF_DISABLE_DEPRECATION_WARNINGS
1173 dstr = pkt->destruct;
1174 FF_ENABLE_DEPRECATION_WARNINGS
1176 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1177 pkt->data, pkt->size);
1178 #if FF_API_DESTRUCT_PACKET
1179 FF_DISABLE_DEPRECATION_WARNINGS
1180 pkt->destruct = dstr;
1181 FF_ENABLE_DEPRECATION_WARNINGS
1184 pkt->flags |= AV_PKT_FLAG_KEY;
1186 av_free_packet(pkt);
1187 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1188 !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1189 ast->frame_offset++;
1190 avi->stream_index = -1;
1194 /* XXX: How to handle B-frames in AVI? */
1195 pkt->dts = ast->frame_offset;
1196 // pkt->dts += ast->start;
1197 if (ast->sample_size)
1198 pkt->dts /= ast->sample_size;
1200 "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
1201 "base:%d st:%d size:%d\n",
1210 pkt->stream_index = avi->stream_index;
1212 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1215 assert(st->index_entries);
1217 index = av_index_search_timestamp(st, ast->frame_offset, 0);
1218 e = &st->index_entries[index];
1220 if (index >= 0 && e->timestamp == ast->frame_offset)
1221 if (e->flags & AVINDEX_KEYFRAME)
1222 pkt->flags |= AV_PKT_FLAG_KEY;
1224 pkt->flags |= AV_PKT_FLAG_KEY;
1226 ast->frame_offset += get_duration(ast, pkt->size);
1228 ast->remaining -= err;
1229 if (!ast->remaining) {
1230 avi->stream_index = -1;
1231 ast->packet_size = 0;
1237 if ((err = avi_sync(s, 0)) < 0)
1242 /* XXX: We make the implicit supposition that the positions are sorted
1243 * for each stream. */
1244 static int avi_read_idx1(AVFormatContext *s, int size)
1246 AVIContext *avi = s->priv_data;
1247 AVIOContext *pb = s->pb;
1248 int nb_index_entries, i;
1251 unsigned int index, tag, flags, pos, len, first_packet = 1;
1252 unsigned last_pos = -1;
1253 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1255 nb_index_entries = size / 16;
1256 if (nb_index_entries <= 0)
1257 return AVERROR_INVALIDDATA;
1259 idx1_pos = avio_tell(pb);
1260 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1261 if (avi_sync(s, 1) == 0)
1262 first_packet_pos = avio_tell(pb) - 8;
1263 avi->stream_index = -1;
1264 avio_seek(pb, idx1_pos, SEEK_SET);
1266 /* Read the entries and sort them in each stream component. */
1267 for (i = 0; i < nb_index_entries; i++) {
1268 tag = avio_rl32(pb);
1269 flags = avio_rl32(pb);
1270 pos = avio_rl32(pb);
1271 len = avio_rl32(pb);
1272 av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1273 i, tag, flags, pos, len);
1275 index = ((tag & 0xff) - '0') * 10;
1276 index += (tag >> 8 & 0xff) - '0';
1277 if (index >= s->nb_streams)
1279 st = s->streams[index];
1280 ast = st->priv_data;
1282 if (first_packet && first_packet_pos && len) {
1283 data_offset = first_packet_pos - pos;
1288 av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1290 if (pb->eof_reached)
1291 return AVERROR_INVALIDDATA;
1293 if (last_pos == pos)
1294 avi->non_interleaved = 1;
1295 else if (len || !ast->sample_size)
1296 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1297 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1298 ast->cum_len += get_duration(ast, len);
1304 static int guess_ni_flag(AVFormatContext *s)
1307 int64_t last_start = 0;
1308 int64_t first_end = INT64_MAX;
1309 int64_t oldpos = avio_tell(s->pb);
1311 for (i = 0; i < s->nb_streams; i++) {
1312 AVStream *st = s->streams[i];
1313 int n = st->nb_index_entries;
1320 int64_t pos = st->index_entries[0].pos;
1321 avio_seek(s->pb, pos + 4, SEEK_SET);
1322 size = avio_rl32(s->pb);
1323 if (pos + size > st->index_entries[1].pos)
1324 last_start = INT64_MAX;
1327 if (st->index_entries[0].pos > last_start)
1328 last_start = st->index_entries[0].pos;
1329 if (st->index_entries[n - 1].pos < first_end)
1330 first_end = st->index_entries[n - 1].pos;
1332 avio_seek(s->pb, oldpos, SEEK_SET);
1333 return last_start > first_end;
1336 static int avi_load_index(AVFormatContext *s)
1338 AVIContext *avi = s->priv_data;
1339 AVIOContext *pb = s->pb;
1341 int64_t pos = avio_tell(pb);
1344 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1345 goto the_end; // maybe truncated file
1346 av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1348 if (pb->eof_reached)
1350 tag = avio_rl32(pb);
1351 size = avio_rl32(pb);
1352 av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1359 if (tag == MKTAG('i', 'd', 'x', '1') &&
1360 avi_read_idx1(s, size) >= 0) {
1366 if (avio_skip(pb, size) < 0)
1367 break; // something is wrong here
1371 avio_seek(pb, pos, SEEK_SET);
1375 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1377 AVIStream *ast2 = st2->priv_data;
1378 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1379 av_free_packet(&ast2->sub_pkt);
1380 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1381 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1382 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1385 static int avi_read_seek(AVFormatContext *s, int stream_index,
1386 int64_t timestamp, int flags)
1388 AVIContext *avi = s->priv_data;
1394 if (!avi->index_loaded) {
1395 /* we only load the index on demand */
1397 avi->index_loaded = 1;
1399 assert(stream_index >= 0);
1401 st = s->streams[stream_index];
1402 ast = st->priv_data;
1403 index = av_index_search_timestamp(st,
1404 timestamp * FFMAX(ast->sample_size, 1),
1407 return AVERROR_INVALIDDATA;
1409 /* find the position */
1410 pos = st->index_entries[index].pos;
1411 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1413 av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
1414 timestamp, index, st->index_entries[index].timestamp);
1416 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1417 /* One and only one real stream for DV in AVI, and it has video */
1418 /* offsets. Calling with other stream indexes should have failed */
1419 /* the av_index_search_timestamp call above. */
1420 assert(stream_index == 0);
1422 /* Feed the DV video stream version of the timestamp to the */
1423 /* DV demux so it can synthesize correct timestamps. */
1424 ff_dv_offset_reset(avi->dv_demux, timestamp);
1426 avio_seek(s->pb, pos, SEEK_SET);
1427 avi->stream_index = -1;
1431 for (i = 0; i < s->nb_streams; i++) {
1432 AVStream *st2 = s->streams[i];
1433 AVIStream *ast2 = st2->priv_data;
1436 ast2->remaining = 0;
1438 if (ast2->sub_ctx) {
1439 seek_subtitle(st, st2, timestamp);
1443 if (st2->nb_index_entries <= 0)
1446 // assert(st2->codec->block_align);
1447 assert((int64_t)st2->time_base.num * ast2->rate ==
1448 (int64_t)st2->time_base.den * ast2->scale);
1449 index = av_index_search_timestamp(st2,
1450 av_rescale_q(timestamp,
1453 FFMAX(ast2->sample_size, 1),
1454 flags | AVSEEK_FLAG_BACKWARD);
1458 if (!avi->non_interleaved) {
1459 while (index > 0 && st2->index_entries[index].pos > pos)
1461 while (index + 1 < st2->nb_index_entries &&
1462 st2->index_entries[index].pos < pos)
1466 av_dlog(s, "%"PRId64" %d %"PRId64"\n",
1467 timestamp, index, st2->index_entries[index].timestamp);
1468 /* extract the current frame number */
1469 ast2->frame_offset = st2->index_entries[index].timestamp;
1473 avio_seek(s->pb, pos, SEEK_SET);
1474 avi->stream_index = -1;
1478 static int avi_read_close(AVFormatContext *s)
1481 AVIContext *avi = s->priv_data;
1483 for (i = 0; i < s->nb_streams; i++) {
1484 AVStream *st = s->streams[i];
1485 AVIStream *ast = st->priv_data;
1488 av_freep(&ast->sub_ctx->pb);
1489 avformat_close_input(&ast->sub_ctx);
1491 av_free(ast->sub_buffer);
1492 av_free_packet(&ast->sub_pkt);
1496 av_free(avi->dv_demux);
1501 static int avi_probe(AVProbeData *p)
1505 /* check file header */
1506 for (i = 0; avi_headers[i][0]; i++)
1507 if (!memcmp(p->buf, avi_headers[i], 4) &&
1508 !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
1509 return AVPROBE_SCORE_MAX;
1514 AVInputFormat ff_avi_demuxer = {
1516 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1517 .priv_data_size = sizeof(AVIContext),
1518 .read_probe = avi_probe,
1519 .read_header = avi_read_header,
1520 .read_packet = avi_read_packet,
1521 .read_close = avi_read_close,
1522 .read_seek = avi_read_seek,