avidec.c 50.8 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
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
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
 * Libav 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
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
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with Libav; 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
#include "libavutil/avstring.h"
23
#include "libavutil/bswap.h"
24
#include "libavutil/dict.h"
25
#include "libavutil/internal.h"
26 27
#include "libavutil/intreadwrite.h"
#include "libavutil/mathematics.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
28 29
#include "avformat.h"
#include "avi.h"
30
#include "dv.h"
31
#include "internal.h"
32
#include "riff.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
33

34 35 36
#undef NDEBUG
#include <assert.h>

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

43 44
    uint32_t scale;
    uint32_t rate;
45 46
    int sample_size;        /* size of one sample (or packet)
                             * (in the rate/scale sense) in bytes */
47

48 49
    int64_t cum_len;        /* temporary storage (used during seek) */
    int prefix;             /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
50
    int prefix_count;
51 52
    uint32_t pal[256];
    int has_pal;
53 54
    int dshow_block_align;  /* block align variable used to emulate bugs in
                             * the MS dshow demuxer */
55 56 57 58

    AVFormatContext *sub_ctx;
    AVPacket sub_pkt;
    uint8_t *sub_buffer;
Fabrice Bellard's avatar
Fabrice Bellard committed
59
} AVIStream;
Fabrice Bellard's avatar
Fabrice Bellard committed
60 61

typedef struct {
62 63 64
    int64_t riff_end;
    int64_t movi_end;
    int64_t fsize;
65
    int64_t movi_list;
66
    int64_t last_pkt_pos;
Fabrice Bellard's avatar
Fabrice Bellard committed
67
    int index_loaded;
68
    int is_odml;
69 70
    int non_interleaved;
    int stream_index;
71
    DVDemuxContext *dv_demux;
72 73
    int odml_depth;
#define MAX_ODML_DEPTH 1000
Fabrice Bellard's avatar
Fabrice Bellard committed
74 75
} AVIContext;

76
static const char avi_headers[][8] = {
77 78 79 80 81
    { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' '  },
    { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X'  },
    { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
    { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f'  },
    { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' '  },
82 83 84
    { 0 }
};

85 86 87 88 89
static const AVMetadataConv avi_metadata_conv[] = {
    { "strn", "title" },
    { 0 },
};

90
static int avi_load_index(AVFormatContext *s);
91
static int guess_ni_flag(AVFormatContext *s);
92

93 94 95 96 97 98 99
#define print_tag(str, tag, size)                        \
    av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n",        \
            str, tag & 0xff,                             \
            (tag >> 8) & 0xff,                           \
            (tag >> 16) & 0xff,                          \
            (tag >> 24) & 0xff,                          \
            size)
Fabrice Bellard's avatar
Fabrice Bellard committed
100

101 102 103
static inline int get_duration(AVIStream *ast, int len)
{
    if (ast->sample_size)
104
        return len;
105 106 107
    else if (ast->dshow_block_align)
        return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
    else
108 109 110
        return 1;
}

111
static int get_riff(AVFormatContext *s, AVIOContext *pb)
112
{
113
    AVIContext *avi = s->priv_data;
114 115
    char header[8];
    int i;
116

117
    /* check RIFF header */
118
    avio_read(pb, header, 4);
119
    avi->riff_end  = avio_rl32(pb); /* RIFF chunk size */
120
    avi->riff_end += avio_tell(pb); /* RIFF chunk end */
121
    avio_read(pb, header + 4, 4);
122

123 124
    for (i = 0; avi_headers[i][0]; i++)
        if (!memcmp(header, avi_headers[i], 8))
125
            break;
126
    if (!avi_headers[i][0])
127
        return AVERROR_INVALIDDATA;
128

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

133 134 135
    return 0;
}

136 137 138 139 140 141 142 143 144 145 146 147
static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
{
    AVIContext *avi     = s->priv_data;
    AVIOContext *pb     = s->pb;
    int longs_pre_entry = avio_rl16(pb);
    int index_sub_type  = avio_r8(pb);
    int index_type      = avio_r8(pb);
    int entries_in_use  = avio_rl32(pb);
    int chunk_id        = avio_rl32(pb);
    int64_t base        = avio_rl64(pb);
    int stream_id       = ((chunk_id      & 0xFF) - '0') * 10 +
                          ((chunk_id >> 8 & 0xFF) - '0');
148 149 150
    AVStream *st;
    AVIStream *ast;
    int i;
151 152 153 154 155 156 157 158 159 160 161 162 163
    int64_t last_pos = -1;
    int64_t filesize = avio_size(s->pb);

    av_dlog(s,
            "longs_pre_entry:%d index_type:%d entries_in_use:%d "
            "chunk_id:%X base:%16"PRIX64"\n",
            longs_pre_entry,
            index_type,
            entries_in_use,
            chunk_id,
            base);

    if (stream_id >= s->nb_streams || stream_id < 0)
164
        return AVERROR_INVALIDDATA;
165
    st  = s->streams[stream_id];
166 167
    ast = st->priv_data;

168
    if (index_sub_type)
169
        return AVERROR_INVALIDDATA;
170

171
    avio_rl32(pb);
172

173
    if (index_type && longs_pre_entry != 2)
174
        return AVERROR_INVALIDDATA;
175
    if (index_type > 1)
176
        return AVERROR_INVALIDDATA;
177

178
    if (filesize > 0 && base >= filesize) {
179
        av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
180 181 182
        if (base >> 32 == (base & 0xFFFFFFFF) &&
            (base & 0xFFFFFFFF) < filesize    &&
            filesize <= 0xFFFFFFFF)
183 184
            base &= 0xFFFFFFFF;
        else
185
            return AVERROR_INVALIDDATA;
186 187
    }

188 189 190 191 192
    for (i = 0; i < entries_in_use; i++) {
        if (index_type) {
            int64_t pos = avio_rl32(pb) + base - 8;
            int len     = avio_rl32(pb);
            int key     = len >= 0;
193 194
            len &= 0x7FFFFFFF;

195 196
            av_dlog(s, "pos:%"PRId64", len:%X\n", pos, len);

197
            if (pb->eof_reached)
198
                return AVERROR_INVALIDDATA;
199

200 201 202 203 204
            if (last_pos == pos || pos == base - 8)
                avi->non_interleaved = 1;
            if (last_pos != pos && (len || !ast->sample_size))
                av_add_index_entry(st, pos, ast->cum_len, len, 0,
                                   key ? AVINDEX_KEYFRAME : 0);
205

206
            ast->cum_len += get_duration(ast, len);
207 208
            last_pos      = pos;
        } else {
Måns Rullgård's avatar
Måns Rullgård committed
209 210
            int64_t offset, pos;
            int duration;
211 212 213
            offset = avio_rl64(pb);
            avio_rl32(pb);       /* size */
            duration = avio_rl32(pb);
214

215
            if (pb->eof_reached)
216
                return AVERROR_INVALIDDATA;
217

218
            pos = avio_tell(pb);
219

220
            if (avi->odml_depth > MAX_ODML_DEPTH) {
221
                av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
222
                return AVERROR_INVALIDDATA;
223 224
            }

225
            avio_seek(pb, offset + 8, SEEK_SET);
226
            avi->odml_depth++;
227
            read_braindead_odml_indx(s, frame_num);
228
            avi->odml_depth--;
229 230
            frame_num += duration;

231
            avio_seek(pb, pos, SEEK_SET);
232 233
        }
    }
234
    avi->index_loaded = 1;
235 236 237
    return 0;
}

238 239
static void clean_index(AVFormatContext *s)
{
240 241
    int i;
    int64_t j;
242

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

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

253 254
        while (max < 1024)
            max += max;
255

256 257 258
        pos  = st->index_entries[0].pos;
        size = st->index_entries[0].size;
        ts   = st->index_entries[0].timestamp;
259

260 261 262
        for (j = 0; j < size; j += max)
            av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
                               AVINDEX_KEYFRAME);
263 264 265
    }
}

266 267
static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
                        uint32_t size)
