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