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