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