1/*
2 * AVI demuxer
3 * Copyright (c) 2001 Fabrice Bellard
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include "libavutil/intreadwrite.h"
23#include "libavutil/bswap.h"
24#include "avformat.h"
25#include "avi.h"
26#include "dv.h"
27#include "riff.h"
28
29#undef NDEBUG
30#include <assert.h>
31
32//#define DEBUG
33//#define DEBUG_SEEK
34
35typedef 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
53typedef 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
66static 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
75static int avi_load_index(AVFormatContext *s);
76static int guess_ni_flag(AVFormatContext *s);
77
78#ifdef DEBUG
79static void print_tag(const char *str, unsigned int tag, int size)
80{
81    printf("%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
90static 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
114static 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)
174                av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), 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
204static 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/ast->sample_size, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
226        }
227    }
228}
229
230static int avi_read_tag(AVFormatContext *s, const char *key, unsigned int size)
231{
232    ByteIOContext *pb = s->pb;
233    uint8_t value[1024];
234
235    int64_t i = url_ftell(pb);
236    size += (size & 1);
237    get_strz(pb, value, sizeof(value));
238    url_fseek(pb, i+size, SEEK_SET);
239
240    return av_metadata_set(&s->metadata, key, value);
241}
242
243static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
244{
245    AVIContext *avi = s->priv_data;
246    ByteIOContext *pb = s->pb;
247    unsigned int tag, tag1, handler;
248    int codec_type, stream_index, frame_period, bit_rate;
249    unsigned int size, nb_frames;
250    int i;
251    AVStream *st;
252    AVIStream *ast = NULL;
253    int avih_width=0, avih_height=0;
254    int amv_file_format=0;
255
256    avi->stream_index= -1;
257
258    if (get_riff(s, pb) < 0)
259        return -1;
260
261    avi->fsize = url_fsize(pb);
262    if(avi->fsize<=0)
263        avi->fsize= avi->riff_end;
264
265    /* first list tag */
266    stream_index = -1;
267    codec_type = -1;
268    frame_period = 0;
269    for(;;) {
270        if (url_feof(pb))
271            goto fail;
272        tag = get_le32(pb);
273        size = get_le32(pb);
274#ifdef DEBUG
275        print_tag("tag", tag, size);
276#endif
277
278        switch(tag) {
279        case MKTAG('L', 'I', 'S', 'T'):
280            /* Ignored, except at start of video packets. */
281            tag1 = get_le32(pb);
282#ifdef DEBUG
283            print_tag("list", tag1, 0);
284#endif
285            if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
286                avi->movi_list = url_ftell(pb) - 4;
287                if(size) avi->movi_end = avi->movi_list + size + (size & 1);
288                else     avi->movi_end = url_fsize(pb);
289#ifdef DEBUG
290                printf("movi end=%"PRIx64"\n", avi->movi_end);
291#endif
292                goto end_of_header;
293            }
294            break;
295        case MKTAG('d', 'm', 'l', 'h'):
296            avi->is_odml = 1;
297            url_fskip(pb, size + (size & 1));
298            break;
299        case MKTAG('a', 'm', 'v', 'h'):
300            amv_file_format=1;
301        case MKTAG('a', 'v', 'i', 'h'):
302            /* AVI header */
303            /* using frame_period is bad idea */
304            frame_period = get_le32(pb);
305            bit_rate = get_le32(pb) * 8;
306            get_le32(pb);
307            avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
308
309            url_fskip(pb, 2 * 4);
310            get_le32(pb);
311            get_le32(pb);
312            avih_width=get_le32(pb);
313            avih_height=get_le32(pb);
314
315            url_fskip(pb, size - 10 * 4);
316            break;
317        case MKTAG('s', 't', 'r', 'h'):
318            /* stream header */
319
320            tag1 = get_le32(pb);
321            handler = get_le32(pb); /* codec tag */
322
323            if(tag1 == MKTAG('p', 'a', 'd', 's')){
324                url_fskip(pb, size - 8);
325                break;
326            }else{
327                stream_index++;
328                st = av_new_stream(s, stream_index);
329                if (!st)
330                    goto fail;
331
332                ast = av_mallocz(sizeof(AVIStream));
333                if (!ast)
334                    goto fail;
335                st->priv_data = ast;
336            }
337            if(amv_file_format)
338                tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
339
340#ifdef DEBUG
341            print_tag("strh", tag1, -1);
342#endif
343            if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
344                int64_t dv_dur;
345
346                /*
347                 * After some consideration -- I don't think we
348                 * have to support anything but DV in type1 AVIs.
349                 */
350                if (s->nb_streams != 1)
351                    goto fail;
352
353                if (handler != MKTAG('d', 'v', 's', 'd') &&
354                    handler != MKTAG('d', 'v', 'h', 'd') &&
355                    handler != MKTAG('d', 'v', 's', 'l'))
356                   goto fail;
357
358                ast = s->streams[0]->priv_data;
359                av_freep(&s->streams[0]->codec->extradata);
360                av_freep(&s->streams[0]);
361                s->nb_streams = 0;
362                if (CONFIG_DV_DEMUXER) {
363                    avi->dv_demux = dv_init_demux(s);
364                    if (!avi->dv_demux)
365                        goto fail;
366                }
367                s->streams[0]->priv_data = ast;
368                url_fskip(pb, 3 * 4);
369                ast->scale = get_le32(pb);
370                ast->rate = get_le32(pb);
371                url_fskip(pb, 4);  /* start time */
372
373                dv_dur = get_le32(pb);
374                if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
375                    dv_dur *= AV_TIME_BASE;
376                    s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
377                }
378                /*
379                 * else, leave duration alone; timing estimation in utils.c
380                 *      will make a guess based on bitrate.
381                 */
382
383                stream_index = s->nb_streams - 1;
384                url_fskip(pb, size - 9*4);
385                break;
386            }
387
388            assert(stream_index < s->nb_streams);
389            st->codec->stream_codec_tag= handler;
390
391            get_le32(pb); /* flags */
392            get_le16(pb); /* priority */
393            get_le16(pb); /* language */
394            get_le32(pb); /* initial frame */
395            ast->scale = get_le32(pb);
396            ast->rate = get_le32(pb);
397            if(!(ast->scale && ast->rate)){
398                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);
399                if(frame_period){
400                    ast->rate = 1000000;
401                    ast->scale = frame_period;
402                }else{
403                    ast->rate = 25;
404                    ast->scale = 1;
405                }
406            }
407            av_set_pts_info(st, 64, ast->scale, ast->rate);
408
409            ast->cum_len=get_le32(pb); /* start */
410            nb_frames = get_le32(pb);
411
412            st->start_time = 0;
413            st->duration = nb_frames;
414            get_le32(pb); /* buffer size */
415            get_le32(pb); /* quality */
416            ast->sample_size = get_le32(pb); /* sample ssize */
417            ast->cum_len *= FFMAX(1, ast->sample_size);
418//            av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
419
420            switch(tag1) {
421            case MKTAG('v', 'i', 'd', 's'):
422                codec_type = CODEC_TYPE_VIDEO;
423
424                ast->sample_size = 0;
425                break;
426            case MKTAG('a', 'u', 'd', 's'):
427                codec_type = CODEC_TYPE_AUDIO;
428                break;
429            case MKTAG('t', 'x', 't', 's'):
430                //FIXME
431                codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ?  FIXME
432                break;
433            case MKTAG('d', 'a', 't', 's'):
434                codec_type = CODEC_TYPE_DATA;
435                break;
436            default:
437                av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
438                goto fail;
439            }
440            ast->frame_offset= ast->cum_len;
441            url_fskip(pb, size - 12 * 4);
442            break;
443        case MKTAG('s', 't', 'r', 'f'):
444            /* stream header */
445            if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
446                url_fskip(pb, size);
447            } else {
448                st = s->streams[stream_index];
449                switch(codec_type) {
450                case CODEC_TYPE_VIDEO:
451                    if(amv_file_format){
452                        st->codec->width=avih_width;
453                        st->codec->height=avih_height;
454                        st->codec->codec_type = CODEC_TYPE_VIDEO;
455                        st->codec->codec_id = CODEC_ID_AMV;
456                        url_fskip(pb, size);
457                        break;
458                    }
459                    get_le32(pb); /* size */
460                    st->codec->width = get_le32(pb);
461                    st->codec->height = (int32_t)get_le32(pb);
462                    get_le16(pb); /* panes */
463                    st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
464                    tag1 = get_le32(pb);
465                    get_le32(pb); /* ImageSize */
466                    get_le32(pb); /* XPelsPerMeter */
467                    get_le32(pb); /* YPelsPerMeter */
468                    get_le32(pb); /* ClrUsed */
469                    get_le32(pb); /* ClrImportant */
470
471                    if (tag1 == MKTAG('D', 'X', 'S', 'B')) {
472                        st->codec->codec_type = CODEC_TYPE_SUBTITLE;
473                        st->codec->codec_tag = tag1;
474                        st->codec->codec_id = CODEC_ID_XSUB;
475                        break;
476                    }
477
478                    if(size > 10*4 && size<(1<<30)){
479                        st->codec->extradata_size= size - 10*4;
480                        st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
481                        get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
482                    }
483
484                    if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
485                        get_byte(pb);
486
487                    /* Extract palette from extradata if bpp <= 8. */
488                    /* This code assumes that extradata contains only palette. */
489                    /* This is true for all paletted codecs implemented in FFmpeg. */
490                    if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
491                        st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
492#ifdef WORDS_BIGENDIAN
493                        for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
494                            st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
495#else
496                        memcpy(st->codec->palctrl->palette, st->codec->extradata,
497                               FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
498#endif
499                        st->codec->palctrl->palette_changed = 1;
500                    }
501
502#ifdef DEBUG
503                    print_tag("video", tag1, 0);
504#endif
505                    st->codec->codec_type = CODEC_TYPE_VIDEO;
506                    st->codec->codec_tag = tag1;
507                    st->codec->codec_id = codec_get_id(codec_bmp_tags, tag1);
508                    st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
509
510                    if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
511                        st->codec->extradata_size+= 9;
512                        st->codec->extradata= av_realloc(st->codec->extradata, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
513                        if(st->codec->extradata)
514                            memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
515                    }
516                    st->codec->height= FFABS(st->codec->height);
517
518//                    url_fskip(pb, size - 5 * 4);
519                    break;
520                case CODEC_TYPE_AUDIO:
521                    get_wav_header(pb, st->codec, size);
522                    if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
523                        av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
524                        ast->sample_size= st->codec->block_align;
525                    }
526                    if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
527                        url_fskip(pb, 1);
528                    /* Force parsing as several audio frames can be in
529                     * one packet and timestamps refer to packet start. */
530                    st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
531                    /* ADTS header is in extradata, AAC without header must be
532                     * stored as exact frames. Parser not needed and it will
533                     * fail. */
534                    if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
535                        st->need_parsing = AVSTREAM_PARSE_NONE;
536                    /* AVI files with Xan DPCM audio (wrongly) declare PCM
537                     * audio in the header but have Axan as stream_code_tag. */
538                    if (st->codec->stream_codec_tag == AV_RL32("Axan")){
539                        st->codec->codec_id  = CODEC_ID_XAN_DPCM;
540                        st->codec->codec_tag = 0;
541                    }
542                    if (amv_file_format)
543                        st->codec->codec_id  = CODEC_ID_ADPCM_IMA_AMV;
544                    break;
545                default:
546                    st->codec->codec_type = CODEC_TYPE_DATA;
547                    st->codec->codec_id= CODEC_ID_NONE;
548                    st->codec->codec_tag= 0;
549                    url_fskip(pb, size);
550                    break;
551                }
552            }
553            break;
554        case MKTAG('i', 'n', 'd', 'x'):
555            i= url_ftell(pb);
556            if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
557                read_braindead_odml_indx(s, 0);
558            }
559            url_fseek(pb, i+size, SEEK_SET);
560            break;
561        case MKTAG('v', 'p', 'r', 'p'):
562            if(stream_index < (unsigned)s->nb_streams && size > 9*4){
563                AVRational active, active_aspect;
564
565                st = s->streams[stream_index];
566                get_le32(pb);
567                get_le32(pb);
568                get_le32(pb);
569                get_le32(pb);
570                get_le32(pb);
571
572                active_aspect.den= get_le16(pb);
573                active_aspect.num= get_le16(pb);
574                active.num       = get_le32(pb);
575                active.den       = get_le32(pb);
576                get_le32(pb); //nbFieldsPerFrame
577
578                if(active_aspect.num && active_aspect.den && active.num && active.den){
579                    st->sample_aspect_ratio= av_div_q(active_aspect, active);
580//av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
581                }
582                size -= 9*4;
583            }
584            url_fseek(pb, size, SEEK_CUR);
585            break;
586        case MKTAG('I', 'N', 'A', 'M'):
587            avi_read_tag(s, "Title", size);
588            break;
589        case MKTAG('I', 'A', 'R', 'T'):
590            avi_read_tag(s, "Artist", size);
591            break;
592        case MKTAG('I', 'C', 'O', 'P'):
593            avi_read_tag(s, "Copyright", size);
594            break;
595        case MKTAG('I', 'C', 'M', 'T'):
596            avi_read_tag(s, "Comment", size);
597            break;
598        case MKTAG('I', 'G', 'N', 'R'):
599            avi_read_tag(s, "Genre", size);
600            break;
601        case MKTAG('I', 'P', 'R', 'D'):
602            avi_read_tag(s, "Album", size);
603            break;
604        case MKTAG('I', 'P', 'R', 'T'):
605            avi_read_tag(s, "Track", size);
606            break;
607        default:
608            if(size > 1000000){
609                av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
610                                        "I will ignore it and try to continue anyway.\n");
611                avi->movi_list = url_ftell(pb) - 4;
612                avi->movi_end  = url_fsize(pb);
613                goto end_of_header;
614            }
615            /* skip tag */
616            size += (size & 1);
617            url_fskip(pb, size);
618            break;
619        }
620    }
621 end_of_header:
622    /* check stream number */
623    if (stream_index != s->nb_streams - 1) {
624    fail:
625        return -1;
626    }
627
628    if(!avi->index_loaded && !url_is_streamed(pb))
629        avi_load_index(s);
630    avi->index_loaded = 1;
631    avi->non_interleaved |= guess_ni_flag(s);
632    if(avi->non_interleaved) {
633        av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
634        clean_index(s);
635    }
636
637    return 0;
638}
639
640static int get_stream_idx(int *d){
641    if(    d[0] >= '0' && d[0] <= '9'
642        && d[1] >= '0' && d[1] <= '9'){
643        return (d[0] - '0') * 10 + (d[1] - '0');
644    }else{
645        return 100; //invalid stream ID
646    }
647}
648
649static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
650{
651    AVIContext *avi = s->priv_data;
652    ByteIOContext *pb = s->pb;
653    int n, d[8];
654    unsigned int size;
655    int64_t i, sync;
656    void* dstr;
657
658    if (CONFIG_DV_DEMUXER && avi->dv_demux) {
659        int size = dv_get_packet(avi->dv_demux, pkt);
660        if (size >= 0)
661            return size;
662    }
663
664    if(avi->non_interleaved){
665        int best_stream_index = 0;
666        AVStream *best_st= NULL;
667        AVIStream *best_ast;
668        int64_t best_ts= INT64_MAX;
669        int i;
670
671        for(i=0; i<s->nb_streams; i++){
672            AVStream *st = s->streams[i];
673            AVIStream *ast = st->priv_data;
674            int64_t ts= ast->frame_offset;
675
676            if(ast->sample_size)
677                ts /= ast->sample_size;
678            ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
679
680//            av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
681            if(ts < best_ts && st->nb_index_entries){
682                best_ts= ts;
683                best_st= st;
684                best_stream_index= i;
685            }
686        }
687        if(!best_st)
688            return -1;
689
690        best_ast = best_st->priv_data;
691        best_ts= av_rescale(best_ts, best_st->time_base.den, AV_TIME_BASE * (int64_t)best_st->time_base.num); //FIXME a little ugly
692        if(best_ast->remaining)
693            i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
694        else{
695            i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
696            if(i>=0)
697                best_ast->frame_offset= best_st->index_entries[i].timestamp
698                                      * FFMAX(1, best_ast->sample_size);
699        }
700
701//        av_log(s, AV_LOG_DEBUG, "%d\n", i);
702        if(i>=0){
703            int64_t pos= best_st->index_entries[i].pos;
704            pos += best_ast->packet_size - best_ast->remaining;
705            url_fseek(s->pb, pos + 8, SEEK_SET);
706//        av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
707
708            assert(best_ast->remaining <= best_ast->packet_size);
709
710            avi->stream_index= best_stream_index;
711            if(!best_ast->remaining)
712                best_ast->packet_size=
713                best_ast->remaining= best_st->index_entries[i].size;
714        }
715    }
716
717resync:
718    if(avi->stream_index >= 0){
719        AVStream *st= s->streams[ avi->stream_index ];
720        AVIStream *ast= st->priv_data;
721        int size, err;
722
723        if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
724            size= INT_MAX;
725        else if(ast->sample_size < 32)
726            size= 64*ast->sample_size;
727        else
728            size= ast->sample_size;
729
730        if(size > ast->remaining)
731            size= ast->remaining;
732        avi->last_pkt_pos= url_ftell(pb);
733        err= av_get_packet(pb, pkt, size);
734        if(err<0)
735            return err;
736
737        if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
738            void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
739            if(ptr){
740            ast->has_pal=0;
741            pkt->size += 4*256;
742            pkt->data= ptr;
743                memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
744            }else
745                av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
746        }
747
748        if (CONFIG_DV_DEMUXER && avi->dv_demux) {
749            dstr = pkt->destruct;
750            size = dv_produce_packet(avi->dv_demux, pkt,
751                                    pkt->data, pkt->size);
752            pkt->destruct = dstr;
753            pkt->flags |= PKT_FLAG_KEY;
754        } else {
755            /* XXX: How to handle B-frames in AVI? */
756            pkt->dts = ast->frame_offset;
757//                pkt->dts += ast->start;
758            if(ast->sample_size)
759                pkt->dts /= ast->sample_size;
760//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);
761            pkt->stream_index = avi->stream_index;
762
763            if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
764                AVIndexEntry *e;
765                int index;
766                assert(st->index_entries);
767
768                index= av_index_search_timestamp(st, pkt->dts, 0);
769                e= &st->index_entries[index];
770
771                if(index >= 0 && e->timestamp == ast->frame_offset){
772                    if (e->flags & AVINDEX_KEYFRAME)
773                        pkt->flags |= PKT_FLAG_KEY;
774                }
775            } else {
776                pkt->flags |= PKT_FLAG_KEY;
777            }
778            if(ast->sample_size)
779                ast->frame_offset += pkt->size;
780            else
781                ast->frame_offset++;
782        }
783        ast->remaining -= size;
784        if(!ast->remaining){
785            avi->stream_index= -1;
786            ast->packet_size= 0;
787        }
788
789        return size;
790    }
791
792    memset(d, -1, sizeof(int)*8);
793    for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
794        int j;
795
796        for(j=0; j<7; j++)
797            d[j]= d[j+1];
798        d[7]= get_byte(pb);
799
800        size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
801
802        n= get_stream_idx(d+2);
803//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);
804        if(i + (uint64_t)size > avi->fsize || d[0]<0)
805            continue;
806
807        //parse ix##
808        if(  (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
809        //parse JUNK
810           ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
811           ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
812            url_fskip(pb, size);
813//av_log(s, AV_LOG_DEBUG, "SKIP\n");
814            goto resync;
815        }
816
817        n= get_stream_idx(d);
818
819        if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
820            continue;
821
822        //parse ##dc/##wb
823        if(n < s->nb_streams){
824            AVStream *st;
825            AVIStream *ast;
826            st = s->streams[n];
827            ast = st->priv_data;
828
829            if(s->nb_streams>=2){
830                AVStream *st1  = s->streams[1];
831                AVIStream *ast1= st1->priv_data;
832                //workaround for broken small-file-bug402.avi
833                if(   d[2] == 'w' && d[3] == 'b'
834                   && n==0
835                   && st ->codec->codec_type == CODEC_TYPE_VIDEO
836                   && st1->codec->codec_type == CODEC_TYPE_AUDIO
837                   && ast->prefix == 'd'*256+'c'
838                   && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
839                  ){
840                    n=1;
841                    st = st1;
842                    ast = ast1;
843                    av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
844                }
845            }
846
847
848            if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
849               /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
850               || st->discard >= AVDISCARD_ALL){
851                if(ast->sample_size) ast->frame_offset += pkt->size;
852                else                 ast->frame_offset++;
853                url_fskip(pb, size);
854                goto resync;
855            }
856
857            if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
858                int k = get_byte(pb);
859                int last = (k + get_byte(pb) - 1) & 0xFF;
860
861                get_le16(pb); //flags
862
863                for (; k <= last; k++)
864                    ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
865                ast->has_pal= 1;
866                goto resync;
867            } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
868                         d[2]*256+d[3] == ast->prefix /*||
869                         (d[2] == 'd' && d[3] == 'c') ||
870                         (d[2] == 'w' && d[3] == 'b')*/) {
871
872//av_log(s, AV_LOG_DEBUG, "OK\n");
873                if(d[2]*256+d[3] == ast->prefix)
874                    ast->prefix_count++;
875                else{
876                    ast->prefix= d[2]*256+d[3];
877                    ast->prefix_count= 0;
878                }
879
880                avi->stream_index= n;
881                ast->packet_size= size + 8;
882                ast->remaining= size;
883
884                {
885                    uint64_t pos= url_ftell(pb) - 8;
886                    if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
887                        av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
888                    }
889                }
890                goto resync;
891            }
892        }
893    }
894
895    return AVERROR_EOF;
896}
897
898/* XXX: We make the implicit supposition that the positions are sorted
899   for each stream. */
900static int avi_read_idx1(AVFormatContext *s, int size)
901{
902    AVIContext *avi = s->priv_data;
903    ByteIOContext *pb = s->pb;
904    int nb_index_entries, i;
905    AVStream *st;
906    AVIStream *ast;
907    unsigned int index, tag, flags, pos, len;
908    unsigned last_pos= -1;
909
910    nb_index_entries = size / 16;
911    if (nb_index_entries <= 0)
912        return -1;
913
914    /* Read the entries and sort them in each stream component. */
915    for(i = 0; i < nb_index_entries; i++) {
916        tag = get_le32(pb);
917        flags = get_le32(pb);
918        pos = get_le32(pb);
919        len = get_le32(pb);
920#if defined(DEBUG_SEEK)
921        av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
922               i, tag, flags, pos, len);
923#endif
924        if(i==0 && pos > avi->movi_list)
925            avi->movi_list= 0; //FIXME better check
926        pos += avi->movi_list;
927
928        index = ((tag & 0xff) - '0') * 10;
929        index += ((tag >> 8) & 0xff) - '0';
930        if (index >= s->nb_streams)
931            continue;
932        st = s->streams[index];
933        ast = st->priv_data;
934
935#if defined(DEBUG_SEEK)
936        av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
937#endif
938        if(url_feof(pb))
939            return -1;
940
941        if(last_pos == pos)
942            avi->non_interleaved= 1;
943        else
944            av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
945        if(ast->sample_size)
946            ast->cum_len += len;
947        else
948            ast->cum_len ++;
949        last_pos= pos;
950    }
951    return 0;
952}
953
954static int guess_ni_flag(AVFormatContext *s){
955    int i;
956    int64_t last_start=0;
957    int64_t first_end= INT64_MAX;
958
959    for(i=0; i<s->nb_streams; i++){
960        AVStream *st = s->streams[i];
961        int n= st->nb_index_entries;
962
963        if(n <= 0)
964            continue;
965
966        if(st->index_entries[0].pos > last_start)
967            last_start= st->index_entries[0].pos;
968        if(st->index_entries[n-1].pos < first_end)
969            first_end= st->index_entries[n-1].pos;
970    }
971    return last_start > first_end;
972}
973
974static int avi_load_index(AVFormatContext *s)
975{
976    AVIContext *avi = s->priv_data;
977    ByteIOContext *pb = s->pb;
978    uint32_t tag, size;
979    int64_t pos= url_ftell(pb);
980
981    url_fseek(pb, avi->movi_end, SEEK_SET);
982#ifdef DEBUG_SEEK
983    printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
984#endif
985    for(;;) {
986        if (url_feof(pb))
987            break;
988        tag = get_le32(pb);
989        size = get_le32(pb);
990#ifdef DEBUG_SEEK
991        printf("tag=%c%c%c%c size=0x%x\n",
992               tag & 0xff,
993               (tag >> 8) & 0xff,
994               (tag >> 16) & 0xff,
995               (tag >> 24) & 0xff,
996               size);
997#endif
998        switch(tag) {
999        case MKTAG('i', 'd', 'x', '1'):
1000            if (avi_read_idx1(s, size) < 0)
1001                goto skip;
1002            else
1003                goto the_end;
1004            break;
1005        default:
1006        skip:
1007            size += (size & 1);
1008            url_fskip(pb, size);
1009            break;
1010        }
1011    }
1012 the_end:
1013    url_fseek(pb, pos, SEEK_SET);
1014    return 0;
1015}
1016
1017static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1018{
1019    AVIContext *avi = s->priv_data;
1020    AVStream *st;
1021    int i, index;
1022    int64_t pos;
1023
1024    if (!avi->index_loaded) {
1025        /* we only load the index on demand */
1026        avi_load_index(s);
1027        avi->index_loaded = 1;
1028    }
1029    assert(stream_index>= 0);
1030
1031    st = s->streams[stream_index];
1032    index= av_index_search_timestamp(st, timestamp, flags);
1033    if(index<0)
1034        return -1;
1035
1036    /* find the position */
1037    pos = st->index_entries[index].pos;
1038    timestamp = st->index_entries[index].timestamp;
1039
1040//    av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1041
1042    if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1043        /* One and only one real stream for DV in AVI, and it has video  */
1044        /* offsets. Calling with other stream indexes should have failed */
1045        /* the av_index_search_timestamp call above.                     */
1046        assert(stream_index == 0);
1047
1048        /* Feed the DV video stream version of the timestamp to the */
1049        /* DV demux so it can synthesize correct timestamps.        */
1050        dv_offset_reset(avi->dv_demux, timestamp);
1051
1052        url_fseek(s->pb, pos, SEEK_SET);
1053        avi->stream_index= -1;
1054        return 0;
1055    }
1056
1057    for(i = 0; i < s->nb_streams; i++) {
1058        AVStream *st2 = s->streams[i];
1059        AVIStream *ast2 = st2->priv_data;
1060
1061        ast2->packet_size=
1062        ast2->remaining= 0;
1063
1064        if (st2->nb_index_entries <= 0)
1065            continue;
1066
1067//        assert(st2->codec->block_align);
1068        assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1069        index = av_index_search_timestamp(
1070                st2,
1071                av_rescale(timestamp, st2->time_base.den*(int64_t)st->time_base.num, st->time_base.den * (int64_t)st2->time_base.num),
1072                flags | AVSEEK_FLAG_BACKWARD);
1073        if(index<0)
1074            index=0;
1075
1076        if(!avi->non_interleaved){
1077            while(index>0 && st2->index_entries[index].pos > pos)
1078                index--;
1079            while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
1080                index++;
1081        }
1082
1083//        av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
1084        /* extract the current frame number */
1085        ast2->frame_offset = st2->index_entries[index].timestamp;
1086        if(ast2->sample_size)
1087            ast2->frame_offset *=ast2->sample_size;
1088    }
1089
1090    /* do the seek */
1091    url_fseek(s->pb, pos, SEEK_SET);
1092    avi->stream_index= -1;
1093    return 0;
1094}
1095
1096static int avi_read_close(AVFormatContext *s)
1097{
1098    int i;
1099    AVIContext *avi = s->priv_data;
1100
1101    for(i=0;i<s->nb_streams;i++) {
1102        AVStream *st = s->streams[i];
1103        av_free(st->codec->palctrl);
1104    }
1105
1106    if (avi->dv_demux)
1107        av_free(avi->dv_demux);
1108
1109    return 0;
1110}
1111
1112static int avi_probe(AVProbeData *p)
1113{
1114    int i;
1115
1116    /* check file header */
1117    for(i=0; avi_headers[i][0]; i++)
1118        if(!memcmp(p->buf  , avi_headers[i]  , 4) &&
1119           !memcmp(p->buf+8, avi_headers[i]+4, 4))
1120            return AVPROBE_SCORE_MAX;
1121
1122    return 0;
1123}
1124
1125AVInputFormat avi_demuxer = {
1126    "avi",
1127    NULL_IF_CONFIG_SMALL("AVI format"),
1128    sizeof(AVIContext),
1129    avi_probe,
1130    avi_read_header,
1131    avi_read_packet,
1132    avi_read_close,
1133    avi_read_seek,
1134};
1135