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