Statistics
| Branch: | Revision:

ffmpeg / libavformat / avidec.c @ 5e9de76f

History | View | Annotate | Download (46 KB)

1
/*
2
 * AVI demuxer
3
 * Copyright (c) 2001 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

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

    
25
#include <strings.h>
26
#include "libavutil/intreadwrite.h"
27
#include "libavutil/bswap.h"
28
#include "avformat.h"
29
#include "avi.h"
30
#include "dv.h"
31
#include "riff.h"
32

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

    
36
typedef struct AVIStream {
37
    int64_t frame_offset; /* current frame (video) or byte (audio) counter
38
                         (used to compute the pts) */
39
    int remaining;
40
    int packet_size;
41

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

    
46
    int64_t cum_len; /* temporary storage (used during seek) */
47

    
48
    int prefix;                       ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
49
    int prefix_count;
50
    uint32_t pal[256];
51
    int has_pal;
52
    int dshow_block_align;            ///< block align variable used to emulate bugs in the MS dshow demuxer
53

    
54
    AVFormatContext *sub_ctx;
55
    AVPacket sub_pkt;
56
    uint8_t *sub_buffer;
57

    
58
    int64_t seek_pos;
59
} AVIStream;
60

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

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

    
85
static int avi_load_index(AVFormatContext *s);
86
static int guess_ni_flag(AVFormatContext *s);
87

    
88
#define print_tag(str, tag, size)                       \
89
    av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n",       \
90
           str, tag & 0xff,                             \
91
           (tag >> 8) & 0xff,                           \
92
           (tag >> 16) & 0xff,                          \
93
           (tag >> 24) & 0xff,                          \
94
           size)
95

    
96
static inline int get_duration(AVIStream *ast, int len){
97
    if(ast->sample_size){
98
        return len;
99
    }else if (ast->dshow_block_align){
100
        return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
101
    }else
102
        return 1;
103
}
104

    
105
static int get_riff(AVFormatContext *s, AVIOContext *pb)
106
{
107
    AVIContext *avi = s->priv_data;
108
    char header[8];
109
    int i;
110

    
111
    /* check RIFF header */
112
    avio_read(pb, header, 4);
113
    avi->riff_end = avio_rl32(pb);  /* RIFF chunk size */
114
    avi->riff_end += avio_tell(pb); /* RIFF chunk end */
115
    avio_read(pb, header+4, 4);
116

    
117
    for(i=0; avi_headers[i][0]; i++)
118
        if(!memcmp(header, avi_headers[i], 8))
119
            break;
120
    if(!avi_headers[i][0])
121
        return -1;
122

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

    
126
    return 0;
127
}
128

    
129
static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
130
    AVIContext *avi = s->priv_data;
131
    AVIOContext *pb = s->pb;
132
    int longs_pre_entry= avio_rl16(pb);
133
    int index_sub_type = avio_r8(pb);
134
    int index_type     = avio_r8(pb);
135
    int entries_in_use = avio_rl32(pb);
136
    int chunk_id       = avio_rl32(pb);
137
    int64_t base       = avio_rl64(pb);
138
    int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
139
    AVStream *st;
140
    AVIStream *ast;
141
    int i;
142
    int64_t last_pos= -1;
143
    int64_t filesize= avio_size(s->pb);
144

    
145
#ifdef DEBUG_SEEK
146
    av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
147
        longs_pre_entry,index_type, entries_in_use, chunk_id, base);
148
#endif
149

    
150
    if(stream_id >= s->nb_streams || stream_id < 0)
151
        return -1;
152
    st= s->streams[stream_id];
153
    ast = st->priv_data;
154

    
155
    if(index_sub_type)
156
        return -1;
157

    
158
    avio_rl32(pb);
159

    
160
    if(index_type && longs_pre_entry != 2)
161
        return -1;
162
    if(index_type>1)
163
        return -1;
164

    
165
    if(filesize > 0 && base >= filesize){
166
        av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
167
        if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
168
            base &= 0xFFFFFFFF;
169
        else
170
            return -1;
171
    }
172

    
173
    for(i=0; i<entries_in_use; i++){
174
        if(index_type){
175
            int64_t pos= avio_rl32(pb) + base - 8;
176
            int len    = avio_rl32(pb);
177
            int key= len >= 0;
178
            len &= 0x7FFFFFFF;
179

    
180
#ifdef DEBUG_SEEK
181
            av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
182
#endif
183
            if(url_feof(pb))
184
                return -1;
185

    
186
            if(last_pos == pos || pos == base - 8)
187
                avi->non_interleaved= 1;
188
            if(last_pos != pos && (len || !ast->sample_size))
189
                av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
190

    
191
            ast->cum_len += get_duration(ast, len);
192
            last_pos= pos;
193
        }else{
194
            int64_t offset, pos;
195
            int duration;
196
            offset = avio_rl64(pb);
197
            avio_rl32(pb);       /* size */
198
            duration = avio_rl32(pb);
199

    
200
            if(url_feof(pb))
201
                return -1;
202

    
203
            pos = avio_tell(pb);
204

    
205
            if(avi->odml_depth > MAX_ODML_DEPTH){
206
                av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
207
                return -1;
208
            }
209

    
210
            avio_seek(pb, offset+8, SEEK_SET);
211
            avi->odml_depth++;
212
            read_braindead_odml_indx(s, frame_num);
213
            avi->odml_depth--;
214
            frame_num += duration;
215

    
216
            avio_seek(pb, pos, SEEK_SET);
217
        }
218
    }
219
    avi->index_loaded=1;
220
    return 0;
