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
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/bswap.h"
35 typedef struct AVIStream {
36 int64_t frame_offset; /* current frame (video) or byte (audio) counter
37 (used to compute the pts) */
43 int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
45 int64_t cum_len; /* temporary storage (used during seek) */
47 int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
63 DVDemuxContext* dv_demux;
66 static const char avi_headers[][8] = {
67 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
68 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
69 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
70 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
71 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
75 static int avi_load_index(AVFormatContext *s);
76 static int guess_ni_flag(AVFormatContext *s);
79 static void print_tag(const char *str, unsigned int tag, int size)
81 dprintf(NULL, "%s: tag=%c%c%c%c size=0x%x\n",
90 static int get_riff(AVFormatContext *s, ByteIOContext *pb)
92 AVIContext *avi = s->priv_data;
96 /* check RIFF header */
97 get_buffer(pb, header, 4);
98 avi->riff_end = get_le32(pb); /* RIFF chunk size */
99 avi->riff_end += url_ftell(pb); /* RIFF chunk end */
100 get_buffer(pb, header+4, 4);
102 for(i=0; avi_headers[i][0]; i++)
103 if(!memcmp(header, avi_headers[i], 8))
105 if(!avi_headers[i][0])
108 if(header[7] == 0x19)
109 av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
114 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
115 AVIContext *avi = s->priv_data;
116 ByteIOContext *pb = s->pb;
117 int longs_pre_entry= get_le16(pb);
118 int index_sub_type = get_byte(pb);
119 int index_type = get_byte(pb);
120 int entries_in_use = get_le32(pb);
121 int chunk_id = get_le32(pb);
122 int64_t base = get_le64(pb);
123 int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
127 int64_t last_pos= -1;
128 int64_t filesize= url_fsize(s->pb);
131 av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
132 longs_pre_entry,index_type, entries_in_use, chunk_id, base);
135 if(stream_id >= s->nb_streams || stream_id < 0)
137 st= s->streams[stream_id];
145 if(index_type && longs_pre_entry != 2)
150 if(filesize > 0 && base >= filesize){
151 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
152 if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
158 for(i=0; i<entries_in_use; i++){
160 int64_t pos= get_le32(pb) + base - 8;
161 int len = get_le32(pb);
166 av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
171 if(last_pos == pos || pos == base - 8)
172 avi->non_interleaved= 1;
173 if(last_pos != pos && (len || !ast->sample_size))
174 av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
184 offset = get_le64(pb);
185 get_le32(pb); /* size */
186 duration = get_le32(pb);
193 url_fseek(pb, offset+8, SEEK_SET);
194 read_braindead_odml_indx(s, frame_num);
195 frame_num += duration;
197 url_fseek(pb, pos, SEEK_SET);
204 static void clean_index(AVFormatContext *s){
208 for(i=0; i<s->nb_streams; i++){
209 AVStream *st = s->streams[i];
210 AVIStream *ast = st->priv_data;
211 int n= st->nb_index_entries;
212 int max= ast->sample_size;
213 int64_t pos, size, ts;
215 if(n != 1 || ast->sample_size==0)
218 while(max < 1024) max+=max;
220 pos= st->index_entries[0].pos;
221 size= st->index_entries[0].size;
222 ts= st->index_entries[0].timestamp;
224 for(j=0; j<size; j+=max){
225 av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
230 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
232 ByteIOContext *pb = s->pb;
233 char key[5] = {0}, *value;
237 if (size == UINT_MAX)
239 value = av_malloc(size+1);
242 get_buffer(pb, value, size);
248 return av_metadata_set2(&st->metadata, key, value,
249 AV_METADATA_DONT_STRDUP_VAL);
251 return av_metadata_set2(&s->metadata, key, value,
252 AV_METADATA_DONT_STRDUP_VAL);
255 static void avi_read_info(AVFormatContext *s, uint64_t end)
257 while (url_ftell(s->pb) < end) {
258 uint32_t tag = get_le32(s->pb);
259 uint32_t size = get_le32(s->pb);
260 avi_read_tag(s, NULL, tag, size);
264 static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
266 AVIContext *avi = s->priv_data;
267 ByteIOContext *pb = s->pb;
268 unsigned int tag, tag1, handler;
269 int codec_type, stream_index, frame_period, bit_rate;
273 AVIStream *ast = NULL;
274 int avih_width=0, avih_height=0;
275 int amv_file_format=0;
276 uint64_t list_end = 0;
278 avi->stream_index= -1;
280 if (get_riff(s, pb) < 0)
283 avi->fsize = url_fsize(pb);
285 avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
297 print_tag("tag", tag, size);
301 case MKTAG('L', 'I', 'S', 'T'):
302 list_end = url_ftell(pb) + size;
303 /* Ignored, except at start of video packets. */
306 print_tag("list", tag1, 0);
308 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
309 avi->movi_list = url_ftell(pb) - 4;
310 if(size) avi->movi_end = avi->movi_list + size + (size & 1);
311 else avi->movi_end = url_fsize(pb);
312 dprintf(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
315 else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
316 avi_read_info(s, list_end);
319 case MKTAG('d', 'm', 'l', 'h'):
321 url_fskip(pb, size + (size & 1));
323 case MKTAG('a', 'm', 'v', 'h'):
325 case MKTAG('a', 'v', 'i', 'h'):
327 /* using frame_period is bad idea */
328 frame_period = get_le32(pb);
329 bit_rate = get_le32(pb) * 8;
331 avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
333 url_fskip(pb, 2 * 4);
336 avih_width=get_le32(pb);
337 avih_height=get_le32(pb);
339 url_fskip(pb, size - 10 * 4);
341 case MKTAG('s', 't', 'r', 'h'):
345 handler = get_le32(pb); /* codec tag */
347 if(tag1 == MKTAG('p', 'a', 'd', 's')){
348 url_fskip(pb, size - 8);
352 st = av_new_stream(s, stream_index);
356 ast = av_mallocz(sizeof(AVIStream));
362 tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
365 print_tag("strh", tag1, -1);
367 if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
371 * After some consideration -- I don't think we
372 * have to support anything but DV in type1 AVIs.
374 if (s->nb_streams != 1)
377 if (handler != MKTAG('d', 'v', 's', 'd') &&
378 handler != MKTAG('d', 'v', 'h', 'd') &&
379 handler != MKTAG('d', 'v', 's', 'l'))
382 ast = s->streams[0]->priv_data;
383 av_freep(&s->streams[0]->codec->extradata);
384 av_freep(&s->streams[0]);
386 if (CONFIG_DV_DEMUXER) {
387 avi->dv_demux = dv_init_demux(s);
391 s->streams[0]->priv_data = ast;
392 url_fskip(pb, 3 * 4);
393 ast->scale = get_le32(pb);
394 ast->rate = get_le32(pb);
395 url_fskip(pb, 4); /* start time */
397 dv_dur = get_le32(pb);
398 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
399 dv_dur *= AV_TIME_BASE;
400 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
403 * else, leave duration alone; timing estimation in utils.c
404 * will make a guess based on bitrate.
407 stream_index = s->nb_streams - 1;
408 url_fskip(pb, size - 9*4);
412 assert(stream_index < s->nb_streams);
413 st->codec->stream_codec_tag= handler;
415 get_le32(pb); /* flags */
416 get_le16(pb); /* priority */
417 get_le16(pb); /* language */
418 get_le32(pb); /* initial frame */
419 ast->scale = get_le32(pb);
420 ast->rate = get_le32(pb);
421 if(!(ast->scale && ast->rate)){
422 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);
425 ast->scale = frame_period;
431 av_set_pts_info(st, 64, ast->scale, ast->rate);
433 ast->cum_len=get_le32(pb); /* start */
434 st->nb_frames = get_le32(pb);
437 get_le32(pb); /* buffer size */
438 get_le32(pb); /* quality */
439 ast->sample_size = get_le32(pb); /* sample ssize */
440 ast->cum_len *= FFMAX(1, ast->sample_size);
441 // av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
444 case MKTAG('v', 'i', 'd', 's'):
445 codec_type = AVMEDIA_TYPE_VIDEO;
447 ast->sample_size = 0;
449 case MKTAG('a', 'u', 'd', 's'):
450 codec_type = AVMEDIA_TYPE_AUDIO;
452 case MKTAG('t', 'x', 't', 's'):
454 codec_type = AVMEDIA_TYPE_DATA; //AVMEDIA_TYPE_SUB ? FIXME
456 case MKTAG('d', 'a', 't', 's'):
457 codec_type = AVMEDIA_TYPE_DATA;
460 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
463 if(ast->sample_size == 0)
464 st->duration = st->nb_frames;
465 ast->frame_offset= ast->cum_len;
466 url_fskip(pb, size - 12 * 4);
468 case MKTAG('s', 't', 'r', 'f'):
470 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
473 uint64_t cur_pos = url_ftell(pb);
474 if (cur_pos < list_end)
475 size = FFMIN(size, list_end - cur_pos);
476 st = s->streams[stream_index];
478 case AVMEDIA_TYPE_VIDEO:
480 st->codec->width=avih_width;
481 st->codec->height=avih_height;
482 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
483 st->codec->codec_id = CODEC_ID_AMV;
487 get_le32(pb); /* size */
488 st->codec->width = get_le32(pb);
489 st->codec->height = (int32_t)get_le32(pb);
490 get_le16(pb); /* panes */
491 st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
493 get_le32(pb); /* ImageSize */
494 get_le32(pb); /* XPelsPerMeter */
495 get_le32(pb); /* YPelsPerMeter */
496 get_le32(pb); /* ClrUsed */
497 get_le32(pb); /* ClrImportant */
499 if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
500 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
501 st->codec->codec_tag = tag1;
502 st->codec->codec_id = CODEC_ID_XSUB;
506 if(size > 10*4 && size<(1<<30)){
507 st->codec->extradata_size= size - 10*4;
508 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
509 if (!st->codec->extradata) {
510 st->codec->extradata_size= 0;
511 return AVERROR(ENOMEM);
513 get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
516 if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
519 /* Extract palette from extradata if bpp <= 8. */
520 /* This code assumes that extradata contains only palette. */
521 /* This is true for all paletted codecs implemented in FFmpeg. */
522 if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
523 st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
525 for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
526 st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
528 memcpy(st->codec->palctrl->palette, st->codec->extradata,
529 FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
531 st->codec->palctrl->palette_changed = 1;
535 print_tag("video", tag1, 0);
537 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
538 st->codec->codec_tag = tag1;
539 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
540 st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
541 // Support "Resolution 1:1" for Avid AVI Codec
542 if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
543 st->codec->extradata_size >= 31 &&
544 !memcmp(&st->codec->extradata[28], "1:1", 3))
545 st->codec->codec_id = CODEC_ID_RAWVIDEO;
547 if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
548 st->codec->extradata_size+= 9;
549 st->codec->extradata= av_realloc(st->codec->extradata, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
550 if(st->codec->extradata)
551 memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
553 st->codec->height= FFABS(st->codec->height);
555 // url_fskip(pb, size - 5 * 4);
557 case AVMEDIA_TYPE_AUDIO:
558 ff_get_wav_header(pb, st->codec, size);
559 if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
560 av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
561 ast->sample_size= st->codec->block_align;
563 if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
565 /* Force parsing as several audio frames can be in
566 * one packet and timestamps refer to packet start. */
567 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
568 /* ADTS header is in extradata, AAC without header must be
569 * stored as exact frames. Parser not needed and it will
571 if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
572 st->need_parsing = AVSTREAM_PARSE_NONE;
573 /* AVI files with Xan DPCM audio (wrongly) declare PCM
574 * audio in the header but have Axan as stream_code_tag. */
575 if (st->codec->stream_codec_tag == AV_RL32("Axan")){
576 st->codec->codec_id = CODEC_ID_XAN_DPCM;
577 st->codec->codec_tag = 0;
580 st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
583 st->codec->codec_type = AVMEDIA_TYPE_DATA;
584 st->codec->codec_id= CODEC_ID_NONE;
585 st->codec->codec_tag= 0;
591 case MKTAG('i', 'n', 'd', 'x'):
593 if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
594 read_braindead_odml_indx(s, 0);
596 url_fseek(pb, i+size, SEEK_SET);
598 case MKTAG('v', 'p', 'r', 'p'):
599 if(stream_index < (unsigned)s->nb_streams && size > 9*4){
600 AVRational active, active_aspect;
602 st = s->streams[stream_index];
609 active_aspect.den= get_le16(pb);
610 active_aspect.num= get_le16(pb);
611 active.num = get_le32(pb);
612 active.den = get_le32(pb);
613 get_le32(pb); //nbFieldsPerFrame
615 if(active_aspect.num && active_aspect.den && active.num && active.den){
616 st->sample_aspect_ratio= av_div_q(active_aspect, active);
617 //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
621 url_fseek(pb, size, SEEK_CUR);
623 case MKTAG('s', 't', 'r', 'n'):
625 avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
630 av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
631 "I will ignore it and try to continue anyway.\n");
632 avi->movi_list = url_ftell(pb) - 4;
633 avi->movi_end = url_fsize(pb);
643 /* check stream number */
644 if (stream_index != s->nb_streams - 1) {
649 if(!avi->index_loaded && !url_is_streamed(pb))
651 avi->index_loaded = 1;
652 avi->non_interleaved |= guess_ni_flag(s);
653 for(i=0; i<s->nb_streams; i++){
654 AVStream *st = s->streams[i];
655 if(st->nb_index_entries)
658 if(i==s->nb_streams && avi->non_interleaved) {
659 av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
660 avi->non_interleaved=0;
663 if(avi->non_interleaved) {
664 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
671 static int get_stream_idx(int *d){
672 if( d[0] >= '0' && d[0] <= '9'
673 && d[1] >= '0' && d[1] <= '9'){
674 return (d[0] - '0') * 10 + (d[1] - '0');
676 return 100; //invalid stream ID
680 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
682 AVIContext *avi = s->priv_data;
683 ByteIOContext *pb = s->pb;
689 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
690 int size = dv_get_packet(avi->dv_demux, pkt);
695 if(avi->non_interleaved){
696 int best_stream_index = 0;
697 AVStream *best_st= NULL;
699 int64_t best_ts= INT64_MAX;
702 for(i=0; i<s->nb_streams; i++){
703 AVStream *st = s->streams[i];
704 AVIStream *ast = st->priv_data;
705 int64_t ts= ast->frame_offset;
708 if(!st->nb_index_entries)
711 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
712 if(!ast->remaining && ts > last_ts)
715 ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
717 // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
721 best_stream_index= i;
727 best_ast = best_st->priv_data;
728 best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
729 if(best_ast->remaining)
730 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
732 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
734 best_ast->frame_offset= best_st->index_entries[i].timestamp;
737 // av_log(s, AV_LOG_DEBUG, "%d\n", i);
739 int64_t pos= best_st->index_entries[i].pos;
740 pos += best_ast->packet_size - best_ast->remaining;
741 url_fseek(s->pb, pos + 8, SEEK_SET);
742 // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
744 assert(best_ast->remaining <= best_ast->packet_size);
746 avi->stream_index= best_stream_index;
747 if(!best_ast->remaining)
748 best_ast->packet_size=
749 best_ast->remaining= best_st->index_entries[i].size;
754 if(avi->stream_index >= 0){
755 AVStream *st= s->streams[ avi->stream_index ];
756 AVIStream *ast= st->priv_data;
759 if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
761 else if(ast->sample_size < 32)
762 // arbitrary multiplier to avoid tiny packets for raw PCM data
763 size= 1024*ast->sample_size;
765 size= ast->sample_size;
767 if(size > ast->remaining)
768 size= ast->remaining;
769 avi->last_pkt_pos= url_ftell(pb);
770 err= av_get_packet(pb, pkt, size);
774 if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
775 void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
780 memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
782 av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
785 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
786 dstr = pkt->destruct;
787 size = dv_produce_packet(avi->dv_demux, pkt,
788 pkt->data, pkt->size);
789 pkt->destruct = dstr;
790 pkt->flags |= AV_PKT_FLAG_KEY;
792 /* XXX: How to handle B-frames in AVI? */
793 pkt->dts = ast->frame_offset;
794 // pkt->dts += ast->start;
796 pkt->dts /= ast->sample_size;
797 //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);
798 pkt->stream_index = avi->stream_index;
800 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
803 assert(st->index_entries);
805 index= av_index_search_timestamp(st, ast->frame_offset, 0);
806 e= &st->index_entries[index];
808 if(index >= 0 && e->timestamp == ast->frame_offset){
809 if (e->flags & AVINDEX_KEYFRAME)
810 pkt->flags |= AV_PKT_FLAG_KEY;
813 pkt->flags |= AV_PKT_FLAG_KEY;
816 ast->frame_offset += pkt->size;
820 ast->remaining -= size;
822 avi->stream_index= -1;
829 memset(d, -1, sizeof(int)*8);
830 for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
837 size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
839 n= get_stream_idx(d+2);
840 //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);
841 if(i + (uint64_t)size > avi->fsize || d[0]<0)
845 if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
847 ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
848 ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
850 //av_log(s, AV_LOG_DEBUG, "SKIP\n");
855 if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
860 n= get_stream_idx(d);
862 if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
865 //detect ##ix chunk and skip
866 if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
872 if(n < s->nb_streams){
878 if(s->nb_streams>=2){
879 AVStream *st1 = s->streams[1];
880 AVIStream *ast1= st1->priv_data;
881 //workaround for broken small-file-bug402.avi
882 if( d[2] == 'w' && d[3] == 'b'
884 && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
885 && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
886 && ast->prefix == 'd'*256+'c'
887 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
892 av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
897 if( (st->discard >= AVDISCARD_DEFAULT && size==0)
898 /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
899 || st->discard >= AVDISCARD_ALL){
900 if(ast->sample_size) ast->frame_offset += size;
901 else ast->frame_offset++;
906 if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
907 int k = get_byte(pb);
908 int last = (k + get_byte(pb) - 1) & 0xFF;
910 get_le16(pb); //flags
912 for (; k <= last; k++)
913 ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
916 } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
917 d[2]*256+d[3] == ast->prefix /*||
918 (d[2] == 'd' && d[3] == 'c') ||
919 (d[2] == 'w' && d[3] == 'b')*/) {
921 //av_log(s, AV_LOG_DEBUG, "OK\n");
922 if(d[2]*256+d[3] == ast->prefix)
925 ast->prefix= d[2]*256+d[3];
926 ast->prefix_count= 0;
929 avi->stream_index= n;
930 ast->packet_size= size + 8;
931 ast->remaining= size;
933 if(size || !ast->sample_size){
934 uint64_t pos= url_ftell(pb) - 8;
935 if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
936 av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
947 /* XXX: We make the implicit supposition that the positions are sorted
949 static int avi_read_idx1(AVFormatContext *s, int size)
951 AVIContext *avi = s->priv_data;
952 ByteIOContext *pb = s->pb;
953 int nb_index_entries, i;
956 unsigned int index, tag, flags, pos, len;
957 unsigned last_pos= -1;
959 nb_index_entries = size / 16;
960 if (nb_index_entries <= 0)
963 /* Read the entries and sort them in each stream component. */
964 for(i = 0; i < nb_index_entries; i++) {
966 flags = get_le32(pb);
969 #if defined(DEBUG_SEEK)
970 av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
971 i, tag, flags, pos, len);
973 if(i==0 && pos > avi->movi_list)
974 avi->movi_list= 0; //FIXME better check
975 pos += avi->movi_list;
977 index = ((tag & 0xff) - '0') * 10;
978 index += ((tag >> 8) & 0xff) - '0';
979 if (index >= s->nb_streams)
981 st = s->streams[index];
984 #if defined(DEBUG_SEEK)
985 av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
991 avi->non_interleaved= 1;
992 else if(len || !ast->sample_size)
993 av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1003 static int guess_ni_flag(AVFormatContext *s){
1005 int64_t last_start=0;
1006 int64_t first_end= INT64_MAX;
1007 int64_t oldpos= url_ftell(s->pb);
1009 for(i=0; i<s->nb_streams; i++){
1010 AVStream *st = s->streams[i];
1011 int n= st->nb_index_entries;
1018 int64_t pos= st->index_entries[0].pos;
1019 url_fseek(s->pb, pos + 4, SEEK_SET);
1020 size= get_le32(s->pb);
1021 if(pos + size > st->index_entries[1].pos)
1022 last_start= INT64_MAX;
1025 if(st->index_entries[0].pos > last_start)
1026 last_start= st->index_entries[0].pos;
1027 if(st->index_entries[n-1].pos < first_end)
1028 first_end= st->index_entries[n-1].pos;
1030 url_fseek(s->pb, oldpos, SEEK_SET);
1031 return last_start > first_end;
1034 static int avi_load_index(AVFormatContext *s)
1036 AVIContext *avi = s->priv_data;
1037 ByteIOContext *pb = s->pb;
1039 int64_t pos= url_ftell(pb);
1042 if (url_fseek(pb, avi->movi_end, SEEK_SET) < 0)
1043 goto the_end; // maybe truncated file
1045 printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
1051 size = get_le32(pb);
1053 printf("tag=%c%c%c%c size=0x%x\n",
1061 case MKTAG('i', 'd', 'x', '1'):
1062 if (avi_read_idx1(s, size) < 0)
1070 if (url_fseek(pb, size, SEEK_CUR) < 0)
1071 goto the_end; // something is wrong here
1076 url_fseek(pb, pos, SEEK_SET);
1080 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1082 AVIContext *avi = s->priv_data;
1088 if (!avi->index_loaded) {
1089 /* we only load the index on demand */
1091 avi->index_loaded = 1;
1093 assert(stream_index>= 0);
1095 st = s->streams[stream_index];
1097 index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
1101 /* find the position */
1102 pos = st->index_entries[index].pos;
1103 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1105 // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1107 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1108 /* One and only one real stream for DV in AVI, and it has video */
1109 /* offsets. Calling with other stream indexes should have failed */
1110 /* the av_index_search_timestamp call above. */
1111 assert(stream_index == 0);
1113 /* Feed the DV video stream version of the timestamp to the */
1114 /* DV demux so it can synthesize correct timestamps. */
1115 dv_offset_reset(avi->dv_demux, timestamp);
1117 url_fseek(s->pb, pos, SEEK_SET);
1118 avi->stream_index= -1;
1122 for(i = 0; i < s->nb_streams; i++) {
1123 AVStream *st2 = s->streams[i];
1124 AVIStream *ast2 = st2->priv_data;
1129 if (st2->nb_index_entries <= 0)
1132 // assert(st2->codec->block_align);
1133 assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1134 index = av_index_search_timestamp(
1136 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1137 flags | AVSEEK_FLAG_BACKWARD);
1141 if(!avi->non_interleaved){
1142 while(index>0 && st2->index_entries[index].pos > pos)
1144 while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
1148 // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
1149 /* extract the current frame number */
1150 ast2->frame_offset = st2->index_entries[index].timestamp;
1154 url_fseek(s->pb, pos, SEEK_SET);
1155 avi->stream_index= -1;
1159 static int avi_read_close(AVFormatContext *s)
1162 AVIContext *avi = s->priv_data;
1164 for(i=0;i<s->nb_streams;i++) {
1165 AVStream *st = s->streams[i];
1166 av_free(st->codec->palctrl);
1170 av_free(avi->dv_demux);
1175 static int avi_probe(AVProbeData *p)
1179 /* check file header */
1180 for(i=0; avi_headers[i][0]; i++)
1181 if(!memcmp(p->buf , avi_headers[i] , 4) &&
1182 !memcmp(p->buf+8, avi_headers[i]+4, 4))
1183 return AVPROBE_SCORE_MAX;
1188 AVInputFormat avi_demuxer = {
1190 NULL_IF_CONFIG_SMALL("AVI format"),
1197 .metadata_conv = ff_avi_metadata_conv,