268
{
269
    AVIOContext *pb = s->pb;
270 271
    char key[5]     = { 0 };
    char *value;
272

273
    size += (size & 1);
274

275
    if (size == UINT_MAX)
276
        return AVERROR(EINVAL);
277
    value = av_malloc(size + 1);
278
    if (!value)
279
        return AVERROR(ENOMEM);
280
    avio_read(pb, value, size);
281
    value[size] = 0;
282

283 284
    AV_WL32(key, tag);

285
    return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
286
                       AV_DICT_DONT_STRDUP_VAL);
287 288
}

289 290 291
static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

292
static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
293 294 295 296 297
{
    char month[4], time[9], buffer[64];
    int i, day, year;
    /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
    if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
298
               month, &day, time, &year) == 4) {
299
        for (i = 0; i < 12; i++)
300
            if (!av_strcasecmp(month, months[i])) {
301
                snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
302
                         year, i + 1, day, time);
303
                av_dict_set(metadata, "creation_time", buffer, 0);
304
            }
305 306
    } else if (date[4] == '/' && date[7] == '/') {
        date[4] = date[7] = '-';
307
        av_dict_set(metadata, "creation_time", date, 0);
308
    }
309 310
}

311 312
static void avi_read_nikon(AVFormatContext *s, uint64_t end)
{
313
    while (avio_tell(s->pb) < end) {
314 315
        uint32_t tag  = avio_rl32(s->pb);
        uint32_t size = avio_rl32(s->pb);
316
        switch (tag) {
317 318
        case MKTAG('n', 'c', 't', 'g'):  /* Nikon Tags */
        {
319 320
            uint64_t tag_end = avio_tell(s->pb) + size;
            while (avio_tell(s->pb) < tag_end) {
321 322
                uint16_t tag     = avio_rl16(s->pb);
                uint16_t size    = avio_rl16(s->pb);
323
                const char *name = NULL;
324
                char buffer[64]  = { 0 };
325
                size -= avio_read(s->pb, buffer,
326
                                  FFMIN(size, sizeof(buffer) - 1));
327
                switch (tag) {
328 329 330 331 332 333 334 335
                case 0x03:
                    name = "maker";
                    break;
                case 0x04:
                    name = "model";
                    break;
                case 0x13:
                    name = "creation_time";
336 337 338 339 340
                    if (buffer[4] == ':' && buffer[7] == ':')
                        buffer[4] = buffer[7] = '-';
                    break;
                }
                if (name)
341
                    av_dict_set(&s->metadata, name, buffer, 0);
342
                avio_skip(s->pb, size);
343 344 345 346
            }
            break;
        }
        default:
347
            avio_skip(s->pb, size);
348 349 350 351 352
            break;
        }
    }
}