221
}
222

    
223
static void clean_index(AVFormatContext *s){
224
    int i;
225
    int64_t j;
226

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

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

    
237
        while(max < 1024) max+=max;
238

    
239
        pos= st->index_entries[0].pos;
240
        size= st->index_entries[0].size;
241
        ts= st->index_entries[0].timestamp;
242

    
243
        for(j=0; j<size; j+=max){
244
            av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
245
        }
246
    }
247
}
248

    
249
static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
250
{
251
    AVIOContext *pb = s->pb;
252
    char key[5] = {0}, *value;
253

    
254
    size += (size & 1);
255

    
256
    if (size == UINT_MAX)
257
        return -1;
258
    value = av_malloc(size+1);
259
    if (!value)
260
        return -1;
261
    avio_read(pb, value, size);
262
    value[size]=0;
263

    
264
    AV_WL32(key, tag);
265

    
266
    return av_metadata_set2(st ? &st->metadata : &s->metadata, key, value,
267
                            AV_METADATA_DONT_STRDUP_VAL);
268
}
269

    
270
static void avi_read_info(AVFormatContext *s, uint64_t end)
271
{
272
    while (avio_tell(s->pb) < end) {
273
        uint32_t tag  = avio_rl32(s->pb);
274
        uint32_t size = avio_rl32(s->pb);
275
        avi_read_tag(s, NULL, tag, size);
276
    }
277
}
278

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

    
282
static void avi_metadata_creation_time(AVMetadata **metadata, char *date)
283
{
284
    char month[4], time[9], buffer[64];
285
    int i, day, year;
286
    /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
287
    if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
288
               month, &day, time, &year) == 4) {
289
        for (i=0; i<12; i++)
290
            if (!strcasecmp(month, months[i])) {
291
                snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
292
                         year, i+1, day, time);
293
                av_metadata_set2(metadata, "creation_time", buffer, 0);
294
            }
295
    } else if (date[4] == '/' && date[7] == '/') {
296
        date[4] = date[7] = '-';
297
        av_metadata_set2(metadata, "creation_time", date, 0);
298
    }
299
}
300

    
301
static void avi_read_nikon(AVFormatContext *s, uint64_t end)
302
{
303
    while (avio_tell(s->pb) < end) {
304
        uint32_t tag  = avio_rl32(s->pb);
305
        uint32_t size = avio_rl32(s->pb);
306
        switch (tag) {
307
        case MKTAG('n', 'c', 't', 'g'): {  /* Nikon Tags */
308
            uint64_t tag_end = avio_tell(s->pb) + size;
309
            while (avio_tell(s->pb) < tag_end) {
310
                uint16_t tag  = avio_rl16(s->pb);
311
                uint16_t size = avio_rl16(s->pb);
312
                const char *name = NULL;
313
                char buffer[64] = {0};
314
                size -= avio_read(s->pb, buffer,
315
                                   FFMIN(size, sizeof(buffer)-1));
316
                switch (tag) {
317
                case 0x03:  name = "maker";  break;
318
                case 0x04:  name = "model";  break;
319
                case 0x13:  name = "creation_time";
320
                    if (buffer[4] == ':' && buffer[7] == ':')
321
                        buffer[4] = buffer[7] = '-';
322
                    break;
323
                }
324
                if (name)
325
                    av_metadata_set2(&s->metadata, name, buffer, 0);
326
                avio_skip(s->pb, size);
327
            }
328
            break;
329
        }
330
        default:
331
            avio_skip(s->pb, size);
332
            break;
333
        }
334
    }
335
}
336

    
337
static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
338
{
339
    AVIContext *avi = s->priv_data;
340
    AVIOContext *pb = s->pb;
341
    unsigned int tag, tag1, handler;
342
    int codec_type, stream_index, frame_period, bit_rate;
343
    unsigned int size;
344
    int i;
345
    AVStream *st;
346
    AVIStream *ast = NULL;
347
    int avih_width=0, avih_height=0;
348
    int amv_file_format=0;
349
    uint64_t list_end = 0;
350
    int ret;
351

    
352
    avi->stream_index= -1;
353

    
354
    if (get_riff(s, pb) < 0)
355
        return -1;
356

    
357
    avi->fsize = avio_size(pb);
358
    if(avi->fsize<=0)
359
        avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
360

    
361
    /* first list tag */
362
    stream_index = -1;
363
    codec_type = -1;
364
    frame_period = 0;
365
    for(;;) {
366
        if (url_feof(pb))
367
            goto fail;
368
        tag = avio_rl32(pb);
369
        size = avio_rl32(pb);
370

    
371
        print_tag("tag", tag, size);
372

    
373
        switch(tag) {
374
        case MKTAG('L', 'I', 'S', 'T'):
375
            list_end = avio_tell(pb) + size;
376
            /* Ignored, except at start of video packets. */
377
            tag1 = avio_rl32(pb);
378

    
379
            print_tag("list", tag1, 0);
380

    
381
            if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
382
                avi->movi_list = avio_tell(pb) - 4;
383
                if(size) avi->movi_end = avi->movi_list + size + (size & 1);
384
                else     avi->movi_end = avio_size(pb);
385
                av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
386
                goto end_of_header;
387
            }
388
            else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
389
                avi_read_info(s, list_end);
390
            else if (tag1 == MKTAG('n', 'c', 'd', 't'))
391
                avi_read_nikon(s, list_end);
392

    
393
            break;
394
        case MKTAG('I', 'D', 'I', 'T'): {
395
            unsigned char date[64] = {0};
396
            size += (size & 1);
397
            size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
398
            avio_skip(pb, size);
399
            avi_metadata_creation_time(&s->metadata, date);
400
            break;
401
        }
402
        case MKTAG('d', 'm', 'l', 'h'):
403
            avi->is_odml = 1;
404
            avio_skip(pb, size + (size & 1));
405
            break;
406
        case MKTAG('a', 'm', 'v', 'h'):
407
            amv_file_format=1;
408
        case MKTAG('a', 'v', 'i', 'h'):
409
            /* AVI header */
410
            /* using frame_period is bad idea */
411
            frame_period = avio_rl32(pb);
412
            bit_rate = avio_rl32(pb) * 8;
413
            avio_rl32(pb);
414
            avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
415

    
416
            avio_skip(pb, 2 * 4);
417
            avio_rl32(pb);
418
            avio_rl32(pb);
419
            avih_width=avio_rl32(pb);
420
            avih_height=avio_rl32(pb);
421

    
422
            avio_skip(pb, size - 10 * 4);
423
            break;
424
        case MKTAG('s', 't', 'r', 'h'):
425
            /* stream header */
426

    
427
            tag1 = avio_rl32(pb);
428
            handler = avio_rl32(pb); /* codec tag */
429

    
430
            if(tag1 == MKTAG('p', 'a', 'd', 's')){
431
                avio_skip(pb, size - 8);
432
                break;
433
            }else{
434
                stream_index++;
435
                st = av_new_stream(s, stream_index);
436
                if (!st)
437
                    goto fail;
438

    
439
                ast = av_mallocz(sizeof(AVIStream));
440
                if (!ast)
441
                    goto fail;
442
                st->priv_data = ast;
443
            }
444
            if(amv_file_format)
445
                tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
446

    
447
            print_tag("strh", tag1, -1);
448

    
449
            if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
450
                int64_t dv_dur;
451

    
452
                /*
453
                 * After some consideration -- I don't think we
454
                 * have to support anything but DV in type1 AVIs.
455
                 */
456
                if (s->nb_streams != 1)
457
                    goto fail;
458

    
459
                if (handler != MKTAG('d', 'v', 's', 'd') &&
460
                    handler != MKTAG('d', 'v', 'h', 'd') &&
461
                    handler != MKTAG('d', 'v', 's', 'l'))
462
                   goto fail;
463

    
464
                ast = s->streams[0]->priv_data;
465
                av_freep(&s->streams[0]->codec->extradata);
466
                av_freep(&s->streams[0]->codec);
467
                av_freep(&s->streams[0]);
468
                s->nb_streams = 0;
469
                if (CONFIG_DV_DEMUXER) {
470
                    avi->dv_demux = dv_init_demux(s);
471
                    if (!avi->dv_demux)
472
                        goto fail;
473
                }
474
                s->streams[0]->priv_data = ast;
475
                avio_skip(pb, 3 * 4);
476
                ast->scale = avio_rl32(pb);
477
                ast->rate = avio_rl32(pb);
478
                avio_skip(pb, 4);  /* start time */
479

    
480
                dv_dur = avio_rl32(pb);
481
                if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
482
                    dv_dur *= AV_TIME_BASE;
483
                    s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
484
                }
485
                /*
486
                 * else, leave duration alone; timing estimation in utils.c
487
                 *      will make a guess based on bitrate.
488
                 */
489

    
490
                stream_index = s->nb_streams - 1;
491
                avio_skip(pb, size - 9*4);
492
                break;
493
            }
