avidec.c 39.9 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1
/*
2
 * AVI demuxer
Diego Biurrun's avatar
Diego Biurrun committed
3
 * Copyright (c) 2001 Fabrice Bellard
Fabrice Bellard's avatar
Fabrice Bellard committed
4
 *
5 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
Fabrice Bellard's avatar
Fabrice Bellard committed
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Fabrice Bellard's avatar
Fabrice Bellard committed
14 15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
16
 *
Fabrice Bellard's avatar
Fabrice Bellard committed
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
Fabrice Bellard's avatar
Fabrice Bellard committed
20
 */
21

22 23 24
//#define DEBUG
//#define DEBUG_SEEK

25
#include "libavutil/intreadwrite.h"
26
#include "libavutil/bswap.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
27 28
#include "avformat.h"
#include "avi.h"
29
#include "dv.h"
30
#include "riff.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
31

32 33 34
#undef NDEBUG
#include <assert.h>

Fabrice Bellard's avatar
Fabrice Bellard committed
35
typedef struct AVIStream {
36
    int64_t frame_offset; /* current frame (video) or byte (audio) counter
Fabrice Bellard's avatar
Fabrice Bellard committed
37
                         (used to compute the pts) */
38 39 40
    int remaining;
    int packet_size;

Fabrice Bellard's avatar
Fabrice Bellard committed
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 48
    int prefix;                       ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
    int prefix_count;
49 50
    uint32_t pal[256];
    int has_pal;
Fabrice Bellard's avatar
Fabrice Bellard committed
51
} AVIStream;
Fabrice Bellard's avatar
Fabrice Bellard committed
52 53

typedef struct {
54 55
    int64_t  riff_end;
    int64_t  movi_end;
56
    int64_t  fsize;
57
    int64_t movi_list;
58
    int64_t last_pkt_pos;
Fabrice Bellard's avatar
Fabrice Bellard committed
59
    int index_loaded;
60
    int is_odml;
61 62
    int non_interleaved;
    int stream_index;
63
    DVDemuxContext* dv_demux;
64 65
    int odml_depth;
#define MAX_ODML_DEPTH 1000
Fabrice Bellard's avatar
Fabrice Bellard committed
66 67
} AVIContext;

68 69 70 71
static const char avi_headers[][8] = {
    { 'R', 'I', 'F', 'F',    'A', 'V', 'I', ' ' },
    { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 'X' },
    { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 0x19},
72
    { 'O', 'N', '2', ' ',    'O', 'N', '2', 'f' },
73
    { 'R', 'I', 'F', 'F',    'A', 'M', 'V', ' ' },
74 75 76
    { 0 }
};

77
static int avi_load_index(AVFormatContext *s);
Michael Niedermayer's avatar
Michael Niedermayer committed
78
static int guess_ni_flag(AVFormatContext *s);
79

Fabrice Bellard's avatar
Fabrice Bellard committed
80
#ifdef DEBUG
Zdenek Kabelac's avatar
Zdenek Kabelac committed
81
static void print_tag(const char *str, unsigned int tag, int size)
Fabrice Bellard's avatar
Fabrice Bellard committed
82
{
83
    dprintf(NULL, "%s: tag=%c%c%c%c size=0x%x\n",
Fabrice Bellard's avatar
Fabrice Bellard committed
84 85 86 87 88 89 90 91
           str, tag & 0xff,
           (tag >> 8) & 0xff,
           (tag >> 16) & 0xff,
           (tag >> 24) & 0xff,
           size);
}
#endif

92
static int get_riff(AVFormatContext *s, ByteIOContext *pb)
93
{
94
    AVIContext *avi = s->priv_data;
95 96
    char header[8];
    int i;
97

98 99
    /* check RIFF header */
    get_buffer(pb, header, 4);
100 101
    avi->riff_end = get_le32(pb);   /* RIFF chunk size */
    avi->riff_end += url_ftell(pb); /* RIFF chunk end */
102 103 104 105 106 107
    get_buffer(pb, header+4, 4);

    for(i=0; avi_headers[i][0]; i++)
        if(!memcmp(header, avi_headers[i], 8))
            break;
    if(!avi_headers[i][0])
108
        return -1;
109

110
    if(header[7] == 0x19)
111
        av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
112

113 114 115
    return 0;
}

116
static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
117
    AVIContext *avi = s->priv_data;
