avidec: Do not special case palette on big-endian
[libav.git] / libavformat / avidec.c
CommitLineData
de6d9b64 1/*
7fbde343 2 * AVI demuxer
15d6e361 3 * Copyright (c) 2001 Fabrice Bellard
de6d9b64 4 *
2912e87a 5 * This file is part of Libav.
b78e7197 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
19720f15
FB
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
b78e7197 10 * version 2.1 of the License, or (at your option) any later version.
de6d9b64 11 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
de6d9b64 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19720f15
FB
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
de6d9b64 16 *
19720f15 17 * You should have received a copy of the GNU Lesser General Public
2912e87a 18 * License along with Libav; if not, write to the Free Software
5509bffa 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
de6d9b64 20 */
7b114c09 21
d92024f1 22#include <inttypes.h>
8f8bc923 23
10aa44aa 24#include "libavutil/avstring.h"
7b114c09 25#include "libavutil/bswap.h"
d2d67e42 26#include "libavutil/dict.h"
7950e519 27#include "libavutil/internal.h"
10aa44aa
LB
28#include "libavutil/intreadwrite.h"
29#include "libavutil/mathematics.h"
de6d9b64
FB
30#include "avformat.h"
31#include "avi.h"
7458ccbb 32#include "dv.h"
10aa44aa 33#include "internal.h"
4326bc36 34#include "isom.h"
9d9f4119 35#include "riff.h"
de6d9b64 36
52a0bbff
MN
37#undef NDEBUG
38#include <assert.h>
39
155e9ee9 40typedef struct AVIStream {
10aa44aa
LB
41 int64_t frame_offset; /* current frame (video) or byte (audio) counter
42 * (used to compute the pts) */
7c7f3866
MN
43 int remaining;
44 int packet_size;
45
f771b3ab 46 uint32_t handler;
a982e5a0
AK
47 uint32_t scale;
48 uint32_t rate;
10aa44aa
LB
49 int sample_size; /* size of one sample (or packet)
50 * (in the rate/scale sense) in bytes */
115329f1 51
10aa44aa
LB
52 int64_t cum_len; /* temporary storage (used during seek) */
53 int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
d2c5f0a4 54 int prefix_count;
b7c40744
MN
55 uint32_t pal[256];
56 int has_pal;
10aa44aa
LB
57 int dshow_block_align; /* block align variable used to emulate bugs in
58 * the MS dshow demuxer */
37287d41
AJ
59
60 AVFormatContext *sub_ctx;
61 AVPacket sub_pkt;
62 uint8_t *sub_buffer;
155e9ee9 63} AVIStream;
de6d9b64 64
daf8cf35 65typedef struct AVIContext {
10aa44aa
LB
66 int64_t riff_end;
67 int64_t movi_end;
68 int64_t fsize;
bc5c918e 69 int64_t movi_list;
7ccc636f 70 int64_t last_pkt_pos;
155e9ee9 71 int index_loaded;
8f9298f8 72 int is_odml;
7c7f3866
MN
73 int non_interleaved;
74 int stream_index;
10aa44aa 75 DVDemuxContext *dv_demux;
0c0fd063
MN
76 int odml_depth;
77#define MAX_ODML_DEPTH 1000
de6d9b64
FB
78} AVIContext;
79
7b31b092 80static const char avi_headers[][8] = {
10aa44aa
LB
81 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
82 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
83 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
84 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
85 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
7b31b092
AJ
86 { 0 }
87};
88
12bc2050
VV
89static const AVMetadataConv avi_metadata_conv[] = {
90 { "strn", "title" },
91 { 0 },
92};
93
42feef6b 94static int avi_load_index(AVFormatContext *s);
30a43f2d 95static int guess_ni_flag(AVFormatContext *s);
42feef6b 96
10aa44aa 97#define print_tag(str, tag, size) \
1a3eb042 98 av_log(NULL, AV_LOG_TRACE, "%s: tag=%c%c%c%c size=0x%x\n", \
10aa44aa
LB
99 str, tag & 0xff, \
100 (tag >> 8) & 0xff, \
101 (tag >> 16) & 0xff, \
102 (tag >> 24) & 0xff, \
103 size)
de6d9b64 104
10aa44aa
LB
105static inline int get_duration(AVIStream *ast, int len)
106{
107 if (ast->sample_size)
8a472821 108 return len;
10aa44aa
LB
109 else if (ast->dshow_block_align)
110 return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
111 else
8a472821
MN
112 return 1;
113}
114
ae628ec1 115static int get_riff(AVFormatContext *s, AVIOContext *pb)
06219cb1 116{
87ad63c0 117 AVIContext *avi = s->priv_data;
7b31b092
AJ
118 char header[8];
119 int i;
06219cb1 120
7b31b092 121 /* check RIFF header */
b7effd4e 122 avio_read(pb, header, 4);
10aa44aa 123 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
a2704c97 124 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
10aa44aa 125 avio_read(pb, header + 4, 4);
7b31b092 126
10aa44aa
LB
127 for (i = 0; avi_headers[i][0]; i++)
128 if (!memcmp(header, avi_headers[i], 8))
7b31b092 129 break;
10aa44aa 130 if (!avi_headers[i][0])
570a4a01 131 return AVERROR_INVALIDDATA;
115329f1 132
10aa44aa
LB
133 if (header[7] == 0x19)
134 av_log(s, AV_LOG_INFO,
135 "This file has been generated by a totally broken muxer.\n");
7b31b092 136
06219cb1
RS
137 return 0;
138}
139
10aa44aa
LB
140static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
141{
142 AVIContext *avi = s->priv_data;
143 AVIOContext *pb = s->pb;
144 int longs_pre_entry = avio_rl16(pb);
145 int index_sub_type = avio_r8(pb);
146 int index_type = avio_r8(pb);
147 int entries_in_use = avio_rl32(pb);
148 int chunk_id = avio_rl32(pb);
149 int64_t base = avio_rl64(pb);
150 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
151 ((chunk_id >> 8 & 0xFF) - '0');
94d1d6c0
MN
152 AVStream *st;
153 AVIStream *ast;
154 int i;
10aa44aa 155 int64_t last_pos = -1;
90411b33 156 int64_t filesize = avi->fsize;
10aa44aa 157
1a3eb042 158 av_log(s, AV_LOG_TRACE,
10aa44aa
LB
159 "longs_pre_entry:%d index_type:%d entries_in_use:%d "
160 "chunk_id:%X base:%16"PRIX64"\n",
161 longs_pre_entry,
162 index_type,
163 entries_in_use,
164 chunk_id,
165 base);
166
167 if (stream_id >= s->nb_streams || stream_id < 0)
570a4a01 168 return AVERROR_INVALIDDATA;
10aa44aa 169 st = s->streams[stream_id];
94d1d6c0
MN
170 ast = st->priv_data;
171
10aa44aa 172 if (index_sub_type)
570a4a01 173 return AVERROR_INVALIDDATA;
94d1d6c0 174
b7effd4e 175 avio_rl32(pb);
94d1d6c0 176
10aa44aa 177 if (index_type && longs_pre_entry != 2)
570a4a01 178 return AVERROR_INVALIDDATA;
10aa44aa 179 if (index_type > 1)
570a4a01 180 return AVERROR_INVALIDDATA;
94d1d6c0 181
10aa44aa 182 if (filesize > 0 && base >= filesize) {
965a63af 183 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
10aa44aa
LB
184 if (base >> 32 == (base & 0xFFFFFFFF) &&
185 (base & 0xFFFFFFFF) < filesize &&
186 filesize <= 0xFFFFFFFF)
965a63af
MN
187 base &= 0xFFFFFFFF;
188 else
570a4a01 189 return AVERROR_INVALIDDATA;
965a63af
MN
190 }
191
10aa44aa
LB
192 for (i = 0; i < entries_in_use; i++) {
193 if (index_type) {
194 int64_t pos = avio_rl32(pb) + base - 8;
195 int len = avio_rl32(pb);
196 int key = len >= 0;
94d1d6c0
MN
197 len &= 0x7FFFFFFF;
198
1a3eb042 199 av_log(s, AV_LOG_TRACE, "pos:%"PRId64", len:%X\n", pos, len);
919d7a34 200
10aa44aa 201 if (pb->eof_reached)
570a4a01 202 return AVERROR_INVALIDDATA;
8ebe099a 203
10aa44aa
LB
204 if (last_pos == pos || pos == base - 8)
205 avi->non_interleaved = 1;
206 if (last_pos != pos && (len || !ast->sample_size))
207 av_add_index_entry(st, pos, ast->cum_len, len, 0,
208 key ? AVINDEX_KEYFRAME : 0);
30a43f2d 209
8a472821 210 ast->cum_len += get_duration(ast, len);
10aa44aa
LB
211 last_pos = pos;
212 } else {
26b89135
MR
213 int64_t offset, pos;
214 int duration;
b7effd4e
AK
215 offset = avio_rl64(pb);
216 avio_rl32(pb); /* size */
217 duration = avio_rl32(pb);
8ebe099a 218
10aa44aa 219 if (pb->eof_reached)
570a4a01 220 return AVERROR_INVALIDDATA;
8ebe099a 221
a2704c97 222 pos = avio_tell(pb);
94d1d6c0 223
10aa44aa 224 if (avi->odml_depth > MAX_ODML_DEPTH) {
0c0fd063 225 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
570a4a01 226 return AVERROR_INVALIDDATA;
0c0fd063
MN
227 }
228
10aa44aa 229 avio_seek(pb, offset + 8, SEEK_SET);
0c0fd063 230 avi->odml_depth++;
94d1d6c0 231 read_braindead_odml_indx(s, frame_num);
0c0fd063 232 avi->odml_depth--;
94d1d6c0
MN
233 frame_num += duration;
234
6b4aa5da 235 avio_seek(pb, pos, SEEK_SET);
94d1d6c0
MN
236 }
237 }
10aa44aa 238 avi->index_loaded = 1;
94d1d6c0
MN
239 return 0;
240}
241
10aa44aa
LB
242static void clean_index(AVFormatContext *s)
243{
965a63af
MN
244 int i;
245 int64_t j;
115e8ae5 246
10aa44aa
LB
247 for (i = 0; i < s->nb_streams; i++) {
248 AVStream *st = s->streams[i];
115e8ae5 249 AVIStream *ast = st->priv_data;
10aa44aa
LB
250 int n = st->nb_index_entries;
251 int max = ast->sample_size;
115e8ae5
MN
252 int64_t pos, size, ts;
253
10aa44aa 254 if (n != 1 || ast->sample_size == 0)
115e8ae5
MN
255 continue;
256
10aa44aa
LB
257 while (max < 1024)
258 max += max;
115e8ae5 259
10aa44aa
LB
260 pos = st->index_entries[0].pos;
261 size = st->index_entries[0].size;
262 ts = st->index_entries[0].timestamp;
115e8ae5 263
10aa44aa
LB
264 for (j = 0; j < size; j += max)
265 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
266 AVINDEX_KEYFRAME);
115e8ae5
MN
267 }
268}
269
10aa44aa
LB
270static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
271 uint32_t size)
57060f89 272{
ae628ec1 273 AVIOContext *pb = s->pb;
10aa44aa
LB
274 char key[5] = { 0 };
275 char *value;
47146dfb 276
57060f89 277 size += (size & 1);
47146dfb 278
12ad6671 279 if (size == UINT_MAX)
570a4a01 280 return AVERROR(EINVAL);
10aa44aa 281 value = av_malloc(size + 1);
12ad6671 282 if (!value)
570a4a01 283 return AVERROR(ENOMEM);
b7effd4e 284 avio_read(pb, value, size);
10aa44aa 285 value[size] = 0;
12ad6671 286
04d2540c
AK
287 AV_WL32(key, tag);
288
d2d67e42 289 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
10aa44aa 290 AV_DICT_DONT_STRDUP_VAL);
57060f89
DC
291}
292
933875a0
AJ
293static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
294 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
295
d2d67e42 296static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
933875a0
AJ
297{
298 char month[4], time[9], buffer[64];
299 int i, day, year;
300 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
301 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
73d0e331 302 month, &day, time, &year) == 4) {
10aa44aa 303 for (i = 0; i < 12; i++)
bb3244de 304 if (!av_strcasecmp(month, months[i])) {
933875a0 305 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
10aa44aa 306 year, i + 1, day, time);
d2d67e42 307 av_dict_set(metadata, "creation_time", buffer, 0);
933875a0 308 }
73d0e331
AJ
309 } else if (date[4] == '/' && date[7] == '/') {
310 date[4] = date[7] = '-';
d2d67e42 311 av_dict_set(metadata, "creation_time", date, 0);
73d0e331 312 }
933875a0
AJ
313}
314
8ba5bf5a
AJ
315static void avi_read_nikon(AVFormatContext *s, uint64_t end)
316{
a2704c97 317 while (avio_tell(s->pb) < end) {
b7effd4e
AK
318 uint32_t tag = avio_rl32(s->pb);
319 uint32_t size = avio_rl32(s->pb);
8ba5bf5a 320 switch (tag) {
10aa44aa
LB
321 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
322 {
a2704c97
AK
323 uint64_t tag_end = avio_tell(s->pb) + size;
324 while (avio_tell(s->pb) < tag_end) {
10aa44aa
LB
325 uint16_t tag = avio_rl16(s->pb);
326 uint16_t size = avio_rl16(s->pb);
8ba5bf5a 327 const char *name = NULL;
10aa44aa 328 char buffer[64] = { 0 };
b7effd4e 329 size -= avio_read(s->pb, buffer,
10aa44aa 330 FFMIN(size, sizeof(buffer) - 1));
8ba5bf5a 331 switch (tag) {
10aa44aa
LB
332 case 0x03:
333 name = "maker";
334 break;
335 case 0x04:
336 name = "model";
337 break;
338 case 0x13:
339 name = "creation_time";
8ba5bf5a
AJ
340 if (buffer[4] == ':' && buffer[7] == ':')
341 buffer[4] = buffer[7] = '-';
342 break;
343 }
344 if (name)
d2d67e42 345 av_dict_set(&s->metadata, name, buffer, 0);
45a8a02a 346 avio_skip(s->pb, size);
8ba5bf5a
AJ
347 }
348 break;
349 }
350 default:
45a8a02a 351 avio_skip(s->pb, size);
8ba5bf5a
AJ
352 break;
353 }
354 }
355}
356
6e9651d1 357static int avi_read_header(AVFormatContext *s)
de6d9b64 358{
c9a65ca8 359 AVIContext *avi = s->priv_data;
ae628ec1 360 AVIOContext *pb = s->pb;
9d9aac84 361 unsigned int tag, tag1, handler;
e65ab9d9 362 int codec_type, stream_index, frame_period;
bce8840a 363 unsigned int size;
6d29fba9 364 int i;
de6d9b64 365 AVStream *st;
10aa44aa
LB
366 AVIStream *ast = NULL;
367 int avih_width = 0, avih_height = 0;
368 int amv_file_format = 0;
369 uint64_t list_end = 0;
d017ed87 370 int64_t pos;
ca402f32 371 int ret;
de6d9b64 372
10aa44aa 373 avi->stream_index = -1;
115329f1 374
570a4a01
JM
375 ret = get_riff(s, pb);
376 if (ret < 0)
377 return ret;
1101abfe 378
76aa876e 379 avi->fsize = avio_size(pb);
90411b33 380 if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
10aa44aa 381 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
ea4b2b5e 382
de6d9b64
FB
383 /* first list tag */
384 stream_index = -1;
10aa44aa 385 codec_type = -1;
de6d9b64 386 frame_period = 0;
10aa44aa 387 for (;;) {
66e5b1df 388 if (pb->eof_reached)
de6d9b64 389 goto fail;
10aa44aa 390 tag = avio_rl32(pb);
b7effd4e 391 size = avio_rl32(pb);
6081f8c4 392
de6d9b64 393 print_tag("tag", tag, size);
de6d9b64 394
10aa44aa 395 switch (tag) {
de6d9b64 396 case MKTAG('L', 'I', 'S', 'T'):
a2704c97 397 list_end = avio_tell(pb) + size;
15d6e361 398 /* Ignored, except at start of video packets. */
b7effd4e 399 tag1 = avio_rl32(pb);
6081f8c4 400
de6d9b64 401 print_tag("list", tag1, 0);
6081f8c4 402
de6d9b64 403 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
a2704c97 404 avi->movi_list = avio_tell(pb) - 4;
10aa44aa
LB
405 if (size)
406 avi->movi_end = avi->movi_list + size + (size & 1);
407 else
90411b33 408 avi->movi_end = avi->fsize;
1a3eb042 409 av_log(NULL, AV_LOG_TRACE, "movi end=%"PRIx64"\n", avi->movi_end);
de6d9b64 410 goto end_of_header;
10aa44aa 411 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
12bc2050 412 ff_read_riff_info(s, size - 4);
8ba5bf5a
AJ
413 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
414 avi_read_nikon(s, list_end);
04d2540c 415
de6d9b64 416 break;
10aa44aa
LB
417 case MKTAG('I', 'D', 'I', 'T'):
418 {
419 unsigned char date[64] = { 0 };
933875a0 420 size += (size & 1);
10aa44aa 421 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
45a8a02a 422 avio_skip(pb, size);
933875a0
AJ
423 avi_metadata_creation_time(&s->metadata, date);
424 break;
425 }
8f9298f8 426 case MKTAG('d', 'm', 'l', 'h'):
bb270c08 427 avi->is_odml = 1;
45a8a02a 428 avio_skip(pb, size + (size & 1));
bb270c08 429 break;
0b04ebb3 430 case MKTAG('a', 'm', 'v', 'h'):
10aa44aa 431 amv_file_format = 1;
de6d9b64 432 case MKTAG('a', 'v', 'i', 'h'):
15d6e361 433 /* AVI header */
1101abfe 434 /* using frame_period is bad idea */
b7effd4e 435 frame_period = avio_rl32(pb);
e65ab9d9 436 avio_skip(pb, 4);
b7effd4e
AK
437 avio_rl32(pb);
438 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
1894edeb 439
45a8a02a 440 avio_skip(pb, 2 * 4);
b7effd4e
AK
441 avio_rl32(pb);
442 avio_rl32(pb);
10aa44aa
LB
443 avih_width = avio_rl32(pb);
444 avih_height = avio_rl32(pb);
6d29fba9 445
45a8a02a 446 avio_skip(pb, size - 10 * 4);
6d29fba9
MN
447 break;
448 case MKTAG('s', 't', 'r', 'h'):
449 /* stream header */
450
10aa44aa 451 tag1 = avio_rl32(pb);
b7effd4e 452 handler = avio_rl32(pb); /* codec tag */
6d29fba9 453
10aa44aa 454 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
45a8a02a 455 avio_skip(pb, size - 8);
6d29fba9 456 break;
10aa44aa 457 } else {
6d29fba9 458 stream_index++;
84ad31ff 459 st = avformat_new_stream(s, NULL);
de6d9b64
FB
460 if (!st)
461 goto fail;
9ee91c2f 462
84ad31ff 463 st->id = stream_index;
10aa44aa 464 ast = av_mallocz(sizeof(AVIStream));
155e9ee9
FB
465 if (!ast)
466 goto fail;
467 st->priv_data = ast;
bb270c08 468 }
10aa44aa
LB
469 if (amv_file_format)
470 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
471 : MKTAG('v', 'i', 'd', 's');
6d29fba9 472
e344c1ea 473 print_tag("strh", tag1, -1);
6081f8c4 474
10aa44aa
LB
475 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
476 tag1 == MKTAG('i', 'v', 'a', 's')) {
6eb2de74
RS
477 int64_t dv_dur;
478
10aa44aa
LB
479 /* After some consideration -- I don't think we
480 * have to support anything but DV in type1 AVIs. */
bb270c08
DB
481 if (s->nb_streams != 1)
482 goto fail;
483
484 if (handler != MKTAG('d', 'v', 's', 'd') &&
485 handler != MKTAG('d', 'v', 'h', 'd') &&
486 handler != MKTAG('d', 'v', 's', 'l'))
10aa44aa 487 goto fail;
bb270c08
DB
488
489 ast = s->streams[0]->priv_data;
9200514a
AK
490 av_freep(&s->streams[0]->codecpar->extradata);
491 av_freep(&s->streams[0]->codecpar);
ce9bba53 492 av_freep(&s->streams[0]->info);
bb270c08
DB
493 av_freep(&s->streams[0]);
494 s->nb_streams = 0;
49fb20cb 495 if (CONFIG_DV_DEMUXER) {
ab88b25f 496 avi->dv_demux = avpriv_dv_init_demux(s);
38ca53da
AJ
497 if (!avi->dv_demux)
498 goto fail;
1cac9acc
LB
499 } else
500 goto fail;
bb270c08 501 s->streams[0]->priv_data = ast;
45a8a02a 502 avio_skip(pb, 3 * 4);
b7effd4e 503 ast->scale = avio_rl32(pb);
10aa44aa 504 ast->rate = avio_rl32(pb);
45a8a02a 505 avio_skip(pb, 4); /* start time */
6eb2de74 506
b7effd4e 507 dv_dur = avio_rl32(pb);
6eb2de74 508 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
10aa44aa 509 dv_dur *= AV_TIME_BASE;
6eb2de74
RS
510 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
511 }
10aa44aa
LB
512 /* else, leave duration alone; timing estimation in utils.c
513 * will make a guess based on bitrate. */
6eb2de74 514
bb270c08 515 stream_index = s->nb_streams - 1;
10aa44aa 516 avio_skip(pb, size - 9 * 4);
b53f1064
MN
517 break;
518 }
b559b29b 519
6d29fba9 520 assert(stream_index < s->nb_streams);
f771b3ab 521 ast->handler = handler;
b559b29b 522
b7effd4e
AK
523 avio_rl32(pb); /* flags */
524 avio_rl16(pb); /* priority */
525 avio_rl16(pb); /* language */
526 avio_rl32(pb); /* initial frame */
527 ast->scale = avio_rl32(pb);
10aa44aa
LB
528 ast->rate = avio_rl32(pb);
529 if (!(ast->scale && ast->rate)) {
530 av_log(s, AV_LOG_WARNING,
d92024f1 531 "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
10aa44aa
LB
532 "(This file has been generated by broken software.)\n",
533 ast->scale,
534 ast->rate);
535 if (frame_period) {
536 ast->rate = 1000000;
0dbb6515 537 ast->scale = frame_period;
10aa44aa
LB
538 } else {
539 ast->rate = 25;
0dbb6515
MN
540 ast->scale = 1;
541 }
4a030a1f 542 }
c3f9ebf7 543 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
115329f1 544
10aa44aa 545 ast->cum_len = avio_rl32(pb); /* start */
b7effd4e 546 st->nb_frames = avio_rl32(pb);
b559b29b 547
b53f1064 548 st->start_time = 0;
b7effd4e
AK
549 avio_rl32(pb); /* buffer size */
550 avio_rl32(pb); /* quality */
41ed7ab4 551 ast->sample_size = avio_rl32(pb); /* sample size */
10aa44aa 552 ast->cum_len *= FFMAX(1, ast->sample_size);
1a3eb042 553 av_log(s, AV_LOG_TRACE, "%"PRIu32" %"PRIu32" %d\n",
72eaba5e 554 ast->rate, ast->scale, ast->sample_size);
247eadca 555
10aa44aa 556 switch (tag1) {
bb270c08 557 case MKTAG('v', 'i', 'd', 's'):
72415b2a 558 codec_type = AVMEDIA_TYPE_VIDEO;
247eadca 559
b53f1064 560 ast->sample_size = 0;
b53f1064
MN
561 break;
562 case MKTAG('a', 'u', 'd', 's'):
72415b2a 563 codec_type = AVMEDIA_TYPE_AUDIO;
9bf9a5fc 564 break;
cc11e2b3 565 case MKTAG('t', 'x', 't', 's'):
37287d41 566 codec_type = AVMEDIA_TYPE_SUBTITLE;
cc11e2b3 567 break;
25176d6e 568 case MKTAG('d', 'a', 't', 's'):
72415b2a 569 codec_type = AVMEDIA_TYPE_DATA;
25176d6e 570 break;
9bf9a5fc 571 default:
30667f42 572 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
9bf9a5fc 573 goto fail;
de6d9b64 574 }
4d0ee496
AC
575
576 if (ast->sample_size < 0) {
577 if (s->error_recognition & AV_EF_EXPLODE) {
578 av_log(s, AV_LOG_ERROR,
579 "Invalid sample_size %d at stream %d\n",
580 ast->sample_size,
581 stream_index);
582 goto fail;
583 }
584 av_log(s, AV_LOG_WARNING,
585 "Invalid sample_size %d at stream %d "
586 "setting it to 0\n",
587 ast->sample_size,
588 stream_index);
589 ast->sample_size = 0;
590 }
591
10aa44aa 592 if (ast->sample_size == 0)
3c8d75e6 593 st->duration = st->nb_frames;
10aa44aa 594 ast->frame_offset = ast->cum_len;
45a8a02a 595 avio_skip(pb, size - 12 * 4);
de6d9b64
FB
596 break;
597 case MKTAG('s', 't', 'r', 'f'):
598 /* stream header */
6d29fba9 599 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
45a8a02a 600 avio_skip(pb, size);
de6d9b64 601 } else {
a2704c97 602 uint64_t cur_pos = avio_tell(pb);
5a4a4d78
RD
603 if (cur_pos < list_end)
604 size = FFMIN(size, list_end - cur_pos);
de6d9b64 605 st = s->streams[stream_index];
10aa44aa 606 switch (codec_type) {
72415b2a 607 case AVMEDIA_TYPE_VIDEO:
10aa44aa 608 if (amv_file_format) {
9200514a
AK
609 st->codecpar->width = avih_width;
610 st->codecpar->height = avih_height;
611 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
612 st->codecpar->codec_id = AV_CODEC_ID_AMV;
45a8a02a 613 avio_skip(pb, size);
0b04ebb3
VV
614 break;
615 }
456a70ae 616 tag1 = ff_get_bmp_header(pb, st);
b559b29b 617
10aa44aa
LB
618 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
619 tag1 == MKTAG('D', 'X', 'S', 'A')) {
9200514a
AK
620 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
621 st->codecpar->codec_tag = tag1;
622 st->codecpar->codec_id = AV_CODEC_ID_XSUB;
cbb79c0e
RD
623 break;
624 }
625
10aa44aa 626 if (size > 10 * 4 && size < (1 << 30)) {
9200514a
AK
627 st->codecpar->extradata_size = size - 10 * 4;
628 st->codecpar->extradata = av_malloc(st->codecpar->extradata_size +
629 AV_INPUT_BUFFER_PADDING_SIZE);
630 if (!st->codecpar->extradata) {
631 st->codecpar->extradata_size = 0;
3dcddf82
RD
632 return AVERROR(ENOMEM);
633 }
10aa44aa 634 avio_read(pb,
9200514a
AK
635 st->codecpar->extradata,
636 st->codecpar->extradata_size);
e344c1ea 637 }
115329f1 638
10aa44aa 639 // FIXME: check if the encoder really did this correctly
9200514a 640 if (st->codecpar->extradata_size & 1)
b7effd4e 641 avio_r8(pb);
b559b29b 642
10aa44aa
LB
643 /* Extract palette from extradata if bpp <= 8.
644 * This code assumes that extradata contains only palette.
645 * This is true for all paletted codecs implemented in
646 * Libav. */
9200514a
AK
647 if (st->codecpar->extradata_size &&
648 (st->codecpar->bits_per_coded_sample <= 8)) {
649 int pal_size = (1 << st->codecpar->bits_per_coded_sample) << 2;
23f40a07
KS
650 const uint8_t *pal_src;
651
9200514a
AK
652 pal_size = FFMIN(pal_size, st->codecpar->extradata_size);
653 pal_src = st->codecpar->extradata +
654 st->codecpar->extradata_size - pal_size;
10aa44aa 655 for (i = 0; i < pal_size / 4; i++)
bad4aad4 656 ast->pal[i] = AV_RL32(pal_src + 4 * i);
2d8591c2 657 ast->has_pal = 1;
5e29abf8
RT
658 }
659
de6d9b64 660 print_tag("video", tag1, 0);
6081f8c4 661
9200514a
AK
662 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
663 st->codecpar->codec_tag = tag1;
664 st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
10aa44aa 665 tag1);
4326bc36 666 /* If codec is not found yet, try with the mov tags. */
9200514a 667 if (!st->codecpar->codec_id) {
4326bc36
CEH
668 char tag_buf[32];
669 av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag1);
9200514a 670 st->codecpar->codec_id =
4326bc36 671 ff_codec_get_id(ff_codec_movvideo_tags, tag1);
9200514a 672 if (st->codecpar->codec_id)
4326bc36
CEH
673 av_log(s, AV_LOG_WARNING,
674 "mov tag found in avi (fourcc %s)\n",
675 tag_buf);
676 }
10aa44aa
LB
677 /* This is needed to get the pict type which is necessary
678 * for generating correct pts. */
679 st->need_parsing = AVSTREAM_PARSE_HEADERS;
f771b3ab 680
9200514a 681 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4 &&
f771b3ab 682 ast->handler == MKTAG('X', 'V', 'I', 'D'))
9200514a 683 st->codecpar->codec_tag = MKTAG('X', 'V', 'I', 'D');
f771b3ab 684
0941ee0f 685 // Support "Resolution 1:1" for Avid AVI Codec
10aa44aa 686 if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
9200514a
AK
687 st->codecpar->extradata_size >= 31 &&
688 !memcmp(&st->codecpar->extradata[28], "1:1", 3))
689 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
690
691 if (st->codecpar->codec_tag == 0 && st->codecpar->height > 0 &&
692 st->codecpar->extradata_size < 1U << 30) {
693 st->codecpar->extradata_size += 9;
694 if ((ret = av_reallocp(&st->codecpar->extradata,
695 st->codecpar->extradata_size +
059a9348 696 AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {
9200514a 697 st->codecpar->extradata_size = 0;
5626f994 698 return ret;
d872fb0f 699 } else
9200514a 700 memcpy(st->codecpar->extradata + st->codecpar->extradata_size - 9,
10aa44aa 701 "BottomUp", 9);
31f2616d 702 }
9200514a 703 st->codecpar->height = FFABS(st->codecpar->height);
31f2616d 704
45a8a02a 705// avio_skip(pb, size - 5 * 4);
de6d9b64 706 break;
72415b2a 707 case AVMEDIA_TYPE_AUDIO:
9200514a 708 ret = ff_get_wav_header(s, pb, st->codecpar, size);
ca402f32
MH
709 if (ret < 0)
710 return ret;
9200514a
AK
711 ast->dshow_block_align = st->codecpar->block_align;
712 if (ast->sample_size && st->codecpar->block_align &&
713 ast->sample_size != st->codecpar->block_align) {
10aa44aa
LB
714 av_log(s,
715 AV_LOG_WARNING,
716 "sample size (%d) != block align (%d)\n",
717 ast->sample_size,
9200514a
AK
718 st->codecpar->block_align);
719 ast->sample_size = st->codecpar->block_align;
78db672c 720 }
10aa44aa
LB
721 /* 2-aligned
722 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
723 if (size & 1)
45a8a02a 724 avio_skip(pb, 1);
5836d158 725 /* Force parsing as several audio frames can be in
15d6e361 726 * one packet and timestamps refer to packet start. */
a74008a4 727 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
15d6e361
DB
728 /* ADTS header is in extradata, AAC without header must be
729 * stored as exact frames. Parser not needed and it will
730 * fail. */
9200514a
AK
731 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
732 st->codecpar->extradata_size)
57004ff1 733 st->need_parsing = AVSTREAM_PARSE_NONE;
8662900b
DB
734 /* AVI files with Xan DPCM audio (wrongly) declare PCM
735 * audio in the header but have Axan as stream_code_tag. */
f771b3ab 736 if (ast->handler == AV_RL32("Axan")) {
9200514a
AK
737 st->codecpar->codec_id = AV_CODEC_ID_XAN_DPCM;
738 st->codecpar->codec_tag = 0;
8662900b 739 }
10aa44aa 740 if (amv_file_format) {
9200514a 741 st->codecpar->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
9862f9e1
MN
742 ast->dshow_block_align = 0;
743 }
de6d9b64 744 break;
37287d41 745 case AVMEDIA_TYPE_SUBTITLE:
9200514a
AK
746 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
747 st->codecpar->codec_id = AV_CODEC_ID_PROBE;
37287d41 748 break;
de6d9b64 749 default:
9200514a
AK
750 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
751 st->codecpar->codec_id = AV_CODEC_ID_NONE;
752 st->codecpar->codec_tag = 0;
45a8a02a 753 avio_skip(pb, size);
de6d9b64
FB
754 break;
755 }
756 }
757 break;
94d1d6c0 758 case MKTAG('i', 'n', 'd', 'x'):
d017ed87 759 pos = avio_tell(pb);
83548fe8
AK
760 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) &&
761 !(s->flags & AVFMT_FLAG_IGNIDX) &&
10aa44aa
LB
762 read_braindead_odml_indx(s, 0) < 0 &&
763 (s->error_recognition & AV_EF_EXPLODE))
2f63440c 764 goto fail;
d017ed87 765 avio_seek(pb, pos + size, SEEK_SET);
94d1d6c0 766 break;
c86ec2f4 767 case MKTAG('v', 'p', 'r', 'p'):
10aa44aa 768 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
c86ec2f4
MN
769 AVRational active, active_aspect;
770
771 st = s->streams[stream_index];
b7effd4e
AK
772 avio_rl32(pb);
773 avio_rl32(pb);
774 avio_rl32(pb);
775 avio_rl32(pb);
776 avio_rl32(pb);
777
10aa44aa
LB
778 active_aspect.den = avio_rl16(pb);
779 active_aspect.num = avio_rl16(pb);
780 active.num = avio_rl32(pb);
781 active.den = avio_rl32(pb);
782 avio_rl32(pb); // nbFieldsPerFrame
c86ec2f4 783
10aa44aa
LB
784 if (active_aspect.num && active_aspect.den &&
785 active.num && active.den) {
786 st->sample_aspect_ratio = av_div_q(active_aspect, active);
1a3eb042 787 av_log(s, AV_LOG_TRACE, "vprp %d/%d %d/%d\n",
72eaba5e
DB
788 active_aspect.num, active_aspect.den,
789 active.num, active.den);
c86ec2f4 790 }
10aa44aa 791 size -= 9 * 4;
c86ec2f4 792 }
45a8a02a 793 avio_skip(pb, size);
c86ec2f4 794 break;
7a9af8ec 795 case MKTAG('s', 't', 'r', 'n'):
10aa44aa
LB
796 if (s->nb_streams) {
797 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
570a4a01
JM
798 if (ret < 0)
799 return ret;
7a9af8ec
MN
800 break;
801 }
de6d9b64 802 default:
10aa44aa
LB
803 if (size > 1000000) {
804 av_log(s, AV_LOG_ERROR,
805 "Something went wrong during header parsing, "
806 "I will ignore it and try to continue anyway.\n");
b89f8774
DB
807 if (s->error_recognition & AV_EF_EXPLODE)
808 goto fail;
a2704c97 809 avi->movi_list = avio_tell(pb) - 4;
90411b33 810 avi->movi_end = avi->fsize;
755c18ae
MN
811 goto end_of_header;
812 }
de6d9b64
FB
813 /* skip tag */
814 size += (size & 1);
45a8a02a 815 avio_skip(pb, size);
de6d9b64
FB
816 break;
817 }
818 }
10aa44aa
LB
819
820end_of_header:
de6d9b64
FB
821 /* check stream number */
822 if (stream_index != s->nb_streams - 1) {
10aa44aa
LB
823
824fail:
570a4a01 825 return AVERROR_INVALIDDATA;
de6d9b64 826 }
1101abfe 827
83548fe8 828 if (!avi->index_loaded && (pb->seekable & AVIO_SEEKABLE_NORMAL))
94d1d6c0 829 avi_load_index(s);
10aa44aa 830 avi->index_loaded = 1;
9d599e3f
MN
831
832 if ((ret = guess_ni_flag(s)) < 0)
833 return ret;
834
835 avi->non_interleaved |= ret;
10aa44aa 836 for (i = 0; i < s->nb_streams; i++) {
fbfccc04 837 AVStream *st = s->streams[i];
10aa44aa 838 if (st->nb_index_entries)
fbfccc04
MN
839 break;
840 }
10aa44aa
LB
841 if (i == s->nb_streams && avi->non_interleaved) {
842 av_log(s, AV_LOG_WARNING,
843 "Non-interleaved AVI without index, switching to interleaved\n");
844 avi->non_interleaved = 0;
fbfccc04
MN
845 }
846
10aa44aa 847 if (avi->non_interleaved) {
15d6e361 848 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
115e8ae5 849 clean_index(s);
9d4cd3bf 850 }
115329f1 851
12bc2050
VV
852 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
853 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
03700d39 854
de6d9b64
FB
855 return 0;
856}
857
10aa44aa
LB
858static int read_gab2_sub(AVStream *st, AVPacket *pkt)
859{
8d07258b
MS
860 if (pkt->size >= 7 &&
861 !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
47fdf00a 862 uint8_t desc[256];
10aa44aa 863 int score = AVPROBE_SCORE_EXTENSION, ret;
37287d41
AJ
864 AVIStream *ast = st->priv_data;
865 AVInputFormat *sub_demuxer;
866 AVRational time_base;
10aa44aa
LB
867 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
868 pkt->size - 7,
869 0, NULL, NULL, NULL, NULL);
37287d41 870 AVProbeData pd;
b7effd4e 871 unsigned int desc_len = avio_rl32(pb);
37287d41 872
47fdf00a
AK
873 if (desc_len > pb->buf_end - pb->buf_ptr)
874 goto error;
37287d41 875
47fdf00a 876 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
45a8a02a 877 avio_skip(pb, desc_len - ret);
37287d41 878 if (*desc)
d2d67e42 879 av_dict_set(&st->metadata, "title", desc, 0);
37287d41 880
b7effd4e
AK
881 avio_rl16(pb); /* flags? */
882 avio_rl32(pb); /* data size */
37287d41 883
10aa44aa
LB
884 pd = (AVProbeData) { .buf = pb->buf_ptr,
885 .buf_size = pb->buf_end - pb->buf_ptr };
37287d41 886 if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
47fdf00a 887 goto error;
37287d41 888
603b8bc2
AK
889 if (!(ast->sub_ctx = avformat_alloc_context()))
890 goto error;
891
10aa44aa 892 ast->sub_ctx->pb = pb;
603b8bc2 893 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
3c90cc2e 894 ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
9200514a 895 avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
37287d41 896 time_base = ast->sub_ctx->streams[0]->time_base;
c3f9ebf7 897 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
37287d41
AJ
898 }
899 ast->sub_buffer = pkt->data;
900 memset(pkt, 0, sizeof(*pkt));
901 return 1;
10aa44aa 902
47fdf00a
AK
903error:
904 av_freep(&pb);
37287d41
AJ
905 }
906 return 0;
907}
908
909static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
910 AVPacket *pkt)
911{
912 AVIStream *ast, *next_ast = next_st->priv_data;
913 int64_t ts, next_ts, ts_min = INT64_MAX;
914 AVStream *st, *sub_st = NULL;
915 int i;
916
917 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
918 AV_TIME_BASE_Q);
919
10aa44aa 920 for (i = 0; i < s->nb_streams; i++) {
37287d41
AJ
921 st = s->streams[i];
922 ast = st->priv_data;
4ed899f2 923 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
37287d41
AJ
924 ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
925 if (ts <= next_ts && ts < ts_min) {
926 ts_min = ts;
927 sub_st = st;
928 }
929 }
930 }
931
932 if (sub_st) {
10aa44aa
LB
933 ast = sub_st->priv_data;
934 *pkt = ast->sub_pkt;
37287d41 935 pkt->stream_index = sub_st->index;
10aa44aa 936
3c90cc2e 937 if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
37287d41
AJ
938 ast->sub_pkt.data = NULL;
939 }
940 return sub_st;
941}
942
10aa44aa
LB
943static int get_stream_idx(int *d)
944{
945 if (d[0] >= '0' && d[0] <= '9' &&
946 d[1] >= '0' && d[1] <= '9') {
f080a7bd 947 return (d[0] - '0') * 10 + (d[1] - '0');
10aa44aa
LB
948 } else {
949 return 100; // invalid stream ID
f080a7bd
MN
950 }
951}
952
d3f610c1 953static int avi_sync(AVFormatContext *s, int exit_early)
de6d9b64
FB
954{
955 AVIContext *avi = s->priv_data;
ae628ec1 956 AVIOContext *pb = s->pb;
1703013c
MR
957 int n;
958 unsigned int d[8];
f5007cc8 959 unsigned int size;
bc5c918e 960 int64_t i, sync;
8b84af74
AC
961
962start_sync:
2886f675 963 memset(d, -1, sizeof(d));
10aa44aa 964 for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
8b84af74
AC
965 int j;
966
10aa44aa
LB
967 for (j = 0; j < 7; j++)
968 d[j] = d[j + 1];
969 d[7] = avio_r8(pb);
8b84af74 970
10aa44aa 971 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
8b84af74 972
10aa44aa 973 n = get_stream_idx(d + 2);
1a3eb042 974 av_log(s, AV_LOG_TRACE, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
72eaba5e 975 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
10aa44aa 976 if (i + (uint64_t)size > avi->fsize || d[0] > 127)
8b84af74
AC
977 continue;
978
10aa44aa
LB
979 // parse ix##
980 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
981 // parse JUNK
982 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
983 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
8b84af74 984 avio_skip(pb, size);
8b84af74
AC
985 goto start_sync;
986 }
987
10aa44aa
LB
988 // parse stray LIST
989 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
8b84af74
AC
990 avio_skip(pb, 4);
991 goto start_sync;
992 }
993
0fc61c6a 994 n = get_stream_idx(d);
8b84af74 995
10aa44aa
LB
996 if (!((i - avi->last_pkt_pos) & 1) &&
997 get_stream_idx(d + 1) < s->nb_streams)
8b84af74
AC
998 continue;
999
10aa44aa
LB
1000 // detect ##ix chunk and skip
1001 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
8b84af74
AC
1002 avio_skip(pb, size);
1003 goto start_sync;
1004 }
1005
0fc61c6a
MN
1006 if (avi->dv_demux && n != 0)
1007 continue;
1008
10aa44aa
LB
1009 // parse ##dc/##wb
1010 if (n < s->nb_streams) {
8b84af74
AC
1011 AVStream *st;
1012 AVIStream *ast;
10aa44aa 1013 st = s->streams[n];
8b84af74
AC
1014 ast = st->priv_data;
1015
10aa44aa
LB
1016 if (s->nb_streams >= 2) {
1017 AVStream *st1 = s->streams[1];
1018 AVIStream *ast1 = st1->priv_data;
1019 // workaround for broken small-file-bug402.avi
1020 if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
9200514a
AK
1021 st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1022 st1->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
10aa44aa
LB
1023 ast->prefix == 'd' * 256 + 'c' &&
1024 (d[2] * 256 + d[3] == ast1->prefix ||
1025 !ast1->prefix_count)) {
1026 n = 1;
1027 st = st1;
8b84af74 1028 ast = ast1;
10aa44aa
LB
1029 av_log(s, AV_LOG_WARNING,
1030 "Invalid stream + prefix combination, assuming audio.\n");
8b84af74
AC
1031 }
1032 }
1033
c8f0b20b
LB
1034 if (!avi->dv_demux &&
1035 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
1036 // FIXME: needs a little reordering
1037 (st->discard >= AVDISCARD_NONKEY &&
1038 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1039 || st->discard >= AVDISCARD_ALL)) {
d3f610c1
AC
1040 if (!exit_early) {
1041 ast->frame_offset += get_duration(ast, size);
1042 }
8b84af74
AC
1043 avio_skip(pb, size);
1044 goto start_sync;
1045 }
1046
10aa44aa
LB
1047 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1048 int k = avio_r8(pb);
8b84af74
AC
1049 int last = (k + avio_r8(pb) - 1) & 0xFF;
1050
10aa44aa 1051 avio_rl16(pb); // flags
8b84af74 1052
10aa44aa 1053 // b + (g << 8) + (r << 16);
8b84af74 1054 for (; k <= last; k++)
10aa44aa 1055 ast->pal[k] = avio_rb32(pb) >> 8;
8b84af74 1056
10aa44aa
LB
1057 ast->has_pal = 1;
1058 goto start_sync;
1059 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1060 d[2] < 128 && d[3] < 128) ||
1061 d[2] * 256 + d[3] == ast->prefix /* ||
1062 (d[2] == 'd' && d[3] == 'c') ||
1063 (d[2] == 'w' && d[3] == 'b') */) {
d3f610c1
AC
1064 if (exit_early)
1065 return 0;
10aa44aa 1066 if (d[2] * 256 + d[3] == ast->prefix)
8b84af74 1067 ast->prefix_count++;
10aa44aa
LB
1068 else {
1069 ast->prefix = d[2] * 256 + d[3];
1070 ast->prefix_count = 0;
8b84af74
AC
1071 }
1072
10aa44aa
LB
1073 avi->stream_index = n;
1074 ast->packet_size = size + 8;
1075 ast->remaining = size;
8b84af74 1076
10aa44aa
LB
1077 if (size || !ast->sample_size) {
1078 uint64_t pos = avio_tell(pb) - 8;
1079 if (!st->index_entries || !st->nb_index_entries ||
1080 st->index_entries[st->nb_index_entries - 1].pos < pos) {
1081 av_add_index_entry(st, pos, ast->frame_offset, size,
1082 0, AVINDEX_KEYFRAME);
8b84af74
AC
1083 }
1084 }
1085 return 0;
1086 }
1087 }
1088 }
1089
1090 return AVERROR_EOF;
1091}
1092
5f3a081b
LB
1093static int ni_prepare_read(AVFormatContext *s)
1094{
1095 AVIContext *avi = s->priv_data;
1096 int best_stream_index = 0;
1097 AVStream *best_st = NULL;
1098 AVIStream *best_ast;
1099 int64_t best_ts = INT64_MAX;
1100 int i;
1101
1102 for (i = 0; i < s->nb_streams; i++) {
1103 AVStream *st = s->streams[i];
1104 AVIStream *ast = st->priv_data;
1105 int64_t ts = ast->frame_offset;
1106 int64_t last_ts;
1107
1108 if (!st->nb_index_entries)
1109 continue;
1110
1111 last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1112 if (!ast->remaining && ts > last_ts)
1113 continue;
1114
1115 ts = av_rescale_q(ts, st->time_base,
1116 (AVRational) { FFMAX(1, ast->sample_size),
1117 AV_TIME_BASE });
1118
1119 av_log(s, AV_LOG_TRACE, "%"PRId64" %d/%d %"PRId64"\n", ts,
1120 st->time_base.num, st->time_base.den, ast->frame_offset);
1121 if (ts < best_ts) {
1122 best_ts = ts;
1123 best_st = st;
1124 best_stream_index = i;
1125 }
1126 }
1127 if (!best_st)
1128 return AVERROR_EOF;
1129
1130 best_ast = best_st->priv_data;
1131 best_ts = av_rescale_q(best_ts,
1132 (AVRational) { FFMAX(1, best_ast->sample_size),
1133 AV_TIME_BASE },
1134 best_st->time_base);
1135 if (best_ast->remaining) {
1136 i = av_index_search_timestamp(best_st,
1137 best_ts,
1138 AVSEEK_FLAG_ANY |
1139 AVSEEK_FLAG_BACKWARD);
1140 } else {
1141 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1142 if (i >= 0)
1143 best_ast->frame_offset = best_st->index_entries[i].timestamp;
1144 }
1145
1146 if (i >= 0) {
1147 int64_t pos = best_st->index_entries[i].pos;
1148 pos += best_ast->packet_size - best_ast->remaining;
1149 avio_seek(s->pb, pos + 8, SEEK_SET);
1150
1151 assert(best_ast->remaining <= best_ast->packet_size);
1152
1153 avi->stream_index = best_stream_index;
1154 if (!best_ast->remaining)
1155 best_ast->packet_size =
1156 best_ast->remaining = best_st->index_entries[i].size;
1157 }
1158
1159 return 0;
1160}
1161
8b84af74
AC
1162static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1163{
1164 AVIContext *avi = s->priv_data;
1165 AVIOContext *pb = s->pb;
1166 int err;
115329f1 1167
49fb20cb 1168 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
ab88b25f 1169 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
bb270c08
DB
1170 if (size >= 0)
1171 return size;
ceec6e79
LB
1172 else
1173 goto resync;
2af7e610 1174 }
115329f1 1175
10aa44aa 1176 if (avi->non_interleaved) {
5f3a081b
LB
1177 err = ni_prepare_read(s);
1178 if (err < 0)
1179 return err;
7c7f3866 1180 }
115329f1 1181
4a8d5135 1182resync:
10aa44aa
LB
1183 if (avi->stream_index >= 0) {
1184 AVStream *st = s->streams[avi->stream_index];
1185 AVIStream *ast = st->priv_data;
c60a0f85 1186 int size, err;
115329f1 1187
10aa44aa 1188 if (get_subtitle_pkt(s, st, pkt))
37287d41
AJ
1189 return 0;
1190
10aa44aa
LB
1191 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1192 if (ast->sample_size <= 1)
1193 size = INT_MAX;
1194 else if (ast->sample_size < 32)
28eb5773 1195 // arbitrary multiplier to avoid tiny packets for raw PCM data
10aa44aa 1196 size = 1024 * ast->sample_size;
7c7f3866 1197 else
10aa44aa 1198 size = ast->sample_size;
7c7f3866 1199
10aa44aa
LB
1200 if (size > ast->remaining)
1201 size = ast->remaining;
1202 avi->last_pkt_pos = avio_tell(pb);
1203 err = av_get_packet(pb, pkt, size);
1204 if (err < 0)
c60a0f85 1205 return err;
115329f1 1206
10aa44aa 1207 if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
2d8591c2 1208 uint8_t *pal;
10aa44aa
LB
1209 pal = av_packet_new_side_data(pkt,
1210 AV_PKT_DATA_PALETTE,
1211 AVPALETTE_SIZE);
1212 if (!pal) {
1213 av_log(s, AV_LOG_ERROR,
1214 "Failed to allocate data for palette\n");
1215 } else {
2d8591c2
KS
1216 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1217 ast->has_pal = 0;
1218 }
b7c40744
MN
1219 }
1220
49fb20cb 1221 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1afddbe5 1222 AVBufferRef *avbuf = pkt->buf;
ab88b25f 1223 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
10aa44aa 1224 pkt->data, pkt->size);
10aa44aa 1225 pkt->buf = avbuf;
cc947f04 1226 pkt->flags |= AV_PKT_FLAG_KEY;
bbfb2c80 1227 if (size < 0)
ce70f28a 1228 av_packet_unref(pkt);
9200514a
AK
1229 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1230 !st->codecpar->codec_tag && read_gab2_sub(st, pkt)) {
37287d41
AJ
1231 ast->frame_offset++;
1232 avi->stream_index = -1;
10aa44aa 1233 ast->remaining = 0;
37287d41 1234 goto resync;
7c7f3866 1235 } else {
15d6e361 1236 /* XXX: How to handle B-frames in AVI? */
7c7f3866
MN
1237 pkt->dts = ast->frame_offset;
1238// pkt->dts += ast->start;
10aa44aa 1239 if (ast->sample_size)
7c7f3866 1240 pkt->dts /= ast->sample_size;
1a3eb042 1241 av_log(s, AV_LOG_TRACE,
10aa44aa
LB
1242 "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
1243 "base:%d st:%d size:%d\n",
1244 pkt->dts,
1245 ast->frame_offset,
1246 ast->scale,
1247 ast->rate,
1248 ast->sample_size,
1249 AV_TIME_BASE,
1250 avi->stream_index,
1251 size);
7c7f3866
MN
1252 pkt->stream_index = avi->stream_index;
1253
9200514a 1254 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
4323b09d
MN
1255 AVIndexEntry *e;
1256 int index;
ded3c7da 1257 assert(st->index_entries);
7c7f3866 1258
10aa44aa
LB
1259 index = av_index_search_timestamp(st, ast->frame_offset, 0);
1260 e = &st->index_entries[index];
115329f1 1261
10aa44aa 1262 if (index >= 0 && e->timestamp == ast->frame_offset)
4323b09d 1263 if (e->flags & AVINDEX_KEYFRAME)
cc947f04 1264 pkt->flags |= AV_PKT_FLAG_KEY;
7c7f3866 1265 } else {
cc947f04 1266 pkt->flags |= AV_PKT_FLAG_KEY;
7c7f3866 1267 }
8a472821 1268 ast->frame_offset += get_duration(ast, pkt->size);
7c7f3866 1269 }
0af49a63 1270 ast->remaining -= err;
10aa44aa
LB
1271 if (!ast->remaining) {
1272 avi->stream_index = -1;
1273 ast->packet_size = 0;
7c7f3866
MN
1274 }
1275
eeade678 1276 return 0;
7c7f3866
MN
1277 }
1278
d3f610c1 1279 if ((err = avi_sync(s, 0)) < 0)
8b84af74
AC
1280 return err;
1281 goto resync;
de6d9b64
FB
1282}
1283
15d6e361 1284/* XXX: We make the implicit supposition that the positions are sorted
10aa44aa 1285 * for each stream. */
155e9ee9
FB
1286static int avi_read_idx1(AVFormatContext *s, int size)
1287{
7c7f3866 1288 AVIContext *avi = s->priv_data;
ae628ec1 1289 AVIOContext *pb = s->pb;
155e9ee9
FB
1290 int nb_index_entries, i;
1291 AVStream *st;
1292 AVIStream *ast;
d3f610c1 1293 unsigned int index, tag, flags, pos, len, first_packet = 1;
10aa44aa 1294 unsigned last_pos = -1;
d3f610c1 1295 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
115329f1 1296
155e9ee9
FB
1297 nb_index_entries = size / 16;
1298 if (nb_index_entries <= 0)
570a4a01 1299 return AVERROR_INVALIDDATA;
155e9ee9 1300
d3f610c1 1301 idx1_pos = avio_tell(pb);
10aa44aa
LB
1302 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1303 if (avi_sync(s, 1) == 0)
d3f610c1 1304 first_packet_pos = avio_tell(pb) - 8;
d3f610c1
AC
1305 avi->stream_index = -1;
1306 avio_seek(pb, idx1_pos, SEEK_SET);
1307
15d6e361 1308 /* Read the entries and sort them in each stream component. */
10aa44aa
LB
1309 for (i = 0; i < nb_index_entries; i++) {
1310 tag = avio_rl32(pb);
b7effd4e 1311 flags = avio_rl32(pb);
10aa44aa
LB
1312 pos = avio_rl32(pb);
1313 len = avio_rl32(pb);
1a3eb042 1314 av_log(s, AV_LOG_TRACE, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
919d7a34 1315 i, tag, flags, pos, len);
7c7f3866 1316
10aa44aa
LB
1317 index = ((tag & 0xff) - '0') * 10;
1318 index += (tag >> 8 & 0xff) - '0';
155e9ee9
FB
1319 if (index >= s->nb_streams)
1320 continue;
10aa44aa 1321 st = s->streams[index];
155e9ee9 1322 ast = st->priv_data;
115329f1 1323
10aa44aa
LB
1324 if (first_packet && first_packet_pos && len) {
1325 data_offset = first_packet_pos - pos;
d3f610c1
AC
1326 first_packet = 0;
1327 }
1328 pos += data_offset;
1329
1a3eb042 1330 av_log(s, AV_LOG_TRACE, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
919d7a34 1331
10aa44aa 1332 if (pb->eof_reached)
570a4a01 1333 return AVERROR_INVALIDDATA;
8ebe099a 1334
10aa44aa
LB
1335 if (last_pos == pos)
1336 avi->non_interleaved = 1;
1337 else if (len || !ast->sample_size)
1338 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1339 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
8a472821 1340 ast->cum_len += get_duration(ast, len);
10aa44aa 1341 last_pos = pos;
155e9ee9
FB
1342 }
1343 return 0;
1344}
1345
9d599e3f
MN
1346/* Scan the index and consider any file with streams more than
1347 * 2 seconds or 64MB apart non-interleaved. */
1348static int check_stream_max_drift(AVFormatContext *s)
1349{
1350 int64_t min_pos, pos;
1351 int i;
1352 int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
1353 if (!idx)
1354 return AVERROR(ENOMEM);
1355
1356 for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
1357 int64_t max_dts = INT64_MIN / 2;
1358 int64_t min_dts = INT64_MAX / 2;
1359 int64_t max_buffer = 0;
1360
1361 min_pos = INT64_MAX;
1362
1363 for (i = 0; i < s->nb_streams; i++) {
1364 AVStream *st = s->streams[i];
1365 AVIStream *ast = st->priv_data;
1366 int n = st->nb_index_entries;
1367 while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
1368 idx[i]++;
1369 if (idx[i] < n) {
1370 int64_t dts;
1371 dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
1372 FFMAX(ast->sample_size, 1),
1373 st->time_base, AV_TIME_BASE_Q);
1374 min_dts = FFMIN(min_dts, dts);
1375 min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
1376 }
1377 }
1378 for (i = 0; i < s->nb_streams; i++) {
1379 AVStream *st = s->streams[i];
1380 AVIStream *ast = st->priv_data;
1381
1382 if (idx[i] && min_dts != INT64_MAX / 2) {
1383 int64_t dts;
1384 dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
1385 FFMAX(ast->sample_size, 1),
1386 st->time_base, AV_TIME_BASE_Q);
1387 max_dts = FFMAX(max_dts, dts);
1388 max_buffer = FFMAX(max_buffer,
1389 av_rescale(dts - min_dts,
9200514a 1390 st->codecpar->bit_rate,
9d599e3f
MN
1391 AV_TIME_BASE));
1392 }
1393 }
1394 if (max_dts - min_dts > 2 * AV_TIME_BASE ||
1395 max_buffer > 1024 * 1024 * 8 * 8) {
1396 av_free(idx);
1397 return 1;
1398 }
1399 }
1400 av_free(idx);
1401 return 0;
1402}
1403
10aa44aa
LB
1404static int guess_ni_flag(AVFormatContext *s)
1405{
7c7f3866 1406 int i;
10aa44aa
LB
1407 int64_t last_start = 0;
1408 int64_t first_end = INT64_MAX;
1409 int64_t oldpos = avio_tell(s->pb);
115329f1 1410
10aa44aa 1411 for (i = 0; i < s->nb_streams; i++) {
7c7f3866 1412 AVStream *st = s->streams[i];
10aa44aa 1413 int n = st->nb_index_entries;
8c68f25b 1414 unsigned int size;
7c7f3866 1415
10aa44aa 1416 if (n <= 0)
7c7f3866
MN
1417 continue;
1418
10aa44aa
LB
1419 if (n >= 2) {
1420 int64_t pos = st->index_entries[0].pos;
6b4aa5da 1421 avio_seek(s->pb, pos + 4, SEEK_SET);
10aa44aa
LB
1422 size = avio_rl32(s->pb);
1423 if (pos + size > st->index_entries[1].pos)
1424 last_start = INT64_MAX;
8c68f25b
MN
1425 }
1426
10aa44aa
LB
1427 if (st->index_entries[0].pos > last_start)
1428 last_start = st->index_entries[0].pos;
1429 if (st->index_entries[n - 1].pos < first_end)
1430 first_end = st->index_entries[n - 1].pos;
7c7f3866 1431 }
6b4aa5da 1432 avio_seek(s->pb, oldpos, SEEK_SET);
9d599e3f
MN
1433
1434 if (last_start > first_end)
1435 return 1;
1436
1437 return check_stream_max_drift(s);
7c7f3866
MN
1438}
1439
155e9ee9
FB
1440static int avi_load_index(AVFormatContext *s)
1441{
1442 AVIContext *avi = s->priv_data;
ae628ec1 1443 AVIOContext *pb = s->pb;
155e9ee9 1444 uint32_t tag, size;
10aa44aa
LB
1445 int64_t pos = avio_tell(pb);
1446 int ret = -1;
115329f1 1447
6b4aa5da 1448 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
44ed34b7 1449 goto the_end; // maybe truncated file
1a3eb042 1450 av_log(s, AV_LOG_TRACE, "movi_end=0x%"PRIx64"\n", avi->movi_end);
10aa44aa 1451 for (;;) {
66e5b1df 1452 if (pb->eof_reached)
155e9ee9 1453 break;
10aa44aa 1454 tag = avio_rl32(pb);
b7effd4e 1455 size = avio_rl32(pb);
1a3eb042 1456 av_log(s, AV_LOG_TRACE, "tag=%c%c%c%c size=0x%x\n",
919d7a34
DB
1457 tag & 0xff,
1458 (tag >> 8) & 0xff,
1459 (tag >> 16) & 0xff,
1460 (tag >> 24) & 0xff,
1461 size);
c9403419
MR
1462
1463 if (tag == MKTAG('i', 'd', 'x', '1') &&
1464 avi_read_idx1(s, size) >= 0) {
44ed34b7 1465 ret = 0;
155e9ee9
FB
1466 break;
1467 }
c9403419
MR
1468
1469 size += (size & 1);
1470 if (avio_skip(pb, size) < 0)
1471 break; // something is wrong here
155e9ee9 1472 }
10aa44aa
LB
1473
1474the_end:
6b4aa5da 1475 avio_seek(pb, pos, SEEK_SET);
44ed34b7 1476 return ret;
155e9ee9
FB
1477}
1478
37287d41
AJ
1479static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1480{
1481 AVIStream *ast2 = st2->priv_data;
10aa44aa 1482 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
ce70f28a 1483 av_packet_unref(&ast2->sub_pkt);
37287d41
AJ
1484 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1485 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
3c90cc2e 1486 ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
37287d41
AJ
1487}
1488
10aa44aa
LB
1489static int avi_read_seek(AVFormatContext *s, int stream_index,
1490 int64_t timestamp, int flags)
155e9ee9
FB
1491{
1492 AVIContext *avi = s->priv_data;
1493 AVStream *st;
52a0bbff 1494 int i, index;
155e9ee9 1495 int64_t pos;
83a4d356 1496 AVIStream *ast;
155e9ee9 1497
756547ce
LB
1498 /* Does not matter which stream is requested dv in avi has the
1499 * stream information in the first video stream.
1500 */
1501 if (avi->dv_demux)
1502 stream_index = 0;
1503
155e9ee9
FB
1504 if (!avi->index_loaded) {
1505 /* we only load the index on demand */
1506 avi_load_index(s);
1507 avi->index_loaded = 1;
1508 }
10aa44aa
LB
1509
1510 st = s->streams[stream_index];
1511 ast = st->priv_data;
1512 index = av_index_search_timestamp(st,
1513 timestamp * FFMAX(ast->sample_size, 1),
1514 flags);
1515 if (index < 0)
570a4a01 1516 return AVERROR_INVALIDDATA;
115329f1 1517
155e9ee9 1518 /* find the position */
10aa44aa 1519 pos = st->index_entries[index].pos;
83a4d356 1520 timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
52a0bbff 1521
1a3eb042 1522 av_log(s, AV_LOG_TRACE, "XX %"PRId64" %d %"PRId64"\n",
72eaba5e 1523 timestamp, index, st->index_entries[index].timestamp);
155e9ee9 1524
49fb20cb 1525 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
6eb2de74 1526 /* One and only one real stream for DV in AVI, and it has video */
f4433de9 1527 /* offsets. Calling with other stream indexes should have failed */
6eb2de74 1528 /* the av_index_search_timestamp call above. */
6eb2de74
RS
1529
1530 /* Feed the DV video stream version of the timestamp to the */
15d6e361 1531 /* DV demux so it can synthesize correct timestamps. */
167f3b8d 1532 ff_dv_offset_reset(avi->dv_demux, timestamp);
6eb2de74 1533
6b4aa5da 1534 avio_seek(s->pb, pos, SEEK_SET);
10aa44aa 1535 avi->stream_index = -1;
6eb2de74
RS
1536 return 0;
1537 }
1538
10aa44aa
LB
1539 for (i = 0; i < s->nb_streams; i++) {
1540 AVStream *st2 = s->streams[i];
52a0bbff 1541 AVIStream *ast2 = st2->priv_data;
7c7f3866 1542
10aa44aa
LB
1543 ast2->packet_size =
1544 ast2->remaining = 0;
7c7f3866 1545
37287d41
AJ
1546 if (ast2->sub_ctx) {
1547 seek_subtitle(st, st2, timestamp);
1548 continue;
1549 }
1550
52a0bbff
MN
1551 if (st2->nb_index_entries <= 0)
1552 continue;
115329f1 1553
9200514a 1554// assert(st2->codecpar->block_align);
10aa44aa
LB
1555 assert((int64_t)st2->time_base.num * ast2->rate ==
1556 (int64_t)st2->time_base.den * ast2->scale);
1557 index = av_index_search_timestamp(st2,
1558 av_rescale_q(timestamp,
1559 st->time_base,
1560 st2->time_base) *
1561 FFMAX(ast2->sample_size, 1),
1562 flags | AVSEEK_FLAG_BACKWARD);
1563 if (index < 0)
1564 index = 0;
1565
1566 if (!avi->non_interleaved) {
1567 while (index > 0 && st2->index_entries[index].pos > pos)
7c7f3866 1568 index--;
10aa44aa
LB
1569 while (index + 1 < st2->nb_index_entries &&
1570 st2->index_entries[index].pos < pos)
7c7f3866
MN
1571 index++;
1572 }
1573
1a3eb042 1574 av_log(s, AV_LOG_TRACE, "%"PRId64" %d %"PRId64"\n",
72eaba5e 1575 timestamp, index, st2->index_entries[index].timestamp);
52a0bbff
MN
1576 /* extract the current frame number */
1577 ast2->frame_offset = st2->index_entries[index].timestamp;
155e9ee9 1578 }
52a0bbff 1579
155e9ee9 1580 /* do the seek */
6b4aa5da 1581 avio_seek(s->pb, pos, SEEK_SET);
10aa44aa 1582 avi->stream_index = -1;
155e9ee9
FB
1583 return 0;
1584}
1585
1101abfe 1586static int avi_read_close(AVFormatContext *s)
de6d9b64 1587{
5ae2c73e
MN
1588 int i;
1589 AVIContext *avi = s->priv_data;
5ae2c73e 1590
10aa44aa
LB
1591 for (i = 0; i < s->nb_streams; i++) {
1592 AVStream *st = s->streams[i];
37287d41 1593 AVIStream *ast = st->priv_data;
4ed899f2 1594 if (ast) {
2b50c4f6
CEH
1595 if (ast->sub_ctx) {
1596 av_freep(&ast->sub_ctx->pb);
cd3716b9 1597 avformat_close_input(&ast->sub_ctx);
2b50c4f6
CEH
1598 }
1599 av_free(ast->sub_buffer);
ce70f28a 1600 av_packet_unref(&ast->sub_pkt);
4ed899f2 1601 }
5ae2c73e
MN
1602 }
1603
290849e2 1604 av_free(avi->dv_demux);
7458ccbb 1605
c9a65ca8
FB
1606 return 0;
1607}
1608
1609static int avi_probe(AVProbeData *p)
1610{
7b31b092
AJ
1611 int i;
1612
c9a65ca8 1613 /* check file header */
10aa44aa
LB
1614 for (i = 0; avi_headers[i][0]; i++)
1615 if (!memcmp(p->buf, avi_headers[i], 4) &&
1616 !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
7b31b092
AJ
1617 return AVPROBE_SCORE_MAX;
1618
1619 return 0;
c9a65ca8
FB
1620}
1621
c6610a21 1622AVInputFormat ff_avi_demuxer = {
dfc2c4d9 1623 .name = "avi",
0177b7d2 1624 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
dfc2c4d9 1625 .priv_data_size = sizeof(AVIContext),
f1c4a54f 1626 .extensions = "avi",
dfc2c4d9
AK
1627 .read_probe = avi_probe,
1628 .read_header = avi_read_header,
1629 .read_packet = avi_read_packet,
1630 .read_close = avi_read_close,
1631 .read_seek = avi_read_seek,
c9a65ca8 1632};