494

    
495
            assert(stream_index < s->nb_streams);
496
            st->codec->stream_codec_tag= handler;
497

    
498
            avio_rl32(pb); /* flags */
499
            avio_rl16(pb); /* priority */
500
            avio_rl16(pb); /* language */
501
            avio_rl32(pb); /* initial frame */
502
            ast->scale = avio_rl32(pb);
503
            ast->rate = avio_rl32(pb);
504
            if(!(ast->scale && ast->rate)){
505
                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);
506
                if(frame_period){
507
                    ast->rate = 1000000;
508
                    ast->scale = frame_period;
509
                }else{
510
                    ast->rate = 25;
511
                    ast->scale = 1;
512
                }
513
            }
514
            av_set_pts_info(st, 64, ast->scale, ast->rate);
515

    
516
            ast->cum_len=avio_rl32(pb); /* start */
517
            st->nb_frames = avio_rl32(pb);
518

    
519
            st->start_time = 0;
520
            avio_rl32(pb); /* buffer size */
521
            avio_rl32(pb); /* quality */
522
            ast->sample_size = avio_rl32(pb); /* sample ssize */
523
            ast->cum_len *= FFMAX(1, ast->sample_size);
524
//            av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
525

    
526
            switch(tag1) {
527
            case MKTAG('v', 'i', 'd', 's'):
528
                codec_type = AVMEDIA_TYPE_VIDEO;
529

    
530
                ast->sample_size = 0;
531
                break;
532
            case MKTAG('a', 'u', 'd', 's'):
533
                codec_type = AVMEDIA_TYPE_AUDIO;
534
                break;
535
            case MKTAG('t', 'x', 't', 's'):
536
                codec_type = AVMEDIA_TYPE_SUBTITLE;
537
                break;
538
            case MKTAG('d', 'a', 't', 's'):
539
                codec_type = AVMEDIA_TYPE_DATA;
540
                break;
541
            default:
542
                av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
543
                goto fail;
544
            }
545
            if(ast->sample_size == 0)
546
                st->duration = st->nb_frames;
547
            ast->frame_offset= ast->cum_len;
548
            avio_skip(pb, size - 12 * 4);
549
            break;
550
        case MKTAG('s', 't', 'r', 'f'):
551
            /* stream header */
552
            if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
553
                avio_skip(pb, size);
