]> git.sesse.net Git - ffmpeg/blob - libavformat/avidec.c
Merge commit '605b047bcc48482dc8a356f56629da259fbddbf1'
[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, {.i64 = 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 AVERROR_INVALIDDATA;
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 AVERROR_INVALIDDATA;
172     st= s->streams[stream_id];
173     ast = st->priv_data;
174
175     if(index_sub_type)
176         return AVERROR_INVALIDDATA;
177
178     avio_rl32(pb);
179
180     if(index_type && longs_pre_entry != 2)
181         return AVERROR_INVALIDDATA;
182     if(index_type>1)
183         return AVERROR_INVALIDDATA;
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 AVERROR_INVALIDDATA;
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 AVERROR_INVALIDDATA;
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 AVERROR_INVALIDDATA;
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 AVERROR_INVALIDDATA;
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 AVERROR(EINVAL);
283     value = av_malloc(size+1);
284     if (!value)
285         return AVERROR(ENOMEM);
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     ret = get_riff(s, pb);
371     if (ret < 0)
372         return ret;
373
374     av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
375
376     avi->fsize = avio_size(pb);
377     if(avi->fsize<=0 || avi->fsize < avi->riff_end)
378         avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
379
380     /* first list tag */
381     stream_index = -1;
382     codec_type = -1;
383     frame_period = 0;
384     for(;;) {
385         if (url_feof(pb))
386             goto fail;
387         tag = avio_rl32(pb);
388         size = avio_rl32(pb);
389
390         print_tag("tag", tag, size);
391
392         switch(tag) {
393         case MKTAG('L', 'I', 'S', 'T'):
394             list_end = avio_tell(pb) + size;
395             /* Ignored, except at start of video packets. */
396             tag1 = avio_rl32(pb);
397
398             print_tag("list", tag1, 0);
399
400             if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
401                 avi->movi_list = avio_tell(pb) - 4;
402                 if(size) avi->movi_end = avi->movi_list + size + (size & 1);
403                 else     avi->movi_end = avi->fsize;
404                 av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
405                 goto end_of_header;
406             }
407             else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
408                 ff_read_riff_info(s, size - 4);
409             else if (tag1 == MKTAG('n', 'c', 'd', 't'))
410                 avi_read_nikon(s, list_end);
411
412             break;
413         case MKTAG('I', 'D', 'I', 'T'): {
414             unsigned char date[64] = {0};
415             size += (size & 1);
416             size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
417             avio_skip(pb, size);
418             avi_metadata_creation_time(&s->metadata, date);
419             break;
420         }
421         case MKTAG('d', 'm', 'l', 'h'):
422             avi->is_odml = 1;
423             avio_skip(pb, size + (size & 1));
424             break;
425         case MKTAG('a', 'm', 'v', 'h'):
426             amv_file_format=1;
427         case MKTAG('a', 'v', 'i', 'h'):
428             /* AVI header */
429             /* using frame_period is bad idea */
430             frame_period = avio_rl32(pb);
431             avio_rl32(pb); /* max. bytes per second */
432             avio_rl32(pb);
433             avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
434
435             avio_skip(pb, 2 * 4);
436             avio_rl32(pb);
437             avio_rl32(pb);
438             avih_width=avio_rl32(pb);
439             avih_height=avio_rl32(pb);
440
441             avio_skip(pb, size - 10 * 4);
442             break;
443         case MKTAG('s', 't', 'r', 'h'):
444             /* stream header */
445
446             tag1 = avio_rl32(pb);
447             handler = avio_rl32(pb); /* codec tag */
448
449             if(tag1 == MKTAG('p', 'a', 'd', 's')){
450                 avio_skip(pb, size - 8);
451                 break;
452             }else{
453                 stream_index++;
454                 st = avformat_new_stream(s, NULL);
455                 if (!st)
456                     goto fail;
457
458                 st->id = stream_index;
459                 ast = av_mallocz(sizeof(AVIStream));
460                 if (!ast)
461                     goto fail;
462                 st->priv_data = ast;
463             }
464             if(amv_file_format)
465                 tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
466
467             print_tag("strh", tag1, -1);
468
469             if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
470                 int64_t dv_dur;
471
472                 /*
473                  * After some consideration -- I don't think we
474                  * have to support anything but DV in type1 AVIs.
475                  */
476                 if (s->nb_streams != 1)
477                     goto fail;
478
479                 if (handler != MKTAG('d', 'v', 's', 'd') &&
480                     handler != MKTAG('d', 'v', 'h', 'd') &&
481                     handler != MKTAG('d', 'v', 's', 'l'))
482                    goto fail;
483
484                 ast = s->streams[0]->priv_data;
485                 av_freep(&s->streams[0]->codec->extradata);
486                 av_freep(&s->streams[0]->codec);
487                 av_freep(&s->streams[0]->info);
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             av_assert0(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_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
550                     ast->rate, ast->scale, ast->sample_size);
551
552             switch(tag1) {
553             case MKTAG('v', 'i', 'd', 's'):
554                 codec_type = AVMEDIA_TYPE_VIDEO;
555
556                 ast->sample_size = 0;
557                 break;
558             case MKTAG('a', 'u', 'd', 's'):
559                 codec_type = AVMEDIA_TYPE_AUDIO;
560                 break;
561             case MKTAG('t', 'x', 't', 's'):
562                 codec_type = AVMEDIA_TYPE_SUBTITLE;
563                 break;
564             case MKTAG('d', 'a', 't', 's'):
565                 codec_type = AVMEDIA_TYPE_DATA;
566                 break;
567             default:
568                 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
569             }
570             if(ast->sample_size == 0)
571                 st->duration = st->nb_frames;
572             ast->frame_offset= ast->cum_len;
573             avio_skip(pb, size - 12 * 4);
574             break;
575         case MKTAG('s', 't', 'r', 'f'):
576             /* stream header */
577             if (!size)
578                 break;
579             if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
580                 avio_skip(pb, size);
581             } else {
582                 uint64_t cur_pos = avio_tell(pb);
583                 unsigned esize;
584                 if (cur_pos < list_end)
585                     size = FFMIN(size, list_end - cur_pos);
586                 st = s->streams[stream_index];
587                 switch(codec_type) {
588                 case AVMEDIA_TYPE_VIDEO:
589                     if(amv_file_format){
590                         st->codec->width=avih_width;
591                         st->codec->height=avih_height;
592                         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
593                         st->codec->codec_id = AV_CODEC_ID_AMV;
594                         avio_skip(pb, size);
595                         break;
596                     }
597                     tag1 = ff_get_bmp_header(pb, st, &esize);
598
599                     if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
600                         st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
601                         st->codec->codec_tag = tag1;
602                         st->codec->codec_id = AV_CODEC_ID_XSUB;
603                         break;
604                     }
605
606                     if(size > 10*4 && size<(1<<30) && size < avi->fsize){
607                         if(esize == size-1 && (esize&1)) st->codec->extradata_size= esize - 10*4;
608                         else                             st->codec->extradata_size=  size - 10*4;
609                         st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
610                         if (!st->codec->extradata) {
611                             st->codec->extradata_size= 0;
612                             return AVERROR(ENOMEM);
613                         }
614                         avio_read(pb, st->codec->extradata, st->codec->extradata_size);
615                     }
616
617                     if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
618                         avio_r8(pb);
619
620                     /* Extract palette from extradata if bpp <= 8. */
621                     /* This code assumes that extradata contains only palette. */
622                     /* This is true for all paletted codecs implemented in FFmpeg. */
623                     if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
624                         int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
625                         const uint8_t *pal_src;
626
627                         pal_size = FFMIN(pal_size, st->codec->extradata_size);
628                         pal_src = st->codec->extradata + st->codec->extradata_size - pal_size;
629                         for (i = 0; i < pal_size/4; i++)
630                             ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i);
631                         ast->has_pal = 1;
632                     }
633
634                     print_tag("video", tag1, 0);
635
636                     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
637                     st->codec->codec_tag = tag1;
638                     st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
639                     st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
640
641                     if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
642                         st->codec->extradata_size+= 9;
643                         st->codec->extradata= av_realloc_f(st->codec->extradata, 1, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
644                         if(st->codec->extradata)
645                             memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
646                     }
647                     st->codec->height= FFABS(st->codec->height);
648
649 //                    avio_skip(pb, size - 5 * 4);
650                     break;
651                 case AVMEDIA_TYPE_AUDIO:
652                     ret = ff_get_wav_header(pb, st->codec, size);
653                     if (ret < 0)
654                         return ret;
655                     ast->dshow_block_align= st->codec->block_align;
656                     if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
657                         av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
658                         ast->sample_size= st->codec->block_align;
659                     }
660                     if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
661                         avio_skip(pb, 1);
662                     /* Force parsing as several audio frames can be in
663                      * one packet and timestamps refer to packet start. */
664                     st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
665                     /* ADTS header is in extradata, AAC without header must be
666                      * stored as exact frames. Parser not needed and it will
667                      * fail. */
668                     if (st->codec->codec_id == AV_CODEC_ID_AAC && st->codec->extradata_size)
669                         st->need_parsing = AVSTREAM_PARSE_NONE;
670                     /* AVI files with Xan DPCM audio (wrongly) declare PCM
671                      * audio in the header but have Axan as stream_code_tag. */
672                     if (st->codec->stream_codec_tag == AV_RL32("Axan")){
673                         st->codec->codec_id  = AV_CODEC_ID_XAN_DPCM;
674                         st->codec->codec_tag = 0;
675                         ast->dshow_block_align = 0;
676                     }
677                     if (amv_file_format){
678                         st->codec->codec_id  = AV_CODEC_ID_ADPCM_IMA_AMV;
679                         ast->dshow_block_align = 0;
680                     }
681                     if(st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
682                         av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
683                         ast->dshow_block_align = 0;
684                     }
685                     if(st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
686                        st->codec->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
687                        st->codec->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
688                         av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
689                         ast->sample_size = 0;
690                     }
691                     break;
692                 case AVMEDIA_TYPE_SUBTITLE:
693                     st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
694                     st->request_probe= 1;
695                     avio_skip(pb, size);
696                     break;
697                 default:
698                     st->codec->codec_type = AVMEDIA_TYPE_DATA;
699                     st->codec->codec_id= AV_CODEC_ID_NONE;
700                     st->codec->codec_tag= 0;
701                     avio_skip(pb, size);
702                     break;
703                 }
704             }
705             break;
706         case MKTAG('s', 't', 'r', 'd'):
707             if (stream_index >= (unsigned)s->nb_streams || s->streams[stream_index]->codec->extradata_size) {
708                 avio_skip(pb, size);
709             } else {
710                 uint64_t cur_pos = avio_tell(pb);
711                 if (cur_pos < list_end)
712                     size = FFMIN(size, list_end - cur_pos);
713                 st = s->streams[stream_index];
714
715                 if(size<(1<<30)){
716                     st->codec->extradata_size= size;
717                     st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
718                     if (!st->codec->extradata) {
719                         st->codec->extradata_size= 0;
720                         return AVERROR(ENOMEM);
721                     }
722                     avio_read(pb, st->codec->extradata, st->codec->extradata_size);
723                 }
724
725                 if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
726                     avio_r8(pb);
727             }
728             break;
729         case MKTAG('i', 'n', 'd', 'x'):
730             i= avio_tell(pb);
731             if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) && avi->use_odml &&
732                read_braindead_odml_indx(s, 0) < 0 && (s->error_recognition & AV_EF_EXPLODE))
733                 goto fail;
734             avio_seek(pb, i+size, SEEK_SET);
735             break;
736         case MKTAG('v', 'p', 'r', 'p'):
737             if(stream_index < (unsigned)s->nb_streams && size > 9*4){
738                 AVRational active, active_aspect;
739
740                 st = s->streams[stream_index];
741                 avio_rl32(pb);
742                 avio_rl32(pb);
743                 avio_rl32(pb);
744                 avio_rl32(pb);
745                 avio_rl32(pb);
746
747                 active_aspect.den= avio_rl16(pb);
748                 active_aspect.num= avio_rl16(pb);
749                 active.num       = avio_rl32(pb);
750                 active.den       = avio_rl32(pb);
751                 avio_rl32(pb); //nbFieldsPerFrame
752
753                 if(active_aspect.num && active_aspect.den && active.num && active.den){
754                     st->sample_aspect_ratio= av_div_q(active_aspect, active);
755                     av_dlog(s, "vprp %d/%d %d/%d\n",
756                             active_aspect.num, active_aspect.den,
757                             active.num, active.den);
758                 }
759                 size -= 9*4;
760             }
761             avio_skip(pb, size);
762             break;
763         case MKTAG('s', 't', 'r', 'n'):
764             if(s->nb_streams){
765                 ret = avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
766                 if (ret < 0)
767                     return ret;
768                 break;
769             }
770         default:
771             if(size > 1000000){
772                 av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
773                                         "I will ignore it and try to continue anyway.\n");
774                 if (s->error_recognition & AV_EF_EXPLODE)
775                     goto fail;
776                 avi->movi_list = avio_tell(pb) - 4;
777                 avi->movi_end  = avi->fsize;
778                 goto end_of_header;
779             }
780             /* skip tag */
781             size += (size & 1);
782             avio_skip(pb, size);
783             break;
784         }
785     }
786  end_of_header:
787     /* check stream number */
788     if (stream_index != s->nb_streams - 1) {
789     fail:
790         return AVERROR_INVALIDDATA;
791     }
792
793     if(!avi->index_loaded && pb->seekable)
794         avi_load_index(s);
795     avi->index_loaded |= 1;
796     avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
797     for(i=0; i<s->nb_streams; i++){
798         AVStream *st = s->streams[i];
799         if(st->nb_index_entries)
800             break;
801     }
802     // DV-in-AVI cannot be non-interleaved, if set this must be
803     // a mis-detection.
804     if(avi->dv_demux)
805         avi->non_interleaved=0;
806     if(i==s->nb_streams && avi->non_interleaved) {
807         av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
808         avi->non_interleaved=0;
809     }
810
811     if(avi->non_interleaved) {
812         av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
813         clean_index(s);
814     }
815
816     ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
817     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
818
819     return 0;
820 }
821
822 static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
823     if (pkt->data && !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
824         uint8_t desc[256];
825         int score = AVPROBE_SCORE_MAX / 2, ret;
826         AVIStream *ast = st->priv_data;
827         AVInputFormat *sub_demuxer;
828         AVRational time_base;
829         AVIOContext *pb = avio_alloc_context( pkt->data + 7,
830                                               pkt->size - 7,
831                                               0, NULL, NULL, NULL, NULL);
832         AVProbeData pd;
833         unsigned int desc_len = avio_rl32(pb);
834
835         if (desc_len > pb->buf_end - pb->buf_ptr)
836             goto error;
837
838         ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
839         avio_skip(pb, desc_len - ret);
840         if (*desc)
841             av_dict_set(&st->metadata, "title", desc, 0);
842
843         avio_rl16(pb);   /* flags? */
844         avio_rl32(pb);   /* data size */
845
846         pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
847         if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
848             goto error;
849
850         if (!(ast->sub_ctx = avformat_alloc_context()))
851             goto error;
852
853         ast->sub_ctx->pb      = pb;
854         if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
855             ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
856             *st->codec = *ast->sub_ctx->streams[0]->codec;
857             ast->sub_ctx->streams[0]->codec->extradata = NULL;
858             time_base = ast->sub_ctx->streams[0]->time_base;
859             avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
860         }
861         ast->sub_buffer = pkt->data;
862         memset(pkt, 0, sizeof(*pkt));
863         return 1;
864 error:
865         av_freep(&pb);
866     }
867     return 0;
868 }
869
870 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
871                                   AVPacket *pkt)
872 {
873     AVIStream *ast, *next_ast = next_st->priv_data;
874     int64_t ts, next_ts, ts_min = INT64_MAX;
875     AVStream *st, *sub_st = NULL;
876     int i;
877
878     next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
879                            AV_TIME_BASE_Q);
880
881     for (i=0; i<s->nb_streams; i++) {
882         st  = s->streams[i];
883         ast = st->priv_data;
884         if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
885             ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
886             if (ts <= next_ts && ts < ts_min) {
887                 ts_min = ts;
888                 sub_st = st;
889             }
890         }
891     }
892
893     if (sub_st) {
894         ast = sub_st->priv_data;
895         *pkt = ast->sub_pkt;
896         pkt->stream_index = sub_st->index;
897         if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
898             ast->sub_pkt.data = NULL;
899     }
900     return sub_st;
901 }
902
903 static int get_stream_idx(int *d){
904     if(    d[0] >= '0' && d[0] <= '9'
905         && d[1] >= '0' && d[1] <= '9'){
906         return (d[0] - '0') * 10 + (d[1] - '0');
907     }else{
908         return 100; //invalid stream ID
909     }
910 }
911
912 /**
913  *
914  * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
915  */
916 static int avi_sync(AVFormatContext *s, int exit_early)
917 {
918     AVIContext *avi = s->priv_data;
919     AVIOContext *pb = s->pb;
920     int n;
921     unsigned int d[8];
922     unsigned int size;
923     int64_t i, sync;
924
925 start_sync:
926     memset(d, -1, sizeof(d));
927     for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
928         int j;
929
930         for(j=0; j<7; j++)
931             d[j]= d[j+1];
932         d[7]= avio_r8(pb);
933
934         size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
935
936         n= get_stream_idx(d+2);
937         av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
938                 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
939         if(i + (uint64_t)size > avi->fsize || d[0] > 127)
940             continue;
941
942         //parse ix##
943         if(  (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
944         //parse JUNK
945            ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
946            ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
947             avio_skip(pb, size);
948             goto start_sync;
949         }
950
951         //parse stray LIST
952         if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
953             avio_skip(pb, 4);
954             goto start_sync;
955         }
956
957         n= get_stream_idx(d);
958
959         if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
960             continue;
961
962         //detect ##ix chunk and skip
963         if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
964             avio_skip(pb, size);
965             goto start_sync;
966         }
967
968         //parse ##dc/##wb
969         if(n < s->nb_streams){
970             AVStream *st;
971             AVIStream *ast;
972             st = s->streams[n];
973             ast = st->priv_data;
974
975             if (!ast) {
976                 av_log(s, AV_LOG_WARNING, "Skiping foreign stream %d packet\n", n);
977                 continue;
978             }
979
980             if(s->nb_streams>=2){
981                 AVStream *st1  = s->streams[1];
982                 AVIStream *ast1= st1->priv_data;
983                 //workaround for broken small-file-bug402.avi
984                 if(   d[2] == 'w' && d[3] == 'b'
985                    && n==0
986                    && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
987                    && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
988                    && ast->prefix == 'd'*256+'c'
989                    && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
990                   ){
991                     n=1;
992                     st = st1;
993                     ast = ast1;
994                     av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
995                 }
996             }
997
998
999             if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
1000                /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
1001                || st->discard >= AVDISCARD_ALL){
1002                 if (!exit_early) {
1003                     ast->frame_offset += get_duration(ast, size);
1004                 }
1005                 avio_skip(pb, size);
1006                 goto start_sync;
1007             }
1008
1009             if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
1010                 int k = avio_r8(pb);
1011                 int last = (k + avio_r8(pb) - 1) & 0xFF;
1012
1013                 avio_rl16(pb); //flags
1014
1015                 for (; k <= last; k++)
1016                     ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
1017                 ast->has_pal= 1;
1018                 goto start_sync;
1019             } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
1020                          d[2]*256+d[3] == ast->prefix /*||
1021                          (d[2] == 'd' && d[3] == 'c') ||
1022                          (d[2] == 'w' && d[3] == 'b')*/) {
1023
1024                 if (exit_early)
1025                     return 0;
1026                 if(d[2]*256+d[3] == ast->prefix)
1027                     ast->prefix_count++;
1028                 else{
1029                     ast->prefix= d[2]*256+d[3];
1030                     ast->prefix_count= 0;
1031                 }
1032
1033                 avi->stream_index= n;
1034                 ast->packet_size= size + 8;
1035                 ast->remaining= size;
1036
1037                 if(size || !ast->sample_size){
1038                     uint64_t pos= avio_tell(pb) - 8;
1039                     if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
1040                         av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
1041                     }
1042                 }
1043                 return 0;
1044             }
1045         }
1046     }
1047
1048     if(pb->error)
1049         return pb->error;
1050     return AVERROR_EOF;
1051 }
1052
1053 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1054 {
1055     AVIContext *avi = s->priv_data;
1056     AVIOContext *pb = s->pb;
1057     int err;
1058     void* dstr;
1059
1060     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1061         int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1062         if (size >= 0)
1063             return size;
1064     }
1065
1066     if(avi->non_interleaved){
1067         int best_stream_index = 0;
1068         AVStream *best_st= NULL;
1069         AVIStream *best_ast;
1070         int64_t best_ts= INT64_MAX;
1071         int i;
1072
1073         for(i=0; i<s->nb_streams; i++){
1074             AVStream *st = s->streams[i];
1075             AVIStream *ast = st->priv_data;
1076             int64_t ts= ast->frame_offset;
1077             int64_t last_ts;
1078
1079             if(!st->nb_index_entries)
1080                 continue;
1081
1082             last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1083             if(!ast->remaining && ts > last_ts)
1084                 continue;
1085
1086             ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
1087
1088             av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
1089                     st->time_base.num, st->time_base.den, ast->frame_offset);
1090             if(ts < best_ts){
1091                 best_ts= ts;
1092                 best_st= st;
1093                 best_stream_index= i;
1094             }
1095         }
1096         if(!best_st)
1097             return AVERROR_EOF;
1098
1099         best_ast = best_st->priv_data;
1100         best_ts = best_ast->frame_offset;
1101         if(best_ast->remaining)
1102             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
1103         else{
1104             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1105             if(i>=0)
1106                 best_ast->frame_offset= best_st->index_entries[i].timestamp;
1107         }
1108
1109         if(i>=0){
1110             int64_t pos= best_st->index_entries[i].pos;
1111             pos += best_ast->packet_size - best_ast->remaining;
1112             if(avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
1113               return AVERROR_EOF;
1114
1115             av_assert0(best_ast->remaining <= best_ast->packet_size);
1116
1117             avi->stream_index= best_stream_index;
1118             if(!best_ast->remaining)
1119                 best_ast->packet_size=
1120                 best_ast->remaining= best_st->index_entries[i].size;
1121         }
1122         else
1123           return AVERROR_EOF;
1124     }
1125
1126 resync:
1127     if(avi->stream_index >= 0){
1128         AVStream *st= s->streams[ avi->stream_index ];
1129         AVIStream *ast= st->priv_data;
1130         int size, err;
1131
1132         if(get_subtitle_pkt(s, st, pkt))
1133             return 0;
1134
1135         if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1136             size= INT_MAX;
1137         else if(ast->sample_size < 32)
1138             // arbitrary multiplier to avoid tiny packets for raw PCM data
1139             size= 1024*ast->sample_size;
1140         else
1141             size= ast->sample_size;
1142
1143         if(size > ast->remaining)
1144             size= ast->remaining;
1145         avi->last_pkt_pos= avio_tell(pb);
1146         err= av_get_packet(pb, pkt, size);
1147         if(err<0)
1148             return err;
1149         size = err;
1150
1151         if(ast->has_pal && pkt->size<(unsigned)INT_MAX/2){
1152             uint8_t *pal;
1153             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
1154             if(!pal){
1155                 av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
1156             }else{
1157                 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1158                 ast->has_pal = 0;
1159             }
1160         }
1161
1162         if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1163             dstr = pkt->destruct;
1164             size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1165                                     pkt->data, pkt->size, pkt->pos);
1166             pkt->destruct = dstr;
1167             pkt->flags |= AV_PKT_FLAG_KEY;
1168             if (size < 0)
1169                 av_free_packet(pkt);
1170         } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
1171                    && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1172             ast->frame_offset++;
1173             avi->stream_index = -1;
1174             ast->remaining = 0;
1175             goto resync;
1176         } else {
1177             /* XXX: How to handle B-frames in AVI? */
1178             pkt->dts = ast->frame_offset;
1179 //                pkt->dts += ast->start;
1180             if(ast->sample_size)
1181                 pkt->dts /= ast->sample_size;
1182             av_dlog(s, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n",
1183                     pkt->dts, ast->frame_offset, ast->scale, ast->rate,
1184                     ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
1185             pkt->stream_index = avi->stream_index;
1186
1187             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1188                 AVIndexEntry *e;
1189                 int index;
1190                 av_assert0(st->index_entries);
1191
1192                 index= av_index_search_timestamp(st, ast->frame_offset, 0);
1193                 e= &st->index_entries[index];
1194
1195                 if(index >= 0 && e->timestamp == ast->frame_offset){
1196                     if (index == st->nb_index_entries-1){
1197                         int key=1;
1198                         int i;
1199                         uint32_t state=-1;
1200                         for(i=0; i<FFMIN(size,256); i++){
1201                             if(st->codec->codec_id == AV_CODEC_ID_MPEG4){
1202                                 if(state == 0x1B6){
1203                                     key= !(pkt->data[i]&0xC0);
1204                                     break;
1205                                 }
1206                             }else
1207                                 break;
1208                             state= (state<<8) + pkt->data[i];
1209                         }
1210                         if(!key)
1211                             e->flags &= ~AVINDEX_KEYFRAME;
1212                     }
1213                     if (e->flags & AVINDEX_KEYFRAME)
1214                         pkt->flags |= AV_PKT_FLAG_KEY;
1215                 }
1216             } else {
1217                 pkt->flags |= AV_PKT_FLAG_KEY;
1218             }
1219             ast->frame_offset += get_duration(ast, pkt->size);
1220         }
1221         ast->remaining -= err;
1222         if(!ast->remaining){
1223             avi->stream_index= -1;
1224             ast->packet_size= 0;
1225         }
1226
1227         if(!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos){
1228             av_free_packet(pkt);
1229             goto resync;
1230         }
1231         ast->seek_pos= 0;
1232
1233         if(!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1){
1234             int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
1235
1236             if(avi->dts_max - dts > 2*AV_TIME_BASE){
1237                 avi->non_interleaved= 1;
1238                 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
1239             }else if(avi->dts_max < dts)
1240                 avi->dts_max = dts;
1241         }
1242
1243         return 0;
1244     }
1245
1246     if ((err = avi_sync(s, 0)) < 0)
1247         return err;
1248     goto resync;
1249 }
1250
1251 /* XXX: We make the implicit supposition that the positions are sorted
1252    for each stream. */
1253 static int avi_read_idx1(AVFormatContext *s, int size)
1254 {
1255     AVIContext *avi = s->priv_data;
1256     AVIOContext *pb = s->pb;
1257     int nb_index_entries, i;
1258     AVStream *st;
1259     AVIStream *ast;
1260     unsigned int index, tag, flags, pos, len, first_packet = 1;
1261     unsigned last_pos= -1;
1262     unsigned last_idx= -1;
1263     int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1264     int anykey = 0;
1265
1266     nb_index_entries = size / 16;
1267     if (nb_index_entries <= 0)
1268         return AVERROR_INVALIDDATA;
1269
1270     idx1_pos = avio_tell(pb);
1271     avio_seek(pb, avi->movi_list+4, SEEK_SET);
1272     if (avi_sync(s, 1) == 0) {
1273         first_packet_pos = avio_tell(pb) - 8;
1274     }
1275     avi->stream_index = -1;
1276     avio_seek(pb, idx1_pos, SEEK_SET);
1277
1278     if (s->nb_streams == 1 && s->streams[0]->codec->codec_tag == AV_RL32("MMES")){
1279         first_packet_pos = 0;
1280         data_offset = avi->movi_list;
1281     }
1282
1283     /* Read the entries and sort them in each stream component. */
1284     for(i = 0; i < nb_index_entries; i++) {
1285         if(url_feof(pb))
1286             return -1;
1287
1288         tag = avio_rl32(pb);
1289         flags = avio_rl32(pb);
1290         pos = avio_rl32(pb);
1291         len = avio_rl32(pb);
1292         av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1293                 i, tag, flags, pos, len);
1294
1295         index = ((tag & 0xff) - '0') * 10;
1296         index += ((tag >> 8) & 0xff) - '0';
1297         if (index >= s->nb_streams)
1298             continue;
1299         st = s->streams[index];
1300         ast = st->priv_data;
1301
1302         if(first_packet && first_packet_pos && len) {
1303             data_offset = first_packet_pos - pos;
1304             first_packet = 0;
1305         }
1306         pos += data_offset;
1307
1308         av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1309
1310         // even if we have only a single stream, we should
1311         // switch to non-interleaved to get correct timestamps
1312         if(last_pos == pos)
1313             avi->non_interleaved= 1;
1314         if(last_idx != pos && len) {
1315             av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1316             last_idx= pos;
1317         }
1318         ast->cum_len += get_duration(ast, len);
1319         last_pos= pos;
1320         anykey |= flags&AVIIF_INDEX;
1321     }
1322     if (!anykey) {
1323         for (index = 0; index < s->nb_streams; index++) {
1324             st = s->streams[index];
1325             if (st->nb_index_entries)
1326                 st->index_entries[0].flags |= AVINDEX_KEYFRAME;
1327         }
1328     }
1329     return 0;
1330 }
1331
1332 static int guess_ni_flag(AVFormatContext *s){
1333     int i;
1334     int64_t last_start=0;
1335     int64_t first_end= INT64_MAX;
1336     int64_t oldpos= avio_tell(s->pb);
1337     int *idx;
1338     int64_t min_pos, pos;
1339
1340     for(i=0; i<s->nb_streams; i++){
1341         AVStream *st = s->streams[i];
1342         int n= st->nb_index_entries;
1343         unsigned int size;
1344
1345         if(n <= 0)
1346             continue;
1347
1348         if(n >= 2){
1349             int64_t pos= st->index_entries[0].pos;
1350             avio_seek(s->pb, pos + 4, SEEK_SET);
1351             size= avio_rl32(s->pb);
1352             if(pos + size > st->index_entries[1].pos)
1353                 last_start= INT64_MAX;
1354         }
1355
1356         if(st->index_entries[0].pos > last_start)
1357             last_start= st->index_entries[0].pos;
1358         if(st->index_entries[n-1].pos < first_end)
1359             first_end= st->index_entries[n-1].pos;
1360     }
1361     avio_seek(s->pb, oldpos, SEEK_SET);
1362     if (last_start > first_end)
1363         return 1;
1364     idx= av_mallocz(sizeof(*idx) * s->nb_streams);
1365     for (min_pos=pos=0; min_pos!=INT64_MAX; pos= min_pos+1LU) {
1366         int64_t max_dts = INT64_MIN/2, min_dts= INT64_MAX/2;
1367         min_pos = INT64_MAX;
1368
1369         for (i=0; i<s->nb_streams; i++) {
1370             AVStream *st = s->streams[i];
1371             int n= st->nb_index_entries;
1372             while (idx[i]<n && st->index_entries[idx[i]].pos < pos)
1373                 idx[i]++;
1374             if (idx[i] < n) {
1375                 min_dts = FFMIN(min_dts, av_rescale_q(st->index_entries[idx[i]].timestamp, st->time_base, AV_TIME_BASE_Q));
1376                 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
1377             }
1378             if (idx[i])
1379                 max_dts = FFMAX(max_dts, av_rescale_q(st->index_entries[idx[i]-1].timestamp, st->time_base, AV_TIME_BASE_Q));
1380         }
1381         if(max_dts - min_dts > 2*AV_TIME_BASE) {
1382             av_free(idx);
1383             return 1;
1384         }
1385     }
1386     av_free(idx);
1387     return 0;
1388 }
1389
1390 static int avi_load_index(AVFormatContext *s)
1391 {
1392     AVIContext *avi = s->priv_data;
1393     AVIOContext *pb = s->pb;
1394     uint32_t tag, size;
1395     int64_t pos= avio_tell(pb);
1396     int64_t next;
1397     int ret = -1;
1398
1399     if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1400         goto the_end; // maybe truncated file
1401     av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1402     for(;;) {
1403         tag = avio_rl32(pb);
1404         size = avio_rl32(pb);
1405         if (url_feof(pb))
1406             break;
1407         next = avio_tell(pb) + size + (size & 1);
1408
1409         av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1410                  tag        & 0xff,
1411                 (tag >>  8) & 0xff,
1412                 (tag >> 16) & 0xff,
1413                 (tag >> 24) & 0xff,
1414                 size);
1415
1416         if (tag == MKTAG('i', 'd', 'x', '1') &&
1417             avi_read_idx1(s, size) >= 0) {
1418             avi->index_loaded=2;
1419             ret = 0;
1420         }else if(tag == MKTAG('L', 'I', 'S', 'T')) {
1421             uint32_t tag1 = avio_rl32(pb);
1422
1423             if (tag1 == MKTAG('I', 'N', 'F', 'O'))
1424                 ff_read_riff_info(s, size - 4);
1425         }else if(!ret)
1426             break;
1427
1428         if (avio_seek(pb, next, SEEK_SET) < 0)
1429             break; // something is wrong here
1430     }
1431  the_end:
1432     avio_seek(pb, pos, SEEK_SET);
1433     return ret;
1434 }
1435
1436 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1437 {
1438     AVIStream *ast2 = st2->priv_data;
1439     int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1440     av_free_packet(&ast2->sub_pkt);
1441     if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1442         avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1443         ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1444 }
1445
1446 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1447 {
1448     AVIContext *avi = s->priv_data;
1449     AVStream *st;
1450     int i, index;
1451     int64_t pos, pos_min;
1452     AVIStream *ast;
1453
1454     if (!avi->index_loaded) {
1455         /* we only load the index on demand */
1456         avi_load_index(s);
1457         avi->index_loaded |= 1;
1458     }
1459     av_assert0(stream_index>= 0);
1460
1461     st = s->streams[stream_index];
1462     ast= st->priv_data;
1463     index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
1464     if (index<0) {
1465         if (st->nb_index_entries > 0)
1466             av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
1467                    timestamp * FFMAX(ast->sample_size, 1),
1468                    st->index_entries[0].timestamp,
1469                    st->index_entries[st->nb_index_entries - 1].timestamp);
1470         return AVERROR_INVALIDDATA;
1471     }
1472
1473     /* find the position */
1474     pos = st->index_entries[index].pos;
1475     timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1476
1477     av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
1478             timestamp, index, st->index_entries[index].timestamp);
1479
1480     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1481         /* One and only one real stream for DV in AVI, and it has video  */
1482         /* offsets. Calling with other stream indexes should have failed */
1483         /* the av_index_search_timestamp call above.                     */
1484         av_assert0(stream_index == 0);
1485
1486         if(avio_seek(s->pb, pos, SEEK_SET) < 0)
1487             return -1;
1488
1489         /* Feed the DV video stream version of the timestamp to the */
1490         /* DV demux so it can synthesize correct timestamps.        */
1491         ff_dv_offset_reset(avi->dv_demux, timestamp);
1492
1493         avi->stream_index= -1;
1494         return 0;
1495     }
1496
1497     pos_min= pos;
1498     for(i = 0; i < s->nb_streams; i++) {
1499         AVStream *st2 = s->streams[i];
1500         AVIStream *ast2 = st2->priv_data;
1501
1502         ast2->packet_size=
1503         ast2->remaining= 0;
1504
1505         if (ast2->sub_ctx) {
1506             seek_subtitle(st, st2, timestamp);
1507             continue;
1508         }
1509
1510         if (st2->nb_index_entries <= 0)
1511             continue;
1512
1513 //        av_assert1(st2->codec->block_align);
1514         av_assert0((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1515         index = av_index_search_timestamp(
1516                 st2,
1517                 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1518                 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1519         if(index<0)
1520             index=0;
1521         ast2->seek_pos= st2->index_entries[index].pos;
1522         pos_min= FFMIN(pos_min,ast2->seek_pos);
1523     }
1524     for(i = 0; i < s->nb_streams; i++) {
1525         AVStream *st2 = s->streams[i];
1526         AVIStream *ast2 = st2->priv_data;
1527
1528         if (ast2->sub_ctx || st2->nb_index_entries <= 0)
1529             continue;
1530
1531         index = av_index_search_timestamp(
1532                 st2,
1533                 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1534                 flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1535         if(index<0)
1536             index=0;
1537         while(!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
1538             index--;
1539         ast2->frame_offset = st2->index_entries[index].timestamp;
1540     }
1541
1542     /* do the seek */
1543     if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
1544         av_log(s, AV_LOG_ERROR, "Seek failed\n");
1545         return -1;
1546     }
1547     avi->stream_index= -1;
1548     avi->dts_max= INT_MIN;
1549     return 0;
1550 }
1551
1552 static int avi_read_close(AVFormatContext *s)
1553 {
1554     int i;
1555     AVIContext *avi = s->priv_data;
1556
1557     for(i=0;i<s->nb_streams;i++) {
1558         AVStream *st = s->streams[i];
1559         AVIStream *ast = st->priv_data;
1560         if (ast) {
1561             if (ast->sub_ctx) {
1562                 av_freep(&ast->sub_ctx->pb);
1563                 avformat_close_input(&ast->sub_ctx);
1564             }
1565             av_free(ast->sub_buffer);
1566             av_free_packet(&ast->sub_pkt);
1567         }
1568     }
1569
1570     av_free(avi->dv_demux);
1571
1572     return 0;
1573 }
1574
1575 static int avi_probe(AVProbeData *p)
1576 {
1577     int i;
1578
1579     /* check file header */
1580     for(i=0; avi_headers[i][0]; i++)
1581         if(!memcmp(p->buf  , avi_headers[i]  , 4) &&
1582            !memcmp(p->buf+8, avi_headers[i]+4, 4))
1583             return AVPROBE_SCORE_MAX;
1584
1585     return 0;
1586 }
1587
1588 AVInputFormat ff_avi_demuxer = {
1589     .name           = "avi",
1590     .long_name      = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1591     .priv_data_size = sizeof(AVIContext),
1592     .read_probe     = avi_probe,
1593     .read_header    = avi_read_header,
1594     .read_packet    = avi_read_packet,
1595     .read_close     = avi_read_close,
1596     .read_seek      = avi_read_seek,
1597     .priv_class = &demuxer_class,
1598 };