]> git.sesse.net Git - ffmpeg/blob - libavformat/avidec.c
ffmpeg: Factor out redundant sync_ipts calculation
[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 //#define DEBUG
23 //#define DEBUG_SEEK
24
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/bswap.h"
27 #include "avformat.h"
28 #include "avi.h"
29 #include "dv.h"
30 #include "riff.h"
31
32 #undef NDEBUG
33 #include <assert.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     int scale;
42     int 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 } AVIStream;
52
53 typedef struct {
54     int64_t  riff_end;
55     int64_t  movi_end;
56     int64_t  fsize;
57     int64_t movi_list;
58     int64_t last_pkt_pos;
59     int index_loaded;
60     int is_odml;
61     int non_interleaved;
62     int stream_index;
63     DVDemuxContext* dv_demux;
64 } AVIContext;
65
66 static const char avi_headers[][8] = {
67     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', ' ' },
68     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 'X' },
69     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 0x19},
70     { 'O', 'N', '2', ' ',    'O', 'N', '2', 'f' },
71     { 'R', 'I', 'F', 'F',    'A', 'M', 'V', ' ' },
72     { 0 }
73 };
74
75 static int avi_load_index(AVFormatContext *s);
76 static int guess_ni_flag(AVFormatContext *s);
77
78 #ifdef DEBUG
79 static void print_tag(const char *str, unsigned int tag, int size)
80 {
81     dprintf(NULL, "%s: tag=%c%c%c%c size=0x%x\n",
82            str, tag & 0xff,
83            (tag >> 8) & 0xff,
84            (tag >> 16) & 0xff,
85            (tag >> 24) & 0xff,
86            size);
87 }
88 #endif
89
90 static int get_riff(AVFormatContext *s, ByteIOContext *pb)
91 {
92     AVIContext *avi = s->priv_data;
93     char header[8];
94     int i;
95
96     /* check RIFF header */
97     get_buffer(pb, header, 4);
98     avi->riff_end = get_le32(pb);   /* RIFF chunk size */
99     avi->riff_end += url_ftell(pb); /* RIFF chunk end */
100     get_buffer(pb, header+4, 4);
101
102     for(i=0; avi_headers[i][0]; i++)
103         if(!memcmp(header, avi_headers[i], 8))
104             break;
105     if(!avi_headers[i][0])
106         return -1;
107
108     if(header[7] == 0x19)
109         av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
110
111     return 0;
112 }
113
114 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
115     AVIContext *avi = s->priv_data;
116     ByteIOContext *pb = s->pb;
117     int longs_pre_entry= get_le16(pb);
118     int index_sub_type = get_byte(pb);
119     int index_type     = get_byte(pb);
120     int entries_in_use = get_le32(pb);
121     int chunk_id       = get_le32(pb);
122     int64_t base       = get_le64(pb);
123     int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
124     AVStream *st;
125     AVIStream *ast;
126     int i;
127     int64_t last_pos= -1;
128     int64_t filesize= url_fsize(s->pb);
129
130 #ifdef DEBUG_SEEK
131     av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
132         longs_pre_entry,index_type, entries_in_use, chunk_id, base);
133 #endif
134
135     if(stream_id >= s->nb_streams || stream_id < 0)
136         return -1;
137     st= s->streams[stream_id];
138     ast = st->priv_data;
139
140     if(index_sub_type)
141         return -1;
142
143     get_le32(pb);
144
145     if(index_type && longs_pre_entry != 2)
146         return -1;
147     if(index_type>1)
148         return -1;
149
150     if(filesize > 0 && base >= filesize){
151         av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
152         if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
153             base &= 0xFFFFFFFF;
154         else
155             return -1;
156     }
157
158     for(i=0; i<entries_in_use; i++){
159         if(index_type){
160             int64_t pos= get_le32(pb) + base - 8;
161             int len    = get_le32(pb);
162             int key= len >= 0;
163             len &= 0x7FFFFFFF;
164
165 #ifdef DEBUG_SEEK
166             av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
167 #endif
168             if(url_feof(pb))
169                 return -1;
170
171             if(last_pos == pos || pos == base - 8)
172                 avi->non_interleaved= 1;
173             if(last_pos != pos && (len || !ast->sample_size))
174                 av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
175
176             if(ast->sample_size)
177                 ast->cum_len += len;
178             else
179                 ast->cum_len ++;
180             last_pos= pos;
181         }else{
182             int64_t offset, pos;
183             int duration;
184             offset = get_le64(pb);
185             get_le32(pb);       /* size */
186             duration = get_le32(pb);
187
188             if(url_feof(pb))
189                 return -1;
190
191             pos = url_ftell(pb);
192
193             url_fseek(pb, offset+8, SEEK_SET);
194             read_braindead_odml_indx(s, frame_num);
195             frame_num += duration;
196
197             url_fseek(pb, pos, SEEK_SET);
198         }
199     }
200     avi->index_loaded=1;
201     return 0;
202 }
203
204 static void clean_index(AVFormatContext *s){
205     int i;
206     int64_t j;
207
208     for(i=0; i<s->nb_streams; i++){
209         AVStream *st = s->streams[i];
210         AVIStream *ast = st->priv_data;
211         int n= st->nb_index_entries;
212         int max= ast->sample_size;
213         int64_t pos, size, ts;
214
215         if(n != 1 || ast->sample_size==0)
216             continue;
217
218         while(max < 1024) max+=max;
219
220         pos= st->index_entries[0].pos;
221         size= st->index_entries[0].size;
222         ts= st->index_entries[0].timestamp;
223
224         for(j=0; j<size; j+=max){
225             av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
226         }
227     }
228 }
229
230 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
231 {
232     ByteIOContext *pb = s->pb;
233     char key[5] = {0}, *value;
234
235     size += (size & 1);
236
237     if (size == UINT_MAX)
238         return -1;
239     value = av_malloc(size+1);
240     if (!value)
241         return -1;
242     get_buffer(pb, value, size);
243     value[size]=0;
244
245     AV_WL32(key, tag);
246
247     if(st)
248         return av_metadata_set2(&st->metadata, key, value,
249                                     AV_METADATA_DONT_STRDUP_VAL);
250     else
251     return av_metadata_set2(&s->metadata, key, value,
252                                   AV_METADATA_DONT_STRDUP_VAL);
253 }
254
255 static void avi_read_info(AVFormatContext *s, uint64_t end)
256 {
257     while (url_ftell(s->pb) < end) {
258         uint32_t tag  = get_le32(s->pb);
259         uint32_t size = get_le32(s->pb);
260         avi_read_tag(s, NULL, tag, size);
261     }
262 }
263
264 static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
265 {
266     AVIContext *avi = s->priv_data;
267     ByteIOContext *pb = s->pb;
268     unsigned int tag, tag1, handler;
269     int codec_type, stream_index, frame_period, bit_rate;
270     unsigned int size;
271     int i;
272     AVStream *st;
273     AVIStream *ast = NULL;
274     int avih_width=0, avih_height=0;
275     int amv_file_format=0;
276     uint64_t list_end = 0;
277
278     avi->stream_index= -1;
279
280     if (get_riff(s, pb) < 0)
281         return -1;
282
283     avi->fsize = url_fsize(pb);
284     if(avi->fsize<=0)
285         avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
286
287     /* first list tag */
288     stream_index = -1;
289     codec_type = -1;
290     frame_period = 0;
291     for(;;) {
292         if (url_feof(pb))
293             goto fail;
294         tag = get_le32(pb);
295         size = get_le32(pb);
296 #ifdef DEBUG
297         print_tag("tag", tag, size);
298 #endif
299
300         switch(tag) {
301         case MKTAG('L', 'I', 'S', 'T'):
302             list_end = url_ftell(pb) + size;
303             /* Ignored, except at start of video packets. */
304             tag1 = get_le32(pb);
305 #ifdef DEBUG
306             print_tag("list", tag1, 0);
307 #endif
308             if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
309                 avi->movi_list = url_ftell(pb) - 4;
310                 if(size) avi->movi_end = avi->movi_list + size + (size & 1);
311                 else     avi->movi_end = url_fsize(pb);
312                 dprintf(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
313                 goto end_of_header;
314             }
315             else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
316                 avi_read_info(s, list_end);
317
318             break;
319         case MKTAG('d', 'm', 'l', 'h'):
320             avi->is_odml = 1;
321             url_fskip(pb, size + (size & 1));
322             break;
323         case MKTAG('a', 'm', 'v', 'h'):
324             amv_file_format=1;
325         case MKTAG('a', 'v', 'i', 'h'):
326             /* AVI header */
327             /* using frame_period is bad idea */
328             frame_period = get_le32(pb);
329             bit_rate = get_le32(pb) * 8;
330             get_le32(pb);
331             avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
332
333             url_fskip(pb, 2 * 4);
334             get_le32(pb);
335             get_le32(pb);
336             avih_width=get_le32(pb);
337             avih_height=get_le32(pb);
338
339             url_fskip(pb, size - 10 * 4);
340             break;
341         case MKTAG('s', 't', 'r', 'h'):
342             /* stream header */
343
344             tag1 = get_le32(pb);
345             handler = get_le32(pb); /* codec tag */
346
347             if(tag1 == MKTAG('p', 'a', 'd', 's')){
348                 url_fskip(pb, size - 8);
349                 break;
350             }else{
351                 stream_index++;
352                 st = av_new_stream(s, stream_index);
353                 if (!st)
354                     goto fail;
355
356                 ast = av_mallocz(sizeof(AVIStream));
357                 if (!ast)
358                     goto fail;
359                 st->priv_data = ast;
360             }
361             if(amv_file_format)
362                 tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
363
364 #ifdef DEBUG
365             print_tag("strh", tag1, -1);
366 #endif
367             if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
368                 int64_t dv_dur;
369
370                 /*
371                  * After some consideration -- I don't think we
372                  * have to support anything but DV in type1 AVIs.
373                  */
374                 if (s->nb_streams != 1)
375                     goto fail;
376
377                 if (handler != MKTAG('d', 'v', 's', 'd') &&
378                     handler != MKTAG('d', 'v', 'h', 'd') &&
379                     handler != MKTAG('d', 'v', 's', 'l'))
380                    goto fail;
381
382                 ast = s->streams[0]->priv_data;
383                 av_freep(&s->streams[0]->codec->extradata);
384                 av_freep(&s->streams[0]);
385                 s->nb_streams = 0;
386                 if (CONFIG_DV_DEMUXER) {
387                     avi->dv_demux = dv_init_demux(s);
388                     if (!avi->dv_demux)
389                         goto fail;
390                 }
391                 s->streams[0]->priv_data = ast;
392                 url_fskip(pb, 3 * 4);
393                 ast->scale = get_le32(pb);
394                 ast->rate = get_le32(pb);
395                 url_fskip(pb, 4);  /* start time */
396
397                 dv_dur = get_le32(pb);
398                 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
399                     dv_dur *= AV_TIME_BASE;
400                     s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
401                 }
402                 /*
403                  * else, leave duration alone; timing estimation in utils.c
404                  *      will make a guess based on bitrate.
405                  */
406
407                 stream_index = s->nb_streams - 1;
408                 url_fskip(pb, size - 9*4);
409                 break;
410             }
411
412             assert(stream_index < s->nb_streams);
413             st->codec->stream_codec_tag= handler;
414
415             get_le32(pb); /* flags */
416             get_le16(pb); /* priority */
417             get_le16(pb); /* language */
418             get_le32(pb); /* initial frame */
419             ast->scale = get_le32(pb);
420             ast->rate = get_le32(pb);
421             if(!(ast->scale && ast->rate)){
422                 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);
423                 if(frame_period){
424                     ast->rate = 1000000;
425                     ast->scale = frame_period;
426                 }else{
427                     ast->rate = 25;
428                     ast->scale = 1;
429                 }
430             }
431             av_set_pts_info(st, 64, ast->scale, ast->rate);
432
433             ast->cum_len=get_le32(pb); /* start */
434             st->nb_frames = get_le32(pb);
435
436             st->start_time = 0;
437             get_le32(pb); /* buffer size */
438             get_le32(pb); /* quality */
439             ast->sample_size = get_le32(pb); /* sample ssize */
440             ast->cum_len *= FFMAX(1, ast->sample_size);
441 //            av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
442
443             switch(tag1) {
444             case MKTAG('v', 'i', 'd', 's'):
445                 codec_type = CODEC_TYPE_VIDEO;
446
447                 ast->sample_size = 0;
448                 break;
449             case MKTAG('a', 'u', 'd', 's'):
450                 codec_type = CODEC_TYPE_AUDIO;
451                 break;
452             case MKTAG('t', 'x', 't', 's'):
453                 //FIXME
454                 codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ?  FIXME
455                 break;
456             case MKTAG('d', 'a', 't', 's'):
457                 codec_type = CODEC_TYPE_DATA;
458                 break;
459             default:
460                 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
461                 goto fail;
462             }
463             if(ast->sample_size == 0)
464                 st->duration = st->nb_frames;
465             ast->frame_offset= ast->cum_len;
466             url_fskip(pb, size - 12 * 4);
467             break;
468         case MKTAG('s', 't', 'r', 'f'):
469             /* stream header */
470             if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
471                 url_fskip(pb, size);
472             } else {
473                 uint64_t cur_pos = url_ftell(pb);
474                 if (cur_pos < list_end)
475                     size = FFMIN(size, list_end - cur_pos);
476                 st = s->streams[stream_index];
477                 switch(codec_type) {
478                 case CODEC_TYPE_VIDEO:
479                     if(amv_file_format){
480                         st->codec->width=avih_width;
481                         st->codec->height=avih_height;
482                         st->codec->codec_type = CODEC_TYPE_VIDEO;
483                         st->codec->codec_id = CODEC_ID_AMV;
484                         url_fskip(pb, size);
485                         break;
486                     }
487                     get_le32(pb); /* size */
488                     st->codec->width = get_le32(pb);
489                     st->codec->height = (int32_t)get_le32(pb);
490                     get_le16(pb); /* panes */
491                     st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
492                     tag1 = get_le32(pb);
493                     get_le32(pb); /* ImageSize */
494                     get_le32(pb); /* XPelsPerMeter */
495                     get_le32(pb); /* YPelsPerMeter */
496                     get_le32(pb); /* ClrUsed */
497                     get_le32(pb); /* ClrImportant */
498
499                     if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
500                         st->codec->codec_type = CODEC_TYPE_SUBTITLE;
501                         st->codec->codec_tag = tag1;
502                         st->codec->codec_id = CODEC_ID_XSUB;
503                         break;
504                     }
505
506                     if(size > 10*4 && size<(1<<30)){
507                         st->codec->extradata_size= size - 10*4;
508                         st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
509                         if (!st->codec->extradata) {
510                             st->codec->extradata_size= 0;
511                             return AVERROR(ENOMEM);
512                         }
513                         get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
514                     }
515
516                     if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
517                         get_byte(pb);
518
519                     /* Extract palette from extradata if bpp <= 8. */
520                     /* This code assumes that extradata contains only palette. */
521                     /* This is true for all paletted codecs implemented in FFmpeg. */
522                     if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
523                         st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
524 #if HAVE_BIGENDIAN
525                         for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
526                             st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
527 #else
528                         memcpy(st->codec->palctrl->palette, st->codec->extradata,
529                                FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
530 #endif
531                         st->codec->palctrl->palette_changed = 1;
532                     }
533
534 #ifdef DEBUG
535                     print_tag("video", tag1, 0);
536 #endif
537                     st->codec->codec_type = CODEC_TYPE_VIDEO;
538                     st->codec->codec_tag = tag1;
539                     st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
540                     st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
541                     // Support "Resolution 1:1" for Avid AVI Codec
542                     if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
543                        st->codec->extradata_size >= 31 &&
544                        !memcmp(&st->codec->extradata[28], "1:1", 3))
545                         st->codec->codec_id = CODEC_ID_RAWVIDEO;
546
547                     if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
548                         st->codec->extradata_size+= 9;
549                         st->codec->extradata= av_realloc(st->codec->extradata, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
550                         if(st->codec->extradata)
551                             memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
552                     }
553                     st->codec->height= FFABS(st->codec->height);
554
555 //                    url_fskip(pb, size - 5 * 4);
556                     break;
557                 case CODEC_TYPE_AUDIO:
558                     ff_get_wav_header(pb, st->codec, size);
559                     if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
560                         av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
561                         ast->sample_size= st->codec->block_align;
562                     }
563                     if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
564                         url_fskip(pb, 1);
565                     /* Force parsing as several audio frames can be in
566                      * one packet and timestamps refer to packet start. */
567                     st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
568                     /* ADTS header is in extradata, AAC without header must be
569                      * stored as exact frames. Parser not needed and it will
570                      * fail. */
571                     if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
572                         st->need_parsing = AVSTREAM_PARSE_NONE;
573                     /* AVI files with Xan DPCM audio (wrongly) declare PCM
574                      * audio in the header but have Axan as stream_code_tag. */
575                     if (st->codec->stream_codec_tag == AV_RL32("Axan")){
576                         st->codec->codec_id  = CODEC_ID_XAN_DPCM;
577                         st->codec->codec_tag = 0;
578                     }
579                     if (amv_file_format)
580                         st->codec->codec_id  = CODEC_ID_ADPCM_IMA_AMV;
581                     break;
582                 default:
583                     st->codec->codec_type = CODEC_TYPE_DATA;
584                     st->codec->codec_id= CODEC_ID_NONE;
585                     st->codec->codec_tag= 0;
586                     url_fskip(pb, size);
587                     break;
588                 }
589             }
590             break;
591         case MKTAG('i', 'n', 'd', 'x'):
592             i= url_ftell(pb);
593             if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
594                 read_braindead_odml_indx(s, 0);
595             }
596             url_fseek(pb, i+size, SEEK_SET);
597             break;
598         case MKTAG('v', 'p', 'r', 'p'):
599             if(stream_index < (unsigned)s->nb_streams && size > 9*4){
600                 AVRational active, active_aspect;
601
602                 st = s->streams[stream_index];
603                 get_le32(pb);
604                 get_le32(pb);
605                 get_le32(pb);
606                 get_le32(pb);
607                 get_le32(pb);
608
609                 active_aspect.den= get_le16(pb);
610                 active_aspect.num= get_le16(pb);
611                 active.num       = get_le32(pb);
612                 active.den       = get_le32(pb);
613                 get_le32(pb); //nbFieldsPerFrame
614
615                 if(active_aspect.num && active_aspect.den && active.num && active.den){
616                     st->sample_aspect_ratio= av_div_q(active_aspect, active);
617 //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
618                 }
619                 size -= 9*4;
620             }
621             url_fseek(pb, size, SEEK_CUR);
622             break;
623         case MKTAG('s', 't', 'r', 'n'):
624             if(s->nb_streams){
625                 avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
626                 break;
627             }
628         default:
629             if(size > 1000000){
630                 av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
631                                         "I will ignore it and try to continue anyway.\n");
632                 avi->movi_list = url_ftell(pb) - 4;
633                 avi->movi_end  = url_fsize(pb);
634                 goto end_of_header;
635             }
636             /* skip tag */
637             size += (size & 1);
638             url_fskip(pb, size);
639             break;
640         }
641     }
642  end_of_header:
643     /* check stream number */
644     if (stream_index != s->nb_streams - 1) {
645     fail:
646         return -1;
647     }
648
649     if(!avi->index_loaded && !url_is_streamed(pb))
650         avi_load_index(s);
651     avi->index_loaded = 1;
652     avi->non_interleaved |= guess_ni_flag(s);
653     if(avi->non_interleaved) {
654         av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
655         clean_index(s);
656     }
657
658     return 0;
659 }
660
661 static int get_stream_idx(int *d){
662     if(    d[0] >= '0' && d[0] <= '9'
663         && d[1] >= '0' && d[1] <= '9'){
664         return (d[0] - '0') * 10 + (d[1] - '0');
665     }else{
666         return 100; //invalid stream ID
667     }
668 }
669
670 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
671 {
672     AVIContext *avi = s->priv_data;
673     ByteIOContext *pb = s->pb;
674     int n, d[8];
675     unsigned int size;
676     int64_t i, sync;
677     void* dstr;
678
679     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
680         int size = dv_get_packet(avi->dv_demux, pkt);
681         if (size >= 0)
682             return size;
683     }
684
685     if(avi->non_interleaved){
686         int best_stream_index = 0;
687         AVStream *best_st= NULL;
688         AVIStream *best_ast;
689         int64_t best_ts= INT64_MAX;
690         int i;
691
692         for(i=0; i<s->nb_streams; i++){
693             AVStream *st = s->streams[i];
694             AVIStream *ast = st->priv_data;
695             int64_t ts= ast->frame_offset;
696             int64_t last_ts;
697
698             if(!st->nb_index_entries)
699                 continue;
700
701             last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
702             if(!ast->remaining && ts > last_ts)
703                 continue;
704
705             ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
706
707 //            av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
708             if(ts < best_ts){
709                 best_ts= ts;
710                 best_st= st;
711                 best_stream_index= i;
712             }
713         }
714         if(!best_st)
715             return -1;
716
717         best_ast = best_st->priv_data;
718         best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
719         if(best_ast->remaining)
720             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
721         else{
722             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
723             if(i>=0)
724                 best_ast->frame_offset= best_st->index_entries[i].timestamp;
725         }
726
727 //        av_log(s, AV_LOG_DEBUG, "%d\n", i);
728         if(i>=0){
729             int64_t pos= best_st->index_entries[i].pos;
730             pos += best_ast->packet_size - best_ast->remaining;
731             url_fseek(s->pb, pos + 8, SEEK_SET);
732 //        av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
733
734             assert(best_ast->remaining <= best_ast->packet_size);
735
736             avi->stream_index= best_stream_index;
737             if(!best_ast->remaining)
738                 best_ast->packet_size=
739                 best_ast->remaining= best_st->index_entries[i].size;
740         }
741     }
742
743 resync:
744     if(avi->stream_index >= 0){
745         AVStream *st= s->streams[ avi->stream_index ];
746         AVIStream *ast= st->priv_data;
747         int size, err;
748
749         if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
750             size= INT_MAX;
751         else if(ast->sample_size < 32)
752             // arbitrary multiplier to avoid tiny packets for raw PCM data
753             size= 1024*ast->sample_size;
754         else
755             size= ast->sample_size;
756
757         if(size > ast->remaining)
758             size= ast->remaining;
759         avi->last_pkt_pos= url_ftell(pb);
760         err= av_get_packet(pb, pkt, size);
761         if(err<0)
762             return err;
763
764         if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
765             void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
766             if(ptr){
767             ast->has_pal=0;
768             pkt->size += 4*256;
769             pkt->data= ptr;
770                 memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
771             }else
772                 av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
773         }
774
775         if (CONFIG_DV_DEMUXER && avi->dv_demux) {
776             dstr = pkt->destruct;
777             size = dv_produce_packet(avi->dv_demux, pkt,
778                                     pkt->data, pkt->size);
779             pkt->destruct = dstr;
780             pkt->flags |= PKT_FLAG_KEY;
781         } else {
782             /* XXX: How to handle B-frames in AVI? */
783             pkt->dts = ast->frame_offset;
784 //                pkt->dts += ast->start;
785             if(ast->sample_size)
786                 pkt->dts /= ast->sample_size;
787 //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);
788             pkt->stream_index = avi->stream_index;
789
790             if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
791                 AVIndexEntry *e;
792                 int index;
793                 assert(st->index_entries);
794
795                 index= av_index_search_timestamp(st, ast->frame_offset, 0);
796                 e= &st->index_entries[index];
797
798                 if(index >= 0 && e->timestamp == ast->frame_offset){
799                     if (e->flags & AVINDEX_KEYFRAME)
800                         pkt->flags |= PKT_FLAG_KEY;
801                 }
802             } else {
803                 pkt->flags |= PKT_FLAG_KEY;
804             }
805             if(ast->sample_size)
806                 ast->frame_offset += pkt->size;
807             else
808                 ast->frame_offset++;
809         }
810         ast->remaining -= size;
811         if(!ast->remaining){
812             avi->stream_index= -1;
813             ast->packet_size= 0;
814         }
815
816         return size;
817     }
818
819     memset(d, -1, sizeof(int)*8);
820     for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
821         int j;
822
823         for(j=0; j<7; j++)
824             d[j]= d[j+1];
825         d[7]= get_byte(pb);
826
827         size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
828
829         n= get_stream_idx(d+2);
830 //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);
831         if(i + (uint64_t)size > avi->fsize || d[0]<0)
832             continue;
833
834         //parse ix##
835         if(  (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
836         //parse JUNK
837            ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
838            ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
839             url_fskip(pb, size);
840 //av_log(s, AV_LOG_DEBUG, "SKIP\n");
841             goto resync;
842         }
843
844         //parse stray LIST
845         if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
846             url_fskip(pb, 4);
847             goto resync;
848         }
849
850         n= get_stream_idx(d);
851
852         if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
853             continue;
854
855         //detect ##ix chunk and skip
856         if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
857             url_fskip(pb, size);
858             goto resync;
859         }
860
861         //parse ##dc/##wb
862         if(n < s->nb_streams){
863             AVStream *st;
864             AVIStream *ast;
865             st = s->streams[n];
866             ast = st->priv_data;
867
868             if(s->nb_streams>=2){
869                 AVStream *st1  = s->streams[1];
870                 AVIStream *ast1= st1->priv_data;
871                 //workaround for broken small-file-bug402.avi
872                 if(   d[2] == 'w' && d[3] == 'b'
873                    && n==0
874                    && st ->codec->codec_type == CODEC_TYPE_VIDEO
875                    && st1->codec->codec_type == CODEC_TYPE_AUDIO
876                    && ast->prefix == 'd'*256+'c'
877                    && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
878                   ){
879                     n=1;
880                     st = st1;
881                     ast = ast1;
882                     av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
883                 }
884             }
885
886
887             if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
888                /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
889                || st->discard >= AVDISCARD_ALL){
890                 if(ast->sample_size) ast->frame_offset += pkt->size;
891                 else                 ast->frame_offset++;
892                 url_fskip(pb, size);
893                 goto resync;
894             }
895
896             if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
897                 int k = get_byte(pb);
898                 int last = (k + get_byte(pb) - 1) & 0xFF;
899
900                 get_le16(pb); //flags
901
902                 for (; k <= last; k++)
903                     ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
904                 ast->has_pal= 1;
905                 goto resync;
906             } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
907                          d[2]*256+d[3] == ast->prefix /*||
908                          (d[2] == 'd' && d[3] == 'c') ||
909                          (d[2] == 'w' && d[3] == 'b')*/) {
910
911 //av_log(s, AV_LOG_DEBUG, "OK\n");
912                 if(d[2]*256+d[3] == ast->prefix)
913                     ast->prefix_count++;
914                 else{
915                     ast->prefix= d[2]*256+d[3];
916                     ast->prefix_count= 0;
917                 }
918
919                 avi->stream_index= n;
920                 ast->packet_size= size + 8;
921                 ast->remaining= size;
922
923                 if(size || !ast->sample_size){
924                     uint64_t pos= url_ftell(pb) - 8;
925                     if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
926                         av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
927                     }
928                 }
929                 goto resync;
930             }
931         }
932     }
933
934     return AVERROR_EOF;
935 }
936
937 /* XXX: We make the implicit supposition that the positions are sorted
938    for each stream. */
939 static int avi_read_idx1(AVFormatContext *s, int size)
940 {
941     AVIContext *avi = s->priv_data;
942     ByteIOContext *pb = s->pb;
943     int nb_index_entries, i;
944     AVStream *st;
945     AVIStream *ast;
946     unsigned int index, tag, flags, pos, len;
947     unsigned last_pos= -1;
948
949     nb_index_entries = size / 16;
950     if (nb_index_entries <= 0)
951         return -1;
952
953     /* Read the entries and sort them in each stream component. */
954     for(i = 0; i < nb_index_entries; i++) {
955         tag = get_le32(pb);
956         flags = get_le32(pb);
957         pos = get_le32(pb);
958         len = get_le32(pb);
959 #if defined(DEBUG_SEEK)
960         av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
961                i, tag, flags, pos, len);
962 #endif
963         if(i==0 && pos > avi->movi_list)
964             avi->movi_list= 0; //FIXME better check
965         pos += avi->movi_list;
966
967         index = ((tag & 0xff) - '0') * 10;
968         index += ((tag >> 8) & 0xff) - '0';
969         if (index >= s->nb_streams)
970             continue;
971         st = s->streams[index];
972         ast = st->priv_data;
973
974 #if defined(DEBUG_SEEK)
975         av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
976 #endif
977         if(url_feof(pb))
978             return -1;
979
980         if(last_pos == pos)
981             avi->non_interleaved= 1;
982         else if(len || !ast->sample_size)
983             av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
984         if(ast->sample_size)
985             ast->cum_len += len;
986         else
987             ast->cum_len ++;
988         last_pos= pos;
989     }
990     return 0;
991 }
992
993 static int guess_ni_flag(AVFormatContext *s){
994     int i;
995     int64_t last_start=0;
996     int64_t first_end= INT64_MAX;
997     int64_t oldpos= url_ftell(s->pb);
998
999     for(i=0; i<s->nb_streams; i++){
1000         AVStream *st = s->streams[i];
1001         int n= st->nb_index_entries;
1002         unsigned int size;
1003
1004         if(n <= 0)
1005             continue;
1006
1007         if(n >= 2){
1008             int64_t pos= st->index_entries[0].pos;
1009             url_fseek(s->pb, pos + 4, SEEK_SET);
1010             size= get_le32(s->pb);
1011             if(pos + size > st->index_entries[1].pos)
1012                 last_start= INT64_MAX;
1013         }
1014
1015         if(st->index_entries[0].pos > last_start)
1016             last_start= st->index_entries[0].pos;
1017         if(st->index_entries[n-1].pos < first_end)
1018             first_end= st->index_entries[n-1].pos;
1019     }
1020     url_fseek(s->pb, oldpos, SEEK_SET);
1021     return last_start > first_end;
1022 }
1023
1024 static int avi_load_index(AVFormatContext *s)
1025 {
1026     AVIContext *avi = s->priv_data;
1027     ByteIOContext *pb = s->pb;
1028     uint32_t tag, size;
1029     int64_t pos= url_ftell(pb);
1030     int ret = -1;
1031
1032     if (url_fseek(pb, avi->movi_end, SEEK_SET) < 0)
1033         goto the_end; // maybe truncated file
1034 #ifdef DEBUG_SEEK
1035     printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
1036 #endif
1037     for(;;) {
1038         if (url_feof(pb))
1039             break;
1040         tag = get_le32(pb);
1041         size = get_le32(pb);
1042 #ifdef DEBUG_SEEK
1043         printf("tag=%c%c%c%c size=0x%x\n",
1044                tag & 0xff,
1045                (tag >> 8) & 0xff,
1046                (tag >> 16) & 0xff,
1047                (tag >> 24) & 0xff,
1048                size);
1049 #endif
1050         switch(tag) {
1051         case MKTAG('i', 'd', 'x', '1'):
1052             if (avi_read_idx1(s, size) < 0)
1053                 goto skip;
1054             ret = 0;
1055                 goto the_end;
1056             break;
1057         default:
1058         skip:
1059             size += (size & 1);
1060             if (url_fseek(pb, size, SEEK_CUR) < 0)
1061                 goto the_end; // something is wrong here
1062             break;
1063         }
1064     }
1065  the_end:
1066     url_fseek(pb, pos, SEEK_SET);
1067     return ret;
1068 }
1069
1070 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1071 {
1072     AVIContext *avi = s->priv_data;
1073     AVStream *st;
1074     int i, index;
1075     int64_t pos;
1076     AVIStream *ast;
1077
1078     if (!avi->index_loaded) {
1079         /* we only load the index on demand */
1080         avi_load_index(s);
1081         avi->index_loaded = 1;
1082     }
1083     assert(stream_index>= 0);
1084
1085     st = s->streams[stream_index];
1086     ast= st->priv_data;
1087     index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
1088     if(index<0)
1089         return -1;
1090
1091     /* find the position */
1092     pos = st->index_entries[index].pos;
1093     timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1094
1095 //    av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1096
1097     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1098         /* One and only one real stream for DV in AVI, and it has video  */
1099         /* offsets. Calling with other stream indexes should have failed */
1100         /* the av_index_search_timestamp call above.                     */
1101         assert(stream_index == 0);
1102
1103         /* Feed the DV video stream version of the timestamp to the */
1104         /* DV demux so it can synthesize correct timestamps.        */
1105         dv_offset_reset(avi->dv_demux, timestamp);
1106
1107         url_fseek(s->pb, pos, SEEK_SET);
1108         avi->stream_index= -1;
1109         return 0;
1110     }
1111
1112     for(i = 0; i < s->nb_streams; i++) {
1113         AVStream *st2 = s->streams[i];
1114         AVIStream *ast2 = st2->priv_data;
1115
1116         ast2->packet_size=
1117         ast2->remaining= 0;
1118
1119         if (st2->nb_index_entries <= 0)
1120             continue;
1121
1122 //        assert(st2->codec->block_align);
1123         assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1124         index = av_index_search_timestamp(
1125                 st2,
1126                 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1127                 flags | AVSEEK_FLAG_BACKWARD);
1128         if(index<0)
1129             index=0;
1130
1131         if(!avi->non_interleaved){
1132             while(index>0 && st2->index_entries[index].pos > pos)
1133                 index--;
1134             while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
1135                 index++;
1136         }
1137
1138 //        av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
1139         /* extract the current frame number */
1140         ast2->frame_offset = st2->index_entries[index].timestamp;
1141     }
1142
1143     /* do the seek */
1144     url_fseek(s->pb, pos, SEEK_SET);
1145     avi->stream_index= -1;
1146     return 0;
1147 }
1148
1149 static int avi_read_close(AVFormatContext *s)
1150 {
1151     int i;
1152     AVIContext *avi = s->priv_data;
1153
1154     for(i=0;i<s->nb_streams;i++) {
1155         AVStream *st = s->streams[i];
1156         av_free(st->codec->palctrl);
1157     }
1158
1159     if (avi->dv_demux)
1160         av_free(avi->dv_demux);
1161
1162     return 0;
1163 }
1164
1165 static int avi_probe(AVProbeData *p)
1166 {
1167     int i;
1168
1169     /* check file header */
1170     for(i=0; avi_headers[i][0]; i++)
1171         if(!memcmp(p->buf  , avi_headers[i]  , 4) &&
1172            !memcmp(p->buf+8, avi_headers[i]+4, 4))
1173             return AVPROBE_SCORE_MAX;
1174
1175     return 0;
1176 }
1177
1178 AVInputFormat avi_demuxer = {
1179     "avi",
1180     NULL_IF_CONFIG_SMALL("AVI format"),
1181     sizeof(AVIContext),
1182     avi_probe,
1183     avi_read_header,
1184     avi_read_packet,
1185     avi_read_close,
1186     avi_read_seek,
1187     .metadata_conv = ff_avi_metadata_conv,
1188 };