554
            } else {
555
                uint64_t cur_pos = avio_tell(pb);
556
                if (cur_pos < list_end)
557
                    size = FFMIN(size, list_end - cur_pos);
558
                st = s->streams[stream_index];
559
                switch(codec_type) {
560
                case AVMEDIA_TYPE_VIDEO:
561
                    if(amv_file_format){
562
                        st->codec->width=avih_width;
563
                        st->codec->height=avih_height;
564
                        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
565
                        st->codec->codec_id = CODEC_ID_AMV;
566
                        avio_skip(pb, size);
567
                        break;
568
                    }
569
                    tag1 = ff_get_bmp_header(pb, st);
570

    
571
                    if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
572
                        st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
573
                        st->codec->codec_tag = tag1;
574
                        st->codec->codec_id = CODEC_ID_XSUB;
575
                        break;
576
                    }
577

    
578
                    if(size > 10*4 && size<(1<<30)){
579
                        st->codec->extradata_size= size - 10*4;
580
                        st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
581
                        if (!st->codec->extradata) {
582
                            st->codec->extradata_size= 0;
583
                            return AVERROR(ENOMEM);
584
                        }
585
                        avio_read(pb, st->codec->extradata, st->codec->extradata_size);
586
                    }
587

    
588
                    if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
589
                        avio_r8(pb);
590

    
591
                    /* Extract palette from extradata if bpp <= 8. */
592
                    /* This code assumes that extradata contains only palette. */
593
                    /* This is true for all paletted codecs implemented in FFmpeg. */
594
                    if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
595
#if HAVE_BIGENDIAN
596
                        for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
597
                            ast->pal[i] = av_bswap32(((uint32_t*)st->codec->extradata)[i]);
598
#else
599
                        memcpy(ast->pal, st->codec->extradata,
600
                               FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
601
#endif
602
                        ast->has_pal = 1;
603
                    }
604

    
605
                    print_tag("video", tag1, 0);
606

    
607
                    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
608
                    st->codec->codec_tag = tag1;
609
                    st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
610
                    st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
611
                    // Support "Resolution 1:1" for Avid AVI Codec
612
                    if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
613
                       st->codec->extradata_size >= 31 &&
614
                       !memcmp(&st->codec->extradata[28], "1:1", 3))
615
                        st->codec->codec_id = CODEC_ID_RAWVIDEO;
616

    
617
                    if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
618
                        st->codec->extradata_size+= 9;
619
                        st->codec->extradata= av_realloc(st->codec->extradata, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
620
                        if(st->codec->extradata)
621
                            memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
622
                    }
623
                    st->codec->height= FFABS(st->codec->height);
624

    
625
//                    avio_skip(pb, size - 5 * 4);
626
                    break;
627
                case AVMEDIA_TYPE_AUDIO:
628
                    ret = ff_get_wav_header(pb, st->codec, size);
629
                    if (ret < 0)
630
                        return ret;
631
                    ast->dshow_block_align= st->codec->block_align;
632
                    if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
633
                        av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
634
                        ast->sample_size= st->codec->block_align;
635
                    }
636
                    if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
637
                        avio_skip(pb, 1);
638
                    /* Force parsing as several audio frames can be in
639
                     * one packet and timestamps refer to packet start. */
640
                    st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
641
                    /* ADTS header is in extradata, AAC without header must be
642
                     * stored as exact frames. Parser not needed and it will
643
                     * fail. */
644
                    if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
645
                        st->need_parsing = AVSTREAM_PARSE_NONE;
646
                    /* AVI files with Xan DPCM audio (wrongly) declare PCM
647
                     * audio in the header but have Axan as stream_code_tag. */
648
                    if (st->codec->stream_codec_tag == AV_RL32("Axan")){
649
                        st->codec->codec_id  = CODEC_ID_XAN_DPCM;
650
                        st->codec->codec_tag = 0;
651
                    }
652
                    if (amv_file_format){
653
                        st->codec->codec_id  = CODEC_ID_ADPCM_IMA_AMV;
654
                        ast->dshow_block_align = 0;
655
                    }
656
                    break;
657
                case AVMEDIA_TYPE_SUBTITLE:
658
                    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
659
                    st->request_probe= 1;
660
                    break;
661
                default:
662
                    st->codec->codec_type = AVMEDIA_TYPE_DATA;
663
                    st->codec->codec_id= CODEC_ID_NONE;
664
                    st->codec->codec_tag= 0;
665
                    avio_skip(pb, size);
666
                    break;
667
                }
668
            }
669
            break;
670
        case MKTAG('i', 'n', 'd', 'x'):
671
            i= avio_tell(pb);
672
            if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX)){
673
                read_braindead_odml_indx(s, 0);
674
            }
675
            avio_seek(pb, i+size, SEEK_SET);
676
            break;
677
        case MKTAG('v', 'p', 'r', 'p'):
678
            if(stream_index < (unsigned)s->nb_streams && size > 9*4){
679
                AVRational active, active_aspect;
680

    
681
                st = s->streams[stream_index];
682
                avio_rl32(pb);
683
                avio_rl32(pb);
684
                avio_rl32(pb);
685
                avio_rl32(pb);
686
                avio_rl32(pb);
687

    
688
                active_aspect.den= avio_rl16(pb);
689
                active_aspect.num= avio_rl16(pb);
690
                active.num       = avio_rl32(pb);
691
                active.den       = avio_rl32(pb);
692
                avio_rl32(pb); //nbFieldsPerFrame
693

    
694
                if(active_aspect.num && active_aspect.den && active.num && active.den){
695
                    st->sample_aspect_ratio= av_div_q(active_aspect, active);
696
//av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
697
                }
698
                size -= 9*4;
699
            }
700
            avio_skip(pb, size);
701
            break;
702
        case MKTAG('s', 't', 'r', 'n'):
