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