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