118
    ByteIOContext *pb = s->pb;
119 120 121 122 123 124 125 126 127 128
    int longs_pre_entry= get_le16(pb);
    int index_sub_type = get_byte(pb);
    int index_type     = get_byte(pb);
    int entries_in_use = get_le32(pb);
    int chunk_id       = get_le32(pb);
    int64_t base       = get_le64(pb);
    int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
    AVStream *st;
    AVIStream *ast;
    int i;
129
    int64_t last_pos= -1;
130
    int64_t filesize= url_fsize(s->pb);
131

132
#ifdef DEBUG_SEEK
133
    av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
134 135
        longs_pre_entry,index_type, entries_in_use, chunk_id, base);
#endif
136

137
    if(stream_id >= s->nb_streams || stream_id < 0)
138 139 140 141 142 143 144 145 146 147 148 149 150 151
        return -1;
    st= s->streams[stream_id];
    ast = st->priv_data;

    if(index_sub_type)
        return -1;

    get_le32(pb);

    if(index_type && longs_pre_entry != 2)
        return -1;
    if(index_type>1)
        return -1;

152 153 154 155 156 157 158 159
    if(filesize > 0 && base >= filesize){
        av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
        if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
            base &= 0xFFFFFFFF;
        else
            return -1;
    }

160 161
    for(i=0; i<entries_in_use; i++){
        if(index_type){
Michael Niedermayer's avatar
Michael Niedermayer committed
162
            int64_t pos= get_le32(pb) + base - 8;
163
            int len    = get_le32(pb);
Michael Niedermayer's avatar
Michael Niedermayer committed
164
            int key= len >= 0;
165 166
            len &= 0x7FFFFFFF;

167
#ifdef DEBUG_SEEK
168
            av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
169
#endif
170 171 172
            if(url_feof(pb))
                return -1;

173 174
            if(last_pos == pos || pos == base - 8)
                avi->non_interleaved= 1;
175
            if(last_pos != pos && (len || !ast->sample_size))
176
                av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
Michael Niedermayer's avatar
Michael Niedermayer committed
177

178
            if(ast->sample_size)
179
                ast->cum_len += len;
180 181
            else
                ast->cum_len ++;
182
            last_pos= pos;
183
        }else{
Måns Rullgård's avatar
Måns Rullgård committed
184 185 186 187 188
            int64_t offset, pos;
            int duration;
            offset = get_le64(pb);
            get_le32(pb);       /* size */
            duration = get_le32(pb);
189 190 191 192

            if(url_feof(pb))
                return -1;

Måns Rullgård's avatar
Måns Rullgård committed
193
            pos = url_ftell(pb);
194

195 196 197 198 199
            if(avi->odml_depth > MAX_ODML_DEPTH){
                av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
                return -1;
            }

200
            url_fseek(pb, offset+8, SEEK_SET);
201
            avi->odml_depth++;
202
            read_braindead_odml_indx(s, frame_num);
203
            avi->odml_depth--;
204 205 206 207 208
            frame_num += duration;

            url_fseek(pb, pos, SEEK_SET);
        }
    }
209
    avi->index_loaded=1;
210 211 212
    return 0;
}

213
static void clean_index(AVFormatContext *s){
214 215
    int i;
    int64_t j;
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

    for(i=0; i<s->nb_streams; i++){
        AVStream *st = s->streams[i];
        AVIStream *ast = st->priv_data;
        int n= st->nb_index_entries;
        int max= ast->sample_size;
        int64_t pos, size, ts;

        if(n != 1 || ast->sample_size==0)
            continue;

        while(max < 1024) max+=max;

        pos= st->index_entries[0].pos;
        size= st->index_entries[0].size;
        ts= st->index_entries[0].timestamp;

        for(j=0; j<size; j+=max){
234
            av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
235 236 237 238
        }
    }
}

239
static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
240
{
Michael Niedermayer's avatar
Michael Niedermayer committed
241
    ByteIOContext *pb = s->pb;
242
    char key[5] = {0}, *value;
Michael Niedermayer's avatar
Michael Niedermayer committed
243

244
    size += (size & 1);
Michael Niedermayer's avatar
Michael Niedermayer committed
245

246 247 248 249 250
    if (size == UINT_MAX)
        return -1;
    value = av_malloc(size+1);
    if (!value)
        return -1;
251 252
    get_buffer(pb, value, size);
    value[size]=0;
253

254 255
    AV_WL32(key, tag);

256 257 258 259
    if(st)
        return av_metadata_set2(&st->metadata, key, value,
                                    AV_METADATA_DONT_STRDUP_VAL);
    else
260 261
    return av_metadata_set2(&s->metadata, key, value,
                                  AV_METADATA_DONT_STRDUP_VAL);
262 263
}

