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
26 #include "libavutil/intreadwrite.h"
27 #include "libavutil/bswap.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;
71 DVDemuxContext* dv_demux;
73 #define MAX_ODML_DEPTH 1000
76 static const char avi_headers[][8] = {
77 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
78 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
79 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
80 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
81 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
85 static int avi_load_index(AVFormatContext *s);
86 static int guess_ni_flag(AVFormatContext *s);
88 #define print_tag(str, tag, size) \
89 av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
96 static inline int get_duration(AVIStream *ast, int len){
99 }else if (ast->dshow_block_align){
100 return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
105 static int get_riff(AVFormatContext *s, AVIOContext *pb)
107 AVIContext *avi = s->priv_data;
111 /* check RIFF header */
112 avio_read(pb, header, 4);
113 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
114 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
115 avio_read(pb, header+4, 4);
117 for(i=0; avi_headers[i][0]; i++)
118 if(!memcmp(header, avi_headers[i], 8))
120 if(!avi_headers[i][0])
123 if(header[7] == 0x19)
124 av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
129 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
130 AVIContext *avi = s->priv_data;
131 AVIOContext *pb = s->pb;
132 int longs_pre_entry= avio_rl16(pb);
133 int index_sub_type = avio_r8(pb);
134 int index_type = avio_r8(pb);
135 int entries_in_use = avio_rl32(pb);
136 int chunk_id = avio_rl32(pb);
137 int64_t base = avio_rl64(pb);
138 int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
142 int64_t last_pos= -1;
143 int64_t filesize= avio_size(s->pb);
146 av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
147 longs_pre_entry,index_type, entries_in_use, chunk_id, base);
150 if(stream_id >= s->nb_streams || stream_id < 0)
152 st= s->streams[stream_id];
160 if(index_type && longs_pre_entry != 2)
165 if(filesize > 0 && base >= filesize){
166 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
167 if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
173 for(i=0; i<entries_in_use; i++){
175 int64_t pos= avio_rl32(pb) + base - 8;
176 int len = avio_rl32(pb);
181 av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
186 if(last_pos == pos || pos == base - 8)
187 avi->non_interleaved= 1;
188 if(last_pos != pos && (len || !ast->sample_size))
189 av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
191 ast->cum_len += get_duration(ast, len);
196 offset = avio_rl64(pb);
197 avio_rl32(pb); /* size */
198 duration = avio_rl32(pb);
205 if(avi->odml_depth > MAX_ODML_DEPTH){
206 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
210 avio_seek(pb, offset+8, SEEK_SET);
212 read_braindead_odml_indx(s, frame_num);
214 frame_num += duration;
216 avio_seek(pb, pos, SEEK_SET);
223 static void clean_index(AVFormatContext *s){
227 for(i=0; i<s->nb_streams; i++){
228 AVStream *st = s->streams[i];
229 AVIStream *ast = st->priv_data;
230 int n= st->nb_index_entries;
231 int max= ast->sample_size;
232 int64_t pos, size, ts;
234 if(n != 1 || ast->sample_size==0)
237 while(max < 1024) max+=max;
239 pos= st->index_entries[0].pos;
240 size= st->index_entries[0].size;
241 ts= st->index_entries[0].timestamp;
243 for(j=0; j<size; j+=max){
244 av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
249 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
251 AVIOContext *pb = s->pb;
252 char key[5] = {0}, *value;
256 if (size == UINT_MAX)
258 value = av_malloc(size+1);
261 avio_read(pb, value, size);
266 return av_metadata_set2(st ? &st->metadata : &s->metadata, key, value,
267 AV_METADATA_DONT_STRDUP_VAL);
270 static void avi_read_info(AVFormatContext *s, uint64_t end)
272 while (avio_tell(s->pb) < end) {
273 uint32_t tag = avio_rl32(s->pb);
274 uint32_t size = avio_rl32(s->pb);
275 avi_read_tag(s, NULL, tag, size);
279 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
280 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
282 static void avi_metadata_creation_time(AVMetadata **metadata, char *date)
284 char month[4], time[9], buffer[64];
286 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
287 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
288 month, &day, time, &year) == 4) {
290 if (!strcasecmp(month, months[i])) {
291 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
292 year, i+1, day, time);
293 av_metadata_set2(metadata, "creation_time", buffer, 0);
295 } else if (date[4] == '/' && date[7] == '/') {
296 date[4] = date[7] = '-';
297 av_metadata_set2(metadata, "creation_time", date, 0);
301 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
303 while (avio_tell(s->pb) < end) {
304 uint32_t tag = avio_rl32(s->pb);
305 uint32_t size = avio_rl32(s->pb);
307 case MKTAG('n', 'c', 't', 'g'): { /* Nikon Tags */
308 uint64_t tag_end = avio_tell(s->pb) + size;
309 while (avio_tell(s->pb) < tag_end) {
310 uint16_t tag = avio_rl16(s->pb);
311 uint16_t size = avio_rl16(s->pb);
312 const char *name = NULL;
313 char buffer[64] = {0};
314 size -= avio_read(s->pb, buffer,
315 FFMIN(size, sizeof(buffer)-1));
317 case 0x03: name = "maker"; break;
318 case 0x04: name = "model"; break;
319 case 0x13: name = "creation_time";
320 if (buffer[4] == ':' && buffer[7] == ':')
321 buffer[4] = buffer[7] = '-';
325 av_metadata_set2(&s->metadata, name, buffer, 0);
326 avio_skip(s->pb, size);
331 avio_skip(s->pb, size);
337 static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
339 AVIContext *avi = s->priv_data;
340 AVIOContext *pb = s->pb;
341 unsigned int tag, tag1, handler;
342 int codec_type, stream_index, frame_period, bit_rate;
346 AVIStream *ast = NULL;
347 int avih_width=0, avih_height=0;
348 int amv_file_format=0;
349 uint64_t list_end = 0;
352 avi->stream_index= -1;
354 if (get_riff(s, pb) < 0)
357 avi->fsize = avio_size(pb);
359 avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
369 size = avio_rl32(pb);
371 print_tag("tag", tag, size);
374 case MKTAG('L', 'I', 'S', 'T'):
375 list_end = avio_tell(pb) + size;
376 /* Ignored, except at start of video packets. */
377 tag1 = avio_rl32(pb);
379 print_tag("list", tag1, 0);
381 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
382 avi->movi_list = avio_tell(pb) - 4;
383 if(size) avi->movi_end = avi->movi_list + size + (size & 1);
384 else avi->movi_end = avio_size(pb);
385 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
388 else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
389 avi_read_info(s, list_end);
390 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
391 avi_read_nikon(s, list_end);
394 case MKTAG('I', 'D', 'I', 'T'): {
395 unsigned char date[64] = {0};
397 size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
399 avi_metadata_creation_time(&s->metadata, date);
402 case MKTAG('d', 'm', 'l', 'h'):
404 avio_skip(pb, size + (size & 1));
406 case MKTAG('a', 'm', 'v', 'h'):
408 case MKTAG('a', 'v', 'i', 'h'):
410 /* using frame_period is bad idea */
411 frame_period = avio_rl32(pb);
412 bit_rate = avio_rl32(pb) * 8;
414 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
416 avio_skip(pb, 2 * 4);
419 avih_width=avio_rl32(pb);
420 avih_height=avio_rl32(pb);
422 avio_skip(pb, size - 10 * 4);
424 case MKTAG('s', 't', 'r', 'h'):
427 tag1 = avio_rl32(pb);
428 handler = avio_rl32(pb); /* codec tag */
430 if(tag1 == MKTAG('p', 'a', 'd', 's')){
431 avio_skip(pb, size - 8);
435 st = av_new_stream(s, stream_index);
439 ast = av_mallocz(sizeof(AVIStream));
445 tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
447 print_tag("strh", tag1, -1);
449 if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
453 * After some consideration -- I don't think we
454 * have to support anything but DV in type1 AVIs.
456 if (s->nb_streams != 1)
459 if (handler != MKTAG('d', 'v', 's', 'd') &&
460 handler != MKTAG('d', 'v', 'h', 'd') &&
461 handler != MKTAG('d', 'v', 's', 'l'))
464 ast = s->streams[0]->priv_data;
465 av_freep(&s->streams[0]->codec->extradata);
466 av_freep(&s->streams[0]->codec);
467 av_freep(&s->streams[0]);
469 if (CONFIG_DV_DEMUXER) {
470 avi->dv_demux = dv_init_demux(s);
474 s->streams[0]->priv_data = ast;
475 avio_skip(pb, 3 * 4);
476 ast->scale = avio_rl32(pb);
477 ast->rate = avio_rl32(pb);
478 avio_skip(pb, 4); /* start time */
480 dv_dur = avio_rl32(pb);
481 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
482 dv_dur *= AV_TIME_BASE;
483 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
486 * else, leave duration alone; timing estimation in utils.c
487 * will make a guess based on bitrate.
490 stream_index = s->nb_streams - 1;
491 avio_skip(pb, size - 9*4);
495 assert(stream_index < s->nb_streams);
496 st->codec->stream_codec_tag= handler;
498 avio_rl32(pb); /* flags */
499 avio_rl16(pb); /* priority */
500 avio_rl16(pb); /* language */
501 avio_rl32(pb); /* initial frame */
502 ast->scale = avio_rl32(pb);
503 ast->rate = avio_rl32(pb);
504 if(!(ast->scale && ast->rate)){
505 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);
508 ast->scale = frame_period;
514 av_set_pts_info(st, 64, ast->scale, ast->rate);
516 ast->cum_len=avio_rl32(pb); /* start */
517 st->nb_frames = avio_rl32(pb);
520 avio_rl32(pb); /* buffer size */
521 avio_rl32(pb); /* quality */
522 ast->sample_size = avio_rl32(pb); /* sample ssize */
523 ast->cum_len *= FFMAX(1, ast->sample_size);
524 // av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
527 case MKTAG('v', 'i', 'd', 's'):
528 codec_type = AVMEDIA_TYPE_VIDEO;
530 ast->sample_size = 0;
532 case MKTAG('a', 'u', 'd', 's'):
533 codec_type = AVMEDIA_TYPE_AUDIO;
535 case MKTAG('t', 'x', 't', 's'):
536 codec_type = AVMEDIA_TYPE_SUBTITLE;
538 case MKTAG('d', 'a', 't', 's'):
539 codec_type = AVMEDIA_TYPE_DATA;
542 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
545 if(ast->sample_size == 0)
546 st->duration = st->nb_frames;
547 ast->frame_offset= ast->cum_len;
548 avio_skip(pb, size - 12 * 4);
550 case MKTAG('s', 't', 'r', 'f'):
552 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
555 uint64_t cur_pos = avio_tell(pb);
556 if (cur_pos < list_end)
557 size = FFMIN(size, list_end - cur_pos);
558 st = s->streams[stream_index];
560 case AVMEDIA_TYPE_VIDEO:
562 st->codec->width=avih_width;
563 st->codec->height=avih_height;
564 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
565 st->codec->codec_id = CODEC_ID_AMV;
569 tag1 = ff_get_bmp_header(pb, st);
571 if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
572 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
573 st->codec->codec_tag = tag1;
574 st->codec->codec_id = CODEC_ID_XSUB;
578 if(size > 10*4 && size<(1<<30)){
579 st->codec->extradata_size= size - 10*4;
580 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
581 if (!st->codec->extradata) {
582 st->codec->extradata_size= 0;
583 return AVERROR(ENOMEM);
585 avio_read(pb, st->codec->extradata, st->codec->extradata_size);
588 if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
591 /* Extract palette from extradata if bpp <= 8. */
592 /* This code assumes that extradata contains only palette. */
593 /* This is true for all paletted codecs implemented in FFmpeg. */
594 if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
595 int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
596 const uint8_t *pal_src;
598 pal_size = FFMIN(pal_size, st->codec->extradata_size);
599 pal_src = st->codec->extradata + st->codec->extradata_size - pal_size;
601 for (i = 0; i < pal_size/4; i++)
602 ast->pal[i] = AV_RL32(pal_src+4*i);
604 memcpy(ast->pal, pal_src, pal_size);
609 print_tag("video", tag1, 0);
611 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
612 st->codec->codec_tag = tag1;
613 st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
614 st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
615 // Support "Resolution 1:1" for Avid AVI Codec
616 if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
617 st->codec->extradata_size >= 31 &&
618 !memcmp(&st->codec->extradata[28], "1:1", 3))
619 st->codec->codec_id = CODEC_ID_RAWVIDEO;
621 if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
622 st->codec->extradata_size+= 9;
623 st->codec->extradata= av_realloc(st->codec->extradata, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
624 if(st->codec->extradata)
625 memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
627 st->codec->height= FFABS(st->codec->height);
629 // avio_skip(pb, size - 5 * 4);
631 case AVMEDIA_TYPE_AUDIO:
632 ret = ff_get_wav_header(pb, st->codec, size);
635 ast->dshow_block_align= st->codec->block_align;
636 if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
637 av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
638 ast->sample_size= st->codec->block_align;
640 if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
642 /* Force parsing as several audio frames can be in
643 * one packet and timestamps refer to packet start. */
644 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
645 /* ADTS header is in extradata, AAC without header must be
646 * stored as exact frames. Parser not needed and it will
648 if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
649 st->need_parsing = AVSTREAM_PARSE_NONE;
650 /* AVI files with Xan DPCM audio (wrongly) declare PCM
651 * audio in the header but have Axan as stream_code_tag. */
652 if (st->codec->stream_codec_tag == AV_RL32("Axan")){
653 st->codec->codec_id = CODEC_ID_XAN_DPCM;
654 st->codec->codec_tag = 0;
656 if (amv_file_format){
657 st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
658 ast->dshow_block_align = 0;
661 case AVMEDIA_TYPE_SUBTITLE:
662 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
663 st->request_probe= 1;
666 st->codec->codec_type = AVMEDIA_TYPE_DATA;
667 st->codec->codec_id= CODEC_ID_NONE;
668 st->codec->codec_tag= 0;
674 case MKTAG('i', 'n', 'd', 'x'):
676 if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX)){
677 read_braindead_odml_indx(s, 0);
679 avio_seek(pb, i+size, SEEK_SET);
681 case MKTAG('v', 'p', 'r', 'p'):
682 if(stream_index < (unsigned)s->nb_streams && size > 9*4){
683 AVRational active, active_aspect;
685 st = s->streams[stream_index];
692 active_aspect.den= avio_rl16(pb);
693 active_aspect.num= avio_rl16(pb);
694 active.num = avio_rl32(pb);
695 active.den = avio_rl32(pb);
696 avio_rl32(pb); //nbFieldsPerFrame
698 if(active_aspect.num && active_aspect.den && active.num && active.den){
699 st->sample_aspect_ratio= av_div_q(active_aspect, active);
700 //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
706 case MKTAG('s', 't', 'r', 'n'):
708 avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
713 av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
714 "I will ignore it and try to continue anyway.\n");
715 avi->movi_list = avio_tell(pb) - 4;
716 avi->movi_end = avio_size(pb);
726 /* check stream number */
727 if (stream_index != s->nb_streams - 1) {
732 if(!avi->index_loaded && pb->seekable)
734 avi->index_loaded = 1;
735 avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
736 for(i=0; i<s->nb_streams; i++){
737 AVStream *st = s->streams[i];
738 if(st->nb_index_entries)
741 // DV-in-AVI cannot be non-interleaved, if set this must be
744 avi->non_interleaved=0;
745 if(i==s->nb_streams && avi->non_interleaved) {
746 av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
747 avi->non_interleaved=0;
750 if(avi->non_interleaved) {
751 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
755 ff_metadata_conv_ctx(s, NULL, ff_avi_metadata_conv);
760 static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
761 if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
763 int score = AVPROBE_SCORE_MAX / 2, ret;
764 AVIStream *ast = st->priv_data;
765 AVInputFormat *sub_demuxer;
766 AVRational time_base;
767 AVIOContext *pb = avio_alloc_context( pkt->data + 7,
769 0, NULL, NULL, NULL, NULL);
771 unsigned int desc_len = avio_rl32(pb);
773 if (desc_len > pb->buf_end - pb->buf_ptr)
776 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
777 avio_skip(pb, desc_len - ret);
779 av_metadata_set2(&st->metadata, "title", desc, 0);
781 avio_rl16(pb); /* flags? */
782 avio_rl32(pb); /* data size */
784 pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
785 if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
788 if (!av_open_input_stream(&ast->sub_ctx, pb, "", sub_demuxer, NULL)) {
789 av_read_packet(ast->sub_ctx, &ast->sub_pkt);
790 *st->codec = *ast->sub_ctx->streams[0]->codec;
791 ast->sub_ctx->streams[0]->codec->extradata = NULL;
792 time_base = ast->sub_ctx->streams[0]->time_base;
793 av_set_pts_info(st, 64, time_base.num, time_base.den);
795 ast->sub_buffer = pkt->data;
796 memset(pkt, 0, sizeof(*pkt));
804 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
807 AVIStream *ast, *next_ast = next_st->priv_data;
808 int64_t ts, next_ts, ts_min = INT64_MAX;
809 AVStream *st, *sub_st = NULL;
812 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
815 for (i=0; i<s->nb_streams; i++) {
818 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
819 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
820 if (ts <= next_ts && ts < ts_min) {
828 ast = sub_st->priv_data;
830 pkt->stream_index = sub_st->index;
831 if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
832 ast->sub_pkt.data = NULL;
837 static int get_stream_idx(int *d){
838 if( d[0] >= '0' && d[0] <= '9'
839 && d[1] >= '0' && d[1] <= '9'){
840 return (d[0] - '0') * 10 + (d[1] - '0');
842 return 100; //invalid stream ID
846 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
848 AVIContext *avi = s->priv_data;
849 AVIOContext *pb = s->pb;
855 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
856 int size = dv_get_packet(avi->dv_demux, pkt);
861 if(avi->non_interleaved){
862 int best_stream_index = 0;
863 AVStream *best_st= NULL;
865 int64_t best_ts= INT64_MAX;
868 for(i=0; i<s->nb_streams; i++){
869 AVStream *st = s->streams[i];
870 AVIStream *ast = st->priv_data;
871 int64_t ts= ast->frame_offset;
874 if(!st->nb_index_entries)
877 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
878 if(!ast->remaining && ts > last_ts)
881 ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
883 // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
887 best_stream_index= i;
893 best_ast = best_st->priv_data;
894 best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
895 if(best_ast->remaining)
896 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
898 i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
900 best_ast->frame_offset= best_st->index_entries[i].timestamp;
903 // av_log(s, AV_LOG_DEBUG, "%d\n", i);
905 int64_t pos= best_st->index_entries[i].pos;
906 pos += best_ast->packet_size - best_ast->remaining;
907 avio_seek(s->pb, pos + 8, SEEK_SET);
908 // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
910 assert(best_ast->remaining <= best_ast->packet_size);
912 avi->stream_index= best_stream_index;
913 if(!best_ast->remaining)
914 best_ast->packet_size=
915 best_ast->remaining= best_st->index_entries[i].size;
920 if(avi->stream_index >= 0){
921 AVStream *st= s->streams[ avi->stream_index ];
922 AVIStream *ast= st->priv_data;
925 if(get_subtitle_pkt(s, st, pkt))
928 if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
930 else if(ast->sample_size < 32)
931 // arbitrary multiplier to avoid tiny packets for raw PCM data
932 size= 1024*ast->sample_size;
934 size= ast->sample_size;
936 if(size > ast->remaining)
937 size= ast->remaining;
938 avi->last_pkt_pos= avio_tell(pb);
939 err= av_get_packet(pb, pkt, size);
943 if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
945 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
947 av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
949 memcpy(pal, ast->pal, AVPALETTE_SIZE);
954 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
955 dstr = pkt->destruct;
956 size = dv_produce_packet(avi->dv_demux, pkt,
957 pkt->data, pkt->size);
958 pkt->destruct = dstr;
959 pkt->flags |= AV_PKT_FLAG_KEY;
962 } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
963 && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
965 avi->stream_index = -1;
969 /* XXX: How to handle B-frames in AVI? */
970 pkt->dts = ast->frame_offset;
971 // pkt->dts += ast->start;
973 pkt->dts /= ast->sample_size;
974 //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);
975 pkt->stream_index = avi->stream_index;
977 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
980 assert(st->index_entries);
982 index= av_index_search_timestamp(st, ast->frame_offset, 0);
983 e= &st->index_entries[index];
985 if(index >= 0 && e->timestamp == ast->frame_offset){
986 if (e->flags & AVINDEX_KEYFRAME)
987 pkt->flags |= AV_PKT_FLAG_KEY;
990 pkt->flags |= AV_PKT_FLAG_KEY;
992 ast->frame_offset += get_duration(ast, pkt->size);
994 ast->remaining -= size;
996 avi->stream_index= -1;
1000 if(!avi->non_interleaved && ast->seek_pos > pkt->pos){
1001 av_free_packet(pkt);
1009 memset(d, -1, sizeof(int)*8);
1010 for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
1017 size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
1019 n= get_stream_idx(d+2);
1020 //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);
1021 if(i + (uint64_t)size > avi->fsize || d[0]<0)
1025 if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
1027 ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
1028 ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
1029 avio_skip(pb, size);
1030 //av_log(s, AV_LOG_DEBUG, "SKIP\n");
1035 if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
1040 n= get_stream_idx(d);
1042 if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
1045 //detect ##ix chunk and skip
1046 if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
1047 avio_skip(pb, size);
1052 if(n < s->nb_streams){
1056 ast = st->priv_data;
1058 if(s->nb_streams>=2){
1059 AVStream *st1 = s->streams[1];
1060 AVIStream *ast1= st1->priv_data;
1061 //workaround for broken small-file-bug402.avi
1062 if( d[2] == 'w' && d[3] == 'b'
1064 && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
1065 && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
1066 && ast->prefix == 'd'*256+'c'
1067 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
1072 av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
1077 if( (st->discard >= AVDISCARD_DEFAULT && size==0)
1078 /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
1079 || st->discard >= AVDISCARD_ALL){
1080 ast->frame_offset += get_duration(ast, size);
1081 avio_skip(pb, size);
1085 if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
1086 int k = avio_r8(pb);
1087 int last = (k + avio_r8(pb) - 1) & 0xFF;
1089 avio_rl16(pb); //flags
1091 for (; k <= last; k++)
1092 ast->pal[k] = avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
1095 } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
1096 d[2]*256+d[3] == ast->prefix /*||
1097 (d[2] == 'd' && d[3] == 'c') ||
1098 (d[2] == 'w' && d[3] == 'b')*/) {
1100 //av_log(s, AV_LOG_DEBUG, "OK\n");
1101 if(d[2]*256+d[3] == ast->prefix)
1102 ast->prefix_count++;
1104 ast->prefix= d[2]*256+d[3];
1105 ast->prefix_count= 0;
1108 avi->stream_index= n;
1109 ast->packet_size= size + 8;
1110 ast->remaining= size;
1112 if(size || !ast->sample_size){
1113 uint64_t pos= avio_tell(pb) - 8;
1114 if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
1115 av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
1126 /* XXX: We make the implicit supposition that the positions are sorted
1128 static int avi_read_idx1(AVFormatContext *s, int size)
1130 AVIContext *avi = s->priv_data;
1131 AVIOContext *pb = s->pb;
1132 int nb_index_entries, i;
1135 unsigned int index, tag, flags, pos, len;
1136 unsigned last_pos= -1;
1138 nb_index_entries = size / 16;
1139 if (nb_index_entries <= 0)
1142 /* Read the entries and sort them in each stream component. */
1143 for(i = 0; i < nb_index_entries; i++) {
1144 tag = avio_rl32(pb);
1145 flags = avio_rl32(pb);
1146 pos = avio_rl32(pb);
1147 len = avio_rl32(pb);
1148 #if defined(DEBUG_SEEK)
1149 av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1150 i, tag, flags, pos, len);
1152 if(i==0 && pos > avi->movi_list)
1153 avi->movi_list= 0; //FIXME better check
1154 pos += avi->movi_list;
1156 index = ((tag & 0xff) - '0') * 10;
1157 index += ((tag >> 8) & 0xff) - '0';
1158 if (index >= s->nb_streams)
1160 st = s->streams[index];
1161 ast = st->priv_data;
1163 #if defined(DEBUG_SEEK)
1164 av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1170 avi->non_interleaved= 1;
1171 else if(len || !ast->sample_size)
1172 av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1173 ast->cum_len += get_duration(ast, len);
1179 static int guess_ni_flag(AVFormatContext *s){
1181 int64_t last_start=0;
1182 int64_t first_end= INT64_MAX;
1183 int64_t oldpos= avio_tell(s->pb);
1185 for(i=0; i<s->nb_streams; i++){
1186 AVStream *st = s->streams[i];
1187 int n= st->nb_index_entries;
1194 int64_t pos= st->index_entries[0].pos;
1195 avio_seek(s->pb, pos + 4, SEEK_SET);
1196 size= avio_rl32(s->pb);
1197 if(pos + size > st->index_entries[1].pos)
1198 last_start= INT64_MAX;
1201 if(st->index_entries[0].pos > last_start)
1202 last_start= st->index_entries[0].pos;
1203 if(st->index_entries[n-1].pos < first_end)
1204 first_end= st->index_entries[n-1].pos;
1206 avio_seek(s->pb, oldpos, SEEK_SET);
1207 return last_start > first_end;
1210 static int avi_load_index(AVFormatContext *s)
1212 AVIContext *avi = s->priv_data;
1213 AVIOContext *pb = s->pb;
1215 int64_t pos= avio_tell(pb);
1218 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1219 goto the_end; // maybe truncated file
1221 printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
1226 tag = avio_rl32(pb);
1227 size = avio_rl32(pb);
1229 printf("tag=%c%c%c%c size=0x%x\n",
1237 case MKTAG('i', 'd', 'x', '1'):
1238 if (avi_read_idx1(s, size) < 0)
1246 if (avio_skip(pb, size) < 0)
1247 goto the_end; // something is wrong here
1252 avio_seek(pb, pos, SEEK_SET);
1256 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1258 AVIStream *ast2 = st2->priv_data;
1259 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1260 av_free_packet(&ast2->sub_pkt);
1261 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1262 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1263 av_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1266 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1268 AVIContext *avi = s->priv_data;
1271 int64_t pos, pos_min;
1274 if (!avi->index_loaded) {
1275 /* we only load the index on demand */
1277 avi->index_loaded = 1;
1279 assert(stream_index>= 0);
1281 st = s->streams[stream_index];
1283 index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
1287 /* find the position */
1288 pos = st->index_entries[index].pos;
1289 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1291 // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1293 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1294 /* One and only one real stream for DV in AVI, and it has video */
1295 /* offsets. Calling with other stream indexes should have failed */
1296 /* the av_index_search_timestamp call above. */
1297 assert(stream_index == 0);
1299 /* Feed the DV video stream version of the timestamp to the */
1300 /* DV demux so it can synthesize correct timestamps. */
1301 dv_offset_reset(avi->dv_demux, timestamp);
1303 avio_seek(s->pb, pos, SEEK_SET);
1304 avi->stream_index= -1;
1309 for(i = 0; i < s->nb_streams; i++) {
1310 AVStream *st2 = s->streams[i];
1311 AVIStream *ast2 = st2->priv_data;
1316 if (ast2->sub_ctx) {
1317 seek_subtitle(st, st2, timestamp);
1321 if (st2->nb_index_entries <= 0)
1324 // assert(st2->codec->block_align);
1325 assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1326 index = av_index_search_timestamp(
1328 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1329 flags | AVSEEK_FLAG_BACKWARD);
1332 ast2->seek_pos= st2->index_entries[index].pos;
1333 pos_min= FFMIN(pos_min,ast2->seek_pos);
1334 ast2->frame_offset = st2->index_entries[index].timestamp;
1338 avio_seek(s->pb, pos_min, SEEK_SET);
1339 avi->stream_index= -1;
1343 static int avi_read_close(AVFormatContext *s)
1346 AVIContext *avi = s->priv_data;
1348 for(i=0;i<s->nb_streams;i++) {
1349 AVStream *st = s->streams[i];
1350 AVIStream *ast = st->priv_data;
1353 av_freep(&ast->sub_ctx->pb);
1354 av_close_input_stream(ast->sub_ctx);
1356 av_free(ast->sub_buffer);
1357 av_free_packet(&ast->sub_pkt);
1361 av_free(avi->dv_demux);
1366 static int avi_probe(AVProbeData *p)
1370 /* check file header */
1371 for(i=0; avi_headers[i][0]; i++)
1372 if(!memcmp(p->buf , avi_headers[i] , 4) &&
1373 !memcmp(p->buf+8, avi_headers[i]+4, 4))
1374 return AVPROBE_SCORE_MAX;
1379 AVInputFormat ff_avi_demuxer = {
1381 NULL_IF_CONFIG_SMALL("AVI format"),