Statistics
| Branch: | Revision:

ffmpeg / libavformat / avidec.c @ 63613fe6

History | View | Annotate | Download (38.1 KB)

1 de6d9b64 Fabrice Bellard
/*
2 7fbde343 Aurelien Jacobs
 * AVI demuxer
3 15d6e361 Diego Biurrun
 * Copyright (c) 2001 Fabrice Bellard
4 de6d9b64 Fabrice Bellard
 *
5 b78e7197 Diego Biurrun
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8 19720f15 Fabrice Bellard
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10 b78e7197 Diego Biurrun
 * version 2.1 of the License, or (at your option) any later version.
11 de6d9b64 Fabrice Bellard
 *
12 b78e7197 Diego Biurrun
 * FFmpeg is distributed in the hope that it will be useful,
13 de6d9b64 Fabrice Bellard
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 19720f15 Fabrice Bellard
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16 de6d9b64 Fabrice Bellard
 *
17 19720f15 Fabrice Bellard
 * You should have received a copy of the GNU Lesser General Public
18 b78e7197 Diego Biurrun
 * License along with FFmpeg; if not, write to the Free Software
19 5509bffa Diego Biurrun
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 de6d9b64 Fabrice Bellard
 */
21 7b114c09 Måns Rullgård
22 c13b250b Baptiste Coudurier
//#define DEBUG
23
//#define DEBUG_SEEK
24
25 2bb6eba2 Aurelien Jacobs
#include "libavutil/intreadwrite.h"
26 7b114c09 Måns Rullgård
#include "libavutil/bswap.h"
27 de6d9b64 Fabrice Bellard
#include "avformat.h"
28
#include "avi.h"
29 7458ccbb Roman Shaposhnik
#include "dv.h"
30 9d9f4119 Måns Rullgård
#include "riff.h"
31 de6d9b64 Fabrice Bellard
32 52a0bbff Michael Niedermayer
#undef NDEBUG
33
#include <assert.h>
34
35 155e9ee9 Fabrice Bellard
typedef struct AVIStream {
36 7c7f3866 Michael Niedermayer
    int64_t frame_offset; /* current frame (video) or byte (audio) counter
37 155e9ee9 Fabrice Bellard
                         (used to compute the pts) */
38 7c7f3866 Michael Niedermayer
    int remaining;
39
    int packet_size;
40
41 155e9ee9 Fabrice Bellard
    int scale;
42 115329f1 Diego Biurrun
    int rate;
43 8223bca5 Michael Niedermayer
    int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
44 115329f1 Diego Biurrun
45 94d1d6c0 Michael Niedermayer
    int64_t cum_len; /* temporary storage (used during seek) */
46 115329f1 Diego Biurrun
47 d2c5f0a4 Michael Niedermayer
    int prefix;                       ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
48
    int prefix_count;
49 b7c40744 Michael Niedermayer
    uint32_t pal[256];
50
    int has_pal;
51 155e9ee9 Fabrice Bellard
} AVIStream;
52 de6d9b64 Fabrice Bellard
53
typedef struct {
54 7458ccbb Roman Shaposhnik
    int64_t  riff_end;
55
    int64_t  movi_end;
56 ea4b2b5e Michael Niedermayer
    int64_t  fsize;
57 bc5c918e Diego Biurrun
    int64_t movi_list;
58 7ccc636f Michael Niedermayer
    int64_t last_pkt_pos;
59 155e9ee9 Fabrice Bellard
    int index_loaded;
60 8f9298f8 Roman Shaposhnik
    int is_odml;
61 7c7f3866 Michael Niedermayer
    int non_interleaved;
62
    int stream_index;
63 ddaae6a9 Roman Shaposhnik
    DVDemuxContext* dv_demux;
64 de6d9b64 Fabrice Bellard
} AVIContext;
65
66 7b31b092 Aurelien Jacobs
static const char avi_headers[][8] = {
67
    { 'R', 'I', 'F', 'F',    'A', 'V', 'I', ' ' },
68
    { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 'X' },
69
    { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 0x19},
70 b925ef61 Aurelien Jacobs
    { 'O', 'N', '2', ' ',    'O', 'N', '2', 'f' },
71 0b04ebb3 Vladimir Voroshilov
    { 'R', 'I', 'F', 'F',    'A', 'M', 'V', ' ' },
72 7b31b092 Aurelien Jacobs
    { 0 }
73
};
74
75 42feef6b Michael Niedermayer
static int avi_load_index(AVFormatContext *s);
76 30a43f2d Michael Niedermayer
static int guess_ni_flag(AVFormatContext *s);
77 42feef6b Michael Niedermayer
78 de6d9b64 Fabrice Bellard
#ifdef DEBUG
79 1101abfe Zdenek Kabelac
static void print_tag(const char *str, unsigned int tag, int size)
80 de6d9b64 Fabrice Bellard
{
81 c13b250b Baptiste Coudurier
    dprintf(NULL, "%s: tag=%c%c%c%c size=0x%x\n",
82 de6d9b64 Fabrice Bellard
           str, tag & 0xff,
83
           (tag >> 8) & 0xff,
84
           (tag >> 16) & 0xff,
85
           (tag >> 24) & 0xff,
86
           size);
87
}
88
#endif
89
90 87ad63c0 Benoit Fouet
static int get_riff(AVFormatContext *s, ByteIOContext *pb)
91 06219cb1 Roman Shaposhnik
{
92 87ad63c0 Benoit Fouet
    AVIContext *avi = s->priv_data;
93 7b31b092 Aurelien Jacobs
    char header[8];
94
    int i;
95 06219cb1 Roman Shaposhnik
96 7b31b092 Aurelien Jacobs
    /* check RIFF header */
97
    get_buffer(pb, header, 4);
98 06219cb1 Roman Shaposhnik
    avi->riff_end = get_le32(pb);   /* RIFF chunk size */
99
    avi->riff_end += url_ftell(pb); /* RIFF chunk end */
100 7b31b092 Aurelien Jacobs
    get_buffer(pb, header+4, 4);
101
102
    for(i=0; avi_headers[i][0]; i++)
103
        if(!memcmp(header, avi_headers[i], 8))
104
            break;
105
    if(!avi_headers[i][0])
106 06219cb1 Roman Shaposhnik
        return -1;
107 115329f1 Diego Biurrun
108 7b31b092 Aurelien Jacobs
    if(header[7] == 0x19)
109 87ad63c0 Benoit Fouet
        av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
110 7b31b092 Aurelien Jacobs
111 06219cb1 Roman Shaposhnik
    return 0;
112
}
113
114 94d1d6c0 Michael Niedermayer
static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
115 8945ebb9 Michael Niedermayer
    AVIContext *avi = s->priv_data;
116 899681cd Björn Axelsson
    ByteIOContext *pb = s->pb;
117 94d1d6c0 Michael Niedermayer
    int longs_pre_entry= get_le16(pb);
118
    int index_sub_type = get_byte(pb);
119
    int index_type     = get_byte(pb);
120
    int entries_in_use = get_le32(pb);
121
    int chunk_id       = get_le32(pb);
122
    int64_t base       = get_le64(pb);
123
    int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
124
    AVStream *st;
125
    AVIStream *ast;
126
    int i;
127 8945ebb9 Michael Niedermayer
    int64_t last_pos= -1;
128 899681cd Björn Axelsson
    int64_t filesize= url_fsize(s->pb);
129 94d1d6c0 Michael Niedermayer
130 965a63af Michael Niedermayer
#ifdef DEBUG_SEEK
131 949b1a13 Steve L'Homme
    av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
132 965a63af Michael Niedermayer
        longs_pre_entry,index_type, entries_in_use, chunk_id, base);
