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