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 if(avi->non_interleaved) {
654 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
661 static int get_stream_idx(int *d){
662 if( d[0] >= '0' && d[0] <= '9'
663 && d[1] >= '0' && d[1] <= '9'){
664 return (d[0] - '0') * 10 + (d[1] - '0');
666 return 100; //invalid stream ID
670 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
672 AVIContext *avi = s->priv_data;
673 ByteIOContext *pb = s->pb;
679 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
680 int size = dv_get_packet(avi->dv_demux, pkt);
685 if(avi->non_interleaved){
686 int best_stream_index = 0;
687 AVStream *best_st= NULL;
689 int64_t best_ts= INT64_MAX;
692 for(i=0; i<s->nb_streams; i++){
693 AVStream *st = s->streams[i];
694 AVIStream *ast = st->priv_data;
695 int64_t ts= ast->frame_offset;
698 if(!st->nb_index_entries)
701 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
702 if(!ast->remaining && ts > last_ts)
705 ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
707 // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
711 best_stream_index= i;
717 best_ast = best_st->priv_data;
718 best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
719 if(best_ast->remaining)
720 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
722 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
724 best_ast->frame_offset= best_st->index_entries[i].timestamp;
727 // av_log(s, AV_LOG_DEBUG, "%d\n", i);
729 int64_t pos= best_st->index_entries[i].pos;
730 pos += best_ast->packet_size - best_ast->remaining;
731 url_fseek(s->pb, pos + 8, SEEK_SET);
732 // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
734 assert(best_ast->remaining <= best_ast->packet_size);
736 avi->stream_index= best_stream_index;
737 if(!best_ast->remaining)
738 best_ast->packet_size=
739 best_ast->remaining= best_st->index_entries[i].size;
744 if(avi->stream_index >= 0){
745 AVStream *st= s->streams[ avi->stream_index ];
746 AVIStream *ast= st->priv_data;
749 if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
751 else if(ast->sample_size < 32)
752 // arbitrary multiplier to avoid tiny packets for raw PCM data
753 size= 1024*ast->sample_size;
755 size= ast->sample_size;
757 if(size > ast->remaining)
758 size= ast->remaining;
759 avi->last_pkt_pos= url_ftell(pb);
760 err= av_get_packet(pb, pkt, size);
764 if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
765 void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
770 memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
772 av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
775 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
776 dstr = pkt->destruct;
777 size = dv_produce_packet(avi->dv_demux, pkt,
778 pkt->data, pkt->size);
779 pkt->destruct = dstr;
780 pkt->flags |= AV_PKT_FLAG_KEY;
782 /* XXX: How to handle B-frames in AVI? */
783 pkt->dts = ast->frame_offset;
784 // pkt->dts += ast->start;
786 pkt->dts /= ast->sample_size;
787 //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);
788 pkt->stream_index = avi->stream_index;
790 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
793 assert(st->index_entries);
795 index= av_index_search_timestamp(st, ast->frame_offset, 0);
796 e= &st->index_entries[index];
798 if(index >= 0 && e->timestamp == ast->frame_offset){
799 if (e->flags & AVINDEX_KEYFRAME)
800 pkt->flags |= AV_PKT_FLAG_KEY;
803 pkt->flags |= AV_PKT_FLAG_KEY;
806 ast->frame_offset += pkt->size;
810 ast->remaining -= size;
812 avi->stream_index= -1;
819 memset(d, -1, sizeof(int)*8);
820 for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
827 size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
829 n= get_stream_idx(d+2);
830 //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);
831 if(i + (uint64_t)size > avi->fsize || d[0]<0)
835 if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
837 ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
838 ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
840 //av_log(s, AV_LOG_DEBUG, "SKIP\n");
845 if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
850 n= get_stream_idx(d);
852 if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
855 //detect ##ix chunk and skip
856 if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
862 if(n < s->nb_streams){
868 if(s->nb_streams>=2){
869 AVStream *st1 = s->streams[1];
870 AVIStream *ast1= st1->priv_data;
871 //workaround for broken small-file-bug402.avi
872 if( d[2] == 'w' && d[3] == 'b'
874 && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
875 && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
876 && ast->prefix == 'd'*256+'c'
877 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
882 av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
887 if( (st->discard >= AVDISCARD_DEFAULT && size==0)
888 /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
889 || st->discard >= AVDISCARD_ALL){
890 if(ast->sample_size) ast->frame_offset += pkt->size;
891 else ast->frame_offset++;
896 if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
897 int k = get_byte(pb);
898 int last = (k + get_byte(pb) - 1) & 0xFF;
900 get_le16(pb); //flags
902 for (; k <= last; k++)
903 ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
906 } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
907 d[2]*256+d[3] == ast->prefix /*||
908 (d[2] == 'd' && d[3] == 'c') ||
909 (d[2] == 'w' && d[3] == 'b')*/) {
911 //av_log(s, AV_LOG_DEBUG, "OK\n");
912 if(d[2]*256+d[3] == ast->prefix)
915 ast->prefix= d[2]*256+d[3];
916 ast->prefix_count= 0;
919 avi->stream_index= n;
920 ast->packet_size= size + 8;
921 ast->remaining= size;
923 if(size || !ast->sample_size){
924 uint64_t pos= url_ftell(pb) - 8;
925 if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
926 av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
937 /* XXX: We make the implicit supposition that the positions are sorted
939 static int avi_read_idx1(AVFormatContext *s, int size)
941 AVIContext *avi = s->priv_data;
942 ByteIOContext *pb = s->pb;
943 int nb_index_entries, i;
946 unsigned int index, tag, flags, pos, len;
947 unsigned last_pos= -1;
949 nb_index_entries = size / 16;
950 if (nb_index_entries <= 0)
953 /* Read the entries and sort them in each stream component. */
954 for(i = 0; i < nb_index_entries; i++) {
956 flags = get_le32(pb);
959 #if defined(DEBUG_SEEK)
960 av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
961 i, tag, flags, pos, len);
963 if(i==0 && pos > avi->movi_list)
964 avi->movi_list= 0; //FIXME better check
965 pos += avi->movi_list;
967 index = ((tag & 0xff) - '0') * 10;
968 index += ((tag >> 8) & 0xff) - '0';
969 if (index >= s->nb_streams)
971 st = s->streams[index];
974 #if defined(DEBUG_SEEK)
975 av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
981 avi->non_interleaved= 1;
982 else if(len || !ast->sample_size)
983 av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
993 static int guess_ni_flag(AVFormatContext *s){
995 int64_t last_start=0;
996 int64_t first_end= INT64_MAX;
997 int64_t oldpos= url_ftell(s->pb);
999 for(i=0; i<s->nb_streams; i++){
1000 AVStream *st = s->streams[i];
1001 int n= st->nb_index_entries;
1008 int64_t pos= st->index_entries[0].pos;
1009 url_fseek(s->pb, pos + 4, SEEK_SET);
1010 size= get_le32(s->pb);
1011 if(pos + size > st->index_entries[1].pos)
1012 last_start= INT64_MAX;
1015 if(st->index_entries[0].pos > last_start)
1016 last_start= st->index_entries[0].pos;
1017 if(st->index_entries[n-1].pos < first_end)
1018 first_end= st->index_entries[n-1].pos;
1020 url_fseek(s->pb, oldpos, SEEK_SET);
1021 return last_start > first_end;
1024 static int avi_load_index(AVFormatContext *s)
1026 AVIContext *avi = s->priv_data;
1027 ByteIOContext *pb = s->pb;
1029 int64_t pos= url_ftell(pb);
1032 if (url_fseek(pb, avi->movi_end, SEEK_SET) < 0)
1033 goto the_end; // maybe truncated file
1035 printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
1041 size = get_le32(pb);
1043 printf("tag=%c%c%c%c size=0x%x\n",
1051 case MKTAG('i', 'd', 'x', '1'):
1052 if (avi_read_idx1(s, size) < 0)
1060 if (url_fseek(pb, size, SEEK_CUR) < 0)
1061 goto the_end; // something is wrong here
1066 url_fseek(pb, pos, SEEK_SET);
1070 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1072 AVIContext *avi = s->priv_data;
1078 if (!avi->index_loaded) {
1079 /* we only load the index on demand */
1081 avi->index_loaded = 1;
1083 assert(stream_index>= 0);
1085 st = s->streams[stream_index];
1087 index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
1091 /* find the position */
1092 pos = st->index_entries[index].pos;
1093 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1095 // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1097 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1098 /* One and only one real stream for DV in AVI, and it has video */
1099 /* offsets. Calling with other stream indexes should have failed */
1100 /* the av_index_search_timestamp call above. */
1101 assert(stream_index == 0);
1103 /* Feed the DV video stream version of the timestamp to the */
1104 /* DV demux so it can synthesize correct timestamps. */
1105 dv_offset_reset(avi->dv_demux, timestamp);
1107 url_fseek(s->pb, pos, SEEK_SET);
1108 avi->stream_index= -1;
1112 for(i = 0; i < s->nb_streams; i++) {
1113 AVStream *st2 = s->streams[i];
1114 AVIStream *ast2 = st2->priv_data;
1119 if (st2->nb_index_entries <= 0)
1122 // assert(st2->codec->block_align);
1123 assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1124 index = av_index_search_timestamp(
1126 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1127 flags | AVSEEK_FLAG_BACKWARD);
1131 if(!avi->non_interleaved){
1132 while(index>0 && st2->index_entries[index].pos > pos)
1134 while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
1138 // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
1139 /* extract the current frame number */
1140 ast2->frame_offset = st2->index_entries[index].timestamp;
1144 url_fseek(s->pb, pos, SEEK_SET);
1145 avi->stream_index= -1;
1149 static int avi_read_close(AVFormatContext *s)
1152 AVIContext *avi = s->priv_data;
1154 for(i=0;i<s->nb_streams;i++) {
1155 AVStream *st = s->streams[i];
1156 av_free(st->codec->palctrl);
1160 av_free(avi->dv_demux);
1165 static int avi_probe(AVProbeData *p)
1169 /* check file header */
1170 for(i=0; avi_headers[i][0]; i++)
1171 if(!memcmp(p->buf , avi_headers[i] , 4) &&
1172 !memcmp(p->buf+8, avi_headers[i]+4, 4))
1173 return AVPROBE_SCORE_MAX;
1178 AVInputFormat avi_demuxer = {
1180 NULL_IF_CONFIG_SMALL("AVI format"),
1187 .metadata_conv = ff_avi_metadata_conv,