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