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