264 265 266 267 268 269 270 271 272
static void avi_read_info(AVFormatContext *s, uint64_t end)
{
    while (url_ftell(s->pb) < end) {
        uint32_t tag  = get_le32(s->pb);
        uint32_t size = get_le32(s->pb);
        avi_read_tag(s, NULL, tag, size);
    }
}

Zdenek Kabelac's avatar
Zdenek Kabelac committed
273
static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
Fabrice Bellard's avatar
Fabrice Bellard committed
274
{
Fabrice Bellard's avatar
Fabrice Bellard committed
275
    AVIContext *avi = s->priv_data;
276
    ByteIOContext *pb = s->pb;
277
    unsigned int tag, tag1, handler;
Michael Niedermayer's avatar
Michael Niedermayer committed
278
    int codec_type, stream_index, frame_period, bit_rate;
Michael Niedermayer's avatar
Michael Niedermayer committed
279
    unsigned int size;
280
    int i;
Fabrice Bellard's avatar
Fabrice Bellard committed
281
    AVStream *st;
Måns Rullgård's avatar
Måns Rullgård committed
282
    AVIStream *ast = NULL;
283 284
    int avih_width=0, avih_height=0;
    int amv_file_format=0;
285
    uint64_t list_end = 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
286

287
    avi->stream_index= -1;
288

289
    if (get_riff(s, pb) < 0)
Fabrice Bellard's avatar
Fabrice Bellard committed
290
        return -1;
Zdenek Kabelac's avatar
Zdenek Kabelac committed
291

292 293
    avi->fsize = url_fsize(pb);
    if(avi->fsize<=0)
294
        avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
295

Fabrice Bellard's avatar
Fabrice Bellard committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    /* first list tag */
    stream_index = -1;
    codec_type = -1;
    frame_period = 0;
    for(;;) {
        if (url_feof(pb))
            goto fail;
        tag = get_le32(pb);
        size = get_le32(pb);
#ifdef DEBUG
        print_tag("tag", tag, size);
#endif

        switch(tag) {
        case MKTAG('L', 'I', 'S', 'T'):
311
            list_end = url_ftell(pb) + size;
Diego Biurrun's avatar
Diego Biurrun committed
312
            /* Ignored, except at start of video packets. */
Fabrice Bellard's avatar
Fabrice Bellard committed
313 314 315 316 317
            tag1 = get_le32(pb);
#ifdef DEBUG
            print_tag("list", tag1, 0);
#endif
            if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
Fabrice Bellard's avatar
Fabrice Bellard committed
318
                avi->movi_list = url_ftell(pb) - 4;
319
                if(size) avi->movi_end = avi->movi_list + size + (size & 1);
320
                else     avi->movi_end = url_fsize(pb);
321
                dprintf(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
Fabrice Bellard's avatar
Fabrice Bellard committed
322 323
                goto end_of_header;
            }
324 325 326
            else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
                avi_read_info(s, list_end);

Fabrice Bellard's avatar
Fabrice Bellard committed
327
            break;
328
        case MKTAG('d', 'm', 'l', 'h'):
329 330 331
            avi->is_odml = 1;
            url_fskip(pb, size + (size & 1));
            break;
332 333
        case MKTAG('a', 'm', 'v', 'h'):
            amv_file_format=1;
Fabrice Bellard's avatar
Fabrice Bellard committed
334
        case MKTAG('a', 'v', 'i', 'h'):
Diego Biurrun's avatar
Diego Biurrun committed
335
            /* AVI header */
Zdenek Kabelac's avatar
Zdenek Kabelac committed
336
            /* using frame_period is bad idea */
Fabrice Bellard's avatar
Fabrice Bellard committed
337 338
            frame_period = get_le32(pb);
            bit_rate = get_le32(pb) * 8;
339 340 341 342
            get_le32(pb);
            avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;

            url_fskip(pb, 2 * 4);
343
            get_le32(pb);
344 345 346
            get_le32(pb);
            avih_width=get_le32(pb);
            avih_height=get_le32(pb);
347

348
            url_fskip(pb, size - 10 * 4);
349 350 351 352 353 354 355 356 357 358 359 360 361
            break;
        case MKTAG('s', 't', 'r', 'h'):
            /* stream header */

            tag1 = get_le32(pb);
            handler = get_le32(pb); /* codec tag */

            if(tag1 == MKTAG('p', 'a', 'd', 's')){
                url_fskip(pb, size - 8);
                break;
            }else{
                stream_index++;
                st = av_new_stream(s, stream_index);
Fabrice Bellard's avatar
Fabrice Bellard committed
362 363
                if (!st)
                    goto fail;
364

Fabrice Bellard's avatar
Fabrice Bellard committed
365 366 367 368
                ast = av_mallocz(sizeof(AVIStream));
                if (!ast)
                    goto fail;
                st->priv_data = ast;
369
            }
370 371
            if(amv_file_format)
                tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
372

373
#ifdef DEBUG
374
            print_tag("strh", tag1, -1);
375
#endif
Michael Niedermayer's avatar
Michael Niedermayer committed
376
            if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
377 378
                int64_t dv_dur;

379
                /*
380
                 * After some consideration -- I don't think we
Diego Biurrun's avatar
Diego Biurrun committed
381
                 * have to support anything but DV in type1 AVIs.
382 383 384 385 386 387 388 389 390 391 392 393 394
                 */
                if (s->nb_streams != 1)
                    goto fail;

                if (handler != MKTAG('d', 'v', 's', 'd') &&
                    handler != MKTAG('d', 'v', 'h', 'd') &&
                    handler != MKTAG('d', 'v', 's', 'l'))
                   goto fail;

                ast = s->streams[0]->priv_data;
                av_freep(&s->streams[0]->codec->extradata);
                av_freep(&s->streams[0]);
                s->nb_streams = 0;
395
                if (CONFIG_DV_DEMUXER) {
396 397 398
                    avi->dv_demux = dv_init_demux(s);
                    if (!avi->dv_demux)
                        goto fail;
399
                }
400 401 402 403
                s->streams[0]->priv_data = ast;
                url_fskip(pb, 3 * 4);
                ast->scale = get_le32(pb);
                ast->rate = get_le32(pb);
404 405 406 407 408 409 410 411 412
                url_fskip(pb, 4);  /* start time */

                dv_dur = get_le32(pb);
                if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
                    dv_dur *= AV_TIME_BASE;
                    s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
                }
                /*
                 * else, leave duration alone; timing estimation in utils.c
Diego Biurrun's avatar
Diego Biurrun committed
413
                 *      will make a guess based on bitrate.
414 415
                 */

416
                stream_index = s->nb_streams - 1;
417
                url_fskip(pb, size - 9*4);
Michael Niedermayer's avatar
Michael Niedermayer committed
418 419
                break;
            }
420

421
            assert(stream_index < s->nb_streams);
422
            st->codec->stream_codec_tag= handler;
423

Michael Niedermayer's avatar
Michael Niedermayer committed
424 425 426 427 428 429
            get_le32(pb); /* flags */
            get_le16(pb); /* priority */
            get_le16(pb); /* language */
            get_le32(pb); /* initial frame */
            ast->scale = get_le32(pb);
            ast->rate = get_le32(pb);
430
            if(!(ast->scale && ast->rate)){
Diego Biurrun's avatar
Diego Biurrun committed
431
                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);
Michael Niedermayer's avatar
indent  
Michael Niedermayer committed
432 433 434 435 436 437 438
                if(frame_period){
                    ast->rate = 1000000;
                    ast->scale = frame_period;
                }else{
                    ast->rate = 25;
                    ast->scale = 1;
                }
439
            }