133
#endif
134 94d1d6c0 Michael Niedermayer
135
    if(stream_id > s->nb_streams || stream_id < 0)
136
        return -1;
137
    st= s->streams[stream_id];
138
    ast = st->priv_data;
139
140
    if(index_sub_type)
141
        return -1;
142
143
    get_le32(pb);
144
145
    if(index_type && longs_pre_entry != 2)
146
        return -1;
147
    if(index_type>1)
148
        return -1;
149
150 965a63af Michael Niedermayer
    if(filesize > 0 && base >= filesize){
151
        av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
152
        if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
153
            base &= 0xFFFFFFFF;
154
        else
155
            return -1;
156
    }
157
158 94d1d6c0 Michael Niedermayer
    for(i=0; i<entries_in_use; i++){
159
        if(index_type){
160 30a43f2d Michael Niedermayer
            int64_t pos= get_le32(pb) + base - 8;
161 94d1d6c0 Michael Niedermayer
            int len    = get_le32(pb);
162 30a43f2d Michael Niedermayer
            int key= len >= 0;
163 94d1d6c0 Michael Niedermayer
            len &= 0x7FFFFFFF;
164
165 965a63af Michael Niedermayer
#ifdef DEBUG_SEEK
166 949b1a13 Steve L'Homme
            av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
167 965a63af Michael Niedermayer
#endif
168 8ebe099a Michael Niedermayer
            if(url_feof(pb))
169
                return -1;
170
171 8945ebb9 Michael Niedermayer
            if(last_pos == pos || pos == base - 8)
172
                avi->non_interleaved= 1;
173 ca5b528e Michael Niedermayer
            if(last_pos != pos)
174 2b70eb2b Michael Niedermayer
                av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, key ? AVINDEX_KEYFRAME : 0);
175 30a43f2d Michael Niedermayer
176 94d1d6c0 Michael Niedermayer
            if(ast->sample_size)
177 2b70eb2b Michael Niedermayer
                ast->cum_len += len;
178 94d1d6c0 Michael Niedermayer
            else
179
                ast->cum_len ++;
180 8945ebb9 Michael Niedermayer
            last_pos= pos;
181 94d1d6c0 Michael Niedermayer
        }else{
182 26b89135 Måns Rullgård
            int64_t offset, pos;
183
            int duration;
184
            offset = get_le64(pb);
185
            get_le32(pb);       /* size */
186
            duration = get_le32(pb);
187 8ebe099a Michael Niedermayer
188
            if(url_feof(pb))
189
                return -1;
190
191 26b89135 Måns Rullgård
            pos = url_ftell(pb);
192 94d1d6c0 Michael Niedermayer
193
            url_fseek(pb, offset+8, SEEK_SET);
194
            read_braindead_odml_indx(s, frame_num);
195
            frame_num += duration;
196
197
            url_fseek(pb, pos, SEEK_SET);
198
        }
199
    }
200 965a63af Michael Niedermayer
    avi->index_loaded=1;
201 94d1d6c0 Michael Niedermayer
    return 0;
