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