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