202
}
203
204 115e8ae5 Michael Niedermayer
static void clean_index(AVFormatContext *s){
205 965a63af Michael Niedermayer
    int i;
206
    int64_t j;
207 115e8ae5 Michael Niedermayer
208
    for(i=0; i<s->nb_streams; i++){
209
        AVStream *st = s->streams[i];
210
        AVIStream *ast = st->priv_data;
211
        int n= st->nb_index_entries;
212
        int max= ast->sample_size;
213
        int64_t pos, size, ts;
214
215
        if(n != 1 || ast->sample_size==0)
216
            continue;
217
218
        while(max < 1024) max+=max;
219
220
        pos= st->index_entries[0].pos;
221
        size= st->index_entries[0].size;
222
        ts= st->index_entries[0].timestamp;
223
224
        for(j=0; j<size; j+=max){
225
            av_add_index_entry(st, pos+j, ts + j/ast->sample_size, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
226
        }
227
    }
228
}
229
230 47146dfb Michael Niedermayer
static int avi_read_tag(AVFormatContext *s, const char *key, unsigned int size)
231 57060f89 David Conrad
{
232 47146dfb Michael Niedermayer
    ByteIOContext *pb = s->pb;
233
    uint8_t value[1024];
234
235 bc5c918e Diego Biurrun
    int64_t i = url_ftell(pb);
236 57060f89 David Conrad
    size += (size & 1);
237 47146dfb Michael Niedermayer
    get_strz(pb, value, sizeof(value));
238 57060f89 David Conrad
    url_fseek(pb, i+size, SEEK_SET);
239 47146dfb Michael Niedermayer
240 5ea7ce88 Aurelien Jacobs
    return av_metadata_set(&s->metadata, key, value);
241 57060f89 David Conrad
}
242
243 1101abfe Zdenek Kabelac
static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
244 de6d9b64 Fabrice Bellard
{
245 c9a65ca8 Fabrice Bellard
    AVIContext *avi = s->priv_data;
246 899681cd Björn Axelsson
    ByteIOContext *pb = s->pb;
247 9d9aac84 Marc Mason
    unsigned int tag, tag1, handler;
248 b53f1064 Michael Niedermayer
    int codec_type, stream_index, frame_period, bit_rate;
249 247eadca Fabrice Bellard
    unsigned int size, nb_frames;
250 6d29fba9 Michael Niedermayer
    int i;
251 de6d9b64 Fabrice Bellard
    AVStream *st;
252 26b89135 Måns Rullgård
    AVIStream *ast = NULL;
253 0b04ebb3 Vladimir Voroshilov
    int avih_width=0, avih_height=0;
254
    int amv_file_format=0;
255 5a4a4d78 Reimar Döffinger
    uint64_t list_end = 0;
256 de6d9b64 Fabrice Bellard
257 7c7f3866 Michael Niedermayer
    avi->stream_index= -1;
258 115329f1 Diego Biurrun
259 037c08d6 Måns Rullgård
    if (get_riff(s, pb) < 0)
260 de6d9b64 Fabrice Bellard
        return -1;
261 1101abfe Zdenek Kabelac
262 ea4b2b5e Michael Niedermayer
    avi->fsize = url_fsize(pb);
263
    if(avi->fsize<=0)
264 87657891 Baptiste Coudurier
        avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
265 ea4b2b5e Michael Niedermayer
266 de6d9b64 Fabrice Bellard
    /* first list tag */
267
    stream_index = -1;
268
    codec_type = -1;
269
    frame_period = 0;
270
    for(;;) {
271
        if (url_feof(pb))
272
            goto fail;
273
        tag = get_le32(pb);
274
        size = get_le32(pb);
275
#ifdef DEBUG
276
        print_tag("tag", tag, size);
277
#endif
278
279
        switch(tag) {
280
        case MKTAG('L', 'I', 'S', 'T'):
281 5a4a4d78 Reimar Döffinger
            list_end = url_ftell(pb) + size;
282 15d6e361 Diego Biurrun
            /* Ignored, except at start of video packets. */
283 de6d9b64 Fabrice Bellard
            tag1 = get_le32(pb);
284
#ifdef DEBUG
285
            print_tag("list", tag1, 0);
286
#endif
287
            if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
288 155e9ee9 Fabrice Bellard
                avi->movi_list = url_ftell(pb) - 4;
289 2064c77a David Conrad
                if(size) avi->movi_end = avi->movi_list + size + (size & 1);
290 a965c478 Aurelien Jacobs
                else     avi->movi_end = url_fsize(pb);
291 de6d9b64 Fabrice Bellard
#ifdef DEBUG
292 c13b250b Baptiste Coudurier
                dprintf(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
293 de6d9b64 Fabrice Bellard
#endif
294
                goto end_of_header;
295
            }
296
            break;
297 8f9298f8 Roman Shaposhnik
        case MKTAG('d', 'm', 'l', 'h'):
298 bb270c08 Diego Biurrun
            avi->is_odml = 1;
299
            url_fskip(pb, size + (size & 1));
300
            break;
301 0b04ebb3 Vladimir Voroshilov
        case MKTAG('a', 'm', 'v', 'h'):
302
            amv_file_format=1;
303 de6d9b64 Fabrice Bellard
        case MKTAG('a', 'v', 'i', 'h'):
304 15d6e361 Diego Biurrun
            /* AVI header */
305 1101abfe Zdenek Kabelac
            /* using frame_period is bad idea */
306 de6d9b64 Fabrice Bellard
            frame_period = get_le32(pb);
307
            bit_rate = get_le32(pb) * 8;
308 1894edeb Michael Niedermayer
            get_le32(pb);
309
            avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
310
311
            url_fskip(pb, 2 * 4);
312 6d29fba9 Michael Niedermayer
            get_le32(pb);
313 0b04ebb3 Vladimir Voroshilov
            get_le32(pb);
314
            avih_width=get_le32(pb);
315
            avih_height=get_le32(pb);
316 6d29fba9 Michael Niedermayer
317 0b04ebb3 Vladimir Voroshilov
            url_fskip(pb, size - 10 * 4);
318 6d29fba9 Michael Niedermayer
            break;
319
        case MKTAG('s', 't', 'r', 'h'):
320
            /* stream header */
321
322
            tag1 = get_le32(pb);
323
            handler = get_le32(pb); /* codec tag */
324
325
            if(tag1 == MKTAG('p', 'a', 'd', 's')){
326
                url_fskip(pb, size - 8);
327
                break;
328
            }else{
329
                stream_index++;
330
                st = av_new_stream(s, stream_index);
331 de6d9b64 Fabrice Bellard
                if (!st)
332
                    goto fail;
333 9ee91c2f Michael Niedermayer
334 155e9ee9 Fabrice Bellard
                ast = av_mallocz(sizeof(AVIStream));
335
                if (!ast)
336
                    goto fail;
337
                st->priv_data = ast;
338 bb270c08 Diego Biurrun
            }
339 0b04ebb3 Vladimir Voroshilov
            if(amv_file_format)
340
                tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
341 6d29fba9 Michael Niedermayer
342 cc11e2b3 Michael Niedermayer
#ifdef DEBUG
343 e344c1ea Steve L'Homme
            print_tag("strh", tag1, -1);
344 cc11e2b3 Michael Niedermayer
#endif
345 b53f1064 Michael Niedermayer
            if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
346 6eb2de74 Roman Shaposhnik
                int64_t dv_dur;
347
348 115329f1 Diego Biurrun
                /*
349 bb270c08 Diego Biurrun
                 * After some consideration -- I don't think we
350 15d6e361 Diego Biurrun
                 * have to support anything but DV in type1 AVIs.
351 bb270c08 Diego Biurrun
                 */
352
                if (s->nb_streams != 1)
353
                    goto fail;
354
355
                if (handler != MKTAG('d', 'v', 's', 'd') &&
356
                    handler != MKTAG('d', 'v', 'h', 'd') &&
357
                    handler != MKTAG('d', 'v', 's', 'l'))
358
                   goto fail;
359
360
                ast = s->streams[0]->priv_data;
361
                av_freep(&s->streams[0]->codec->extradata);
362
                av_freep(&s->streams[0]);
363
                s->nb_streams = 0;
364 49fb20cb Aurelien Jacobs
                if (CONFIG_DV_DEMUXER) {
365 38ca53da Aurelien Jacobs
                    avi->dv_demux = dv_init_demux(s);
366
                    if (!avi->dv_demux)
367
                        goto fail;
368 a2a6332b Aurelien Jacobs
                }
369 bb270c08 Diego Biurrun
                s->streams[0]->priv_data = ast;
370
                url_fskip(pb, 3 * 4);
371
                ast->scale = get_le32(pb);
372
                ast->rate = get_le32(pb);
373 6eb2de74 Roman Shaposhnik
                url_fskip(pb, 4);  /* start time */
374
375
                dv_dur = get_le32(pb);
376
                if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
377
                    dv_dur *= AV_TIME_BASE;
378
                    s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
379
                }
380
                /*
381
                 * else, leave duration alone; timing estimation in utils.c
382 15d6e361 Diego Biurrun
                 *      will make a guess based on bitrate.
383 6eb2de74 Roman Shaposhnik
                 */
384
385 bb270c08 Diego Biurrun
                stream_index = s->nb_streams - 1;
386 6eb2de74 Roman Shaposhnik
                url_fskip(pb, size - 9*4);
387 b53f1064 Michael Niedermayer
                break;
388
            }
389 b559b29b Michael Niedermayer
390 6d29fba9 Michael Niedermayer
            assert(stream_index < s->nb_streams);
391 01f4895c Michael Niedermayer
            st->codec->stream_codec_tag= handler;
392 b559b29b Michael Niedermayer
393 b53f1064 Michael Niedermayer
            get_le32(pb); /* flags */
394
            get_le16(pb); /* priority */
395
            get_le16(pb); /* language */
396
            get_le32(pb); /* initial frame */
397
            ast->scale = get_le32(pb);
398
            ast->rate = get_le32(pb);
399 4a030a1f Michael Niedermayer
            if(!(ast->scale && ast->rate)){
400 15d6e361 Diego Biurrun
                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);
401 0dbb6515 Michael Niedermayer
                if(frame_period){
402
                    ast->rate = 1000000;
403
                    ast->scale = frame_period;
404
                }else{
405
                    ast->rate = 25;
406
                    ast->scale = 1;
407
                }
408 4a030a1f Michael Niedermayer
            }
409 b53f1064 Michael Niedermayer
            av_set_pts_info(st, 64, ast->scale, ast->rate);
410 115329f1 Diego Biurrun
411 b72a2bc8 Michael Niedermayer
            ast->cum_len=get_le32(pb); /* start */
412 b53f1064 Michael Niedermayer
            nb_frames = get_le32(pb);
413 b559b29b Michael Niedermayer
414 b53f1064 Michael Niedermayer
            st->start_time = 0;
415 c0df9d75 Michael Niedermayer
            st->duration = nb_frames;
416 b53f1064 Michael Niedermayer
            get_le32(pb); /* buffer size */
417
            get_le32(pb); /* quality */
418
            ast->sample_size = get_le32(pb); /* sample ssize */
419 2b70eb2b Michael Niedermayer
            ast->cum_len *= FFMAX(1, ast->sample_size);
420 87ad63c0 Benoit Fouet
//            av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
421 247eadca Fabrice Bellard
422 b53f1064 Michael Niedermayer
            switch(tag1) {
423 bb270c08 Diego Biurrun
            case MKTAG('v', 'i', 'd', 's'):
424 b53f1064 Michael Niedermayer
                codec_type = CODEC_TYPE_VIDEO;
425 247eadca Fabrice Bellard
426 b53f1064 Michael Niedermayer
                ast->sample_size = 0;
427
                break;
428
            case MKTAG('a', 'u', 'd', 's'):
429
                codec_type = CODEC_TYPE_AUDIO;
430 9bf9a5fc Michael Niedermayer
                break;
431 cc11e2b3 Michael Niedermayer
            case MKTAG('t', 'x', 't', 's'):
432 115329f1 Diego Biurrun
                //FIXME
433 cc11e2b3 Michael Niedermayer
                codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ?  FIXME
434
                break;
435 25176d6e Florian Echtler
            case MKTAG('d', 'a', 't', 's'):
436
                codec_type = CODEC_TYPE_DATA;
437
                break;
438 9bf9a5fc Michael Niedermayer
            default:
439 30667f42 Michael Niedermayer
                av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
440 9bf9a5fc Michael Niedermayer
                goto fail;
441 de6d9b64 Fabrice Bellard
            }
442 2b70eb2b Michael Niedermayer
            ast->frame_offset= ast->cum_len;
443 b53f1064 Michael Niedermayer
            url_fskip(pb, size - 12 * 4);
444 de6d9b64 Fabrice Bellard
            break;
445
        case MKTAG('s', 't', 'r', 'f'):
446
            /* stream header */
447 6d29fba9 Michael Niedermayer
            if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
448 de6d9b64 Fabrice Bellard
                url_fskip(pb, size);
449
            } else {
450 5a4a4d78 Reimar Döffinger
                uint64_t cur_pos = url_ftell(pb);
451
                if (cur_pos < list_end)
452
                    size = FFMIN(size, list_end - cur_pos);
453 de6d9b64 Fabrice Bellard
                st = s->streams[stream_index];
454
                switch(codec_type) {
455
                case CODEC_TYPE_VIDEO:
456 0b04ebb3 Vladimir Voroshilov
                    if(amv_file_format){
457
                        st->codec->width=avih_width;
458
                        st->codec->height=avih_height;
459
                        st->codec->codec_type = CODEC_TYPE_VIDEO;
460
                        st->codec->codec_id = CODEC_ID_AMV;
461
                        url_fskip(pb, size);
462
                        break;
463
                    }
464 de6d9b64 Fabrice Bellard
                    get_le32(pb); /* size */
465 01f4895c Michael Niedermayer
                    st->codec->width = get_le32(pb);
466 31f2616d Michael Niedermayer
                    st->codec->height = (int32_t)get_le32(pb);
467 de6d9b64 Fabrice Bellard
                    get_le16(pb); /* panes */
468 dd1c8f3e Luca Abeni
                    st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
469 de6d9b64 Fabrice Bellard
                    tag1 = get_le32(pb);
470 b559b29b Michael Niedermayer
                    get_le32(pb); /* ImageSize */
471
                    get_le32(pb); /* XPelsPerMeter */
472
                    get_le32(pb); /* YPelsPerMeter */
473
                    get_le32(pb); /* ClrUsed */
474
                    get_le32(pb); /* ClrImportant */
475
476 cbb79c0e Reimar Döffinger
                    if (tag1 == MKTAG('D', 'X', 'S', 'B')) {
477
                        st->codec->codec_type = CODEC_TYPE_SUBTITLE;
478
                        st->codec->codec_tag = tag1;
479
                        st->codec->codec_id = CODEC_ID_XSUB;
480
                        break;
481
                    }
482
483 e344c1ea Steve L'Homme
                    if(size > 10*4 && size<(1<<30)){
484
                        st->codec->extradata_size= size - 10*4;
485
                        st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
486 3dcddf82 Reimar Döffinger
                        if (!st->codec->extradata) {
487
                            st->codec->extradata_size= 0;
488
                            return AVERROR(ENOMEM);
489
                        }
490 e344c1ea Steve L'Homme
                        get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
491
                    }
492 115329f1 Diego Biurrun
493 01f4895c Michael Niedermayer
                    if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
494 952c69c4 Michael Niedermayer
                        get_byte(pb);
495 b559b29b Michael Niedermayer
496 15d6e361 Diego Biurrun
                    /* Extract palette from extradata if bpp <= 8. */
497
                    /* This code assumes that extradata contains only palette. */
498
                    /* This is true for all paletted codecs implemented in FFmpeg. */
499 dd1c8f3e Luca Abeni
                    if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
500 01f4895c Michael Niedermayer
                        st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
501 63613fe6 Måns Rullgård
#if HAVE_BIGENDIAN
502 01f4895c Michael Niedermayer
                        for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
503
                            st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
504 5e29abf8 Roberto Togni
#else
505 01f4895c Michael Niedermayer
                        memcpy(st->codec->palctrl->palette, st->codec->extradata,
506
                               FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
507 5e29abf8 Roberto Togni
#endif
508 01f4895c Michael Niedermayer
                        st->codec->palctrl->palette_changed = 1;
509 5e29abf8 Roberto Togni
                    }
510
511 de6d9b64 Fabrice Bellard
#ifdef DEBUG
512
                    print_tag("video", tag1, 0);
513
#endif
514 01f4895c Michael Niedermayer
                    st->codec->codec_type = CODEC_TYPE_VIDEO;
515
                    st->codec->codec_tag = tag1;
516 1a40491e Daniel Verkamp
                    st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
517 15d6e361 Diego Biurrun
                    st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
518 31f2616d Michael Niedermayer
519
                    if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
520
                        st->codec->extradata_size+= 9;
521
                        st->codec->extradata= av_realloc(st->codec->extradata, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
522
                        if(st->codec->extradata)
523
                            memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
524
                    }
525
                    st->codec->height= FFABS(st->codec->height);
526
527 b559b29b Michael Niedermayer
//                    url_fskip(pb, size - 5 * 4);
528 de6d9b64 Fabrice Bellard
                    break;
529 9bf9a5fc Michael Niedermayer
                case CODEC_TYPE_AUDIO:
530 1a40491e Daniel Verkamp
                    ff_get_wav_header(pb, st->codec, size);
531 78db672c Michael Niedermayer
                    if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
532 143b0820 Michael Niedermayer
                        av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
533 78db672c Michael Niedermayer
                        ast->sample_size= st->codec->block_align;
534
                    }
535 1cef9527 François Revol
                    if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
536
                        url_fskip(pb, 1);
537 5836d158 Diego Biurrun
                    /* Force parsing as several audio frames can be in
538 15d6e361 Diego Biurrun
                     * one packet and timestamps refer to packet start. */
539 a74008a4 Joakim Plate
                    st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
540 15d6e361 Diego Biurrun
                    /* ADTS header is in extradata, AAC without header must be
541
                     * stored as exact frames. Parser not needed and it will
542
                     * fail. */
543 cbee7a69 Baptiste Coudurier
                    if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
544 57004ff1 Aurelien Jacobs
                        st->need_parsing = AVSTREAM_PARSE_NONE;
545 8662900b Diego Biurrun
                    /* AVI files with Xan DPCM audio (wrongly) declare PCM
546
                     * audio in the header but have Axan as stream_code_tag. */
547 2bb6eba2 Aurelien Jacobs
                    if (st->codec->stream_codec_tag == AV_RL32("Axan")){
548 8662900b Diego Biurrun
                        st->codec->codec_id  = CODEC_ID_XAN_DPCM;
549
                        st->codec->codec_tag = 0;
550
                    }
551 0b04ebb3 Vladimir Voroshilov
                    if (amv_file_format)
552
                        st->codec->codec_id  = CODEC_ID_ADPCM_IMA_AMV;
553 de6d9b64 Fabrice Bellard
                    break;
554
                default:
555 01f4895c Michael Niedermayer
                    st->codec->codec_type = CODEC_TYPE_DATA;
556
                    st->codec->codec_id= CODEC_ID_NONE;
557
                    st->codec->codec_tag= 0;
558 de6d9b64 Fabrice Bellard
                    url_fskip(pb, size);
559
                    break;
560
                }