353
static int avi_read_header(AVFormatContext *s)
Fabrice Bellard's avatar
Fabrice Bellard committed
354
{
Fabrice Bellard's avatar
Fabrice Bellard committed
355
    AVIContext *avi = s->priv_data;
356
    AVIOContext *pb = s->pb;
357
    unsigned int tag, tag1, handler;
Mans Rullgard's avatar
Mans Rullgard committed
358
    int codec_type, stream_index, frame_period;
Michael Niedermayer's avatar
Michael Niedermayer committed
359
    unsigned int size;
360
    int i;
Fabrice Bellard's avatar
Fabrice Bellard committed
361
    AVStream *st;
362 363 364 365
    AVIStream *ast      = NULL;
    int avih_width      = 0, avih_height = 0;
    int amv_file_format = 0;
    uint64_t list_end   = 0;
366
    int ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
367

368
    avi->stream_index = -1;
369

370 371 372
    ret = get_riff(s, pb);
    if (ret < 0)
        return ret;
373

374
    avi->fsize = avio_size(pb);
375 376
    if (avi->fsize <= 0)
        avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
377

Fabrice Bellard's avatar
Fabrice Bellard committed
378 379
    /* first list tag */
    stream_index = -1;
380
    codec_type   = -1;
Fabrice Bellard's avatar
Fabrice Bellard committed
381
    frame_period = 0;
382
    for (;;) {
Anton Khirnov's avatar
Anton Khirnov committed
383
        if (pb->eof_reached)
Fabrice Bellard's avatar
Fabrice Bellard committed
384
            goto fail;
385
        tag  = avio_rl32(pb);
386
        size = avio_rl32(pb);
387

Fabrice Bellard's avatar
Fabrice Bellard committed
388 389
        print_tag("tag", tag, size);

390
        switch (tag) {
Fabrice Bellard's avatar
Fabrice Bellard committed
391
        case MKTAG('L', 'I', 'S', 'T'):
392
            list_end = avio_tell(pb) + size;
Diego Biurrun's avatar
Diego Biurrun committed
393
            /* Ignored, except at start of video packets. */
394
            tag1 = avio_rl32(pb);
395

Fabrice Bellard's avatar
Fabrice Bellard committed
396
            print_tag("list", tag1, 0);
397

Fabrice Bellard's avatar
Fabrice Bellard committed
398
            if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
399
                avi->movi_list = avio_tell(pb) - 4;
400 401 402 403
                if (size)
                    avi->movi_end = avi->movi_list + size + (size & 1);
                else
                    avi->movi_end = avio_size(pb);
404
                av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
Fabrice Bellard's avatar
Fabrice Bellard committed
405
                goto end_of_header;
406
            } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
407
                ff_read_riff_info(s, size - 4);
408 409
            else if (tag1 == MKTAG('n', 'c', 'd', 't'))
                avi_read_nikon(s, list_end);
410

Fabrice Bellard's avatar
Fabrice Bellard committed
411
            break;
412 413 414
        case MKTAG('I', 'D', 'I', 'T'):
        {
            unsigned char date[64] = { 0 };
415
            size += (size & 1);
416
            size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
417
            avio_skip(pb, size);
418 419 420
            avi_metadata_creation_time(&s->metadata, date);
            break;
        }
421
        case MKTAG('d', 'm', 'l', 'h'):
422
            avi->is_odml = 1;
423
            avio_skip(pb, size + (size & 1));
424
            break;
425
        case MKTAG('a', 'm', 'v', 'h'):
426
            amv_file_format = 1;
Fabrice Bellard's avatar
Fabrice Bellard committed
427
        case MKTAG('a', 'v', 'i', 'h'):
Diego Biurrun's avatar
Diego Biurrun committed
428
            /* AVI header */
429
            /* using frame_period is bad idea */
430
            frame_period = avio_rl32(pb);
Mans Rullgard's avatar
Mans Rullgard committed
431
            avio_skip(pb, 4);
432 433
            avio_rl32(pb);
            avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
434

435
            avio_skip(pb, 2 * 4);
436 437
            avio_rl32(pb);
            avio_rl32(pb);
438 439
            avih_width  = avio_rl32(pb);
            avih_height = avio_rl32(pb);
440

441
            avio_skip(pb, size - 10 * 4);
442 443 444 445
            break;
        case MKTAG('s', 't', 'r', 'h'):
            /* stream header */

446
            tag1    = avio_rl32(pb);
447
            handler = avio_rl32(pb); /* codec tag */
448

449
            if (tag1 == MKTAG('p', 'a', 'd', 's')) {
450
                avio_skip(pb, size - 8);
451
                break;
452
            } else {
453
                stream_index++;
454
                st = avformat_new_stream(s, NULL);
Fabrice Bellard's avatar
Fabrice Bellard committed
455 456
                if (!st)
                    goto fail;
457

458
                st->id = stream_index;
459
                ast    = av_mallocz(sizeof(AVIStream));
Fabrice Bellard's avatar
Fabrice Bellard committed
460 461 462
                if (!ast)
                    goto fail;
                st->priv_data = ast;
463
            }
464 465 466
            if (amv_file_format)
                tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
                                    : MKTAG('v', 'i', 'd', 's');
467

468
            print_tag("strh", tag1, -1);
469

470 471
            if (tag1 == MKTAG('i', 'a', 'v', 's') ||
                tag1 == MKTAG('i', 'v', 'a', 's')) {
472 473
                int64_t dv_dur;

474 475
                /* After some consideration -- I don't think we
                 * have to support anything but DV in type1 AVIs. */
476 477 478 479 480 481
                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'))
482
                    goto fail;
483 484 485

                ast = s->streams[0]->priv_data;
                av_freep(&s->streams[0]->codec->extradata);
486
                av_freep(&s->streams[0]->codec);
487 488
                av_freep(&s->streams[0]);
                s->nb_streams = 0;
489
                if (CONFIG_DV_DEMUXER) {
490
                    avi->dv_demux = avpriv_dv_init_demux(s);
491 492
                    if (!avi->dv_demux)
                        goto fail;
493
                }
494
                s->streams[0]->priv_data = ast;
495
                avio_skip(pb, 3 * 4);
496
                ast->scale = avio_rl32(pb);
497
                ast->rate  = avio_rl32(pb);
498
                avio_skip(pb, 4);  /* start time */
499

500
                dv_dur = avio_rl32(pb);
501
                if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
502
                    dv_dur     *= AV_TIME_BASE;
503 504
                    s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
                }
505 506
                /* else, leave duration alone; timing estimation in utils.c
                 * will make a guess based on bitrate. */
507

508
                stream_index = s->nb_streams - 1;
509
                avio_skip(pb, size - 9 * 4);
510 511
                break;
            }
512

513
            assert(stream_index < s->nb_streams);
514
            st->codec->stream_codec_tag = handler;
515

516 517 518 519 520
            avio_rl32(pb); /* flags */
            avio_rl16(pb); /* priority */
            avio_rl16(pb); /* language */
            avio_rl32(pb); /* initial frame */
            ast->scale = avio_rl32(pb);
521 522 523 524 525 526 527 528 529
            ast->rate  = avio_rl32(pb);
            if (!(ast->scale && ast->rate)) {
                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);
                if (frame_period) {
                    ast->rate  = 1000000;
Michael Niedermayer's avatar
Michael Niedermayer committed
530
                    ast->scale = frame_period;
531 532
                } else {
                    ast->rate  = 25;
Michael Niedermayer's avatar
Michael Niedermayer committed
533 534
                    ast->scale = 1;
                }
535
            }
536
            avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
537

538
            ast->cum_len  = avio_rl32(pb); /* start */
539
            st->nb_frames = avio_rl32(pb);
540

541
            st->start_time = 0;
542 543 544
            avio_rl32(pb); /* buffer size */
            avio_rl32(pb); /* quality */
            ast->sample_size = avio_rl32(pb); /* sample ssize */
545
            ast->cum_len    *= FFMAX(1, ast->sample_size);
546 547
            av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
                    ast->rate, ast->scale, ast->sample_size);
548

549
            switch (tag1) {
550
            case MKTAG('v', 'i', 'd', 's'):
551
                codec_type = AVMEDIA_TYPE_VIDEO;
552

553 554 555
                ast->sample_size = 0;
                break;
            case MKTAG('a', 'u', 'd', 's'):
556
                codec_type = AVMEDIA_TYPE_AUDIO;
557
                break;
558
            case MKTAG('t', 'x', 't', 's'):
559
                codec_type = AVMEDIA_TYPE_SUBTITLE;
560
                break;
Florian Echtler's avatar
Florian Echtler committed
561
            case MKTAG('d', 'a', 't', 's'):
562
                codec_type = AVMEDIA_TYPE_DATA;
Florian Echtler's avatar
Florian Echtler committed
563
                break;
564
            default:
Michael Niedermayer's avatar
Michael Niedermayer committed
565
                av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
566
                goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
567
            }
568
            if (ast->sample_size == 0)
569
                st->duration = st->nb_frames;
570
            ast->frame_offset = ast->cum_len;
571
            avio_skip(pb, size - 12 * 4);
Fabrice Bellard's avatar
Fabrice Bellard committed
572 573 574
            break;
        case MKTAG('s', 't', 'r', 'f'):
            /* stream header */
575
            if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
576
                avio_skip(pb, size);
Fabrice Bellard's avatar
Fabrice Bellard committed
577
            } else {
578
                uint64_t cur_pos = avio_tell(pb);
579 580
                if (cur_pos < list_end)
                    size = FFMIN(size, list_end - cur_pos);
Fabrice Bellard's avatar
Fabrice Bellard committed
581
                st = s->streams[stream_index];
582
                switch (codec_type) {
583
                case AVMEDIA_TYPE_VIDEO:
584 585 586
                    if (amv_file_format) {
                        st->codec->width      = avih_width;
                        st->codec->height     = avih_height;
587
                        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
588
                        st->codec->codec_id   = AV_CODEC_ID_AMV;
589
                        avio_skip(pb, size);
590 591
                        break;
                    }
Peter Ross's avatar
Peter Ross committed
592
                    tag1 = ff_get_bmp_header(pb, st);
593

594 595
                    if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
                        tag1 == MKTAG('D', 'X', 'S', 'A')) {
596
                        st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
597 598
                        st->codec->codec_tag  = tag1;
                        st->codec->codec_id   = AV_CODEC_ID_XSUB;
599 600 601
                        break;
                    }

602 603 604 605
                    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);
