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
23 #include "libavutil/intreadwrite.h"
24 #include "libavutil/mathematics.h"
25 #include "libavutil/bswap.h"
26 #include "libavutil/opt.h"
27 #include "libavutil/dict.h"
36 typedef struct AVIStream {
37 int64_t frame_offset; /* current frame (video) or byte (audio) counter
38 (used to compute the pts) */
44 int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
46 int64_t cum_len; /* temporary storage (used during seek) */
48 int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
52 int dshow_block_align; ///< block align variable used to emulate bugs in the MS dshow demuxer
54 AVFormatContext *sub_ctx;
72 DVDemuxContext* dv_demux;
75 #define MAX_ODML_DEPTH 1000
80 static const AVOption options[] = {
81 { "use_odml", "use odml index", offsetof(AVIContext, use_odml), FF_OPT_TYPE_INT, {.dbl = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
85 static const AVClass demuxer_class = {
89 LIBAVUTIL_VERSION_INT,
93 static const char avi_headers[][8] = {
94 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
95 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
96 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
97 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
98 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
102 static int avi_load_index(AVFormatContext *s);
103 static int guess_ni_flag(AVFormatContext *s);
105 #define print_tag(str, tag, size) \
106 av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
109 (tag >> 16) & 0xff, \
110 (tag >> 24) & 0xff, \
113 static inline int get_duration(AVIStream *ast, int len){
114 if(ast->sample_size){
116 }else if (ast->dshow_block_align){
117 return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
122 static int get_riff(AVFormatContext *s, AVIOContext *pb)
124 AVIContext *avi = s->priv_data;
128 /* check RIFF header */
129 avio_read(pb, header, 4);
130 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
131 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
132 avio_read(pb, header+4, 4);
134 for(i=0; avi_headers[i][0]; i++)
135 if(!memcmp(header, avi_headers[i], 8))
137 if(!avi_headers[i][0])
140 if(header[7] == 0x19)
141 av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
146 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
147 AVIContext *avi = s->priv_data;
148 AVIOContext *pb = s->pb;
149 int longs_pre_entry= avio_rl16(pb);
150 int index_sub_type = avio_r8(pb);
151 int index_type = avio_r8(pb);
152 int entries_in_use = avio_rl32(pb);
153 int chunk_id = avio_rl32(pb);
154 int64_t base = avio_rl64(pb);
155 int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
159 int64_t last_pos= -1;
160 int64_t filesize= avi->fsize;
162 av_dlog(s, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
163 longs_pre_entry,index_type, entries_in_use, chunk_id, base);
165 if(stream_id >= s->nb_streams || stream_id < 0)
167 st= s->streams[stream_id];
175 if(index_type && longs_pre_entry != 2)
180 if(filesize > 0 && base >= filesize){
181 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
182 if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
188 for(i=0; i<entries_in_use; i++){
190 int64_t pos= avio_rl32(pb) + base - 8;
191 int len = avio_rl32(pb);
196 av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
201 if(last_pos == pos || pos == base - 8)
202 avi->non_interleaved= 1;
203 if(last_pos != pos && (len || !ast->sample_size))
204 av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
206 ast->cum_len += get_duration(ast, len);
211 offset = avio_rl64(pb);
212 avio_rl32(pb); /* size */
213 duration = avio_rl32(pb);
220 if(avi->odml_depth > MAX_ODML_DEPTH){
221 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
225 if(avio_seek(pb, offset+8, SEEK_SET) < 0)
228 read_braindead_odml_indx(s, frame_num);
230 frame_num += duration;
232 if(avio_seek(pb, pos, SEEK_SET) < 0) {
233 av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index");
243 static void clean_index(AVFormatContext *s){
247 for(i=0; i<s->nb_streams; i++){
248 AVStream *st = s->streams[i];
249 AVIStream *ast = st->priv_data;
250 int n= st->nb_index_entries;
251 int max= ast->sample_size;
252 int64_t pos, size, ts;
254 if(n != 1 || ast->sample_size==0)
257 while(max < 1024) max+=max;
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, AVINDEX_KEYFRAME);
269 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
271 AVIOContext *pb = s->pb;
272 char key[5] = {0}, *value;
276 if (size == UINT_MAX)
278 value = av_malloc(size+1);
281 avio_read(pb, value, size);
286 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
287 AV_DICT_DONT_STRDUP_VAL);
290 static void avi_read_info(AVFormatContext *s, uint64_t end)
292 while (avio_tell(s->pb) < end) {
293 uint32_t tag = avio_rl32(s->pb);
294 uint32_t size = avio_rl32(s->pb);
295 avi_read_tag(s, NULL, tag, size);
299 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
300 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
302 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
304 char month[4], time[9], buffer[64];
306 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
307 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
308 month, &day, time, &year) == 4) {
310 if (!strcasecmp(month, months[i])) {
311 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
312 year, i+1, day, time);
313 av_dict_set(metadata, "creation_time", buffer, 0);
315 } else if (date[4] == '/' && date[7] == '/') {
316 date[4] = date[7] = '-';
317 av_dict_set(metadata, "creation_time", date, 0);
321 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
323 while (avio_tell(s->pb) < end) {
324 uint32_t tag = avio_rl32(s->pb);
325 uint32_t size = avio_rl32(s->pb);
327 case MKTAG('n', 'c', 't', 'g'): { /* Nikon Tags */
328 uint64_t tag_end = avio_tell(s->pb) + size;
329 while (avio_tell(s->pb) < tag_end) {
330 uint16_t tag = avio_rl16(s->pb);
331 uint16_t size = avio_rl16(s->pb);
332 const char *name = NULL;
333 char buffer[64] = {0};
334 size -= avio_read(s->pb, buffer,
335 FFMIN(size, sizeof(buffer)-1));
337 case 0x03: name = "maker"; break;
338 case 0x04: name = "model"; break;
339 case 0x13: name = "creation_time";
340 if (buffer[4] == ':' && buffer[7] == ':')
341 buffer[4] = buffer[7] = '-';
345 av_dict_set(&s->metadata, name, buffer, 0);
346 avio_skip(s->pb, size);
351 avio_skip(s->pb, size);
357 static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
359 AVIContext *avi = s->priv_data;
360 AVIOContext *pb = s->pb;
361 unsigned int tag, tag1, handler;
362 int codec_type, stream_index, frame_period;
366 AVIStream *ast = NULL;
367 int avih_width=0, avih_height=0;
368 int amv_file_format=0;
369 uint64_t list_end = 0;
372 avi->stream_index= -1;
374 if (get_riff(s, pb) < 0)
377 av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
379 avi->fsize = avio_size(pb);
380 if(avi->fsize<=0 || avi->fsize < avi->riff_end)
381 avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
391 size = avio_rl32(pb);
393 print_tag("tag", tag, size);
396 case MKTAG('L', 'I', 'S', 'T'):
397 list_end = avio_tell(pb) + size;
398 /* Ignored, except at start of video packets. */
399 tag1 = avio_rl32(pb);
401 print_tag("list", tag1, 0);
403 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
404 avi->movi_list = avio_tell(pb) - 4;
405 if(size) avi->movi_end = avi->movi_list + size + (size & 1);
406 else avi->movi_end = avi->fsize;
407 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
410 else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
411 avi_read_info(s, list_end);
412 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
413 avi_read_nikon(s, list_end);
416 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);
434 avio_rl32(pb); /* max. bytes per second */
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 = av_new_stream(s, stream_index);
461 ast = av_mallocz(sizeof(AVIStream));
467 tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
469 print_tag("strh", tag1, -1);
471 if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
475 * After some consideration -- I don't think we
476 * have to support anything but DV in type1 AVIs.
478 if (s->nb_streams != 1)
481 if (handler != MKTAG('d', 'v', 's', 'd') &&
482 handler != MKTAG('d', 'v', 'h', 'd') &&
483 handler != MKTAG('d', 'v', 's', 'l'))
486 ast = s->streams[0]->priv_data;
487 av_freep(&s->streams[0]->codec->extradata);
488 av_freep(&s->streams[0]->codec);
489 av_freep(&s->streams[0]);
491 if (CONFIG_DV_DEMUXER) {
492 avi->dv_demux = dv_init_demux(s);
496 s->streams[0]->priv_data = ast;
497 avio_skip(pb, 3 * 4);
498 ast->scale = avio_rl32(pb);
499 ast->rate = avio_rl32(pb);
500 avio_skip(pb, 4); /* start time */
502 dv_dur = avio_rl32(pb);
503 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
504 dv_dur *= AV_TIME_BASE;
505 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
508 * else, leave duration alone; timing estimation in utils.c
509 * will make a guess based on bitrate.
512 stream_index = s->nb_streams - 1;
513 avio_skip(pb, size - 9*4);
517 assert(stream_index < s->nb_streams);
518 st->codec->stream_codec_tag= handler;
520 avio_rl32(pb); /* flags */
521 avio_rl16(pb); /* priority */
522 avio_rl16(pb); /* language */
523 avio_rl32(pb); /* initial frame */
524 ast->scale = avio_rl32(pb);
525 ast->rate = avio_rl32(pb);
526 if(!(ast->scale && ast->rate)){
527 av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
530 ast->scale = frame_period;
536 av_set_pts_info(st, 64, ast->scale, ast->rate);
538 ast->cum_len=avio_rl32(pb); /* start */
539 st->nb_frames = avio_rl32(pb);
542 avio_rl32(pb); /* buffer size */
543 avio_rl32(pb); /* quality */
544 ast->sample_size = avio_rl32(pb); /* sample ssize */
545 ast->cum_len *= FFMAX(1, ast->sample_size);
546 // av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
549 case MKTAG('v', 'i', 'd', 's'):
550 codec_type = AVMEDIA_TYPE_VIDEO;
552 ast->sample_size = 0;
554 case MKTAG('a', 'u', 'd', 's'):
555 codec_type = AVMEDIA_TYPE_AUDIO;
557 case MKTAG('t', 'x', 't', 's'):
558 codec_type = AVMEDIA_TYPE_SUBTITLE;
560 case MKTAG('d', 'a', 't', 's'):
561 codec_type = AVMEDIA_TYPE_DATA;
564 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
566 if(ast->sample_size == 0)
567 st->duration = st->nb_frames;
568 ast->frame_offset= ast->cum_len;
569 avio_skip(pb, size - 12 * 4);
571 case MKTAG('s', 't', 'r', 'f'):
573 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
576 uint64_t cur_pos = avio_tell(pb);
577 if (cur_pos < list_end)
578 size = FFMIN(size, list_end - cur_pos);
579 st = s->streams[stream_index];
581 case AVMEDIA_TYPE_VIDEO:
583 st->codec->width=avih_width;
584 st->codec->height=avih_height;
585 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
586 st->codec->codec_id = CODEC_ID_AMV;
590 tag1 = ff_get_bmp_header(pb, st);
592 if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
593 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
594 st->codec->codec_tag = tag1;
595 st->codec->codec_id = CODEC_ID_XSUB;
599 if(size > 10*4 && size<(1<<30)){
600 st->codec->extradata_size= size - 10*4;
601 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
602 if (!st->codec->extradata) {
603 st->codec->extradata_size= 0;
604 return AVERROR(ENOMEM);
606 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
609 if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
612 /* Extract palette from extradata if bpp <= 8. */
613 /* This code assumes that extradata contains only palette. */
614 /* This is true for all paletted codecs implemented in FFmpeg. */
615 if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
616 int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
617 const uint8_t *pal_src;
619 pal_size = FFMIN(pal_size, st->codec->extradata_size);
620 pal_src = st->codec->extradata + st->codec->extradata_size - pal_size;
622 for (i = 0; i < pal_size/4; i++)
623 ast->pal[i] = AV_RL32(pal_src+4*i);
625 memcpy(ast->pal, pal_src, pal_size);
630 print_tag("video", tag1, 0);
632 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
633 st->codec->codec_tag = tag1;
634 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
635 st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
636 // Support "Resolution 1:1" for Avid AVI Codec
637 if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
638 st->codec->extradata_size >= 31 &&
639 !memcmp(&st->codec->extradata[28], "1:1", 3))
640 st->codec->codec_id = CODEC_ID_RAWVIDEO;
642 if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
643 st->codec->extradata_size+= 9;
644 st->codec->extradata= av_realloc_f(st->codec->extradata, 1, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
645 if(st->codec->extradata)
646 memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
648 st->codec->height= FFABS(st->codec->height);
650 // avio_skip(pb, size - 5 * 4);
652 case AVMEDIA_TYPE_AUDIO:
653 ret = ff_get_wav_header(pb, st->codec, size);
656 ast->dshow_block_align= st->codec->block_align;
657 if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
658 av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
659 ast->sample_size= st->codec->block_align;
661 if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
663 /* Force parsing as several audio frames can be in
664 * one packet and timestamps refer to packet start. */
665 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
666 /* ADTS header is in extradata, AAC without header must be
667 * stored as exact frames. Parser not needed and it will
669 if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
670 st->need_parsing = AVSTREAM_PARSE_NONE;
671 /* AVI files with Xan DPCM audio (wrongly) declare PCM
672 * audio in the header but have Axan as stream_code_tag. */
673 if (st->codec->stream_codec_tag == AV_RL32("Axan")){
674 st->codec->codec_id = CODEC_ID_XAN_DPCM;
675 st->codec->codec_tag = 0;
676 ast->dshow_block_align = 0;
678 if (amv_file_format){
679 st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
680 ast->dshow_block_align = 0;
683 case AVMEDIA_TYPE_SUBTITLE:
684 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
685 st->request_probe= 1;
688 st->codec->codec_type = AVMEDIA_TYPE_DATA;
689 st->codec->codec_id= CODEC_ID_NONE;
690 st->codec->codec_tag= 0;
696 case MKTAG('i', 'n', 'd', 'x'):
698 if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) && avi->use_odml &&
699 read_braindead_odml_indx(s, 0) < 0 && s->error_recognition >= FF_ER_EXPLODE){
701 avio_seek(pb, i+size, SEEK_SET);
703 case MKTAG('v', 'p', 'r', 'p'):
704 if(stream_index < (unsigned)s->nb_streams && size > 9*4){
705 AVRational active, active_aspect;
707 st = s->streams[stream_index];
714 active_aspect.den= avio_rl16(pb);
715 active_aspect.num= avio_rl16(pb);
716 active.num = avio_rl32(pb);
717 active.den = avio_rl32(pb);
718 avio_rl32(pb); //nbFieldsPerFrame
720 if(active_aspect.num && active_aspect.den && active.num && active.den){
721 st->sample_aspect_ratio= av_div_q(active_aspect, active);
722 //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
728 case MKTAG('s', 't', 'r', 'n'):
730 avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
735 av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
736 "I will ignore it and try to continue anyway.\n");
737 if (s->error_recognition >= FF_ER_EXPLODE) goto fail;
738 avi->movi_list = avio_tell(pb) - 4;
739 avi->movi_end = avi->fsize;
749 /* check stream number */
750 if (stream_index != s->nb_streams - 1) {
755 if(!avi->index_loaded && pb->seekable)
757 avi->index_loaded = 1;
758 avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
759 for(i=0; i<s->nb_streams; i++){
760 AVStream *st = s->streams[i];
761 if(st->nb_index_entries)
764 // DV-in-AVI cannot be non-interleaved, if set this must be
767 avi->non_interleaved=0;
768 if(i==s->nb_streams && avi->non_interleaved) {
769 av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
770 avi->non_interleaved=0;
773 if(avi->non_interleaved) {
774 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
778 ff_metadata_conv_ctx(s, NULL, ff_avi_metadata_conv);
783 static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
784 if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
786 int score = AVPROBE_SCORE_MAX / 2, ret;
787 AVIStream *ast = st->priv_data;
788 AVInputFormat *sub_demuxer;
789 AVRational time_base;
790 AVIOContext *pb = avio_alloc_context( pkt->data + 7,
792 0, NULL, NULL, NULL, NULL);
794 unsigned int desc_len = avio_rl32(pb);
796 if (desc_len > pb->buf_end - pb->buf_ptr)
799 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
800 avio_skip(pb, desc_len - ret);
802 av_dict_set(&st->metadata, "title", desc, 0);
804 avio_rl16(pb); /* flags? */
805 avio_rl32(pb); /* data size */
807 pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
808 if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
811 if (!(ast->sub_ctx = avformat_alloc_context()))
814 ast->sub_ctx->pb = pb;
815 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
816 av_read_packet(ast->sub_ctx, &ast->sub_pkt);
817 *st->codec = *ast->sub_ctx->streams[0]->codec;
818 ast->sub_ctx->streams[0]->codec->extradata = NULL;
819 time_base = ast->sub_ctx->streams[0]->time_base;
820 av_set_pts_info(st, 64, time_base.num, time_base.den);
822 ast->sub_buffer = pkt->data;
823 memset(pkt, 0, sizeof(*pkt));
831 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
834 AVIStream *ast, *next_ast = next_st->priv_data;
835 int64_t ts, next_ts, ts_min = INT64_MAX;
836 AVStream *st, *sub_st = NULL;
839 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
842 for (i=0; i<s->nb_streams; i++) {
845 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
846 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
847 if (ts <= next_ts && ts < ts_min) {
855 ast = sub_st->priv_data;
857 pkt->stream_index = sub_st->index;
858 if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
859 ast->sub_pkt.data = NULL;
864 static int get_stream_idx(int *d){
865 if( d[0] >= '0' && d[0] <= '9'
866 && d[1] >= '0' && d[1] <= '9'){
867 return (d[0] - '0') * 10 + (d[1] - '0');
869 return 100; //invalid stream ID
873 static int avi_sync(AVFormatContext *s, int exit_early)
875 AVIContext *avi = s->priv_data;
876 AVIOContext *pb = s->pb;
883 memset(d, -1, sizeof(d));
884 for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
891 size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
893 n= get_stream_idx(d+2);
894 //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);
895 if(i + (uint64_t)size > avi->fsize || d[0] > 127)
899 if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
901 ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
902 ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
904 //av_log(s, AV_LOG_DEBUG, "SKIP\n");
909 if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
914 n= get_stream_idx(d);
916 if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
919 //detect ##ix chunk and skip
920 if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
926 if(n < s->nb_streams){
932 if(s->nb_streams>=2){
933 AVStream *st1 = s->streams[1];
934 AVIStream *ast1= st1->priv_data;
935 //workaround for broken small-file-bug402.avi
936 if( d[2] == 'w' && d[3] == 'b'
938 && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
939 && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
940 && ast->prefix == 'd'*256+'c'
941 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
946 av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
951 if( (st->discard >= AVDISCARD_DEFAULT && size==0)
952 /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
953 || st->discard >= AVDISCARD_ALL){
955 ast->frame_offset += get_duration(ast, size);
961 if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
963 int last = (k + avio_r8(pb) - 1) & 0xFF;
965 avio_rl16(pb); //flags
967 for (; k <= last; k++)
968 ast->pal[k] = avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
971 } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
972 d[2]*256+d[3] == ast->prefix /*||
973 (d[2] == 'd' && d[3] == 'c') ||
974 (d[2] == 'w' && d[3] == 'b')*/) {
978 //av_log(s, AV_LOG_DEBUG, "OK\n");
979 if(d[2]*256+d[3] == ast->prefix)
982 ast->prefix= d[2]*256+d[3];
983 ast->prefix_count= 0;
986 avi->stream_index= n;
987 ast->packet_size= size + 8;
988 ast->remaining= size;
990 if(size || !ast->sample_size){
991 uint64_t pos= avio_tell(pb) - 8;
992 if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
993 av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
1004 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1006 AVIContext *avi = s->priv_data;
1007 AVIOContext *pb = s->pb;
1011 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1012 int size = dv_get_packet(avi->dv_demux, pkt);
1017 if(avi->non_interleaved){
1018 int best_stream_index = 0;
1019 AVStream *best_st= NULL;
1020 AVIStream *best_ast;
1021 int64_t best_ts= INT64_MAX;
1024 for(i=0; i<s->nb_streams; i++){
1025 AVStream *st = s->streams[i];
1026 AVIStream *ast = st->priv_data;
1027 int64_t ts= ast->frame_offset;
1030 if(!st->nb_index_entries)
1033 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1034 if(!ast->remaining && ts > last_ts)
1037 ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
1039 // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
1043 best_stream_index= i;
1049 best_ast = best_st->priv_data;
1050 best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
1051 if(best_ast->remaining)
1052 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
1054 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1056 best_ast->frame_offset= best_st->index_entries[i].timestamp;
1059 // av_log(s, AV_LOG_DEBUG, "%d\n", i);
1061 int64_t pos= best_st->index_entries[i].pos;
1062 pos += best_ast->packet_size - best_ast->remaining;
1063 if(avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
1065 // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
1067 assert(best_ast->remaining <= best_ast->packet_size);
1069 avi->stream_index= best_stream_index;
1070 if(!best_ast->remaining)
1071 best_ast->packet_size=
1072 best_ast->remaining= best_st->index_entries[i].size;
1079 if(avi->stream_index >= 0){
1080 AVStream *st= s->streams[ avi->stream_index ];
1081 AVIStream *ast= st->priv_data;
1084 if(get_subtitle_pkt(s, st, pkt))
1087 if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1089 else if(ast->sample_size < 32)
1090 // arbitrary multiplier to avoid tiny packets for raw PCM data
1091 size= 1024*ast->sample_size;
1093 size= ast->sample_size;
1095 if(size > ast->remaining)
1096 size= ast->remaining;
1097 avi->last_pkt_pos= avio_tell(pb);
1098 err= av_get_packet(pb, pkt, size);
1102 if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
1104 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
1106 av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
1108 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1113 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1114 dstr = pkt->destruct;
1115 size = dv_produce_packet(avi->dv_demux, pkt,
1116 pkt->data, pkt->size, pkt->pos);
1117 pkt->destruct = dstr;
1118 pkt->flags |= AV_PKT_FLAG_KEY;
1120 av_free_packet(pkt);
1121 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
1122 && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1123 ast->frame_offset++;
1124 avi->stream_index = -1;
1128 /* XXX: How to handle B-frames in AVI? */
1129 pkt->dts = ast->frame_offset;
1130 // pkt->dts += ast->start;
1131 if(ast->sample_size)
1132 pkt->dts /= ast->sample_size;
1133 //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);
1134 pkt->stream_index = avi->stream_index;
1136 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1139 assert(st->index_entries);
1141 index= av_index_search_timestamp(st, ast->frame_offset, 0);
1142 e= &st->index_entries[index];
1144 if(index >= 0 && e->timestamp == ast->frame_offset){
1145 if (index == st->nb_index_entries-1){
1149 for(i=0; i<FFMIN(size,256); i++){
1150 if(st->codec->codec_id == CODEC_ID_MPEG4){
1152 key= !(pkt->data[i]&0xC0);
1157 state= (state<<8) + pkt->data[i];
1160 e->flags &= ~AVINDEX_KEYFRAME;
1162 if (e->flags & AVINDEX_KEYFRAME)
1163 pkt->flags |= AV_PKT_FLAG_KEY;
1166 pkt->flags |= AV_PKT_FLAG_KEY;
1168 ast->frame_offset += get_duration(ast, pkt->size);
1170 ast->remaining -= size;
1171 if(!ast->remaining){
1172 avi->stream_index= -1;
1173 ast->packet_size= 0;
1176 if(!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos){
1177 av_free_packet(pkt);
1182 if(!avi->non_interleaved && st->nb_index_entries>1){
1183 int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
1185 if(avi->dts_max - dts > 2*AV_TIME_BASE){
1186 avi->non_interleaved= 1;
1187 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
1188 }else if(avi->dts_max < dts)
1195 if ((err = avi_sync(s, 0)) < 0)
1200 /* XXX: We make the implicit supposition that the positions are sorted
1202 static int avi_read_idx1(AVFormatContext *s, int size)
1204 AVIContext *avi = s->priv_data;
1205 AVIOContext *pb = s->pb;
1206 int nb_index_entries, i;
1209 unsigned int index, tag, flags, pos, len, first_packet = 1;
1210 unsigned last_pos= -1;
1211 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1213 nb_index_entries = size / 16;
1214 if (nb_index_entries <= 0)
1217 idx1_pos = avio_tell(pb);
1218 avio_seek(pb, avi->movi_list+4, SEEK_SET);
1219 if (avi_sync(s, 1) == 0) {
1220 first_packet_pos = avio_tell(pb) - 8;
1222 avi->stream_index = -1;
1223 avio_seek(pb, idx1_pos, SEEK_SET);
1225 /* Read the entries and sort them in each stream component. */
1226 for(i = 0; i < nb_index_entries; i++) {
1227 tag = avio_rl32(pb);
1228 flags = avio_rl32(pb);
1229 pos = avio_rl32(pb);
1230 len = avio_rl32(pb);
1231 av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1232 i, tag, flags, pos, len);
1234 index = ((tag & 0xff) - '0') * 10;
1235 index += ((tag >> 8) & 0xff) - '0';
1236 if (index >= s->nb_streams)
1238 st = s->streams[index];
1239 ast = st->priv_data;
1241 if(first_packet && first_packet_pos && len) {
1242 data_offset = first_packet_pos - pos;
1247 av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1253 avi->non_interleaved= 1;
1254 else if(len || !ast->sample_size)
1255 av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1256 ast->cum_len += get_duration(ast, len);
1262 static int guess_ni_flag(AVFormatContext *s){
1264 int64_t last_start=0;
1265 int64_t first_end= INT64_MAX;
1266 int64_t oldpos= avio_tell(s->pb);
1268 for(i=0; i<s->nb_streams; i++){
1269 AVStream *st = s->streams[i];
1270 int n= st->nb_index_entries;
1277 int64_t pos= st->index_entries[0].pos;
1278 avio_seek(s->pb, pos + 4, SEEK_SET);
1279 size= avio_rl32(s->pb);
1280 if(pos + size > st->index_entries[1].pos)
1281 last_start= INT64_MAX;
1284 if(st->index_entries[0].pos > last_start)
1285 last_start= st->index_entries[0].pos;
1286 if(st->index_entries[n-1].pos < first_end)
1287 first_end= st->index_entries[n-1].pos;
1289 avio_seek(s->pb, oldpos, SEEK_SET);
1290 return last_start > first_end;
1293 static int avi_load_index(AVFormatContext *s)
1295 AVIContext *avi = s->priv_data;
1296 AVIOContext *pb = s->pb;
1298 int64_t pos= avio_tell(pb);
1301 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1302 goto the_end; // maybe truncated file
1303 av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1307 tag = avio_rl32(pb);
1308 size = avio_rl32(pb);
1309 av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1316 if (tag == MKTAG('i', 'd', 'x', '1') &&
1317 avi_read_idx1(s, size) >= 0) {
1323 if (avio_skip(pb, size) < 0)
1324 break; // something is wrong here
1327 avio_seek(pb, pos, SEEK_SET);
1331 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1333 AVIStream *ast2 = st2->priv_data;
1334 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1335 av_free_packet(&ast2->sub_pkt);
1336 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1337 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1338 av_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1341 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1343 AVIContext *avi = s->priv_data;
1346 int64_t pos, pos_min;
1349 if (!avi->index_loaded) {
1350 /* we only load the index on demand */
1352 avi->index_loaded = 1;
1354 assert(stream_index>= 0);
1356 st = s->streams[stream_index];
1358 index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
1362 /* find the position */
1363 pos = st->index_entries[index].pos;
1364 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1366 // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1368 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1369 /* One and only one real stream for DV in AVI, and it has video */
1370 /* offsets. Calling with other stream indexes should have failed */
1371 /* the av_index_search_timestamp call above. */
1372 assert(stream_index == 0);
1374 if(avio_seek(s->pb, pos, SEEK_SET) < 0)
1377 /* Feed the DV video stream version of the timestamp to the */
1378 /* DV demux so it can synthesize correct timestamps. */
1379 dv_offset_reset(avi->dv_demux, timestamp);
1381 avi->stream_index= -1;
1386 for(i = 0; i < s->nb_streams; i++) {
1387 AVStream *st2 = s->streams[i];
1388 AVIStream *ast2 = st2->priv_data;
1393 if (ast2->sub_ctx) {
1394 seek_subtitle(st, st2, timestamp);
1398 if (st2->nb_index_entries <= 0)
1401 // assert(st2->codec->block_align);
1402 assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1403 index = av_index_search_timestamp(
1405 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1406 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1409 ast2->seek_pos= st2->index_entries[index].pos;
1410 pos_min= FFMIN(pos_min,ast2->seek_pos);
1412 for(i = 0; i < s->nb_streams; i++) {
1413 AVStream *st2 = s->streams[i];
1414 AVIStream *ast2 = st2->priv_data;
1416 if (ast2->sub_ctx || st2->nb_index_entries <= 0)
1419 index = av_index_search_timestamp(
1421 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1422 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1425 while(!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
1427 ast2->frame_offset = st2->index_entries[index].timestamp;
1431 if (avio_seek(s->pb, pos_min, SEEK_SET) < 0)
1433 avi->stream_index= -1;
1434 avi->dts_max= INT_MIN;
1438 static int avi_read_close(AVFormatContext *s)
1441 AVIContext *avi = s->priv_data;
1443 for(i=0;i<s->nb_streams;i++) {
1444 AVStream *st = s->streams[i];
1445 AVIStream *ast = st->priv_data;
1448 av_freep(&ast->sub_ctx->pb);
1449 av_close_input_file(ast->sub_ctx);
1451 av_free(ast->sub_buffer);
1452 av_free_packet(&ast->sub_pkt);
1456 av_free(avi->dv_demux);
1461 static int avi_probe(AVProbeData *p)
1465 /* check file header */
1466 for(i=0; avi_headers[i][0]; i++)
1467 if(!memcmp(p->buf , avi_headers[i] , 4) &&
1468 !memcmp(p->buf+8, avi_headers[i]+4, 4))
1469 return AVPROBE_SCORE_MAX;
1474 AVInputFormat ff_avi_demuxer = {
1476 .long_name = NULL_IF_CONFIG_SMALL("AVI format"),
1477 .priv_data_size = sizeof(AVIContext),
1478 .read_probe = avi_probe,
1479 .read_header = avi_read_header,
1480 .read_packet = avi_read_packet,
1481 .read_close = avi_read_close,
1482 .read_seek = avi_read_seek,
1483 .priv_class = &demuxer_class,