703
            if(s->nb_streams){
704
                avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
705
                break;
706
            }
707
        default:
708
            if(size > 1000000){
709
                av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
710
                                        "I will ignore it and try to continue anyway.\n");
711
                avi->movi_list = avio_tell(pb) - 4;
712
                avi->movi_end  = avio_size(pb);
713
                goto end_of_header;
714
            }
715
            /* skip tag */
716
            size += (size & 1);
717
            avio_skip(pb, size);
718
            break;
719
        }
720
    }
721
 end_of_header:
722
    /* check stream number */
723
    if (stream_index != s->nb_streams - 1) {
724
    fail:
725
        return -1;
726
    }
727

    
728
    if(!avi->index_loaded && pb->seekable)
729
        avi_load_index(s);
730
    avi->index_loaded = 1;
731
    avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
732
    for(i=0; i<s->nb_streams; i++){
733
        AVStream *st = s->streams[i];
734
        if(st->nb_index_entries)
735
            break;
736
    }
737
    // DV-in-AVI cannot be non-interleaved, if set this must be
738
    // a mis-detection.
739
    if(avi->dv_demux)
740
        avi->non_interleaved=0;
741
    if(i==s->nb_streams && avi->non_interleaved) {
742
        av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
743
        avi->non_interleaved=0;
744
    }
745

    
746
    if(avi->non_interleaved) {
747
        av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
748
        clean_index(s);
749
    }
750

    
751
    ff_metadata_conv_ctx(s, NULL, ff_avi_metadata_conv);
752

    
753
    return 0;
754
}
755

    
756
static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
757
    if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
758
        uint8_t desc[256];
759
        int score = AVPROBE_SCORE_MAX / 2, ret;
760
        AVIStream *ast = st->priv_data;
761
        AVInputFormat *sub_demuxer;
762
        AVRational time_base;
763
        AVIOContext *pb = avio_alloc_context( pkt->data + 7,
764
                                              pkt->size - 7,
765
                                              0, NULL, NULL, NULL, NULL);
766
        AVProbeData pd;
767
        unsigned int desc_len = avio_rl32(pb);
768

    
769
        if (desc_len > pb->buf_end - pb->buf_ptr)
770
            goto error;
771

    
772
        ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
773
        avio_skip(pb, desc_len - ret);
774
        if (*desc)
775
            av_metadata_set2(&st->metadata, "title", desc, 0);
776

    
777
        avio_rl16(pb);   /* flags? */
778
        avio_rl32(pb);   /* data size */
779

    
780
        pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
781
        if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
782
            goto error;
783

    
784
        if (!av_open_input_stream(&ast->sub_ctx, pb, "", sub_demuxer, NULL)) {
785
            av_read_packet(ast->sub_ctx, &ast->sub_pkt);
786
            *st->codec = *ast->sub_ctx->streams[0]->codec;
787
            ast->sub_ctx->streams[0]->codec->extradata = NULL;
788
            time_base = ast->sub_ctx->streams[0]->time_base;
789
            av_set_pts_info(st, 64, time_base.num, time_base.den);
790
        }
791
        ast->sub_buffer = pkt->data;
792
        memset(pkt, 0, sizeof(*pkt));
793
        return 1;
794
error:
795
        av_freep(&pb);
796
    }
797
    return 0;
798
}
799

    
800
static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
801
                                  AVPacket *pkt)
802
{
803
    AVIStream *ast, *next_ast = next_st->priv_data;
804
    int64_t ts, next_ts, ts_min = INT64_MAX;
805
    AVStream *st, *sub_st = NULL;
806
    int i;
807

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

    
811
    for (i=0; i<s->nb_streams; i++) {
812
        st  = s->streams[i];
813
        ast = st->priv_data;
814
        if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
815
            ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
816
            if (ts <= next_ts && ts < ts_min) {
817
                ts_min = ts;
818
                sub_st = st;
819
            }
820
        }
821
    }
822

    
823
    if (sub_st) {
824
        ast = sub_st->priv_data;
825
        *pkt = ast->sub_pkt;
826
        pkt->stream_index = sub_st->index;
827
        if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
828
            ast->sub_pkt.data = NULL;
829
    }
830
    return sub_st;