606
                        if (!st->codec->extradata) {
607
                            st->codec->extradata_size = 0;
608 609
                            return AVERROR(ENOMEM);
                        }
610 611 612
                        avio_read(pb,
                                  st->codec->extradata,
                                  st->codec->extradata_size);
613
                    }
614

615 616
                    // FIXME: check if the encoder really did this correctly
                    if (st->codec->extradata_size & 1)
617
                        avio_r8(pb);
618

619 620 621 622 623 624
                    /* Extract palette from extradata if bpp <= 8.
                     * This code assumes that extradata contains only palette.
                     * This is true for all paletted codecs implemented in
                     * Libav. */
                    if (st->codec->extradata_size &&
                        (st->codec->bits_per_coded_sample <= 8)) {
625 626 627 628
                        int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
                        const uint8_t *pal_src;

                        pal_size = FFMIN(pal_size, st->codec->extradata_size);
629 630
                        pal_src  = st->codec->extradata +
                                   st->codec->extradata_size - pal_size;
631
#if HAVE_BIGENDIAN
632 633
                        for (i = 0; i < pal_size / 4; i++)
                            ast->pal[i] = av_bswap32(((uint32_t *)pal_src)[i]);
634
#else
635
                        memcpy(ast->pal, pal_src, pal_size);
636
#endif
637
                        ast->has_pal = 1;
638 639
                    }

Fabrice Bellard's avatar
Fabrice Bellard committed
640
                    print_tag("video", tag1, 0);
641

642
                    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
643 644 645 646 647 648
                    st->codec->codec_tag  = tag1;
                    st->codec->codec_id   = ff_codec_get_id(ff_codec_bmp_tags,
                                                            tag1);
                    /* This is needed to get the pict type which is necessary
                     * for generating correct pts. */
                    st->need_parsing = AVSTREAM_PARSE_HEADERS;
649
                    // Support "Resolution 1:1" for Avid AVI Codec
650 651 652
                    if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
                        st->codec->extradata_size >= 31   &&
                        !memcmp(&st->codec->extradata[28], "1:1", 3))
653
                        st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
654

655 656 657 658 659 660 661 662 663
                    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);
664
                    }
665
                    st->codec->height = FFABS(st->codec->height);
666

667
//                    avio_skip(pb, size - 5 * 4);
Fabrice Bellard's avatar
Fabrice Bellard committed
668
                    break;
669
                case AVMEDIA_TYPE_AUDIO:
670 671 672
                    ret = ff_get_wav_header(pb, st->codec, size);
                    if (ret < 0)
                        return ret;
673 674 675 676 677 678 679 680 681
                    ast->dshow_block_align = st->codec->block_align;
                    if (ast->sample_size && st->codec->block_align &&
                        ast->sample_size != st->codec->block_align) {
                        av_log(s,
                               AV_LOG_WARNING,
                               "sample size (%d) != block align (%d)\n",
                               ast->sample_size,
                               st->codec->block_align);
                        ast->sample_size = st->codec->block_align;
682
                    }
683 684 685
                    /* 2-aligned
                     * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
                    if (size & 1)
686
                        avio_skip(pb, 1);
Diego Biurrun's avatar
Diego Biurrun committed
687
                    /* Force parsing as several audio frames can be in
Diego Biurrun's avatar
Diego Biurrun committed
688
                     * one packet and timestamps refer to packet start. */
689
                    st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
Diego Biurrun's avatar
Diego Biurrun committed
690 691 692
                    /* ADTS header is in extradata, AAC without header must be
                     * stored as exact frames. Parser not needed and it will
                     * fail. */
693 694
                    if (st->codec->codec_id == AV_CODEC_ID_AAC &&
                        st->codec->extradata_size)
695
                        st->need_parsing = AVSTREAM_PARSE_NONE;
696 697
                    /* AVI files with Xan DPCM audio (wrongly) declare PCM
                     * audio in the header but have Axan as stream_code_tag. */
698
                    if (st->codec->stream_codec_tag == AV_RL32("Axan")) {
699
                        st->codec->codec_id  = AV_CODEC_ID_XAN_DPCM;
700 701
                        st->codec->codec_tag = 0;
                    }
702 703
                    if (amv_file_format) {
                        st->codec->codec_id    = AV_CODEC_ID_ADPCM_IMA_AMV;
704 705
                        ast->dshow_block_align = 0;
                    }
Fabrice Bellard's avatar
Fabrice Bellard committed
706
                    break;
707 708
                case AVMEDIA_TYPE_SUBTITLE:
                    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
709
                    st->codec->codec_id   = AV_CODEC_ID_PROBE;
710
                    break;
Fabrice Bellard's avatar
Fabrice Bellard committed
711
                default:
712
                    st->codec->codec_type = AVMEDIA_TYPE_DATA;
713 714
                    st->codec->codec_id   = AV_CODEC_ID_NONE;
                    st->codec->codec_tag  = 0;
715
                    avio_skip(pb, size);
Fabrice Bellard's avatar
Fabrice Bellard committed
716 717 718 719
                    break;
                }
            }
            break;
720
        case MKTAG('i', 'n', 'd', 'x'):
721 722 723 724
            i = avio_tell(pb);
            if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
                read_braindead_odml_indx(s, 0) < 0 &&
                (s->error_recognition & AV_EF_EXPLODE))
725
                goto fail;
726
            avio_seek(pb, i + size, SEEK_SET);
727
            break;
728
        case MKTAG('v', 'p', 'r', 'p'):
729
            if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
730 731 732
                AVRational active, active_aspect;

                st = s->streams[stream_index];
733 734 735 736 737 738
                avio_rl32(pb);
                avio_rl32(pb);
                avio_rl32(pb);
                avio_rl32(pb);
                avio_rl32(pb);

739 740 741 742 743
                active_aspect.den = avio_rl16(pb);
                active_aspect.num = avio_rl16(pb);
                active.num        = avio_rl32(pb);
                active.den        = avio_rl32(pb);
                avio_rl32(pb); // nbFieldsPerFrame
744

745 746 747
                if (active_aspect.num && active_aspect.den &&
                    active.num && active.den) {
                    st->sample_aspect_ratio = av_div_q(active_aspect, active);
748 749 750
                    av_dlog(s, "vprp %d/%d %d/%d\n",
                            active_aspect.num, active_aspect.den,
                            active.num, active.den);
751
                }
752
                size -= 9 * 4;
753
            }
754
            avio_skip(pb, size);
755
            break;
756
        case MKTAG('s', 't', 'r', 'n'):
757 758
            if (s->nb_streams) {
                ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
759 760
                if (ret < 0)
                    return ret;
761 762
                break;
            }
Fabrice Bellard's avatar
Fabrice Bellard committed
763
        default:
764 765 766 767
            if (size > 1000000) {
                av_log(s, AV_LOG_ERROR,
                       "Something went wrong during header parsing, "
                       "I will ignore it and try to continue anyway.\n");
768 769
                if (s->error_recognition & AV_EF_EXPLODE)
                    goto fail;
770
                avi->movi_list = avio_tell(pb) - 4;
771
                avi->movi_end  = avio_size(pb);
772 773
                goto end_of_header;
            }
Fabrice Bellard's avatar
Fabrice Bellard committed
774 775
            /* skip tag */
            size += (size & 1);
776
            avio_skip(pb, size);
Fabrice Bellard's avatar
Fabrice Bellard committed
777 778 779
            break;
        }
    }
780 781

end_of_header:
Fabrice Bellard's avatar
Fabrice Bellard committed
782 783
    /* check stream number */
    if (stream_index != s->nb_streams - 1) {
784 785

fail:
786
        return AVERROR_INVALIDDATA;
Fabrice Bellard's avatar
Fabrice Bellard committed
787
    }
788

789
    if (!avi->index_loaded && pb->seekable)
790
        avi_load_index(s);
791
    avi->index_loaded     = 1;
792
    avi->non_interleaved |= guess_ni_flag(s);
793
    for (i = 0; i < s->nb_streams; i++) {
794
        AVStream *st = s->streams[i];
795
        if (st->nb_index_entries)
796 797
            break;
    }
798 799 800 801
    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;
802 803
    }

804
    if (avi->non_interleaved) {
Diego Biurrun's avatar
Diego Biurrun committed
805
        av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
806
        clean_index(s);
807
    }
808

809 810
    ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
    ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
811

Fabrice Bellard's avatar
Fabrice Bellard committed
812 813 814
    return 0;
}

815 816 817
static int read_gab2_sub(AVStream *st, AVPacket *pkt)
{
    if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
818
        uint8_t desc[256];
819
        int score      = AVPROBE_SCORE_EXTENSION, ret;
820 821 822
        AVIStream *ast = st->priv_data;
        AVInputFormat *sub_demuxer;
        AVRational time_base;
823 824 825
        AVIOContext *pb = avio_alloc_context(pkt->data + 7,
                                             pkt->size - 7,
                                             0, NULL, NULL, NULL, NULL);
826
        AVProbeData pd;
827
        unsigned int desc_len = avio_rl32(pb);
828

829 830
        if (desc_len > pb->buf_end - pb->buf_ptr)
            goto error;
831

832
        ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
833
        avio_skip(pb, desc_len - ret);
834
        if (*desc)
835
            av_dict_set(&st->metadata, "title", desc, 0);
836

837 838
        avio_rl16(pb);   /* flags? */
        avio_rl32(pb);   /* data size */
839

840 841
        pd = (AVProbeData) { .buf      = pb->buf_ptr,
                             .buf_size = pb->buf_end - pb->buf_ptr };
842
        if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
843
            goto error;
844

845 846 847
        if (!(ast->sub_ctx = avformat_alloc_context()))
            goto error;

848
        ast->sub_ctx->pb = pb;
849
        if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
850
            ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
851 852 853
            *st->codec = *ast->sub_ctx->streams[0]->codec;
            ast->sub_ctx->streams[0]->codec->extradata = NULL;
            time_base = ast->sub_ctx->streams[0]->time_base;
854
            avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
855 856 857 858
        }
        ast->sub_buffer = pkt->data;
        memset(pkt, 0, sizeof(*pkt));
        return 1;
859

860 861
error:
        av_freep(&pb);
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
    }
    return 0;
}

static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
                                  AVPacket *pkt)
{
    AVIStream *ast, *next_ast = next_st->priv_data;
    int64_t ts, next_ts, ts_min = INT64_MAX;
    AVStream *st, *sub_st = NULL;
    int i;

    next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
                           AV_TIME_BASE_Q);

877
    for (i = 0; i < s->nb_streams; i++) {
878 879
        st  = s->streams[i];
        ast = st->priv_data;
880
        if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
881 882 883 884 885 886 887 888 889
            ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
            if (ts <= next_ts && ts < ts_min) {
                ts_min = ts;
                sub_st = st;
            }
        }
    }

    if (sub_st) {
890 891
        ast               = sub_st->priv_data;
        *pkt              = ast->sub_pkt;
892
        pkt->stream_index = sub_st->index;
893

894
        if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
895 896 897 898 899
            ast->sub_pkt.data = NULL;
    }
    return sub_st;
}

900 901 902 903
static int get_stream_idx(int *d)
{
    if (d[0] >= '0' && d[0] <= '9' &&
        d[1] >= '0' && d[1] <= '9') {
904
        return (d[0] - '0') * 10 + (d[1] - '0');
905 906
    } else {
        return 100; // invalid stream ID
907 908 909
    }
}

910
static int avi_sync(AVFormatContext *s, int exit_early)
Fabrice Bellard's avatar
Fabrice Bellard committed
911 912
{
    AVIContext *avi = s->priv_data;
913
    AVIOContext *pb = s->pb;
914 915
    int n;
    unsigned int d[8];
916
    unsigned int size;
917
    int64_t i, sync;
918 919

start_sync:
920
    memset(d, -1, sizeof(d));
921
    for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
922 923
        int j;

924 925 926
        for (j = 0; j < 7; j++)
            d[j] = d[j + 1];
        d[7] = avio_r8(pb);
927

928
        size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
929

930
        n = get_stream_idx(d + 2);
931 932
        av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
                d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
933
        if (i + (uint64_t)size > avi->fsize || d[0] > 127)
934 935
            continue;

936 937 938 939 940
        // parse ix##
        if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
            // parse JUNK
            (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
            (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
941 942 943 944
            avio_skip(pb, size);
            goto start_sync;
        }

945 946
        // parse stray LIST
        if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
947 948 949 950
            avio_skip(pb, 4);
            goto start_sync;
        }

951
        n = get_stream_idx(d);
952

953 954
        if (!((i - avi->last_pkt_pos) & 1) &&
            get_stream_idx(d + 1) < s->nb_streams)
955 956
            continue;

957 958
        // detect ##ix chunk and skip
        if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
959 960 961 962
            avio_skip(pb, size);
            goto start_sync;
        }

963 964
        // parse ##dc/##wb
        if (n < s->nb_streams) {
965 966
            AVStream *st;
            AVIStream *ast;
967
            st  = s->streams[n];
968 969
            ast = st->priv_data;

970 971 972 973 974 975 976 977 978 979 980 981
            if (s->nb_streams >= 2) {
                AVStream *st1   = s->streams[1];
                AVIStream *ast1 = st1->priv_data;
                // workaround for broken small-file-bug402.avi
                if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
                    st->codec->codec_type  == AVMEDIA_TYPE_VIDEO &&
                    st1->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
                    ast->prefix == 'd' * 256 + 'c' &&
                    (d[2] * 256 + d[3] == ast1->prefix ||
                     !ast1->prefix_count)) {
                    n   = 1;
                    st  = st1;
982
                    ast = ast1;
983 984
                    av_log(s, AV_LOG_WARNING,
                           "Invalid stream + prefix combination, assuming audio.\n");
985 986 987
                }
            }