Michael Niedermayer's avatar
Michael Niedermayer committed
440
            av_set_pts_info(st, 64, ast->scale, ast->rate);
441

Michael Niedermayer's avatar
Michael Niedermayer committed
442
            ast->cum_len=get_le32(pb); /* start */
Michael Niedermayer's avatar
Michael Niedermayer committed
443
            st->nb_frames = get_le32(pb);
444

Michael Niedermayer's avatar
Michael Niedermayer committed
445 446 447 448
            st->start_time = 0;
            get_le32(pb); /* buffer size */
            get_le32(pb); /* quality */
            ast->sample_size = get_le32(pb); /* sample ssize */
449
            ast->cum_len *= FFMAX(1, ast->sample_size);
450
//            av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
451

Michael Niedermayer's avatar
Michael Niedermayer committed
452
            switch(tag1) {
453
            case MKTAG('v', 'i', 'd', 's'):
454
                codec_type = AVMEDIA_TYPE_VIDEO;
455

Michael Niedermayer's avatar
Michael Niedermayer committed
456 457 458
                ast->sample_size = 0;
                break;
            case MKTAG('a', 'u', 'd', 's'):
459
                codec_type = AVMEDIA_TYPE_AUDIO;
460
                break;
461
            case MKTAG('t', 'x', 't', 's'):
462
                //FIXME
463
                codec_type = AVMEDIA_TYPE_DATA; //AVMEDIA_TYPE_SUB ?  FIXME
464
                break;
Florian Echtler's avatar
Florian Echtler committed
465
            case MKTAG('d', 'a', 't', 's'):
466
                codec_type = AVMEDIA_TYPE_DATA;
Florian Echtler's avatar
Florian Echtler committed
467
                break;
468
            default:
Michael Niedermayer's avatar
Michael Niedermayer committed
469
                av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
470
                goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
471
            }
