]> git.sesse.net Git - ffmpeg/blob - libavformat/avidec.c
RTSP: Remove skip_spaces in favor of strspn
[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 = AVMEDIA_TYPE_VIDEO;
446
447                 ast->sample_size = 0;
448                 break;
449             case MKTAG('a', 'u', 'd', 's'):
450                 codec_type = AVMEDIA_TYPE_AUDIO;
451                 break;
452             case MKTAG('t', 'x', 't', 's'):
453                 //FIXME
454                 codec_type = AVMEDIA_TYPE_DATA; //AVMEDIA_TYPE_SUB ?  FIXME
455                 break;
456             case MKTAG('d', 'a', 't', 's'):
457                 codec_type = AVMEDIA_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 AVMEDIA_TYPE_VIDEO:
479                     if(amv_file_format){
480                         st->codec->width=avih_width;
481                         st->codec->height=avih_height;
482                         st->codec->codec_type = AVMEDIA_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 = AVMEDIA_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 = AVMEDIA_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 AVMEDIA_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&1) /* 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 = AVMEDIA_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     for(i=0; i<s->nb_streams; i++){
654         AVStream *st = s->streams[i];
655         if(st->nb_index_entries)
656             break;
657     }
658     if(i==s->nb_streams && avi->non_interleaved) {
659         av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
660         avi->non_interleaved=0;
661     }
662
663     if(avi->non_interleaved) {
664         av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
665         clean_index(s);
666     }
667
668     return 0;
669 }
670
671 static int get_stream_idx(int *d){
672     if(    d[0] >= '0' && d[0] <= '9'
673         && d[1] >= '0' && d[1] <= '9'){
674         return (d[0] - '0') * 10 + (d[1] - '0');
675     }else{
676         return 100; //invalid stream ID
677     }
678 }
679
680 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
681 {
682     AVIContext *avi = s->priv_data;
683     ByteIOContext *pb = s->pb;
684     int n, d[8];
685     unsigned int size;
686     int64_t i, sync;
687     void* dstr;
688
689     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
690         int size = dv_get_packet(avi->dv_demux, pkt);
691         if (size >= 0)
692             return size;
693     }
694
695     if(avi->non_interleaved){
696         int best_stream_index = 0;
697         AVStream *best_st= NULL;
698         AVIStream *best_ast;
699         int64_t best_ts= INT64_MAX;
700         int i;
701
702         for(i=0; i<s->nb_streams; i++){
703             AVStream *st = s->streams[i];
704             AVIStream *ast = st->priv_data;
705             int64_t ts= ast->frame_offset;
706             int64_t last_ts;
707
708             if(!st->nb_index_entries)
709                 continue;
710
711             last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
712             if(!ast->remaining && ts > last_ts)
713                 continue;
714
715             ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
716
717 //            av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
718             if(ts < best_ts){
719                 best_ts= ts;
720                 best_st= st;
721                 best_stream_index= i;
722             }
723         }
724         if(!best_st)
725             return -1;
726
727         best_ast = best_st->priv_data;
728         best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
729         if(best_ast->remaining)
730             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
731         else{
732             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
733             if(i>=0)
734                 best_ast->frame_offset= best_st->index_entries[i].timestamp;
735         }
736
737 //        av_log(s, AV_LOG_DEBUG, "%d\n", i);
738         if(i>=0){
739             int64_t pos= best_st->index_entries[i].pos;
740             pos += best_ast->packet_size - best_ast->remaining;
741             url_fseek(s->pb, pos + 8, SEEK_SET);
742 //        av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
743
744             assert(best_ast->remaining <= best_ast->packet_size);
745
746             avi->stream_index= best_stream_index;
747             if(!best_ast->remaining)
748                 best_ast->packet_size=
749                 best_ast->remaining= best_st->index_entries[i].size;
750         }
751     }
752
753 resync:
754     if(avi->stream_index >= 0){
755         AVStream *st= s->streams[ avi->stream_index ];
756         AVIStream *ast= st->priv_data;
757         int size, err;
758
759         if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
760             size= INT_MAX;
761         else if(ast->sample_size < 32)
762             // arbitrary multiplier to avoid tiny packets for raw PCM data
763             size= 1024*ast->sample_size;
764         else
765             size= ast->sample_size;
766
767         if(size > ast->remaining)
768             size= ast->remaining;
769         avi->last_pkt_pos= url_ftell(pb);
770         err= av_get_packet(pb, pkt, size);
771         if(err<0)
772             return err;
773
774         if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
775             void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
776             if(ptr){
777             ast->has_pal=0;
778             pkt->size += 4*256;
779             pkt->data= ptr;
780                 memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
781             }else
782                 av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
783         }
784
785         if (CONFIG_DV_DEMUXER && avi->dv_demux) {
786             dstr = pkt->destruct;
787             size = dv_produce_packet(avi->dv_demux, pkt,
788                                     pkt->data, pkt->size);
789             pkt->destruct = dstr;
790             pkt->flags |= AV_PKT_FLAG_KEY;
791         } else {
792             /* XXX: How to handle B-frames in AVI? */
793             pkt->dts = ast->frame_offset;
794 //                pkt->dts += ast->start;
795             if(ast->sample_size)
796                 pkt->dts /= ast->sample_size;
797 //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);
798             pkt->stream_index = avi->stream_index;
799
800             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
801                 AVIndexEntry *e;
802                 int index;
803                 assert(st->index_entries);
804
805                 index= av_index_search_timestamp(st, ast->frame_offset, 0);
806                 e= &st->index_entries[index];
807
808                 if(index >= 0 && e->timestamp == ast->frame_offset){
809                     if (e->flags & AVINDEX_KEYFRAME)
810                         pkt->flags |= AV_PKT_FLAG_KEY;
811                 }
812             } else {
813                 pkt->flags |= AV_PKT_FLAG_KEY;
814             }
815             if(ast->sample_size)
816                 ast->frame_offset += pkt->size;
817             else
818                 ast->frame_offset++;
819         }
820         ast->remaining -= size;
821         if(!ast->remaining){
822             avi->stream_index= -1;
823             ast->packet_size= 0;
824         }
825
826         return size;
827     }
828
829     memset(d, -1, sizeof(int)*8);
830     for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
831         int j;
832
833         for(j=0; j<7; j++)
834             d[j]= d[j+1];
835         d[7]= get_byte(pb);
836
837         size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
838
839         n= get_stream_idx(d+2);
840 //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);
841         if(i + (uint64_t)size > avi->fsize || d[0]<0)
842             continue;
843
844         //parse ix##
845         if(  (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
846         //parse JUNK
847            ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
848            ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
849             url_fskip(pb, size);
850 //av_log(s, AV_LOG_DEBUG, "SKIP\n");
851             goto resync;
852         }
853
854         //parse stray LIST
855         if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
856             url_fskip(pb, 4);
857             goto resync;
858         }
859
860         n= get_stream_idx(d);
861
862         if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
863             continue;
864
865         //detect ##ix chunk and skip
866         if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
867             url_fskip(pb, size);
868             goto resync;
869         }
870
871         //parse ##dc/##wb
872         if(n < s->nb_streams){
873             AVStream *st;
874             AVIStream *ast;
875             st = s->streams[n];
876             ast = st->priv_data;
877
878             if(s->nb_streams>=2){
879                 AVStream *st1  = s->streams[1];
880                 AVIStream *ast1= st1->priv_data;
881                 //workaround for broken small-file-bug402.avi
882                 if(   d[2] == 'w' && d[3] == 'b'
883                    && n==0
884                    && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
885                    && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
886                    && ast->prefix == 'd'*256+'c'
887                    && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
888                   ){
889                     n=1;
890                     st = st1;
891                     ast = ast1;
892                     av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
893                 }
894             }
895
896
897             if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
898                /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
899                || st->discard >= AVDISCARD_ALL){
900                 if(ast->sample_size) ast->frame_offset += size;
901                 else                 ast->frame_offset++;
902                 url_fskip(pb, size);
903                 goto resync;
904             }
905
906             if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
907                 int k = get_byte(pb);
908                 int last = (k + get_byte(pb) - 1) & 0xFF;
909
910                 get_le16(pb); //flags
911
912                 for (; k <= last; k++)
913                     ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
914                 ast->has_pal= 1;
915                 goto resync;
916             } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
917                          d[2]*256+d[3] == ast->prefix /*||
918                          (d[2] == 'd' && d[3] == 'c') ||
919                          (d[2] == 'w' && d[3] == 'b')*/) {
920
921 //av_log(s, AV_LOG_DEBUG, "OK\n");
922                 if(d[2]*256+d[3] == ast->prefix)
923                     ast->prefix_count++;
924                 else{
925                     ast->prefix= d[2]*256+d[3];
926                     ast->prefix_count= 0;
927                 }
928
929                 avi->stream_index= n;
930                 ast->packet_size= size + 8;
931                 ast->remaining= size;
932
933                 if(size || !ast->sample_size){
934                     uint64_t pos= url_ftell(pb) - 8;
935                     if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
936                         av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
937                     }
938                 }
939                 goto resync;
940             }
941         }
942     }
943
944     return AVERROR_EOF;
945 }
946
947 /* XXX: We make the implicit supposition that the positions are sorted
948    for each stream. */
949 static int avi_read_idx1(AVFormatContext *s, int size)
950 {
951     AVIContext *avi = s->priv_data;
952     ByteIOContext *pb = s->pb;
953     int nb_index_entries, i;
954     AVStream *st;
955     AVIStream *ast;
956     unsigned int index, tag, flags, pos, len;
957     unsigned last_pos= -1;
958
959     nb_index_entries = size / 16;
960     if (nb_index_entries <= 0)
961         return -1;
962
963     /* Read the entries and sort them in each stream component. */
964     for(i = 0; i < nb_index_entries; i++) {
965         tag = get_le32(pb);
966         flags = get_le32(pb);
967         pos = get_le32(pb);
968         len = get_le32(pb);
969 #if defined(DEBUG_SEEK)
970         av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
971                i, tag, flags, pos, len);
972 #endif
973         if(i==0 && pos > avi->movi_list)
974             avi->movi_list= 0; //FIXME better check
975         pos += avi->movi_list;
976
977         index = ((tag & 0xff) - '0') * 10;
978         index += ((tag >> 8) & 0xff) - '0';
979         if (index >= s->nb_streams)
980             continue;
981         st = s->streams[index];
982         ast = st->priv_data;
983
984 #if defined(DEBUG_SEEK)
985         av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
986 #endif
987         if(url_feof(pb))
988             return -1;
989
990         if(last_pos == pos)
991             avi->non_interleaved= 1;
992         else if(len || !ast->sample_size)
993             av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
994         if(ast->sample_size)
995             ast->cum_len += len;
996         else
997             ast->cum_len ++;
998         last_pos= pos;
999     }
1000     return 0;
1001 }
1002
1003 static int guess_ni_flag(AVFormatContext *s){
1004     int i;
1005     int64_t last_start=0;
1006     int64_t first_end= INT64_MAX;
1007     int64_t oldpos= url_ftell(s->pb);
1008
1009     for(i=0; i<s->nb_streams; i++){
1010         AVStream *st = s->streams[i];
1011         int n= st->nb_index_entries;
1012         unsigned int size;
1013
1014         if(n <= 0)
1015             continue;
1016
1017         if(n >= 2){
1018             int64_t pos= st->index_entries[0].pos;
1019             url_fseek(s->pb, pos + 4, SEEK_SET);
1020             size= get_le32(s->pb);
1021             if(pos + size > st->index_entries[1].pos)
1022                 last_start= INT64_MAX;
1023         }
1024
1025         if(st->index_entries[0].pos > last_start)
1026             last_start= st->index_entries[0].pos;
1027         if(st->index_entries[n-1].pos < first_end)
1028             first_end= st->index_entries[n-1].pos;
1029     }
1030     url_fseek(s->pb, oldpos, SEEK_SET);
1031     return last_start > first_end;
1032 }
1033
1034 static int avi_load_index(AVFormatContext *s)
1035 {
1036     AVIContext *avi = s->priv_data;
1037     ByteIOContext *pb = s->pb;
1038     uint32_t tag, size;
1039     int64_t pos= url_ftell(pb);
1040     int ret = -1;
1041
1042     if (url_fseek(pb, avi->movi_end, SEEK_SET) < 0)
1043         goto the_end; // maybe truncated file
1044 #ifdef DEBUG_SEEK
1045     printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
1046 #endif
1047     for(;;) {
1048         if (url_feof(pb))
1049             break;
1050         tag = get_le32(pb);
1051         size = get_le32(pb);
1052 #ifdef DEBUG_SEEK
1053         printf("tag=%c%c%c%c size=0x%x\n",
1054                tag & 0xff,
1055                (tag >> 8) & 0xff,
1056                (tag >> 16) & 0xff,
1057                (tag >> 24) & 0xff,
1058                size);
1059 #endif
1060         switch(tag) {
1061         case MKTAG('i', 'd', 'x', '1'):
1062             if (avi_read_idx1(s, size) < 0)
1063                 goto skip;
1064             ret = 0;
1065                 goto the_end;
1066             break;
1067         default:
1068         skip:
1069             size += (size & 1);
1070             if (url_fseek(pb, size, SEEK_CUR) < 0)
1071                 goto the_end; // something is wrong here
1072             break;
1073         }
1074     }
1075  the_end:
1076     url_fseek(pb, pos, SEEK_SET);
1077     return ret;
1078 }
1079
1080 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1081 {
1082     AVIContext *avi = s->priv_data;
1083     AVStream *st;
1084     int i, index;
1085     int64_t pos;
1086     AVIStream *ast;
1087
1088     if (!avi->index_loaded) {
1089         /* we only load the index on demand */
1090         avi_load_index(s);
1091         avi->index_loaded = 1;
1092     }
1093     assert(stream_index>= 0);
1094
1095     st = s->streams[stream_index];
1096     ast= st->priv_data;
1097     index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
1098     if(index<0)
1099         return -1;
1100
1101     /* find the position */
1102     pos = st->index_entries[index].pos;
1103     timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1104
1105 //    av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1106
1107     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1108         /* One and only one real stream for DV in AVI, and it has video  */
1109         /* offsets. Calling with other stream indexes should have failed */
1110         /* the av_index_search_timestamp call above.                     */
1111         assert(stream_index == 0);
1112
1113         /* Feed the DV video stream version of the timestamp to the */
1114         /* DV demux so it can synthesize correct timestamps.        */
1115         dv_offset_reset(avi->dv_demux, timestamp);
1116
1117         url_fseek(s->pb, pos, SEEK_SET);
1118         avi->stream_index= -1;
1119         return 0;
1120     }
1121
1122     for(i = 0; i < s->nb_streams; i++) {
1123         AVStream *st2 = s->streams[i];
1124         AVIStream *ast2 = st2->priv_data;
1125
1126         ast2->packet_size=
1127         ast2->remaining= 0;
1128
1129         if (st2->nb_index_entries <= 0)
1130             continue;
1131
1132 //        assert(st2->codec->block_align);
1133         assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1134         index = av_index_search_timestamp(
1135                 st2,
1136                 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1137                 flags | AVSEEK_FLAG_BACKWARD);
1138         if(index<0)
1139             index=0;
1140
1141         if(!avi->non_interleaved){
1142             while(index>0 && st2->index_entries[index].pos > pos)
1143                 index--;
1144             while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
1145                 index++;
1146         }
1147
1148 //        av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
1149         /* extract the current frame number */
1150         ast2->frame_offset = st2->index_entries[index].timestamp;
1151     }
1152
1153     /* do the seek */
1154     url_fseek(s->pb, pos, SEEK_SET);
1155     avi->stream_index= -1;
1156     return 0;
1157 }
1158
1159 static int avi_read_close(AVFormatContext *s)
1160 {
1161     int i;
1162     AVIContext *avi = s->priv_data;
1163
1164     for(i=0;i<s->nb_streams;i++) {
1165         AVStream *st = s->streams[i];
1166         av_free(st->codec->palctrl);
1167     }
1168
1169     if (avi->dv_demux)
1170         av_free(avi->dv_demux);
1171
1172     return 0;
1173 }
1174
1175 static int avi_probe(AVProbeData *p)
1176 {
1177     int i;
1178
1179     /* check file header */
1180     for(i=0; avi_headers[i][0]; i++)
1181         if(!memcmp(p->buf  , avi_headers[i]  , 4) &&
1182            !memcmp(p->buf+8, avi_headers[i]+4, 4))
1183             return AVPROBE_SCORE_MAX;
1184
1185     return 0;
1186 }
1187
1188 AVInputFormat avi_demuxer = {
1189     "avi",
1190     NULL_IF_CONFIG_SMALL("AVI format"),
1191     sizeof(AVIContext),
1192     avi_probe,
1193     avi_read_header,
1194     avi_read_packet,
1195     avi_read_close,
1196     avi_read_seek,
1197     .metadata_conv = ff_avi_metadata_conv,
1198 };