988 989 990 991 992 993
            if (!avi->dv_demux &&
                ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
                 // FIXME: needs a little reordering
                 (st->discard >= AVDISCARD_NONKEY &&
                 !(pkt->flags & AV_PKT_FLAG_KEY)) */
                || st->discard >= AVDISCARD_ALL)) {
994 995 996
                if (!exit_early) {
                    ast->frame_offset += get_duration(ast, size);
                }
997 998 999 1000
                avio_skip(pb, size);
                goto start_sync;
            }

1001 1002
            if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
                int k    = avio_r8(pb);
1003 1004
                int last = (k + avio_r8(pb) - 1) & 0xFF;

1005
                avio_rl16(pb); // flags
1006

1007
                // b + (g << 8) + (r << 16);
1008
                for (; k <= last; k++)
1009
                    ast->pal[k] = avio_rb32(pb) >> 8;
1010

1011 1012 1013 1014 1015 1016 1017
                ast->has_pal = 1;
                goto start_sync;
            } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
                        d[2] < 128 && d[3] < 128) ||
                       d[2] * 256 + d[3] == ast->prefix /* ||
                       (d[2] == 'd' && d[3] == 'c') ||
                       (d[2] == 'w' && d[3] == 'b') */) {
1018 1019
                if (exit_early)
                    return 0;
1020
                if (d[2] * 256 + d[3] == ast->prefix)
1021
                    ast->prefix_count++;
1022 1023 1024
                else {
                    ast->prefix       = d[2] * 256 + d[3];
                    ast->prefix_count = 0;
1025 1026
                }

1027 1028 1029
                avi->stream_index = n;
                ast->packet_size  = size + 8;
                ast->remaining    = size;
1030

1031 1032 1033 1034 1035 1036
                if (size || !ast->sample_size) {
                    uint64_t pos = avio_tell(pb) - 8;
                    if (!st->index_entries || !st->nb_index_entries ||
                        st->index_entries[st->nb_index_entries - 1].pos < pos) {
                        av_add_index_entry(st, pos, ast->frame_offset, size,
                                           0, AVINDEX_KEYFRAME);
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
                    }
                }
                return 0;
            }
        }
    }

    return AVERROR_EOF;
}

static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
{
    AVIContext *avi = s->priv_data;
    AVIOContext *pb = s->pb;
    int err;
1052
#if FF_API_DESTRUCT_PACKET
1053
    void *dstr;
1054
#endif
1055

1056
    if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1057
        int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1058 1059
        if (size >= 0)
            return size;
1060
    }
1061

1062
    if (avi->non_interleaved) {
1063
        int best_stream_index = 0;
1064
        AVStream *best_st     = NULL;
1065
        AVIStream *best_ast;
1066
        int64_t best_ts = INT64_MAX;
1067
        int i;
1068

1069 1070
        for (i = 0; i < s->nb_streams; i++) {
            AVStream *st   = s->streams[i];
1071
            AVIStream *ast = st->priv_data;
1072
            int64_t ts     = ast->frame_offset;
1073
            int64_t last_ts;
1074

1075
            if (!st->nb_index_entries)
1076 1077
                continue;

1078
            last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1079
            if (!ast->remaining && ts > last_ts)
1080 1081
                continue;

1082 1083 1084
            ts = av_rescale_q(ts, st->time_base,
                              (AVRational) { FFMAX(1, ast->sample_size),
                                             AV_TIME_BASE });
1085

1086 1087
            av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
                    st->time_base.num, st->time_base.den, ast->frame_offset);
1088 1089 1090 1091
            if (ts < best_ts) {
                best_ts           = ts;
                best_st           = st;
                best_stream_index = i;
1092 1093
            }
        }
1094
        if (!best_st)
1095
            return AVERROR_EOF;
1096

1097
        best_ast = best_st->priv_data;
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
        best_ts  = av_rescale_q(best_ts,
                                (AVRational) { FFMAX(1, best_ast->sample_size),
                                               AV_TIME_BASE },
                                best_st->time_base);
        if (best_ast->remaining) {
            i = av_index_search_timestamp(best_st,
                                          best_ts,
                                          AVSEEK_FLAG_ANY |
                                          AVSEEK_FLAG_BACKWARD);
        } else {
            i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
            if (i >= 0)
                best_ast->frame_offset = best_st->index_entries[i].timestamp;
1111
        }
1112

1113 1114
        if (i >= 0) {
            int64_t pos = best_st->index_entries[i].pos;
1115
            pos += best_ast->packet_size - best_ast->remaining;
1116
            avio_seek(s->pb, pos + 8, SEEK_SET);
1117

1118 1119
            assert(best_ast->remaining <= best_ast->packet_size);

1120 1121 1122 1123
            avi->stream_index = best_stream_index;
            if (!best_ast->remaining)
                best_ast->packet_size =
                best_ast->remaining   = best_st->index_entries[i].size;
1124 1125
        }
    }
1126

1127
resync:
1128 1129 1130
    if (avi->stream_index >= 0) {
        AVStream *st   = s->streams[avi->stream_index];
        AVIStream *ast = st->priv_data;
1131
        int size, err;
1132

1133
        if (get_subtitle_pkt(s, st, pkt))
1134 1135
            return 0;

1136 1137 1138 1139
        // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
        if (ast->sample_size <= 1)
            size = INT_MAX;
        else if (ast->sample_size < 32)
1140
            // arbitrary multiplier to avoid tiny packets for raw PCM data
1141
            size = 1024 * ast->sample_size;
1142
        else
1143
            size = ast->sample_size;
1144

1145 1146 1147 1148 1149
        if (size > ast->remaining)
            size = ast->remaining;
        avi->last_pkt_pos = avio_tell(pb);
        err               = av_get_packet(pb, pkt, size);
        if (err < 0)
1150
            return err;
1151

1152
        if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
1153
            uint8_t *pal;
1154 1155 1156 1157 1158 1159 1160
            pal = av_packet_new_side_data(pkt,
                                          AV_PKT_DATA_PALETTE,
                                          AVPALETTE_SIZE);
            if (!pal) {
                av_log(s, AV_LOG_ERROR,
                       "Failed to allocate data for palette\n");
            } else {
1161 1162 1163
                memcpy(pal, ast->pal, AVPALETTE_SIZE);
                ast->has_pal = 0;
            }
1164 1165
        }

1166
        if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1167 1168
            AVBufferRef *avbuf = pkt->buf;
#if FF_API_DESTRUCT_PACKET
1169
FF_DISABLE_DEPRECATION_WARNINGS
1170
            dstr = pkt->destruct;
1171
FF_ENABLE_DEPRECATION_WARNINGS
1172
#endif
1173
            size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1174
                                            pkt->data, pkt->size);
1175
#if FF_API_DESTRUCT_PACKET
1176
FF_DISABLE_DEPRECATION_WARNINGS
1177
            pkt->destruct = dstr;
