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