561
            }
562
            break;
563 94d1d6c0 Michael Niedermayer
        case MKTAG('i', 'n', 'd', 'x'):
564
            i= url_ftell(pb);
565 2c00106c Michael Niedermayer
            if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
566 b7b22558 Michael Niedermayer
                read_braindead_odml_indx(s, 0);
567
            }
568 94d1d6c0 Michael Niedermayer
            url_fseek(pb, i+size, SEEK_SET);
569
            break;
570 c86ec2f4 Michael Niedermayer
        case MKTAG('v', 'p', 'r', 'p'):
571
            if(stream_index < (unsigned)s->nb_streams && size > 9*4){
572
                AVRational active, active_aspect;
573
574
                st = s->streams[stream_index];
575
                get_le32(pb);
576
                get_le32(pb);
577
                get_le32(pb);
578
                get_le32(pb);
579
                get_le32(pb);
580
581
                active_aspect.den= get_le16(pb);
582 61559562 Michael Niedermayer
                active_aspect.num= get_le16(pb);
583 c86ec2f4 Michael Niedermayer
                active.num       = get_le32(pb);
584
                active.den       = get_le32(pb);
585
                get_le32(pb); //nbFieldsPerFrame
586
587
                if(active_aspect.num && active_aspect.den && active.num && active.den){
588 59729451 Aurelien Jacobs
                    st->sample_aspect_ratio= av_div_q(active_aspect, active);
589 c86ec2f4 Michael Niedermayer
//av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
590
                }
591
                size -= 9*4;
592
            }
