Statistics
| Branch: | Revision:

ffmpeg / libavformat / avidec.c @ 8a472821

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