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