1178
FF_ENABLE_DEPRECATION_WARNINGS
1179
#endif
1180
            pkt->buf    = avbuf;
1181
            pkt->flags |= AV_PKT_FLAG_KEY;
1182 1183
            if (size < 0)
                av_free_packet(pkt);
1184 1185
        } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
                   !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1186 1187
            ast->frame_offset++;
            avi->stream_index = -1;
1188
            ast->remaining    = 0;
1189
            goto resync;
1190
        } else {
Diego Biurrun's avatar
Diego Biurrun committed
1191
            /* XXX: How to handle B-frames in AVI? */
1192 1193
            pkt->dts = ast->frame_offset;
//                pkt->dts += ast->start;
1194
            if (ast->sample_size)
1195
                pkt->dts /= ast->sample_size;
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
            av_dlog(s,
                    "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);
1207 1208
            pkt->stream_index = avi->stream_index;

1209
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
Michael Niedermayer's avatar
Michael Niedermayer committed
1210 1211
                AVIndexEntry *e;
                int index;
1212
                assert(st->index_entries);
1213

1214 1215
                index = av_index_search_timestamp(st, ast->frame_offset, 0);
                e     = &st->index_entries[index];
1216

1217
                if (index >= 0 && e->timestamp == ast->frame_offset)
Michael Niedermayer's avatar
Michael Niedermayer committed
1218
                    if (e->flags & AVINDEX_KEYFRAME)
1219
                        pkt->flags |= AV_PKT_FLAG_KEY;
1220
            } else {
1221
                pkt->flags |= AV_PKT_FLAG_KEY;
1222
            }
1223
            ast->frame_offset += get_duration(ast, pkt->size);
1224
        }
1225
        ast->remaining -= err;
1226 1227 1228
        if (!ast->remaining) {
            avi->stream_index = -1;
            ast->packet_size  = 0;
1229 1230
        }

1231
        return 0;
1232 1233
    }

1234
    if ((err = avi_sync(s, 0)) < 0)
1235 1236
        return err;
    goto resync;
Fabrice Bellard's avatar
Fabrice Bellard committed
1237 1238
}

Diego Biurrun's avatar
Diego Biurrun committed
1239
/* XXX: We make the implicit supposition that the positions are sorted
1240
 * for each stream. */
Fabrice Bellard's avatar
Fabrice Bellard committed
1241 1242
static int avi_read_idx1(AVFormatContext *s, int size)
{
1243
    AVIContext *avi = s->priv_data;
1244
    AVIOContext *pb = s->pb;
Fabrice Bellard's avatar
Fabrice Bellard committed
1245 1246 1247
    int nb_index_entries, i;
    AVStream *st;
    AVIStream *ast;
1248
    unsigned int index, tag, flags, pos, len, first_packet = 1;
1249
    unsigned last_pos = -1;
1250
    int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1251

Fabrice Bellard's avatar
Fabrice Bellard committed
1252 1253
    nb_index_entries = size / 16;
    if (nb_index_entries <= 0)
1254
        return AVERROR_INVALIDDATA;
Fabrice Bellard's avatar
Fabrice Bellard committed
1255

1256
    idx1_pos = avio_tell(pb);
1257 1258
    avio_seek(pb, avi->movi_list + 4, SEEK_SET);
    if (avi_sync(s, 1) == 0)
1259 1260 1261 1262
        first_packet_pos = avio_tell(pb) - 8;
    avi->stream_index = -1;
    avio_seek(pb, idx1_pos, SEEK_SET);

Diego Biurrun's avatar
Diego Biurrun committed
1263
    /* Read the entries and sort them in each stream component. */
1264 1265
    for (i = 0; i < nb_index_entries; i++) {
        tag   = avio_rl32(pb);
1266
        flags = avio_rl32(pb);
1267 1268
        pos   = avio_rl32(pb);
        len   = avio_rl32(pb);
1269 1270
        av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
                i, tag, flags, pos, len);
1271

1272 1273
        index  = ((tag      & 0xff) - '0') * 10;
        index +=  (tag >> 8 & 0xff) - '0';
Fabrice Bellard's avatar
Fabrice Bellard committed
1274 1275
        if (index >= s->nb_streams)
            continue;
1276
        st  = s->streams[index];
Fabrice Bellard's avatar
Fabrice Bellard committed
1277
        ast = st->priv_data;
1278

1279 1280
        if (first_packet && first_packet_pos && len) {
            data_offset  = first_packet_pos - pos;
1281 1282 1283 1284
            first_packet = 0;
        }
        pos += data_offset;

1285 1286
        av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);

1287
        if (pb->eof_reached)
1288
            return AVERROR_INVALIDDATA;
1289

1290 1291 1292 1293 1294
        if (last_pos == pos)
            avi->non_interleaved = 1;
        else if (len || !ast->sample_size)
            av_add_index_entry(st, pos, ast->cum_len, len, 0,
                               (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1295
        ast->cum_len += get_duration(ast, len);
1296
        last_pos      = pos;
Fabrice Bellard's avatar
Fabrice Bellard committed
1297 1298 1299 1300
    }
    return 0;
}

1301 1302
static int guess_ni_flag(AVFormatContext *s)
{
1303
    int i;
1304 1305 1306
    int64_t last_start = 0;
    int64_t first_end  = INT64_MAX;
    int64_t oldpos     = avio_tell(s->pb);
1307

1308
    for (i = 0; i < s->nb_streams; i++) {
1309
        AVStream *st = s->streams[i];
1310
        int n        = st->nb_index_entries;
1311
        unsigned int size;
1312

1313
        if (n <= 0)
1314 1315
            continue;

1316 1317
        if (n >= 2) {
            int64_t pos = st->index_entries[0].pos;
1318
            avio_seek(s->pb, pos + 4, SEEK_SET);
1319 1320 1321
            size = avio_rl32(s->pb);
            if (pos + size > st->index_entries[1].pos)
                last_start = INT64_MAX;
1322 1323
        }

1324 1325 1326 1327
        if (st->index_entries[0].pos > last_start)
            last_start = st->index_entries[0].pos;
        if (st->index_entries[n - 1].pos < first_end)
            first_end = st->index_entries[n - 1].pos;
1328
    }
1329
    avio_seek(s->pb, oldpos, SEEK_SET);
1330 1331 1332
    return last_start > first_end;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
1333 1334 1335
static int avi_load_index(AVFormatContext *s)
{
    AVIContext *avi = s->priv_data;
1336
    AVIOContext *pb = s->pb;
Fabrice Bellard's avatar
Fabrice Bellard committed
1337
    uint32_t tag, size;
1338 1339
    int64_t pos = avio_tell(pb);
    int ret     = -1;
1340

1341
    if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1342
        goto the_end; // maybe truncated file
1343
    av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1344
    for (;;) {
Anton Khirnov's avatar
Anton Khirnov committed
1345
        if (pb->eof_reached)
Fabrice Bellard's avatar
Fabrice Bellard committed
1346
            break;
1347
        tag  = avio_rl32(pb);
1348
        size = avio_rl32(pb);
1349 1350 1351 1352 1353 1354
        av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
                 tag        & 0xff,
                (tag >>  8) & 0xff,
                (tag >> 16) & 0xff,
                (tag >> 24) & 0xff,
                size);
1355 1356 1357

        if (tag == MKTAG('i', 'd', 'x', '1') &&
            avi_read_idx1(s, size) >= 0) {
1358
            ret = 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
1359 1360
            break;
        }
1361 1362 1363 1364

        size += (size & 1);
        if (avio_skip(pb, size) < 0)
            break; // something is wrong here
Fabrice Bellard's avatar
Fabrice Bellard committed
1365
    }
1366 1367

the_end:
1368
    avio_seek(pb, pos, SEEK_SET);
1369
    return ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
1370 1371
}

