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