831
}
832

    
833
static int get_stream_idx(int *d){
834
    if(    d[0] >= '0' && d[0] <= '9'
835
        && d[1] >= '0' && d[1] <= '9'){
836
        return (d[0] - '0') * 10 + (d[1] - '0');
837
    }else{
838
        return 100; //invalid stream ID
839
    }
840
}
841

    
842
static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
843
{
844
    AVIContext *avi = s->priv_data;
845
    AVIOContext *pb = s->pb;
846
    int n, d[8];
847
    unsigned int size;
848
    int64_t i, sync;
849
    void* dstr;
850

    
851
    if (CONFIG_DV_DEMUXER && avi->dv_demux) {
852
        int size = dv_get_packet(avi->dv_demux, pkt);
853
        if (size >= 0)
854
            return size;
855
    }
856

    
857
    if(avi->non_interleaved){
858
        int best_stream_index = 0;
859
        AVStream *best_st= NULL;
860
        AVIStream *best_ast;
861
        int64_t best_ts= INT64_MAX;
862
        int i;
863

    
864
        for(i=0; i<s->nb_streams; i++){
865
            AVStream *st = s->streams[i];
866
            AVIStream *ast = st->priv_data;
867
            int64_t ts= ast->frame_offset;
868
            int64_t last_ts;
869

    
870
            if(!st->nb_index_entries)
871
                continue;
872

    
873
            last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
874
            if(!ast->remaining && ts > last_ts)
875
                continue;
876

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

    
879
//            av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
880
            if(ts < best_ts){
881
                best_ts= ts;
882
                best_st= st;
883
                best_stream_index= i;
884
            }
885
        }
886
        if(!best_st)
887
            return -1;
888

    
889
        best_ast = best_st->priv_data;
890
        best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
891
        if(best_ast->remaining)
892
            i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
893
        else{
894
            i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
895
            if(i>=0)
896
                best_ast->frame_offset= best_st->index_entries[i].timestamp;
897
        }
898

    
899
//        av_log(s, AV_LOG_DEBUG, "%d\n", i);
900
        if(i>=0){
901
            int64_t pos= best_st->index_entries[i].pos;
902
            pos += best_ast->packet_size - best_ast->remaining;
903
            avio_seek(s->pb, pos + 8, SEEK_SET);
904
//        av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
905

    
906
            assert(best_ast->remaining <= best_ast->packet_size);
907

    
908
            avi->stream_index= best_stream_index;
909
            if(!best_ast->remaining)
910
                best_ast->packet_size=
911
                best_ast->remaining= best_st->index_entries[i].size;
912
        }
913
    }
914

    
915
resync:
916
    if(avi->stream_index >= 0){
917
        AVStream *st= s->streams[ avi->stream_index ];
918
        AVIStream *ast= st->priv_data;
919
        int size, err;
920

    
921
        if(get_subtitle_pkt(s, st, pkt))
922
            return 0;
923

    
924
        if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
925
            size= INT_MAX;
926
        else if(ast->sample_size < 32)
927
            // arbitrary multiplier to avoid tiny packets for raw PCM data
928
            size= 1024*ast->sample_size;
929
        else
930
            size= ast->sample_size;
931

    
932
        if(size > ast->remaining)
933
            size= ast->remaining;
934
        avi->last_pkt_pos= avio_tell(pb);
935
        err= av_get_packet(pb, pkt, size);
936
        if(err<0)
937
            return err;
938

    
939
        if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
940
            uint8_t *pal;
941
            pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
942
            if(!pal){
943
                av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
944
            }else{
945
                memcpy(pal, ast->pal, AVPALETTE_SIZE);
946
                ast->has_pal = 0;
947
            }
948
        }
949

    
950
        if (CONFIG_DV_DEMUXER && avi->dv_demux) {
951
            dstr = pkt->destruct;
952
            size = dv_produce_packet(avi->dv_demux, pkt,
953
                                    pkt->data, pkt->size);
954
            pkt->destruct = dstr;
955
            pkt->flags |= AV_PKT_FLAG_KEY;
956
            if (size < 0)
957
                av_free_packet(pkt);
958
        } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
959
                   && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
960
            ast->frame_offset++;
961
            avi->stream_index = -1;
962
            ast->remaining = 0;
963
            goto resync;
964
        } else {
965
            /* XXX: How to handle B-frames in AVI? */
966
            pkt->dts = ast->frame_offset;
967
//                pkt->dts += ast->start;
968
            if(ast->sample_size)
969
                pkt->dts /= ast->sample_size;
970
//av_log(s, AV_LOG_DEBUG, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
971
            pkt->stream_index = avi->stream_index;
972

    
973
            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
974
                AVIndexEntry *e;
975
                int index;
976
                assert(st->index_entries);
977

    
978
                index= av_index_search_timestamp(st, ast->frame_offset, 0);
979
                e= &st->index_entries[index];
980

    
981
                if(index >= 0 && e->timestamp == ast->frame_offset){
982
                    if (e->flags & AVINDEX_KEYFRAME)
983
                        pkt->flags |= AV_PKT_FLAG_KEY;
984
                }
985
            } else {
986
                pkt->flags |= AV_PKT_FLAG_KEY;
987
            }
988
            ast->frame_offset += get_duration(ast, pkt->size);
989
        }
990
        ast->remaining -= size;
991
        if(!ast->remaining){
992
            avi->stream_index= -1;
993
            ast->packet_size= 0;
994
        }
995

    
996
        if(!avi->non_interleaved && ast->seek_pos > pkt->pos){
997
            av_free_packet(pkt);
998
            goto resync;
999
        }
1000
        ast->seek_pos= 0;
1001

    
1002
        return size;
1003
    }
1004

    
1005
    memset(d, -1, sizeof(int)*8);
1006
    for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
1007
        int j;
1008

    
1009
        for(j=0; j<7; j++)
1010
            d[j]= d[j+1];
1011
        d[7]= avio_r8(pb);
1012

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

    
1015
        n= get_stream_idx(d+2);
1016
//av_log(s, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
1017
        if(i + (uint64_t)size > avi->fsize || d[0]<0)
1018
            continue;
1019

    
1020
        //parse ix##
1021
        if(  (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
1022
        //parse JUNK
1023
           ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
1024
           ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
1025
            avio_skip(pb, size);
1026
//av_log(s, AV_LOG_DEBUG, "SKIP\n");
1027
            goto resync;
1028
        }
1029

    
1030
        //parse stray LIST
1031
        if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
1032
            avio_skip(pb, 4);
1033
            goto resync;
1034
        }
1035

    
1036
        n= get_stream_idx(d);
1037

    
1038
        if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
1039
            continue;
1040

    
1041
        //detect ##ix chunk and skip
1042
        if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
1043
            avio_skip(pb, size);
1044
            goto resync;
1045
        }
1046

    
1047
        //parse ##dc/##wb