593
            url_fseek(pb, size, SEEK_CUR);
594
            break;
595 57060f89 David Conrad
        case MKTAG('I', 'N', 'A', 'M'):
596 47146dfb Michael Niedermayer
            avi_read_tag(s, "Title", size);
597 57060f89 David Conrad
            break;
598
        case MKTAG('I', 'A', 'R', 'T'):
599 47146dfb Michael Niedermayer
            avi_read_tag(s, "Artist", size);
600 57060f89 David Conrad
            break;
601
        case MKTAG('I', 'C', 'O', 'P'):
602 47146dfb Michael Niedermayer
            avi_read_tag(s, "Copyright", size);
603 57060f89 David Conrad
            break;
604
        case MKTAG('I', 'C', 'M', 'T'):
605 47146dfb Michael Niedermayer
            avi_read_tag(s, "Comment", size);
606 57060f89 David Conrad
            break;
607
        case MKTAG('I', 'G', 'N', 'R'):
608 47146dfb Michael Niedermayer
            avi_read_tag(s, "Genre", size);
609 57060f89 David Conrad
            break;
610 f0861f46 Panagiotis Issaris
        case MKTAG('I', 'P', 'R', 'D'):
611 47146dfb Michael Niedermayer
            avi_read_tag(s, "Album", size);
612 f0861f46 Panagiotis Issaris
            break;
613 2ad4648f Panagiotis Issaris
        case MKTAG('I', 'P', 'R', 'T'):
614 47146dfb Michael Niedermayer
            avi_read_tag(s, "Track", size);
615 2ad4648f Panagiotis Issaris
            break;
616 de6d9b64 Fabrice Bellard
        default:
617 755c18ae Michael Niedermayer
            if(size > 1000000){
618 15d6e361 Diego Biurrun
                av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
619
                                        "I will ignore it and try to continue anyway.\n");
620 755c18ae Michael Niedermayer
                avi->movi_list = url_ftell(pb) - 4;
621
                avi->movi_end  = url_fsize(pb);
622
                goto end_of_header;
623
            }
624 de6d9b64 Fabrice Bellard
            /* skip tag */
625
            size += (size & 1);
626
            url_fskip(pb, size);
627
            break;
628
        }
629
    }
630
 end_of_header:
631
    /* check stream number */
632
    if (stream_index != s->nb_streams - 1) {
633
    fail:
634
        return -1;
635
    }
636 1101abfe Zdenek Kabelac
637 b7b22558 Michael Niedermayer
    if(!avi->index_loaded && !url_is_streamed(pb))
638 94d1d6c0 Michael Niedermayer
        avi_load_index(s);
639 42feef6b Michael Niedermayer
    avi->index_loaded = 1;
640 30a43f2d Michael Niedermayer
    avi->non_interleaved |= guess_ni_flag(s);
641 9d4cd3bf Michael Niedermayer
    if(avi->non_interleaved) {
642 15d6e361 Diego Biurrun
        av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
643 115e8ae5 Michael Niedermayer
        clean_index(s);
644 9d4cd3bf Michael Niedermayer
    }
645 115329f1 Diego Biurrun
646 de6d9b64 Fabrice Bellard
    return 0;
