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