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