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