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) */
48 int sample_size; /* size of one sample (or packet)
49 * (in the rate/scale sense) in bytes */
51 int64_t cum_len; /* temporary storage (used during seek) */
52 int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
56 int dshow_block_align; /* block align variable used to emulate bugs in
57 * the MS dshow demuxer */
59 AVFormatContext *sub_ctx;
74 DVDemuxContext *dv_demux;
76 #define MAX_ODML_DEPTH 1000
79 static const char avi_headers[][8] = {
80 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
81 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
82 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
83 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
84 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
88 static const AVMetadataConv avi_metadata_conv[] = {
93 static int avi_load_index(AVFormatContext *s);
94 static int guess_ni_flag(AVFormatContext *s);
96 #define print_tag(str, tag, size) \
97 av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
100 (tag >> 16) & 0xff, \
101 (tag >> 24) & 0xff, \
104 static inline int get_duration(AVIStream *ast, int len)
106 if (ast->sample_size)
108 else if (ast->dshow_block_align)
109 return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
114 static int get_riff(AVFormatContext *s, AVIOContext *pb)
116 AVIContext *avi = s->priv_data;
120 /* check RIFF header */
121 avio_read(pb, header, 4);
122 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
123 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
124 avio_read(pb, header + 4, 4);
126 for (i = 0; avi_headers[i][0]; i++)
127 if (!memcmp(header, avi_headers[i], 8))
129 if (!avi_headers[i][0])
130 return AVERROR_INVALIDDATA;
132 if (header[7] == 0x19)
133 av_log(s, AV_LOG_INFO,
134 "This file has been generated by a totally broken muxer.\n");
139 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
141 AVIContext *avi = s->priv_data;
142 AVIOContext *pb = s->pb;
143 int longs_pre_entry = avio_rl16(pb);
144 int index_sub_type = avio_r8(pb);
145 int index_type = avio_r8(pb);
146 int entries_in_use = avio_rl32(pb);
147 int chunk_id = avio_rl32(pb);
148 int64_t base = avio_rl64(pb);
149 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
150 ((chunk_id >> 8 & 0xFF) - '0');
154 int64_t last_pos = -1;
155 int64_t filesize = avi->fsize;
158 "longs_pre_entry:%d index_type:%d entries_in_use:%d "
159 "chunk_id:%X base:%16"PRIX64"\n",
166 if (stream_id >= s->nb_streams || stream_id < 0)
167 return AVERROR_INVALIDDATA;
168 st = s->streams[stream_id];
172 return AVERROR_INVALIDDATA;
176 if (index_type && longs_pre_entry != 2)
177 return AVERROR_INVALIDDATA;
179 return AVERROR_INVALIDDATA;
181 if (filesize > 0 && base >= filesize) {
182 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
183 if (base >> 32 == (base & 0xFFFFFFFF) &&
184 (base & 0xFFFFFFFF) < filesize &&
185 filesize <= 0xFFFFFFFF)
188 return AVERROR_INVALIDDATA;
191 for (i = 0; i < entries_in_use; i++) {
193 int64_t pos = avio_rl32(pb) + base - 8;
194 int len = avio_rl32(pb);
198 av_dlog(s, "pos:%"PRId64", len:%X\n", pos, len);
201 return AVERROR_INVALIDDATA;
203 if (last_pos == pos || pos == base - 8)
204 avi->non_interleaved = 1;
205 if (last_pos != pos && (len || !ast->sample_size))
206 av_add_index_entry(st, pos, ast->cum_len, len, 0,
207 key ? AVINDEX_KEYFRAME : 0);
209 ast->cum_len += get_duration(ast, len);
214 offset = avio_rl64(pb);
215 avio_rl32(pb); /* size */
216 duration = avio_rl32(pb);
219 return AVERROR_INVALIDDATA;
223 if (avi->odml_depth > MAX_ODML_DEPTH) {
224 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
225 return AVERROR_INVALIDDATA;
228 avio_seek(pb, offset + 8, SEEK_SET);
230 read_braindead_odml_indx(s, frame_num);
232 frame_num += duration;
234 avio_seek(pb, pos, SEEK_SET);
237 avi->index_loaded = 1;
241 static void clean_index(AVFormatContext *s)
246 for (i = 0; i < s->nb_streams; i++) {
247 AVStream *st = s->streams[i];
248 AVIStream *ast = st->priv_data;
249 int n = st->nb_index_entries;
250 int max = ast->sample_size;
251 int64_t pos, size, ts;
253 if (n != 1 || ast->sample_size == 0)
259 pos = st->index_entries[0].pos;
260 size = st->index_entries[0].size;
261 ts = st->index_entries[0].timestamp;
263 for (j = 0; j < size; j += max)
264 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
269 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
272 AVIOContext *pb = s->pb;
278 if (size == UINT_MAX)
279 return AVERROR(EINVAL);
280 value = av_malloc(size + 1);
282 return AVERROR(ENOMEM);
283 avio_read(pb, value, size);
288 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
289 AV_DICT_DONT_STRDUP_VAL);
292 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
293 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
295 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
297 char month[4], time[9], buffer[64];
299 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
300 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
301 month, &day, time, &year) == 4) {
302 for (i = 0; i < 12; i++)
303 if (!av_strcasecmp(month, months[i])) {
304 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
305 year, i + 1, day, time);
306 av_dict_set(metadata, "creation_time", buffer, 0);
308 } else if (date[4] == '/' && date[7] == '/') {
309 date[4] = date[7] = '-';
310 av_dict_set(metadata, "creation_time", date, 0);
314 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
316 while (avio_tell(s->pb) < end) {
317 uint32_t tag = avio_rl32(s->pb);
318 uint32_t size = avio_rl32(s->pb);
320 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
322 uint64_t tag_end = avio_tell(s->pb) + size;
323 while (avio_tell(s->pb) < tag_end) {
324 uint16_t tag = avio_rl16(s->pb);
325 uint16_t size = avio_rl16(s->pb);
326 const char *name = NULL;
327 char buffer[64] = { 0 };
328 size -= avio_read(s->pb, buffer,
329 FFMIN(size, sizeof(buffer) - 1));
338 name = "creation_time";
339 if (buffer[4] == ':' && buffer[7] == ':')
340 buffer[4] = buffer[7] = '-';
344 av_dict_set(&s->metadata, name, buffer, 0);
345 avio_skip(s->pb, size);
350 avio_skip(s->pb, size);
356 static int avi_read_header(AVFormatContext *s)
358 AVIContext *avi = s->priv_data;
359 AVIOContext *pb = s->pb;
360 unsigned int tag, tag1, handler;
361 int codec_type, stream_index, frame_period;
365 AVIStream *ast = NULL;
366 int avih_width = 0, avih_height = 0;
367 int amv_file_format = 0;
368 uint64_t list_end = 0;
371 avi->stream_index = -1;
373 ret = get_riff(s, pb);
377 avi->fsize = avio_size(pb);
378 if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
379 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
389 size = avio_rl32(pb);
391 print_tag("tag", tag, size);
394 case MKTAG('L', 'I', 'S', 'T'):
395 list_end = avio_tell(pb) + size;
396 /* Ignored, except at start of video packets. */
397 tag1 = avio_rl32(pb);
399 print_tag("list", tag1, 0);
401 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
402 avi->movi_list = avio_tell(pb) - 4;
404 avi->movi_end = avi->movi_list + size + (size & 1);
406 avi->movi_end = avi->fsize;
407 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
409 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
410 ff_read_riff_info(s, size - 4);
411 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
412 avi_read_nikon(s, list_end);
415 case MKTAG('I', 'D', 'I', 'T'):
417 unsigned char date[64] = { 0 };
419 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
421 avi_metadata_creation_time(&s->metadata, date);
424 case MKTAG('d', 'm', 'l', 'h'):
426 avio_skip(pb, size + (size & 1));
428 case MKTAG('a', 'm', 'v', 'h'):
430 case MKTAG('a', 'v', 'i', 'h'):
432 /* using frame_period is bad idea */
433 frame_period = avio_rl32(pb);
436 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
438 avio_skip(pb, 2 * 4);
441 avih_width = avio_rl32(pb);
442 avih_height = avio_rl32(pb);
444 avio_skip(pb, size - 10 * 4);
446 case MKTAG('s', 't', 'r', 'h'):
449 tag1 = avio_rl32(pb);
450 handler = avio_rl32(pb); /* codec tag */
452 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
453 avio_skip(pb, size - 8);
457 st = avformat_new_stream(s, NULL);
461 st->id = stream_index;
462 ast = av_mallocz(sizeof(AVIStream));
468 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
469 : MKTAG('v', 'i', 'd', 's');
471 print_tag("strh", tag1, -1);
473 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
474 tag1 == MKTAG('i', 'v', 'a', 's')) {
477 /* After some consideration -- I don't think we
478 * have to support anything but DV in type1 AVIs. */
479 if (s->nb_streams != 1)
482 if (handler != MKTAG('d', 'v', 's', 'd') &&
483 handler != MKTAG('d', 'v', 'h', 'd') &&
484 handler != MKTAG('d', 'v', 's', 'l'))
487 ast = s->streams[0]->priv_data;
488 av_freep(&s->streams[0]->codec->extradata);
489 av_freep(&s->streams[0]->codec);
490 av_freep(&s->streams[0]->info);
491 av_freep(&s->streams[0]);
493 if (CONFIG_DV_DEMUXER) {
494 avi->dv_demux = avpriv_dv_init_demux(s);
499 s->streams[0]->priv_data = ast;
500 avio_skip(pb, 3 * 4);
501 ast->scale = avio_rl32(pb);
502 ast->rate = avio_rl32(pb);
503 avio_skip(pb, 4); /* start time */
505 dv_dur = avio_rl32(pb);
506 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
507 dv_dur *= AV_TIME_BASE;
508 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
510 /* else, leave duration alone; timing estimation in utils.c
511 * will make a guess based on bitrate. */
513 stream_index = s->nb_streams - 1;
514 avio_skip(pb, size - 9 * 4);
518 assert(stream_index < s->nb_streams);
519 ast->handler = handler;
521 avio_rl32(pb); /* flags */
522 avio_rl16(pb); /* priority */
523 avio_rl16(pb); /* language */
524 avio_rl32(pb); /* initial frame */
525 ast->scale = avio_rl32(pb);
526 ast->rate = avio_rl32(pb);
527 if (!(ast->scale && ast->rate)) {
528 av_log(s, AV_LOG_WARNING,
529 "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
530 "(This file has been generated by broken software.)\n",
535 ast->scale = frame_period;
541 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
543 ast->cum_len = avio_rl32(pb); /* start */
544 st->nb_frames = avio_rl32(pb);
547 avio_rl32(pb); /* buffer size */
548 avio_rl32(pb); /* quality */
549 ast->sample_size = avio_rl32(pb); /* sample ssize */
550 ast->cum_len *= FFMAX(1, ast->sample_size);
551 av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
552 ast->rate, ast->scale, ast->sample_size);
555 case MKTAG('v', 'i', 'd', 's'):
556 codec_type = AVMEDIA_TYPE_VIDEO;
558 ast->sample_size = 0;
560 case MKTAG('a', 'u', 'd', 's'):
561 codec_type = AVMEDIA_TYPE_AUDIO;
563 case MKTAG('t', 'x', 't', 's'):
564 codec_type = AVMEDIA_TYPE_SUBTITLE;
566 case MKTAG('d', 'a', 't', 's'):
567 codec_type = AVMEDIA_TYPE_DATA;
570 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
573 if (ast->sample_size == 0)
574 st->duration = st->nb_frames;
575 ast->frame_offset = ast->cum_len;
576 avio_skip(pb, size - 12 * 4);
578 case MKTAG('s', 't', 'r', 'f'):
580 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
583 uint64_t cur_pos = avio_tell(pb);
584 if (cur_pos < list_end)
585 size = FFMIN(size, list_end - cur_pos);
586 st = s->streams[stream_index];
587 switch (codec_type) {
588 case AVMEDIA_TYPE_VIDEO:
589 if (amv_file_format) {
590 st->codec->width = avih_width;
591 st->codec->height = avih_height;
592 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
593 st->codec->codec_id = AV_CODEC_ID_AMV;
597 tag1 = ff_get_bmp_header(pb, st);
599 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
600 tag1 == MKTAG('D', 'X', 'S', 'A')) {
601 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
602 st->codec->codec_tag = tag1;
603 st->codec->codec_id = AV_CODEC_ID_XSUB;
607 if (size > 10 * 4 && size < (1 << 30)) {
608 st->codec->extradata_size = size - 10 * 4;
609 st->codec->extradata = av_malloc(st->codec->extradata_size +
610 FF_INPUT_BUFFER_PADDING_SIZE);
611 if (!st->codec->extradata) {
612 st->codec->extradata_size = 0;
613 return AVERROR(ENOMEM);
616 st->codec->extradata,
617 st->codec->extradata_size);
620 // FIXME: check if the encoder really did this correctly
621 if (st->codec->extradata_size & 1)
624 /* Extract palette from extradata if bpp <= 8.
625 * This code assumes that extradata contains only palette.
626 * This is true for all paletted codecs implemented in
628 if (st->codec->extradata_size &&
629 (st->codec->bits_per_coded_sample <= 8)) {
630 int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
631 const uint8_t *pal_src;
633 pal_size = FFMIN(pal_size, st->codec->extradata_size);
634 pal_src = st->codec->extradata +
635 st->codec->extradata_size - pal_size;
637 for (i = 0; i < pal_size / 4; i++)
638 ast->pal[i] = av_bswap32(((uint32_t *)pal_src)[i]);
640 memcpy(ast->pal, pal_src, pal_size);
645 print_tag("video", tag1, 0);
647 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
648 st->codec->codec_tag = tag1;
649 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
651 /* This is needed to get the pict type which is necessary
652 * for generating correct pts. */
653 st->need_parsing = AVSTREAM_PARSE_HEADERS;
655 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
656 ast->handler == MKTAG('X', 'V', 'I', 'D'))
657 st->codec->codec_tag = MKTAG('X', 'V', 'I', 'D');
659 // Support "Resolution 1:1" for Avid AVI Codec
660 if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
661 st->codec->extradata_size >= 31 &&
662 !memcmp(&st->codec->extradata[28], "1:1", 3))
663 st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
665 if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
666 st->codec->extradata_size < 1U << 30) {
667 st->codec->extradata_size += 9;
668 if ((ret = av_reallocp(&st->codec->extradata,
669 st->codec->extradata_size +
670 FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
671 st->codec->extradata_size = 0;
674 memcpy(st->codec->extradata + st->codec->extradata_size - 9,
677 st->codec->height = FFABS(st->codec->height);
679 // avio_skip(pb, size - 5 * 4);
681 case AVMEDIA_TYPE_AUDIO:
682 ret = ff_get_wav_header(pb, st->codec, size);
685 ast->dshow_block_align = st->codec->block_align;
686 if (ast->sample_size && st->codec->block_align &&
687 ast->sample_size != st->codec->block_align) {
690 "sample size (%d) != block align (%d)\n",
692 st->codec->block_align);
693 ast->sample_size = st->codec->block_align;
696 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
699 /* Force parsing as several audio frames can be in
700 * one packet and timestamps refer to packet start. */
701 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
702 /* ADTS header is in extradata, AAC without header must be
703 * stored as exact frames. Parser not needed and it will
705 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
706 st->codec->extradata_size)
707 st->need_parsing = AVSTREAM_PARSE_NONE;
708 /* AVI files with Xan DPCM audio (wrongly) declare PCM
709 * audio in the header but have Axan as stream_code_tag. */
710 if (ast->handler == AV_RL32("Axan")) {
711 st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
712 st->codec->codec_tag = 0;
714 if (amv_file_format) {
715 st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
716 ast->dshow_block_align = 0;
719 case AVMEDIA_TYPE_SUBTITLE:
720 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
721 st->codec->codec_id = AV_CODEC_ID_PROBE;
724 st->codec->codec_type = AVMEDIA_TYPE_DATA;
725 st->codec->codec_id = AV_CODEC_ID_NONE;
726 st->codec->codec_tag = 0;
732 case MKTAG('i', 'n', 'd', 'x'):
734 if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
735 read_braindead_odml_indx(s, 0) < 0 &&
736 (s->error_recognition & AV_EF_EXPLODE))
738 avio_seek(pb, i + size, SEEK_SET);
740 case MKTAG('v', 'p', 'r', 'p'):
741 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
742 AVRational active, active_aspect;
744 st = s->streams[stream_index];
751 active_aspect.den = avio_rl16(pb);
752 active_aspect.num = avio_rl16(pb);
753 active.num = avio_rl32(pb);
754 active.den = avio_rl32(pb);
755 avio_rl32(pb); // nbFieldsPerFrame
757 if (active_aspect.num && active_aspect.den &&
758 active.num && active.den) {
759 st->sample_aspect_ratio = av_div_q(active_aspect, active);
760 av_dlog(s, "vprp %d/%d %d/%d\n",
761 active_aspect.num, active_aspect.den,
762 active.num, active.den);
768 case MKTAG('s', 't', 'r', 'n'):
770 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
776 if (size > 1000000) {
777 av_log(s, AV_LOG_ERROR,
778 "Something went wrong during header parsing, "
779 "I will ignore it and try to continue anyway.\n");
780 if (s->error_recognition & AV_EF_EXPLODE)
782 avi->movi_list = avio_tell(pb) - 4;
783 avi->movi_end = avi->fsize;
794 /* check stream number */
795 if (stream_index != s->nb_streams - 1) {
798 return AVERROR_INVALIDDATA;
801 if (!avi->index_loaded && pb->seekable)
803 avi->index_loaded = 1;
805 if ((ret = guess_ni_flag(s)) < 0)
808 avi->non_interleaved |= ret;
809 for (i = 0; i < s->nb_streams; i++) {
810 AVStream *st = s->streams[i];
811 if (st->nb_index_entries)
814 if (i == s->nb_streams && avi->non_interleaved) {
815 av_log(s, AV_LOG_WARNING,
816 "Non-interleaved AVI without index, switching to interleaved\n");
817 avi->non_interleaved = 0;
820 if (avi->non_interleaved) {
821 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
825 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
826 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
831 static int read_gab2_sub(AVStream *st, AVPacket *pkt)
833 if (pkt->size >= 7 &&
834 !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
836 int score = AVPROBE_SCORE_EXTENSION, ret;
837 AVIStream *ast = st->priv_data;
838 AVInputFormat *sub_demuxer;
839 AVRational time_base;
840 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
842 0, NULL, NULL, NULL, NULL);
844 unsigned int desc_len = avio_rl32(pb);
846 if (desc_len > pb->buf_end - pb->buf_ptr)
849 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
850 avio_skip(pb, desc_len - ret);
852 av_dict_set(&st->metadata, "title", desc, 0);
854 avio_rl16(pb); /* flags? */
855 avio_rl32(pb); /* data size */
857 pd = (AVProbeData) { .buf = pb->buf_ptr,
858 .buf_size = pb->buf_end - pb->buf_ptr };
859 if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
862 if (!(ast->sub_ctx = avformat_alloc_context()))
865 ast->sub_ctx->pb = pb;
866 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
867 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
868 *st->codec = *ast->sub_ctx->streams[0]->codec;
869 ast->sub_ctx->streams[0]->codec->extradata = NULL;
870 time_base = ast->sub_ctx->streams[0]->time_base;
871 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
873 ast->sub_buffer = pkt->data;
874 memset(pkt, 0, sizeof(*pkt));
883 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
886 AVIStream *ast, *next_ast = next_st->priv_data;
887 int64_t ts, next_ts, ts_min = INT64_MAX;
888 AVStream *st, *sub_st = NULL;
891 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
894 for (i = 0; i < s->nb_streams; i++) {
897 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
898 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
899 if (ts <= next_ts && ts < ts_min) {
907 ast = sub_st->priv_data;
909 pkt->stream_index = sub_st->index;
911 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
912 ast->sub_pkt.data = NULL;
917 static int get_stream_idx(int *d)
919 if (d[0] >= '0' && d[0] <= '9' &&
920 d[1] >= '0' && d[1] <= '9') {
921 return (d[0] - '0') * 10 + (d[1] - '0');
923 return 100; // invalid stream ID
927 static int avi_sync(AVFormatContext *s, int exit_early)
929 AVIContext *avi = s->priv_data;
930 AVIOContext *pb = s->pb;
937 memset(d, -1, sizeof(d));
938 for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
941 for (j = 0; j < 7; j++)
945 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
947 n = get_stream_idx(d + 2);
948 av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
949 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
950 if (i + (uint64_t)size > avi->fsize || d[0] > 127)
954 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
956 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
957 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
963 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
968 n = avi->dv_demux ? 0 : get_stream_idx(d);
970 if (!((i - avi->last_pkt_pos) & 1) &&
971 get_stream_idx(d + 1) < s->nb_streams)
974 // detect ##ix chunk and skip
975 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
981 if (n < s->nb_streams) {
987 if (s->nb_streams >= 2) {
988 AVStream *st1 = s->streams[1];
989 AVIStream *ast1 = st1->priv_data;
990 // workaround for broken small-file-bug402.avi
991 if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
992 st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
993 st1->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
994 ast->prefix == 'd' * 256 + 'c' &&
995 (d[2] * 256 + d[3] == ast1->prefix ||
996 !ast1->prefix_count)) {
1000 av_log(s, AV_LOG_WARNING,
1001 "Invalid stream + prefix combination, assuming audio.\n");
1005 if (!avi->dv_demux &&
1006 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
1007 // FIXME: needs a little reordering
1008 (st->discard >= AVDISCARD_NONKEY &&
1009 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1010 || st->discard >= AVDISCARD_ALL)) {
1012 ast->frame_offset += get_duration(ast, size);
1014 avio_skip(pb, size);
1018 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1019 int k = avio_r8(pb);
1020 int last = (k + avio_r8(pb) - 1) & 0xFF;
1022 avio_rl16(pb); // flags
1024 // b + (g << 8) + (r << 16);
1025 for (; k <= last; k++)
1026 ast->pal[k] = avio_rb32(pb) >> 8;
1030 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1031 d[2] < 128 && d[3] < 128) ||
1032 d[2] * 256 + d[3] == ast->prefix /* ||
1033 (d[2] == 'd' && d[3] == 'c') ||
1034 (d[2] == 'w' && d[3] == 'b') */) {
1037 if (d[2] * 256 + d[3] == ast->prefix)
1038 ast->prefix_count++;
1040 ast->prefix = d[2] * 256 + d[3];
1041 ast->prefix_count = 0;
1044 avi->stream_index = n;
1045 ast->packet_size = size + 8;
1046 ast->remaining = size;
1048 if (size || !ast->sample_size) {
1049 uint64_t pos = avio_tell(pb) - 8;
1050 if (!st->index_entries || !st->nb_index_entries ||
1051 st->index_entries[st->nb_index_entries - 1].pos < pos) {
1052 av_add_index_entry(st, pos, ast->frame_offset, size,
1053 0, AVINDEX_KEYFRAME);
1064 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1066 AVIContext *avi = s->priv_data;
1067 AVIOContext *pb = s->pb;
1069 #if FF_API_DESTRUCT_PACKET
1073 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1074 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1081 if (avi->non_interleaved) {
1082 int best_stream_index = 0;
1083 AVStream *best_st = NULL;
1084 AVIStream *best_ast;
1085 int64_t best_ts = INT64_MAX;
1088 for (i = 0; i < s->nb_streams; i++) {
1089 AVStream *st = s->streams[i];
1090 AVIStream *ast = st->priv_data;
1091 int64_t ts = ast->frame_offset;
1094 if (!st->nb_index_entries)
1097 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1098 if (!ast->remaining && ts > last_ts)
1101 ts = av_rescale_q(ts, st->time_base,
1102 (AVRational) { FFMAX(1, ast->sample_size),
1105 av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
1106 st->time_base.num, st->time_base.den, ast->frame_offset);
1110 best_stream_index = i;
1116 best_ast = best_st->priv_data;
1117 best_ts = av_rescale_q(best_ts,
1118 (AVRational) { FFMAX(1, best_ast->sample_size),
1120 best_st->time_base);
1121 if (best_ast->remaining) {
1122 i = av_index_search_timestamp(best_st,
1125 AVSEEK_FLAG_BACKWARD);
1127 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1129 best_ast->frame_offset = best_st->index_entries[i].timestamp;
1133 int64_t pos = best_st->index_entries[i].pos;
1134 pos += best_ast->packet_size - best_ast->remaining;
1135 avio_seek(s->pb, pos + 8, SEEK_SET);
1137 assert(best_ast->remaining <= best_ast->packet_size);
1139 avi->stream_index = best_stream_index;
1140 if (!best_ast->remaining)
1141 best_ast->packet_size =
1142 best_ast->remaining = best_st->index_entries[i].size;
1147 if (avi->stream_index >= 0) {
1148 AVStream *st = s->streams[avi->stream_index];
1149 AVIStream *ast = st->priv_data;
1152 if (get_subtitle_pkt(s, st, pkt))
1155 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1156 if (ast->sample_size <= 1)
1158 else if (ast->sample_size < 32)
1159 // arbitrary multiplier to avoid tiny packets for raw PCM data
1160 size = 1024 * ast->sample_size;
1162 size = ast->sample_size;
1164 if (size > ast->remaining)
1165 size = ast->remaining;
1166 avi->last_pkt_pos = avio_tell(pb);
1167 err = av_get_packet(pb, pkt, size);
1171 if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
1173 pal = av_packet_new_side_data(pkt,
1174 AV_PKT_DATA_PALETTE,
1177 av_log(s, AV_LOG_ERROR,
1178 "Failed to allocate data for palette\n");
1180 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1185 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1186 AVBufferRef *avbuf = pkt->buf;
1187 #if FF_API_DESTRUCT_PACKET
1188 FF_DISABLE_DEPRECATION_WARNINGS
1189 dstr = pkt->destruct;
1190 FF_ENABLE_DEPRECATION_WARNINGS
1192 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1193 pkt->data, pkt->size);
1194 #if FF_API_DESTRUCT_PACKET
1195 FF_DISABLE_DEPRECATION_WARNINGS
1196 pkt->destruct = dstr;
1197 FF_ENABLE_DEPRECATION_WARNINGS
1200 pkt->flags |= AV_PKT_FLAG_KEY;
1202 av_free_packet(pkt);
1203 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1204 !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1205 ast->frame_offset++;
1206 avi->stream_index = -1;
1210 /* XXX: How to handle B-frames in AVI? */
1211 pkt->dts = ast->frame_offset;
1212 // pkt->dts += ast->start;
1213 if (ast->sample_size)
1214 pkt->dts /= ast->sample_size;
1216 "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
1217 "base:%d st:%d size:%d\n",
1226 pkt->stream_index = avi->stream_index;
1228 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1231 assert(st->index_entries);
1233 index = av_index_search_timestamp(st, ast->frame_offset, 0);
1234 e = &st->index_entries[index];
1236 if (index >= 0 && e->timestamp == ast->frame_offset)
1237 if (e->flags & AVINDEX_KEYFRAME)
1238 pkt->flags |= AV_PKT_FLAG_KEY;
1240 pkt->flags |= AV_PKT_FLAG_KEY;
1242 ast->frame_offset += get_duration(ast, pkt->size);
1244 ast->remaining -= err;
1245 if (!ast->remaining) {
1246 avi->stream_index = -1;
1247 ast->packet_size = 0;
1253 if ((err = avi_sync(s, 0)) < 0)
1258 /* XXX: We make the implicit supposition that the positions are sorted
1259 * for each stream. */
1260 static int avi_read_idx1(AVFormatContext *s, int size)
1262 AVIContext *avi = s->priv_data;
1263 AVIOContext *pb = s->pb;
1264 int nb_index_entries, i;
1267 unsigned int index, tag, flags, pos, len, first_packet = 1;
1268 unsigned last_pos = -1;
1269 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1271 nb_index_entries = size / 16;
1272 if (nb_index_entries <= 0)
1273 return AVERROR_INVALIDDATA;
1275 idx1_pos = avio_tell(pb);
1276 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1277 if (avi_sync(s, 1) == 0)
1278 first_packet_pos = avio_tell(pb) - 8;
1279 avi->stream_index = -1;
1280 avio_seek(pb, idx1_pos, SEEK_SET);
1282 /* Read the entries and sort them in each stream component. */
1283 for (i = 0; i < nb_index_entries; i++) {
1284 tag = avio_rl32(pb);
1285 flags = avio_rl32(pb);
1286 pos = avio_rl32(pb);
1287 len = avio_rl32(pb);
1288 av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1289 i, tag, flags, pos, len);
1291 index = ((tag & 0xff) - '0') * 10;
1292 index += (tag >> 8 & 0xff) - '0';
1293 if (index >= s->nb_streams)
1295 st = s->streams[index];
1296 ast = st->priv_data;
1298 if (first_packet && first_packet_pos && len) {
1299 data_offset = first_packet_pos - pos;
1304 av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1306 if (pb->eof_reached)
1307 return AVERROR_INVALIDDATA;
1309 if (last_pos == pos)
1310 avi->non_interleaved = 1;
1311 else if (len || !ast->sample_size)
1312 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1313 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1314 ast->cum_len += get_duration(ast, len);
1320 /* Scan the index and consider any file with streams more than
1321 * 2 seconds or 64MB apart non-interleaved. */
1322 static int check_stream_max_drift(AVFormatContext *s)
1324 int64_t min_pos, pos;
1326 int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
1328 return AVERROR(ENOMEM);
1330 for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
1331 int64_t max_dts = INT64_MIN / 2;
1332 int64_t min_dts = INT64_MAX / 2;
1333 int64_t max_buffer = 0;
1335 min_pos = INT64_MAX;
1337 for (i = 0; i < s->nb_streams; i++) {
1338 AVStream *st = s->streams[i];
1339 AVIStream *ast = st->priv_data;
1340 int n = st->nb_index_entries;
1341 while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
1345 dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
1346 FFMAX(ast->sample_size, 1),
1347 st->time_base, AV_TIME_BASE_Q);
1348 min_dts = FFMIN(min_dts, dts);
1349 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
1352 for (i = 0; i < s->nb_streams; i++) {
1353 AVStream *st = s->streams[i];
1354 AVIStream *ast = st->priv_data;
1356 if (idx[i] && min_dts != INT64_MAX / 2) {
1358 dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
1359 FFMAX(ast->sample_size, 1),
1360 st->time_base, AV_TIME_BASE_Q);
1361 max_dts = FFMAX(max_dts, dts);
1362 max_buffer = FFMAX(max_buffer,
1363 av_rescale(dts - min_dts,
1364 st->codec->bit_rate,
1368 if (max_dts - min_dts > 2 * AV_TIME_BASE ||
1369 max_buffer > 1024 * 1024 * 8 * 8) {
1378 static int guess_ni_flag(AVFormatContext *s)
1381 int64_t last_start = 0;
1382 int64_t first_end = INT64_MAX;
1383 int64_t oldpos = avio_tell(s->pb);
1385 for (i = 0; i < s->nb_streams; i++) {
1386 AVStream *st = s->streams[i];
1387 int n = st->nb_index_entries;
1394 int64_t pos = st->index_entries[0].pos;
1395 avio_seek(s->pb, pos + 4, SEEK_SET);
1396 size = avio_rl32(s->pb);
1397 if (pos + size > st->index_entries[1].pos)
1398 last_start = INT64_MAX;
1401 if (st->index_entries[0].pos > last_start)
1402 last_start = st->index_entries[0].pos;
1403 if (st->index_entries[n - 1].pos < first_end)
1404 first_end = st->index_entries[n - 1].pos;
1406 avio_seek(s->pb, oldpos, SEEK_SET);
1408 if (last_start > first_end)
1411 return check_stream_max_drift(s);
1414 static int avi_load_index(AVFormatContext *s)
1416 AVIContext *avi = s->priv_data;
1417 AVIOContext *pb = s->pb;
1419 int64_t pos = avio_tell(pb);
1422 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1423 goto the_end; // maybe truncated file
1424 av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1426 if (pb->eof_reached)
1428 tag = avio_rl32(pb);
1429 size = avio_rl32(pb);
1430 av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1437 if (tag == MKTAG('i', 'd', 'x', '1') &&
1438 avi_read_idx1(s, size) >= 0) {
1444 if (avio_skip(pb, size) < 0)
1445 break; // something is wrong here
1449 avio_seek(pb, pos, SEEK_SET);
1453 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1455 AVIStream *ast2 = st2->priv_data;
1456 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1457 av_free_packet(&ast2->sub_pkt);
1458 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1459 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1460 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1463 static int avi_read_seek(AVFormatContext *s, int stream_index,
1464 int64_t timestamp, int flags)
1466 AVIContext *avi = s->priv_data;
1472 /* Does not matter which stream is requested dv in avi has the
1473 * stream information in the first video stream.
1478 if (!avi->index_loaded) {
1479 /* we only load the index on demand */
1481 avi->index_loaded = 1;
1484 st = s->streams[stream_index];
1485 ast = st->priv_data;
1486 index = av_index_search_timestamp(st,
1487 timestamp * FFMAX(ast->sample_size, 1),
1490 return AVERROR_INVALIDDATA;
1492 /* find the position */
1493 pos = st->index_entries[index].pos;
1494 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1496 av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
1497 timestamp, index, st->index_entries[index].timestamp);
1499 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1500 /* One and only one real stream for DV in AVI, and it has video */
1501 /* offsets. Calling with other stream indexes should have failed */
1502 /* the av_index_search_timestamp call above. */
1504 /* Feed the DV video stream version of the timestamp to the */
1505 /* DV demux so it can synthesize correct timestamps. */
1506 ff_dv_offset_reset(avi->dv_demux, timestamp);
1508 avio_seek(s->pb, pos, SEEK_SET);
1509 avi->stream_index = -1;
1513 for (i = 0; i < s->nb_streams; i++) {
1514 AVStream *st2 = s->streams[i];
1515 AVIStream *ast2 = st2->priv_data;
1518 ast2->remaining = 0;
1520 if (ast2->sub_ctx) {
1521 seek_subtitle(st, st2, timestamp);
1525 if (st2->nb_index_entries <= 0)
1528 // assert(st2->codec->block_align);
1529 assert((int64_t)st2->time_base.num * ast2->rate ==
1530 (int64_t)st2->time_base.den * ast2->scale);
1531 index = av_index_search_timestamp(st2,
1532 av_rescale_q(timestamp,
1535 FFMAX(ast2->sample_size, 1),
1536 flags | AVSEEK_FLAG_BACKWARD);
1540 if (!avi->non_interleaved) {
1541 while (index > 0 && st2->index_entries[index].pos > pos)
1543 while (index + 1 < st2->nb_index_entries &&
1544 st2->index_entries[index].pos < pos)
1548 av_dlog(s, "%"PRId64" %d %"PRId64"\n",
1549 timestamp, index, st2->index_entries[index].timestamp);
1550 /* extract the current frame number */
1551 ast2->frame_offset = st2->index_entries[index].timestamp;
1555 avio_seek(s->pb, pos, SEEK_SET);
1556 avi->stream_index = -1;
1560 static int avi_read_close(AVFormatContext *s)
1563 AVIContext *avi = s->priv_data;
1565 for (i = 0; i < s->nb_streams; i++) {
1566 AVStream *st = s->streams[i];
1567 AVIStream *ast = st->priv_data;
1570 av_freep(&ast->sub_ctx->pb);
1571 avformat_close_input(&ast->sub_ctx);
1573 av_free(ast->sub_buffer);
1574 av_free_packet(&ast->sub_pkt);
1578 av_free(avi->dv_demux);
1583 static int avi_probe(AVProbeData *p)
1587 /* check file header */
1588 for (i = 0; avi_headers[i][0]; i++)
1589 if (!memcmp(p->buf, avi_headers[i], 4) &&
1590 !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
1591 return AVPROBE_SCORE_MAX;
1596 AVInputFormat ff_avi_demuxer = {
1598 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1599 .priv_data_size = sizeof(AVIContext),
1600 .extensions = "avi",
1601 .read_probe = avi_probe,
1602 .read_header = avi_read_header,
1603 .read_packet = avi_read_packet,
1604 .read_close = avi_read_close,
1605 .read_seek = avi_read_seek,