3 * Copyright (c) 2001 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "config_components.h"
26 #include "libavutil/avassert.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/mem.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/dict.h"
31 #include "libavutil/integer.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/mathematics.h"
42 #include "libavcodec/bytestream.h"
43 #include "libavcodec/exif.h"
44 #include "libavcodec/startcode.h"
46 typedef struct AVIStream
{
47 int64_t frame_offset
; /* current frame (video) or byte (audio) counter
48 * (used to compute the pts) */
55 int sample_size
; /* size of one sample (or packet)
56 * (in the rate/scale sense) in bytes */
58 int64_t cum_len
; /* temporary storage (used during seek) */
59 int prefix
; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
63 int dshow_block_align
; /* block align variable used to emulate bugs in
64 * the MS dshow demuxer */
66 AVFormatContext
*sub_ctx
;
68 AVBufferRef
*sub_buffer
;
73 typedef struct AVIContext
{
85 DVDemuxContext
*dv_demux
;
90 #define MAX_ODML_DEPTH 1000
95 static const AVOption options
[] = {
96 { "use_odml", "use odml index", offsetof(AVIContext
, use_odml
), AV_OPT_TYPE_BOOL
, {.i64
= 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM
},
100 static const AVClass demuxer_class
= {
102 .item_name
= av_default_item_name
,
104 .version
= LIBAVUTIL_VERSION_INT
,
105 .category
= AV_CLASS_CATEGORY_DEMUXER
,
109 static const char avi_headers
[][8] = {
110 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
111 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
112 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
113 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
114 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
118 static const AVMetadataConv avi_metadata_conv
[] = {
120 { "isbj", "subject" },
122 { "iart", "artist" },
123 { "icop", "copyright" },
124 { "icmt", "comment" },
126 { "iprd", "product" },
127 { "isft", "software" },
132 static int avi_load_index(AVFormatContext
*s
);
133 static int guess_ni_flag(AVFormatContext
*s
);
135 #define print_tag(s, str, tag, size) \
136 av_log(s, AV_LOG_TRACE, "pos:%"PRIX64" %s: tag=%s size=0x%x\n", \
137 avio_tell(pb), str, av_fourcc2str(tag), size) \
139 static inline int get_duration(AVIStream *ast, int len)
141 if (ast
->sample_size
)
143 else if (ast
->dshow_block_align
)
144 return (len
+ (int64_t)ast
->dshow_block_align
- 1) / ast
->dshow_block_align
;
149 static int get_riff(AVFormatContext
*s
, AVIOContext
*pb
)
151 AVIContext
*avi
= s
->priv_data
;
152 char header
[8] = {0};
155 /* check RIFF header */
156 avio_read(pb
, header
, 4);
157 avi
->riff_end
= avio_rl32(pb
); /* RIFF chunk size */
158 avi
->riff_end
+= avio_tell(pb
); /* RIFF chunk end */
159 avio_read(pb
, header
+ 4, 4);
161 for (i
= 0; avi_headers
[i
][0]; i
++)
162 if (!memcmp(header
, avi_headers
[i
], 8))
164 if (!avi_headers
[i
][0])
165 return AVERROR_INVALIDDATA
;
167 if (header
[7] == 0x19)
168 av_log(s
, AV_LOG_INFO
,
169 "This file has been generated by a totally broken muxer.\n");
174 static int read_odml_index(AVFormatContext
*s
, int64_t frame_num
)
176 AVIContext
*avi
= s
->priv_data
;
177 AVIOContext
*pb
= s
->pb
;
178 int longs_per_entry
= avio_rl16(pb
);
179 int index_sub_type
= avio_r8(pb
);
180 int index_type
= avio_r8(pb
);
181 int entries_in_use
= avio_rl32(pb
);
182 int chunk_id
= avio_rl32(pb
);
183 int64_t base
= avio_rl64(pb
);
184 int stream_id
= ((chunk_id
& 0xFF) - '0') * 10 +
185 ((chunk_id
>> 8 & 0xFF) - '0');
189 int64_t last_pos
= -1;
190 int64_t filesize
= avi
->fsize
;
192 av_log(s
, AV_LOG_TRACE
,
193 "longs_per_entry:%d index_type:%d entries_in_use:%d "
194 "chunk_id:%X base:%16"PRIX64
" frame_num:%"PRId64
"\n",
202 if (stream_id
>= s
->nb_streams
|| stream_id
< 0)
203 return AVERROR_INVALIDDATA
;
204 st
= s
->streams
[stream_id
];
207 if (index_sub_type
|| entries_in_use
< 0)
208 return AVERROR_INVALIDDATA
;
212 if (index_type
&& longs_per_entry
!= 2)
213 return AVERROR_INVALIDDATA
;
215 return AVERROR_INVALIDDATA
;
217 if (filesize
> 0 && base
>= filesize
) {
218 av_log(s
, AV_LOG_ERROR
, "ODML index invalid\n");
219 if (base
>> 32 == (base
& 0xFFFFFFFF) &&
220 (base
& 0xFFFFFFFF) < filesize
&&
221 filesize
<= 0xFFFFFFFF)
224 return AVERROR_INVALIDDATA
;
227 for (i
= 0; i
< entries_in_use
; i
++) {
228 avi
->odml_max_pos
= FFMAX(avi
->odml_max_pos
, avio_tell(pb
));
230 // If we read more than there are bytes then we must have been reading something twice
231 if (avi
->odml_read
> avi
->odml_max_pos
)
232 return AVERROR_INVALIDDATA
;
235 int64_t pos
= avio_rl32(pb
) + base
- 8;
236 int len
= avio_rl32(pb
);
241 av_log(s
, AV_LOG_TRACE
, "pos:%"PRId64
", len:%X\n", pos
, len
);
244 return AVERROR_INVALIDDATA
;
246 if (last_pos
== pos
|| pos
== base
- 8)
247 avi
->non_interleaved
= 1;
248 if (last_pos
!= pos
&& len
)
249 av_add_index_entry(st
, pos
, ast
->cum_len
, len
, 0,
250 key
? AVINDEX_KEYFRAME
: 0);
252 ast
->cum_len
+= get_duration(ast
, len
);
258 avi
->odml_read
+= 16;
260 offset
= avio_rl64(pb
);
261 avio_rl32(pb
); /* size */
262 duration
= avio_rl32(pb
);
264 if (avio_feof(pb
) || offset
> INT64_MAX
- 8)
265 return AVERROR_INVALIDDATA
;
269 if (avi
->odml_depth
> MAX_ODML_DEPTH
) {
270 av_log(s
, AV_LOG_ERROR
, "Too deeply nested ODML indexes\n");
271 return AVERROR_INVALIDDATA
;
274 if (avio_seek(pb
, offset
+ 8, SEEK_SET
) < 0)
277 ret
= read_odml_index(s
, frame_num
);
279 frame_num
+= duration
;
281 if (avio_seek(pb
, pos
, SEEK_SET
) < 0) {
282 av_log(s
, AV_LOG_ERROR
, "Failed to restore position after reading index\n");
289 avi
->index_loaded
= 2;
293 static void clean_index(AVFormatContext
*s
)
298 for (i
= 0; i
< s
->nb_streams
; i
++) {
299 AVStream
*st
= s
->streams
[i
];
300 FFStream
*const sti
= ffstream(st
);
301 AVIStream
*ast
= st
->priv_data
;
302 int n
= sti
->nb_index_entries
;
303 int max
= ast
->sample_size
;
304 int64_t pos
, size
, ts
;
306 if (n
!= 1 || ast
->sample_size
== 0)
312 pos
= sti
->index_entries
[0].pos
;
313 size
= sti
->index_entries
[0].size
;
314 ts
= sti
->index_entries
[0].timestamp
;
316 for (j
= 0; j
< size
; j
+= max
)
317 av_add_index_entry(st
, pos
+ j
, ts
+ j
, FFMIN(max
, size
- j
), 0,
322 static int avi_read_tag(AVFormatContext
*s
, AVStream
*st
, uint32_t tag
,
325 AVIOContext
*pb
= s
->pb
;
331 if (size
== UINT_MAX
)
332 return AVERROR(EINVAL
);
333 value
= av_malloc(size
+ 1);
335 return AVERROR(ENOMEM
);
336 if (avio_read(pb
, value
, size
) != size
) {
338 return AVERROR_INVALIDDATA
;
344 return av_dict_set(st
? &st
->metadata
: &s
->metadata
, key
, value
,
345 AV_DICT_DONT_STRDUP_VAL
);
348 static const char months
[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
349 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
351 static void avi_metadata_creation_time(AVDictionary
**metadata
, char *date
)
353 char month
[4], time
[9], buffer
[64];
355 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
356 if (sscanf(date
, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
357 month
, &day
, time
, &year
) == 4) {
358 for (i
= 0; i
< 12; i
++)
359 if (!av_strcasecmp(month
, months
[i
])) {
360 snprintf(buffer
, sizeof(buffer
), "%.4d-%.2d-%.2d %s",
361 year
, i
+ 1, day
, time
);
362 av_dict_set(metadata
, "creation_time", buffer
, 0);
364 } else if (date
[4] == '/' && date
[7] == '/') {
365 date
[4] = date
[7] = '-';
366 av_dict_set(metadata
, "creation_time", date
, 0);
370 static void avi_read_nikon(AVFormatContext
*s
, uint64_t end
)
372 while (avio_tell(s
->pb
) < end
&& !avio_feof(s
->pb
)) {
373 uint32_t tag
= avio_rl32(s
->pb
);
374 uint32_t size
= avio_rl32(s
->pb
);
376 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
378 uint64_t tag_end
= avio_tell(s
->pb
) + size
;
379 while (avio_tell(s
->pb
) < tag_end
&& !avio_feof(s
->pb
)) {
380 uint16_t tag
= avio_rl16(s
->pb
);
381 uint16_t size
= avio_rl16(s
->pb
);
382 const char *name
= NULL
;
383 char buffer
[64] = { 0 };
384 uint64_t remaining
= tag_end
- avio_tell(s
->pb
);
385 size
= FFMIN(size
, remaining
);
386 size
-= avio_read(s
->pb
, buffer
,
387 FFMIN(size
, sizeof(buffer
) - 1));
396 name
= "creation_time";
397 if (buffer
[4] == ':' && buffer
[7] == ':')
398 buffer
[4] = buffer
[7] = '-';
402 av_dict_set(&s
->metadata
, name
, buffer
, 0);
403 avio_skip(s
->pb
, size
);
408 avio_skip(s
->pb
, size
);
414 static int avi_extract_stream_metadata(AVFormatContext
*s
, AVStream
*st
)
417 uint8_t *data
= st
->codecpar
->extradata
;
418 int data_size
= st
->codecpar
->extradata_size
;
421 if (!data
|| data_size
< 8) {
422 return AVERROR_INVALIDDATA
;
425 bytestream2_init(&gb
, data
, data_size
);
427 tag
= bytestream2_get_le32(&gb
);
430 case MKTAG('A', 'V', 'I', 'F'): {
431 AVExifMetadata ifd
= { 0 };
433 // skip 4 byte padding
434 bytestream2_skip(&gb
, 4);
435 offset
= bytestream2_tell(&gb
);
437 // decode EXIF tags from IFD, AVI is always little-endian
438 ret
= av_exif_parse_buffer(s
, data
+ offset
, data_size
- offset
, &ifd
, AV_EXIF_ASSUME_LE
);
441 ret
= av_exif_ifd_to_dict(s
, &ifd
, &st
->metadata
);
445 case MKTAG('C', 'A', 'S', 'I'):
446 avpriv_request_sample(s
, "RIFF stream data tag type CASI (%u)", tag
);
448 case MKTAG('Z', 'o', 'r', 'a'):
449 avpriv_request_sample(s
, "RIFF stream data tag type Zora (%u)", tag
);
458 static int calculate_bitrate(AVFormatContext
*s
)
460 AVIContext
*avi
= s
->priv_data
;
465 for (i
= 0; i
<s
->nb_streams
; i
++) {
467 FFStream
*const sti
= ffstream(s
->streams
[i
]);
469 if (!sti
->nb_index_entries
)
472 for (j
= 0; j
< sti
->nb_index_entries
; j
++)
473 len
+= sti
->index_entries
[j
].size
;
474 maxpos
= FFMAX(maxpos
, sti
->index_entries
[j
-1].pos
);
477 if (maxpos
< av_rescale(avi
->io_fsize
, 9, 10)) // index does not cover the whole file
479 if (lensum
*9/10 > maxpos
|| lensum
< maxpos
*9/10) // frame sum and filesize mismatch
482 for (i
= 0; i
<s
->nb_streams
; i
++) {
484 AVStream
*st
= s
->streams
[i
];
485 FFStream
*const sti
= ffstream(st
);
487 AVInteger bitrate_i
, den_i
, num_i
;
489 for (j
= 0; j
< sti
->nb_index_entries
; j
++)
490 len
+= sti
->index_entries
[j
].size
;
492 if (sti
->nb_index_entries
< 2 || st
->codecpar
->bit_rate
> 0)
494 duration
= sti
->index_entries
[j
-1].timestamp
- sti
->index_entries
[0].timestamp
;
495 den_i
= av_mul_i(av_int2i(duration
), av_int2i(st
->time_base
.num
));
496 num_i
= av_add_i(av_mul_i(av_int2i(8*len
), av_int2i(st
->time_base
.den
)), av_shr_i(den_i
, 1));
497 bitrate_i
= av_div_i(num_i
, den_i
);
498 if (av_cmp_i(bitrate_i
, av_int2i(INT64_MAX
)) <= 0) {
499 int64_t bitrate
= av_i2int(bitrate_i
);
501 st
->codecpar
->bit_rate
= bitrate
;
508 static int avi_read_header(AVFormatContext
*s
)
510 AVIContext
*avi
= s
->priv_data
;
511 AVIOContext
*pb
= s
->pb
;
512 unsigned int tag
, tag1
, handler
;
513 int codec_type
, stream_index
, frame_period
;
517 AVIStream
*ast
= NULL
;
518 int avih_width
= 0, avih_height
= 0;
519 int amv_file_format
= 0;
520 uint64_t list_end
= 0;
523 AVDictionaryEntry
*dict_entry
;
525 avi
->stream_index
= -1;
527 ret
= get_riff(s
, pb
);
531 av_log(avi
, AV_LOG_DEBUG
, "use odml:%d\n", avi
->use_odml
);
533 avi
->io_fsize
= avi
->fsize
= avio_size(pb
);
534 if (avi
->fsize
<= 0 || avi
->fsize
< avi
->riff_end
)
535 avi
->fsize
= avi
->riff_end
== 8 ? INT64_MAX
: avi
->riff_end
;
543 return AVERROR_INVALIDDATA
;
545 size
= avio_rl32(pb
);
547 print_tag(s
, "tag", tag
, size
);
550 case MKTAG('L', 'I', 'S', 'T'):
551 list_end
= avio_tell(pb
) + size
;
552 /* Ignored, except at start of video packets. */
553 tag1
= avio_rl32(pb
);
555 print_tag(s
, "list", tag1
, 0);
557 if (tag1
== MKTAG('m', 'o', 'v', 'i')) {
558 avi
->movi_list
= avio_tell(pb
) - 4;
560 avi
->movi_end
= avi
->movi_list
+ size
+ (size
& 1);
562 avi
->movi_end
= avi
->fsize
;
563 av_log(s
, AV_LOG_TRACE
, "movi end=%"PRIx64
"\n", avi
->movi_end
);
565 } else if (tag1
== MKTAG('I', 'N', 'F', 'O'))
566 ff_read_riff_info(s
, size
- 4);
567 else if (tag1
== MKTAG('n', 'c', 'd', 't'))
568 avi_read_nikon(s
, list_end
);
571 case MKTAG('I', 'D', 'I', 'T'):
573 unsigned char date
[64] = { 0 };
575 size
-= avio_read(pb
, date
, FFMIN(size
, sizeof(date
) - 1));
577 avi_metadata_creation_time(&s
->metadata
, date
);
580 case MKTAG('d', 'm', 'l', 'h'):
582 avio_skip(pb
, size
+ (size
& 1));
584 case MKTAG('a', 'm', 'v', 'h'):
586 case MKTAG('a', 'v', 'i', 'h'):
588 /* using frame_period is bad idea */
589 frame_period
= avio_rl32(pb
);
590 avio_rl32(pb
); /* max. bytes per second */
592 avi
->non_interleaved
|= avio_rl32(pb
) & AVIF_MUSTUSEINDEX
;
594 avio_skip(pb
, 2 * 4);
597 avih_width
= avio_rl32(pb
);
598 avih_height
= avio_rl32(pb
);
600 avio_skip(pb
, size
- 10 * 4);
602 case MKTAG('s', 't', 'r', 'h'):
605 tag1
= avio_rl32(pb
);
606 handler
= avio_rl32(pb
); /* codec tag */
608 if (tag1
== MKTAG('p', 'a', 'd', 's')) {
609 avio_skip(pb
, size
- 8);
613 st
= avformat_new_stream(s
, NULL
);
615 return AVERROR(ENOMEM
);
617 st
->id
= stream_index
;
618 ast
= av_mallocz(sizeof(AVIStream
));
620 return AVERROR(ENOMEM
);
624 tag1
= stream_index
? MKTAG('a', 'u', 'd', 's')
625 : MKTAG('v', 'i', 'd', 's');
627 print_tag(s
, "strh", tag1
, -1);
629 if (tag1
== MKTAG('i', 'a', 'v', 's') ||
630 tag1
== MKTAG('i', 'v', 'a', 's')) {
633 /* After some consideration -- I don't think we
634 * have to support anything but DV in type1 AVIs. */
635 if (s
->nb_streams
!= 1)
636 return AVERROR_INVALIDDATA
;
638 if (handler
!= MKTAG('d', 'v', 's', 'd') &&
639 handler
!= MKTAG('d', 'v', 'h', 'd') &&
640 handler
!= MKTAG('d', 'v', 's', 'l'))
641 return AVERROR_INVALIDDATA
;
643 if (!CONFIG_DV_DEMUXER
)
644 return AVERROR_DEMUXER_NOT_FOUND
;
646 ast
= s
->streams
[0]->priv_data
;
647 st
->priv_data
= NULL
;
648 ff_remove_stream(s
, st
);
650 avi
->dv_demux
= avpriv_dv_init_demux(s
);
651 if (!avi
->dv_demux
) {
653 return AVERROR(ENOMEM
);
656 s
->streams
[0]->priv_data
= ast
;
657 avio_skip(pb
, 3 * 4);
658 ast
->scale
= avio_rl32(pb
);
659 ast
->rate
= avio_rl32(pb
);
660 avio_skip(pb
, 4); /* start time */
662 dv_dur
= avio_rl32(pb
);
663 if (ast
->scale
> 0 && ast
->rate
> 0 && dv_dur
> 0) {
664 dv_dur
*= AV_TIME_BASE
;
665 s
->duration
= av_rescale(dv_dur
, ast
->scale
, ast
->rate
);
667 /* else, leave duration alone; timing estimation in utils.c
668 * will make a guess based on bitrate. */
670 stream_index
= s
->nb_streams
- 1;
671 avio_skip(pb
, size
- 9 * 4);
675 av_assert0(stream_index
< s
->nb_streams
);
676 ast
->handler
= handler
;
678 avio_rl32(pb
); /* flags */
679 avio_rl16(pb
); /* priority */
680 avio_rl16(pb
); /* language */
681 avio_rl32(pb
); /* initial frame */
682 ast
->scale
= avio_rl32(pb
);
683 ast
->rate
= avio_rl32(pb
);
684 if (!(ast
->scale
&& ast
->rate
)) {
685 av_log(s
, AV_LOG_WARNING
,
686 "scale/rate is %"PRIu32
"/%"PRIu32
" which is invalid. "
687 "(This file has been generated by broken software.)\n",
692 ast
->scale
= frame_period
;
698 avpriv_set_pts_info(st
, 64, ast
->scale
, ast
->rate
);
700 ast
->cum_len
= avio_rl32(pb
); /* start */
701 st
->nb_frames
= avio_rl32(pb
);
704 avio_rl32(pb
); /* buffer size */
705 avio_rl32(pb
); /* quality */
706 if (ast
->cum_len
> 3600LL * ast
->rate
/ ast
->scale
) {
707 av_log(s
, AV_LOG_ERROR
, "crazy start time, iam scared, giving up\n");
710 ast
->sample_size
= avio_rl32(pb
);
711 ast
->cum_len
*= FFMAX(1, ast
->sample_size
);
712 av_log(s
, AV_LOG_TRACE
, "%"PRIu32
" %"PRIu32
" %d\n",
713 ast
->rate
, ast
->scale
, ast
->sample_size
);
716 case MKTAG('v', 'i', 'd', 's'):
717 codec_type
= AVMEDIA_TYPE_VIDEO
;
719 ast
->sample_size
= 0;
720 st
->avg_frame_rate
= av_inv_q(st
->time_base
);
722 case MKTAG('a', 'u', 'd', 's'):
723 codec_type
= AVMEDIA_TYPE_AUDIO
;
725 case MKTAG('t', 'x', 't', 's'):
726 codec_type
= AVMEDIA_TYPE_SUBTITLE
;
728 case MKTAG('d', 'a', 't', 's'):
729 codec_type
= AVMEDIA_TYPE_DATA
;
732 av_log(s
, AV_LOG_INFO
, "unknown stream type %X\n", tag1
);
735 if (ast
->sample_size
< 0) {
736 if (s
->error_recognition
& AV_EF_EXPLODE
) {
737 av_log(s
, AV_LOG_ERROR
,
738 "Invalid sample_size %d at stream %d\n",
741 return AVERROR_INVALIDDATA
;
743 av_log(s
, AV_LOG_WARNING
,
744 "Invalid sample_size %d at stream %d "
748 ast
->sample_size
= 0;
751 if (ast
->sample_size
== 0) {
752 st
->duration
= st
->nb_frames
;
753 if (st
->duration
> 0 && avi
->io_fsize
> 0 && avi
->riff_end
> avi
->io_fsize
) {
754 av_log(s
, AV_LOG_DEBUG
, "File is truncated adjusting duration\n");
755 st
->duration
= av_rescale(st
->duration
, avi
->io_fsize
, avi
->riff_end
);
758 ast
->frame_offset
= ast
->cum_len
;
759 avio_skip(pb
, size
- 12 * 4);
761 case MKTAG('s', 't', 'r', 'f'):
763 if (!size
&& (codec_type
== AVMEDIA_TYPE_AUDIO
||
764 codec_type
== AVMEDIA_TYPE_VIDEO
))
766 if (stream_index
>= (unsigned)s
->nb_streams
|| avi
->dv_demux
) {
769 uint64_t cur_pos
= avio_tell(pb
);
772 if (cur_pos
< list_end
)
773 size
= FFMIN(size
, list_end
- cur_pos
);
774 st
= s
->streams
[stream_index
];
776 if (st
->codecpar
->codec_type
!= AVMEDIA_TYPE_UNKNOWN
) {
780 switch (codec_type
) {
781 case AVMEDIA_TYPE_VIDEO
:
782 if (amv_file_format
) {
783 st
->codecpar
->width
= avih_width
;
784 st
->codecpar
->height
= avih_height
;
785 st
->codecpar
->codec_type
= AVMEDIA_TYPE_VIDEO
;
786 st
->codecpar
->codec_id
= AV_CODEC_ID_AMV
;
790 tag1
= ff_get_bmp_header(pb
, st
, &esize
);
792 if (tag1
== MKTAG('D', 'X', 'S', 'B') ||
793 tag1
== MKTAG('D', 'X', 'S', 'A')) {
794 st
->codecpar
->codec_type
= AVMEDIA_TYPE_SUBTITLE
;
795 st
->codecpar
->codec_tag
= tag1
;
796 st
->codecpar
->codec_id
= AV_CODEC_ID_XSUB
;
800 if (size
> 10 * 4 && size
< (1 << 30) && size
< avi
->fsize
) {
801 if (esize
== size
-1 && (esize
&1)) {
802 st
->codecpar
->extradata_size
= esize
- 10 * 4;
804 st
->codecpar
->extradata_size
= size
- 10 * 4;
805 if (st
->codecpar
->extradata
) {
806 av_log(s
, AV_LOG_WARNING
, "New extradata in strf chunk, freeing previous one.\n");
808 ret
= ff_get_extradata(s
, st
->codecpar
, pb
,
809 st
->codecpar
->extradata_size
);
814 // FIXME: check if the encoder really did this correctly
815 if (st
->codecpar
->extradata_size
& 1)
818 /* Extract palette from extradata if bpp <= 8.
819 * This code assumes that extradata contains only palette.
820 * This is true for all paletted codecs implemented in
822 if (st
->codecpar
->extradata_size
&&
823 (st
->codecpar
->bits_per_coded_sample
<= 8)) {
824 int pal_size
= (1 << st
->codecpar
->bits_per_coded_sample
) << 2;
825 const uint8_t *pal_src
;
827 pal_size
= FFMIN(pal_size
, st
->codecpar
->extradata_size
);
828 pal_src
= st
->codecpar
->extradata
+
829 st
->codecpar
->extradata_size
- pal_size
;
830 /* Exclude the "BottomUp" field from the palette */
831 if (pal_src
- st
->codecpar
->extradata
>= 9 &&
832 !memcmp(st
->codecpar
->extradata
+ st
->codecpar
->extradata_size
- 9, "BottomUp", 9))
834 for (i
= 0; i
< pal_size
/ 4; i
++)
835 ast
->pal
[i
] = 0xFFU
<<24 | AV_RL32(pal_src
+ 4 * i
);
839 print_tag(s
, "video", tag1
, 0);
841 st
->codecpar
->codec_type
= AVMEDIA_TYPE_VIDEO
;
842 st
->codecpar
->codec_tag
= tag1
;
843 st
->codecpar
->codec_id
= ff_codec_get_id(ff_codec_bmp_tags
,
845 /* If codec is not found yet, try with the mov tags. */
846 if (!st
->codecpar
->codec_id
) {
847 st
->codecpar
->codec_id
=
848 ff_codec_get_id(ff_codec_movvideo_tags
, tag1
);
849 if (st
->codecpar
->codec_id
)
850 av_log(s
, AV_LOG_WARNING
,
851 "mov tag found in avi (fourcc %s)\n",
852 av_fourcc2str(tag1
));
854 if (!st
->codecpar
->codec_id
)
855 st
->codecpar
->codec_id
= ff_codec_get_id(ff_codec_bmp_tags_unofficial
, tag1
);
857 /* This is needed to get the pict type which is necessary
858 * for generating correct pts. */
859 sti
->need_parsing
= AVSTREAM_PARSE_HEADERS
;
861 if (st
->codecpar
->codec_id
== AV_CODEC_ID_MPEG4
&&
862 ast
->handler
== MKTAG('X', 'V', 'I', 'D'))
863 st
->codecpar
->codec_tag
= MKTAG('X', 'V', 'I', 'D');
865 if (st
->codecpar
->codec_tag
== MKTAG('V', 'S', 'S', 'H'))
866 sti
->need_parsing
= AVSTREAM_PARSE_FULL
;
867 if (st
->codecpar
->codec_id
== AV_CODEC_ID_RV40
)
868 sti
->need_parsing
= AVSTREAM_PARSE_NONE
;
869 if (st
->codecpar
->codec_id
== AV_CODEC_ID_HEVC
&&
870 st
->codecpar
->codec_tag
== MKTAG('H', '2', '6', '5'))
871 sti
->need_parsing
= AVSTREAM_PARSE_FULL
;
873 if (st
->codecpar
->codec_id
== AV_CODEC_ID_AVRN
&&
874 st
->codecpar
->codec_tag
== MKTAG('A', 'V', 'R', 'n') &&
875 (st
->codecpar
->extradata_size
< 31 ||
876 memcmp(&st
->codecpar
->extradata
[28], "1:1", 3)))
877 st
->codecpar
->codec_id
= AV_CODEC_ID_MJPEG
;
879 if (st
->codecpar
->codec_tag
== 0 && st
->codecpar
->height
> 0 &&
880 st
->codecpar
->extradata_size
< 1U << 30) {
881 st
->codecpar
->extradata_size
+= 9;
882 if ((ret
= av_reallocp(&st
->codecpar
->extradata
,
883 st
->codecpar
->extradata_size
+
884 AV_INPUT_BUFFER_PADDING_SIZE
)) < 0) {
885 st
->codecpar
->extradata_size
= 0;
888 memcpy(st
->codecpar
->extradata
+ st
->codecpar
->extradata_size
- 9,
891 if (st
->codecpar
->height
== INT_MIN
)
892 return AVERROR_INVALIDDATA
;
893 st
->codecpar
->height
= FFABS(st
->codecpar
->height
);
895 // avio_skip(pb, size - 5 * 4);
897 case AVMEDIA_TYPE_AUDIO
:
898 ret
= ff_get_wav_header(s
, pb
, st
->codecpar
, size
, 0);
901 ast
->dshow_block_align
= st
->codecpar
->block_align
;
902 if (ast
->sample_size
&& st
->codecpar
->block_align
&&
903 ast
->sample_size
!= st
->codecpar
->block_align
) {
906 "sample size (%d) != block align (%d)\n",
908 st
->codecpar
->block_align
);
909 ast
->sample_size
= st
->codecpar
->block_align
;
912 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
915 /* Force parsing as several audio frames can be in
916 * one packet and timestamps refer to packet start. */
917 sti
->need_parsing
= AVSTREAM_PARSE_TIMESTAMPS
;
918 /* ADTS header is in extradata, AAC without header must be
919 * stored as exact frames. Parser not needed and it will
921 if (st
->codecpar
->codec_id
== AV_CODEC_ID_AAC
&&
922 st
->codecpar
->extradata_size
)
923 sti
->need_parsing
= AVSTREAM_PARSE_NONE
;
924 // The flac parser does not work with AVSTREAM_PARSE_TIMESTAMPS
925 if (st
->codecpar
->codec_id
== AV_CODEC_ID_FLAC
)
926 sti
->need_parsing
= AVSTREAM_PARSE_NONE
;
927 /* AVI files with Xan DPCM audio (wrongly) declare PCM
928 * audio in the header but have Axan as stream_code_tag. */
929 if (ast
->handler
== AV_RL32("Axan")) {
930 st
->codecpar
->codec_id
= AV_CODEC_ID_XAN_DPCM
;
931 st
->codecpar
->codec_tag
= 0;
932 ast
->dshow_block_align
= 0;
934 if (amv_file_format
) {
935 st
->codecpar
->codec_id
= AV_CODEC_ID_ADPCM_IMA_AMV
;
936 ast
->dshow_block_align
= 0;
938 if ((st
->codecpar
->codec_id
== AV_CODEC_ID_AAC
||
939 st
->codecpar
->codec_id
== AV_CODEC_ID_FTR
||
940 st
->codecpar
->codec_id
== AV_CODEC_ID_FLAC
||
941 st
->codecpar
->codec_id
== AV_CODEC_ID_MP2
) && ast
->dshow_block_align
<= 4 && ast
->dshow_block_align
) {
942 av_log(s
, AV_LOG_DEBUG
, "overriding invalid dshow_block_align of %d\n", ast
->dshow_block_align
);
943 ast
->dshow_block_align
= 0;
945 if (st
->codecpar
->codec_id
== AV_CODEC_ID_AAC
&& ast
->dshow_block_align
== 1024 && ast
->sample_size
== 1024 ||
946 st
->codecpar
->codec_id
== AV_CODEC_ID_AAC
&& ast
->dshow_block_align
== 4096 && ast
->sample_size
== 4096 ||
947 st
->codecpar
->codec_id
== AV_CODEC_ID_MP3
&& ast
->dshow_block_align
== 1152 && ast
->sample_size
== 1152) {
948 av_log(s
, AV_LOG_DEBUG
, "overriding sample_size\n");
949 ast
->sample_size
= 0;
952 case AVMEDIA_TYPE_SUBTITLE
:
953 st
->codecpar
->codec_type
= AVMEDIA_TYPE_SUBTITLE
;
954 sti
->request_probe
= 1;
958 st
->codecpar
->codec_type
= AVMEDIA_TYPE_DATA
;
959 st
->codecpar
->codec_id
= AV_CODEC_ID_NONE
;
960 st
->codecpar
->codec_tag
= 0;
966 case MKTAG('s', 't', 'r', 'd'):
967 if (stream_index
>= (unsigned)s
->nb_streams
968 || s
->streams
[stream_index
]->codecpar
->extradata_size
969 || s
->streams
[stream_index
]->codecpar
->codec_tag
== MKTAG('H','2','6','4')) {
972 uint64_t cur_pos
= avio_tell(pb
);
973 if (cur_pos
< list_end
)
974 size
= FFMIN(size
, list_end
- cur_pos
);
975 st
= s
->streams
[stream_index
];
978 if (st
->codecpar
->extradata
) {
979 av_log(s
, AV_LOG_WARNING
, "New extradata in strd chunk, freeing previous one.\n");
981 if ((ret
= ff_get_extradata(s
, st
->codecpar
, pb
, size
)) < 0)
985 if (st
->codecpar
->extradata_size
& 1) //FIXME check if the encoder really did this correctly
988 ret
= avi_extract_stream_metadata(s
, st
);
990 av_log(s
, AV_LOG_WARNING
, "could not decoding EXIF data in stream header.\n");
994 case MKTAG('i', 'n', 'd', 'x'):
996 if ((pb
->seekable
& AVIO_SEEKABLE_NORMAL
) && !(s
->flags
& AVFMT_FLAG_IGNIDX
) &&
998 read_odml_index(s
, 0) < 0 &&
999 (s
->error_recognition
& AV_EF_EXPLODE
))
1000 return AVERROR_INVALIDDATA
;
1001 avio_seek(pb
, pos
+ size
, SEEK_SET
);
1003 case MKTAG('v', 'p', 'r', 'p'):
1004 if (stream_index
< (unsigned)s
->nb_streams
&& size
> 9 * 4) {
1005 AVRational active
, active_aspect
;
1007 st
= s
->streams
[stream_index
];
1014 active_aspect
.den
= avio_rl16(pb
);
1015 active_aspect
.num
= avio_rl16(pb
);
1016 active
.num
= avio_rl32(pb
);
1017 active
.den
= avio_rl32(pb
);
1018 avio_rl32(pb
); // nbFieldsPerFrame
1020 if (active_aspect
.num
&& active_aspect
.den
&&
1021 active
.num
&& active
.den
) {
1022 st
->sample_aspect_ratio
= av_div_q(active_aspect
, active
);
1023 av_log(s
, AV_LOG_TRACE
, "vprp %d/%d %d/%d\n",
1024 active_aspect
.num
, active_aspect
.den
,
1025 active
.num
, active
.den
);
1029 avio_skip(pb
, size
);
1031 case MKTAG('s', 't', 'r', 'n'):
1032 case MKTAG('i', 's', 'b', 'j'):
1033 case MKTAG('i', 'n', 'a', 'm'):
1034 case MKTAG('i', 'a', 'r', 't'):
1035 case MKTAG('i', 'c', 'o', 'p'):
1036 case MKTAG('i', 'c', 'm', 't'):
1037 case MKTAG('i', 'g', 'n', 'r'):
1038 case MKTAG('i', 'p', 'o', 'd'):
1039 case MKTAG('i', 's', 'o', 'f'):
1040 if (s
->nb_streams
) {
1041 ret
= avi_read_tag(s
, s
->streams
[s
->nb_streams
- 1], tag
, size
);
1047 if (size
> 1000000) {
1048 av_log(s
, AV_LOG_ERROR
,
1049 "Something went wrong during header parsing, "
1050 "tag %s has size %u, "
1051 "I will ignore it and try to continue anyway.\n",
1052 av_fourcc2str(tag
), size
);
1053 if (s
->error_recognition
& AV_EF_EXPLODE
)
1054 return AVERROR_INVALIDDATA
;
1055 avi
->movi_list
= avio_tell(pb
) - 4;
1056 avi
->movi_end
= avi
->fsize
;
1059 /* Do not fail for very large idx1 tags */
1060 case MKTAG('i', 'd', 'x', '1'):
1063 avio_skip(pb
, size
);
1069 /* check stream number */
1070 if (stream_index
!= s
->nb_streams
- 1)
1071 return AVERROR_INVALIDDATA
;
1073 if (!avi
->index_loaded
&& (pb
->seekable
& AVIO_SEEKABLE_NORMAL
))
1075 calculate_bitrate(s
);
1076 avi
->index_loaded
|= 1;
1078 if ((ret
= guess_ni_flag(s
)) < 0)
1081 avi
->non_interleaved
|= ret
| (s
->flags
& AVFMT_FLAG_SORT_DTS
);
1083 dict_entry
= av_dict_get(s
->metadata
, "ISFT", NULL
, 0);
1084 if (dict_entry
&& !strcmp(dict_entry
->value
, "PotEncoder"))
1085 for (i
= 0; i
< s
->nb_streams
; i
++) {
1086 AVStream
*st
= s
->streams
[i
];
1087 if ( st
->codecpar
->codec_id
== AV_CODEC_ID_MPEG1VIDEO
1088 || st
->codecpar
->codec_id
== AV_CODEC_ID_MPEG2VIDEO
)
1089 ffstream(st
)->need_parsing
= AVSTREAM_PARSE_FULL
;
1092 for (i
= 0; i
< s
->nb_streams
; i
++) {
1093 AVStream
*st
= s
->streams
[i
];
1094 if (ffstream(st
)->nb_index_entries
)
1097 // DV-in-AVI cannot be non-interleaved, if set this must be
1100 avi
->non_interleaved
= 0;
1101 if (i
== s
->nb_streams
&& avi
->non_interleaved
) {
1102 av_log(s
, AV_LOG_WARNING
,
1103 "Non-interleaved AVI without index, switching to interleaved\n");
1104 avi
->non_interleaved
= 0;
1107 if (avi
->non_interleaved
) {
1108 av_log(s
, AV_LOG_INFO
, "non-interleaved AVI\n");
1112 ff_metadata_conv_ctx(s
, NULL
, avi_metadata_conv
);
1113 ff_metadata_conv_ctx(s
, NULL
, ff_riff_info_conv
);
1118 static int read_gab2_sub(AVFormatContext
*s
, AVStream
*st
, AVPacket
*pkt
)
1120 if (pkt
->size
>= 7 &&
1121 pkt
->size
< INT_MAX
- AVPROBE_PADDING_SIZE
&&
1122 !strcmp(pkt
->data
, "GAB2") && AV_RL16(pkt
->data
+ 5) == 2) {
1124 int score
= AVPROBE_SCORE_EXTENSION
, ret
;
1125 AVIStream
*ast
= st
->priv_data
;
1126 const AVInputFormat
*sub_demuxer
;
1127 AVRational time_base
;
1130 unsigned int desc_len
;
1135 AVIOContext
*pb
= avio_alloc_context(pkt
->data
+ 7,
1137 0, NULL
, NULL
, NULL
, NULL
);
1141 desc_len
= avio_rl32(pb
);
1143 if (desc_len
> pb
->buf_end
- pb
->buf_ptr
)
1146 ret
= avio_get_str16le(pb
, desc_len
, desc
, sizeof(desc
));
1147 avio_skip(pb
, desc_len
- ret
);
1149 av_dict_set(&st
->metadata
, "title", desc
, 0);
1151 avio_rl16(pb
); /* flags? */
1152 avio_rl32(pb
); /* data size */
1154 size
= pb
->buf_end
- pb
->buf_ptr
;
1155 pd
= (AVProbeData
) { .buf
= av_mallocz(size
+ AVPROBE_PADDING_SIZE
),
1159 memcpy(pd
.buf
, pb
->buf_ptr
, size
);
1160 sub_demuxer
= av_probe_input_format2(&pd
, 1, &score
);
1165 if (strcmp(sub_demuxer
->name
, "srt") && strcmp(sub_demuxer
->name
, "ass"))
1168 if (!(ast
->sub_pkt
= av_packet_alloc()))
1171 if (!(ast
->sub_ctx
= avformat_alloc_context()))
1174 ast
->sub_ctx
->pb
= pb
;
1176 if (ff_copy_whiteblacklists(ast
->sub_ctx
, s
) < 0)
1179 if (!avformat_open_input(&ast
->sub_ctx
, "", sub_demuxer
, NULL
)) {
1180 if (ast
->sub_ctx
->nb_streams
!= 1)
1182 ff_read_packet(ast
->sub_ctx
, ast
->sub_pkt
);
1183 avcodec_parameters_copy(st
->codecpar
, ast
->sub_ctx
->streams
[0]->codecpar
);
1184 time_base
= ast
->sub_ctx
->streams
[0]->time_base
;
1185 avpriv_set_pts_info(st
, 64, time_base
.num
, time_base
.den
);
1187 ast
->sub_buffer
= pkt
->buf
;
1189 av_packet_unref(pkt
);
1193 av_packet_free(&ast
->sub_pkt
);
1194 av_freep(&ast
->sub_ctx
);
1195 avio_context_free(&pb
);
1200 static AVStream
*get_subtitle_pkt(AVFormatContext
*s
, AVStream
*next_st
,
1203 AVIStream
*ast
, *next_ast
= next_st
->priv_data
;
1204 int64_t ts
, next_ts
, ts_min
= INT64_MAX
;
1205 AVStream
*st
, *sub_st
= NULL
;
1208 next_ts
= av_rescale_q(next_ast
->frame_offset
, next_st
->time_base
,
1211 for (i
= 0; i
< s
->nb_streams
; i
++) {
1213 ast
= st
->priv_data
;
1214 if (st
->discard
< AVDISCARD_ALL
&& ast
&& ast
->sub_pkt
&& ast
->sub_pkt
->data
) {
1215 ts
= av_rescale_q(ast
->sub_pkt
->dts
, st
->time_base
, AV_TIME_BASE_Q
);
1216 if (ts
<= next_ts
&& ts
< ts_min
) {
1224 ast
= sub_st
->priv_data
;
1225 av_packet_move_ref(pkt
, ast
->sub_pkt
);
1226 pkt
->stream_index
= sub_st
->index
;
1228 if (ff_read_packet(ast
->sub_ctx
, ast
->sub_pkt
) < 0)
1229 ast
->sub_pkt
->data
= NULL
;
1234 static int get_stream_idx(const unsigned *d
)
1236 if (d
[0] >= '0' && d
[0] <= '9' &&
1237 d
[1] >= '0' && d
[1] <= '9') {
1238 return (d
[0] - '0') * 10 + (d
[1] - '0');
1240 return 100; // invalid stream ID
1246 * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
1248 static int avi_sync(AVFormatContext
*s
, int exit_early
)
1250 AVIContext
*avi
= s
->priv_data
;
1251 AVIOContext
*pb
= s
->pb
;
1258 memset(d
, -1, sizeof(d
));
1259 for (i
= sync
= avio_tell(pb
); !avio_feof(pb
); i
++) {
1262 for (j
= 0; j
< 7; j
++)
1266 size
= d
[4] + (d
[5] << 8) + (d
[6] << 16) + (d
[7] << 24);
1268 n
= get_stream_idx(d
+ 2);
1269 ff_tlog(s
, "%X %X %X %X %X %X %X %X %"PRId64
" %u %d\n",
1270 d
[0], d
[1], d
[2], d
[3], d
[4], d
[5], d
[6], d
[7], i
, size
, n
);
1271 if (i
*(avi
->io_fsize
>0) + (uint64_t)size
> avi
->fsize
|| d
[0] > 127)
1275 if ((d
[0] == 'i' && d
[1] == 'x' && n
< s
->nb_streams
) ||
1277 (d
[0] == 'J' && d
[1] == 'U' && d
[2] == 'N' && d
[3] == 'K') ||
1278 (d
[0] == 'i' && d
[1] == 'd' && d
[2] == 'x' && d
[3] == '1') ||
1279 (d
[0] == 'i' && d
[1] == 'n' && d
[2] == 'd' && d
[3] == 'x')) {
1280 avio_skip(pb
, size
);
1285 if (d
[0] == 'L' && d
[1] == 'I' && d
[2] == 'S' && d
[3] == 'T') {
1290 n
= get_stream_idx(d
);
1292 if (!((i
- avi
->last_pkt_pos
) & 1) &&
1293 get_stream_idx(d
+ 1) < s
->nb_streams
)
1296 // detect ##ix chunk and skip
1297 if (d
[2] == 'i' && d
[3] == 'x' && n
< s
->nb_streams
) {
1298 avio_skip(pb
, size
);
1302 if (d
[2] == 'w' && d
[3] == 'c' && n
< s
->nb_streams
) {
1303 avio_skip(pb
, 16 * 3 + 8);
1307 if (avi
->dv_demux
&& n
!= 0)
1311 if (n
< s
->nb_streams
) {
1315 ast
= st
->priv_data
;
1318 av_log(s
, AV_LOG_WARNING
, "Skipping foreign stream %d packet\n", n
);
1322 if (s
->nb_streams
>= 2) {
1323 AVStream
*st1
= s
->streams
[1];
1324 AVIStream
*ast1
= st1
->priv_data
;
1325 // workaround for broken small-file-bug402.avi
1326 if (ast1
&& d
[2] == 'w' && d
[3] == 'b'
1328 && st
->codecpar
->codec_type
== AVMEDIA_TYPE_VIDEO
1329 && st1
->codecpar
->codec_type
== AVMEDIA_TYPE_AUDIO
1330 && ast
->prefix
== 'd'*256+'c'
1331 && (d
[2]*256+d
[3] == ast1
->prefix
|| !ast1
->prefix_count
)
1336 av_log(s
, AV_LOG_WARNING
,
1337 "Invalid stream + prefix combination, assuming audio.\n");
1341 if (d
[2] == 'p' && d
[3] == 'c' && size
<= 4 * 256 + 4) {
1342 int k
= avio_r8(pb
);
1343 int last
= (k
+ avio_r8(pb
) - 1) & 0xFF;
1345 avio_rl16(pb
); // flags
1347 // b + (g << 8) + (r << 16);
1348 for (; k
<= last
; k
++)
1349 ast
->pal
[k
] = 0xFFU
<<24 | avio_rb32(pb
)>>8;
1353 } else if (((ast
->prefix_count
< 5 || sync
+ 9 > i
) &&
1354 d
[2] < 128 && d
[3] < 128) ||
1355 d
[2] * 256 + d
[3] == ast
->prefix
/* ||
1356 (d[2] == 'd' && d[3] == 'c') ||
1357 (d[2] == 'w' && d[3] == 'b') */) {
1360 if (d
[2] * 256 + d
[3] == ast
->prefix
)
1361 ast
->prefix_count
++;
1363 ast
->prefix
= d
[2] * 256 + d
[3];
1364 ast
->prefix_count
= 0;
1367 if (!avi
->dv_demux
&&
1368 ((st
->discard
>= AVDISCARD_DEFAULT
&& size
== 0) /* ||
1369 // FIXME: needs a little reordering
1370 (st->discard >= AVDISCARD_NONKEY &&
1371 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1372 || st
->discard
>= AVDISCARD_ALL
)) {
1374 ast
->frame_offset
+= get_duration(ast
, size
);
1375 avio_skip(pb
, size
);
1379 avi
->stream_index
= n
;
1380 ast
->packet_size
= size
+ 8;
1381 ast
->remaining
= size
;
1384 FFStream
*const sti
= ffstream(st
);
1385 uint64_t pos
= avio_tell(pb
) - 8;
1386 if (!sti
->index_entries
|| !sti
->nb_index_entries
||
1387 sti
->index_entries
[sti
->nb_index_entries
- 1].pos
< pos
) {
1388 av_add_index_entry(st
, pos
, ast
->frame_offset
, size
,
1389 0, AVINDEX_KEYFRAME
);
1402 static int ni_prepare_read(AVFormatContext
*s
)
1404 AVIContext
*avi
= s
->priv_data
;
1405 int best_stream_index
= 0;
1406 AVStream
*best_st
= NULL
;
1408 AVIStream
*best_ast
;
1409 int64_t best_ts
= INT64_MAX
;
1412 for (i
= 0; i
< s
->nb_streams
; i
++) {
1413 AVStream
*st
= s
->streams
[i
];
1414 FFStream
*const sti
= ffstream(st
);
1415 AVIStream
*ast
= st
->priv_data
;
1416 int64_t ts
= ast
->frame_offset
;
1419 if (!sti
->nb_index_entries
)
1422 last_ts
= sti
->index_entries
[sti
->nb_index_entries
- 1].timestamp
;
1423 if (!ast
->remaining
&& ts
> last_ts
)
1426 ts
= av_rescale_q(ts
, st
->time_base
,
1427 (AVRational
) { FFMAX(1, ast
->sample_size
),
1430 av_log(s
, AV_LOG_TRACE
, "%"PRId64
" %d/%d %"PRId64
"\n", ts
,
1431 st
->time_base
.num
, st
->time_base
.den
, ast
->frame_offset
);
1435 best_stream_index
= i
;
1441 best_sti
= ffstream(best_st
);
1442 best_ast
= best_st
->priv_data
;
1443 best_ts
= best_ast
->frame_offset
;
1444 if (best_ast
->remaining
) {
1445 i
= av_index_search_timestamp(best_st
,
1448 AVSEEK_FLAG_BACKWARD
);
1450 i
= av_index_search_timestamp(best_st
, best_ts
, AVSEEK_FLAG_ANY
);
1452 best_ast
->frame_offset
= best_sti
->index_entries
[i
].timestamp
;
1456 int64_t pos
= best_sti
->index_entries
[i
].pos
;
1457 pos
+= best_ast
->packet_size
- best_ast
->remaining
;
1458 if (avio_seek(s
->pb
, pos
+ 8, SEEK_SET
) < 0)
1461 av_assert0(best_ast
->remaining
<= best_ast
->packet_size
);
1463 avi
->stream_index
= best_stream_index
;
1464 if (!best_ast
->remaining
)
1465 best_ast
->packet_size
=
1466 best_ast
->remaining
= best_sti
->index_entries
[i
].size
;
1474 static int avi_read_packet(AVFormatContext
*s
, AVPacket
*pkt
)
1476 AVIContext
*avi
= s
->priv_data
;
1477 AVIOContext
*pb
= s
->pb
;
1480 if (CONFIG_DV_DEMUXER
&& avi
->dv_demux
) {
1481 int size
= avpriv_dv_get_packet(avi
->dv_demux
, pkt
);
1488 if (avi
->non_interleaved
) {
1489 err
= ni_prepare_read(s
);
1495 if (avi
->stream_index
>= 0) {
1496 AVStream
*st
= s
->streams
[avi
->stream_index
];
1497 FFStream
*const sti
= ffstream(st
);
1498 AVIStream
*ast
= st
->priv_data
;
1499 int dv_demux
= CONFIG_DV_DEMUXER
&& avi
->dv_demux
;
1502 if (get_subtitle_pkt(s
, st
, pkt
))
1505 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1506 if (ast
->sample_size
<= 1)
1508 else if (ast
->sample_size
< 32)
1509 // arbitrary multiplier to avoid tiny packets for raw PCM data
1510 size
= 1024 * ast
->sample_size
;
1512 size
= ast
->sample_size
;
1514 if (size
> ast
->remaining
)
1515 size
= ast
->remaining
;
1516 avi
->last_pkt_pos
= avio_tell(pb
);
1517 err
= av_get_packet(pb
, pkt
, size
);
1522 if (ast
->has_pal
&& pkt
->size
< (unsigned)INT_MAX
/ 2 && !dv_demux
) {
1524 pal
= av_packet_new_side_data(pkt
,
1525 AV_PKT_DATA_PALETTE
,
1528 av_log(s
, AV_LOG_ERROR
,
1529 "Failed to allocate data for palette\n");
1531 memcpy(pal
, ast
->pal
, AVPALETTE_SIZE
);
1536 if (CONFIG_DV_DEMUXER
&& dv_demux
) {
1537 size
= avpriv_dv_produce_packet(avi
->dv_demux
, pkt
,
1538 pkt
->data
, pkt
->size
, pkt
->pos
);
1539 pkt
->flags
|= AV_PKT_FLAG_KEY
;
1541 av_packet_unref(pkt
);
1542 } else if (st
->codecpar
->codec_type
== AVMEDIA_TYPE_SUBTITLE
&&
1543 !st
->codecpar
->codec_tag
&& read_gab2_sub(s
, st
, pkt
)) {
1544 ast
->frame_offset
++;
1545 avi
->stream_index
= -1;
1549 /* XXX: How to handle B-frames in AVI? */
1550 pkt
->dts
= ast
->frame_offset
;
1551 // pkt->dts += ast->start;
1552 if (ast
->sample_size
)
1553 pkt
->dts
/= ast
->sample_size
;
1554 pkt
->stream_index
= avi
->stream_index
;
1556 if (st
->codecpar
->codec_type
== AVMEDIA_TYPE_VIDEO
&& sti
->index_entries
) {
1560 index
= av_index_search_timestamp(st
, ast
->frame_offset
, AVSEEK_FLAG_ANY
);
1561 e
= &sti
->index_entries
[index
];
1563 if (index
>= 0 && e
->timestamp
== ast
->frame_offset
) {
1564 if (index
== sti
->nb_index_entries
-1) {
1567 if (st
->codecpar
->codec_id
== AV_CODEC_ID_MPEG4
) {
1568 const uint8_t *ptr
= pkt
->data
, *end
= ptr
+ FFMIN(size
, 256);
1570 ptr
= avpriv_find_start_code(ptr
, end
, &state
);
1571 if (state
== 0x1B6 && ptr
< end
) {
1572 key
= !(*ptr
& 0xC0);
1578 e
->flags
&= ~AVINDEX_KEYFRAME
;
1580 if (e
->flags
& AVINDEX_KEYFRAME
)
1581 pkt
->flags
|= AV_PKT_FLAG_KEY
;
1584 pkt
->flags
|= AV_PKT_FLAG_KEY
;
1586 ast
->frame_offset
+= get_duration(ast
, pkt
->size
);
1588 ast
->remaining
-= err
;
1589 if (!ast
->remaining
) {
1590 avi
->stream_index
= -1;
1591 ast
->packet_size
= 0;
1594 if (!avi
->non_interleaved
&& pkt
->pos
>= 0 && ast
->seek_pos
> pkt
->pos
) {
1595 av_packet_unref(pkt
);
1600 if (!avi
->non_interleaved
&& sti
->nb_index_entries
> 1 && avi
->index_loaded
> 1) {
1601 int64_t dts
= av_rescale_q(pkt
->dts
, st
->time_base
, AV_TIME_BASE_Q
);
1603 if (avi
->dts_max
< dts
) {
1605 } else if (avi
->dts_max
- (uint64_t)dts
> 2*AV_TIME_BASE
) {
1606 avi
->non_interleaved
= 1;
1607 av_log(s
, AV_LOG_INFO
, "Switching to NI mode, due to poor interleaving\n");
1614 if ((err
= avi_sync(s
, 0)) < 0)
1619 /* XXX: We make the implicit supposition that the positions are sorted
1620 * for each stream. */
1621 static int avi_read_idx1(AVFormatContext
*s
, int size
)
1623 AVIContext
*avi
= s
->priv_data
;
1624 AVIOContext
*pb
= s
->pb
;
1625 int nb_index_entries
, i
;
1629 unsigned int index
, tag
, flags
, len
, first_packet
= 1;
1630 int64_t last_pos
= -1;
1631 unsigned last_idx
= -1;
1632 int64_t idx1_pos
, first_packet_pos
= 0, data_offset
= 0;
1635 nb_index_entries
= size
/ 16;
1636 if (nb_index_entries
<= 0)
1637 return AVERROR_INVALIDDATA
;
1639 idx1_pos
= avio_tell(pb
);
1640 avio_seek(pb
, avi
->movi_list
+ 4, SEEK_SET
);
1641 if (avi_sync(s
, 1) == 0)
1642 first_packet_pos
= avio_tell(pb
) - 8;
1643 avi
->stream_index
= -1;
1644 avio_seek(pb
, idx1_pos
, SEEK_SET
);
1646 if (s
->nb_streams
== 1 && s
->streams
[0]->codecpar
->codec_tag
== AV_RL32("MMES")) {
1647 first_packet_pos
= 0;
1648 data_offset
= avi
->movi_list
;
1651 /* Read the entries and sort them in each stream component. */
1652 for (i
= 0; i
< nb_index_entries
; i
++) {
1656 tag
= avio_rl32(pb
);
1657 flags
= avio_rl32(pb
);
1658 pos
= avio_rl32(pb
);
1659 len
= avio_rl32(pb
);
1660 av_log(s
, AV_LOG_TRACE
, "%d: tag=0x%x flags=0x%x pos=0x%"PRIx64
" len=%d/",
1661 i
, tag
, flags
, pos
, len
);
1663 index
= ((tag
& 0xff) - '0') * 10;
1664 index
+= (tag
>> 8 & 0xff) - '0';
1665 if (index
>= s
->nb_streams
)
1667 st
= s
->streams
[index
];
1668 ast
= st
->priv_data
;
1670 /* Skip 'xxpc' palette change entries in the index until a logic
1671 * to process these is properly implemented. */
1672 if ((tag
>> 16 & 0xff) == 'p' && (tag
>> 24 & 0xff) == 'c')
1675 if (first_packet
&& first_packet_pos
) {
1676 if (avi
->movi_list
+ 4 != pos
|| pos
+ 500 > first_packet_pos
)
1677 data_offset
= first_packet_pos
- pos
;
1682 av_log(s
, AV_LOG_TRACE
, "%d cum_len=%"PRId64
"\n", len
, ast
->cum_len
);
1684 // even if we have only a single stream, we should
1685 // switch to non-interleaved to get correct timestamps
1686 if (last_pos
== pos
)
1687 avi
->non_interleaved
= 1;
1688 if (last_idx
!= pos
&& len
) {
1689 av_add_index_entry(st
, pos
, ast
->cum_len
, len
, 0,
1690 (flags
& AVIIF_INDEX
) ? AVINDEX_KEYFRAME
: 0);
1693 ast
->cum_len
+= get_duration(ast
, len
);
1695 anykey
|= flags
&AVIIF_INDEX
;
1698 for (index
= 0; index
< s
->nb_streams
; index
++) {
1699 FFStream
*const sti
= ffstream(s
->streams
[index
]);
1700 if (sti
->nb_index_entries
)
1701 sti
->index_entries
[0].flags
|= AVINDEX_KEYFRAME
;
1707 /* Scan the index and consider any file with streams more than
1708 * 2 seconds or 64MB apart non-interleaved. */
1709 static int check_stream_max_drift(AVFormatContext
*s
)
1711 int64_t min_pos
, pos
;
1713 int *idx
= av_calloc(s
->nb_streams
, sizeof(*idx
));
1715 return AVERROR(ENOMEM
);
1716 for (min_pos
= pos
= 0; min_pos
!= INT64_MAX
; pos
= min_pos
+ 1ULL) {
1717 int64_t max_dts
= INT64_MIN
/ 2;
1718 int64_t min_dts
= INT64_MAX
/ 2;
1719 int64_t max_buffer
= 0;
1721 min_pos
= INT64_MAX
;
1723 for (i
= 0; i
< s
->nb_streams
; i
++) {
1724 AVStream
*st
= s
->streams
[i
];
1725 AVIStream
*ast
= st
->priv_data
;
1726 FFStream
*const sti
= ffstream(st
);
1727 int n
= sti
->nb_index_entries
;
1728 while (idx
[i
] < n
&& sti
->index_entries
[idx
[i
]].pos
< pos
)
1732 dts
= av_rescale_q(sti
->index_entries
[idx
[i
]].timestamp
/
1733 FFMAX(ast
->sample_size
, 1),
1734 st
->time_base
, AV_TIME_BASE_Q
);
1735 min_dts
= FFMIN(min_dts
, dts
);
1736 min_pos
= FFMIN(min_pos
, sti
->index_entries
[idx
[i
]].pos
);
1739 for (i
= 0; i
< s
->nb_streams
; i
++) {
1740 AVStream
*st
= s
->streams
[i
];
1741 FFStream
*const sti
= ffstream(st
);
1742 AVIStream
*ast
= st
->priv_data
;
1744 if (idx
[i
] && min_dts
!= INT64_MAX
/ 2) {
1745 int64_t dts
, delta_dts
;
1746 dts
= av_rescale_q(sti
->index_entries
[idx
[i
] - 1].timestamp
/
1747 FFMAX(ast
->sample_size
, 1),
1748 st
->time_base
, AV_TIME_BASE_Q
);
1749 delta_dts
= av_sat_sub64(dts
, min_dts
);
1750 max_dts
= FFMAX(max_dts
, dts
);
1751 max_buffer
= FFMAX(max_buffer
,
1752 av_rescale(delta_dts
,
1753 st
->codecpar
->bit_rate
,
1757 if (av_sat_sub64(max_dts
, min_dts
) > 2 * AV_TIME_BASE
||
1758 max_buffer
> 1024 * 1024 * 8 * 8) {
1767 static int guess_ni_flag(AVFormatContext
*s
)
1770 int64_t last_start
= 0;
1771 int64_t first_end
= INT64_MAX
;
1772 int64_t oldpos
= avio_tell(s
->pb
);
1774 for (i
= 0; i
< s
->nb_streams
; i
++) {
1775 AVStream
*st
= s
->streams
[i
];
1776 FFStream
*const sti
= ffstream(st
);
1777 int n
= sti
->nb_index_entries
;
1784 int64_t pos
= sti
->index_entries
[0].pos
;
1786 avio_seek(s
->pb
, pos
, SEEK_SET
);
1787 tag
[0] = avio_r8(s
->pb
);
1788 tag
[1] = avio_r8(s
->pb
);
1790 size
= avio_rl32(s
->pb
);
1791 if (get_stream_idx(tag
) == i
&& pos
+ size
> sti
->index_entries
[1].pos
)
1792 last_start
= INT64_MAX
;
1793 if (get_stream_idx(tag
) == i
&& size
== sti
->index_entries
[0].size
+ 8)
1794 last_start
= INT64_MAX
;
1797 if (sti
->index_entries
[0].pos
> last_start
)
1798 last_start
= sti
->index_entries
[0].pos
;
1799 if (sti
->index_entries
[n
- 1].pos
< first_end
)
1800 first_end
= sti
->index_entries
[n
- 1].pos
;
1802 avio_seek(s
->pb
, oldpos
, SEEK_SET
);
1804 if (last_start
> first_end
)
1807 return check_stream_max_drift(s
);
1810 static int avi_load_index(AVFormatContext
*s
)
1812 AVIContext
*avi
= s
->priv_data
;
1813 AVIOContext
*pb
= s
->pb
;
1815 int64_t pos
= avio_tell(pb
);
1819 if (avio_seek(pb
, avi
->movi_end
, SEEK_SET
) < 0)
1820 goto the_end
; // maybe truncated file
1821 av_log(s
, AV_LOG_TRACE
, "movi_end=0x%"PRIx64
"\n", avi
->movi_end
);
1823 tag
= avio_rl32(pb
);
1824 size
= avio_rl32(pb
);
1827 next
= avio_tell(pb
);
1828 if (next
< 0 || next
> INT64_MAX
- size
- (size
& 1))
1830 next
+= size
+ (size
& 1LL);
1832 if (tag
== MKTAG('i', 'd', 'x', '1') &&
1833 avi_read_idx1(s
, size
) >= 0) {
1834 avi
->index_loaded
=2;
1836 }else if (tag
== MKTAG('L', 'I', 'S', 'T')) {
1837 uint32_t tag1
= avio_rl32(pb
);
1839 if (tag1
== MKTAG('I', 'N', 'F', 'O'))
1840 ff_read_riff_info(s
, size
- 4);
1844 if (avio_seek(pb
, next
, SEEK_SET
) < 0)
1845 break; // something is wrong here
1849 avio_seek(pb
, pos
, SEEK_SET
);
1853 static void seek_subtitle(AVStream
*st
, AVStream
*st2
, int64_t timestamp
)
1855 AVIStream
*ast2
= st2
->priv_data
;
1856 int64_t ts2
= av_rescale_q(timestamp
, st
->time_base
, st2
->time_base
);
1857 av_packet_unref(ast2
->sub_pkt
);
1858 if (avformat_seek_file(ast2
->sub_ctx
, 0, INT64_MIN
, ts2
, ts2
, 0) >= 0 ||
1859 avformat_seek_file(ast2
->sub_ctx
, 0, ts2
, ts2
, INT64_MAX
, 0) >= 0)
1860 ff_read_packet(ast2
->sub_ctx
, ast2
->sub_pkt
);
1863 static int avi_read_seek(AVFormatContext
*s
, int stream_index
,
1864 int64_t timestamp
, int flags
)
1866 AVIContext
*avi
= s
->priv_data
;
1870 int64_t pos
, pos_min
;
1873 /* Does not matter which stream is requested dv in avi has the
1874 * stream information in the first video stream.
1879 if (!avi
->index_loaded
) {
1880 /* we only load the index on demand */
1882 avi
->index_loaded
|= 1;
1884 av_assert0(stream_index
>= 0);
1886 st
= s
->streams
[stream_index
];
1888 ast
= st
->priv_data
;
1890 if (avi
->dv_demux
) {
1891 // index entries are in the AVI scale/rate timebase, which does
1892 // not match DV demuxer's stream timebase
1893 timestamp
= av_rescale_q(timestamp
, st
->time_base
,
1894 (AVRational
){ ast
->scale
, ast
->rate
});
1896 timestamp
*= FFMAX(ast
->sample_size
, 1);
1898 index
= av_index_search_timestamp(st
, timestamp
, flags
);
1900 if (sti
->nb_index_entries
> 0)
1901 av_log(s
, AV_LOG_DEBUG
, "Failed to find timestamp %"PRId64
" in index %"PRId64
" .. %"PRId64
"\n",
1903 sti
->index_entries
[0].timestamp
,
1904 sti
->index_entries
[sti
->nb_index_entries
- 1].timestamp
);
1905 return AVERROR_INVALIDDATA
;
1908 /* find the position */
1909 pos
= sti
->index_entries
[index
].pos
;
1910 timestamp
= sti
->index_entries
[index
].timestamp
;
1912 av_log(s
, AV_LOG_TRACE
, "XX %"PRId64
" %d %"PRId64
"\n",
1913 timestamp
, index
, sti
->index_entries
[index
].timestamp
);
1915 if (CONFIG_DV_DEMUXER
&& avi
->dv_demux
) {
1916 /* One and only one real stream for DV in AVI, and it has video */
1917 /* offsets. Calling with other stream indexes should have failed */
1918 /* the av_index_search_timestamp call above. */
1920 if (avio_seek(s
->pb
, pos
, SEEK_SET
) < 0)
1923 /* Feed the DV video stream version of the timestamp to the */
1924 /* DV demux so it can synthesize correct timestamps. */
1925 ff_dv_ts_reset(avi
->dv_demux
,
1926 av_rescale_q(timestamp
, (AVRational
){ ast
->scale
, ast
->rate
},
1929 avi
->stream_index
= -1;
1932 timestamp
/= FFMAX(ast
->sample_size
, 1);
1935 for (i
= 0; i
< s
->nb_streams
; i
++) {
1936 AVStream
*st2
= s
->streams
[i
];
1937 FFStream
*const sti2
= ffstream(st2
);
1938 AVIStream
*ast2
= st2
->priv_data
;
1941 ast2
->remaining
= 0;
1943 if (ast2
->sub_ctx
) {
1944 seek_subtitle(st
, st2
, timestamp
);
1948 if (sti2
->nb_index_entries
<= 0)
1951 // av_assert1(st2->codecpar->block_align);
1952 index
= av_index_search_timestamp(st2
,
1953 av_rescale_q(timestamp
,
1956 FFMAX(ast2
->sample_size
, 1),
1958 AVSEEK_FLAG_BACKWARD
|
1959 (st2
->codecpar
->codec_type
!= AVMEDIA_TYPE_VIDEO
? AVSEEK_FLAG_ANY
: 0));
1962 ast2
->seek_pos
= sti2
->index_entries
[index
].pos
;
1963 pos_min
= FFMIN(pos_min
,ast2
->seek_pos
);
1965 for (i
= 0; i
< s
->nb_streams
; i
++) {
1966 AVStream
*st2
= s
->streams
[i
];
1967 FFStream
*const sti2
= ffstream(st2
);
1968 AVIStream
*ast2
= st2
->priv_data
;
1970 if (ast2
->sub_ctx
|| sti2
->nb_index_entries
<= 0)
1973 index
= av_index_search_timestamp(
1975 av_rescale_q(timestamp
, st
->time_base
, st2
->time_base
) * FFMAX(ast2
->sample_size
, 1),
1976 flags
| AVSEEK_FLAG_BACKWARD
| (st2
->codecpar
->codec_type
!= AVMEDIA_TYPE_VIDEO
? AVSEEK_FLAG_ANY
: 0));
1979 while (!avi
->non_interleaved
&& index
> 0 && sti2
->index_entries
[index
-1].pos
>= pos_min
)
1981 ast2
->frame_offset
= sti2
->index_entries
[index
].timestamp
;
1985 if (avio_seek(s
->pb
, pos_min
, SEEK_SET
) < 0) {
1986 av_log(s
, AV_LOG_ERROR
, "Seek failed\n");
1989 avi
->stream_index
= -1;
1990 avi
->dts_max
= INT_MIN
;
1994 static int avi_read_close(AVFormatContext
*s
)
1997 AVIContext
*avi
= s
->priv_data
;
1999 for (i
= 0; i
< s
->nb_streams
; i
++) {
2000 AVStream
*st
= s
->streams
[i
];
2001 AVIStream
*ast
= st
->priv_data
;
2004 av_freep(&ast
->sub_ctx
->pb
);
2005 avformat_close_input(&ast
->sub_ctx
);
2007 av_buffer_unref(&ast
->sub_buffer
);
2008 av_packet_free(&ast
->sub_pkt
);
2012 av_freep(&avi
->dv_demux
);
2017 static int avi_probe(const AVProbeData
*p
)
2021 /* check file header */
2022 for (i
= 0; avi_headers
[i
][0]; i
++)
2023 if (AV_RL32(p
->buf
) == AV_RL32(avi_headers
[i
] ) &&
2024 AV_RL32(p
->buf
+ 8) == AV_RL32(avi_headers
[i
] + 4))
2025 return AVPROBE_SCORE_MAX
;
2030 const FFInputFormat ff_avi_demuxer
= {
2032 .p
.long_name
= NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
2033 .p
.extensions
= "avi",
2034 .p
.priv_class
= &demuxer_class
,
2035 .priv_data_size
= sizeof(AVIContext
),
2036 .flags_internal
= FF_INFMT_FLAG_INIT_CLEANUP
,
2037 .read_probe
= avi_probe
,
2038 .read_header
= avi_read_header
,
2039 .read_packet
= avi_read_packet
,
2040 .read_close
= avi_read_close
,
2041 .read_seek
= avi_read_seek
,