647
}
648
649 f080a7bd Michael Niedermayer
static int get_stream_idx(int *d){
650
    if(    d[0] >= '0' && d[0] <= '9'
651
        && d[1] >= '0' && d[1] <= '9'){
652
        return (d[0] - '0') * 10 + (d[1] - '0');
653
    }else{
654
        return 100; //invalid stream ID
655
    }
656
}
657
658 1101abfe Zdenek Kabelac
static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
659 de6d9b64 Fabrice Bellard
{
660
    AVIContext *avi = s->priv_data;
661 899681cd Björn Axelsson
    ByteIOContext *pb = s->pb;
662 f5007cc8 Michael Niedermayer
    int n, d[8];
663
    unsigned int size;
664 bc5c918e Diego Biurrun
    int64_t i, sync;
665 7458ccbb Roman Shaposhnik
    void* dstr;
666 115329f1 Diego Biurrun
667 49fb20cb Aurelien Jacobs
    if (CONFIG_DV_DEMUXER && avi->dv_demux) {
668 f5007cc8 Michael Niedermayer
        int size = dv_get_packet(avi->dv_demux, pkt);
669 bb270c08 Diego Biurrun
        if (size >= 0)
670
            return size;
671 2af7e610 Fabrice Bellard
    }
672 115329f1 Diego Biurrun
673 7c7f3866 Michael Niedermayer
    if(avi->non_interleaved){
674 79396ac6 Måns Rullgård
        int best_stream_index = 0;
675 7c7f3866 Michael Niedermayer
        AVStream *best_st= NULL;
676
        AVIStream *best_ast;
677
        int64_t best_ts= INT64_MAX;
678
        int i;
679 115329f1 Diego Biurrun
680 7c7f3866 Michael Niedermayer
        for(i=0; i<s->nb_streams; i++){
681
            AVStream *st = s->streams[i];
682
            AVIStream *ast = st->priv_data;
683
            int64_t ts= ast->frame_offset;
684
685
            if(ast->sample_size)
686
                ts /= ast->sample_size;
687
            ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
688
689 87ad63c0 Benoit Fouet
//            av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
690 2be83b96 Michael Niedermayer
            if(ts < best_ts && st->nb_index_entries){
691 7c7f3866 Michael Niedermayer
                best_ts= ts;
692
                best_st= st;
693
                best_stream_index= i;
694
            }
695
        }
696 fce88d52 Michael Niedermayer
        if(!best_st)
697
            return -1;
698
699 7c7f3866 Michael Niedermayer
        best_ast = best_st->priv_data;
700
        best_ts= av_rescale(best_ts, best_st->time_base.den, AV_TIME_BASE * (int64_t)best_st->time_base.num); //FIXME a little ugly
701
        if(best_ast->remaining)
702
            i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
703 25983dcd Michael Niedermayer
        else{
704 7c7f3866 Michael Niedermayer
            i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
705 25983dcd Michael Niedermayer
            if(i>=0)
706 a3bb564e Michael Niedermayer
                best_ast->frame_offset= best_st->index_entries[i].timestamp
707
                                      * FFMAX(1, best_ast->sample_size);
708 25983dcd Michael Niedermayer
        }
709 7c7f3866 Michael Niedermayer
710 87ad63c0 Benoit Fouet
//        av_log(s, AV_LOG_DEBUG, "%d\n", i);
711 7c7f3866 Michael Niedermayer
        if(i>=0){
712
            int64_t pos= best_st->index_entries[i].pos;
713 5c89153e Michael Niedermayer
            pos += best_ast->packet_size - best_ast->remaining;
714 899681cd Björn Axelsson
            url_fseek(s->pb, pos + 8, SEEK_SET);
715 87ad63c0 Benoit Fouet
//        av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
716 115329f1 Diego Biurrun
717 8223bca5 Michael Niedermayer
            assert(best_ast->remaining <= best_ast->packet_size);
718
719 1894edeb Michael Niedermayer
            avi->stream_index= best_stream_index;
720
            if(!best_ast->remaining)
721 8223bca5 Michael Niedermayer
                best_ast->packet_size=
722 1894edeb Michael Niedermayer
                best_ast->remaining= best_st->index_entries[i].size;
723 7c7f3866 Michael Niedermayer
        }
724
    }
725 115329f1 Diego Biurrun
726 4a8d5135 Michael Niedermayer
resync:
727 7c7f3866 Michael Niedermayer
    if(avi->stream_index >= 0){
728
        AVStream *st= s->streams[ avi->stream_index ];
729
        AVIStream *ast= st->priv_data;
730 c60a0f85 Michael Niedermayer
        int size, err;
731 115329f1 Diego Biurrun
732 e84dab5f Michael Niedermayer
        if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
733 7c7f3866 Michael Niedermayer
            size= INT_MAX;
734 115329f1 Diego Biurrun
        else if(ast->sample_size < 32)
735 7c7f3866 Michael Niedermayer
            size= 64*ast->sample_size;
736
        else
737
            size= ast->sample_size;
738
739
        if(size > ast->remaining)
740
            size= ast->remaining;
741 7ccc636f Michael Niedermayer
        avi->last_pkt_pos= url_ftell(pb);
742 c60a0f85 Michael Niedermayer
        err= av_get_packet(pb, pkt, size);
743
        if(err<0)
744
            return err;
745 115329f1 Diego Biurrun
746 b7c40744 Michael Niedermayer
        if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
747 c60a0f85 Michael Niedermayer
            void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
748
            if(ptr){
749 b7c40744 Michael Niedermayer
            ast->has_pal=0;
750
            pkt->size += 4*256;
751 c60a0f85 Michael Niedermayer
            pkt->data= ptr;
752 b7c40744 Michael Niedermayer
                memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
753 c60a0f85 Michael Niedermayer
            }else
754
                av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
755 b7c40744 Michael Niedermayer
        }
756
757 49fb20cb Aurelien Jacobs
        if (CONFIG_DV_DEMUXER && avi->dv_demux) {
758 7c7f3866 Michael Niedermayer
            dstr = pkt->destruct;
759
            size = dv_produce_packet(avi->dv_demux, pkt,
760
                                    pkt->data, pkt->size);
761
            pkt->destruct = dstr;
762
            pkt->flags |= PKT_FLAG_KEY;
763
        } else {
764 15d6e361 Diego Biurrun
            /* XXX: How to handle B-frames in AVI? */
765 7c7f3866 Michael Niedermayer
            pkt->dts = ast->frame_offset;
766
//                pkt->dts += ast->start;
767
            if(ast->sample_size)
768
                pkt->dts /= ast->sample_size;
769 87ad63c0 Benoit Fouet
//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);
770 7c7f3866 Michael Niedermayer
            pkt->stream_index = avi->stream_index;
771
772 01f4895c Michael Niedermayer
            if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
773 4323b09d Michael Niedermayer
                AVIndexEntry *e;
774
                int index;
775 ded3c7da Michael Niedermayer
                assert(st->index_entries);
776 7c7f3866 Michael Niedermayer
777 4323b09d Michael Niedermayer
                index= av_index_search_timestamp(st, pkt->dts, 0);
778
                e= &st->index_entries[index];
779 115329f1 Diego Biurrun
780 4323b09d Michael Niedermayer
                if(index >= 0 && e->timestamp == ast->frame_offset){
781
                    if (e->flags & AVINDEX_KEYFRAME)
782
                        pkt->flags |= PKT_FLAG_KEY;
783
                }
784 7c7f3866 Michael Niedermayer
            } else {
785 115329f1 Diego Biurrun
                pkt->flags |= PKT_FLAG_KEY;
786 7c7f3866 Michael Niedermayer
            }
787
            if(ast->sample_size)
788
                ast->frame_offset += pkt->size;
789
            else
790
                ast->frame_offset++;
791
        }
792
        ast->remaining -= size;
793
        if(!ast->remaining){
794
            avi->stream_index= -1;
795
            ast->packet_size= 0;
796
        }
797
798
        return size;
799
    }
800
801 4a8d5135 Michael Niedermayer
    memset(d, -1, sizeof(int)*8);
802
    for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
803 df99755b Michael Niedermayer
        int j;
804 1101abfe Zdenek Kabelac
805 df99755b Michael Niedermayer
        for(j=0; j<7; j++)
806
            d[j]= d[j+1];
807
        d[7]= get_byte(pb);
808 115329f1 Diego Biurrun
809 df99755b Michael Niedermayer
        size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
810 115329f1 Diego Biurrun
811 f080a7bd Michael Niedermayer
        n= get_stream_idx(d+2);
812 87ad63c0 Benoit Fouet
//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);
813 f5007cc8 Michael Niedermayer
        if(i + (uint64_t)size > avi->fsize || d[0]<0)
814 d2c5f0a4 Michael Niedermayer
            continue;
815 115329f1 Diego Biurrun
816 d2c5f0a4 Michael Niedermayer
        //parse ix##
817
        if(  (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
818 bb270c08 Diego Biurrun
        //parse JUNK
819 bc3a73bc Michael Niedermayer
           ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
820
           ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
821 8f9298f8 Roman Shaposhnik
            url_fskip(pb, size);
822 87ad63c0 Benoit Fouet
//av_log(s, AV_LOG_DEBUG, "SKIP\n");
823 4a8d5135 Michael Niedermayer
            goto resync;
824 8f9298f8 Roman Shaposhnik
        }
825 d2c5f0a4 Michael Niedermayer
826 f080a7bd Michael Niedermayer
        n= get_stream_idx(d);
827 115329f1 Diego Biurrun
828 7ccc636f Michael Niedermayer
        if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
829
            continue;
830
831 d2c5f0a4 Michael Niedermayer
        //parse ##dc/##wb
832 80e3a08c Michael Niedermayer
        if(n < s->nb_streams){
833 1ce50d32 Michael Niedermayer
            AVStream *st;
834
            AVIStream *ast;
835
            st = s->streams[n];
836
            ast = st->priv_data;
837 41757171 Michael Niedermayer
838 79d6b9cb Michael Niedermayer
            if(s->nb_streams>=2){
839
                AVStream *st1  = s->streams[1];
840
                AVIStream *ast1= st1->priv_data;
841 1ce50d32 Michael Niedermayer
                //workaround for broken small-file-bug402.avi
842
                if(   d[2] == 'w' && d[3] == 'b'
843
                   && n==0
844
                   && st ->codec->codec_type == CODEC_TYPE_VIDEO
845
                   && st1->codec->codec_type == CODEC_TYPE_AUDIO
846
                   && ast->prefix == 'd'*256+'c'
847
                   && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
848
                  ){
849
                    n=1;
850
                    st = st1;
851
                    ast = ast1;
852 15d6e361 Diego Biurrun
                    av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
853 1ce50d32 Michael Niedermayer
                }
854 79d6b9cb Michael Niedermayer
            }
855 41757171 Michael Niedermayer
856
857 1ce50d32 Michael Niedermayer
            if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
858
               /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
859
               || st->discard >= AVDISCARD_ALL){
860 f3356e9c Michael Niedermayer
                if(ast->sample_size) ast->frame_offset += pkt->size;
861
                else                 ast->frame_offset++;
862 b4aea108 Michael Niedermayer
                url_fskip(pb, size);
863
                goto resync;
864 1ce50d32 Michael Niedermayer
            }
865 d2c5f0a4 Michael Niedermayer
866 1ce50d32 Michael Niedermayer
            if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
867 b7c40744 Michael Niedermayer
                int k = get_byte(pb);
868
                int last = (k + get_byte(pb) - 1) & 0xFF;
869
870
                get_le16(pb); //flags
871
872
                for (; k <= last; k++)
873
                    ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
874
                ast->has_pal= 1;
875
                goto resync;
876 1ce50d32 Michael Niedermayer
            } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
