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