1048
        if(n < s->nb_streams){
1049
            AVStream *st;
1050
            AVIStream *ast;
1051
            st = s->streams[n];
1052
            ast = st->priv_data;
1053

    
1054
            if(s->nb_streams>=2){
1055
                AVStream *st1  = s->streams[1];
1056
                AVIStream *ast1= st1->priv_data;
1057
                //workaround for broken small-file-bug402.avi
1058
                if(   d[2] == 'w' && d[3] == 'b'
1059
                   && n==0
1060
                   && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
1061
                   && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
1062
                   && ast->prefix == 'd'*256+'c'
1063
                   && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
1064
                  ){
1065
                    n=1;
1066
                    st = st1;
1067
                    ast = ast1;
1068
                    av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
1069
                }
1070
            }
1071

    
1072

    
1073
            if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
1074
               /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
1075
               || st->discard >= AVDISCARD_ALL){
1076
                ast->frame_offset += get_duration(ast, size);
1077
                avio_skip(pb, size);
1078
                goto resync;
1079
            }
1080

    
1081
            if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
1082
                int k = avio_r8(pb);
1083
                int last = (k + avio_r8(pb) - 1) & 0xFF;
1084

    
1085
                avio_rl16(pb); //flags
1086

    
1087
                for (; k <= last; k++)
1088
                    ast->pal[k] = avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
1089
                ast->has_pal= 1;
1090
                goto resync;
1091
            } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
1092
                         d[2]*256+d[3] == ast->prefix /*||
1093
                         (d[2] == 'd' && d[3] == 'c') ||
1094
                         (d[2] == 'w' && d[3] == 'b')*/) {
1095

    
1096
//av_log(s, AV_LOG_DEBUG, "OK\n");
1097
                if(d[2]*256+d[3] == ast->prefix)
1098
                    ast->prefix_count++;
1099
                else{
1100
                    ast->prefix= d[2]*256+d[3];
1101
                    ast->prefix_count= 0;
1102
                }
1103

    
1104
                avi->stream_index= n;
1105
                ast->packet_size= size + 8;
1106
                ast->remaining= size;
1107

    
1108
                if(size || !ast->sample_size){
1109
                    uint64_t pos= avio_tell(pb) - 8;
1110
                    if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
1111
                        av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
1112
                    }
1113
                }
1114
                goto resync;
1115
            }
1116
        }
1117
    }
1118

    
1119
    return AVERROR_EOF;
1120
}
1121

    
1122
/* XXX: We make the implicit supposition that the positions are sorted
1123
   for each stream. */
1124
static int avi_read_idx1(AVFormatContext *s, int size)
1125
{
1126
    AVIContext *avi = s->priv_data;
1127
    AVIOContext *pb = s->pb;
1128
    int nb_index_entries, i;
1129
    AVStream *st;
1130
    AVIStream *ast;
1131
    unsigned int index, tag, flags, pos, len;
1132
    unsigned last_pos= -1;
1133

    
1134
    nb_index_entries = size / 16;
1135
    if (nb_index_entries <= 0)
1136
        return -1;
1137

    
1138
    /* Read the entries and sort them in each stream component. */
1139
    for(i = 0; i < nb_index_entries; i++) {
1140
        tag = avio_rl32(pb);
1141
        flags = avio_rl32(pb);
1142
        pos = avio_rl32(pb);
1143
        len = avio_rl32(pb);
1144
#if defined(DEBUG_SEEK)
1145
        av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1146
               i, tag, flags, pos, len);
1147
#endif
1148
        if(i==0 && pos > avi->movi_list)
1149
            avi->movi_list= 0; //FIXME better check
1150
        pos += avi->movi_list;
1151

    
1152
        index = ((tag & 0xff) - '0') * 10;
1153
        index += ((tag >> 8) & 0xff) - '0';
1154
        if (index >= s->nb_streams)
1155
            continue;
1156
        st = s->streams[index];
1157
        ast = st->priv_data;
1158

    
1159
#if defined(DEBUG_SEEK)
1160
        av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1161
#endif
1162
        if(url_feof(pb))
1163
            return -1;
1164

    
1165
        if(last_pos == pos)
1166
            avi->non_interleaved= 1;
1167
        else if(len || !ast->sample_size)
1168
            av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1169
        ast->cum_len += get_duration(ast, len);
1170
        last_pos= pos;
1171
    }
1172
    return 0;
