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