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