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