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