]> git.sesse.net Git - ffmpeg/blob - libavformat/avidec.c
Merge commit '45a1694fde251ee56e23aec073d73172c00aa470'
[ffmpeg] / libavformat / avidec.c
1 /*
2  * AVI demuxer
3  * Copyright (c) 2001 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 #include "libavutil/intreadwrite.h"
23 #include "libavutil/mathematics.h"
24 #include "libavutil/bswap.h"
25 #include "libavutil/opt.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/avassert.h"
29 #include "avformat.h"
30 #include "internal.h"
31 #include "avi.h"
32 #include "dv.h"
33 #include "riff.h"
34
35 typedef struct AVIStream {
36     int64_t frame_offset; /* current frame (video) or byte (audio) counter
37                          (used to compute the pts) */
38     int remaining;
39     int packet_size;
40
41     uint32_t scale;
42     uint32_t rate;
43     int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
44
45     int64_t cum_len; /* temporary storage (used during seek) */
46
47     int prefix;                       ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
48     int prefix_count;
49     uint32_t pal[256];
50     int has_pal;
51     int dshow_block_align;            ///< block align variable used to emulate bugs in the MS dshow demuxer
52
53     AVFormatContext *sub_ctx;
54     AVPacket sub_pkt;
55     uint8_t *sub_buffer;
56
57     int64_t seek_pos;
58 } AVIStream;
59
60 typedef struct {
61     const AVClass *class;
62     int64_t  riff_end;
63     int64_t  movi_end;
64     int64_t  fsize;
65     int64_t io_fsize;
66     int64_t movi_list;
67     int64_t last_pkt_pos;
68     int index_loaded;
69     int is_odml;
70     int non_interleaved;
71     int stream_index;
72     DVDemuxContext* dv_demux;
73     int odml_depth;
74     int use_odml;
75 #define MAX_ODML_DEPTH 1000
76     int64_t dts_max;
77 } AVIContext;
78
79
80 static const AVOption options[] = {
81     { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_INT, {.i64 = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
82     { NULL },
83 };
84
85 static const AVClass demuxer_class = {
86     .class_name = "avi",
87     .item_name  = av_default_item_name,
88     .option     = options,
89     .version    = LIBAVUTIL_VERSION_INT,
90     .category   = AV_CLASS_CATEGORY_DEMUXER,
91 };
92
93
94 static const char avi_headers[][8] = {
95     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', ' ' },
96     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 'X' },
97     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 0x19},
98     { 'O', 'N', '2', ' ',    'O', 'N', '2', 'f' },
99     { 'R', 'I', 'F', 'F',    'A', 'M', 'V', ' ' },
100     { 0 }
101 };
102
103 static const AVMetadataConv avi_metadata_conv[] = {
104     { "strn", "title" },
105     { 0 },
106 };
107
108 static int avi_load_index(AVFormatContext *s);
109 static int guess_ni_flag(AVFormatContext *s);
110
111 #define print_tag(str, tag, size)                       \
112     av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n",       \
113            str, tag & 0xff,                             \
114            (tag >> 8) & 0xff,                           \
115            (tag >> 16) & 0xff,                          \
116            (tag >> 24) & 0xff,                          \
117            size)
118
119 static inline int get_duration(AVIStream *ast, int len){
120     if(ast->sample_size){
121         return len;
122     }else if (ast->dshow_block_align){
123         return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
124     }else
125         return 1;
126 }
127
128 static int get_riff(AVFormatContext *s, AVIOContext *pb)
129 {
130     AVIContext *avi = s->priv_data;
131     char header[8];
132     int i;
133
134     /* check RIFF header */
135     avio_read(pb, header, 4);
136     avi->riff_end = avio_rl32(pb);  /* RIFF chunk size */
137     avi->riff_end += avio_tell(pb); /* RIFF chunk end */
138     avio_read(pb, header+4, 4);
139
140     for(i=0; avi_headers[i][0]; i++)
141         if(!memcmp(header, avi_headers[i], 8))
142             break;
143     if(!avi_headers[i][0])
144         return AVERROR_INVALIDDATA;
145
146     if(header[7] == 0x19)
147         av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
148
149     return 0;
150 }
151
152 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
153     AVIContext *avi = s->priv_data;
154     AVIOContext *pb = s->pb;
155     int longs_pre_entry= avio_rl16(pb);
156     int index_sub_type = avio_r8(pb);
157     int index_type     = avio_r8(pb);
158     int entries_in_use = avio_rl32(pb);
159     int chunk_id       = avio_rl32(pb);
160     int64_t base       = avio_rl64(pb);
161     int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
162     AVStream *st;
163     AVIStream *ast;
164     int i;
165     int64_t last_pos= -1;
166     int64_t filesize= avi->fsize;
167
168     av_dlog(s, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
169             longs_pre_entry,index_type, entries_in_use, chunk_id, base);
170
171     if(stream_id >= s->nb_streams || stream_id < 0)
172         return AVERROR_INVALIDDATA;
173     st= s->streams[stream_id];
174     ast = st->priv_data;
175
176     if(index_sub_type)
177         return AVERROR_INVALIDDATA;
178
179     avio_rl32(pb);
180
181     if(index_type && longs_pre_entry != 2)
182         return AVERROR_INVALIDDATA;
183     if(index_type>1)
184         return AVERROR_INVALIDDATA;
185
186     if(filesize > 0 && base >= filesize){
187         av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
188         if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
189             base &= 0xFFFFFFFF;
190         else
191             return AVERROR_INVALIDDATA;
192     }
193
194     for(i=0; i<entries_in_use; i++){
195         if(index_type){
196             int64_t pos= avio_rl32(pb) + base - 8;
197             int len    = avio_rl32(pb);
198             int key= len >= 0;
199             len &= 0x7FFFFFFF;
200
201 #ifdef DEBUG_SEEK
202             av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
203 #endif
204             if(url_feof(pb))
205                 return AVERROR_INVALIDDATA;
206
207             if(last_pos == pos || pos == base - 8)
208                 avi->non_interleaved= 1;
209             if(last_pos != pos && (len || !ast->sample_size))
210                 av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
211
212             ast->cum_len += get_duration(ast, len);
213             last_pos= pos;
214         }else{
215             int64_t offset, pos;
216             int duration;
217             offset = avio_rl64(pb);
218             avio_rl32(pb);       /* size */
219             duration = avio_rl32(pb);
220
221             if(url_feof(pb))
222                 return AVERROR_INVALIDDATA;
223
224             pos = avio_tell(pb);
225
226             if(avi->odml_depth > MAX_ODML_DEPTH){
227                 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
228                 return AVERROR_INVALIDDATA;
229             }
230
231             if(avio_seek(pb, offset+8, SEEK_SET) < 0)
232                 return -1;
233             avi->odml_depth++;
234             read_braindead_odml_indx(s, frame_num);
235             avi->odml_depth--;
236             frame_num += duration;
237
238             if(avio_seek(pb, pos, SEEK_SET) < 0) {
239                 av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index\n");
240                 return -1;
241             }
242
243         }
244     }
245     avi->index_loaded=2;
246     return 0;
247 }
248
249 static void clean_index(AVFormatContext *s){
250     int i;
251     int64_t j;
252
253     for(i=0; i<s->nb_streams; i++){
254         AVStream *st = s->streams[i];
255         AVIStream *ast = st->priv_data;
256         int n= st->nb_index_entries;
257         int max= ast->sample_size;
258         int64_t pos, size, ts;
259
260         if(n != 1 || ast->sample_size==0)
261             continue;
262
263         while(max < 1024) max+=max;
264
265         pos= st->index_entries[0].pos;
266         size= st->index_entries[0].size;
267         ts= st->index_entries[0].timestamp;
268
269         for(j=0; j<size; j+=max){
270             av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
271         }
272     }
273 }
274
275 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
276 {
277     AVIOContext *pb = s->pb;
278     char key[5] = {0}, *value;
279
280     size += (size & 1);
281
282     if (size == UINT_MAX)
283         return AVERROR(EINVAL);
284     value = av_malloc(size+1);
285     if (!value)
286         return AVERROR(ENOMEM);
287     avio_read(pb, value, size);
288     value[size]=0;
289
290     AV_WL32(key, tag);
291
292     return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
293                             AV_DICT_DONT_STRDUP_VAL);
294 }
295
296 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
297                                     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
298
299 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
300 {
301     char month[4], time[9], buffer[64];
302     int i, day, year;
303     /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
304     if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
305                month, &day, time, &year) == 4) {
306         for (i=0; i<12; i++)
307             if (!av_strcasecmp(month, months[i])) {
308                 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
309                          year, i+1, day, time);
310                 av_dict_set(metadata, "creation_time", buffer, 0);
311             }
312     } else if (date[4] == '/' && date[7] == '/') {
313         date[4] = date[7] = '-';
314         av_dict_set(metadata, "creation_time", date, 0);
315     }
316 }
317
318 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
319 {
320     while (avio_tell(s->pb) < end) {
321         uint32_t tag  = avio_rl32(s->pb);
322         uint32_t size = avio_rl32(s->pb);
323         switch (tag) {
324         case MKTAG('n', 'c', 't', 'g'): {  /* Nikon Tags */
325             uint64_t tag_end = avio_tell(s->pb) + size;
326             while (avio_tell(s->pb) < tag_end) {
327                 uint16_t tag  = avio_rl16(s->pb);
328                 uint16_t size = avio_rl16(s->pb);
329                 const char *name = NULL;
330                 char buffer[64] = {0};
331                 size -= avio_read(s->pb, buffer,
332                                    FFMIN(size, sizeof(buffer)-1));
333                 switch (tag) {
334                 case 0x03:  name = "maker";  break;
335                 case 0x04:  name = "model";  break;
336                 case 0x13:  name = "creation_time";
337                     if (buffer[4] == ':' && buffer[7] == ':')
338                         buffer[4] = buffer[7] = '-';
339                     break;
340                 }
341                 if (name)
342                     av_dict_set(&s->metadata, name, buffer, 0);
343                 avio_skip(s->pb, size);
344             }
345             break;
346         }
347         default:
348             avio_skip(s->pb, size);
349             break;
350         }
351     }
352 }
353
354 static int avi_read_header(AVFormatContext *s)
355 {
356     AVIContext *avi = s->priv_data;
357     AVIOContext *pb = s->pb;
358     unsigned int tag, tag1, handler;
359     int codec_type, stream_index, frame_period;
360     unsigned int size;
361     int i;
362     AVStream *st;
363     AVIStream *ast = NULL;
364     int avih_width=0, avih_height=0;
365     int amv_file_format=0;
366     uint64_t list_end = 0;
367     int ret;
368
369     avi->stream_index= -1;
370
371     ret = get_riff(s, pb);
372     if (ret < 0)
373         return ret;
374
375     av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
376
377     avi->io_fsize = avi->fsize = avio_size(pb);
378     if(avi->fsize<=0 || avi->fsize < avi->riff_end)
379         avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
380
381     /* first list tag */
382     stream_index = -1;
383     codec_type = -1;
384     frame_period = 0;
385     for(;;) {
386         if (url_feof(pb))
387             goto fail;
388         tag = avio_rl32(pb);
389         size = avio_rl32(pb);
390
391         print_tag("tag", tag, size);
392
393         switch(tag) {
394         case MKTAG('L', 'I', 'S', 'T'):
395             list_end = avio_tell(pb) + size;
396             /* Ignored, except at start of video packets. */
397             tag1 = avio_rl32(pb);
398
399             print_tag("list", tag1, 0);
400
401             if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
402                 avi->movi_list = avio_tell(pb) - 4;
403                 if(size) avi->movi_end = avi->movi_list + size + (size & 1);
404                 else     avi->movi_end = avi->fsize;
405                 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
406                 goto end_of_header;
407             }
408             else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
409                 ff_read_riff_info(s, size - 4);
410             else if (tag1 == MKTAG('n', 'c', 'd', 't'))
411                 avi_read_nikon(s, list_end);
412
413             break;
414         case MKTAG('I', 'D', 'I', 'T'): {
415             unsigned char date[64] = {0};
416             size += (size & 1);
417             size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
418             avio_skip(pb, size);
419             avi_metadata_creation_time(&s->metadata, date);
420             break;
421         }
422         case MKTAG('d', 'm', 'l', 'h'):
423             avi->is_odml = 1;
424             avio_skip(pb, size + (size & 1));
425             break;
426         case MKTAG('a', 'm', 'v', 'h'):
427             amv_file_format=1;
428         case MKTAG('a', 'v', 'i', 'h'):
429             /* AVI header */
430             /* using frame_period is bad idea */
431             frame_period = avio_rl32(pb);
432             avio_rl32(pb); /* max. bytes per second */
433             avio_rl32(pb);
434             avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
435
436             avio_skip(pb, 2 * 4);
437             avio_rl32(pb);
438             avio_rl32(pb);
439             avih_width=avio_rl32(pb);
440             avih_height=avio_rl32(pb);
441
442             avio_skip(pb, size - 10 * 4);
443             break;
444         case MKTAG('s', 't', 'r', 'h'):
445             /* stream header */
446
447             tag1 = avio_rl32(pb);
448             handler = avio_rl32(pb); /* codec tag */
449
450             if(tag1 == MKTAG('p', 'a', 'd', 's')){
451                 avio_skip(pb, size - 8);
452                 break;
453             }else{
454                 stream_index++;
455                 st = avformat_new_stream(s, NULL);
456                 if (!st)
457                     goto fail;
458
459                 st->id = stream_index;
460                 ast = av_mallocz(sizeof(AVIStream));
461                 if (!ast)
462                     goto fail;
463                 st->priv_data = ast;
464             }
465             if(amv_file_format)
466                 tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
467
468             print_tag("strh", tag1, -1);
469
470             if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
471                 int64_t dv_dur;
472
473                 /*
474                  * After some consideration -- I don't think we
475                  * have to support anything but DV in type1 AVIs.
476                  */
477                 if (s->nb_streams != 1)
478                     goto fail;
479
480                 if (handler != MKTAG('d', 'v', 's', 'd') &&
481                     handler != MKTAG('d', 'v', 'h', 'd') &&
482                     handler != MKTAG('d', 'v', 's', 'l'))
483                    goto fail;
484
485                 ast = s->streams[0]->priv_data;
486                 av_freep(&s->streams[0]->codec->extradata);
487                 av_freep(&s->streams[0]->codec);
488                 if (s->streams[0]->info)
489                     av_freep(&s->streams[0]->info->duration_error);
490                 av_freep(&s->streams[0]->info);
491                 av_freep(&s->streams[0]);
492                 s->nb_streams = 0;
493                 if (CONFIG_DV_DEMUXER) {
494                     avi->dv_demux = avpriv_dv_init_demux(s);
495                     if (!avi->dv_demux)
496                         goto fail;
497                 }
498                 s->streams[0]->priv_data = ast;
499                 avio_skip(pb, 3 * 4);
500                 ast->scale = avio_rl32(pb);
501                 ast->rate = avio_rl32(pb);
502                 avio_skip(pb, 4);  /* start time */
503
504                 dv_dur = avio_rl32(pb);
505                 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
506                     dv_dur *= AV_TIME_BASE;
507                     s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
508                 }
509                 /*
510                  * else, leave duration alone; timing estimation in utils.c
511                  *      will make a guess based on bitrate.
512                  */
513
514                 stream_index = s->nb_streams - 1;
515                 avio_skip(pb, size - 9*4);
516                 break;
517             }
518
519             av_assert0(stream_index < s->nb_streams);
520             st->codec->stream_codec_tag= handler;
521
522             avio_rl32(pb); /* flags */
523             avio_rl16(pb); /* priority */
524             avio_rl16(pb); /* language */
525             avio_rl32(pb); /* initial frame */
526             ast->scale = avio_rl32(pb);
527             ast->rate = avio_rl32(pb);
528             if(!(ast->scale && ast->rate)){
529                 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                 if(frame_period){
531                     ast->rate = 1000000;
532                     ast->scale = frame_period;
533                 }else{
534                     ast->rate = 25;
535                     ast->scale = 1;
536                 }
537             }
538             avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
539
540             ast->cum_len=avio_rl32(pb); /* start */
541             st->nb_frames = avio_rl32(pb);
542
543             st->start_time = 0;
544             avio_rl32(pb); /* buffer size */
545             avio_rl32(pb); /* quality */
546             if (ast->cum_len*ast->scale/ast->rate > 3600) {
547                 av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
548                 return AVERROR_INVALIDDATA;
549             }
550             ast->sample_size = avio_rl32(pb); /* sample ssize */
551             ast->cum_len *= FFMAX(1, ast->sample_size);
552             av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
553                     ast->rate, ast->scale, ast->sample_size);
554
555             switch(tag1) {
556             case MKTAG('v', 'i', 'd', 's'):
557                 codec_type = AVMEDIA_TYPE_VIDEO;
558
559                 ast->sample_size = 0;
560                 break;
561             case MKTAG('a', 'u', 'd', 's'):
562                 codec_type = AVMEDIA_TYPE_AUDIO;
563                 break;
564             case MKTAG('t', 'x', 't', 's'):
565                 codec_type = AVMEDIA_TYPE_SUBTITLE;
566                 break;
567             case MKTAG('d', 'a', 't', 's'):
568                 codec_type = AVMEDIA_TYPE_DATA;
569                 break;
570             default:
571                 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
572             }
573             if(ast->sample_size == 0) {
574                 st->duration = st->nb_frames;
575                 if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) {
576                     av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n");
577                     st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end);
578                 }
579             }
580             ast->frame_offset= ast->cum_len;
581             avio_skip(pb, size - 12 * 4);
582             break;
583         case MKTAG('s', 't', 'r', 'f'):
584             /* stream header */
585             if (!size)
586                 break;
587             if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
588                 avio_skip(pb, size);
589             } else {
590                 uint64_t cur_pos = avio_tell(pb);
591                 unsigned esize;
592                 if (cur_pos < list_end)
593                     size = FFMIN(size, list_end - cur_pos);
594                 st = s->streams[stream_index];
595                 switch(codec_type) {
596                 case AVMEDIA_TYPE_VIDEO:
597                     if(amv_file_format){
598                         st->codec->width=avih_width;
599                         st->codec->height=avih_height;
600                         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
601                         st->codec->codec_id = AV_CODEC_ID_AMV;
602                         avio_skip(pb, size);
603                         break;
604                     }
605                     tag1 = ff_get_bmp_header(pb, st, &esize);
606
607                     if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
608                         st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
609                         st->codec->codec_tag = tag1;
610                         st->codec->codec_id = AV_CODEC_ID_XSUB;
611                         break;
612                     }
613
614                     if(size > 10*4 && size<(1<<30) && size < avi->fsize){
615                         if(esize == size-1 && (esize&1)) st->codec->extradata_size= esize - 10*4;
616                         else                             st->codec->extradata_size=  size - 10*4;
617                         st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
618                         if (!st->codec->extradata) {
619                             st->codec->extradata_size= 0;
620                             return AVERROR(ENOMEM);
621                         }
622                         avio_read(pb, st->codec->extradata, st->codec->extradata_size);
623                     }
624
625                     if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
626                         avio_r8(pb);
627
628                     /* Extract palette from extradata if bpp <= 8. */
629                     /* This code assumes that extradata contains only palette. */
630                     /* This is true for all paletted codecs implemented in FFmpeg. */
631                     if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
632                         int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
633                         const uint8_t *pal_src;
634
635                         pal_size = FFMIN(pal_size, st->codec->extradata_size);
636                         pal_src = st->codec->extradata + st->codec->extradata_size - pal_size;
637                         for (i = 0; i < pal_size/4; i++)
638                             ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i);
639                         ast->has_pal = 1;
640                     }
641
642                     print_tag("video", tag1, 0);
643
644                     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
645                     st->codec->codec_tag = tag1;
646                     st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
647                     st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
648
649                     if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
650                         st->codec->extradata_size+= 9;
651                         st->codec->extradata= av_realloc_f(st->codec->extradata, 1, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
652                         if(st->codec->extradata)
653                             memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
654                     }
655                     st->codec->height= FFABS(st->codec->height);
656
657 //                    avio_skip(pb, size - 5 * 4);
658                     break;
659                 case AVMEDIA_TYPE_AUDIO:
660                     ret = ff_get_wav_header(pb, st->codec, size);
661                     if (ret < 0)
662                         return ret;
663                     ast->dshow_block_align= st->codec->block_align;
664                     if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
665                         av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
666                         ast->sample_size= st->codec->block_align;
667                     }
668                     if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
669                         avio_skip(pb, 1);
670                     /* Force parsing as several audio frames can be in
671                      * one packet and timestamps refer to packet start. */
672                     st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
673                     /* ADTS header is in extradata, AAC without header must be
674                      * stored as exact frames. Parser not needed and it will
675                      * fail. */
676                     if (st->codec->codec_id == AV_CODEC_ID_AAC && st->codec->extradata_size)
677                         st->need_parsing = AVSTREAM_PARSE_NONE;
678                     /* AVI files with Xan DPCM audio (wrongly) declare PCM
679                      * audio in the header but have Axan as stream_code_tag. */
680                     if (st->codec->stream_codec_tag == AV_RL32("Axan")){
681                         st->codec->codec_id  = AV_CODEC_ID_XAN_DPCM;
682                         st->codec->codec_tag = 0;
683                         ast->dshow_block_align = 0;
684                     }
685                     if (amv_file_format){
686                         st->codec->codec_id  = AV_CODEC_ID_ADPCM_IMA_AMV;
687                         ast->dshow_block_align = 0;
688                     }
689                     if(st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
690                         av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
691                         ast->dshow_block_align = 0;
692                     }
693                     if(st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
694                        st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
695                        st->codec->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
696                         av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
697                         ast->sample_size = 0;
698                     }
699                     break;
700                 case AVMEDIA_TYPE_SUBTITLE:
701                     st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
702                     st->request_probe= 1;
703                     avio_skip(pb, size);
704                     break;
705                 default:
706                     st->codec->codec_type = AVMEDIA_TYPE_DATA;
707                     st->codec->codec_id= AV_CODEC_ID_NONE;
708                     st->codec->codec_tag= 0;
709                     avio_skip(pb, size);
710                     break;
711                 }
712             }
713             break;
714         case MKTAG('s', 't', 'r', 'd'):
715             if (stream_index >= (unsigned)s->nb_streams || s->streams[stream_index]->codec->extradata_size) {
716                 avio_skip(pb, size);
717             } else {
718                 uint64_t cur_pos = avio_tell(pb);
719                 if (cur_pos < list_end)
720                     size = FFMIN(size, list_end - cur_pos);
721                 st = s->streams[stream_index];
722
723                 if(size<(1<<30)){
724                     st->codec->extradata_size= size;
725                     st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
726                     if (!st->codec->extradata) {
727                         st->codec->extradata_size= 0;
728                         return AVERROR(ENOMEM);
729                     }
730                     avio_read(pb, st->codec->extradata, st->codec->extradata_size);
731                 }
732
733                 if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
734                     avio_r8(pb);
735             }
736             break;
737         case MKTAG('i', 'n', 'd', 'x'):
738             i= avio_tell(pb);
739             if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) && avi->use_odml &&
740                read_braindead_odml_indx(s, 0) < 0 && (s->error_recognition & AV_EF_EXPLODE))
741                 goto fail;
742             avio_seek(pb, i+size, SEEK_SET);
743             break;
744         case MKTAG('v', 'p', 'r', 'p'):
745             if(stream_index < (unsigned)s->nb_streams && size > 9*4){
746                 AVRational active, active_aspect;
747
748                 st = s->streams[stream_index];
749                 avio_rl32(pb);
750                 avio_rl32(pb);
751                 avio_rl32(pb);
752                 avio_rl32(pb);
753                 avio_rl32(pb);
754
755                 active_aspect.den= avio_rl16(pb);
756                 active_aspect.num= avio_rl16(pb);
757                 active.num       = avio_rl32(pb);
758                 active.den       = avio_rl32(pb);
759                 avio_rl32(pb); //nbFieldsPerFrame
760
761                 if(active_aspect.num && active_aspect.den && active.num && active.den){
762                     st->sample_aspect_ratio= av_div_q(active_aspect, active);
763                     av_dlog(s, "vprp %d/%d %d/%d\n",
764                             active_aspect.num, active_aspect.den,
765                             active.num, active.den);
766                 }
767                 size -= 9*4;
768             }
769             avio_skip(pb, size);
770             break;
771         case MKTAG('s', 't', 'r', 'n'):
772             if(s->nb_streams){
773                 ret = avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
774                 if (ret < 0)
775                     return ret;
776                 break;
777             }
778         default:
779             if(size > 1000000){
780                 av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
781                                         "I will ignore it and try to continue anyway.\n");
782                 if (s->error_recognition & AV_EF_EXPLODE)
783                     goto fail;
784                 avi->movi_list = avio_tell(pb) - 4;
785                 avi->movi_end  = avi->fsize;
786                 goto end_of_header;
787             }
788             /* skip tag */
789             size += (size & 1);
790             avio_skip(pb, size);
791             break;
792         }
793     }
794  end_of_header:
795     /* check stream number */
796     if (stream_index != s->nb_streams - 1) {
797     fail:
798         return AVERROR_INVALIDDATA;
799     }
800
801     if(!avi->index_loaded && pb->seekable)
802         avi_load_index(s);
803     avi->index_loaded |= 1;
804     avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
805     for(i=0; i<s->nb_streams; i++){
806         AVStream *st = s->streams[i];
807         if(st->nb_index_entries)
808             break;
809     }
810     // DV-in-AVI cannot be non-interleaved, if set this must be
811     // a mis-detection.
812     if(avi->dv_demux)
813         avi->non_interleaved=0;
814     if(i==s->nb_streams && avi->non_interleaved) {
815         av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
816         avi->non_interleaved=0;
817     }
818
819     if(avi->non_interleaved) {
820         av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
821         clean_index(s);
822     }
823
824     ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
825     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
826
827     return 0;
828 }
829
830 static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
831     if (pkt->data && !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
832         uint8_t desc[256];
833         int score = AVPROBE_SCORE_EXTENSION, ret;
834         AVIStream *ast = st->priv_data;
835         AVInputFormat *sub_demuxer;
836         AVRational time_base;
837         AVIOContext *pb = avio_alloc_context( pkt->data + 7,
838                                               pkt->size - 7,
839                                               0, NULL, NULL, NULL, NULL);
840         AVProbeData pd;
841         unsigned int desc_len = avio_rl32(pb);
842
843         if (desc_len > pb->buf_end - pb->buf_ptr)
844             goto error;
845
846         ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
847         avio_skip(pb, desc_len - ret);
848         if (*desc)
849             av_dict_set(&st->metadata, "title", desc, 0);
850
851         avio_rl16(pb);   /* flags? */
852         avio_rl32(pb);   /* data size */
853
854         pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
855         if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
856             goto error;
857
858         if (!(ast->sub_ctx = avformat_alloc_context()))
859             goto error;
860
861         ast->sub_ctx->pb      = pb;
862         if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
863             ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
864             *st->codec = *ast->sub_ctx->streams[0]->codec;
865             ast->sub_ctx->streams[0]->codec->extradata = NULL;
866             time_base = ast->sub_ctx->streams[0]->time_base;
867             avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
868         }
869         ast->sub_buffer = pkt->data;
870         memset(pkt, 0, sizeof(*pkt));
871         return 1;
872 error:
873         av_freep(&pb);
874     }
875     return 0;
876 }
877
878 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
879                                   AVPacket *pkt)
880 {
881     AVIStream *ast, *next_ast = next_st->priv_data;
882     int64_t ts, next_ts, ts_min = INT64_MAX;
883     AVStream *st, *sub_st = NULL;
884     int i;
885
886     next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
887                            AV_TIME_BASE_Q);
888
889     for (i=0; i<s->nb_streams; i++) {
890         st  = s->streams[i];
891         ast = st->priv_data;
892         if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
893             ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
894             if (ts <= next_ts && ts < ts_min) {
895                 ts_min = ts;
896                 sub_st = st;
897             }
898         }
899     }
900
901     if (sub_st) {
902         ast = sub_st->priv_data;
903         *pkt = ast->sub_pkt;
904         pkt->stream_index = sub_st->index;
905         if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
906             ast->sub_pkt.data = NULL;
907     }
908     return sub_st;
909 }
910
911 static int get_stream_idx(int *d){
912     if(    d[0] >= '0' && d[0] <= '9'
913         && d[1] >= '0' && d[1] <= '9'){
914         return (d[0] - '0') * 10 + (d[1] - '0');
915     }else{
916         return 100; //invalid stream ID
917     }
918 }
919
920 /**
921  *
922  * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
923  */
924 static int avi_sync(AVFormatContext *s, int exit_early)
925 {
926     AVIContext *avi = s->priv_data;
927     AVIOContext *pb = s->pb;
928     int n;
929     unsigned int d[8];
930     unsigned int size;
931     int64_t i, sync;
932
933 start_sync:
934     memset(d, -1, sizeof(d));
935     for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
936         int j;
937
938         for(j=0; j<7; j++)
939             d[j]= d[j+1];
940         d[7]= avio_r8(pb);
941
942         size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
943
944         n= get_stream_idx(d+2);
945         av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
946                 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
947         if(i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127)
948             continue;
949
950         //parse ix##
951         if(  (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
952         //parse JUNK
953            ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
954            ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
955             avio_skip(pb, size);
956             goto start_sync;
957         }
958
959         //parse stray LIST
960         if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
961             avio_skip(pb, 4);
962             goto start_sync;
963         }
964
965         n= get_stream_idx(d);
966
967         if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
968             continue;
969
970         //detect ##ix chunk and skip
971         if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
972             avio_skip(pb, size);
973             goto start_sync;
974         }
975
976         //parse ##dc/##wb
977         if(n < s->nb_streams){
978             AVStream *st;
979             AVIStream *ast;
980             st = s->streams[n];
981             ast = st->priv_data;
982
983             if (!ast) {
984                 av_log(s, AV_LOG_WARNING, "Skiping foreign stream %d packet\n", n);
985                 continue;
986             }
987
988             if(s->nb_streams>=2){
989                 AVStream *st1  = s->streams[1];
990                 AVIStream *ast1= st1->priv_data;
991                 //workaround for broken small-file-bug402.avi
992                 if(   d[2] == 'w' && d[3] == 'b'
993                    && n==0
994                    && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
995                    && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
996                    && ast->prefix == 'd'*256+'c'
997                    && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
998                   ){
999                     n=1;
1000                     st = st1;
1001                     ast = ast1;
1002                     av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
1003                 }
1004             }
1005
1006
1007             if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
1008                /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
1009                || st->discard >= AVDISCARD_ALL){
1010                 if (!exit_early) {
1011                     ast->frame_offset += get_duration(ast, size);
1012                 }
1013                 avio_skip(pb, size);
1014                 goto start_sync;
1015             }
1016
1017             if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
1018                 int k = avio_r8(pb);
1019                 int last = (k + avio_r8(pb) - 1) & 0xFF;
1020
1021                 avio_rl16(pb); //flags
1022
1023                 for (; k <= last; k++)
1024                     ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
1025                 ast->has_pal= 1;
1026                 goto start_sync;
1027             } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
1028                          d[2]*256+d[3] == ast->prefix /*||
1029                          (d[2] == 'd' && d[3] == 'c') ||
1030                          (d[2] == 'w' && d[3] == 'b')*/) {
1031
1032                 if (exit_early)
1033                     return 0;
1034                 if(d[2]*256+d[3] == ast->prefix)
1035                     ast->prefix_count++;
1036                 else{
1037                     ast->prefix= d[2]*256+d[3];
1038                     ast->prefix_count= 0;
1039                 }
1040
1041                 avi->stream_index= n;
1042                 ast->packet_size= size + 8;
1043                 ast->remaining= size;
1044
1045                 if(size || !ast->sample_size){
1046                     uint64_t pos= avio_tell(pb) - 8;
1047                     if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
1048                         av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
1049                     }
1050                 }
1051                 return 0;
1052             }
1053         }
1054     }
1055
1056     if(pb->error)
1057         return pb->error;
1058     return AVERROR_EOF;
1059 }
1060
1061 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1062 {
1063     AVIContext *avi = s->priv_data;
1064     AVIOContext *pb = s->pb;
1065     int err;
1066 #if FF_API_DESTRUCT_PACKET
1067     void* dstr;
1068 #endif
1069
1070     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1071         int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1072         if (size >= 0)
1073             return size;
1074     }
1075
1076     if(avi->non_interleaved){
1077         int best_stream_index = 0;
1078         AVStream *best_st= NULL;
1079         AVIStream *best_ast;
1080         int64_t best_ts= INT64_MAX;
1081         int i;
1082
1083         for(i=0; i<s->nb_streams; i++){
1084             AVStream *st = s->streams[i];
1085             AVIStream *ast = st->priv_data;
1086             int64_t ts= ast->frame_offset;
1087             int64_t last_ts;
1088
1089             if(!st->nb_index_entries)
1090                 continue;
1091
1092             last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1093             if(!ast->remaining && ts > last_ts)
1094                 continue;
1095
1096             ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
1097
1098             av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
1099                     st->time_base.num, st->time_base.den, ast->frame_offset);
1100             if(ts < best_ts){
1101                 best_ts= ts;
1102                 best_st= st;
1103                 best_stream_index= i;
1104             }
1105         }
1106         if(!best_st)
1107             return AVERROR_EOF;
1108
1109         best_ast = best_st->priv_data;
1110         best_ts = best_ast->frame_offset;
1111         if(best_ast->remaining)
1112             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
1113         else{
1114             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1115             if(i>=0)
1116                 best_ast->frame_offset= best_st->index_entries[i].timestamp;
1117         }
1118
1119         if(i>=0){
1120             int64_t pos= best_st->index_entries[i].pos;
1121             pos += best_ast->packet_size - best_ast->remaining;
1122             if(avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
1123               return AVERROR_EOF;
1124
1125             av_assert0(best_ast->remaining <= best_ast->packet_size);
1126
1127             avi->stream_index= best_stream_index;
1128             if(!best_ast->remaining)
1129                 best_ast->packet_size=
1130                 best_ast->remaining= best_st->index_entries[i].size;
1131         }
1132         else
1133           return AVERROR_EOF;
1134     }
1135
1136 resync:
1137     if(avi->stream_index >= 0){
1138         AVStream *st= s->streams[ avi->stream_index ];
1139         AVIStream *ast= st->priv_data;
1140         int size, err;
1141
1142         if(get_subtitle_pkt(s, st, pkt))
1143             return 0;
1144
1145         if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1146             size= INT_MAX;
1147         else if(ast->sample_size < 32)
1148             // arbitrary multiplier to avoid tiny packets for raw PCM data
1149             size= 1024*ast->sample_size;
1150         else
1151             size= ast->sample_size;
1152
1153         if(size > ast->remaining)
1154             size= ast->remaining;
1155         avi->last_pkt_pos= avio_tell(pb);
1156         err= av_get_packet(pb, pkt, size);
1157         if(err<0)
1158             return err;
1159         size = err;
1160
1161         if(ast->has_pal && pkt->size<(unsigned)INT_MAX/2){
1162             uint8_t *pal;
1163             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
1164             if(!pal){
1165                 av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
1166             }else{
1167                 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1168                 ast->has_pal = 0;
1169             }
1170         }
1171
1172         if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1173             AVBufferRef *avbuf = pkt->buf;
1174 #if FF_API_DESTRUCT_PACKET
1175             dstr = pkt->destruct;
1176 #endif
1177             size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1178                                     pkt->data, pkt->size, pkt->pos);
1179 #if FF_API_DESTRUCT_PACKET
1180             pkt->destruct = dstr;
1181 #endif
1182             pkt->buf = avbuf;
1183             pkt->flags |= AV_PKT_FLAG_KEY;
1184             if (size < 0)
1185                 av_free_packet(pkt);
1186         } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
1187                    && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1188             ast->frame_offset++;
1189             avi->stream_index = -1;
1190             ast->remaining = 0;
1191             goto resync;
1192         } else {
1193             /* XXX: How to handle B-frames in AVI? */
1194             pkt->dts = ast->frame_offset;
1195 //                pkt->dts += ast->start;
1196             if(ast->sample_size)
1197                 pkt->dts /= ast->sample_size;
1198             av_dlog(s, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n",
1199                     pkt->dts, ast->frame_offset, ast->scale, ast->rate,
1200                     ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
1201             pkt->stream_index = avi->stream_index;
1202
1203             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1204                 AVIndexEntry *e;
1205                 int index;
1206                 av_assert0(st->index_entries);
1207
1208                 index= av_index_search_timestamp(st, ast->frame_offset, 0);
1209                 e= &st->index_entries[index];
1210
1211                 if(index >= 0 && e->timestamp == ast->frame_offset){
1212                     if (index == st->nb_index_entries-1){
1213                         int key=1;
1214                         int i;
1215                         uint32_t state=-1;
1216                         for(i=0; i<FFMIN(size,256); i++){
1217                             if(st->codec->codec_id == AV_CODEC_ID_MPEG4){
1218                                 if(state == 0x1B6){
1219                                     key= !(pkt->data[i]&0xC0);
1220                                     break;
1221                                 }
1222                             }else
1223                                 break;
1224                             state= (state<<8) + pkt->data[i];
1225                         }
1226                         if(!key)
1227                             e->flags &= ~AVINDEX_KEYFRAME;
1228                     }
1229                     if (e->flags & AVINDEX_KEYFRAME)
1230                         pkt->flags |= AV_PKT_FLAG_KEY;
1231                 }
1232             } else {
1233                 pkt->flags |= AV_PKT_FLAG_KEY;
1234             }
1235             ast->frame_offset += get_duration(ast, pkt->size);
1236         }
1237         ast->remaining -= err;
1238         if(!ast->remaining){
1239             avi->stream_index= -1;
1240             ast->packet_size= 0;
1241         }
1242
1243         if(!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos){
1244             av_free_packet(pkt);
1245             goto resync;
1246         }
1247         ast->seek_pos= 0;
1248
1249         if(!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1){
1250             int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
1251
1252             if(avi->dts_max - dts > 2*AV_TIME_BASE){
1253                 avi->non_interleaved= 1;
1254                 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
1255             }else if(avi->dts_max < dts)
1256                 avi->dts_max = dts;
1257         }
1258
1259         return 0;
1260     }
1261
1262     if ((err = avi_sync(s, 0)) < 0)
1263         return err;
1264     goto resync;
1265 }
1266
1267 /* XXX: We make the implicit supposition that the positions are sorted
1268    for each stream. */
1269 static int avi_read_idx1(AVFormatContext *s, int size)
1270 {
1271     AVIContext *avi = s->priv_data;
1272     AVIOContext *pb = s->pb;
1273     int nb_index_entries, i;
1274     AVStream *st;
1275     AVIStream *ast;
1276     unsigned int index, tag, flags, pos, len, first_packet = 1;
1277     unsigned last_pos= -1;
1278     unsigned last_idx= -1;
1279     int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1280     int anykey = 0;
1281
1282     nb_index_entries = size / 16;
1283     if (nb_index_entries <= 0)
1284         return AVERROR_INVALIDDATA;
1285
1286     idx1_pos = avio_tell(pb);
1287     avio_seek(pb, avi->movi_list+4, SEEK_SET);
1288     if (avi_sync(s, 1) == 0) {
1289         first_packet_pos = avio_tell(pb) - 8;
1290     }
1291     avi->stream_index = -1;
1292     avio_seek(pb, idx1_pos, SEEK_SET);
1293
1294     if (s->nb_streams == 1 && s->streams[0]->codec->codec_tag == AV_RL32("MMES")){
1295         first_packet_pos = 0;
1296         data_offset = avi->movi_list;
1297     }
1298
1299     /* Read the entries and sort them in each stream component. */
1300     for(i = 0; i < nb_index_entries; i++) {
1301         if(url_feof(pb))
1302             return -1;
1303
1304         tag = avio_rl32(pb);
1305         flags = avio_rl32(pb);
1306         pos = avio_rl32(pb);
1307         len = avio_rl32(pb);
1308         av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1309                 i, tag, flags, pos, len);
1310
1311         index = ((tag & 0xff) - '0') * 10;
1312         index += ((tag >> 8) & 0xff) - '0';
1313         if (index >= s->nb_streams)
1314             continue;
1315         st = s->streams[index];
1316         ast = st->priv_data;
1317
1318         if(first_packet && first_packet_pos && len) {
1319             data_offset = first_packet_pos - pos;
1320             first_packet = 0;
1321         }
1322         pos += data_offset;
1323
1324         av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1325
1326         // even if we have only a single stream, we should
1327         // switch to non-interleaved to get correct timestamps
1328         if(last_pos == pos)
1329             avi->non_interleaved= 1;
1330         if(last_idx != pos && len) {
1331             av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1332             last_idx= pos;
1333         }
1334         ast->cum_len += get_duration(ast, len);
1335         last_pos= pos;
1336         anykey |= flags&AVIIF_INDEX;
1337     }
1338     if (!anykey) {
1339         for (index = 0; index < s->nb_streams; index++) {
1340             st = s->streams[index];
1341             if (st->nb_index_entries)
1342                 st->index_entries[0].flags |= AVINDEX_KEYFRAME;
1343         }
1344     }
1345     return 0;
1346 }
1347
1348 static int guess_ni_flag(AVFormatContext *s){
1349     int i;
1350     int64_t last_start=0;
1351     int64_t first_end= INT64_MAX;
1352     int64_t oldpos= avio_tell(s->pb);
1353     int *idx;
1354     int64_t min_pos, pos;
1355
1356     for(i=0; i<s->nb_streams; i++){
1357         AVStream *st = s->streams[i];
1358         int n= st->nb_index_entries;
1359         unsigned int size;
1360
1361         if(n <= 0)
1362             continue;
1363
1364         if(n >= 2){
1365             int64_t pos= st->index_entries[0].pos;
1366             avio_seek(s->pb, pos + 4, SEEK_SET);
1367             size= avio_rl32(s->pb);
1368             if(pos + size > st->index_entries[1].pos)
1369                 last_start= INT64_MAX;
1370         }
1371
1372         if(st->index_entries[0].pos > last_start)
1373             last_start= st->index_entries[0].pos;
1374         if(st->index_entries[n-1].pos < first_end)
1375             first_end= st->index_entries[n-1].pos;
1376     }
1377     avio_seek(s->pb, oldpos, SEEK_SET);
1378     if (last_start > first_end)
1379         return 1;
1380     idx= av_mallocz(sizeof(*idx) * s->nb_streams);
1381     for (min_pos=pos=0; min_pos!=INT64_MAX; pos= min_pos+1LU) {
1382         int64_t max_dts = INT64_MIN/2, min_dts= INT64_MAX/2;
1383         min_pos = INT64_MAX;
1384
1385         for (i=0; i<s->nb_streams; i++) {
1386             AVStream *st = s->streams[i];
1387             int n= st->nb_index_entries;
1388             while (idx[i]<n && st->index_entries[idx[i]].pos < pos)
1389                 idx[i]++;
1390             if (idx[i] < n) {
1391                 min_dts = FFMIN(min_dts, av_rescale_q(st->index_entries[idx[i]].timestamp, st->time_base, AV_TIME_BASE_Q));
1392                 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
1393             }
1394             if (idx[i])
1395                 max_dts = FFMAX(max_dts, av_rescale_q(st->index_entries[idx[i]-1].timestamp, st->time_base, AV_TIME_BASE_Q));
1396         }
1397         if(max_dts - min_dts > 2*AV_TIME_BASE) {
1398             av_free(idx);
1399             return 1;
1400         }
1401     }
1402     av_free(idx);
1403     return 0;
1404 }
1405
1406 static int avi_load_index(AVFormatContext *s)
1407 {
1408     AVIContext *avi = s->priv_data;
1409     AVIOContext *pb = s->pb;
1410     uint32_t tag, size;
1411     int64_t pos= avio_tell(pb);
1412     int64_t next;
1413     int ret = -1;
1414
1415     if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1416         goto the_end; // maybe truncated file
1417     av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1418     for(;;) {
1419         tag = avio_rl32(pb);
1420         size = avio_rl32(pb);
1421         if (url_feof(pb))
1422             break;
1423         next = avio_tell(pb) + size + (size & 1);
1424
1425         av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1426                  tag        & 0xff,
1427                 (tag >>  8) & 0xff,
1428                 (tag >> 16) & 0xff,
1429                 (tag >> 24) & 0xff,
1430                 size);
1431
1432         if (tag == MKTAG('i', 'd', 'x', '1') &&
1433             avi_read_idx1(s, size) >= 0) {
1434             avi->index_loaded=2;
1435             ret = 0;
1436         }else if(tag == MKTAG('L', 'I', 'S', 'T')) {
1437             uint32_t tag1 = avio_rl32(pb);
1438
1439             if (tag1 == MKTAG('I', 'N', 'F', 'O'))
1440                 ff_read_riff_info(s, size - 4);
1441         }else if(!ret)
1442             break;
1443
1444         if (avio_seek(pb, next, SEEK_SET) < 0)
1445             break; // something is wrong here
1446     }
1447  the_end:
1448     avio_seek(pb, pos, SEEK_SET);
1449     return ret;
1450 }
1451
1452 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1453 {
1454     AVIStream *ast2 = st2->priv_data;
1455     int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1456     av_free_packet(&ast2->sub_pkt);
1457     if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1458         avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1459         ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1460 }
1461
1462 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1463 {
1464     AVIContext *avi = s->priv_data;
1465     AVStream *st;
1466     int i, index;
1467     int64_t pos, pos_min;
1468     AVIStream *ast;
1469
1470     if (!avi->index_loaded) {
1471         /* we only load the index on demand */
1472         avi_load_index(s);
1473         avi->index_loaded |= 1;
1474     }
1475     av_assert0(stream_index>= 0);
1476
1477     st = s->streams[stream_index];
1478     ast= st->priv_data;
1479     index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
1480     if (index<0) {
1481         if (st->nb_index_entries > 0)
1482             av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
1483                    timestamp * FFMAX(ast->sample_size, 1),
1484                    st->index_entries[0].timestamp,
1485                    st->index_entries[st->nb_index_entries - 1].timestamp);
1486         return AVERROR_INVALIDDATA;
1487     }
1488
1489     /* find the position */
1490     pos = st->index_entries[index].pos;
1491     timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1492
1493     av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
1494             timestamp, index, st->index_entries[index].timestamp);
1495
1496     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1497         /* One and only one real stream for DV in AVI, and it has video  */
1498         /* offsets. Calling with other stream indexes should have failed */
1499         /* the av_index_search_timestamp call above.                     */
1500         av_assert0(stream_index == 0);
1501
1502         if(avio_seek(s->pb, pos, SEEK_SET) < 0)
1503             return -1;
1504
1505         /* Feed the DV video stream version of the timestamp to the */
1506         /* DV demux so it can synthesize correct timestamps.        */
1507         ff_dv_offset_reset(avi->dv_demux, timestamp);
1508
1509         avi->stream_index= -1;
1510         return 0;
1511     }
1512
1513     pos_min= pos;
1514     for(i = 0; i < s->nb_streams; i++) {
1515         AVStream *st2 = s->streams[i];
1516         AVIStream *ast2 = st2->priv_data;
1517
1518         ast2->packet_size=
1519         ast2->remaining= 0;
1520
1521         if (ast2->sub_ctx) {
1522             seek_subtitle(st, st2, timestamp);
1523             continue;
1524         }
1525
1526         if (st2->nb_index_entries <= 0)
1527             continue;
1528
1529 //        av_assert1(st2->codec->block_align);
1530         av_assert0((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1531         index = av_index_search_timestamp(
1532                 st2,
1533                 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1534                 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1535         if(index<0)
1536             index=0;
1537         ast2->seek_pos= st2->index_entries[index].pos;
1538         pos_min= FFMIN(pos_min,ast2->seek_pos);
1539     }
1540     for(i = 0; i < s->nb_streams; i++) {
1541         AVStream *st2 = s->streams[i];
1542         AVIStream *ast2 = st2->priv_data;
1543
1544         if (ast2->sub_ctx || st2->nb_index_entries <= 0)
1545             continue;
1546
1547         index = av_index_search_timestamp(
1548                 st2,
1549                 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1550                 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1551         if(index<0)
1552             index=0;
1553         while(!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
1554             index--;
1555         ast2->frame_offset = st2->index_entries[index].timestamp;
1556     }
1557
1558     /* do the seek */
1559     if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
1560         av_log(s, AV_LOG_ERROR, "Seek failed\n");
1561         return -1;
1562     }
1563     avi->stream_index= -1;
1564     avi->dts_max= INT_MIN;
1565     return 0;
1566 }
1567
1568 static int avi_read_close(AVFormatContext *s)
1569 {
1570     int i;
1571     AVIContext *avi = s->priv_data;
1572
1573     for(i=0;i<s->nb_streams;i++) {
1574         AVStream *st = s->streams[i];
1575         AVIStream *ast = st->priv_data;
1576         if (ast) {
1577             if (ast->sub_ctx) {
1578                 av_freep(&ast->sub_ctx->pb);
1579                 avformat_close_input(&ast->sub_ctx);
1580             }
1581             av_free(ast->sub_buffer);
1582             av_free_packet(&ast->sub_pkt);
1583         }
1584     }
1585
1586     av_free(avi->dv_demux);
1587
1588     return 0;
1589 }
1590
1591 static int avi_probe(AVProbeData *p)
1592 {
1593     int i;
1594
1595     /* check file header */
1596     for(i=0; avi_headers[i][0]; i++)
1597         if(!memcmp(p->buf  , avi_headers[i]  , 4) &&
1598            !memcmp(p->buf+8, avi_headers[i]+4, 4))
1599             return AVPROBE_SCORE_MAX;
1600
1601     return 0;
1602 }
1603
1604 AVInputFormat ff_avi_demuxer = {
1605     .name           = "avi",
1606     .long_name      = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1607     .priv_data_size = sizeof(AVIContext),
1608     .read_probe     = avi_probe,
1609     .read_header    = avi_read_header,
1610     .read_packet    = avi_read_packet,
1611     .read_close     = avi_read_close,
1612     .read_seek      = avi_read_seek,
1613     .priv_class = &demuxer_class,
1614 };