1173
}
1174

    
1175
static int guess_ni_flag(AVFormatContext *s){
1176
    int i;
1177
    int64_t last_start=0;
1178
    int64_t first_end= INT64_MAX;
1179
    int64_t oldpos= avio_tell(s->pb);
1180

    
1181
    for(i=0; i<s->nb_streams; i++){
1182
        AVStream *st = s->streams[i];
1183
        int n= st->nb_index_entries;
1184
        unsigned int size;
1185

    
1186
        if(n <= 0)
1187
            continue;
1188

    
1189
        if(n >= 2){
1190
            int64_t pos= st->index_entries[0].pos;
1191
            avio_seek(s->pb, pos + 4, SEEK_SET);
1192
            size= avio_rl32(s->pb);
1193
            if(pos + size > st->index_entries[1].pos)
1194
                last_start= INT64_MAX;
1195
        }
1196

    
1197
        if(st->index_entries[0].pos > last_start)
1198
            last_start= st->index_entries[0].pos;
1199
        if(st->index_entries[n-1].pos < first_end)
1200
            first_end= st->index_entries[n-1].pos;
1201
    }
1202
    avio_seek(s->pb, oldpos, SEEK_SET);
1203
    return last_start > first_end;
1204
}
1205

    
1206
static int avi_load_index(AVFormatContext *s)
1207
{
1208
    AVIContext *avi = s->priv_data;
1209
    AVIOContext *pb = s->pb;
1210
    uint32_t tag, size;
1211
    int64_t pos= avio_tell(pb);
1212
    int ret = -1;
1213

    
1214
    if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1215
        goto the_end; // maybe truncated file
1216
#ifdef DEBUG_SEEK
1217
    printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
1218
#endif
1219
    for(;;) {
1220
        if (url_feof(pb))
1221
            break;
1222
        tag = avio_rl32(pb);
1223
        size = avio_rl32(pb);
1224
#ifdef DEBUG_SEEK
1225
        printf("tag=%c%c%c%c size=0x%x\n",
1226
               tag & 0xff,
1227
               (tag >> 8) & 0xff,
1228
               (tag >> 16) & 0xff,
1229
               (tag >> 24) & 0xff,
1230
               size);
1231
#endif
1232
        switch(tag) {
1233
        case MKTAG('i', 'd', 'x', '1'):
1234
            if (avi_read_idx1(s, size) < 0)
1235
                goto skip;
1236
            ret = 0;
1237
                goto the_end;
1238
            break;
1239
        default:
1240
        skip:
1241
            size += (size & 1);
1242
            if (avio_skip(pb, size) < 0)
1243
                goto the_end; // something is wrong here
1244
            break;
1245
        }
1246
    }
1247
 the_end:
1248
    avio_seek(pb, pos, SEEK_SET);
1249
    return ret;
1250
}
1251

    
1252
static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1253
{
1254
    AVIStream *ast2 = st2->priv_data;
1255
    int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1256
    av_free_packet(&ast2->sub_pkt);
1257
    if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1258
        avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1259
        av_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1260
}
1261

    
1262
static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1263
{
1264
    AVIContext *avi = s->priv_data;
1265
    AVStream *st;
1266
    int i, index;
1267
    int64_t pos, pos_min;
1268
    AVIStream *ast;
1269

    
1270
    if (!avi->index_loaded) {
1271
        /* we only load the index on demand */
1272
        avi_load_index(s);
1273
        avi->index_loaded = 1;
1274
    }
1275
    assert(stream_index>= 0);
1276

    
1277
    st = s->streams[stream_index];
1278
    ast= st->priv_data;
1279
    index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
1280
    if(index<0)
1281
        return -1;
1282

    
1283
    /* find the position */
1284
    pos = st->index_entries[index].pos;
1285
    timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1286

    
1287
//    av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1288

    
1289
    if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1290
        /* One and only one real stream for DV in AVI, and it has video  */
1291
        /* offsets. Calling with other stream indexes should have failed */
1292
        /* the av_index_search_timestamp call above.                     */
1293
        assert(stream_index == 0);
1294

    
1295
        /* Feed the DV video stream version of the timestamp to the */
1296
        /* DV demux so it can synthesize correct timestamps.        */
1297
        dv_offset_reset(avi->dv_demux, timestamp);
1298

    
1299
        avio_seek(s->pb, pos, SEEK_SET);
1300
        avi->stream_index= -1;
1301
        return 0;
1302
    }
1303

    
1304
    pos_min= pos;
1305
    for(i = 0; i < s->nb_streams; i++) {
1306
        AVStream *st2 = s->streams[i];
1307
        AVIStream *ast2 = st2->priv_data;
1308

    
1309
        ast2->packet_size=
1310
        ast2->remaining= 0;
1311

    
1312
        if (ast2->sub_ctx) {
1313
            seek_subtitle(st, st2, timestamp);
1314
            continue;
1315
        }
1316

    
1317
        if (st2->nb_index_entries <= 0)
1318
            continue;
1319

    
1320
//        assert(st2->codec->block_align);
1321
        assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1322
        index = av_index_search_timestamp(
1323
                st2,
1324
                av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1325
                flags | AVSEEK_FLAG_BACKWARD);
1326
        if(index<0)
1327
            index=0;
1328
        ast2->seek_pos= st2->index_entries[index].pos;
1329
        pos_min= FFMIN(pos_min,ast2->seek_pos);
1330
        ast2->frame_offset = st2->index_entries[index].timestamp;
1331
    }
1332

    
1333
    /* do the seek */
1334
    avio_seek(s->pb, pos_min, SEEK_SET);
1335
    avi->stream_index= -1;
1336
    return 0;
1337
}
1338

    
1339
static int avi_read_close(AVFormatContext *s)
1340
{
1341
    int i;
1342
    AVIContext *avi = s->priv_data;
1343

    
1344
    for(i=0;i<s->nb_streams;i++) {
1345
        AVStream *st = s->streams[i];
1346
        AVIStream *ast = st->priv_data;
1347
        if (ast) {
1348
            if (ast->sub_ctx) {
1349
                av_freep(&ast->sub_ctx->pb);
1350
                av_close_input_stream(ast->sub_ctx);
1351
            }
1352
            av_free(ast->sub_buffer);
1353
            av_free_packet(&ast->sub_pkt);
1354
        }
1355
    }
1356

    
1357
    av_free(avi->dv_demux);
1358

    
1359
    return 0;
1360
}
1361

    
1362
static int avi_probe(AVProbeData *p)
1363
{
1364
    int i;
1365

    
1366
    /* check file header */
1367
    for(i=0; avi_headers[i][0]; i++)
1368
        if(!memcmp(p->buf  , avi_headers[i]  , 4) &&
1369
           !memcmp(p->buf+8, avi_headers[i]+4, 4))
1370
            return AVPROBE_SCORE_MAX;
1371

    
1372
    return 0;
1373
}
1374

    
1375
AVInputFormat ff_avi_demuxer = {
1376
    "avi",
1377
    NULL_IF_CONFIG_SMALL("AVI format"),
1378
    sizeof(AVIContext),
1379
    avi_probe,
1380
    avi_read_header,
1381
    avi_read_packet,
1382
    avi_read_close,
1383
    avi_read_seek,
1384
};