472 473
            if(ast->sample_size == 0)
                st->duration = st->nb_frames;
474
            ast->frame_offset= ast->cum_len;
Michael Niedermayer's avatar
Michael Niedermayer committed
475
            url_fskip(pb, size - 12 * 4);
Fabrice Bellard's avatar
Fabrice Bellard committed
476 477 478
            break;
        case MKTAG('s', 't', 'r', 'f'):
            /* stream header */
479
            if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
Fabrice Bellard's avatar
Fabrice Bellard committed
480 481
                url_fskip(pb, size);
            } else {
482 483 484
                uint64_t cur_pos = url_ftell(pb);
                if (cur_pos < list_end)
                    size = FFMIN(size, list_end - cur_pos);
Fabrice Bellard's avatar
Fabrice Bellard committed
485 486
                st = s->streams[stream_index];
                switch(codec_type) {
487
                case AVMEDIA_TYPE_VIDEO:
488 489 490
                    if(amv_file_format){
                        st->codec->width=avih_width;
                        st->codec->height=avih_height;
491
                        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
492 493 494 495
                        st->codec->codec_id = CODEC_ID_AMV;
                        url_fskip(pb, size);
                        break;
                    }
Fabrice Bellard's avatar
Fabrice Bellard committed
496
                    get_le32(pb); /* size */
497
                    st->codec->width = get_le32(pb);
498
                    st->codec->height = (int32_t)get_le32(pb);
Fabrice Bellard's avatar
Fabrice Bellard committed
499
                    get_le16(pb); /* panes */
500
                    st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
Fabrice Bellard's avatar
Fabrice Bellard committed
501
                    tag1 = get_le32(pb);
502 503 504 505 506 507
                    get_le32(pb); /* ImageSize */
                    get_le32(pb); /* XPelsPerMeter */
                    get_le32(pb); /* YPelsPerMeter */
                    get_le32(pb); /* ClrUsed */
                    get_le32(pb); /* ClrImportant */

Michael Niedermayer's avatar
Michael Niedermayer committed
508
                    if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
509
                        st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
510 511 512 513 514
                        st->codec->codec_tag = tag1;
                        st->codec->codec_id = CODEC_ID_XSUB;
                        break;
                    }

515 516 517
                    if(size > 10*4 && size<(1<<30)){
                        st->codec->extradata_size= size - 10*4;
                        st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
518 519 520 521
                        if (!st->codec->extradata) {
                            st->codec->extradata_size= 0;
                            return AVERROR(ENOMEM);
                        }
522 523
                        get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
                    }
524

525
                    if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
Michael Niedermayer's avatar
Michael Niedermayer committed
526
                        get_byte(pb);
527

Diego Biurrun's avatar
Diego Biurrun committed
528 529 530
                    /* Extract palette from extradata if bpp <= 8. */
                    /* This code assumes that extradata contains only palette. */
                    /* This is true for all paletted codecs implemented in FFmpeg. */
531
                    if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
532
                        st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
533
#if HAVE_BIGENDIAN
534 535
                        for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
                            st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
536
#else
537 538
                        memcpy(st->codec->palctrl->palette, st->codec->extradata,
                               FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
539
#endif
540
                        st->codec->palctrl->palette_changed = 1;
541 542
                    }

Fabrice Bellard's avatar
Fabrice Bellard committed
543 544 545
#ifdef DEBUG
                    print_tag("video", tag1, 0);
#endif
546
                    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
547
                    st->codec->codec_tag = tag1;
548
                    st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
Diego Biurrun's avatar
Diego Biurrun committed
549
                    st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
550 551 552 553 554
                    // Support "Resolution 1:1" for Avid AVI Codec
                    if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
                       st->codec->extradata_size >= 31 &&
                       !memcmp(&st->codec->extradata[28], "1:1", 3))
                        st->codec->codec_id = CODEC_ID_RAWVIDEO;