877
                         d[2]*256+d[3] == ast->prefix /*||
878
                         (d[2] == 'd' && d[3] == 'c') ||
879
                         (d[2] == 'w' && d[3] == 'b')*/) {
880 d2c5f0a4 Michael Niedermayer
881 87ad63c0 Benoit Fouet
//av_log(s, AV_LOG_DEBUG, "OK\n");
882 1ce50d32 Michael Niedermayer
                if(d[2]*256+d[3] == ast->prefix)
883
                    ast->prefix_count++;
884
                else{
885
                    ast->prefix= d[2]*256+d[3];
886
                    ast->prefix_count= 0;
887
                }
888 d2c5f0a4 Michael Niedermayer
889 1ce50d32 Michael Niedermayer
                avi->stream_index= n;
890
                ast->packet_size= size + 8;
891
                ast->remaining= size;
892 ded3c7da Michael Niedermayer
893 1ce50d32 Michael Niedermayer
                {
894
                    uint64_t pos= url_ftell(pb) - 8;
895
                    if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
896
                        av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
897
                    }
898 ded3c7da Michael Niedermayer
                }
899 1ce50d32 Michael Niedermayer
                goto resync;
900 ded3c7da Michael Niedermayer
            }
901 df99755b Michael Niedermayer
        }
902
    }
903 d2c5f0a4 Michael Niedermayer
904 1e04bbee Peter Ross
    return AVERROR_EOF;
905 de6d9b64 Fabrice Bellard
}
906
907 15d6e361 Diego Biurrun
/* XXX: We make the implicit supposition that the positions are sorted
908
   for each stream. */
909 155e9ee9 Fabrice Bellard
static int avi_read_idx1(AVFormatContext *s, int size)
910
{
911 7c7f3866 Michael Niedermayer
    AVIContext *avi = s->priv_data;
912 899681cd Björn Axelsson
    ByteIOContext *pb = s->pb;
913 155e9ee9 Fabrice Bellard
    int nb_index_entries, i;
914
    AVStream *st;
915
    AVIStream *ast;
916
    unsigned int index, tag, flags, pos, len;
917 7c7f3866 Michael Niedermayer
    unsigned last_pos= -1;
918 115329f1 Diego Biurrun
919 155e9ee9 Fabrice Bellard
    nb_index_entries = size / 16;
920
    if (nb_index_entries <= 0)
921
        return -1;
922
923 15d6e361 Diego Biurrun
    /* Read the entries and sort them in each stream component. */
924 155e9ee9 Fabrice Bellard
    for(i = 0; i < nb_index_entries; i++) {
925
        tag = get_le32(pb);
926
        flags = get_le32(pb);
927
        pos = get_le32(pb);
928
        len = get_le32(pb);
929 52a0bbff Michael Niedermayer
#if defined(DEBUG_SEEK)
930 87ad63c0 Benoit Fouet
        av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
931 155e9ee9 Fabrice Bellard
               i, tag, flags, pos, len);
932
#endif
933 7c7f3866 Michael Niedermayer
        if(i==0 && pos > avi->movi_list)
934
            avi->movi_list= 0; //FIXME better check
935 5c89153e Michael Niedermayer
        pos += avi->movi_list;
936 7c7f3866 Michael Niedermayer
937 155e9ee9 Fabrice Bellard
        index = ((tag & 0xff) - '0') * 10;
938
        index += ((tag >> 8) & 0xff) - '0';
939
        if (index >= s->nb_streams)
940
            continue;
941
        st = s->streams[index];
942
        ast = st->priv_data;
943 115329f1 Diego Biurrun
944 52a0bbff Michael Niedermayer
#if defined(DEBUG_SEEK)
945 87ad63c0 Benoit Fouet
        av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
946 52a0bbff Michael Niedermayer
#endif
947 8ebe099a Michael Niedermayer
        if(url_feof(pb))
948
            return -1;
949
950 80e3a08c Michael Niedermayer
        if(last_pos == pos)
951
            avi->non_interleaved= 1;
952
        else
953 2b70eb2b Michael Niedermayer
            av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
954 7c7f3866 Michael Niedermayer
        if(ast->sample_size)
955 2b70eb2b Michael Niedermayer
            ast->cum_len += len;
956 7c7f3866 Michael Niedermayer
        else
957
            ast->cum_len ++;
958
        last_pos= pos;
959 155e9ee9 Fabrice Bellard
    }
960
    return 0;
