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 "libavutil/intreadwrite.h"
23 #include "libavutil/mathematics.h"
24 #include "libavutil/bswap.h"
25 #include "libavutil/opt.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/avstring.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) (in the rate/scale sense) in bytes */
47 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 the MS dshow demuxer
55 AVFormatContext *sub_ctx;
73 DVDemuxContext* dv_demux;
76 #define MAX_ODML_DEPTH 1000
81 static const AVOption options[] = {
82 { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_INT, {.dbl = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
86 static const AVClass demuxer_class = {
90 LIBAVUTIL_VERSION_INT,
94 static const char avi_headers[][8] = {
95 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
96 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
97 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
98 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
99 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
103 static const AVMetadataConv avi_metadata_conv[] = {
108 static int avi_load_index(AVFormatContext *s);
109 static int guess_ni_flag(AVFormatContext *s);
111 #define print_tag(str, tag, size) \
112 av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
115 (tag >> 16) & 0xff, \
116 (tag >> 24) & 0xff, \
119 static inline int get_duration(AVIStream *ast, int len){
120 if(ast->sample_size){
122 }else if (ast->dshow_block_align){
123 return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
128 static int get_riff(AVFormatContext *s, AVIOContext *pb)
130 AVIContext *avi = s->priv_data;
134 /* check RIFF header */
135 avio_read(pb, header, 4);
136 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
137 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
138 avio_read(pb, header+4, 4);
140 for(i=0; avi_headers[i][0]; i++)
141 if(!memcmp(header, avi_headers[i], 8))
143 if(!avi_headers[i][0])
146 if(header[7] == 0x19)
147 av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
152 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
153 AVIContext *avi = s->priv_data;
154 AVIOContext *pb = s->pb;
155 int longs_pre_entry= avio_rl16(pb);
156 int index_sub_type = avio_r8(pb);
157 int index_type = avio_r8(pb);
158 int entries_in_use = avio_rl32(pb);
159 int chunk_id = avio_rl32(pb);
160 int64_t base = avio_rl64(pb);
161 int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
165 int64_t last_pos= -1;
166 int64_t filesize= avi->fsize;
168 av_dlog(s, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
169 longs_pre_entry,index_type, entries_in_use, chunk_id, base);
171 if(stream_id >= s->nb_streams || stream_id < 0)
173 st= s->streams[stream_id];
181 if(index_type && longs_pre_entry != 2)
186 if(filesize > 0 && base >= filesize){
187 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
188 if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
194 for(i=0; i<entries_in_use; i++){
196 int64_t pos= avio_rl32(pb) + base - 8;
197 int len = avio_rl32(pb);
202 av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
207 if(last_pos == pos || pos == base - 8)
208 avi->non_interleaved= 1;
209 if(last_pos != pos && (len || !ast->sample_size))
210 av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
212 ast->cum_len += get_duration(ast, len);
217 offset = avio_rl64(pb);
218 avio_rl32(pb); /* size */
219 duration = avio_rl32(pb);
226 if(avi->odml_depth > MAX_ODML_DEPTH){
227 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
231 if(avio_seek(pb, offset+8, SEEK_SET) < 0)
234 read_braindead_odml_indx(s, frame_num);
236 frame_num += duration;
238 if(avio_seek(pb, pos, SEEK_SET) < 0) {
239 av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index");
249 static void clean_index(AVFormatContext *s){
253 for(i=0; i<s->nb_streams; i++){
254 AVStream *st = s->streams[i];
255 AVIStream *ast = st->priv_data;
256 int n= st->nb_index_entries;
257 int max= ast->sample_size;
258 int64_t pos, size, ts;
260 if(n != 1 || ast->sample_size==0)
263 while(max < 1024) max+=max;
265 pos= st->index_entries[0].pos;
266 size= st->index_entries[0].size;
267 ts= st->index_entries[0].timestamp;
269 for(j=0; j<size; j+=max){
270 av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
275 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
277 AVIOContext *pb = s->pb;
278 char key[5] = {0}, *value;
282 if (size == UINT_MAX)
284 value = av_malloc(size+1);
287 avio_read(pb, value, size);
292 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
293 AV_DICT_DONT_STRDUP_VAL);
296 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
297 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
299 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
301 char month[4], time[9], buffer[64];
303 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
304 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
305 month, &day, time, &year) == 4) {
307 if (!av_strcasecmp(month, months[i])) {
308 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
309 year, i+1, day, time);
310 av_dict_set(metadata, "creation_time", buffer, 0);
312 } else if (date[4] == '/' && date[7] == '/') {
313 date[4] = date[7] = '-';
314 av_dict_set(metadata, "creation_time", date, 0);
318 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
320 while (avio_tell(s->pb) < end) {
321 uint32_t tag = avio_rl32(s->pb);
322 uint32_t size = avio_rl32(s->pb);
324 case MKTAG('n', 'c', 't', 'g'): { /* Nikon Tags */
325 uint64_t tag_end = avio_tell(s->pb) + size;
326 while (avio_tell(s->pb) < tag_end) {
327 uint16_t tag = avio_rl16(s->pb);
328 uint16_t size = avio_rl16(s->pb);
329 const char *name = NULL;
330 char buffer[64] = {0};
331 size -= avio_read(s->pb, buffer,
332 FFMIN(size, sizeof(buffer)-1));
334 case 0x03: name = "maker"; break;
335 case 0x04: name = "model"; break;
336 case 0x13: name = "creation_time";
337 if (buffer[4] == ':' && buffer[7] == ':')
338 buffer[4] = buffer[7] = '-';
342 av_dict_set(&s->metadata, name, buffer, 0);
343 avio_skip(s->pb, size);
348 avio_skip(s->pb, size);
354 static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
356 AVIContext *avi = s->priv_data;
357 AVIOContext *pb = s->pb;
358 unsigned int tag, tag1, handler;
359 int codec_type, stream_index, frame_period;
363 AVIStream *ast = NULL;
364 int avih_width=0, avih_height=0;
365 int amv_file_format=0;
366 uint64_t list_end = 0;
369 avi->stream_index= -1;
371 if (get_riff(s, pb) < 0)
374 av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
376 avi->fsize = avio_size(pb);
377 if(avi->fsize<=0 || avi->fsize < avi->riff_end)
378 avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
388 size = avio_rl32(pb);
390 if(size > avi->fsize){
391 av_log(s, AV_LOG_ERROR, "chunk size is too big during header parsing\n");
395 print_tag("tag", tag, size);
398 case MKTAG('L', 'I', 'S', 'T'):
399 list_end = avio_tell(pb) + size;
400 /* Ignored, except at start of video packets. */
401 tag1 = avio_rl32(pb);
403 print_tag("list", tag1, 0);
405 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
406 avi->movi_list = avio_tell(pb) - 4;
407 if(size) avi->movi_end = avi->movi_list + size + (size & 1);
408 else avi->movi_end = avi->fsize;
409 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
412 else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
413 ff_read_riff_info(s, size - 4);
414 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
415 avi_read_nikon(s, list_end);
418 case MKTAG('I', 'D', 'I', 'T'): {
419 unsigned char date[64] = {0};
421 size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
423 avi_metadata_creation_time(&s->metadata, date);
426 case MKTAG('d', 'm', 'l', 'h'):
428 avio_skip(pb, size + (size & 1));
430 case MKTAG('a', 'm', 'v', 'h'):
432 case MKTAG('a', 'v', 'i', 'h'):
434 /* using frame_period is bad idea */
435 frame_period = avio_rl32(pb);
436 avio_rl32(pb); /* max. bytes per second */
438 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
440 avio_skip(pb, 2 * 4);
443 avih_width=avio_rl32(pb);
444 avih_height=avio_rl32(pb);
446 avio_skip(pb, size - 10 * 4);
448 case MKTAG('s', 't', 'r', 'h'):
451 tag1 = avio_rl32(pb);
452 handler = avio_rl32(pb); /* codec tag */
454 if(tag1 == MKTAG('p', 'a', 'd', 's')){
455 avio_skip(pb, size - 8);
459 st = avformat_new_stream(s, NULL);
463 st->id = stream_index;
464 ast = av_mallocz(sizeof(AVIStream));
470 tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
472 print_tag("strh", tag1, -1);
474 if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
478 * After some consideration -- I don't think we
479 * have to support anything but DV in type1 AVIs.
481 if (s->nb_streams != 1)
484 if (handler != MKTAG('d', 'v', 's', 'd') &&
485 handler != MKTAG('d', 'v', 'h', 'd') &&
486 handler != MKTAG('d', 'v', 's', 'l'))
489 ast = s->streams[0]->priv_data;
490 av_freep(&s->streams[0]->codec->extradata);
491 av_freep(&s->streams[0]->codec);
492 av_freep(&s->streams[0]);
494 if (CONFIG_DV_DEMUXER) {
495 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);
511 * else, leave duration alone; timing estimation in utils.c
512 * will make a guess based on bitrate.
515 stream_index = s->nb_streams - 1;
516 avio_skip(pb, size - 9*4);
520 assert(stream_index < s->nb_streams);
521 st->codec->stream_codec_tag= handler;
523 avio_rl32(pb); /* flags */
524 avio_rl16(pb); /* priority */
525 avio_rl16(pb); /* language */
526 avio_rl32(pb); /* initial frame */
527 ast->scale = avio_rl32(pb);
528 ast->rate = avio_rl32(pb);
529 if(!(ast->scale && ast->rate)){
530 av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
533 ast->scale = frame_period;
539 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
541 ast->cum_len=avio_rl32(pb); /* start */
542 st->nb_frames = avio_rl32(pb);
545 avio_rl32(pb); /* buffer size */
546 avio_rl32(pb); /* quality */
547 if (ast->cum_len*ast->scale/ast->rate > 3600) {
548 av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
549 return AVERROR_INVALIDDATA;
551 ast->sample_size = avio_rl32(pb); /* sample ssize */
552 ast->cum_len *= FFMAX(1, ast->sample_size);
553 // av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
556 case MKTAG('v', 'i', 'd', 's'):
557 codec_type = AVMEDIA_TYPE_VIDEO;
559 ast->sample_size = 0;
561 case MKTAG('a', 'u', 'd', 's'):
562 codec_type = AVMEDIA_TYPE_AUDIO;
564 case MKTAG('t', 'x', 't', 's'):
565 codec_type = AVMEDIA_TYPE_SUBTITLE;
567 case MKTAG('d', 'a', 't', 's'):
568 codec_type = AVMEDIA_TYPE_DATA;
571 av_log(s, AV_LOG_INFO, "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'):
582 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
585 uint64_t cur_pos = avio_tell(pb);
586 if (cur_pos < list_end)
587 size = FFMIN(size, list_end - cur_pos);
588 st = s->streams[stream_index];
590 case AVMEDIA_TYPE_VIDEO:
592 st->codec->width=avih_width;
593 st->codec->height=avih_height;
594 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
595 st->codec->codec_id = CODEC_ID_AMV;
599 tag1 = ff_get_bmp_header(pb, st);
601 if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
602 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
603 st->codec->codec_tag = tag1;
604 st->codec->codec_id = CODEC_ID_XSUB;
608 if(size > 10*4 && size<(1<<30)){
609 st->codec->extradata_size= size - 10*4;
610 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
611 if (!st->codec->extradata) {
612 st->codec->extradata_size= 0;
613 return AVERROR(ENOMEM);
615 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
618 if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
621 /* Extract palette from extradata if bpp <= 8. */
622 /* This code assumes that extradata contains only palette. */
623 /* This is true for all paletted codecs implemented in FFmpeg. */
624 if (st->codec->extradata_size && (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 + st->codec->extradata_size - pal_size;
630 for (i = 0; i < pal_size/4; i++)
631 ast->pal[i] = 0xFF<<24 | AV_RL32(pal_src+4*i);
635 print_tag("video", tag1, 0);
637 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
638 st->codec->codec_tag = tag1;
639 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
640 st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
641 // Support "Resolution 1:1" for Avid AVI Codec
642 if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
643 st->codec->extradata_size >= 31 &&
644 !memcmp(&st->codec->extradata[28], "1:1", 3))
645 st->codec->codec_id = CODEC_ID_RAWVIDEO;
647 if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
648 st->codec->extradata_size+= 9;
649 st->codec->extradata= av_realloc_f(st->codec->extradata, 1, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
650 if(st->codec->extradata)
651 memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
653 st->codec->height= FFABS(st->codec->height);
655 // avio_skip(pb, size - 5 * 4);
657 case AVMEDIA_TYPE_AUDIO:
658 ret = ff_get_wav_header(pb, st->codec, size);
661 ast->dshow_block_align= st->codec->block_align;
662 if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
663 av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
664 ast->sample_size= st->codec->block_align;
666 if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
668 /* Force parsing as several audio frames can be in
669 * one packet and timestamps refer to packet start. */
670 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
671 /* ADTS header is in extradata, AAC without header must be
672 * stored as exact frames. Parser not needed and it will
674 if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
675 st->need_parsing = AVSTREAM_PARSE_NONE;
676 /* AVI files with Xan DPCM audio (wrongly) declare PCM
677 * audio in the header but have Axan as stream_code_tag. */
678 if (st->codec->stream_codec_tag == AV_RL32("Axan")){
679 st->codec->codec_id = CODEC_ID_XAN_DPCM;
680 st->codec->codec_tag = 0;
681 ast->dshow_block_align = 0;
683 if (amv_file_format){
684 st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
685 ast->dshow_block_align = 0;
688 case AVMEDIA_TYPE_SUBTITLE:
689 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
690 st->request_probe= 1;
693 st->codec->codec_type = AVMEDIA_TYPE_DATA;
694 st->codec->codec_id= CODEC_ID_NONE;
695 st->codec->codec_tag= 0;
701 case MKTAG('s', 't', 'r', 'd'):
702 if (stream_index >= (unsigned)s->nb_streams || st->codec->extradata_size) {
705 uint64_t cur_pos = avio_tell(pb);
706 if (cur_pos < list_end)
707 size = FFMIN(size, list_end - cur_pos);
708 st = s->streams[stream_index];
711 st->codec->extradata_size= size;
712 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
713 if (!st->codec->extradata) {
714 st->codec->extradata_size= 0;
715 return AVERROR(ENOMEM);
717 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
720 if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
724 case MKTAG('i', 'n', 'd', 'x'):
726 if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) && avi->use_odml &&
727 read_braindead_odml_indx(s, 0) < 0 && s->error_recognition >= FF_ER_EXPLODE){
729 avio_seek(pb, i+size, SEEK_SET);
731 case MKTAG('v', 'p', 'r', 'p'):
732 if(stream_index < (unsigned)s->nb_streams && size > 9*4){
733 AVRational active, active_aspect;
735 st = s->streams[stream_index];
742 active_aspect.den= avio_rl16(pb);
743 active_aspect.num= avio_rl16(pb);
744 active.num = avio_rl32(pb);
745 active.den = avio_rl32(pb);
746 avio_rl32(pb); //nbFieldsPerFrame
748 if(active_aspect.num && active_aspect.den && active.num && active.den){
749 st->sample_aspect_ratio= av_div_q(active_aspect, active);
750 //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
756 case MKTAG('s', 't', 'r', 'n'):
758 avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
763 av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
764 "I will ignore it and try to continue anyway.\n");
765 if (s->error_recognition >= FF_ER_EXPLODE) goto fail;
766 avi->movi_list = avio_tell(pb) - 4;
767 avi->movi_end = avi->fsize;
777 /* check stream number */
778 if (stream_index != s->nb_streams - 1) {
783 if(!avi->index_loaded && pb->seekable)
785 avi->index_loaded |= 1;
786 avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
787 for(i=0; i<s->nb_streams; i++){
788 AVStream *st = s->streams[i];
789 if(st->nb_index_entries)
792 // DV-in-AVI cannot be non-interleaved, if set this must be
795 avi->non_interleaved=0;
796 if(i==s->nb_streams && avi->non_interleaved) {
797 av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
798 avi->non_interleaved=0;
801 if(avi->non_interleaved) {
802 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
806 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
807 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
812 static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
813 if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
815 int score = AVPROBE_SCORE_MAX / 2, ret;
816 AVIStream *ast = st->priv_data;
817 AVInputFormat *sub_demuxer;
818 AVRational time_base;
819 AVIOContext *pb = avio_alloc_context( pkt->data + 7,
821 0, NULL, NULL, NULL, NULL);
823 unsigned int desc_len = avio_rl32(pb);
825 if (desc_len > pb->buf_end - pb->buf_ptr)
828 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
829 avio_skip(pb, desc_len - ret);
831 av_dict_set(&st->metadata, "title", desc, 0);
833 avio_rl16(pb); /* flags? */
834 avio_rl32(pb); /* data size */
836 pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
837 if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
840 if (!(ast->sub_ctx = avformat_alloc_context()))
843 ast->sub_ctx->pb = pb;
844 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
845 av_read_packet(ast->sub_ctx, &ast->sub_pkt);
846 *st->codec = *ast->sub_ctx->streams[0]->codec;
847 ast->sub_ctx->streams[0]->codec->extradata = NULL;
848 time_base = ast->sub_ctx->streams[0]->time_base;
849 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
851 ast->sub_buffer = pkt->data;
852 memset(pkt, 0, sizeof(*pkt));
860 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
863 AVIStream *ast, *next_ast = next_st->priv_data;
864 int64_t ts, next_ts, ts_min = INT64_MAX;
865 AVStream *st, *sub_st = NULL;
868 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
871 for (i=0; i<s->nb_streams; i++) {
874 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
875 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
876 if (ts <= next_ts && ts < ts_min) {
884 ast = sub_st->priv_data;
886 pkt->stream_index = sub_st->index;
887 if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
888 ast->sub_pkt.data = NULL;
893 static int get_stream_idx(int *d){
894 if( d[0] >= '0' && d[0] <= '9'
895 && d[1] >= '0' && d[1] <= '9'){
896 return (d[0] - '0') * 10 + (d[1] - '0');
898 return 100; //invalid stream ID
902 static int avi_sync(AVFormatContext *s, int exit_early)
904 AVIContext *avi = s->priv_data;
905 AVIOContext *pb = s->pb;
912 memset(d, -1, sizeof(d));
913 for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
920 size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
922 n= get_stream_idx(d+2);
923 //av_log(s, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
924 if(i + (uint64_t)size > avi->fsize || d[0] > 127)
928 if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
930 ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
931 ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
933 //av_log(s, AV_LOG_DEBUG, "SKIP\n");
938 if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
943 n= get_stream_idx(d);
945 if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
948 //detect ##ix chunk and skip
949 if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
955 if(n < s->nb_streams){
961 if(s->nb_streams>=2){
962 AVStream *st1 = s->streams[1];
963 AVIStream *ast1= st1->priv_data;
964 //workaround for broken small-file-bug402.avi
965 if( d[2] == 'w' && d[3] == 'b'
967 && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
968 && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
969 && ast->prefix == 'd'*256+'c'
970 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
975 av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
980 if( (st->discard >= AVDISCARD_DEFAULT && size==0)
981 /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
982 || st->discard >= AVDISCARD_ALL){
984 ast->frame_offset += get_duration(ast, size);
990 if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
992 int last = (k + avio_r8(pb) - 1) & 0xFF;
994 avio_rl16(pb); //flags
996 for (; k <= last; k++)
997 ast->pal[k] = 0xFF<<24 | avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
1000 } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
1001 d[2]*256+d[3] == ast->prefix /*||
1002 (d[2] == 'd' && d[3] == 'c') ||
1003 (d[2] == 'w' && d[3] == 'b')*/) {
1007 //av_log(s, AV_LOG_DEBUG, "OK\n");
1008 if(d[2]*256+d[3] == ast->prefix)
1009 ast->prefix_count++;
1011 ast->prefix= d[2]*256+d[3];
1012 ast->prefix_count= 0;
1015 avi->stream_index= n;
1016 ast->packet_size= size + 8;
1017 ast->remaining= size;
1019 if(size || !ast->sample_size){
1020 uint64_t pos= avio_tell(pb) - 8;
1021 if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
1022 av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
1035 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1037 AVIContext *avi = s->priv_data;
1038 AVIOContext *pb = s->pb;
1042 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1043 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1048 if(avi->non_interleaved){
1049 int best_stream_index = 0;
1050 AVStream *best_st= NULL;
1051 AVIStream *best_ast;
1052 int64_t best_ts= INT64_MAX;
1055 for(i=0; i<s->nb_streams; i++){
1056 AVStream *st = s->streams[i];
1057 AVIStream *ast = st->priv_data;
1058 int64_t ts= ast->frame_offset;
1061 if(!st->nb_index_entries)
1064 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1065 if(!ast->remaining && ts > last_ts)
1068 ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
1070 // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
1074 best_stream_index= i;
1080 best_ast = best_st->priv_data;
1081 best_ts = best_ast->frame_offset;
1082 if(best_ast->remaining)
1083 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
1085 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1087 best_ast->frame_offset= best_st->index_entries[i].timestamp;
1090 // av_log(s, AV_LOG_DEBUG, "%d\n", i);
1092 int64_t pos= best_st->index_entries[i].pos;
1093 pos += best_ast->packet_size - best_ast->remaining;
1094 if(avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
1096 // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
1098 assert(best_ast->remaining <= best_ast->packet_size);
1100 avi->stream_index= best_stream_index;
1101 if(!best_ast->remaining)
1102 best_ast->packet_size=
1103 best_ast->remaining= best_st->index_entries[i].size;
1110 if(avi->stream_index >= 0){
1111 AVStream *st= s->streams[ avi->stream_index ];
1112 AVIStream *ast= st->priv_data;
1115 if(get_subtitle_pkt(s, st, pkt))
1118 if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1120 else if(ast->sample_size < 32)
1121 // arbitrary multiplier to avoid tiny packets for raw PCM data
1122 size= 1024*ast->sample_size;
1124 size= ast->sample_size;
1126 if(size > ast->remaining)
1127 size= ast->remaining;
1128 avi->last_pkt_pos= avio_tell(pb);
1129 err= av_get_packet(pb, pkt, size);
1133 if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
1135 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
1137 av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
1139 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1144 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1145 dstr = pkt->destruct;
1146 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1147 pkt->data, pkt->size, pkt->pos);
1148 pkt->destruct = dstr;
1149 pkt->flags |= AV_PKT_FLAG_KEY;
1151 av_free_packet(pkt);
1152 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
1153 && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1154 ast->frame_offset++;
1155 avi->stream_index = -1;
1159 /* XXX: How to handle B-frames in AVI? */
1160 pkt->dts = ast->frame_offset;
1161 // pkt->dts += ast->start;
1162 if(ast->sample_size)
1163 pkt->dts /= ast->sample_size;
1164 //av_log(s, AV_LOG_DEBUG, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
1165 pkt->stream_index = avi->stream_index;
1167 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1170 assert(st->index_entries);
1172 index= av_index_search_timestamp(st, ast->frame_offset, 0);
1173 e= &st->index_entries[index];
1175 if(index >= 0 && e->timestamp == ast->frame_offset){
1176 if (index == st->nb_index_entries-1){
1180 for(i=0; i<FFMIN(size,256); i++){
1181 if(st->codec->codec_id == CODEC_ID_MPEG4){
1183 key= !(pkt->data[i]&0xC0);
1188 state= (state<<8) + pkt->data[i];
1191 e->flags &= ~AVINDEX_KEYFRAME;
1193 if (e->flags & AVINDEX_KEYFRAME)
1194 pkt->flags |= AV_PKT_FLAG_KEY;
1197 pkt->flags |= AV_PKT_FLAG_KEY;
1199 ast->frame_offset += get_duration(ast, pkt->size);
1201 ast->remaining -= size;
1202 if(!ast->remaining){
1203 avi->stream_index= -1;
1204 ast->packet_size= 0;
1207 if(!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos){
1208 av_free_packet(pkt);
1213 if(!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1){
1214 int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
1216 if(avi->dts_max - dts > 2*AV_TIME_BASE){
1217 avi->non_interleaved= 1;
1218 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
1219 }else if(avi->dts_max < dts)
1226 if ((err = avi_sync(s, 0)) < 0)
1231 /* XXX: We make the implicit supposition that the positions are sorted
1233 static int avi_read_idx1(AVFormatContext *s, int size)
1235 AVIContext *avi = s->priv_data;
1236 AVIOContext *pb = s->pb;
1237 int nb_index_entries, i;
1240 unsigned int index, tag, flags, pos, len, first_packet = 1;
1241 unsigned last_pos= -1;
1242 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1244 nb_index_entries = size / 16;
1245 if (nb_index_entries <= 0)
1248 idx1_pos = avio_tell(pb);
1249 avio_seek(pb, avi->movi_list+4, SEEK_SET);
1250 if (avi_sync(s, 1) == 0) {
1251 first_packet_pos = avio_tell(pb) - 8;
1253 avi->stream_index = -1;
1254 avio_seek(pb, idx1_pos, SEEK_SET);
1256 /* Read the entries and sort them in each stream component. */
1257 for(i = 0; i < nb_index_entries; i++) {
1261 tag = avio_rl32(pb);
1262 flags = avio_rl32(pb);
1263 pos = avio_rl32(pb);
1264 len = avio_rl32(pb);
1265 av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1266 i, tag, flags, pos, len);
1268 index = ((tag & 0xff) - '0') * 10;
1269 index += ((tag >> 8) & 0xff) - '0';
1270 if (index >= s->nb_streams)
1272 st = s->streams[index];
1273 ast = st->priv_data;
1275 if(first_packet && first_packet_pos && len) {
1276 data_offset = first_packet_pos - pos;
1281 av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1285 avi->non_interleaved= 1;
1286 else if(len || !ast->sample_size)
1287 av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1288 ast->cum_len += get_duration(ast, len);
1294 static int guess_ni_flag(AVFormatContext *s){
1296 int64_t last_start=0;
1297 int64_t first_end= INT64_MAX;
1298 int64_t oldpos= avio_tell(s->pb);
1300 for(i=0; i<s->nb_streams; i++){
1301 AVStream *st = s->streams[i];
1302 int n= st->nb_index_entries;
1309 int64_t pos= st->index_entries[0].pos;
1310 avio_seek(s->pb, pos + 4, SEEK_SET);
1311 size= avio_rl32(s->pb);
1312 if(pos + size > st->index_entries[1].pos)
1313 last_start= INT64_MAX;
1316 if(st->index_entries[0].pos > last_start)
1317 last_start= st->index_entries[0].pos;
1318 if(st->index_entries[n-1].pos < first_end)
1319 first_end= st->index_entries[n-1].pos;
1321 avio_seek(s->pb, oldpos, SEEK_SET);
1322 return last_start > first_end;
1325 static int avi_load_index(AVFormatContext *s)
1327 AVIContext *avi = s->priv_data;
1328 AVIOContext *pb = s->pb;
1330 int64_t pos= avio_tell(pb);
1333 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1334 goto the_end; // maybe truncated file
1335 av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1339 tag = avio_rl32(pb);
1340 size = avio_rl32(pb);
1341 av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1348 if (tag == MKTAG('i', 'd', 'x', '1') &&
1349 avi_read_idx1(s, size) >= 0) {
1350 avi->index_loaded=2;
1356 if (avio_skip(pb, size) < 0)
1357 break; // something is wrong here
1360 avio_seek(pb, pos, SEEK_SET);
1364 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1366 AVIStream *ast2 = st2->priv_data;
1367 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1368 av_free_packet(&ast2->sub_pkt);
1369 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1370 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1371 av_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1374 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1376 AVIContext *avi = s->priv_data;
1379 int64_t pos, pos_min;
1382 if (!avi->index_loaded) {
1383 /* we only load the index on demand */
1385 avi->index_loaded |= 1;
1387 assert(stream_index>= 0);
1389 st = s->streams[stream_index];
1391 index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
1395 /* find the position */
1396 pos = st->index_entries[index].pos;
1397 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1399 // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1401 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1402 /* One and only one real stream for DV in AVI, and it has video */
1403 /* offsets. Calling with other stream indexes should have failed */
1404 /* the av_index_search_timestamp call above. */
1405 assert(stream_index == 0);
1407 if(avio_seek(s->pb, pos, SEEK_SET) < 0)
1410 /* Feed the DV video stream version of the timestamp to the */
1411 /* DV demux so it can synthesize correct timestamps. */
1412 dv_offset_reset(avi->dv_demux, timestamp);
1414 avi->stream_index= -1;
1419 for(i = 0; i < s->nb_streams; i++) {
1420 AVStream *st2 = s->streams[i];
1421 AVIStream *ast2 = st2->priv_data;
1426 if (ast2->sub_ctx) {
1427 seek_subtitle(st, st2, timestamp);
1431 if (st2->nb_index_entries <= 0)
1434 // assert(st2->codec->block_align);
1435 assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1436 index = av_index_search_timestamp(
1438 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1439 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1442 ast2->seek_pos= st2->index_entries[index].pos;
1443 pos_min= FFMIN(pos_min,ast2->seek_pos);
1445 for(i = 0; i < s->nb_streams; i++) {
1446 AVStream *st2 = s->streams[i];
1447 AVIStream *ast2 = st2->priv_data;
1449 if (ast2->sub_ctx || st2->nb_index_entries <= 0)
1452 index = av_index_search_timestamp(
1454 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1455 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1458 while(!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
1460 ast2->frame_offset = st2->index_entries[index].timestamp;
1464 if (avio_seek(s->pb, pos_min, SEEK_SET) < 0)
1466 avi->stream_index= -1;
1467 avi->dts_max= INT_MIN;
1471 static int avi_read_close(AVFormatContext *s)
1474 AVIContext *avi = s->priv_data;
1476 for(i=0;i<s->nb_streams;i++) {
1477 AVStream *st = s->streams[i];
1478 AVIStream *ast = st->priv_data;
1481 av_freep(&ast->sub_ctx->pb);
1482 avformat_close_input(&ast->sub_ctx);
1484 av_free(ast->sub_buffer);
1485 av_free_packet(&ast->sub_pkt);
1489 av_free(avi->dv_demux);
1494 static int avi_probe(AVProbeData *p)
1498 /* check file header */
1499 for(i=0; avi_headers[i][0]; i++)
1500 if(!memcmp(p->buf , avi_headers[i] , 4) &&
1501 !memcmp(p->buf+8, avi_headers[i]+4, 4))
1502 return AVPROBE_SCORE_MAX;
1507 AVInputFormat ff_avi_demuxer = {
1509 .long_name = NULL_IF_CONFIG_SMALL("AVI format"),
1510 .priv_data_size = sizeof(AVIContext),
1511 .read_probe = avi_probe,
1512 .read_header = avi_read_header,
1513 .read_packet = avi_read_packet,
1514 .read_close = avi_read_close,
1515 .read_seek = avi_read_seek,
1516 .priv_class = &demuxer_class,