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