1372 1373 1374
static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
{
    AVIStream *ast2 = st2->priv_data;
1375
    int64_t ts2     = av_rescale_q(timestamp, st->time_base, st2->time_base);
1376 1377 1378
    av_free_packet(&ast2->sub_pkt);
    if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
        avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1379
        ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1380 1381
}

1382 1383
static int avi_read_seek(AVFormatContext *s, int stream_index,
                         int64_t timestamp, int flags)
Fabrice Bellard's avatar
Fabrice Bellard committed
1384 1385 1386
{
    AVIContext *avi = s->priv_data;
    AVStream *st;
1387
    int i, index;
Fabrice Bellard's avatar
Fabrice Bellard committed
1388
    int64_t pos;
1389
    AVIStream *ast;
Fabrice Bellard's avatar
Fabrice Bellard committed
1390 1391 1392 1393 1394 1395

    if (!avi->index_loaded) {
        /* we only load the index on demand */
        avi_load_index(s);
        avi->index_loaded = 1;
    }
1396 1397 1398 1399 1400 1401 1402 1403
    assert(stream_index >= 0);

    st    = s->streams[stream_index];
    ast   = st->priv_data;
    index = av_index_search_timestamp(st,
                                      timestamp * FFMAX(ast->sample_size, 1),
                                      flags);
    if (index < 0)
1404
        return AVERROR_INVALIDDATA;
1405

Fabrice Bellard's avatar
Fabrice Bellard committed
1406
    /* find the position */
1407
    pos       = st->index_entries[index].pos;
1408
    timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1409

1410 1411
    av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
            timestamp, index, st->index_entries[index].timestamp);
Fabrice Bellard's avatar
Fabrice Bellard committed
1412

1413
    if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1414
        /* One and only one real stream for DV in AVI, and it has video  */
1415
        /* offsets. Calling with other stream indexes should have failed */
1416 1417 1418 1419
        /* the av_index_search_timestamp call above.                     */
        assert(stream_index == 0);

        /* Feed the DV video stream version of the timestamp to the */
Diego Biurrun's avatar
Diego Biurrun committed
1420
        /* DV demux so it can synthesize correct timestamps.        */
1421
        ff_dv_offset_reset(avi->dv_demux, timestamp);
1422

1423
        avio_seek(s->pb, pos, SEEK_SET);
1424
        avi->stream_index = -1;
1425 1426 1427
        return 0;
    }

1428 1429
    for (i = 0; i < s->nb_streams; i++) {
        AVStream *st2   = s->streams[i];
1430
        AVIStream *ast2 = st2->priv_data;
1431

1432 1433
        ast2->packet_size =
        ast2->remaining   = 0;
1434

1435 1436 1437 1438 1439
        if (ast2->sub_ctx) {
            seek_subtitle(st, st2, timestamp);
            continue;
        }

1440 1441
        if (st2->nb_index_entries <= 0)
            continue;
1442

1443
//        assert(st2->codec->block_align);
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
        assert((int64_t)st2->time_base.num * ast2->rate ==
               (int64_t)st2->time_base.den * ast2->scale);
        index = av_index_search_timestamp(st2,
                                          av_rescale_q(timestamp,
                                                       st->time_base,
                                                       st2->time_base) *
                                          FFMAX(ast2->sample_size, 1),
                                          flags | AVSEEK_FLAG_BACKWARD);
        if (index < 0)
            index = 0;

        if (!avi->non_interleaved) {
            while (index > 0 && st2->index_entries[index].pos > pos)
1457
                index--;
1458 1459
            while (index + 1 < st2->nb_index_entries &&
                   st2->index_entries[index].pos < pos)
1460 1461 1462
                index++;
        }

1463 1464
        av_dlog(s, "%"PRId64" %d %"PRId64"\n",
                timestamp, index, st2->index_entries[index].timestamp);
1465 1466
        /* extract the current frame number */
        ast2->frame_offset = st2->index_entries[index].timestamp;
Fabrice Bellard's avatar
Fabrice Bellard committed
1467
    }
1468

Fabrice Bellard's avatar
Fabrice Bellard committed
1469
    /* do the seek */
1470
    avio_seek(s->pb, pos, SEEK_SET);
1471
    avi->stream_index = -1;
Fabrice Bellard's avatar
Fabrice Bellard committed
1472 1473 1474
    return 0;
}

1475
static int avi_read_close(AVFormatContext *s)
Fabrice Bellard's avatar
Fabrice Bellard committed
1476
{
Michael Niedermayer's avatar
Michael Niedermayer committed
1477 1478 1479
    int i;
    AVIContext *avi = s->priv_data;

1480 1481
    for (i = 0; i < s->nb_streams; i++) {
        AVStream *st   = s->streams[i];
1482
        AVIStream *ast = st->priv_data;
1483
        if (ast) {
1484 1485
            if (ast->sub_ctx) {
                av_freep(&ast->sub_ctx->pb);
1486
                avformat_close_input(&ast->sub_ctx);
1487 1488 1489
            }
            av_free(ast->sub_buffer);
            av_free_packet(&ast->sub_pkt);
1490
        }
Michael Niedermayer's avatar
Michael Niedermayer committed
1491 1492
    }

1493
    av_free(avi->dv_demux);
1494

Fabrice Bellard's avatar
Fabrice Bellard committed
1495 1496 1497 1498 1499
    return 0;
}

static int avi_probe(AVProbeData *p)
{
1500 1501
    int i;

Fabrice Bellard's avatar
Fabrice Bellard committed
1502
    /* check file header */
1503 1504 1505
    for (i = 0; avi_headers[i][0]; i++)
        if (!memcmp(p->buf,     avi_headers[i],     4) &&
            !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
1506 1507 1508
            return AVPROBE_SCORE_MAX;

    return 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
1509 1510
}

1511
AVInputFormat ff_avi_demuxer = {
1512
    .name           = "avi",
1513
    .long_name      = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1514 1515 1516 1517 1518 1519
    .priv_data_size = sizeof(AVIContext),
    .read_probe     = avi_probe,
    .read_header    = avi_read_header,
    .read_packet    = avi_read_packet,
    .read_close     = avi_read_close,
    .read_seek      = avi_read_seek,
Fabrice Bellard's avatar
Fabrice Bellard committed
1520
};