]> git.sesse.net Git - ffmpeg/blob - libavformat/avidec.c
crypto: consistently use size_t as type for length parameters
[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     int64_t pos;
371     int ret;
372
373     avi->stream_index = -1;
374
375     ret = get_riff(s, pb);
376     if (ret < 0)
377         return ret;
378
379     avi->fsize = avio_size(pb);
380     if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
381         avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
382
383     /* first list tag */
384     stream_index = -1;
385     codec_type   = -1;
386     frame_period = 0;
387     for (;;) {
388         if (pb->eof_reached)
389             goto fail;
390         tag  = avio_rl32(pb);
391         size = avio_rl32(pb);
392
393         print_tag("tag", tag, size);
394
395         switch (tag) {
396         case MKTAG('L', 'I', 'S', 'T'):
397             list_end = avio_tell(pb) + size;
398             /* Ignored, except at start of video packets. */
399             tag1 = avio_rl32(pb);
400
401             print_tag("list", tag1, 0);
402
403             if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
404                 avi->movi_list = avio_tell(pb) - 4;
405                 if (size)
406                     avi->movi_end = avi->movi_list + size + (size & 1);
407                 else
408                     avi->movi_end = avi->fsize;
409                 av_log(NULL, AV_LOG_TRACE, "movi end=%"PRIx64"\n", avi->movi_end);
410                 goto end_of_header;
411             } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
412                 ff_read_riff_info(s, size - 4);
413             else if (tag1 == MKTAG('n', 'c', 'd', 't'))
414                 avi_read_nikon(s, list_end);
415
416             break;
417         case MKTAG('I', 'D', 'I', 'T'):
418         {
419             unsigned char date[64] = { 0 };
420             size += (size & 1);
421             size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
422             avio_skip(pb, size);
423             avi_metadata_creation_time(&s->metadata, date);
424             break;
425         }
426         case MKTAG('d', 'm', 'l', 'h'):
427             avi->is_odml = 1;
428             avio_skip(pb, size + (size & 1));
429             break;
430         case MKTAG('a', 'm', 'v', 'h'):
431             amv_file_format = 1;
432         case MKTAG('a', 'v', 'i', 'h'):
433             /* AVI header */
434             /* using frame_period is bad idea */
435             frame_period = avio_rl32(pb);
436             avio_skip(pb, 4);
437             avio_rl32(pb);
438             avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
439
440             avio_skip(pb, 2 * 4);
441             avio_rl32(pb);
442             avio_rl32(pb);
443             avih_width  = avio_rl32(pb);
444             avih_height = avio_rl32(pb);
445
446             avio_skip(pb, size - 10 * 4);
447             break;
448         case MKTAG('s', 't', 'r', 'h'):
449             /* stream header */
450
451             tag1    = avio_rl32(pb);
452             handler = avio_rl32(pb); /* codec tag */
453
454             if (tag1 == MKTAG('p', 'a', 'd', 's')) {
455                 avio_skip(pb, size - 8);
456                 break;
457             } else {
458                 stream_index++;
459                 st = avformat_new_stream(s, NULL);
460                 if (!st)
461                     goto fail;
462
463                 st->id = stream_index;
464                 ast    = av_mallocz(sizeof(AVIStream));
465                 if (!ast)
466                     goto fail;
467                 st->priv_data = ast;
468             }
469             if (amv_file_format)
470                 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
471                                     : MKTAG('v', 'i', 'd', 's');
472
473             print_tag("strh", tag1, -1);
474
475             if (tag1 == MKTAG('i', 'a', 'v', 's') ||
476                 tag1 == MKTAG('i', 'v', 'a', 's')) {
477                 int64_t dv_dur;
478
479                 /* After some consideration -- I don't think we
480                  * have to support anything but DV in type1 AVIs. */
481                 if (s->nb_streams != 1)
482                     goto fail;
483
484                 if (handler != MKTAG('d', 'v', 's', 'd') &&
485                     handler != MKTAG('d', 'v', 'h', 'd') &&
486                     handler != MKTAG('d', 'v', 's', 'l'))
487                     goto fail;
488
489                 ast = s->streams[0]->priv_data;
490                 av_freep(&s->streams[0]->codecpar->extradata);
491                 av_freep(&s->streams[0]->codecpar);
492                 av_freep(&s->streams[0]->info);
493                 av_freep(&s->streams[0]);
494                 s->nb_streams = 0;
495                 if (CONFIG_DV_DEMUXER) {
496                     avi->dv_demux = avpriv_dv_init_demux(s);
497                     if (!avi->dv_demux)
498                         goto fail;
499                 } else
500                     goto fail;
501                 s->streams[0]->priv_data = ast;
502                 avio_skip(pb, 3 * 4);
503                 ast->scale = avio_rl32(pb);
504                 ast->rate  = avio_rl32(pb);
505                 avio_skip(pb, 4);  /* start time */
506
507                 dv_dur = avio_rl32(pb);
508                 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
509                     dv_dur     *= AV_TIME_BASE;
510                     s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
511                 }
512                 /* else, leave duration alone; timing estimation in utils.c
513                  * will make a guess based on bitrate. */
514
515                 stream_index = s->nb_streams - 1;
516                 avio_skip(pb, size - 9 * 4);
517                 break;
518             }
519
520             assert(stream_index < s->nb_streams);
521             ast->handler = handler;
522
523             avio_rl32(pb); /* flags */
524             avio_rl16(pb); /* priority */
525             avio_rl16(pb); /* language */
526             avio_rl32(pb); /* initial frame */
527             ast->scale = avio_rl32(pb);
528             ast->rate  = avio_rl32(pb);
529             if (!(ast->scale && ast->rate)) {
530                 av_log(s, AV_LOG_WARNING,
531                        "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
532                        "(This file has been generated by broken software.)\n",
533                        ast->scale,
534                        ast->rate);
535                 if (frame_period) {
536                     ast->rate  = 1000000;
537                     ast->scale = frame_period;
538                 } else {
539                     ast->rate  = 25;
540                     ast->scale = 1;
541                 }
542             }
543             avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
544
545             ast->cum_len  = avio_rl32(pb); /* start */
546             st->nb_frames = avio_rl32(pb);
547
548             st->start_time = 0;
549             avio_rl32(pb); /* buffer size */
550             avio_rl32(pb); /* quality */
551             ast->sample_size = avio_rl32(pb); /* sample size */
552             ast->cum_len    *= FFMAX(1, ast->sample_size);
553             av_log(s, AV_LOG_TRACE, "%"PRIu32" %"PRIu32" %d\n",
554                     ast->rate, ast->scale, ast->sample_size);
555
556             switch (tag1) {
557             case MKTAG('v', 'i', 'd', 's'):
558                 codec_type = AVMEDIA_TYPE_VIDEO;
559
560                 ast->sample_size = 0;
561                 break;
562             case MKTAG('a', 'u', 'd', 's'):
563                 codec_type = AVMEDIA_TYPE_AUDIO;
564                 break;
565             case MKTAG('t', 'x', 't', 's'):
566                 codec_type = AVMEDIA_TYPE_SUBTITLE;
567                 break;
568             case MKTAG('d', 'a', 't', 's'):
569                 codec_type = AVMEDIA_TYPE_DATA;
570                 break;
571             default:
572                 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
573                 goto fail;
574             }
575
576             if (ast->sample_size < 0) {
577                 if (s->error_recognition & AV_EF_EXPLODE) {
578                     av_log(s, AV_LOG_ERROR,
579                            "Invalid sample_size %d at stream %d\n",
580                            ast->sample_size,
581                            stream_index);
582                     goto fail;
583                 }
584                 av_log(s, AV_LOG_WARNING,
585                        "Invalid sample_size %d at stream %d "
586                        "setting it to 0\n",
587                        ast->sample_size,
588                        stream_index);
589                 ast->sample_size = 0;
590             }
591
592             if (ast->sample_size == 0)
593                 st->duration = st->nb_frames;
594             ast->frame_offset = ast->cum_len;
595             avio_skip(pb, size - 12 * 4);
596             break;
597         case MKTAG('s', 't', 'r', 'f'):
598             /* stream header */
599             if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
600                 avio_skip(pb, size);
601             } else {
602                 uint64_t cur_pos = avio_tell(pb);
603                 if (cur_pos < list_end)
604                     size = FFMIN(size, list_end - cur_pos);
605                 st = s->streams[stream_index];
606                 switch (codec_type) {
607                 case AVMEDIA_TYPE_VIDEO:
608                     if (amv_file_format) {
609                         st->codecpar->width      = avih_width;
610                         st->codecpar->height     = avih_height;
611                         st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
612                         st->codecpar->codec_id   = AV_CODEC_ID_AMV;
613                         avio_skip(pb, size);
614                         break;
615                     }
616                     tag1 = ff_get_bmp_header(pb, st);
617
618                     if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
619                         tag1 == MKTAG('D', 'X', 'S', 'A')) {
620                         st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
621                         st->codecpar->codec_tag  = tag1;
622                         st->codecpar->codec_id   = AV_CODEC_ID_XSUB;
623                         break;
624                     }
625
626                     if (size > 10 * 4 && size < (1 << 30)) {
627                         st->codecpar->extradata_size = size - 10 * 4;
628                         st->codecpar->extradata      = av_malloc(st->codecpar->extradata_size +
629                                                                  AV_INPUT_BUFFER_PADDING_SIZE);
630                         if (!st->codecpar->extradata) {
631                             st->codecpar->extradata_size = 0;
632                             return AVERROR(ENOMEM);
633                         }
634                         avio_read(pb,
635                                   st->codecpar->extradata,
636                                   st->codecpar->extradata_size);
637                     }
638
639                     // FIXME: check if the encoder really did this correctly
640                     if (st->codecpar->extradata_size & 1)
641                         avio_r8(pb);
642
643                     /* Extract palette from extradata if bpp <= 8.
644                      * This code assumes that extradata contains only palette.
645                      * This is true for all paletted codecs implemented in
646                      * Libav. */
647                     if (st->codecpar->extradata_size &&
648                         (st->codecpar->bits_per_coded_sample <= 8)) {
649                         int pal_size = (1 << st->codecpar->bits_per_coded_sample) << 2;
650                         const uint8_t *pal_src;
651
652                         pal_size = FFMIN(pal_size, st->codecpar->extradata_size);
653                         pal_src  = st->codecpar->extradata +
654                                    st->codecpar->extradata_size - pal_size;
655                         for (i = 0; i < pal_size / 4; i++)
656                             ast->pal[i] = (0xFFu << 24) | AV_RL32(pal_src + 4 * i);
657                         ast->has_pal = 1;
658                     }
659
660                     print_tag("video", tag1, 0);
661
662                     st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
663                     st->codecpar->codec_tag  = tag1;
664                     st->codecpar->codec_id   = ff_codec_get_id(ff_codec_bmp_tags,
665                                                             tag1);
666                     /* If codec is not found yet, try with the mov tags. */
667                     if (!st->codecpar->codec_id) {
668                         char tag_buf[32];
669                         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag1);
670                         st->codecpar->codec_id =
671                             ff_codec_get_id(ff_codec_movvideo_tags, tag1);
672                         if (st->codecpar->codec_id)
673                            av_log(s, AV_LOG_WARNING,
674                                   "mov tag found in avi (fourcc %s)\n",
675                                   tag_buf);
676                     }
677                     /* This is needed to get the pict type which is necessary
678                      * for generating correct pts. */
679                     st->need_parsing = AVSTREAM_PARSE_HEADERS;
680
681                     if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4 &&
682                         ast->handler == MKTAG('X', 'V', 'I', 'D'))
683                         st->codecpar->codec_tag = MKTAG('X', 'V', 'I', 'D');
684
685                     // Support "Resolution 1:1" for Avid AVI Codec
686                     if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
687                         st->codecpar->extradata_size >= 31   &&
688                         !memcmp(&st->codecpar->extradata[28], "1:1", 3))
689                         st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
690
691                     if (st->codecpar->codec_tag == 0 && st->codecpar->height > 0 &&
692                         st->codecpar->extradata_size < 1U << 30) {
693                         st->codecpar->extradata_size += 9;
694                         if ((ret = av_reallocp(&st->codecpar->extradata,
695                                                st->codecpar->extradata_size +
696                                                AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {
697                             st->codecpar->extradata_size = 0;
698                             return ret;
699                         } else
700                             memcpy(st->codecpar->extradata + st->codecpar->extradata_size - 9,
701                                    "BottomUp", 9);
702                     }
703                     st->codecpar->height = FFABS(st->codecpar->height);
704
705 //                    avio_skip(pb, size - 5 * 4);
706                     break;
707                 case AVMEDIA_TYPE_AUDIO:
708                     ret = ff_get_wav_header(s, pb, st->codecpar, size);
709                     if (ret < 0)
710                         return ret;
711                     ast->dshow_block_align = st->codecpar->block_align;
712                     if (ast->sample_size && st->codecpar->block_align &&
713                         ast->sample_size != st->codecpar->block_align) {
714                         av_log(s,
715                                AV_LOG_WARNING,
716                                "sample size (%d) != block align (%d)\n",
717                                ast->sample_size,
718                                st->codecpar->block_align);
719                         ast->sample_size = st->codecpar->block_align;
720                     }
721                     /* 2-aligned
722                      * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
723                     if (size & 1)
724                         avio_skip(pb, 1);
725                     /* Force parsing as several audio frames can be in
726                      * one packet and timestamps refer to packet start. */
727                     st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
728                     /* ADTS header is in extradata, AAC without header must be
729                      * stored as exact frames. Parser not needed and it will
730                      * fail. */
731                     if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
732                         st->codecpar->extradata_size)
733                         st->need_parsing = AVSTREAM_PARSE_NONE;
734                     /* AVI files with Xan DPCM audio (wrongly) declare PCM
735                      * audio in the header but have Axan as stream_code_tag. */
736                     if (ast->handler == AV_RL32("Axan")) {
737                         st->codecpar->codec_id  = AV_CODEC_ID_XAN_DPCM;
738                         st->codecpar->codec_tag = 0;
739                     }
740                     if (amv_file_format) {
741                         st->codecpar->codec_id    = AV_CODEC_ID_ADPCM_IMA_AMV;
742                         ast->dshow_block_align = 0;
743                     }
744                     break;
745                 case AVMEDIA_TYPE_SUBTITLE:
746                     st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
747                     st->codecpar->codec_id   = AV_CODEC_ID_PROBE;
748                     break;
749                 default:
750                     st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
751                     st->codecpar->codec_id   = AV_CODEC_ID_NONE;
752                     st->codecpar->codec_tag  = 0;
753                     avio_skip(pb, size);
754                     break;
755                 }
756             }
757             break;
758         case MKTAG('i', 'n', 'd', 'x'):
759             pos = avio_tell(pb);
760             if ((pb->seekable & AVIO_SEEKABLE_NORMAL) &&
761                 !(s->flags & AVFMT_FLAG_IGNIDX) &&
762                 read_braindead_odml_indx(s, 0) < 0 &&
763                 (s->error_recognition & AV_EF_EXPLODE))
764                 goto fail;
765             avio_seek(pb, pos + size, SEEK_SET);
766             break;
767         case MKTAG('v', 'p', 'r', 'p'):
768             if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
769                 AVRational active, active_aspect;
770
771                 st = s->streams[stream_index];
772                 avio_rl32(pb);
773                 avio_rl32(pb);
774                 avio_rl32(pb);
775                 avio_rl32(pb);
776                 avio_rl32(pb);
777
778                 active_aspect.den = avio_rl16(pb);
779                 active_aspect.num = avio_rl16(pb);
780                 active.num        = avio_rl32(pb);
781                 active.den        = avio_rl32(pb);
782                 avio_rl32(pb); // nbFieldsPerFrame
783
784                 if (active_aspect.num && active_aspect.den &&
785                     active.num && active.den) {
786                     st->sample_aspect_ratio = av_div_q(active_aspect, active);
787                     av_log(s, AV_LOG_TRACE, "vprp %d/%d %d/%d\n",
788                             active_aspect.num, active_aspect.den,
789                             active.num, active.den);
790                 }
791                 size -= 9 * 4;
792             }
793             avio_skip(pb, size);
794             break;
795         case MKTAG('s', 't', 'r', 'n'):
796             if (s->nb_streams) {
797                 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
798                 if (ret < 0)
799                     return ret;
800                 break;
801             }
802         default:
803             if (size > 1000000) {
804                 av_log(s, AV_LOG_ERROR,
805                        "Something went wrong during header parsing, "
806                        "I will ignore it and try to continue anyway.\n");
807                 if (s->error_recognition & AV_EF_EXPLODE)
808                     goto fail;
809                 avi->movi_list = avio_tell(pb) - 4;
810                 avi->movi_end  = avi->fsize;
811                 goto end_of_header;
812             }
813             /* skip tag */
814             size += (size & 1);
815             avio_skip(pb, size);
816             break;
817         }
818     }
819
820 end_of_header:
821     /* check stream number */
822     if (stream_index != s->nb_streams - 1) {
823
824 fail:
825         return AVERROR_INVALIDDATA;
826     }
827
828     if (!avi->index_loaded && (pb->seekable & AVIO_SEEKABLE_NORMAL))
829         avi_load_index(s);
830     avi->index_loaded     = 1;
831
832     if ((ret = guess_ni_flag(s)) < 0)
833         return ret;
834
835     avi->non_interleaved |= ret;
836     for (i = 0; i < s->nb_streams; i++) {
837         AVStream *st = s->streams[i];
838         if (st->nb_index_entries)
839             break;
840     }
841     if (i == s->nb_streams && avi->non_interleaved) {
842         av_log(s, AV_LOG_WARNING,
843                "Non-interleaved AVI without index, switching to interleaved\n");
844         avi->non_interleaved = 0;
845     }
846
847     if (avi->non_interleaved) {
848         av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
849         clean_index(s);
850     }
851
852     ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
853     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
854
855     return 0;
856 }
857
858 static int read_gab2_sub(AVStream *st, AVPacket *pkt)
859 {
860     if (pkt->size >= 7 &&
861         !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
862         uint8_t desc[256];
863         int score      = AVPROBE_SCORE_EXTENSION, ret;
864         AVIStream *ast = st->priv_data;
865         AVInputFormat *sub_demuxer;
866         AVRational time_base;
867         AVIOContext *pb = avio_alloc_context(pkt->data + 7,
868                                              pkt->size - 7,
869                                              0, NULL, NULL, NULL, NULL);
870         AVProbeData pd;
871         unsigned int desc_len = avio_rl32(pb);
872
873         if (desc_len > pb->buf_end - pb->buf_ptr)
874             goto error;
875
876         ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
877         avio_skip(pb, desc_len - ret);
878         if (*desc)
879             av_dict_set(&st->metadata, "title", desc, 0);
880
881         avio_rl16(pb);   /* flags? */
882         avio_rl32(pb);   /* data size */
883
884         pd = (AVProbeData) { .buf      = pb->buf_ptr,
885                              .buf_size = pb->buf_end - pb->buf_ptr };
886         if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
887             goto error;
888
889         if (!(ast->sub_ctx = avformat_alloc_context()))
890             goto error;
891
892         ast->sub_ctx->pb = pb;
893         if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
894             ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
895             avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
896             time_base = ast->sub_ctx->streams[0]->time_base;
897             avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
898         }
899         ast->sub_buffer = pkt->data;
900         memset(pkt, 0, sizeof(*pkt));
901         return 1;
902
903 error:
904         av_freep(&pb);
905     }
906     return 0;
907 }
908
909 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
910                                   AVPacket *pkt)
911 {
912     AVIStream *ast, *next_ast = next_st->priv_data;
913     int64_t ts, next_ts, ts_min = INT64_MAX;
914     AVStream *st, *sub_st = NULL;
915     int i;
916
917     next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
918                            AV_TIME_BASE_Q);
919
920     for (i = 0; i < s->nb_streams; i++) {
921         st  = s->streams[i];
922         ast = st->priv_data;
923         if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
924             ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
925             if (ts <= next_ts && ts < ts_min) {
926                 ts_min = ts;
927                 sub_st = st;
928             }
929         }
930     }
931
932     if (sub_st) {
933         ast               = sub_st->priv_data;
934         *pkt              = ast->sub_pkt;
935         pkt->stream_index = sub_st->index;
936
937         if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
938             ast->sub_pkt.data = NULL;
939     }
940     return sub_st;
941 }
942
943 static int get_stream_idx(int *d)
944 {
945     if (d[0] >= '0' && d[0] <= '9' &&
946         d[1] >= '0' && d[1] <= '9') {
947         return (d[0] - '0') * 10 + (d[1] - '0');
948     } else {
949         return 100; // invalid stream ID
950     }
951 }
952
953 static int avi_sync(AVFormatContext *s, int exit_early)
954 {
955     AVIContext *avi = s->priv_data;
956     AVIOContext *pb = s->pb;
957     int n;
958     unsigned int d[8];
959     unsigned int size;
960     int64_t i, sync;
961
962 start_sync:
963     memset(d, -1, sizeof(d));
964     for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
965         int j;
966
967         for (j = 0; j < 7; j++)
968             d[j] = d[j + 1];
969         d[7] = avio_r8(pb);
970
971         size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
972
973         n = get_stream_idx(d + 2);
974         av_log(s, AV_LOG_TRACE, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
975                 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
976         if (i + (uint64_t)size > avi->fsize || d[0] > 127)
977             continue;
978
979         // parse ix##
980         if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
981             // parse JUNK
982             (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
983             (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
984             avio_skip(pb, size);
985             goto start_sync;
986         }
987
988         // parse stray LIST
989         if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
990             avio_skip(pb, 4);
991             goto start_sync;
992         }
993
994         n = get_stream_idx(d);
995
996         if (!((i - avi->last_pkt_pos) & 1) &&
997             get_stream_idx(d + 1) < s->nb_streams)
998             continue;
999
1000         // detect ##ix chunk and skip
1001         if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
1002             avio_skip(pb, size);
1003             goto start_sync;
1004         }
1005
1006         if (avi->dv_demux && n != 0)
1007             continue;
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->codecpar->codec_type  == AVMEDIA_TYPE_VIDEO &&
1022                     st1->codecpar->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 ni_prepare_read(AVFormatContext *s)
1094 {
1095     AVIContext *avi = s->priv_data;
1096     int best_stream_index = 0;
1097     AVStream *best_st     = NULL;
1098     AVIStream *best_ast;
1099     int64_t best_ts = INT64_MAX;
1100     int i;
1101
1102     for (i = 0; i < s->nb_streams; i++) {
1103         AVStream *st   = s->streams[i];
1104         AVIStream *ast = st->priv_data;
1105         int64_t ts     = ast->frame_offset;
1106         int64_t last_ts;
1107
1108         if (!st->nb_index_entries)
1109             continue;
1110
1111         last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1112         if (!ast->remaining && ts > last_ts)
1113             continue;
1114
1115         ts = av_rescale_q(ts, st->time_base,
1116                           (AVRational) { FFMAX(1, ast->sample_size),
1117                                          AV_TIME_BASE });
1118
1119         av_log(s, AV_LOG_TRACE, "%"PRId64" %d/%d %"PRId64"\n", ts,
1120                 st->time_base.num, st->time_base.den, ast->frame_offset);
1121         if (ts < best_ts) {
1122             best_ts           = ts;
1123             best_st           = st;
1124             best_stream_index = i;
1125         }
1126     }
1127     if (!best_st)
1128         return AVERROR_EOF;
1129
1130     best_ast = best_st->priv_data;
1131     best_ts  = av_rescale_q(best_ts,
1132                             (AVRational) { FFMAX(1, best_ast->sample_size),
1133                                            AV_TIME_BASE },
1134                             best_st->time_base);
1135     if (best_ast->remaining) {
1136         i = av_index_search_timestamp(best_st,
1137                                       best_ts,
1138                                       AVSEEK_FLAG_ANY |
1139                                       AVSEEK_FLAG_BACKWARD);
1140     } else {
1141         i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1142         if (i >= 0)
1143             best_ast->frame_offset = best_st->index_entries[i].timestamp;
1144     }
1145
1146     if (i >= 0) {
1147         int64_t pos = best_st->index_entries[i].pos;
1148         pos += best_ast->packet_size - best_ast->remaining;
1149         avio_seek(s->pb, pos + 8, SEEK_SET);
1150
1151         assert(best_ast->remaining <= best_ast->packet_size);
1152
1153         avi->stream_index = best_stream_index;
1154         if (!best_ast->remaining)
1155             best_ast->packet_size =
1156             best_ast->remaining   = best_st->index_entries[i].size;
1157     }
1158
1159     return 0;
1160 }
1161
1162 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1163 {
1164     AVIContext *avi = s->priv_data;
1165     AVIOContext *pb = s->pb;
1166     int err;
1167
1168     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1169         int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1170         if (size >= 0)
1171             return size;
1172         else
1173             goto resync;
1174     }
1175
1176     if (avi->non_interleaved) {
1177         err = ni_prepare_read(s);
1178         if (err < 0)
1179             return err;
1180     }
1181
1182 resync:
1183     if (avi->stream_index >= 0) {
1184         AVStream *st   = s->streams[avi->stream_index];
1185         AVIStream *ast = st->priv_data;
1186         int size, err;
1187
1188         if (get_subtitle_pkt(s, st, pkt))
1189             return 0;
1190
1191         // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1192         if (ast->sample_size <= 1)
1193             size = INT_MAX;
1194         else if (ast->sample_size < 32)
1195             // arbitrary multiplier to avoid tiny packets for raw PCM data
1196             size = 1024 * ast->sample_size;
1197         else
1198             size = ast->sample_size;
1199
1200         if (size > ast->remaining)
1201             size = ast->remaining;
1202         avi->last_pkt_pos = avio_tell(pb);
1203         err               = av_get_packet(pb, pkt, size);
1204         if (err < 0)
1205             return err;
1206
1207         if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
1208             uint8_t *pal;
1209             pal = av_packet_new_side_data(pkt,
1210                                           AV_PKT_DATA_PALETTE,
1211                                           AVPALETTE_SIZE);
1212             if (!pal) {
1213                 av_log(s, AV_LOG_ERROR,
1214                        "Failed to allocate data for palette\n");
1215             } else {
1216                 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1217                 ast->has_pal = 0;
1218             }
1219         }
1220
1221         if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1222             AVBufferRef *avbuf = pkt->buf;
1223             size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1224                                             pkt->data, pkt->size);
1225             pkt->buf    = avbuf;
1226             pkt->flags |= AV_PKT_FLAG_KEY;
1227             if (size < 0)
1228                 av_packet_unref(pkt);
1229         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1230                    !st->codecpar->codec_tag && read_gab2_sub(st, pkt)) {
1231             ast->frame_offset++;
1232             avi->stream_index = -1;
1233             ast->remaining    = 0;
1234             goto resync;
1235         } else {
1236             /* XXX: How to handle B-frames in AVI? */
1237             pkt->dts = ast->frame_offset;
1238 //                pkt->dts += ast->start;
1239             if (ast->sample_size)
1240                 pkt->dts /= ast->sample_size;
1241             pkt->stream_index = avi->stream_index;
1242
1243             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1244                 AVIndexEntry *e;
1245                 int index;
1246                 assert(st->index_entries);
1247
1248                 index = av_index_search_timestamp(st, ast->frame_offset, 0);
1249                 e     = &st->index_entries[index];
1250
1251                 if (index >= 0 && e->timestamp == ast->frame_offset)
1252                     if (e->flags & AVINDEX_KEYFRAME)
1253                         pkt->flags |= AV_PKT_FLAG_KEY;
1254             } else {
1255                 pkt->flags |= AV_PKT_FLAG_KEY;
1256             }
1257             ast->frame_offset += get_duration(ast, pkt->size);
1258         }
1259         ast->remaining -= err;
1260         if (!ast->remaining) {
1261             avi->stream_index = -1;
1262             ast->packet_size  = 0;
1263         }
1264
1265         return 0;
1266     }
1267
1268     if ((err = avi_sync(s, 0)) < 0)
1269         return err;
1270     goto resync;
1271 }
1272
1273 /* XXX: We make the implicit supposition that the positions are sorted
1274  * for each stream. */
1275 static int avi_read_idx1(AVFormatContext *s, int size)
1276 {
1277     AVIContext *avi = s->priv_data;
1278     AVIOContext *pb = s->pb;
1279     int nb_index_entries, i;
1280     AVStream *st;
1281     AVIStream *ast;
1282     unsigned int index, tag, flags, pos, len, first_packet = 1;
1283     unsigned last_pos = -1;
1284     int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1285
1286     nb_index_entries = size / 16;
1287     if (nb_index_entries <= 0)
1288         return AVERROR_INVALIDDATA;
1289
1290     idx1_pos = avio_tell(pb);
1291     avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1292     if (avi_sync(s, 1) == 0)
1293         first_packet_pos = avio_tell(pb) - 8;
1294     avi->stream_index = -1;
1295     avio_seek(pb, idx1_pos, SEEK_SET);
1296
1297     /* Read the entries and sort them in each stream component. */
1298     for (i = 0; i < nb_index_entries; i++) {
1299         tag   = avio_rl32(pb);
1300         flags = avio_rl32(pb);
1301         pos   = avio_rl32(pb);
1302         len   = avio_rl32(pb);
1303         av_log(s, AV_LOG_TRACE, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1304                 i, tag, flags, pos, len);
1305
1306         index  = ((tag      & 0xff) - '0') * 10;
1307         index +=  (tag >> 8 & 0xff) - '0';
1308         if (index >= s->nb_streams)
1309             continue;
1310         st  = s->streams[index];
1311         ast = st->priv_data;
1312
1313         if (first_packet && first_packet_pos && len) {
1314             data_offset  = first_packet_pos - pos;
1315             first_packet = 0;
1316         }
1317         pos += data_offset;
1318
1319         av_log(s, AV_LOG_TRACE, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1320
1321         if (pb->eof_reached)
1322             return AVERROR_INVALIDDATA;
1323
1324         if (last_pos == pos)
1325             avi->non_interleaved = 1;
1326         else if (len || !ast->sample_size)
1327             av_add_index_entry(st, pos, ast->cum_len, len, 0,
1328                                (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1329         ast->cum_len += get_duration(ast, len);
1330         last_pos      = pos;
1331     }
1332     return 0;
1333 }
1334
1335 /* Scan the index and consider any file with streams more than
1336  * 2 seconds or 64MB apart non-interleaved. */
1337 static int check_stream_max_drift(AVFormatContext *s)
1338 {
1339     int64_t min_pos, pos;
1340     int i;
1341     int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
1342     if (!idx)
1343         return AVERROR(ENOMEM);
1344
1345     for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
1346         int64_t max_dts = INT64_MIN / 2;
1347         int64_t min_dts = INT64_MAX / 2;
1348         int64_t max_buffer = 0;
1349
1350         min_pos = INT64_MAX;
1351
1352         for (i = 0; i < s->nb_streams; i++) {
1353             AVStream *st = s->streams[i];
1354             AVIStream *ast = st->priv_data;
1355             int n = st->nb_index_entries;
1356             while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
1357                 idx[i]++;
1358             if (idx[i] < n) {
1359                 int64_t dts;
1360                 dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
1361                                    FFMAX(ast->sample_size, 1),
1362                                    st->time_base, AV_TIME_BASE_Q);
1363                 min_dts = FFMIN(min_dts, dts);
1364                 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
1365             }
1366         }
1367         for (i = 0; i < s->nb_streams; i++) {
1368             AVStream *st = s->streams[i];
1369             AVIStream *ast = st->priv_data;
1370
1371             if (idx[i] && min_dts != INT64_MAX / 2) {
1372                 int64_t dts;
1373                 dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
1374                                    FFMAX(ast->sample_size, 1),
1375                                    st->time_base, AV_TIME_BASE_Q);
1376                 max_dts = FFMAX(max_dts, dts);
1377                 max_buffer = FFMAX(max_buffer,
1378                                    av_rescale(dts - min_dts,
1379                                               st->codecpar->bit_rate,
1380                                               AV_TIME_BASE));
1381             }
1382         }
1383         if (max_dts - min_dts > 2 * AV_TIME_BASE ||
1384             max_buffer > 1024 * 1024 * 8 * 8) {
1385             av_free(idx);
1386             return 1;
1387         }
1388     }
1389     av_free(idx);
1390     return 0;
1391 }
1392
1393 static int guess_ni_flag(AVFormatContext *s)
1394 {
1395     int i;
1396     int64_t last_start = 0;
1397     int64_t first_end  = INT64_MAX;
1398     int64_t oldpos     = avio_tell(s->pb);
1399
1400     for (i = 0; i < s->nb_streams; i++) {
1401         AVStream *st = s->streams[i];
1402         int n        = st->nb_index_entries;
1403         unsigned int size;
1404
1405         if (n <= 0)
1406             continue;
1407
1408         if (n >= 2) {
1409             int64_t pos = st->index_entries[0].pos;
1410             avio_seek(s->pb, pos + 4, SEEK_SET);
1411             size = avio_rl32(s->pb);
1412             if (pos + size > st->index_entries[1].pos)
1413                 last_start = INT64_MAX;
1414         }
1415
1416         if (st->index_entries[0].pos > last_start)
1417             last_start = st->index_entries[0].pos;
1418         if (st->index_entries[n - 1].pos < first_end)
1419             first_end = st->index_entries[n - 1].pos;
1420     }
1421     avio_seek(s->pb, oldpos, SEEK_SET);
1422
1423     if (last_start > first_end)
1424         return 1;
1425
1426     return check_stream_max_drift(s);
1427 }
1428
1429 static int avi_load_index(AVFormatContext *s)
1430 {
1431     AVIContext *avi = s->priv_data;
1432     AVIOContext *pb = s->pb;
1433     uint32_t tag, size;
1434     int64_t pos = avio_tell(pb);
1435     int ret     = -1;
1436
1437     if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1438         goto the_end; // maybe truncated file
1439     av_log(s, AV_LOG_TRACE, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1440     for (;;) {
1441         if (pb->eof_reached)
1442             break;
1443         tag  = avio_rl32(pb);
1444         size = avio_rl32(pb);
1445
1446         if (tag == MKTAG('i', 'd', 'x', '1') &&
1447             avi_read_idx1(s, size) >= 0) {
1448             ret = 0;
1449             break;
1450         }
1451
1452         size += (size & 1);
1453         if (avio_skip(pb, size) < 0)
1454             break; // something is wrong here
1455     }
1456
1457 the_end:
1458     avio_seek(pb, pos, SEEK_SET);
1459     return ret;
1460 }
1461
1462 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1463 {
1464     AVIStream *ast2 = st2->priv_data;
1465     int64_t ts2     = av_rescale_q(timestamp, st->time_base, st2->time_base);
1466     av_packet_unref(&ast2->sub_pkt);
1467     if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1468         avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1469         ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1470 }
1471
1472 static int avi_read_seek(AVFormatContext *s, int stream_index,
1473                          int64_t timestamp, int flags)
1474 {
1475     AVIContext *avi = s->priv_data;
1476     AVStream *st;
1477     int i, index;
1478     int64_t pos;
1479     AVIStream *ast;
1480
1481     /* Does not matter which stream is requested dv in avi has the
1482      * stream information in the first video stream.
1483      */
1484     if (avi->dv_demux)
1485         stream_index = 0;
1486
1487     if (!avi->index_loaded) {
1488         /* we only load the index on demand */
1489         avi_load_index(s);
1490         avi->index_loaded = 1;
1491     }
1492
1493     st    = s->streams[stream_index];
1494     ast   = st->priv_data;
1495     index = av_index_search_timestamp(st,
1496                                       timestamp * FFMAX(ast->sample_size, 1),
1497                                       flags);
1498     if (index < 0)
1499         return AVERROR_INVALIDDATA;
1500
1501     /* find the position */
1502     pos       = st->index_entries[index].pos;
1503     timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1504
1505     av_log(s, AV_LOG_TRACE, "XX %"PRId64" %d %"PRId64"\n",
1506             timestamp, index, st->index_entries[index].timestamp);
1507
1508     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1509         /* One and only one real stream for DV in AVI, and it has video  */
1510         /* offsets. Calling with other stream indexes should have failed */
1511         /* the av_index_search_timestamp call above.                     */
1512
1513         /* Feed the DV video stream version of the timestamp to the */
1514         /* DV demux so it can synthesize correct timestamps.        */
1515         ff_dv_offset_reset(avi->dv_demux, timestamp);
1516
1517         avio_seek(s->pb, pos, SEEK_SET);
1518         avi->stream_index = -1;
1519         return 0;
1520     }
1521
1522     for (i = 0; i < s->nb_streams; i++) {
1523         AVStream *st2   = s->streams[i];
1524         AVIStream *ast2 = st2->priv_data;
1525
1526         ast2->packet_size =
1527         ast2->remaining   = 0;
1528
1529         if (ast2->sub_ctx) {
1530             seek_subtitle(st, st2, timestamp);
1531             continue;
1532         }
1533
1534         if (st2->nb_index_entries <= 0)
1535             continue;
1536
1537 //        assert(st2->codecpar->block_align);
1538         assert((int64_t)st2->time_base.num * ast2->rate ==
1539                (int64_t)st2->time_base.den * ast2->scale);
1540         index = av_index_search_timestamp(st2,
1541                                           av_rescale_q(timestamp,
1542                                                        st->time_base,
1543                                                        st2->time_base) *
1544                                           FFMAX(ast2->sample_size, 1),
1545                                           flags | AVSEEK_FLAG_BACKWARD);
1546         if (index < 0)
1547             index = 0;
1548
1549         if (!avi->non_interleaved) {
1550             while (index > 0 && st2->index_entries[index].pos > pos)
1551                 index--;
1552             while (index + 1 < st2->nb_index_entries &&
1553                    st2->index_entries[index].pos < pos)
1554                 index++;
1555         }
1556
1557         av_log(s, AV_LOG_TRACE, "%"PRId64" %d %"PRId64"\n",
1558                 timestamp, index, st2->index_entries[index].timestamp);
1559         /* extract the current frame number */
1560         ast2->frame_offset = st2->index_entries[index].timestamp;
1561     }
1562
1563     /* do the seek */
1564     avio_seek(s->pb, pos, SEEK_SET);
1565     avi->stream_index = -1;
1566     return 0;
1567 }
1568
1569 static int avi_read_close(AVFormatContext *s)
1570 {
1571     int i;
1572     AVIContext *avi = s->priv_data;
1573
1574     for (i = 0; i < s->nb_streams; i++) {
1575         AVStream *st   = s->streams[i];
1576         AVIStream *ast = st->priv_data;
1577         if (ast) {
1578             if (ast->sub_ctx) {
1579                 av_freep(&ast->sub_ctx->pb);
1580                 avformat_close_input(&ast->sub_ctx);
1581             }
1582             av_free(ast->sub_buffer);
1583             av_packet_unref(&ast->sub_pkt);
1584         }
1585     }
1586
1587     av_free(avi->dv_demux);
1588
1589     return 0;
1590 }
1591
1592 static int avi_probe(AVProbeData *p)
1593 {
1594     int i;
1595
1596     /* check file header */
1597     for (i = 0; avi_headers[i][0]; i++)
1598         if (!memcmp(p->buf,     avi_headers[i],     4) &&
1599             !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
1600             return AVPROBE_SCORE_MAX;
1601
1602     return 0;
1603 }
1604
1605 AVInputFormat ff_avi_demuxer = {
1606     .name           = "avi",
1607     .long_name      = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1608     .priv_data_size = sizeof(AVIContext),
1609     .extensions     = "avi",
1610     .read_probe     = avi_probe,
1611     .read_header    = avi_read_header,
1612     .read_packet    = avi_read_packet,
1613     .read_close     = avi_read_close,
1614     .read_seek      = avi_read_seek,
1615 };