961
}
962
963 7c7f3866 Michael Niedermayer
static int guess_ni_flag(AVFormatContext *s){
964
    int i;
965
    int64_t last_start=0;
966
    int64_t first_end= INT64_MAX;
967 8c68f25b Michael Niedermayer
    int64_t oldpos= url_ftell(s->pb);
968 115329f1 Diego Biurrun
969 7c7f3866 Michael Niedermayer
    for(i=0; i<s->nb_streams; i++){
970
        AVStream *st = s->streams[i];
971
        int n= st->nb_index_entries;
972 8c68f25b Michael Niedermayer
        unsigned int size;
973 7c7f3866 Michael Niedermayer
974
        if(n <= 0)
975
            continue;
976
977 8c68f25b Michael Niedermayer
        if(n >= 2){
978
            int64_t pos= st->index_entries[0].pos;
979
            url_fseek(s->pb, pos + 4, SEEK_SET);
980
            size= get_le32(s->pb);
981
            if(pos + size > st->index_entries[1].pos)
982
                last_start= INT64_MAX;
983
        }
984
985 7c7f3866 Michael Niedermayer
        if(st->index_entries[0].pos > last_start)
986
            last_start= st->index_entries[0].pos;
987
        if(st->index_entries[n-1].pos < first_end)
988
            first_end= st->index_entries[n-1].pos;
989
    }
990 8c68f25b Michael Niedermayer
    url_fseek(s->pb, oldpos, SEEK_SET);
991 7c7f3866 Michael Niedermayer
    return last_start > first_end;
992
}
993
994 155e9ee9 Fabrice Bellard
static int avi_load_index(AVFormatContext *s)
995
{
996
    AVIContext *avi = s->priv_data;
997 899681cd Björn Axelsson
    ByteIOContext *pb = s->pb;
998 155e9ee9 Fabrice Bellard
    uint32_t tag, size;
999 bc5c918e Diego Biurrun
    int64_t pos= url_ftell(pb);
1000 115329f1 Diego Biurrun
1001 155e9ee9 Fabrice Bellard
    url_fseek(pb, avi->movi_end, SEEK_SET);
1002
#ifdef DEBUG_SEEK
1003 949b1a13 Steve L'Homme
    printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
1004 155e9ee9 Fabrice Bellard
#endif
1005
    for(;;) {
1006
        if (url_feof(pb))
1007
            break;
1008
        tag = get_le32(pb);
1009
        size = get_le32(pb);
1010
#ifdef DEBUG_SEEK
1011
        printf("tag=%c%c%c%c size=0x%x\n",
1012
               tag & 0xff,
1013
               (tag >> 8) & 0xff,
1014
               (tag >> 16) & 0xff,
1015
               (tag >> 24) & 0xff,
1016
               size);
1017
#endif
1018
        switch(tag) {
1019
        case MKTAG('i', 'd', 'x', '1'):
1020
            if (avi_read_idx1(s, size) < 0)
1021
                goto skip;
1022
            else
1023
                goto the_end;
1024
            break;
1025
        default:
1026
        skip:
1027
            size += (size & 1);
1028
            url_fskip(pb, size);
1029
            break;
1030
        }
1031
    }
1032
 the_end:
1033 e6c0297f Michael Niedermayer
    url_fseek(pb, pos, SEEK_SET);
1034 155e9ee9 Fabrice Bellard
    return 0;
1035
}
1036
1037 7b3c1382 Michael Niedermayer
static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1038 155e9ee9 Fabrice Bellard
{
1039
    AVIContext *avi = s->priv_data;
1040
    AVStream *st;
1041 52a0bbff Michael Niedermayer
    int i, index;
1042 155e9ee9 Fabrice Bellard
    int64_t pos;
1043
1044
    if (!avi->index_loaded) {
1045
        /* we only load the index on demand */
1046
        avi_load_index(s);
1047
        avi->index_loaded = 1;
1048
    }
1049 52a0bbff Michael Niedermayer
    assert(stream_index>= 0);
1050 155e9ee9 Fabrice Bellard
1051
    st = s->streams[stream_index];
1052 52a0bbff Michael Niedermayer
    index= av_index_search_timestamp(st, timestamp, flags);
1053
    if(index<0)
1054 155e9ee9 Fabrice Bellard
        return -1;
1055 115329f1 Diego Biurrun
1056 155e9ee9 Fabrice Bellard
    /* find the position */
1057 52a0bbff Michael Niedermayer
    pos = st->index_entries[index].pos;
1058
    timestamp = st->index_entries[index].timestamp;
1059
1060 87ad63c0 Benoit Fouet
//    av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1061 155e9ee9 Fabrice Bellard
1062 49fb20cb Aurelien Jacobs
    if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1063 6eb2de74 Roman Shaposhnik
        /* One and only one real stream for DV in AVI, and it has video  */
1064 f4433de9 Diego Biurrun
        /* offsets. Calling with other stream indexes should have failed */
1065 6eb2de74 Roman Shaposhnik
        /* the av_index_search_timestamp call above.                     */
1066
        assert(stream_index == 0);
1067
1068
        /* Feed the DV video stream version of the timestamp to the */
1069 15d6e361 Diego Biurrun
        /* DV demux so it can synthesize correct timestamps.        */
1070 6eb2de74 Roman Shaposhnik
        dv_offset_reset(avi->dv_demux, timestamp);
1071
1072 899681cd Björn Axelsson
        url_fseek(s->pb, pos, SEEK_SET);
1073 6eb2de74 Roman Shaposhnik
        avi->stream_index= -1;
1074
        return 0;
1075
    }
1076
1077 155e9ee9 Fabrice Bellard
    for(i = 0; i < s->nb_streams; i++) {
1078 52a0bbff Michael Niedermayer
        AVStream *st2 = s->streams[i];
1079
        AVIStream *ast2 = st2->priv_data;
1080 7c7f3866 Michael Niedermayer
1081
        ast2->packet_size=
1082
        ast2->remaining= 0;
1083
1084 52a0bbff Michael Niedermayer
        if (st2->nb_index_entries <= 0)
1085
            continue;
1086 115329f1 Diego Biurrun
1087 e84dab5f Michael Niedermayer
//        assert(st2->codec->block_align);
1088 62f25230 Baptiste Coudurier
        assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1089 52a0bbff Michael Niedermayer
        index = av_index_search_timestamp(
1090 115329f1 Diego Biurrun
                st2,
1091 52a0bbff Michael Niedermayer
                av_rescale(timestamp, st2->time_base.den*(int64_t)st->time_base.num, st->time_base.den * (int64_t)st2->time_base.num),
1092
                flags | AVSEEK_FLAG_BACKWARD);
1093
        if(index<0)
1094
            index=0;
1095 115329f1 Diego Biurrun
1096 7c7f3866 Michael Niedermayer
        if(!avi->non_interleaved){
1097
            while(index>0 && st2->index_entries[index].pos > pos)
1098
                index--;
1099
            while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
1100
                index++;
1101
        }
1102
1103 87ad63c0 Benoit Fouet
//        av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
1104 52a0bbff Michael Niedermayer
        /* extract the current frame number */
1105
        ast2->frame_offset = st2->index_entries[index].timestamp;
1106
        if(ast2->sample_size)
1107
            ast2->frame_offset *=ast2->sample_size;
1108 155e9ee9 Fabrice Bellard
    }
1109 52a0bbff Michael Niedermayer
1110 155e9ee9 Fabrice Bellard
    /* do the seek */
1111 899681cd Björn Axelsson
    url_fseek(s->pb, pos, SEEK_SET);
1112 7c7f3866 Michael Niedermayer
    avi->stream_index= -1;
1113 155e9ee9 Fabrice Bellard
    return 0;
1114
}
1115
1116 1101abfe Zdenek Kabelac
static int avi_read_close(AVFormatContext *s)
1117 de6d9b64 Fabrice Bellard
{
1118 5ae2c73e Michael Niedermayer
    int i;
1119
    AVIContext *avi = s->priv_data;
1120
1121
    for(i=0;i<s->nb_streams;i++) {
1122
        AVStream *st = s->streams[i];
1123 01f4895c Michael Niedermayer
        av_free(st->codec->palctrl);
1124 5ae2c73e Michael Niedermayer
    }
1125
1126 7458ccbb Roman Shaposhnik
    if (avi->dv_demux)
1127
        av_free(avi->dv_demux);
1128
1129 c9a65ca8 Fabrice Bellard
    return 0;
1130
}
1131
1132
static int avi_probe(AVProbeData *p)
1133
{
1134 7b31b092 Aurelien Jacobs
    int i;
1135
1136 c9a65ca8 Fabrice Bellard
    /* check file header */
1137 7b31b092 Aurelien Jacobs
    for(i=0; avi_headers[i][0]; i++)
1138
        if(!memcmp(p->buf  , avi_headers[i]  , 4) &&
1139
           !memcmp(p->buf+8, avi_headers[i]+4, 4))
1140
            return AVPROBE_SCORE_MAX;
1141
1142
    return 0;
1143 c9a65ca8 Fabrice Bellard
}
1144
1145 ff70e601 Måns Rullgård
AVInputFormat avi_demuxer = {
1146 c9a65ca8 Fabrice Bellard
    "avi",
1147 bde15e74 Stefano Sabatini
    NULL_IF_CONFIG_SMALL("AVI format"),
1148 c9a65ca8 Fabrice Bellard
    sizeof(AVIContext),
1149
    avi_probe,
1150
    avi_read_header,
1151
    avi_read_packet,
1152
    avi_read_close,
1153 155e9ee9 Fabrice Bellard
    avi_read_seek,
1154 c9a65ca8 Fabrice Bellard
};