555 556 557 558 559 560 561 562 563

                    if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
                        st->codec->extradata_size+= 9;
                        st->codec->extradata= av_realloc(st->codec->extradata, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
                        if(st->codec->extradata)
                            memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
                    }
                    st->codec->height= FFABS(st->codec->height);

564
//                    url_fskip(pb, size - 5 * 4);
Fabrice Bellard's avatar
Fabrice Bellard committed
565
                    break;
566
                case AVMEDIA_TYPE_AUDIO:
567
                    ff_get_wav_header(pb, st->codec, size);
568
                    if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
569
                        av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
570 571
                        ast->sample_size= st->codec->block_align;
                    }
572
                    if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
573
                        url_fskip(pb, 1);
Diego Biurrun's avatar
Diego Biurrun committed
574
                    /* Force parsing as several audio frames can be in
Diego Biurrun's avatar
Diego Biurrun committed
575
                     * one packet and timestamps refer to packet start. */
576
                    st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
Diego Biurrun's avatar
Diego Biurrun committed
577 578 579
                    /* ADTS header is in extradata, AAC without header must be
                     * stored as exact frames. Parser not needed and it will
                     * fail. */
580
                    if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
Aurelien Jacobs's avatar
Aurelien Jacobs committed
581
                        st->need_parsing = AVSTREAM_PARSE_NONE;
582 583
                    /* AVI files with Xan DPCM audio (wrongly) declare PCM
                     * audio in the header but have Axan as stream_code_tag. */
584
                    if (st->codec->stream_codec_tag == AV_RL32("Axan")){
585 586 587
                        st->codec->codec_id  = CODEC_ID_XAN_DPCM;
                        st->codec->codec_tag = 0;
                    }
588 589
                    if (amv_file_format)
                        st->codec->codec_id  = CODEC_ID_ADPCM_IMA_AMV;
Fabrice Bellard's avatar
Fabrice Bellard committed
590 591
                    break;
                default:
592
                    st->codec->codec_type = AVMEDIA_TYPE_DATA;
593 594
                    st->codec->codec_id= CODEC_ID_NONE;
                    st->codec->codec_tag= 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
595 596 597 598 599
                    url_fskip(pb, size);
                    break;
                }
            }
            break;
600 601
        case MKTAG('i', 'n', 'd', 'x'):
            i= url_ftell(pb);
602
            if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
603 604
                read_braindead_odml_indx(s, 0);
            }
605 606
            url_fseek(pb, i+size, SEEK_SET);
            break;
607 608 609 610 611 612 613 614 615 616 617 618
        case MKTAG('v', 'p', 'r', 'p'):
            if(stream_index < (unsigned)s->nb_streams && size > 9*4){
                AVRational active, active_aspect;

                st = s->streams[stream_index];
                get_le32(pb);
                get_le32(pb);
                get_le32(pb);
                get_le32(pb);
                get_le32(pb);

                active_aspect.den= get_le16(pb);
Michael Niedermayer's avatar
Michael Niedermayer committed
619
                active_aspect.num= get_le16(pb);
620 621 622 623 624
                active.num       = get_le32(pb);
                active.den       = get_le32(pb);
                get_le32(pb); //nbFieldsPerFrame

                if(active_aspect.num && active_aspect.den && active.num && active.den){
625
                    st->sample_aspect_ratio= av_div_q(active_aspect, active);
626 627 628 629 630 631
//av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
                }
                size -= 9*4;
            }
            url_fseek(pb, size, SEEK_CUR);
            break;
632 633
        case MKTAG('s', 't', 'r', 'n'):
            if(s->nb_streams){
634
                avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
635 636
                break;
            }
