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