Fabrice Bellard's avatar
Fabrice Bellard committed
637
        default:
638
            if(size > 1000000){
Diego Biurrun's avatar
Diego Biurrun committed
639 640
                av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
                                        "I will ignore it and try to continue anyway.\n");
641 642 643 644
                avi->movi_list = url_ftell(pb) - 4;
                avi->movi_end  = url_fsize(pb);
                goto end_of_header;
            }
Fabrice Bellard's avatar
Fabrice Bellard committed
645 646 647 648 649 650 651 652 653 654 655 656
            /* skip tag */
            size += (size & 1);
            url_fskip(pb, size);
            break;
        }
    }
 end_of_header:
    /* check stream number */
    if (stream_index != s->nb_streams - 1) {
    fail:
        return -1;
    }
Zdenek Kabelac's avatar
Zdenek Kabelac committed
657

658
    if(!avi->index_loaded && !url_is_streamed(pb))
659
        avi_load_index(s);
660
    avi->index_loaded = 1;
Michael Niedermayer's avatar
Michael Niedermayer committed
661
    avi->non_interleaved |= guess_ni_flag(s);
662 663 664 665 666 667 668 669 670 671
    for(i=0; i<s->nb_streams; i++){
        AVStream *st = s->streams[i];
        if(st->nb_index_entries)
            break;
    }
    if(i==s->nb_streams && avi->non_interleaved) {
        av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
        avi->non_interleaved=0;
    }

672
    if(avi->non_interleaved) {
Diego Biurrun's avatar
Diego Biurrun committed
673
        av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
674
        clean_index(s);
675
    }
676

Fabrice Bellard's avatar
Fabrice Bellard committed
677 678 679
    return 0;
}

680 681 682 683 684 685 686 687 688
static int get_stream_idx(int *d){
    if(    d[0] >= '0' && d[0] <= '9'
        && d[1] >= '0' && d[1] <= '9'){
        return (d[0] - '0') * 10 + (d[1] - '0');
    }else{
        return 100; //invalid stream ID
    }
}

Zdenek Kabelac's avatar
Zdenek Kabelac committed
689
static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
Fabrice Bellard's avatar
Fabrice Bellard committed
690 691
{
    AVIContext *avi = s->priv_data;
692
    ByteIOContext *pb = s->pb;
693 694
    int n, d[8];
    unsigned int size;
695
    int64_t i, sync;
696
    void* dstr;
697

698
    if (CONFIG_DV_DEMUXER && avi->dv_demux) {
699
        int size = dv_get_packet(avi->dv_demux, pkt);
700 701
        if (size >= 0)
            return size;
702
    }
703

704
    if(avi->non_interleaved){
705
        int best_stream_index = 0;
706 707 708 709
        AVStream *best_st= NULL;
        AVIStream *best_ast;
        int64_t best_ts= INT64_MAX;
        int i;
710

711 712 713 714
        for(i=0; i<s->nb_streams; i++){
            AVStream *st = s->streams[i];
            AVIStream *ast = st->priv_data;
            int64_t ts= ast->frame_offset;
715
            int64_t last_ts;
716

717 718 719
            if(!st->nb_index_entries)
                continue;

720 721 722 723
            last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
            if(!ast->remaining && ts > last_ts)
                continue;

724
            ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
725

726
//            av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
727
            if(ts < best_ts){
728 729 730 731 732
                best_ts= ts;
                best_st= st;
                best_stream_index= i;
            }
        }
733 734 735
        if(!best_st)
            return -1;

736
        best_ast = best_st->priv_data;
737
        best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
738 739
        if(best_ast->remaining)
            i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
740
        else{
741
            i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
742
            if(i>=0)
743
                best_ast->frame_offset= best_st->index_entries[i].timestamp;
744
        }
745

746
//        av_log(s, AV_LOG_DEBUG, "%d\n", i);
747 748
        if(i>=0){
            int64_t pos= best_st->index_entries[i].pos;
749
            pos += best_ast->packet_size - best_ast->remaining;
750
            url_fseek(s->pb, pos + 8, SEEK_SET);
751
//        av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
752

753 754
            assert(best_ast->remaining <= best_ast->packet_size);

755 756
            avi->stream_index= best_stream_index;
            if(!best_ast->remaining)
757
                best_ast->packet_size=
758
                best_ast->remaining= best_st->index_entries[i].size;
759 760
        }
    }
761

762
resync:
763 764